_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 |
|---|---|---|---|---|---|---|---|---|
0068443d62dce6218bdf1caea81ac5642be8f2b2520398bdcae318088993a0af | mfikes/fifth-postulate | ns405.cljs | (ns fifth-postulate.ns405)
(defn solve-for01 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for02 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for03 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for04 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for05 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for06 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for07 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for08 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for09 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for10 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for11 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for12 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for13 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for14 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for15 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for16 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for17 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for18 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for19 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
| null | https://raw.githubusercontent.com/mfikes/fifth-postulate/22cfd5f8c2b4a2dead1c15a96295bfeb4dba235e/src/fifth_postulate/ns405.cljs | clojure | (ns fifth-postulate.ns405)
(defn solve-for01 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for02 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for03 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for04 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for05 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for06 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for07 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for08 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for09 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for10 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for11 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for12 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for13 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for14 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for15 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for16 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for17 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for18 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for19 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
| |
6a23bf75faa43204c85a02d6fb6b5d8f946d73e1fc5d92a124004c8f0f36e373 | dbuenzli/tgls | myocamlbuild.ml | open Ocamlbuild_plugin
open Command
(* Platform detection *)
let os =
String.trim @@
try Sys.getenv "TGLS_HOST_OS"
with Not_found -> run_and_read "uname -s"
let darwin = os = "Darwin"
let linux = os = "Linux"
let freebsd = os = "FreeBSD"
let rpi =
linux &&
try ignore (run_and_read "cat /proc/cpuinfo | grep -q 'BCM270.'"); true
with Failure _ -> false
pkg - config invocation . we do n't fail if we do n't have the package .
let pkg_config flags package =
let has_package =
try ignore (run_and_read ("pkg-config --exists " ^ package)); true
with Failure _ -> false
in
let cmd tmp =
Command.execute ~quiet:true &
Cmd( S [ A "pkg-config"; A ("--" ^ flags); A package; Sh ">"; A tmp]);
List.map (fun arg -> A arg) (string_list_of_file tmp)
in
if has_package then with_temp_file "pkgconfig" "pkg-config" cmd else []
let use_pkg_config = linux || freebsd
(* Tags for OpenGL X.Y *)
let gl_tag ~tag ~lib ~cpkg =
let make_opt o arg = S [ A o; arg ] in
let stub_l = [A (Printf.sprintf "-l%s" lib)] in
let cflags = if use_pkg_config then pkg_config "cflags" cpkg else [] in
let libs_l = if use_pkg_config then pkg_config "libs-only-l" cpkg else [] in
let libs_L = if use_pkg_config then pkg_config "libs-only-L" cpkg else [] in
let linker = if linux then [A "-Wl,-no-as-needed"] else [] in
let mklib_framework = if darwin then [A "-framework"; A "OpenGL" ] else [] in
let lib_framework = if darwin then [A "-framework OpenGL" ] else [] in
let mklib_flags =
(List.map (make_opt "-ldopt") linker) @ libs_l @ libs_L @ mklib_framework
in
let compile_flags = List.map (make_opt "-ccopt") cflags in
let lib_flags = List.map (make_opt "-cclib") (libs_l @ lib_framework) in
let link_flags = List.map (make_opt "-ccopt") (linker @ libs_L) in
let stublib_flags = List.map (make_opt "-dllib") stub_l in
flag ["c"; "ocamlmklib"; tag] (S mklib_flags);
flag ["c"; "compile"; tag] (S compile_flags);
flag ["link"; "ocaml"; tag] (S (link_flags @ lib_flags));
flag ["link"; "ocaml"; "library"; "byte"; tag] (S stublib_flags)
(* Tags for OpenGL ES X.Y *)
let gles_tag ~tag ~lib ~cpkg =
let make_opt o arg = S [ A o; arg ] in
let stub_l = [A (Printf.sprintf "-l%s" lib)] in
let cflags =
if rpi then [] else
if use_pkg_config then pkg_config "cflags" cpkg else []
in
let libs_l =
if rpi then [A "-lGLESv2"] else
if use_pkg_config then pkg_config "libs-only-l" cpkg else []
in
let libs_L =
if rpi then [A "-L/opt/vc/lib"] else
if use_pkg_config then pkg_config "libs-only-L" cpkg else []
in
let linker =
if rpi || linux then [A "-Wl,-no-as-needed"] else []
in
let mklib_framework = if darwin then [] else [] in
let lib_framework = if darwin then [] else [] in
let mklib_flags =
(List.map (make_opt "-ldopt") linker) @ libs_l @ libs_L @ mklib_framework
in
let compile_flags = List.map (make_opt "-ccopt") cflags in
let lib_flags = List.map (make_opt "-cclib") (libs_l @ lib_framework) in
let link_flags = List.map (make_opt "-ccopt") (linker @ libs_L) in
let stublib_flags = List.map (make_opt "-dllib") stub_l in
flag ["c"; "ocamlmklib"; tag] (S mklib_flags);
flag ["c"; "compile"; tag] (S compile_flags);
flag ["link"; "ocaml"; tag] (S (link_flags @ lib_flags));
flag ["link"; "ocaml"; "library"; "byte"; tag] (S stublib_flags)
let () =
dispatch begin function
| After_rules ->
gl_tag ~tag:"use_gl3" ~lib:"tgl3" ~cpkg:"gl";
gl_tag ~tag:"use_gl4" ~lib:"tgl3" ~cpkg:"gl";
gles_tag ~tag:"use_gles2" ~lib:"tgles2" ~cpkg:"glesv2";
gles_tag ~tag:"use_gles3" ~lib:"tgles3" ~cpkg:"glesv3";
| _ -> ()
end
| null | https://raw.githubusercontent.com/dbuenzli/tgls/58bf47d393da00f24fa8e58521ddb9e3afb08d1d/myocamlbuild.ml | ocaml | Platform detection
Tags for OpenGL X.Y
Tags for OpenGL ES X.Y | open Ocamlbuild_plugin
open Command
let os =
String.trim @@
try Sys.getenv "TGLS_HOST_OS"
with Not_found -> run_and_read "uname -s"
let darwin = os = "Darwin"
let linux = os = "Linux"
let freebsd = os = "FreeBSD"
let rpi =
linux &&
try ignore (run_and_read "cat /proc/cpuinfo | grep -q 'BCM270.'"); true
with Failure _ -> false
pkg - config invocation . we do n't fail if we do n't have the package .
let pkg_config flags package =
let has_package =
try ignore (run_and_read ("pkg-config --exists " ^ package)); true
with Failure _ -> false
in
let cmd tmp =
Command.execute ~quiet:true &
Cmd( S [ A "pkg-config"; A ("--" ^ flags); A package; Sh ">"; A tmp]);
List.map (fun arg -> A arg) (string_list_of_file tmp)
in
if has_package then with_temp_file "pkgconfig" "pkg-config" cmd else []
let use_pkg_config = linux || freebsd
let gl_tag ~tag ~lib ~cpkg =
let make_opt o arg = S [ A o; arg ] in
let stub_l = [A (Printf.sprintf "-l%s" lib)] in
let cflags = if use_pkg_config then pkg_config "cflags" cpkg else [] in
let libs_l = if use_pkg_config then pkg_config "libs-only-l" cpkg else [] in
let libs_L = if use_pkg_config then pkg_config "libs-only-L" cpkg else [] in
let linker = if linux then [A "-Wl,-no-as-needed"] else [] in
let mklib_framework = if darwin then [A "-framework"; A "OpenGL" ] else [] in
let lib_framework = if darwin then [A "-framework OpenGL" ] else [] in
let mklib_flags =
(List.map (make_opt "-ldopt") linker) @ libs_l @ libs_L @ mklib_framework
in
let compile_flags = List.map (make_opt "-ccopt") cflags in
let lib_flags = List.map (make_opt "-cclib") (libs_l @ lib_framework) in
let link_flags = List.map (make_opt "-ccopt") (linker @ libs_L) in
let stublib_flags = List.map (make_opt "-dllib") stub_l in
flag ["c"; "ocamlmklib"; tag] (S mklib_flags);
flag ["c"; "compile"; tag] (S compile_flags);
flag ["link"; "ocaml"; tag] (S (link_flags @ lib_flags));
flag ["link"; "ocaml"; "library"; "byte"; tag] (S stublib_flags)
let gles_tag ~tag ~lib ~cpkg =
let make_opt o arg = S [ A o; arg ] in
let stub_l = [A (Printf.sprintf "-l%s" lib)] in
let cflags =
if rpi then [] else
if use_pkg_config then pkg_config "cflags" cpkg else []
in
let libs_l =
if rpi then [A "-lGLESv2"] else
if use_pkg_config then pkg_config "libs-only-l" cpkg else []
in
let libs_L =
if rpi then [A "-L/opt/vc/lib"] else
if use_pkg_config then pkg_config "libs-only-L" cpkg else []
in
let linker =
if rpi || linux then [A "-Wl,-no-as-needed"] else []
in
let mklib_framework = if darwin then [] else [] in
let lib_framework = if darwin then [] else [] in
let mklib_flags =
(List.map (make_opt "-ldopt") linker) @ libs_l @ libs_L @ mklib_framework
in
let compile_flags = List.map (make_opt "-ccopt") cflags in
let lib_flags = List.map (make_opt "-cclib") (libs_l @ lib_framework) in
let link_flags = List.map (make_opt "-ccopt") (linker @ libs_L) in
let stublib_flags = List.map (make_opt "-dllib") stub_l in
flag ["c"; "ocamlmklib"; tag] (S mklib_flags);
flag ["c"; "compile"; tag] (S compile_flags);
flag ["link"; "ocaml"; tag] (S (link_flags @ lib_flags));
flag ["link"; "ocaml"; "library"; "byte"; tag] (S stublib_flags)
let () =
dispatch begin function
| After_rules ->
gl_tag ~tag:"use_gl3" ~lib:"tgl3" ~cpkg:"gl";
gl_tag ~tag:"use_gl4" ~lib:"tgl3" ~cpkg:"gl";
gles_tag ~tag:"use_gles2" ~lib:"tgles2" ~cpkg:"glesv2";
gles_tag ~tag:"use_gles3" ~lib:"tgles3" ~cpkg:"glesv3";
| _ -> ()
end
|
dba623c065663fa62f713f1839f99529f56b4a17ef36ebcc6bde53be0e91ba95 | kazu-yamamoto/http2 | RingOfQueues.hs | # LANGUAGE ForeignFunctionInterface #
# LANGUAGE RecordWildCards #
{-# LANGUAGE BangPatterns #-}
# LANGUAGE FlexibleContexts #
Haskell implementation of H2O 's priority queue .
--
module RingOfQueues (
Entry
, newEntry
, renewEntry
, item
, Node
, PriorityQueue(..)
, new
, enqueue
, dequeue
, delete
) where
import Control.Monad (replicateM)
import Data.Array (Array, listArray, (!))
import Data.Bits (setBit, clearBit, shiftR)
import Data.IORef
import Data.Word (Word64)
import Foreign.C.Types (CLLong(..))
import DoublyLinkedQueueIO (Queue, Node)
import qualified DoublyLinkedQueueIO as Q
----------------------------------------------------------------
type Weight = Int
-- | Abstract data type of entries for priority queues.
data Entry a = Entry {
item :: a -- ^ Extracting an item from an entry.
, weight :: {-# UNPACK #-} !Weight
, deficit :: {-# UNPACK #-} !Int
} deriving Show
newEntry :: a -> Weight -> Entry a
newEntry x w = Entry x w 0
-- | Changing the item of an entry.
renewEntry :: Entry a -> b -> Entry b
renewEntry ent x = ent { item = x }
----------------------------------------------------------------
data PriorityQueue a = PriorityQueue {
bitsRef :: IORef Word64
, offsetRef :: IORef Int
, queues :: Array Int (Queue (Entry a))
}
----------------------------------------------------------------
bitWidth :: Int
bitWidth = 64
relativeIndex :: Int -> Int -> Int
relativeIndex idx offset = (offset + idx) `mod` bitWidth
----------------------------------------------------------------
deficitSteps :: Int
deficitSteps = 65536
deficitList :: [Int]
deficitList = map calc idxs
where
idxs :: [Double]
idxs = [1..256]
calc w = round (65536 * 63 / w)
deficitTable :: Array Int Int
deficitTable = listArray (1,256) deficitList
----------------------------------------------------------------
--
foreign import ccall unsafe "strings.h ffsll"
c_ffs :: CLLong -> CLLong
| Finding first bit set . O(1 )
--
> > > firstBitSet $ setBit 0 63
63
> > > firstBitSet $ setBit 0 62
62
> > > firstBitSet $ setBit 0 1
1
-- >>> firstBitSet $ setBit 0 0
0
-- >>> firstBitSet 0
-- -1
firstBitSet :: Word64 -> Int
firstBitSet x = ffs x - 1
where
ffs = fromIntegral . c_ffs . fromIntegral
----------------------------------------------------------------
new :: IO (PriorityQueue a)
new = PriorityQueue <$> newIORef 0 <*> newIORef 0 <*> newQueues
where
newQueues = listArray (0, bitWidth - 1) <$> replicateM bitWidth Q.new
-- | Enqueuing an entry. PriorityQueue is updated.
enqueue :: Entry a -> PriorityQueue a -> IO (Node (Entry a))
enqueue ent PriorityQueue{..} = do
let (!idx,!deficit') = calcIdxAndDeficit
!offidx <- getOffIdx idx
node <- push offidx ent { deficit = deficit' }
updateBits idx
return node
where
calcIdxAndDeficit = total `divMod` deficitSteps
where
total = deficitTable ! weight ent + deficit ent
getOffIdx idx = relativeIndex idx <$> readIORef offsetRef
push offidx ent' = Q.enqueue ent' (queues ! offidx)
updateBits idx = modifyIORef' bitsRef $ flip setBit idx
-- | Dequeuing an entry. PriorityQueue is updated.
dequeue :: PriorityQueue a -> IO (Maybe (Entry a))
dequeue pq@PriorityQueue{..} = do
!idx <- getIdx
if idx == -1 then
return Nothing
else do
!offidx <- getOffIdx idx
updateOffset offidx
queueIsEmpty <- checkEmpty offidx
updateBits idx queueIsEmpty
if queueIsEmpty then
dequeue pq
else
Just <$> pop offidx
where
getIdx = firstBitSet <$> readIORef bitsRef
getOffIdx idx = relativeIndex idx <$> readIORef offsetRef
pop offidx = Q.dequeue (queues ! offidx)
checkEmpty offidx = Q.isEmpty (queues ! offidx)
updateOffset offset' = writeIORef offsetRef offset'
updateBits idx isEmpty = modifyIORef' bitsRef shiftClear
where
shiftClear bits
| isEmpty = clearBit (shiftR bits idx) 0
| otherwise = shiftR bits idx
-- bits is not updated because it's difficult.
delete :: Node (Entry a) -> IO ()
delete node = Q.delete node
| null | https://raw.githubusercontent.com/kazu-yamamoto/http2/3c29763be147a3d482eff28f427ad80f1d4df706/bench-priority/RingOfQueues.hs | haskell | # LANGUAGE BangPatterns #
--------------------------------------------------------------
| Abstract data type of entries for priority queues.
^ Extracting an item from an entry.
# UNPACK #
# UNPACK #
| Changing the item of an entry.
--------------------------------------------------------------
--------------------------------------------------------------
--------------------------------------------------------------
--------------------------------------------------------------
>>> firstBitSet $ setBit 0 0
>>> firstBitSet 0
-1
--------------------------------------------------------------
| Enqueuing an entry. PriorityQueue is updated.
| Dequeuing an entry. PriorityQueue is updated.
bits is not updated because it's difficult. | # LANGUAGE ForeignFunctionInterface #
# LANGUAGE RecordWildCards #
# LANGUAGE FlexibleContexts #
Haskell implementation of H2O 's priority queue .
module RingOfQueues (
Entry
, newEntry
, renewEntry
, item
, Node
, PriorityQueue(..)
, new
, enqueue
, dequeue
, delete
) where
import Control.Monad (replicateM)
import Data.Array (Array, listArray, (!))
import Data.Bits (setBit, clearBit, shiftR)
import Data.IORef
import Data.Word (Word64)
import Foreign.C.Types (CLLong(..))
import DoublyLinkedQueueIO (Queue, Node)
import qualified DoublyLinkedQueueIO as Q
type Weight = Int
data Entry a = Entry {
} deriving Show
newEntry :: a -> Weight -> Entry a
newEntry x w = Entry x w 0
renewEntry :: Entry a -> b -> Entry b
renewEntry ent x = ent { item = x }
data PriorityQueue a = PriorityQueue {
bitsRef :: IORef Word64
, offsetRef :: IORef Int
, queues :: Array Int (Queue (Entry a))
}
bitWidth :: Int
bitWidth = 64
relativeIndex :: Int -> Int -> Int
relativeIndex idx offset = (offset + idx) `mod` bitWidth
deficitSteps :: Int
deficitSteps = 65536
deficitList :: [Int]
deficitList = map calc idxs
where
idxs :: [Double]
idxs = [1..256]
calc w = round (65536 * 63 / w)
deficitTable :: Array Int Int
deficitTable = listArray (1,256) deficitList
foreign import ccall unsafe "strings.h ffsll"
c_ffs :: CLLong -> CLLong
| Finding first bit set . O(1 )
> > > firstBitSet $ setBit 0 63
63
> > > firstBitSet $ setBit 0 62
62
> > > firstBitSet $ setBit 0 1
1
0
firstBitSet :: Word64 -> Int
firstBitSet x = ffs x - 1
where
ffs = fromIntegral . c_ffs . fromIntegral
new :: IO (PriorityQueue a)
new = PriorityQueue <$> newIORef 0 <*> newIORef 0 <*> newQueues
where
newQueues = listArray (0, bitWidth - 1) <$> replicateM bitWidth Q.new
enqueue :: Entry a -> PriorityQueue a -> IO (Node (Entry a))
enqueue ent PriorityQueue{..} = do
let (!idx,!deficit') = calcIdxAndDeficit
!offidx <- getOffIdx idx
node <- push offidx ent { deficit = deficit' }
updateBits idx
return node
where
calcIdxAndDeficit = total `divMod` deficitSteps
where
total = deficitTable ! weight ent + deficit ent
getOffIdx idx = relativeIndex idx <$> readIORef offsetRef
push offidx ent' = Q.enqueue ent' (queues ! offidx)
updateBits idx = modifyIORef' bitsRef $ flip setBit idx
dequeue :: PriorityQueue a -> IO (Maybe (Entry a))
dequeue pq@PriorityQueue{..} = do
!idx <- getIdx
if idx == -1 then
return Nothing
else do
!offidx <- getOffIdx idx
updateOffset offidx
queueIsEmpty <- checkEmpty offidx
updateBits idx queueIsEmpty
if queueIsEmpty then
dequeue pq
else
Just <$> pop offidx
where
getIdx = firstBitSet <$> readIORef bitsRef
getOffIdx idx = relativeIndex idx <$> readIORef offsetRef
pop offidx = Q.dequeue (queues ! offidx)
checkEmpty offidx = Q.isEmpty (queues ! offidx)
updateOffset offset' = writeIORef offsetRef offset'
updateBits idx isEmpty = modifyIORef' bitsRef shiftClear
where
shiftClear bits
| isEmpty = clearBit (shiftR bits idx) 0
| otherwise = shiftR bits idx
delete :: Node (Entry a) -> IO ()
delete node = Q.delete node
|
6dcac022867d1adb12e9cacb01705caf21b9a4eb8996e6b25b7f30509cc7e821 | Octachron/codept | broken.ml | module B
open open B
| null | https://raw.githubusercontent.com/Octachron/codept/2d2a95fde3f67cdd0f5a1b68d8b8b47aefef9290/tests/complex/broken_network/broken.ml | ocaml | module B
open open B
| |
ae799ba8fbccd89787c96a0f85c2484a8315ebdc7e2c1ff9a0a5172b94dca90a | kowainik/policeman | Hackage.hs | | Functions to download packages from Hackage .
-}
module Policeman.Download.Hackage
( PackageName (..)
, downloadFromHackage
, getLatestHackageCabalFileContent
) where
import Control.Exception (catch)
import Control.Monad.Trans.Except (withExceptT)
import Shellmet (($?), ($|))
import System.Directory (createDirectoryIfMissing, getCurrentDirectory, removeDirectoryRecursive)
import System.FilePath ((</>))
import System.IO.Error (IOError, isDoesNotExistError)
import Policeman.Core.Package (PackageName (..))
import Policeman.Core.Version (Version (versionText))
import Policeman.Download.Common (DownloadError (..), evidenceDir)
{- | By the given pacakge name it downloads the latest `.cabal` file and
returns its content.
</<name>/<name>.cabal>
-}
getLatestHackageCabalFileContent
:: PackageName
-> ExceptT DownloadError IO ByteString
getLatestHackageCabalFileContent package@(PackageName packageName) = ExceptT $
(Right . encodeUtf8 <$> ("curl" $| ["--silent", url]))
$? pure (Left $ NoSuchPackage package)
where
url :: Text
url = mconcat
[ hackageUrl
, packageName
, "/"
, packageName
, ".cabal"
]
{- | This function takes 'PackageName' and previous package
'Version', downloads @.tar.gz@ archive from Hackage and unpacks it in
the current directory.
-}
downloadFromHackage :: PackageName -> Version -> ExceptT DownloadError IO FilePath
downloadFromHackage packageName@(PackageName name) (versionText -> version) = do
let fullName = name <> "-" <> version
let tarName = fullName <> ".tar.gz"
let tarUrl = mconcat
[ hackageUrl
, name
, "/"
, tarName
]
let tarPath = toText $ evidenceDir </> toString tarName
let srcPath = evidenceDir </> toString fullName
liftIO $ createDirectoryIfMissing True evidenceDir
withExceptT SystemError $ removeDirIfExists srcPath
-- download archive from Hackage
ExceptT $
(Right <$> "curl" ["--silent", tarUrl, "--output", tarPath])
$? pure (Left $ NoSuchPackage packageName)
-- unpack
liftIO $ "tar" ["-xf", tarPath, "-C", toText evidenceDir]
liftIO $ fmap (</> srcPath) getCurrentDirectory
hackageUrl :: Text
hackageUrl = "/"
removeDirIfExists :: FilePath -> ExceptT IOError IO ()
removeDirIfExists fileName = ExceptT $
(Right <$> removeDirectoryRecursive fileName) `catch` (pure . handleExists)
where
handleExists :: IOError -> Either IOError ()
handleExists e
| isDoesNotExistError e = Right ()
| otherwise = Left e
| null | https://raw.githubusercontent.com/kowainik/policeman/26a92678c76b145ad9ae30054bf978a0d6ec2a58/src/Policeman/Download/Hackage.hs | haskell | | By the given pacakge name it downloads the latest `.cabal` file and
returns its content.
</<name>/<name>.cabal>
| This function takes 'PackageName' and previous package
'Version', downloads @.tar.gz@ archive from Hackage and unpacks it in
the current directory.
download archive from Hackage
unpack | | Functions to download packages from Hackage .
-}
module Policeman.Download.Hackage
( PackageName (..)
, downloadFromHackage
, getLatestHackageCabalFileContent
) where
import Control.Exception (catch)
import Control.Monad.Trans.Except (withExceptT)
import Shellmet (($?), ($|))
import System.Directory (createDirectoryIfMissing, getCurrentDirectory, removeDirectoryRecursive)
import System.FilePath ((</>))
import System.IO.Error (IOError, isDoesNotExistError)
import Policeman.Core.Package (PackageName (..))
import Policeman.Core.Version (Version (versionText))
import Policeman.Download.Common (DownloadError (..), evidenceDir)
getLatestHackageCabalFileContent
:: PackageName
-> ExceptT DownloadError IO ByteString
getLatestHackageCabalFileContent package@(PackageName packageName) = ExceptT $
(Right . encodeUtf8 <$> ("curl" $| ["--silent", url]))
$? pure (Left $ NoSuchPackage package)
where
url :: Text
url = mconcat
[ hackageUrl
, packageName
, "/"
, packageName
, ".cabal"
]
downloadFromHackage :: PackageName -> Version -> ExceptT DownloadError IO FilePath
downloadFromHackage packageName@(PackageName name) (versionText -> version) = do
let fullName = name <> "-" <> version
let tarName = fullName <> ".tar.gz"
let tarUrl = mconcat
[ hackageUrl
, name
, "/"
, tarName
]
let tarPath = toText $ evidenceDir </> toString tarName
let srcPath = evidenceDir </> toString fullName
liftIO $ createDirectoryIfMissing True evidenceDir
withExceptT SystemError $ removeDirIfExists srcPath
ExceptT $
(Right <$> "curl" ["--silent", tarUrl, "--output", tarPath])
$? pure (Left $ NoSuchPackage packageName)
liftIO $ "tar" ["-xf", tarPath, "-C", toText evidenceDir]
liftIO $ fmap (</> srcPath) getCurrentDirectory
hackageUrl :: Text
hackageUrl = "/"
removeDirIfExists :: FilePath -> ExceptT IOError IO ()
removeDirIfExists fileName = ExceptT $
(Right <$> removeDirectoryRecursive fileName) `catch` (pure . handleExists)
where
handleExists :: IOError -> Either IOError ()
handleExists e
| isDoesNotExistError e = Right ()
| otherwise = Left e
|
fd2ce15248f2c23d3ac4be83c60b1db554f2ab5e12c07b479afa13696825aedf | inaka/erlang_guidelines | types.erl | -module(types).
-include("bad_types.hrl").
-type id() :: pos_integer().
-record(type, {id :: id(), name :: binary()}).
-opaque type() :: #type{}.
-export_type([id/0, type/0]).
%% If you later want to use these types on your specs you DO NOT have to include
%% any file and you just write -spec my_function(types:id()) -> types:type().
| null | https://raw.githubusercontent.com/inaka/erlang_guidelines/882f7f12b74b65066fdeff9bbe2197a3d6f8a713/src/types.erl | erlang | If you later want to use these types on your specs you DO NOT have to include
any file and you just write -spec my_function(types:id()) -> types:type(). | -module(types).
-include("bad_types.hrl").
-type id() :: pos_integer().
-record(type, {id :: id(), name :: binary()}).
-opaque type() :: #type{}.
-export_type([id/0, type/0]).
|
9df53a3b184d7678946cd8272f9fd9d2afd6459e526c09c3028503329cdb7198 | KavrakiLab/tmkit | smtrun.lisp | (in-package :tmsmt)
(defvar *smt-trace-command* nil)
(defstruct smt
(runtime 0d0 :type double-float)
process)
(defparameter *smt-readtable*
(let ((r (copy-readtable nil)))
(setf (readtable-case r) :preserve)
r))
(defparameter *smt-package* (find-package :tmsmt))
(defun smt-input (smt)
(sb-ext:process-input (smt-process smt)))
(defun smt-output (smt)
(sb-ext:process-output (smt-process smt)))
(defun smt-read (smt &optional (eof-error-p t) eof-value recursive-p)
(let ((*readtable* *smt-readtable*)
(*package* *smt-package*))
(read (smt-output smt) eof-error-p eof-value recursive-p)))
(define-condition smt-runtime-error (error)
((message :initarg :message
:reader message)
(expression :initarg :expression
:reader expression)))
(defmethod print-object ((object smt-runtime-error) stream)
(print-unreadable-object (object stream :type t)
(with-slots (message expression) object
(format stream "\"~A: '~A'\"" message expression))))
(defun smt-symbol-eq (symbol upcase downcase)
(or (eq symbol upcase)
(eq symbol downcase)))
(defun smt-eval (smt exp)
(when (eq (car exp) 'comment)
(return-from smt-eval t))
;; Write
(labels ((command (stream)
(smt-print-1 exp stream)
(terpri stream)
(finish-output stream)))
;; Maybe trace commands
(when *smt-trace-command*
(command *smt-trace-command*))
;; Read
(let ((result
(multiple-value-bind (result run-time real-time)
(sycamore-util::with-timing
(command (smt-input smt))
(smt-read smt))
(declare (ignore run-time))
(incf (smt-runtime smt) real-time)
result)))
(cond
((smt-symbol-eq result 'unsupported '|unsupported|)
(error 'smt-runtime-error
:message "Unsupported expression"
:expression exp))
((smt-symbol-eq result 'success '|success|)
t)
((and (consp result)
(or (smt-symbol-eq (car result) 'error '|error|)))
(error 'smt-runtime-error
:message (second result)
:expression exp))
(t
result)))))
(defparameter *smt-solver-z3*
(list "z3" "-smt2" "-in"))
(defvar *smt*)
(defparameter *smt-solver* *smt-solver-z3*)
(defun smt-process-kill (process)
(when process
(when (sb-ext:process-alive-p process)
(sb-ext:process-kill process 9))
(sb-ext:process-wait process)
(sb-ext:process-close process)))
(defun smt-start (&key (smt-solver *smt-solver*))
(let ((process (sb-ext:run-program (car smt-solver)
(cdr smt-solver)
:search t
:wait nil
:input :stream
:error t
:output :stream
))
(smt (make-smt)))
(sb-ext:finalize smt (lambda () (smt-process-kill process)))
(setf (smt-process smt) process)
(smt-eval smt (smt-set-option ":print-success" '|true|))
( smt - eval smt ( smt - set - option " : produce - unsat - cores " ' |true| ) )
smt))
(defun smt-stop (smt)
(smt-process-kill (smt-process smt))
(setf (smt-process smt) nil))
(defmacro with-smt ((variable &key
(smt-solver '*smt-solver*)
(trace-command "/tmp/smt-command"))
&body body)
`(let ((,variable (smt-start :smt-solver ,smt-solver)))
(labels ((runit ()
(unwind-protect
(progn ,@body)
(smt-stop ,variable))))
,(if trace-command
`(progn
(format *standard-output* "~&Tracing SMT to ~A~%" ,trace-command)
(with-open-file (*smt-trace-command* ,trace-command :direction :output :if-exists :supersede)
(runit)))
`(runit)))))
| null | https://raw.githubusercontent.com/KavrakiLab/tmkit/4fb6fc0fa02c5b242dfcbe0013d3c1178e9d9224/lisp/smtrun.lisp | lisp | Write
Maybe trace commands
Read | (in-package :tmsmt)
(defvar *smt-trace-command* nil)
(defstruct smt
(runtime 0d0 :type double-float)
process)
(defparameter *smt-readtable*
(let ((r (copy-readtable nil)))
(setf (readtable-case r) :preserve)
r))
(defparameter *smt-package* (find-package :tmsmt))
(defun smt-input (smt)
(sb-ext:process-input (smt-process smt)))
(defun smt-output (smt)
(sb-ext:process-output (smt-process smt)))
(defun smt-read (smt &optional (eof-error-p t) eof-value recursive-p)
(let ((*readtable* *smt-readtable*)
(*package* *smt-package*))
(read (smt-output smt) eof-error-p eof-value recursive-p)))
(define-condition smt-runtime-error (error)
((message :initarg :message
:reader message)
(expression :initarg :expression
:reader expression)))
(defmethod print-object ((object smt-runtime-error) stream)
(print-unreadable-object (object stream :type t)
(with-slots (message expression) object
(format stream "\"~A: '~A'\"" message expression))))
(defun smt-symbol-eq (symbol upcase downcase)
(or (eq symbol upcase)
(eq symbol downcase)))
(defun smt-eval (smt exp)
(when (eq (car exp) 'comment)
(return-from smt-eval t))
(labels ((command (stream)
(smt-print-1 exp stream)
(terpri stream)
(finish-output stream)))
(when *smt-trace-command*
(command *smt-trace-command*))
(let ((result
(multiple-value-bind (result run-time real-time)
(sycamore-util::with-timing
(command (smt-input smt))
(smt-read smt))
(declare (ignore run-time))
(incf (smt-runtime smt) real-time)
result)))
(cond
((smt-symbol-eq result 'unsupported '|unsupported|)
(error 'smt-runtime-error
:message "Unsupported expression"
:expression exp))
((smt-symbol-eq result 'success '|success|)
t)
((and (consp result)
(or (smt-symbol-eq (car result) 'error '|error|)))
(error 'smt-runtime-error
:message (second result)
:expression exp))
(t
result)))))
(defparameter *smt-solver-z3*
(list "z3" "-smt2" "-in"))
(defvar *smt*)
(defparameter *smt-solver* *smt-solver-z3*)
(defun smt-process-kill (process)
(when process
(when (sb-ext:process-alive-p process)
(sb-ext:process-kill process 9))
(sb-ext:process-wait process)
(sb-ext:process-close process)))
(defun smt-start (&key (smt-solver *smt-solver*))
(let ((process (sb-ext:run-program (car smt-solver)
(cdr smt-solver)
:search t
:wait nil
:input :stream
:error t
:output :stream
))
(smt (make-smt)))
(sb-ext:finalize smt (lambda () (smt-process-kill process)))
(setf (smt-process smt) process)
(smt-eval smt (smt-set-option ":print-success" '|true|))
( smt - eval smt ( smt - set - option " : produce - unsat - cores " ' |true| ) )
smt))
(defun smt-stop (smt)
(smt-process-kill (smt-process smt))
(setf (smt-process smt) nil))
(defmacro with-smt ((variable &key
(smt-solver '*smt-solver*)
(trace-command "/tmp/smt-command"))
&body body)
`(let ((,variable (smt-start :smt-solver ,smt-solver)))
(labels ((runit ()
(unwind-protect
(progn ,@body)
(smt-stop ,variable))))
,(if trace-command
`(progn
(format *standard-output* "~&Tracing SMT to ~A~%" ,trace-command)
(with-open-file (*smt-trace-command* ,trace-command :direction :output :if-exists :supersede)
(runit)))
`(runit)))))
|
da86a72568983d5ea30506b1d62b2b9a9106fc2b60dec65433740686315a4629 | aerosol/gen_cycle | gen_cycle_sup.erl | -module(gen_cycle_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([start_child/1]).
-export([stop_child/1]).
-export([init/1]).
-define(CHILD(I, Type), {I, {I, start_link, []}, transient, 5000, Type, [I]}).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
start_child(Args) ->
supervisor:start_child(?MODULE, Args).
stop_child(Pid) when is_pid(Pid) ->
supervisor:terminate_child(?MODULE, Pid).
init([]) ->
{ok, {{simple_one_for_one, 500, 10},
[ ?CHILD(gen_cycle, worker) ]}}.
| null | https://raw.githubusercontent.com/aerosol/gen_cycle/34782726521b17a6ea7b397c7eae5a009e8798f7/src/gen_cycle_sup.erl | erlang | -module(gen_cycle_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([start_child/1]).
-export([stop_child/1]).
-export([init/1]).
-define(CHILD(I, Type), {I, {I, start_link, []}, transient, 5000, Type, [I]}).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
start_child(Args) ->
supervisor:start_child(?MODULE, Args).
stop_child(Pid) when is_pid(Pid) ->
supervisor:terminate_child(?MODULE, Pid).
init([]) ->
{ok, {{simple_one_for_one, 500, 10},
[ ?CHILD(gen_cycle, worker) ]}}.
| |
3e8f78ba0be94c766b9b5523bad000d4b16737ceb20dfdf618b4dd93b6ffa04e | UBTECH-Walker/WalkerSimulationFor2020WAIC | GetMapJson.lisp | ; Auto-generated. Do not edit!
(cl:in-package cruiser_msgs-srv)
;//! \htmlinclude GetMapJson-request.msg.html
(cl:defclass <GetMapJson-request> (roslisp-msg-protocol:ros-message)
()
)
(cl:defclass GetMapJson-request (<GetMapJson-request>)
())
(cl:defmethod cl:initialize-instance :after ((m <GetMapJson-request>) cl:&rest args)
(cl:declare (cl:ignorable args))
(cl:unless (cl:typep m 'GetMapJson-request)
(roslisp-msg-protocol:msg-deprecation-warning "using old message class name cruiser_msgs-srv:<GetMapJson-request> is deprecated: use cruiser_msgs-srv:GetMapJson-request instead.")))
(cl:defmethod roslisp-msg-protocol:serialize ((msg <GetMapJson-request>) ostream)
"Serializes a message object of type '<GetMapJson-request>"
)
(cl:defmethod roslisp-msg-protocol:deserialize ((msg <GetMapJson-request>) istream)
"Deserializes a message object of type '<GetMapJson-request>"
msg
)
(cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql '<GetMapJson-request>)))
"Returns string type for a service object of type '<GetMapJson-request>"
"cruiser_msgs/GetMapJsonRequest")
(cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql 'GetMapJson-request)))
"Returns string type for a service object of type 'GetMapJson-request"
"cruiser_msgs/GetMapJsonRequest")
(cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql '<GetMapJson-request>)))
"Returns md5sum for a message object of type '<GetMapJson-request>"
"6825166e7da48608dd55394f68c70e3e")
(cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql 'GetMapJson-request)))
"Returns md5sum for a message object of type 'GetMapJson-request"
"6825166e7da48608dd55394f68c70e3e")
(cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql '<GetMapJson-request>)))
"Returns full string definition for message of type '<GetMapJson-request>"
(cl:format cl:nil "~%~%~%"))
(cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql 'GetMapJson-request)))
"Returns full string definition for message of type 'GetMapJson-request"
(cl:format cl:nil "~%~%~%"))
(cl:defmethod roslisp-msg-protocol:serialization-length ((msg <GetMapJson-request>))
(cl:+ 0
))
(cl:defmethod roslisp-msg-protocol:ros-message-to-list ((msg <GetMapJson-request>))
"Converts a ROS message object to a list"
(cl:list 'GetMapJson-request
))
;//! \htmlinclude GetMapJson-response.msg.html
(cl:defclass <GetMapJson-response> (roslisp-msg-protocol:ros-message)
((json
:reader json
:initarg :json
:type cruiser_msgs-msg:MapJson
:initform (cl:make-instance 'cruiser_msgs-msg:MapJson)))
)
(cl:defclass GetMapJson-response (<GetMapJson-response>)
())
(cl:defmethod cl:initialize-instance :after ((m <GetMapJson-response>) cl:&rest args)
(cl:declare (cl:ignorable args))
(cl:unless (cl:typep m 'GetMapJson-response)
(roslisp-msg-protocol:msg-deprecation-warning "using old message class name cruiser_msgs-srv:<GetMapJson-response> is deprecated: use cruiser_msgs-srv:GetMapJson-response instead.")))
(cl:ensure-generic-function 'json-val :lambda-list '(m))
(cl:defmethod json-val ((m <GetMapJson-response>))
(roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader cruiser_msgs-srv:json-val is deprecated. Use cruiser_msgs-srv:json instead.")
(json m))
(cl:defmethod roslisp-msg-protocol:serialize ((msg <GetMapJson-response>) ostream)
"Serializes a message object of type '<GetMapJson-response>"
(roslisp-msg-protocol:serialize (cl:slot-value msg 'json) ostream)
)
(cl:defmethod roslisp-msg-protocol:deserialize ((msg <GetMapJson-response>) istream)
"Deserializes a message object of type '<GetMapJson-response>"
(roslisp-msg-protocol:deserialize (cl:slot-value msg 'json) istream)
msg
)
(cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql '<GetMapJson-response>)))
"Returns string type for a service object of type '<GetMapJson-response>"
"cruiser_msgs/GetMapJsonResponse")
(cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql 'GetMapJson-response)))
"Returns string type for a service object of type 'GetMapJson-response"
"cruiser_msgs/GetMapJsonResponse")
(cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql '<GetMapJson-response>)))
"Returns md5sum for a message object of type '<GetMapJson-response>"
"6825166e7da48608dd55394f68c70e3e")
(cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql 'GetMapJson-response)))
"Returns md5sum for a message object of type 'GetMapJson-response"
"6825166e7da48608dd55394f68c70e3e")
(cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql '<GetMapJson-response>)))
"Returns full string definition for message of type '<GetMapJson-response>"
(cl:format cl:nil "cruiser_msgs/MapJson json~%~%~%================================================================================~%MSG: cruiser_msgs/MapJson~%uint8[] data
~%
~%~%~%"))
(cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql 'GetMapJson-response)))
"Returns full string definition for message of type 'GetMapJson-response"
(cl:format cl:nil "cruiser_msgs/MapJson json~%~%~%================================================================================~%MSG: cruiser_msgs/MapJson~%uint8[] data
~%
~%~%~%"))
(cl:defmethod roslisp-msg-protocol:serialization-length ((msg <GetMapJson-response>))
(cl:+ 0
(roslisp-msg-protocol:serialization-length (cl:slot-value msg 'json))
))
(cl:defmethod roslisp-msg-protocol:ros-message-to-list ((msg <GetMapJson-response>))
"Converts a ROS message object to a list"
(cl:list 'GetMapJson-response
(cl:cons ':json (json msg))
))
(cl:defmethod roslisp-msg-protocol:service-request-type ((msg (cl:eql 'GetMapJson)))
'GetMapJson-request)
(cl:defmethod roslisp-msg-protocol:service-response-type ((msg (cl:eql 'GetMapJson)))
'GetMapJson-response)
(cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql 'GetMapJson)))
"Returns string type for a service object of type '<GetMapJson>"
"cruiser_msgs/GetMapJson") | null | https://raw.githubusercontent.com/UBTECH-Walker/WalkerSimulationFor2020WAIC/7cdb21dabb8423994ba3f6021bc7934290d5faa9/walker_WAIC_16.04_v1.2_20200616/walker_install/share/common-lisp/ros/cruiser_msgs/srv/GetMapJson.lisp | lisp | Auto-generated. Do not edit!
//! \htmlinclude GetMapJson-request.msg.html
//! \htmlinclude GetMapJson-response.msg.html |
(cl:in-package cruiser_msgs-srv)
(cl:defclass <GetMapJson-request> (roslisp-msg-protocol:ros-message)
()
)
(cl:defclass GetMapJson-request (<GetMapJson-request>)
())
(cl:defmethod cl:initialize-instance :after ((m <GetMapJson-request>) cl:&rest args)
(cl:declare (cl:ignorable args))
(cl:unless (cl:typep m 'GetMapJson-request)
(roslisp-msg-protocol:msg-deprecation-warning "using old message class name cruiser_msgs-srv:<GetMapJson-request> is deprecated: use cruiser_msgs-srv:GetMapJson-request instead.")))
(cl:defmethod roslisp-msg-protocol:serialize ((msg <GetMapJson-request>) ostream)
"Serializes a message object of type '<GetMapJson-request>"
)
(cl:defmethod roslisp-msg-protocol:deserialize ((msg <GetMapJson-request>) istream)
"Deserializes a message object of type '<GetMapJson-request>"
msg
)
(cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql '<GetMapJson-request>)))
"Returns string type for a service object of type '<GetMapJson-request>"
"cruiser_msgs/GetMapJsonRequest")
(cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql 'GetMapJson-request)))
"Returns string type for a service object of type 'GetMapJson-request"
"cruiser_msgs/GetMapJsonRequest")
(cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql '<GetMapJson-request>)))
"Returns md5sum for a message object of type '<GetMapJson-request>"
"6825166e7da48608dd55394f68c70e3e")
(cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql 'GetMapJson-request)))
"Returns md5sum for a message object of type 'GetMapJson-request"
"6825166e7da48608dd55394f68c70e3e")
(cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql '<GetMapJson-request>)))
"Returns full string definition for message of type '<GetMapJson-request>"
(cl:format cl:nil "~%~%~%"))
(cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql 'GetMapJson-request)))
"Returns full string definition for message of type 'GetMapJson-request"
(cl:format cl:nil "~%~%~%"))
(cl:defmethod roslisp-msg-protocol:serialization-length ((msg <GetMapJson-request>))
(cl:+ 0
))
(cl:defmethod roslisp-msg-protocol:ros-message-to-list ((msg <GetMapJson-request>))
"Converts a ROS message object to a list"
(cl:list 'GetMapJson-request
))
(cl:defclass <GetMapJson-response> (roslisp-msg-protocol:ros-message)
((json
:reader json
:initarg :json
:type cruiser_msgs-msg:MapJson
:initform (cl:make-instance 'cruiser_msgs-msg:MapJson)))
)
(cl:defclass GetMapJson-response (<GetMapJson-response>)
())
(cl:defmethod cl:initialize-instance :after ((m <GetMapJson-response>) cl:&rest args)
(cl:declare (cl:ignorable args))
(cl:unless (cl:typep m 'GetMapJson-response)
(roslisp-msg-protocol:msg-deprecation-warning "using old message class name cruiser_msgs-srv:<GetMapJson-response> is deprecated: use cruiser_msgs-srv:GetMapJson-response instead.")))
(cl:ensure-generic-function 'json-val :lambda-list '(m))
(cl:defmethod json-val ((m <GetMapJson-response>))
(roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader cruiser_msgs-srv:json-val is deprecated. Use cruiser_msgs-srv:json instead.")
(json m))
(cl:defmethod roslisp-msg-protocol:serialize ((msg <GetMapJson-response>) ostream)
"Serializes a message object of type '<GetMapJson-response>"
(roslisp-msg-protocol:serialize (cl:slot-value msg 'json) ostream)
)
(cl:defmethod roslisp-msg-protocol:deserialize ((msg <GetMapJson-response>) istream)
"Deserializes a message object of type '<GetMapJson-response>"
(roslisp-msg-protocol:deserialize (cl:slot-value msg 'json) istream)
msg
)
(cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql '<GetMapJson-response>)))
"Returns string type for a service object of type '<GetMapJson-response>"
"cruiser_msgs/GetMapJsonResponse")
(cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql 'GetMapJson-response)))
"Returns string type for a service object of type 'GetMapJson-response"
"cruiser_msgs/GetMapJsonResponse")
(cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql '<GetMapJson-response>)))
"Returns md5sum for a message object of type '<GetMapJson-response>"
"6825166e7da48608dd55394f68c70e3e")
(cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql 'GetMapJson-response)))
"Returns md5sum for a message object of type 'GetMapJson-response"
"6825166e7da48608dd55394f68c70e3e")
(cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql '<GetMapJson-response>)))
"Returns full string definition for message of type '<GetMapJson-response>"
(cl:format cl:nil "cruiser_msgs/MapJson json~%~%~%================================================================================~%MSG: cruiser_msgs/MapJson~%uint8[] data
~%
~%~%~%"))
(cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql 'GetMapJson-response)))
"Returns full string definition for message of type 'GetMapJson-response"
(cl:format cl:nil "cruiser_msgs/MapJson json~%~%~%================================================================================~%MSG: cruiser_msgs/MapJson~%uint8[] data
~%
~%~%~%"))
(cl:defmethod roslisp-msg-protocol:serialization-length ((msg <GetMapJson-response>))
(cl:+ 0
(roslisp-msg-protocol:serialization-length (cl:slot-value msg 'json))
))
(cl:defmethod roslisp-msg-protocol:ros-message-to-list ((msg <GetMapJson-response>))
"Converts a ROS message object to a list"
(cl:list 'GetMapJson-response
(cl:cons ':json (json msg))
))
(cl:defmethod roslisp-msg-protocol:service-request-type ((msg (cl:eql 'GetMapJson)))
'GetMapJson-request)
(cl:defmethod roslisp-msg-protocol:service-response-type ((msg (cl:eql 'GetMapJson)))
'GetMapJson-response)
(cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql 'GetMapJson)))
"Returns string type for a service object of type '<GetMapJson>"
"cruiser_msgs/GetMapJson") |
9f2183a6ca7bb0a2fd522df9f708b78533c376fad073c33c872123525834b8ae | lambe-lang/compiler | type.mli | module Checker : sig
val check :
'a Lambe_ast.Type.gamma
-> 'a Lambe_ast.Type.t
-> 'a Lambe_ast.Kind.t
-> bool
val reduce :
'a Lambe_ast.Type.gamma -> 'a Lambe_ast.Type.t -> 'a Lambe_ast.Type.t option
val subsume :
'a Lambe_ast.Type.gamma
-> 'a Lambe_ast.Type.t
-> 'a Lambe_ast.Type.t
-> bool Context.state
val upper_type :
'a Lambe_ast.Type.gamma
-> 'a Lambe_ast.Type.t
-> 'a Lambe_ast.Type.t
-> 'a Lambe_ast.Type.t Option.t Context.state
module Operator : sig
val ( <:?> ) :
'a Lambe_ast.Type.t
-> 'a Lambe_ast.Kind.t
-> 'a Lambe_ast.Type.gamma
-> bool
val ( <? ) :
'a Lambe_ast.Type.t
-> 'a Lambe_ast.Type.t
-> Context.t
-> 'a Lambe_ast.Type.gamma
-> bool * Context.t
val ( |- ) :
'a Lambe_ast.Type.gamma -> ('a Lambe_ast.Type.gamma -> 'b) -> 'b
val ( --> ) :
'a Lambe_ast.Type.t
-> 'a Lambe_ast.Type.t option
-> 'a Lambe_ast.Type.gamma
-> bool
end
end
| null | https://raw.githubusercontent.com/lambe-lang/compiler/79d7937c06ca30e231855ec4ce99012ca0395cd5/lib/checker/type.mli | ocaml | module Checker : sig
val check :
'a Lambe_ast.Type.gamma
-> 'a Lambe_ast.Type.t
-> 'a Lambe_ast.Kind.t
-> bool
val reduce :
'a Lambe_ast.Type.gamma -> 'a Lambe_ast.Type.t -> 'a Lambe_ast.Type.t option
val subsume :
'a Lambe_ast.Type.gamma
-> 'a Lambe_ast.Type.t
-> 'a Lambe_ast.Type.t
-> bool Context.state
val upper_type :
'a Lambe_ast.Type.gamma
-> 'a Lambe_ast.Type.t
-> 'a Lambe_ast.Type.t
-> 'a Lambe_ast.Type.t Option.t Context.state
module Operator : sig
val ( <:?> ) :
'a Lambe_ast.Type.t
-> 'a Lambe_ast.Kind.t
-> 'a Lambe_ast.Type.gamma
-> bool
val ( <? ) :
'a Lambe_ast.Type.t
-> 'a Lambe_ast.Type.t
-> Context.t
-> 'a Lambe_ast.Type.gamma
-> bool * Context.t
val ( |- ) :
'a Lambe_ast.Type.gamma -> ('a Lambe_ast.Type.gamma -> 'b) -> 'b
val ( --> ) :
'a Lambe_ast.Type.t
-> 'a Lambe_ast.Type.t option
-> 'a Lambe_ast.Type.gamma
-> bool
end
end
| |
a416508561deb5ef9500a89d3af3b63db2b6cb8640f8fa05063df8ae22526950 | snmsts/cserial-port | main.lisp | (cl:in-package :cserial-port)
(defvar *default-name*
(%default-name *serial-class*))
(defvar *default-timeout-ms* nil)
(defvar *default-baud-rate* 9600)
(defvar *default-encoding* :latin-1)
(defvar *default-data-bits* 8)
(defvar *default-stop-bits* 1)
(defvar *default-parity* :none)
;;interfaces borrowed from lisp works
(defun open-serial
(&optional name
&rest args
&key
(baud-rate *default-baud-rate*)
(encoding *default-encoding*)
(data-bits *default-data-bits*)
(stop-bits *default-stop-bits*)
(parity *default-parity*)
;; below are not yet supported
cts-flow-p
dsr-flow-p
dtr
rts
read-interval-timeout
read-total-base-timeout
read-total-byte-timeout
write-total-base-timeout
write-total-byte-timeout)
"Attempts to open the named serial port and return a serial object."
(setq name (let ((name (or name *default-name*)))
(if (numberp name) (%default-name *serial-class* name) name)))
(%open (apply #'make-instance *serial-class*
:baud-rate baud-rate
:data-bits data-bits
:stop-bits stop-bits
:parity parity
:encoding encoding
args)
:name name))
(defun close-serial (serial)
"Closes a serial port"
(unless (%valid-fd-p serial)
(error "serial port ~S already closed" serial))
(%close serial)
t)
(defun get-serial-state (serial keys)
"The function get-serial-state queries various aspects of the state of the serial port associated with serial .
The argument keys should be a list of one or more of the keywords :dsr and :cts . These cause get-serial-state to check the DSR and CTS lines respectively.
The result state is a list giving the state of each line in the same order as they appear in the argument keys ."
(%get-serial-state serial keys))
(defun read-serial-char (serial &key (timeout-ms *default-timeout-ms*))
"Reads a character from a serial port. will return a character."
(unless (%valid-fd-p serial)
(error "invalid serial port ~S" serial))
(cffi:with-foreign-object (b :unsigned-char 1)
(let ((v (make-array
20
:fill-pointer 0
:element-type '(unsigned-byte 8))))
(loop
:do (when (= (%read serial b 1 timeout-ms) 1)
(vector-push-extend (cffi:mem-aref b :unsigned-char) v)
(let ((res (ignore-errors (babel:octets-to-string
v
:errorp t
:encoding (serial-encoding serial)))))
(when res
(return (aref res 0)))))))))
(defun read-serial-byte (serial &key (timeout-ms *default-timeout-ms*))
"Reads a byte from a serial port. will return byte."
(unless (%valid-fd-p serial)
(error "invalid serial port ~S" serial))
(cffi:with-foreign-object (b :unsigned-char 1)
(when (= (%read serial b 1 timeout-ms) 1)
(cffi:mem-aref b :unsigned-char))))
(defun read-serial-byte-vector (buf serial &key (timeout-ms *default-timeout-ms*) (start 0) (end (length buf)))
"Reads a byte from a serial port. will return count-read-bytes or nil when timeout."
(unless (%valid-fd-p serial)
(error "invalid serial port ~S" serial))
(cffi:with-pointer-to-vector-data (buf-sap buf)
(%read serial (cffi:inc-pointer buf-sap start) (- end start) timeout-ms)))
(defun read-serial-string (string serial &key (timeout-ms *default-timeout-ms*) (start 0) (end nil))
"Reads a string from a serial port."
(loop :repeat (- (or end (length string)) start)
:for i :from start
:for nread :from 1
:do (setf (aref string i) (read-serial-char serial :timeout-ms timeout-ms))
:finally (return nread)))
(defun serial-input-available-p (serial)
"Checks whether a character is available on a serial port."
(%input-available-p serial))
(defun set-serial-state (serial &rest args &key dtr rts break)
"Changes various aspects of the state of a serial port."
(declare (ignore dtr rts break))
t
"Description
The function set-serial-state changes various aspects of the state of the serial port associated with serial .
The argument dtr , if supplied, controls the DTR line. A true value means set and nil means clear. If dtr is not supplied, the state is unchanged.
The argument rts controls the RTS line in the same way.
The argument break controls the break state of the data line in the same way."
(apply #'%set-serial-state serial args))
(defun wait-serial-state (serial keys &key (timeout-ms *default-timeout-ms*))
"Waits for some aspect of the state of a serial port to change."
t
"Description
The function wait-serial-state waits for some state in the serial port associated with serial to change.
The argument keys should be a list of one or more of the keywords :cts , :dsr , :err , :ring , :rlsd and :break .
result is a list giving the keys for which the state has changed.
If timeout is non-nil then the function will return nil after that many seconds even if the state has not changed."
(error "not yet implemented")
nil)
(defun write-serial-char (char serial &key (timeout-ms *default-timeout-ms*))
"Writes a character to a serial port. will return written char."
(write-serial-string (string char) serial :timeout-ms timeout-ms))
(defun write-serial-string (string serial &key (timeout-ms *default-timeout-ms*) (start 0) (end nil))
"Writes a string to a serial port. will return written-bytes count."
(unless (%valid-fd-p serial)
(error "invalid serial port ~S" serial))
(cffi:with-foreign-string ((b l) (subseq string start end)
:encoding (serial-encoding serial))
(%write serial b (1- l) timeout-ms)))
(defun write-serial-byte (byte serial &key (timeout-ms *default-timeout-ms*))
"Writes a byte to a serial port. will return written byte."
(let ((data (make-array 1
:element-type '(unsigned-byte 8)
:initial-contents (list byte))))
(write-serial-byte-vector data serial :timeout-ms timeout-ms)
byte))
(defun write-serial-byte-vector (bytes serial &key (timeout-ms *default-timeout-ms*) (start 0) (end (length bytes)))
"Writes bytes to a serial port. will return written-bytes count."
(unless (%valid-fd-p serial)
(error "invalid serial port ~S" serial))
(cffi:with-pointer-to-vector-data (data-sap bytes)
(%write serial (cffi:inc-pointer data-sap start) (- end start) timeout-ms)))
;;more
(defmacro with-serial ((serial name &rest params) &body body)
`(let ((,serial (open-serial ,name ,@params)))
(unwind-protect
(progn ,@body)
(close-serial ,serial))))
(defmacro with-timeout ((ms) &body body)
`(let ((*default-timeout-ms* ,ms))
,@body))
| null | https://raw.githubusercontent.com/snmsts/cserial-port/ba8ba8a7ba69d31970d29ec8dfe4cce937a71e4a/src/main.lisp | lisp | interfaces borrowed from lisp works
below are not yet supported
more | (cl:in-package :cserial-port)
(defvar *default-name*
(%default-name *serial-class*))
(defvar *default-timeout-ms* nil)
(defvar *default-baud-rate* 9600)
(defvar *default-encoding* :latin-1)
(defvar *default-data-bits* 8)
(defvar *default-stop-bits* 1)
(defvar *default-parity* :none)
(defun open-serial
(&optional name
&rest args
&key
(baud-rate *default-baud-rate*)
(encoding *default-encoding*)
(data-bits *default-data-bits*)
(stop-bits *default-stop-bits*)
(parity *default-parity*)
cts-flow-p
dsr-flow-p
dtr
rts
read-interval-timeout
read-total-base-timeout
read-total-byte-timeout
write-total-base-timeout
write-total-byte-timeout)
"Attempts to open the named serial port and return a serial object."
(setq name (let ((name (or name *default-name*)))
(if (numberp name) (%default-name *serial-class* name) name)))
(%open (apply #'make-instance *serial-class*
:baud-rate baud-rate
:data-bits data-bits
:stop-bits stop-bits
:parity parity
:encoding encoding
args)
:name name))
(defun close-serial (serial)
"Closes a serial port"
(unless (%valid-fd-p serial)
(error "serial port ~S already closed" serial))
(%close serial)
t)
(defun get-serial-state (serial keys)
"The function get-serial-state queries various aspects of the state of the serial port associated with serial .
The argument keys should be a list of one or more of the keywords :dsr and :cts . These cause get-serial-state to check the DSR and CTS lines respectively.
The result state is a list giving the state of each line in the same order as they appear in the argument keys ."
(%get-serial-state serial keys))
(defun read-serial-char (serial &key (timeout-ms *default-timeout-ms*))
"Reads a character from a serial port. will return a character."
(unless (%valid-fd-p serial)
(error "invalid serial port ~S" serial))
(cffi:with-foreign-object (b :unsigned-char 1)
(let ((v (make-array
20
:fill-pointer 0
:element-type '(unsigned-byte 8))))
(loop
:do (when (= (%read serial b 1 timeout-ms) 1)
(vector-push-extend (cffi:mem-aref b :unsigned-char) v)
(let ((res (ignore-errors (babel:octets-to-string
v
:errorp t
:encoding (serial-encoding serial)))))
(when res
(return (aref res 0)))))))))
(defun read-serial-byte (serial &key (timeout-ms *default-timeout-ms*))
"Reads a byte from a serial port. will return byte."
(unless (%valid-fd-p serial)
(error "invalid serial port ~S" serial))
(cffi:with-foreign-object (b :unsigned-char 1)
(when (= (%read serial b 1 timeout-ms) 1)
(cffi:mem-aref b :unsigned-char))))
(defun read-serial-byte-vector (buf serial &key (timeout-ms *default-timeout-ms*) (start 0) (end (length buf)))
"Reads a byte from a serial port. will return count-read-bytes or nil when timeout."
(unless (%valid-fd-p serial)
(error "invalid serial port ~S" serial))
(cffi:with-pointer-to-vector-data (buf-sap buf)
(%read serial (cffi:inc-pointer buf-sap start) (- end start) timeout-ms)))
(defun read-serial-string (string serial &key (timeout-ms *default-timeout-ms*) (start 0) (end nil))
"Reads a string from a serial port."
(loop :repeat (- (or end (length string)) start)
:for i :from start
:for nread :from 1
:do (setf (aref string i) (read-serial-char serial :timeout-ms timeout-ms))
:finally (return nread)))
(defun serial-input-available-p (serial)
"Checks whether a character is available on a serial port."
(%input-available-p serial))
(defun set-serial-state (serial &rest args &key dtr rts break)
"Changes various aspects of the state of a serial port."
(declare (ignore dtr rts break))
t
"Description
The function set-serial-state changes various aspects of the state of the serial port associated with serial .
The argument dtr , if supplied, controls the DTR line. A true value means set and nil means clear. If dtr is not supplied, the state is unchanged.
The argument rts controls the RTS line in the same way.
The argument break controls the break state of the data line in the same way."
(apply #'%set-serial-state serial args))
(defun wait-serial-state (serial keys &key (timeout-ms *default-timeout-ms*))
"Waits for some aspect of the state of a serial port to change."
t
"Description
The function wait-serial-state waits for some state in the serial port associated with serial to change.
The argument keys should be a list of one or more of the keywords :cts , :dsr , :err , :ring , :rlsd and :break .
result is a list giving the keys for which the state has changed.
If timeout is non-nil then the function will return nil after that many seconds even if the state has not changed."
(error "not yet implemented")
nil)
(defun write-serial-char (char serial &key (timeout-ms *default-timeout-ms*))
"Writes a character to a serial port. will return written char."
(write-serial-string (string char) serial :timeout-ms timeout-ms))
(defun write-serial-string (string serial &key (timeout-ms *default-timeout-ms*) (start 0) (end nil))
"Writes a string to a serial port. will return written-bytes count."
(unless (%valid-fd-p serial)
(error "invalid serial port ~S" serial))
(cffi:with-foreign-string ((b l) (subseq string start end)
:encoding (serial-encoding serial))
(%write serial b (1- l) timeout-ms)))
(defun write-serial-byte (byte serial &key (timeout-ms *default-timeout-ms*))
"Writes a byte to a serial port. will return written byte."
(let ((data (make-array 1
:element-type '(unsigned-byte 8)
:initial-contents (list byte))))
(write-serial-byte-vector data serial :timeout-ms timeout-ms)
byte))
(defun write-serial-byte-vector (bytes serial &key (timeout-ms *default-timeout-ms*) (start 0) (end (length bytes)))
"Writes bytes to a serial port. will return written-bytes count."
(unless (%valid-fd-p serial)
(error "invalid serial port ~S" serial))
(cffi:with-pointer-to-vector-data (data-sap bytes)
(%write serial (cffi:inc-pointer data-sap start) (- end start) timeout-ms)))
(defmacro with-serial ((serial name &rest params) &body body)
`(let ((,serial (open-serial ,name ,@params)))
(unwind-protect
(progn ,@body)
(close-serial ,serial))))
(defmacro with-timeout ((ms) &body body)
`(let ((*default-timeout-ms* ,ms))
,@body))
|
f2e50831d773fc8608f07707d06f23fb9fb74e3ca8728a3b6cc60be47674a012 | coalton-lang/coalton | settings.lisp | ;;;; settings.lisp
;;;;
;;;; This file contains variables that can be used to control how
Coalton works .
(defpackage #:coalton-impl/settings
(:use #:cl)
(:export
#:coalton-release-p ; FUNCTION
#:*coalton-print-unicode* ; VARIABLE
#:*coalton-dump-ast* ; VARIABLE
#:*coalton-skip-update* ; VARIABLE
#:*emit-type-annotations* ; VARIABLE
#:*coalton-stage-1-complete* ; VARIABLE
#:*coalton-optimize* ; VARIABLE
#:*coalton-optimize-library* ; VARIABLE
))
(in-package #:coalton-impl/settings)
(declaim (type boolean *coalton-print-unicode*))
(defvar *coalton-print-unicode* t
"Whether to print coalton info using unicode symbols")
(defun coalton-release-p ()
"Determines how redefinable code generated by Coalton is.
In development mode (i.e. (not (coalton-release-p))), Coalton turns all declare-type forms into CLOS objects
to support a repl based workflow.
In release mode Coalton compiles declare-type forms into frozen structs or even more optimal layouts which may
not support redefinition.
Development mode is the default.
Enable release mode either by setting the UNIX environment variable COALTON_ENV to \"release\", or by pushing
`:release' into `*features*'. Either of these must be done before loading Coalton.
"
(uiop:featurep :coalton-release))
(when (string-equal (uiop:getenv "COALTON_ENV") "release")
(pushnew :coalton-release *features*))
(when (coalton-release-p)
(format t "~&;; COALTON starting in release mode~%"))
;; Configure the backend to print out the ast of toplevel forms
(declaim (type boolean *coalton-dump-ast*))
(defvar *coalton-dump-ast* nil)
;; Configure the backend to remove env updates from the generated code
(declaim (type boolean *coalton-skip-update*))
(defvar *coalton-skip-update* nil)
;; Configure the backend to remove type annotations from the generated code
(declaim (type boolean *emit-type-annotations*))
(defvar *emit-type-annotations* t)
;; Set to t when base types are defined
(declaim (type boolean *coalton-stage-1-complete*))
this has to be a ` defparameter ' , not a ` defvar ' , or else re - loading coalton in an image where it 's already
;; been compiled once will fail.
(defparameter *coalton-stage-1-complete* nil)
(defvar *coalton-optimize* '(optimize (speed 3) (safety 0)))
(defvar *coalton-optimize-library* '(optimize (speed 3) (safety 1)))
| null | https://raw.githubusercontent.com/coalton-lang/coalton/e3c284d90d98b051a871521b6ef0af5193c89597/src/settings.lisp | lisp | settings.lisp
This file contains variables that can be used to control how
FUNCTION
VARIABLE
VARIABLE
VARIABLE
VARIABLE
VARIABLE
VARIABLE
VARIABLE
Configure the backend to print out the ast of toplevel forms
Configure the backend to remove env updates from the generated code
Configure the backend to remove type annotations from the generated code
Set to t when base types are defined
been compiled once will fail. | Coalton works .
(defpackage #:coalton-impl/settings
(:use #:cl)
(:export
))
(in-package #:coalton-impl/settings)
(declaim (type boolean *coalton-print-unicode*))
(defvar *coalton-print-unicode* t
"Whether to print coalton info using unicode symbols")
(defun coalton-release-p ()
"Determines how redefinable code generated by Coalton is.
In development mode (i.e. (not (coalton-release-p))), Coalton turns all declare-type forms into CLOS objects
to support a repl based workflow.
In release mode Coalton compiles declare-type forms into frozen structs or even more optimal layouts which may
not support redefinition.
Development mode is the default.
Enable release mode either by setting the UNIX environment variable COALTON_ENV to \"release\", or by pushing
`:release' into `*features*'. Either of these must be done before loading Coalton.
"
(uiop:featurep :coalton-release))
(when (string-equal (uiop:getenv "COALTON_ENV") "release")
(pushnew :coalton-release *features*))
(when (coalton-release-p)
(format t "~&;; COALTON starting in release mode~%"))
(declaim (type boolean *coalton-dump-ast*))
(defvar *coalton-dump-ast* nil)
(declaim (type boolean *coalton-skip-update*))
(defvar *coalton-skip-update* nil)
(declaim (type boolean *emit-type-annotations*))
(defvar *emit-type-annotations* t)
(declaim (type boolean *coalton-stage-1-complete*))
this has to be a ` defparameter ' , not a ` defvar ' , or else re - loading coalton in an image where it 's already
(defparameter *coalton-stage-1-complete* nil)
(defvar *coalton-optimize* '(optimize (speed 3) (safety 0)))
(defvar *coalton-optimize-library* '(optimize (speed 3) (safety 1)))
|
73c6adaca05077683f5c8bdf0eb9a86f70d22971cdd187b5de008945808cc938 | wenkokke/MonoProc | FreeNames.hs | module PROC.MF.FreeNames where
import PROC.Base
import Data.Monoid ((<>))
import Data.Set (Set)
import qualified Data.Set as S
-- * Free Variable Names
class FreeNames a where
freeNames :: a -> Set Name
isFreeIn :: Name -> a -> Bool
isFreeIn x a = S.member x (freeNames a)
instance FreeNames Prog where
freeNames (Prog _ s) = freeNames s
instance FreeNames Stmt where
freeNames (Assign _ _ a) = freeNames a
freeNames (Skip _) = S.empty
freeNames (IfThen _ s1 s2) = freeNames s1 <> freeNames s2
freeNames (While _ s1) = freeNames s1
freeNames (Seq s1 s2) = freeNames s1 <> freeNames s2
freeNames (Call _ _ _ _) = S.empty
instance FreeNames BExpr where
freeNames (BConst _) = S.empty
freeNames (Lt a1 a2) = freeNames a1 <> freeNames a2
freeNames (Lte a1 a2) = freeNames a1 <> freeNames a2
freeNames (Gt a1 a2) = freeNames a1 <> freeNames a2
freeNames (Gte a1 a2) = freeNames a1 <> freeNames a2
freeNames (Eq a1 a2) = freeNames a1 <> freeNames a2
freeNames (Neq a1 a2) = freeNames a1 <> freeNames a2
freeNames (Not a1) = freeNames a1
instance FreeNames AExpr where
freeNames (ANull) = S.empty
freeNames (AName n) = S.singleton n
freeNames (AConst _) = S.empty
freeNames (Add e1 e2) = freeNames e1 <> freeNames e2
freeNames (Sub e1 e2) = freeNames e1 <> freeNames e2
freeNames (Mul e1 e2) = freeNames e1 <> freeNames e2
freeNames (Div e1 e2) = freeNames e1 <> freeNames e2
freeNames (Neg e1) = freeNames e1
| null | https://raw.githubusercontent.com/wenkokke/MonoProc/c3d00bd55ee8a6f2c12ebf5abb226c731e856350/src/PROC/MF/FreeNames.hs | haskell | * Free Variable Names | module PROC.MF.FreeNames where
import PROC.Base
import Data.Monoid ((<>))
import Data.Set (Set)
import qualified Data.Set as S
class FreeNames a where
freeNames :: a -> Set Name
isFreeIn :: Name -> a -> Bool
isFreeIn x a = S.member x (freeNames a)
instance FreeNames Prog where
freeNames (Prog _ s) = freeNames s
instance FreeNames Stmt where
freeNames (Assign _ _ a) = freeNames a
freeNames (Skip _) = S.empty
freeNames (IfThen _ s1 s2) = freeNames s1 <> freeNames s2
freeNames (While _ s1) = freeNames s1
freeNames (Seq s1 s2) = freeNames s1 <> freeNames s2
freeNames (Call _ _ _ _) = S.empty
instance FreeNames BExpr where
freeNames (BConst _) = S.empty
freeNames (Lt a1 a2) = freeNames a1 <> freeNames a2
freeNames (Lte a1 a2) = freeNames a1 <> freeNames a2
freeNames (Gt a1 a2) = freeNames a1 <> freeNames a2
freeNames (Gte a1 a2) = freeNames a1 <> freeNames a2
freeNames (Eq a1 a2) = freeNames a1 <> freeNames a2
freeNames (Neq a1 a2) = freeNames a1 <> freeNames a2
freeNames (Not a1) = freeNames a1
instance FreeNames AExpr where
freeNames (ANull) = S.empty
freeNames (AName n) = S.singleton n
freeNames (AConst _) = S.empty
freeNames (Add e1 e2) = freeNames e1 <> freeNames e2
freeNames (Sub e1 e2) = freeNames e1 <> freeNames e2
freeNames (Mul e1 e2) = freeNames e1 <> freeNames e2
freeNames (Div e1 e2) = freeNames e1 <> freeNames e2
freeNames (Neg e1) = freeNames e1
|
f267c803f8cb9f75b5309e108fb2869addf8f793a4874081e3fd1b52e7c8710e | tsloughter/mmmbot | mmmbot_images.erl | %%%-------------------------------------------------------------------
@author < >
( C ) 2012 ,
%%% @doc
%%%
%%% @end
Created : 29 Apr 2012 by < >
%%%-------------------------------------------------------------------
-module(mmmbot_images).
-behaviour(gen_event).
%% API
-export([start/0]).
%% gen_event callbacks
-export([init/1, handle_event/2, handle_call/2,
handle_info/2, terminate/2, code_change/3]).
-define(SERVER, ?MODULE).
-record(state, {bucket, mp}).
%%%===================================================================
%%% gen_event callbacks
%%%===================================================================
start() ->
mmmbot_em:add_handler(?SERVER).
%%--------------------------------------------------------------------
init([]) ->
{ok, AccessKey} = application:get_env(mmmbot_images, access_key),
{ok, SecretKey} = application:get_env(mmmbot_images, secret_key),
{ok, Bucket} = application:get_env(mmmbot_images, bucket),
erlcloud_s3:configure(AccessKey, SecretKey),
{ok, MP} = re:compile("(http|https)://(\\S*)(\\.jpg|\\.png|\\.gif|\\.jpeg|\\.xmp|\\.tiff)", [caseless]),
{ok, #state{bucket=Bucket, mp=MP}}.
%%--------------------------------------------------------------------
handle_event({Line, _User}, State=#state{bucket=Bucket, mp=MP}) ->
AWSConfig = erlcloud_aws:default_config(),
proc_lib:spawn_link(fun() ->
parse(Bucket, Line, MP, AWSConfig)
end),
{ok, State}.
%%--------------------------------------------------------------------
handle_call(_Request, State) ->
Reply = ok,
{ok, Reply, State}.
%%--------------------------------------------------------------------
handle_info(_Info, State) ->
{ok, State}.
%%--------------------------------------------------------------------
terminate(_Reason, _State) ->
ok.
%%--------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%===================================================================
Internal functions
%%%===================================================================
-spec parse(string(), string(), re:mp(), tuple()) -> ok.
parse(Bucket, Msg, MP, AWSConfig) ->
case re:run(Msg, MP, [{capture, first, list}]) of
nomatch ->
ok;
{match, [URL]} ->
image_to_s3(Bucket, URL, false, AWSConfig)
end.
-spec image_to_s3(string(), string(), boolean(), tuple()) -> proplists:proplist().
image_to_s3(Bucket, URL, IsSSL, AWSConfig) ->
ExtStr = string:substr(URL, string:rchr(URL, $.)),
Filename = generate_filename(string:sub_word(filename:basename(URL), 1, $.), ExtStr),
{ok, "200", _, Image} = ibrowse:send_req(URL, [], get, "",
[{is_ssl, IsSSL}, {ssl_options, []}]),
lager:info("Uploading image ~p~n", [Filename]),
erlcloud_s3:put_object(Bucket, Filename, Image, AWSConfig).
-spec generate_filename(string(), string()) -> string().
generate_filename(Basename, ExtStr) ->
lists:flatten([Basename, "_", integer_to_list(calendar:datetime_to_gregorian_seconds(calendar:local_time())), ExtStr]).
%%%===================================================================
%%% Tests
%%%===================================================================
| null | https://raw.githubusercontent.com/tsloughter/mmmbot/12986c8b0984824aa0565fb8fa0e60082b660c97/apps/mmmbot_images/src/mmmbot_images.erl | erlang | -------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
API
gen_event callbacks
===================================================================
gen_event callbacks
===================================================================
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
===================================================================
===================================================================
===================================================================
Tests
=================================================================== | @author < >
( C ) 2012 ,
Created : 29 Apr 2012 by < >
-module(mmmbot_images).
-behaviour(gen_event).
-export([start/0]).
-export([init/1, handle_event/2, handle_call/2,
handle_info/2, terminate/2, code_change/3]).
-define(SERVER, ?MODULE).
-record(state, {bucket, mp}).
start() ->
mmmbot_em:add_handler(?SERVER).
init([]) ->
{ok, AccessKey} = application:get_env(mmmbot_images, access_key),
{ok, SecretKey} = application:get_env(mmmbot_images, secret_key),
{ok, Bucket} = application:get_env(mmmbot_images, bucket),
erlcloud_s3:configure(AccessKey, SecretKey),
{ok, MP} = re:compile("(http|https)://(\\S*)(\\.jpg|\\.png|\\.gif|\\.jpeg|\\.xmp|\\.tiff)", [caseless]),
{ok, #state{bucket=Bucket, mp=MP}}.
handle_event({Line, _User}, State=#state{bucket=Bucket, mp=MP}) ->
AWSConfig = erlcloud_aws:default_config(),
proc_lib:spawn_link(fun() ->
parse(Bucket, Line, MP, AWSConfig)
end),
{ok, State}.
handle_call(_Request, State) ->
Reply = ok,
{ok, Reply, State}.
handle_info(_Info, State) ->
{ok, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
-spec parse(string(), string(), re:mp(), tuple()) -> ok.
parse(Bucket, Msg, MP, AWSConfig) ->
case re:run(Msg, MP, [{capture, first, list}]) of
nomatch ->
ok;
{match, [URL]} ->
image_to_s3(Bucket, URL, false, AWSConfig)
end.
-spec image_to_s3(string(), string(), boolean(), tuple()) -> proplists:proplist().
image_to_s3(Bucket, URL, IsSSL, AWSConfig) ->
ExtStr = string:substr(URL, string:rchr(URL, $.)),
Filename = generate_filename(string:sub_word(filename:basename(URL), 1, $.), ExtStr),
{ok, "200", _, Image} = ibrowse:send_req(URL, [], get, "",
[{is_ssl, IsSSL}, {ssl_options, []}]),
lager:info("Uploading image ~p~n", [Filename]),
erlcloud_s3:put_object(Bucket, Filename, Image, AWSConfig).
-spec generate_filename(string(), string()) -> string().
generate_filename(Basename, ExtStr) ->
lists:flatten([Basename, "_", integer_to_list(calendar:datetime_to_gregorian_seconds(calendar:local_time())), ExtStr]).
|
7cef0bf894d770b151f47ef6509dffe773dfd301878814d87174ec441166a6dd | semilin/layoup | hail.lisp |
(MAKE-LAYOUT :NAME "hail" :MATRIX (APPLY #'KEY-MATRIX 'NIL) :SHIFT-MATRIX NIL
:KEYBOARD NIL) | null | https://raw.githubusercontent.com/semilin/layoup/27ec9ba9a9388cd944ac46206d10424e3ab45499/data/layouts/hail.lisp | lisp |
(MAKE-LAYOUT :NAME "hail" :MATRIX (APPLY #'KEY-MATRIX 'NIL) :SHIFT-MATRIX NIL
:KEYBOARD NIL) | |
ab469a7fbadddb1f92223c550f5c5765c2af291251810e46bb2c0829d001b56b | cram2/cram | gripper.lisp | ;;;
Copyright ( c ) 2016 , < >
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions are met:
;;;
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
* Neither the name of the Institute for Artificial Intelligence/
;;; Universitaet Bremen nor the names of its contributors may be used to
;;; endorse or promote products derived from this software without
;;; specific prior written permission.
;;;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
;;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
;;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
;;; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN
;;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
;;; POSSIBILITY OF SUCH DAMAGE.
(in-package :pr2-ll)
(defparameter *gripper-convergence-delta* 0.001 "in meters")
(defparameter *gripper-action-timeout* 10.0 "in seconds")
(defparameter *gripper-minimal-position* 0.0017235310878717042d0 "in meters")
(defvar *gripper-action-clients* '(:left nil :right nil)
"A list to store PR2 gripper action clients for left and right gripper.")
(defun init-gripper-action-client (left-or-right)
(let ((action-server-name (concatenate
'string
(ecase left-or-right
(:left "l")
(:right "r"))
"_gripper_controller/gripper_action")))
(prog1
(setf (getf *gripper-action-clients* left-or-right)
(actionlib:make-action-client
action-server-name
"pr2_controllers_msgs/Pr2GripperCommandAction"))
(loop until (actionlib:wait-for-server
(getf *gripper-action-clients* left-or-right)
5.0)
do (roslisp:ros-info (gripper-action)
"Waiting for ~a gripper action server."
left-or-right))
(roslisp:ros-info (gripper-action)
"~a gripper action client created."
left-or-right))))
(defun init-gripper-action-clients ()
(mapc #'init-gripper-action-client '(:left :right)))
(defun destroy-gripper-action-clients ()
(setf *gripper-action-clients* '(:left nil :right nil)))
(roslisp-utilities:register-ros-cleanup-function destroy-gripper-action-clients)
(defun get-gripper-action-client (left-or-right)
(or (getf *gripper-action-clients* left-or-right)
(init-gripper-action-client left-or-right)))
(defun make-gripper-action-goal (action-client position &optional max-effort)
(actionlib:make-action-goal action-client
(position command) position
(max_effort command) max-effort))
(defun ensure-gripper-input-parameters (position max-effort)
(let ((position
(etypecase position
(number (cond
((< position 0.0)
(roslisp:ros-warn (gripper-action)
"POSITION (~a) cannot be < 0.0. Clipping."
position)
0.0)
((> position 0.085)
(roslisp:ros-warn (gripper-action)
"POSITION (~a) shouldn't be > 0.085. Clipping."
position)
0.085)
(t
position)))
(keyword (ecase position
(:open 0.085)
(:close *gripper-minimal-position*)
(:grip *gripper-minimal-position*)))))
(max-effort
(or max-effort
(etypecase position
(number 50.0)
(keyword (ecase position
(:open -1)
(:close 500.0) ; because of stupid gazebo
(:grip 50.0)))))))
(values position max-effort)))
(defun ensure-gripper-goal-reached (result
status
original-goal-position
goal-position
convergence-delta)
(when (eql status :timeout)
(roslisp:ros-warn (pr2-ll gripper) "Gripper action timed out."))
(let* ((current-position
(pr2_controllers_msgs-msg:position result))
;; TODO: use current-position from joint state message, not result
;; (current-position (car (joint-positions (list cram-tf:*left-gripper-joint*))))
(converged-p
(values-converged current-position goal-position convergence-delta)))
(if (eql original-goal-position :grip) ; gripper should not completely close
(when converged-p
(cpl:fail 'common-fail:gripper-closed-completely
:description "Tried to grasp but ended up closing the gripper."))
(unless converged-p
(cpl:fail 'common-fail:gripper-goal-not-reached
:description (format nil "Gripper action did not converge to the goal:
goal: ~a, current: ~a, delta: ~a." goal-position current-position convergence-delta))))))
(defun call-gripper-action (left-or-right position &key
max-effort
(delta *gripper-convergence-delta*)
(action-timeout *gripper-action-timeout*))
(declare (type (or keyword list) left-or-right)
(type (or keyword number) position)
(type (or null number) max-effort)
(type number delta action-timeout))
"`goal-position' can be :open, :close, :grip or a joint position."
(multiple-value-bind (goal-position max-effort)
(ensure-gripper-input-parameters position max-effort)
(flet ((move-the-hand-yo (l-or-r)
(multiple-value-bind (result status)
(cpl:with-failure-handling
((simple-error (e)
(format t "Actionlib error occured!~%~a~%Reinitializing...~%~%" e)
(init-gripper-action-clients)
(cpl:retry)))
(let ((actionlib:*action-server-timeout* 10.0)
(action-client (get-gripper-action-client l-or-r)))
(if (eql position :grip) ; double check that we really grasped properly
(progn
(actionlib:call-goal
action-client
(make-gripper-action-goal action-client goal-position max-effort)
:timeout action-timeout)
(cpl:sleep 0.5)
(actionlib:call-goal
action-client
(make-gripper-action-goal action-client goal-position max-effort)
:timeout action-timeout))
(actionlib:call-goal
action-client
(make-gripper-action-goal action-client goal-position max-effort)
:timeout action-timeout))))
(ensure-gripper-goal-reached result status position goal-position delta)
(values result status))))
(if (and left-or-right (listp left-or-right))
(cpl:par
(move-the-hand-yo (first left-or-right))
(move-the-hand-yo (second left-or-right)))
(move-the-hand-yo left-or-right)))))
| null | https://raw.githubusercontent.com/cram2/cram/dcb73031ee944d04215bbff9e98b9e8c210ef6c5/cram_pr2/cram_pr2_low_level/src/gripper.lisp | lisp |
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
Universitaet Bremen nor the names of its contributors may be used to
endorse or promote products derived from this software without
specific prior written permission.
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
because of stupid gazebo
TODO: use current-position from joint state message, not result
(current-position (car (joint-positions (list cram-tf:*left-gripper-joint*))))
gripper should not completely close
double check that we really grasped properly | Copyright ( c ) 2016 , < >
* Neither the name of the Institute for Artificial Intelligence/
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN
(in-package :pr2-ll)
(defparameter *gripper-convergence-delta* 0.001 "in meters")
(defparameter *gripper-action-timeout* 10.0 "in seconds")
(defparameter *gripper-minimal-position* 0.0017235310878717042d0 "in meters")
(defvar *gripper-action-clients* '(:left nil :right nil)
"A list to store PR2 gripper action clients for left and right gripper.")
(defun init-gripper-action-client (left-or-right)
(let ((action-server-name (concatenate
'string
(ecase left-or-right
(:left "l")
(:right "r"))
"_gripper_controller/gripper_action")))
(prog1
(setf (getf *gripper-action-clients* left-or-right)
(actionlib:make-action-client
action-server-name
"pr2_controllers_msgs/Pr2GripperCommandAction"))
(loop until (actionlib:wait-for-server
(getf *gripper-action-clients* left-or-right)
5.0)
do (roslisp:ros-info (gripper-action)
"Waiting for ~a gripper action server."
left-or-right))
(roslisp:ros-info (gripper-action)
"~a gripper action client created."
left-or-right))))
(defun init-gripper-action-clients ()
(mapc #'init-gripper-action-client '(:left :right)))
(defun destroy-gripper-action-clients ()
(setf *gripper-action-clients* '(:left nil :right nil)))
(roslisp-utilities:register-ros-cleanup-function destroy-gripper-action-clients)
(defun get-gripper-action-client (left-or-right)
(or (getf *gripper-action-clients* left-or-right)
(init-gripper-action-client left-or-right)))
(defun make-gripper-action-goal (action-client position &optional max-effort)
(actionlib:make-action-goal action-client
(position command) position
(max_effort command) max-effort))
(defun ensure-gripper-input-parameters (position max-effort)
(let ((position
(etypecase position
(number (cond
((< position 0.0)
(roslisp:ros-warn (gripper-action)
"POSITION (~a) cannot be < 0.0. Clipping."
position)
0.0)
((> position 0.085)
(roslisp:ros-warn (gripper-action)
"POSITION (~a) shouldn't be > 0.085. Clipping."
position)
0.085)
(t
position)))
(keyword (ecase position
(:open 0.085)
(:close *gripper-minimal-position*)
(:grip *gripper-minimal-position*)))))
(max-effort
(or max-effort
(etypecase position
(number 50.0)
(keyword (ecase position
(:open -1)
(:grip 50.0)))))))
(values position max-effort)))
(defun ensure-gripper-goal-reached (result
status
original-goal-position
goal-position
convergence-delta)
(when (eql status :timeout)
(roslisp:ros-warn (pr2-ll gripper) "Gripper action timed out."))
(let* ((current-position
(pr2_controllers_msgs-msg:position result))
(converged-p
(values-converged current-position goal-position convergence-delta)))
(when converged-p
(cpl:fail 'common-fail:gripper-closed-completely
:description "Tried to grasp but ended up closing the gripper."))
(unless converged-p
(cpl:fail 'common-fail:gripper-goal-not-reached
:description (format nil "Gripper action did not converge to the goal:
goal: ~a, current: ~a, delta: ~a." goal-position current-position convergence-delta))))))
(defun call-gripper-action (left-or-right position &key
max-effort
(delta *gripper-convergence-delta*)
(action-timeout *gripper-action-timeout*))
(declare (type (or keyword list) left-or-right)
(type (or keyword number) position)
(type (or null number) max-effort)
(type number delta action-timeout))
"`goal-position' can be :open, :close, :grip or a joint position."
(multiple-value-bind (goal-position max-effort)
(ensure-gripper-input-parameters position max-effort)
(flet ((move-the-hand-yo (l-or-r)
(multiple-value-bind (result status)
(cpl:with-failure-handling
((simple-error (e)
(format t "Actionlib error occured!~%~a~%Reinitializing...~%~%" e)
(init-gripper-action-clients)
(cpl:retry)))
(let ((actionlib:*action-server-timeout* 10.0)
(action-client (get-gripper-action-client l-or-r)))
(progn
(actionlib:call-goal
action-client
(make-gripper-action-goal action-client goal-position max-effort)
:timeout action-timeout)
(cpl:sleep 0.5)
(actionlib:call-goal
action-client
(make-gripper-action-goal action-client goal-position max-effort)
:timeout action-timeout))
(actionlib:call-goal
action-client
(make-gripper-action-goal action-client goal-position max-effort)
:timeout action-timeout))))
(ensure-gripper-goal-reached result status position goal-position delta)
(values result status))))
(if (and left-or-right (listp left-or-right))
(cpl:par
(move-the-hand-yo (first left-or-right))
(move-the-hand-yo (second left-or-right)))
(move-the-hand-yo left-or-right)))))
|
2f24c9ddf2079d221f2d96c34591660a672903d3f2f969826b8c034d6d3dbcef | seckcoder/iu_c311 | type-check.rkt | ; type checking for ki
| null | https://raw.githubusercontent.com/seckcoder/iu_c311/a1215983b6ab08df32058ef1e089cb294419e567/racket/compiler/ki/type-check.rkt | racket | type checking for ki | |
f5fd1a3cc59d8257abcd5eedce24132d9979d72cebb4a09d7525feb1a9aa250e | janestreet/ecaml | display_property.mli | (** [(Info-goto-node "(elisp)Display Property")] *)
open! Core
open! Import
module Margin : sig
type t =
| Left
| Right
[@@deriving sexp_of]
end
type t = Display_in_margin of Margin.t [@@deriving sexp_of]
val to_values : t -> Value.t list
val of_values_exn : Value.t * Value.t -> t
| null | https://raw.githubusercontent.com/janestreet/ecaml/f4efda2ee2dd59ef18722c8c2232fb8972a6770c/src/display_property.mli | ocaml | * [(Info-goto-node "(elisp)Display Property")] |
open! Core
open! Import
module Margin : sig
type t =
| Left
| Right
[@@deriving sexp_of]
end
type t = Display_in_margin of Margin.t [@@deriving sexp_of]
val to_values : t -> Value.t list
val of_values_exn : Value.t * Value.t -> t
|
86d4b5d7353c9a5247c63005eec323cfa30f054790a3c9fdf8f6a9d004c108e1 | tezos/tezos-mirror | fr_carray.ml | (*****************************************************************************)
(* *)
MIT 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. *)
(* *)
(*****************************************************************************)
module Scalar = Bls12_381.Fr
module Elt = struct
type t = Scalar.t
let size = Scalar.size_in_bytes
let zero = Scalar.zero
let allocate () = Scalar.(copy zero)
let eq = Scalar.eq
end
include Carray.Make (Elt)
(* Generator of the multiplicative group Fr^* *)
let generator = Scalar.of_int 7
(* Samples a primitive [n]-th root of unity. *)
let primitive_root_of_unity n =
let n = Z.of_int n in
let multiplicative_group_order = Z.(Scalar.order - one) in
if not (Z.divisible multiplicative_group_order n) then
raise
(Invalid_argument
(Format.sprintf
"There do not exist %s-th roots of unity"
(Z.to_string n)))
else
let exponent = Z.divexact multiplicative_group_order n in
Scalar.pow generator exponent
Samples a 2^i - th root of unity , assuming that it exists
let primitive_root_of_unity_power_of_two ~log =
primitive_root_of_unity (1 lsl log)
let build_array init next len =
let xi = ref init in
Array.init len (fun _ ->
let i = !xi in
xi := next !xi ;
i)
TODO return carray instead of array ?
computes [ | 1 ; x ; x² ; x³ ; ... ; xᵈ⁻¹ | ]
let powers d x = build_array Scalar.one Scalar.(mul x) d
let build_domain n = powers n (primitive_root_of_unity n)
let build_domain_power_of_two ~log =
let g = primitive_root_of_unity_power_of_two ~log in
powers (1 lsl log) g
| null | https://raw.githubusercontent.com/tezos/tezos-mirror/a42b3090645b62bdc1e4e82c69bebefbc0de9763/src/lib_bls12_381_polynomial/fr_carray.ml | ocaml | ***************************************************************************
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.
***************************************************************************
Generator of the multiplicative group Fr^*
Samples a primitive [n]-th root of unity. | MIT License
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
module Scalar = Bls12_381.Fr
module Elt = struct
type t = Scalar.t
let size = Scalar.size_in_bytes
let zero = Scalar.zero
let allocate () = Scalar.(copy zero)
let eq = Scalar.eq
end
include Carray.Make (Elt)
let generator = Scalar.of_int 7
let primitive_root_of_unity n =
let n = Z.of_int n in
let multiplicative_group_order = Z.(Scalar.order - one) in
if not (Z.divisible multiplicative_group_order n) then
raise
(Invalid_argument
(Format.sprintf
"There do not exist %s-th roots of unity"
(Z.to_string n)))
else
let exponent = Z.divexact multiplicative_group_order n in
Scalar.pow generator exponent
Samples a 2^i - th root of unity , assuming that it exists
let primitive_root_of_unity_power_of_two ~log =
primitive_root_of_unity (1 lsl log)
let build_array init next len =
let xi = ref init in
Array.init len (fun _ ->
let i = !xi in
xi := next !xi ;
i)
TODO return carray instead of array ?
computes [ | 1 ; x ; x² ; x³ ; ... ; xᵈ⁻¹ | ]
let powers d x = build_array Scalar.one Scalar.(mul x) d
let build_domain n = powers n (primitive_root_of_unity n)
let build_domain_power_of_two ~log =
let g = primitive_root_of_unity_power_of_two ~log in
powers (1 lsl log) g
|
1ba238f3eea51f6e87a8dc38293ebc0323c574532016d2bc92492cea5468835e | CarlWright/NGerlguten | template1.erl | -module (template1).
-include("../../include/eg.hrl").
-export ([on_instanciation/1, box/3, tag_map/4, handler/5]).
on_instanciation(Env ) ->
FilePart = atom_to_list(?MODULE),
FileName = "../test/template testing/" ++ FilePart ++ ".tem",
Env2 = Env#env{template = ?MODULE},
V = eg_xml_lite:parse_file(FileName),
[{pi, _},{xml,{templates,[],[A]}}] = V,
select the template that matches the 2nd half of the module name
{Env3, BoxRecords} = boxParse(Env2, Boxes), % tear off Box Definitions for a template
Env4 = loadBoxRecords(Env3,FilePart,BoxRecords),
{ box , BoxList , Objects } = BoxDef , % repeat for each box definition in the template
[ { Name , Value } | MoreValues ] = BoxList , % repeat for each value of a box record
Env4.
Parse out the descriptions of the boxes with their tags
boxParse(Env, [BoxDef|MoreBoxes]) ->
Record = #box{},
{box,BoxItem,Objects} = BoxDef,
BoxName = getBoxName(BoxItem),
objectParse(Env, Objects, BoxName),
Record2 = setBoxFields(Record,BoxItem),
boxParse(Env, MoreBoxes, [Record2]).
%% parse out the values for the Box record and return a box record
boxParse(Env,[],Records) ->
{Env, Records};
boxParse(Env, [BoxFields|MoreFields],Records) ->
Record = #box{},
{box,BoxItem,Objects} = BoxFields,
BoxName = getBoxName(BoxItem),
Env2 = objectParse(Env, Objects, BoxName),
Record2 = setBoxFields(Record,BoxItem),
boxParse(Env2, MoreFields, Records ++ [Record2]).
%% parse out each attribute & value for the box
setBoxFields(Record, []) ->
Record;
setBoxFields(Record, [Field|MoreFields]) ->
{Name,Value} = Field,
Record2 = setBoxFields(Record,Name, Value),
setBoxFields( Record2, MoreFields).
%% set the attributes of the box record
setBoxFields(Record,Name, Value ) ->
_RecordOut = case Name of
"bg" -> Record#box{bg = list_to_atom(Value)};
"grid" -> Record#box{ grid = list_to_atom(Value)};
"continue" -> Record#box{ continue = list_to_atom(Value)};
"lines" -> Record#box{ lines = list_to_integer(Value)};
"fontSize" -> Record#box{ fontSize = list_to_integer(Value)};
"width" -> Record#box{ width = list_to_integer(Value)};
"name" -> Record#box{ name = list_to_atom(Value)};
"x" -> Record#box{ x = list_to_integer(Value)};
"y" -> Record#box{ y = list_to_integer(Value)};
"free" -> Record#box{ free = list_to_integer(Value)};
"leading" -> Record#box{ leading = list_to_integer(Value)}
end.
%% get the box name out of the box list
getBoxName(BoxItem) ->
[{"name", BoxName}] = lists:filter(fun(X) -> case catch({"name", Name} = X ) of
{'EXIT',Why} -> false;
_ -> true end
end, BoxItem),
BoxName.
%% load boxes into the dict of the env ... key = {template_atom, box_name}
loadBoxRecords(Env,Template,BoxRecords) ->
Dict = Env#env.dict,
DictNew = loadBoxRecords(Dict, Env, Env#env.template, BoxRecords),
Env#env{dict = DictNew}.
loadBoxRecords(Dict, _, _, []) ->
Dict;
loadBoxRecords(Dict, Env, Tmplt,[Rec|MoreRecs]) ->
Key = {Tmplt, Rec#box.name},
Dict2 = dict:store(Key, Rec, Dict),
loadBoxRecords(Dict2, Env, Tmplt, MoreRecs).
Parse out the descriptions of the boxes with their tags
objectParse(Env, [], BoxName) ->
Env;
objectParse(Env, [ObjDef|MoreObjs], BoxName) ->
Record = #object{},
{obj,ObjList,Tags} = ObjDef,
Record2 = setObjFields(Record,ObjList),
Env2 = tagParse(Env, Tags, BoxName, Record2#object.name),
Env3 = putObjectRecord(Env2, Record2, BoxName, Record2#object.name),
objectParse(Env3, MoreObjs, BoxName).
%% parse out each attribute & value for the obj
setObjFields(Record, []) ->
Record;
setObjFields(Record, [Field|MoreFields]) ->
{Name,Value} = Field,
Record2 = setObjFields(Record,Name, Value),
setObjFields( Record2, MoreFields).
%% set the attributes of the obj record
setObjFields(Record,Name, Value ) ->
_RecordOut = case Name of
"name" -> Record#object{ name = list_to_atom(Value)};
"paraIndent" -> Record#object{ paraIndent = list_to_integer(Value)}
end.
%% put the object record in the Env dictionary. Key is {template-atom, Box-name, Object-name}
putObjectRecord(Env, Record, BoxName, ObjName) ->
Dict = Env#env.dict,
Key = {Env#env.template, BoxName, ObjName},
DictNew = dict:store(Key, Record, Dict),
Env#env{dict = DictNew}.
Parse out the descriptions of the boxes with their tags
tagParse(Env, [], BoxName, ObjectName) ->
Env;
tagParse(Env, [TagDef|MoreTags], BoxName, ObjectName) ->
Record = #tagMap{},
{tag, TagList, _} = TagDef,
Record2 = setTagFields(Record,TagList),
Env2 = putTagRecord(Env, Record2, BoxName, ObjectName),
tagParse(Env2, MoreTags, BoxName, ObjectName).
parse out each attribute & value for the tqag
setTagFields(Record, []) ->
Record;
setTagFields(Record, [Field|MoreFields]) ->
{Name,Value} = Field,
Record2 = setTagFields(Record,Name, Value),
setTagFields( Record2, MoreFields).
%% set the attributes of the tag record
setTagFields(Record,Name, Value ) ->
_RecordOut = case Name of
"name" -> Record#tagMap{ name = list_to_atom(Value)};
"font" -> Record#tagMap{ font = Value};
"color" -> Record#tagMap{ color = list_to_atom(Value)};
"break" -> Record#tagMap{ break = list_to_atom(Value)};
"voff" -> Record#tagMap{ voff = list_to_integer(Value)};
"size" -> Record#tagMap{ size = list_to_integer(Value)}
end.
%% put the object record in the Env dictionary. Key is {template-atom, Box-name, Object-name, Tag-name}
putTagRecord(Env, Record, BoxName, ObjName) ->
Dict = Env#env.dict,
Key = {Env#env.template, BoxName, ObjName, Record#tagMap.name},
DictNew = dict:store(Key, Record, Dict),
Env#env{dict = DictNew}.
box(Env, Template, Box) ->
Dict = Env#env.dict,
dict:fetch({Template, Box}, Dict).
tag_map(Env, Template, Box, Object) ->
Dict = Env#env.dict,
AccOut = dict:fold(fun(Key, Value, Acc) ->
case catch( {Template, Box, Object, Tag} = Key) of
{'EXIT', Why} -> Acc;
_ -> Acc ++ Value
end
end, [],Dict).
handler(Box, TagMap, Args, Data, Env) ->
case Box#box.bg of
default -> eg_block:inner_block(Env#env.pdf, Data,
Box#box.x, Box#box.y, Box#box.width, Box#box.fontSize,
Box#box.leading, Box#box.lines, Box#box.justify, TagMap);
_ -> eg_block:colored_inner_block(Env#env.pdf, Box#box.bg, Data,
Box#box.x, Box#box.y, Box#box.width, Box#box.fontSize,
Box#box.leading, Box#box.lines, Box#box.justify, TagMap)
end,
Env.
| null | https://raw.githubusercontent.com/CarlWright/NGerlguten/3c87f2e3a44ae9069f9379933b99c0feb8262d66/lib/ng_examples/testing/template%20testing/template1.erl | erlang | tear off Box Definitions for a template
repeat for each box definition in the template
repeat for each value of a box record
parse out the values for the Box record and return a box record
parse out each attribute & value for the box
set the attributes of the box record
get the box name out of the box list
load boxes into the dict of the env ... key = {template_atom, box_name}
parse out each attribute & value for the obj
set the attributes of the obj record
put the object record in the Env dictionary. Key is {template-atom, Box-name, Object-name}
set the attributes of the tag record
put the object record in the Env dictionary. Key is {template-atom, Box-name, Object-name, Tag-name} | -module (template1).
-include("../../include/eg.hrl").
-export ([on_instanciation/1, box/3, tag_map/4, handler/5]).
on_instanciation(Env ) ->
FilePart = atom_to_list(?MODULE),
FileName = "../test/template testing/" ++ FilePart ++ ".tem",
Env2 = Env#env{template = ?MODULE},
V = eg_xml_lite:parse_file(FileName),
[{pi, _},{xml,{templates,[],[A]}}] = V,
select the template that matches the 2nd half of the module name
Env4 = loadBoxRecords(Env3,FilePart,BoxRecords),
Env4.
Parse out the descriptions of the boxes with their tags
boxParse(Env, [BoxDef|MoreBoxes]) ->
Record = #box{},
{box,BoxItem,Objects} = BoxDef,
BoxName = getBoxName(BoxItem),
objectParse(Env, Objects, BoxName),
Record2 = setBoxFields(Record,BoxItem),
boxParse(Env, MoreBoxes, [Record2]).
boxParse(Env,[],Records) ->
{Env, Records};
boxParse(Env, [BoxFields|MoreFields],Records) ->
Record = #box{},
{box,BoxItem,Objects} = BoxFields,
BoxName = getBoxName(BoxItem),
Env2 = objectParse(Env, Objects, BoxName),
Record2 = setBoxFields(Record,BoxItem),
boxParse(Env2, MoreFields, Records ++ [Record2]).
setBoxFields(Record, []) ->
Record;
setBoxFields(Record, [Field|MoreFields]) ->
{Name,Value} = Field,
Record2 = setBoxFields(Record,Name, Value),
setBoxFields( Record2, MoreFields).
setBoxFields(Record,Name, Value ) ->
_RecordOut = case Name of
"bg" -> Record#box{bg = list_to_atom(Value)};
"grid" -> Record#box{ grid = list_to_atom(Value)};
"continue" -> Record#box{ continue = list_to_atom(Value)};
"lines" -> Record#box{ lines = list_to_integer(Value)};
"fontSize" -> Record#box{ fontSize = list_to_integer(Value)};
"width" -> Record#box{ width = list_to_integer(Value)};
"name" -> Record#box{ name = list_to_atom(Value)};
"x" -> Record#box{ x = list_to_integer(Value)};
"y" -> Record#box{ y = list_to_integer(Value)};
"free" -> Record#box{ free = list_to_integer(Value)};
"leading" -> Record#box{ leading = list_to_integer(Value)}
end.
getBoxName(BoxItem) ->
[{"name", BoxName}] = lists:filter(fun(X) -> case catch({"name", Name} = X ) of
{'EXIT',Why} -> false;
_ -> true end
end, BoxItem),
BoxName.
loadBoxRecords(Env,Template,BoxRecords) ->
Dict = Env#env.dict,
DictNew = loadBoxRecords(Dict, Env, Env#env.template, BoxRecords),
Env#env{dict = DictNew}.
loadBoxRecords(Dict, _, _, []) ->
Dict;
loadBoxRecords(Dict, Env, Tmplt,[Rec|MoreRecs]) ->
Key = {Tmplt, Rec#box.name},
Dict2 = dict:store(Key, Rec, Dict),
loadBoxRecords(Dict2, Env, Tmplt, MoreRecs).
Parse out the descriptions of the boxes with their tags
objectParse(Env, [], BoxName) ->
Env;
objectParse(Env, [ObjDef|MoreObjs], BoxName) ->
Record = #object{},
{obj,ObjList,Tags} = ObjDef,
Record2 = setObjFields(Record,ObjList),
Env2 = tagParse(Env, Tags, BoxName, Record2#object.name),
Env3 = putObjectRecord(Env2, Record2, BoxName, Record2#object.name),
objectParse(Env3, MoreObjs, BoxName).
setObjFields(Record, []) ->
Record;
setObjFields(Record, [Field|MoreFields]) ->
{Name,Value} = Field,
Record2 = setObjFields(Record,Name, Value),
setObjFields( Record2, MoreFields).
setObjFields(Record,Name, Value ) ->
_RecordOut = case Name of
"name" -> Record#object{ name = list_to_atom(Value)};
"paraIndent" -> Record#object{ paraIndent = list_to_integer(Value)}
end.
putObjectRecord(Env, Record, BoxName, ObjName) ->
Dict = Env#env.dict,
Key = {Env#env.template, BoxName, ObjName},
DictNew = dict:store(Key, Record, Dict),
Env#env{dict = DictNew}.
Parse out the descriptions of the boxes with their tags
tagParse(Env, [], BoxName, ObjectName) ->
Env;
tagParse(Env, [TagDef|MoreTags], BoxName, ObjectName) ->
Record = #tagMap{},
{tag, TagList, _} = TagDef,
Record2 = setTagFields(Record,TagList),
Env2 = putTagRecord(Env, Record2, BoxName, ObjectName),
tagParse(Env2, MoreTags, BoxName, ObjectName).
parse out each attribute & value for the tqag
setTagFields(Record, []) ->
Record;
setTagFields(Record, [Field|MoreFields]) ->
{Name,Value} = Field,
Record2 = setTagFields(Record,Name, Value),
setTagFields( Record2, MoreFields).
setTagFields(Record,Name, Value ) ->
_RecordOut = case Name of
"name" -> Record#tagMap{ name = list_to_atom(Value)};
"font" -> Record#tagMap{ font = Value};
"color" -> Record#tagMap{ color = list_to_atom(Value)};
"break" -> Record#tagMap{ break = list_to_atom(Value)};
"voff" -> Record#tagMap{ voff = list_to_integer(Value)};
"size" -> Record#tagMap{ size = list_to_integer(Value)}
end.
putTagRecord(Env, Record, BoxName, ObjName) ->
Dict = Env#env.dict,
Key = {Env#env.template, BoxName, ObjName, Record#tagMap.name},
DictNew = dict:store(Key, Record, Dict),
Env#env{dict = DictNew}.
box(Env, Template, Box) ->
Dict = Env#env.dict,
dict:fetch({Template, Box}, Dict).
tag_map(Env, Template, Box, Object) ->
Dict = Env#env.dict,
AccOut = dict:fold(fun(Key, Value, Acc) ->
case catch( {Template, Box, Object, Tag} = Key) of
{'EXIT', Why} -> Acc;
_ -> Acc ++ Value
end
end, [],Dict).
handler(Box, TagMap, Args, Data, Env) ->
case Box#box.bg of
default -> eg_block:inner_block(Env#env.pdf, Data,
Box#box.x, Box#box.y, Box#box.width, Box#box.fontSize,
Box#box.leading, Box#box.lines, Box#box.justify, TagMap);
_ -> eg_block:colored_inner_block(Env#env.pdf, Box#box.bg, Data,
Box#box.x, Box#box.y, Box#box.width, Box#box.fontSize,
Box#box.leading, Box#box.lines, Box#box.justify, TagMap)
end,
Env.
|
dd7c56b91409f0a22bfbf157d2bfbe85db803ea63ea0bea09570362c33a8a265 | ghollisjr/cl-ana | histogram.lisp | cl - ana is a Common Lisp data analysis library .
Copyright 2013 , 2014
;;;;
This file is part of cl - ana .
;;;;
;;;; cl-ana is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
;;;; (at your option) any later version.
;;;;
;;;; cl-ana is distributed in the hope that it will be useful, but
;;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;;; General Public License for more details.
;;;;
You should have received a copy of the GNU General Public License
;;;; along with cl-ana. If not, see </>.
;;;;
You may contact ( me ! ) via email at
;;;;
(in-package :cl-ana.serialization)
(defparameter *histogram-data-path* "data")
(defparameter *histogram-bin-spec-path* "bin-specs")
(defun ->double-float (x)
(float x 0d0))
(defun write-histogram (histogram file hdf-path)
"Writes histogram to file. Supports histogram count values with
errors as well as simple numerical values.
Note that this function assumes that either all the dimensions have
names or none of them do."
(hdf-mkgroup file hdf-path)
(flet ((subpath (path)
(concatenate 'string
hdf-path
"/"
path)))
(let* ((raw-data (hist-bin-values histogram))
(errors? (typep (first (first raw-data))
'err-num))
(data (if (not errors?)
raw-data
(mapcar (lambda (datum)
(destructuring-bind (count &rest xs) datum
(list* (err-num-value count)
(err-num-error count)
xs)))
raw-data)))
(data-names-specs
;; had to change this to double-float to allow for
;; normalized histograms etc.
(append (if errors?
(list (cons "count" :double)
(cons "count-error" :double))
(list (cons "count" :double)))
(loop
for i from 0
for n in (hist-dim-names histogram)
collect (cons (if n
n
(with-output-to-string (s)
(format s "x~a" i)))
:double))))
(data-table-path
(subpath *histogram-data-path*))
(data-table (create-hdf-table
file data-table-path data-names-specs))
(data-field-symbols (table-field-symbols data-table))
(hist-dim-specs
(let ((result (hist-dim-specs histogram)))
(loop
for plist in result
for i from 0
do (when (not (getf plist :name))
(setf (getf plist :name)
(with-output-to-string (s)
(format s "x~a" i)))))
result))
(bin-spec-table-path (subpath *histogram-bin-spec-path*))
(max-string-length
(loop
for plist in hist-dim-specs
maximizing (length (getf plist :name))))
(bin-spec-names-specs
(list (cons "name" (list :array :char max-string-length))
(cons "name-length" :int)
(cons "nbins" :int)
(cons "low" :double)
(cons "high" :double)))
(bin-spec-table (create-hdf-table
file bin-spec-table-path
bin-spec-names-specs)))
;; write data table
(loop
for datum in data
do (progn
(loop
for i from 0
for field in datum
for sym in data-field-symbols
do (table-set-field data-table sym
(->double-float field)))
(table-commit-row data-table)))
(table-close data-table)
;; write bin-spec table
;; fix plists
(loop
for plist in hist-dim-specs
for i from 0
do (when (not (getf plist :name))
(setf (getf plist :name)
(with-output-to-string (s)
(format s "x~a" i)))))
(loop
for plist in hist-dim-specs
do (progn
(table-push-fields bin-spec-table
(|name| (getf plist :name))
(|name-length| (length (getf plist :name)))
(|nbins| (getf plist :nbins))
(|low| (->double-float (getf plist :low)))
(|high| (->double-float (getf plist :high))))))
(table-close bin-spec-table))))
;; utility function
(defun h5tget-member-name-as-lisp-string (hdf-type i)
(let* ((name (hdf5:h5tget-member-name hdf-type i))
(lisp-name (cffi:foreign-string-to-lisp name)))
(cffi:foreign-free name)
lisp-name))
new version which uses raw HDF5 functions
(defun read-histogram (file hdf-path &optional (type :sparse))
"Reads a histogram from an hdf-table with file and path.
type can be either :contiguous or :sparse for contiguous-histogram and
sparse-histogram respectively."
(flet ((subpath (path)
(concatenate 'string
hdf-path
"/"
path)))
(let* ((binspec-path
(subpath *histogram-bin-spec-path*))
(binspec-dataset
(hdf5:h5dopen2 file binspec-path hdf5:+H5P-DEFAULT+))
(binspec-datatype
(hdf5:h5dget-type binspec-dataset))
(binspec-dataspace
(hdf5:h5dget-space binspec-dataset))
(data-path
(subpath *histogram-data-path*))
(data-dataset
(hdf5:h5dopen2 file data-path hdf5:+H5P-DEFAULT+))
(data-datatype
(hdf5:h5dget-type data-dataset))
(data-dataspace
(hdf5:h5dget-space data-dataset))
binspec-chunk-size
nrows
ndims
binspec-row-size
binspec-buffer-size
binspecs
data-chunk-size
data-row-size
data-buffer-size
memspace
n-count-vars
hist)
(with-foreign-objects ((binspec-dataset-dims 'hdf5:hsize-t)
(binspec-chunk-dims 'hdf5:hsize-t)
(binspec-name-dims 'hdf5:hsize-t)
(data-dataset-dims 'hdf5:hsize-t)
(data-chunk-dims 'hdf5:hsize-t)
(memspace-dims 'hdf5:hsize-t)
(memspace-maxdims 'hdf5:hsize-t))
(let ((create-plist
(hdf5:h5dget-create-plist binspec-dataset)))
(hdf5:h5pget-chunk create-plist 1 binspec-chunk-dims))
(setf binspec-chunk-size
(mem-aref binspec-chunk-dims 'hdf5:hsize-t))
(hdf5:h5sget-simple-extent-dims binspec-dataspace
binspec-dataset-dims
(null-pointer))
(setf ndims
(mem-aref binspec-dataset-dims 'hdf5:hsize-t))
(hdf5:h5tget-array-dims2
(hdf5:h5tget-member-type binspec-datatype
0)
binspec-name-dims)
(setf binspec-row-size
(hdf5:h5tget-size binspec-datatype))
(setf binspec-buffer-size
(* binspec-chunk-size binspec-row-size))
(with-foreign-object (buffer :char binspec-buffer-size)
(loop
for chunk-index from 0
while (< (* chunk-index binspec-buffer-size)
ndims)
do
(let ((remaining-rows
(- ndims
(* chunk-index binspec-chunk-size))))
(if (< remaining-rows binspec-chunk-size)
(setf (mem-aref memspace-dims 'hdf5:hsize-t 0)
remaining-rows)
(setf (mem-aref memspace-dims 'hdf5:hsize-t 0)
binspec-chunk-size)))
(setf (mem-aref memspace-maxdims 'hdf5:hsize-t)
(mem-aref memspace-dims 'hdf5:hsize-t))
(with-foreign-objects ((start 'hdf5:hsize-t)
(stride 'hdf5:hsize-t)
(cnt 'hdf5:hsize-t)
(blck 'hdf5:hsize-t))
(setf (mem-aref start 'hdf5:hsize-t)
(* chunk-index
binspec-chunk-size))
(setf (mem-aref stride 'hdf5:hsize-t)
1)
(setf (mem-aref cnt 'hdf5:hsize-t)
1)
(setf (mem-aref blck 'hdf5:hsize-t)
(mem-aref memspace-dims 'hdf5:hsize-t))
(hdf5:h5sselect-hyperslab binspec-dataspace
:H5S-SELECT-SET
start
stride
cnt
blck)
(setf memspace
(hdf5:h5screate-simple 1 memspace-dims memspace-maxdims))
(hdf5:h5dread binspec-dataset
binspec-datatype
memspace
binspec-dataspace
hdf5:+H5P-DEFAULT+
buffer)
(loop
for i from 0 below (mem-aref memspace-dims 'hdf5:hsize-t)
do (let* ((buffer-index
(+ (* i binspec-row-size)
(* binspec-chunk-size chunk-index)))
(name-length
(mem-aref
(mem-aptr buffer :char
(+ (hdf5:h5tget-member-offset binspec-datatype
1)
buffer-index))
:int))
(name
(let ((result
(make-string name-length)))
(loop
for j below name-length
do
(setf (aref result j)
(int-char
(mem-aref
buffer :char
(+ (hdf5:h5tget-member-offset
binspec-datatype 0)
buffer-index
j)))))
result))
(nbins
(mem-aref
(mem-aptr buffer :char
(+ (hdf5:h5tget-member-offset
binspec-datatype 2)
buffer-index))
:int))
(low
(mem-aref
(mem-aptr buffer :char
(+ (hdf5:h5tget-member-offset
binspec-datatype 3)
buffer-index))
:double))
(high
(mem-aref
(mem-aptr buffer :char
(+ (hdf5:h5tget-member-offset
binspec-datatype 4)
buffer-index))
:double)))
(push (list :name name
:nbins nbins
:low low
:high high)
binspecs)))
(setf binspecs
(nreverse binspecs))
(setf hist
(if (eq type :sparse)
(make-sparse-hist binspecs)
(make-contiguous-hist binspecs))))))
(let ((create-plist
(hdf5:h5dget-create-plist data-dataset)))
(hdf5:h5pget-chunk create-plist 1 data-chunk-dims))
(setf data-chunk-size
(mem-aref data-chunk-dims 'hdf5:hsize-t))
(hdf5:h5sget-simple-extent-dims data-dataspace
data-dataset-dims
(null-pointer))
(setf nrows
(mem-aref data-dataset-dims
'hdf5:hsize-t))
(let ((second-field-name
(h5tget-member-name-as-lisp-string data-datatype 1)))
(if (equal second-field-name
"count-error")
(progn
(setf n-count-vars 2)
(if (eq type :sparse)
(setf hist
(make-sparse-hist
binspecs
:empty-bin-value
(+- 0 0)
:default-increment (+- 1 1)))
(setf hist
(make-contiguous-hist
binspecs
:empty-bin-value
(+- 0 0)
:default-increment (+- 1 1)))))
(setf n-count-vars 1)))
(setf data-row-size
(hdf5:h5tget-size data-datatype))
(setf data-buffer-size
(* data-row-size
(mem-aref data-dataset-dims 'hdf5:hsize-t)))
(with-foreign-object (buffer :char data-buffer-size)
(setf (mem-aref memspace-dims 'hdf5:hsize-t)
(mem-aref data-dataset-dims 'hdf5:hsize-t))
(setf (mem-aref memspace-maxdims 'hdf5:hsize-t)
(mem-aref memspace-dims 'hdf5:hsize-t))
(with-foreign-objects ((start 'hdf5:hsize-t)
(stride 'hdf5:hsize-t)
(cnt 'hdf5:hsize-t)
(blck 'hdf5:hsize-t))
(setf (mem-aref start 'hdf5:hsize-t)
0)
(setf (mem-aref stride 'hdf5:hsize-t)
1)
(setf (mem-aref cnt 'hdf5:hsize-t)
1)
(setf (mem-aref blck 'hdf5:hsize-t)
(mem-aref memspace-dims 'hdf5:hsize-t))
(hdf5:h5sselect-hyperslab data-dataspace
:H5S-SELECT-SET
start
stride
cnt
blck)
(setf memspace
(hdf5:h5screate-simple 1
memspace-dims
memspace-maxdims))
(hdf5:h5dread data-dataset
data-datatype
memspace
data-dataspace
hdf5:+H5P-DEFAULT+
buffer)
(loop
for i below (mem-aref memspace-dims 'hdf5:hsize-t)
do
(let* ((buffer-index
(* i data-row-size))
(count
(case n-count-vars
(1 (mem-aref
(mem-aptr buffer
:char
(+ buffer-index
(hdf5:h5tget-member-offset
data-datatype 0)))
:double))
(2 (+- (mem-aref
(mem-aptr
buffer
:char
(+ buffer-index
(hdf5:h5tget-member-offset data-datatype 0)))
:double)
(mem-aref
(mem-aptr
buffer
:char
(+ buffer-index
(hdf5:h5tget-member-offset data-datatype 1)))
:double)))))
(xs
(loop
for dim from 0 below ndims
collecting
(mem-aref (mem-aptr buffer
:char
(+ buffer-index
(hdf5:h5tget-member-offset
data-datatype
(+ n-count-vars dim))))
:double))))
(hins hist
xs
count))))))
hist)))
;;;; This version will work again (with possible modification to
function arguments ) once the hdf - table library supports arbitrary
;;;; compound type structures and not just those produced by the C
;;;; compiler.
(defun old-read-histogram (file hdf-path &optional (type :sparse))
"Reads a histogram from an hdf-table with file and path.
type can be either :contiguous or :sparse for contiguous-histogram and
sparse-histogram respectively."
(flet ((subpath (path)
(concatenate 'string
hdf-path
"/"
path)))
(let* ((bin-spec-table
(open-hdf-table file
(subpath *histogram-bin-spec-path*)))
(bin-spec-table-field-names
(list "name" "name-length" "low" "high" "nbins"))
(hist-dim-specs
(let ((result ()))
(table-reduce bin-spec-table
bin-spec-table-field-names
(lambda (state name name-length low high nbins)
(push (list :name (char-vector->string name name-length)
:low low
:high high
:nbins nbins)
result)))
(nreverse result)))
(histogram
(cond
((equal type :contiguous)
(make-contiguous-hist hist-dim-specs))
((equal type :sparse)
(make-sparse-hist hist-dim-specs))
(t (error "Must specify :contiguous or :sparse for
type."))))
(data-table
(open-hdf-table file
(subpath *histogram-data-path*)))
(data-table-field-names
(table-field-names data-table)))
(if (equal (second data-table-field-names)
"count-error")
(table-reduce data-table
data-table-field-names
(lambda (state count count-error &rest xs)
(hist-insert histogram xs
(+- count count-error))))
(table-reduce data-table
data-table-field-names
(lambda (state count &rest xs)
(hist-insert histogram xs count))))
(table-close bin-spec-table)
(table-close data-table)
histogram)))
| null | https://raw.githubusercontent.com/ghollisjr/cl-ana/5cb4c0b0c9c4957452ad2a769d6ff9e8d5df0b10/serialization/histogram.lisp | lisp |
cl-ana is free software: you can redistribute it and/or modify it
(at your option) any later version.
cl-ana is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
along with cl-ana. If not, see </>.
had to change this to double-float to allow for
normalized histograms etc.
write data table
write bin-spec table
fix plists
utility function
This version will work again (with possible modification to
compound type structures and not just those produced by the C
compiler. | cl - ana is a Common Lisp data analysis library .
Copyright 2013 , 2014
This file is part of cl - ana .
under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
You may contact ( me ! ) via email at
(in-package :cl-ana.serialization)
(defparameter *histogram-data-path* "data")
(defparameter *histogram-bin-spec-path* "bin-specs")
(defun ->double-float (x)
(float x 0d0))
(defun write-histogram (histogram file hdf-path)
"Writes histogram to file. Supports histogram count values with
errors as well as simple numerical values.
Note that this function assumes that either all the dimensions have
names or none of them do."
(hdf-mkgroup file hdf-path)
(flet ((subpath (path)
(concatenate 'string
hdf-path
"/"
path)))
(let* ((raw-data (hist-bin-values histogram))
(errors? (typep (first (first raw-data))
'err-num))
(data (if (not errors?)
raw-data
(mapcar (lambda (datum)
(destructuring-bind (count &rest xs) datum
(list* (err-num-value count)
(err-num-error count)
xs)))
raw-data)))
(data-names-specs
(append (if errors?
(list (cons "count" :double)
(cons "count-error" :double))
(list (cons "count" :double)))
(loop
for i from 0
for n in (hist-dim-names histogram)
collect (cons (if n
n
(with-output-to-string (s)
(format s "x~a" i)))
:double))))
(data-table-path
(subpath *histogram-data-path*))
(data-table (create-hdf-table
file data-table-path data-names-specs))
(data-field-symbols (table-field-symbols data-table))
(hist-dim-specs
(let ((result (hist-dim-specs histogram)))
(loop
for plist in result
for i from 0
do (when (not (getf plist :name))
(setf (getf plist :name)
(with-output-to-string (s)
(format s "x~a" i)))))
result))
(bin-spec-table-path (subpath *histogram-bin-spec-path*))
(max-string-length
(loop
for plist in hist-dim-specs
maximizing (length (getf plist :name))))
(bin-spec-names-specs
(list (cons "name" (list :array :char max-string-length))
(cons "name-length" :int)
(cons "nbins" :int)
(cons "low" :double)
(cons "high" :double)))
(bin-spec-table (create-hdf-table
file bin-spec-table-path
bin-spec-names-specs)))
(loop
for datum in data
do (progn
(loop
for i from 0
for field in datum
for sym in data-field-symbols
do (table-set-field data-table sym
(->double-float field)))
(table-commit-row data-table)))
(table-close data-table)
(loop
for plist in hist-dim-specs
for i from 0
do (when (not (getf plist :name))
(setf (getf plist :name)
(with-output-to-string (s)
(format s "x~a" i)))))
(loop
for plist in hist-dim-specs
do (progn
(table-push-fields bin-spec-table
(|name| (getf plist :name))
(|name-length| (length (getf plist :name)))
(|nbins| (getf plist :nbins))
(|low| (->double-float (getf plist :low)))
(|high| (->double-float (getf plist :high))))))
(table-close bin-spec-table))))
(defun h5tget-member-name-as-lisp-string (hdf-type i)
(let* ((name (hdf5:h5tget-member-name hdf-type i))
(lisp-name (cffi:foreign-string-to-lisp name)))
(cffi:foreign-free name)
lisp-name))
new version which uses raw HDF5 functions
(defun read-histogram (file hdf-path &optional (type :sparse))
"Reads a histogram from an hdf-table with file and path.
type can be either :contiguous or :sparse for contiguous-histogram and
sparse-histogram respectively."
(flet ((subpath (path)
(concatenate 'string
hdf-path
"/"
path)))
(let* ((binspec-path
(subpath *histogram-bin-spec-path*))
(binspec-dataset
(hdf5:h5dopen2 file binspec-path hdf5:+H5P-DEFAULT+))
(binspec-datatype
(hdf5:h5dget-type binspec-dataset))
(binspec-dataspace
(hdf5:h5dget-space binspec-dataset))
(data-path
(subpath *histogram-data-path*))
(data-dataset
(hdf5:h5dopen2 file data-path hdf5:+H5P-DEFAULT+))
(data-datatype
(hdf5:h5dget-type data-dataset))
(data-dataspace
(hdf5:h5dget-space data-dataset))
binspec-chunk-size
nrows
ndims
binspec-row-size
binspec-buffer-size
binspecs
data-chunk-size
data-row-size
data-buffer-size
memspace
n-count-vars
hist)
(with-foreign-objects ((binspec-dataset-dims 'hdf5:hsize-t)
(binspec-chunk-dims 'hdf5:hsize-t)
(binspec-name-dims 'hdf5:hsize-t)
(data-dataset-dims 'hdf5:hsize-t)
(data-chunk-dims 'hdf5:hsize-t)
(memspace-dims 'hdf5:hsize-t)
(memspace-maxdims 'hdf5:hsize-t))
(let ((create-plist
(hdf5:h5dget-create-plist binspec-dataset)))
(hdf5:h5pget-chunk create-plist 1 binspec-chunk-dims))
(setf binspec-chunk-size
(mem-aref binspec-chunk-dims 'hdf5:hsize-t))
(hdf5:h5sget-simple-extent-dims binspec-dataspace
binspec-dataset-dims
(null-pointer))
(setf ndims
(mem-aref binspec-dataset-dims 'hdf5:hsize-t))
(hdf5:h5tget-array-dims2
(hdf5:h5tget-member-type binspec-datatype
0)
binspec-name-dims)
(setf binspec-row-size
(hdf5:h5tget-size binspec-datatype))
(setf binspec-buffer-size
(* binspec-chunk-size binspec-row-size))
(with-foreign-object (buffer :char binspec-buffer-size)
(loop
for chunk-index from 0
while (< (* chunk-index binspec-buffer-size)
ndims)
do
(let ((remaining-rows
(- ndims
(* chunk-index binspec-chunk-size))))
(if (< remaining-rows binspec-chunk-size)
(setf (mem-aref memspace-dims 'hdf5:hsize-t 0)
remaining-rows)
(setf (mem-aref memspace-dims 'hdf5:hsize-t 0)
binspec-chunk-size)))
(setf (mem-aref memspace-maxdims 'hdf5:hsize-t)
(mem-aref memspace-dims 'hdf5:hsize-t))
(with-foreign-objects ((start 'hdf5:hsize-t)
(stride 'hdf5:hsize-t)
(cnt 'hdf5:hsize-t)
(blck 'hdf5:hsize-t))
(setf (mem-aref start 'hdf5:hsize-t)
(* chunk-index
binspec-chunk-size))
(setf (mem-aref stride 'hdf5:hsize-t)
1)
(setf (mem-aref cnt 'hdf5:hsize-t)
1)
(setf (mem-aref blck 'hdf5:hsize-t)
(mem-aref memspace-dims 'hdf5:hsize-t))
(hdf5:h5sselect-hyperslab binspec-dataspace
:H5S-SELECT-SET
start
stride
cnt
blck)
(setf memspace
(hdf5:h5screate-simple 1 memspace-dims memspace-maxdims))
(hdf5:h5dread binspec-dataset
binspec-datatype
memspace
binspec-dataspace
hdf5:+H5P-DEFAULT+
buffer)
(loop
for i from 0 below (mem-aref memspace-dims 'hdf5:hsize-t)
do (let* ((buffer-index
(+ (* i binspec-row-size)
(* binspec-chunk-size chunk-index)))
(name-length
(mem-aref
(mem-aptr buffer :char
(+ (hdf5:h5tget-member-offset binspec-datatype
1)
buffer-index))
:int))
(name
(let ((result
(make-string name-length)))
(loop
for j below name-length
do
(setf (aref result j)
(int-char
(mem-aref
buffer :char
(+ (hdf5:h5tget-member-offset
binspec-datatype 0)
buffer-index
j)))))
result))
(nbins
(mem-aref
(mem-aptr buffer :char
(+ (hdf5:h5tget-member-offset
binspec-datatype 2)
buffer-index))
:int))
(low
(mem-aref
(mem-aptr buffer :char
(+ (hdf5:h5tget-member-offset
binspec-datatype 3)
buffer-index))
:double))
(high
(mem-aref
(mem-aptr buffer :char
(+ (hdf5:h5tget-member-offset
binspec-datatype 4)
buffer-index))
:double)))
(push (list :name name
:nbins nbins
:low low
:high high)
binspecs)))
(setf binspecs
(nreverse binspecs))
(setf hist
(if (eq type :sparse)
(make-sparse-hist binspecs)
(make-contiguous-hist binspecs))))))
(let ((create-plist
(hdf5:h5dget-create-plist data-dataset)))
(hdf5:h5pget-chunk create-plist 1 data-chunk-dims))
(setf data-chunk-size
(mem-aref data-chunk-dims 'hdf5:hsize-t))
(hdf5:h5sget-simple-extent-dims data-dataspace
data-dataset-dims
(null-pointer))
(setf nrows
(mem-aref data-dataset-dims
'hdf5:hsize-t))
(let ((second-field-name
(h5tget-member-name-as-lisp-string data-datatype 1)))
(if (equal second-field-name
"count-error")
(progn
(setf n-count-vars 2)
(if (eq type :sparse)
(setf hist
(make-sparse-hist
binspecs
:empty-bin-value
(+- 0 0)
:default-increment (+- 1 1)))
(setf hist
(make-contiguous-hist
binspecs
:empty-bin-value
(+- 0 0)
:default-increment (+- 1 1)))))
(setf n-count-vars 1)))
(setf data-row-size
(hdf5:h5tget-size data-datatype))
(setf data-buffer-size
(* data-row-size
(mem-aref data-dataset-dims 'hdf5:hsize-t)))
(with-foreign-object (buffer :char data-buffer-size)
(setf (mem-aref memspace-dims 'hdf5:hsize-t)
(mem-aref data-dataset-dims 'hdf5:hsize-t))
(setf (mem-aref memspace-maxdims 'hdf5:hsize-t)
(mem-aref memspace-dims 'hdf5:hsize-t))
(with-foreign-objects ((start 'hdf5:hsize-t)
(stride 'hdf5:hsize-t)
(cnt 'hdf5:hsize-t)
(blck 'hdf5:hsize-t))
(setf (mem-aref start 'hdf5:hsize-t)
0)
(setf (mem-aref stride 'hdf5:hsize-t)
1)
(setf (mem-aref cnt 'hdf5:hsize-t)
1)
(setf (mem-aref blck 'hdf5:hsize-t)
(mem-aref memspace-dims 'hdf5:hsize-t))
(hdf5:h5sselect-hyperslab data-dataspace
:H5S-SELECT-SET
start
stride
cnt
blck)
(setf memspace
(hdf5:h5screate-simple 1
memspace-dims
memspace-maxdims))
(hdf5:h5dread data-dataset
data-datatype
memspace
data-dataspace
hdf5:+H5P-DEFAULT+
buffer)
(loop
for i below (mem-aref memspace-dims 'hdf5:hsize-t)
do
(let* ((buffer-index
(* i data-row-size))
(count
(case n-count-vars
(1 (mem-aref
(mem-aptr buffer
:char
(+ buffer-index
(hdf5:h5tget-member-offset
data-datatype 0)))
:double))
(2 (+- (mem-aref
(mem-aptr
buffer
:char
(+ buffer-index
(hdf5:h5tget-member-offset data-datatype 0)))
:double)
(mem-aref
(mem-aptr
buffer
:char
(+ buffer-index
(hdf5:h5tget-member-offset data-datatype 1)))
:double)))))
(xs
(loop
for dim from 0 below ndims
collecting
(mem-aref (mem-aptr buffer
:char
(+ buffer-index
(hdf5:h5tget-member-offset
data-datatype
(+ n-count-vars dim))))
:double))))
(hins hist
xs
count))))))
hist)))
function arguments ) once the hdf - table library supports arbitrary
(defun old-read-histogram (file hdf-path &optional (type :sparse))
"Reads a histogram from an hdf-table with file and path.
type can be either :contiguous or :sparse for contiguous-histogram and
sparse-histogram respectively."
(flet ((subpath (path)
(concatenate 'string
hdf-path
"/"
path)))
(let* ((bin-spec-table
(open-hdf-table file
(subpath *histogram-bin-spec-path*)))
(bin-spec-table-field-names
(list "name" "name-length" "low" "high" "nbins"))
(hist-dim-specs
(let ((result ()))
(table-reduce bin-spec-table
bin-spec-table-field-names
(lambda (state name name-length low high nbins)
(push (list :name (char-vector->string name name-length)
:low low
:high high
:nbins nbins)
result)))
(nreverse result)))
(histogram
(cond
((equal type :contiguous)
(make-contiguous-hist hist-dim-specs))
((equal type :sparse)
(make-sparse-hist hist-dim-specs))
(t (error "Must specify :contiguous or :sparse for
type."))))
(data-table
(open-hdf-table file
(subpath *histogram-data-path*)))
(data-table-field-names
(table-field-names data-table)))
(if (equal (second data-table-field-names)
"count-error")
(table-reduce data-table
data-table-field-names
(lambda (state count count-error &rest xs)
(hist-insert histogram xs
(+- count count-error))))
(table-reduce data-table
data-table-field-names
(lambda (state count &rest xs)
(hist-insert histogram xs count))))
(table-close bin-spec-table)
(table-close data-table)
histogram)))
|
e4e5131319101cce18cdfb8b452595246519784002492fd5cca27d9a14b7f6cb | Lupino/haskell-periodic | FuncStat.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
module Periodic.Server.FuncStat
( FuncStat (..)
, funcStat
, FuncStatList
) where
import qualified Data.ByteString.Char8 as B (intercalate, pack)
import Data.Byteable
import Data.IOMap (IOMap)
import Data.Int (Int64)
import Periodic.Types (FuncName (..))
data FuncStat = FuncStat
{ sSchedAt :: Int64
, sWorker :: Int64
, sJob :: Int64
, sRunning :: Int64
, sLocked :: Int64
, sFuncName :: FuncName
, sBroadcast :: Bool
}
instance Byteable FuncStat where
toBytes FuncStat{..} = B.intercalate ","
[ unFN sFuncName
, B.pack $ show sWorker
, B.pack $ show sJob
, B.pack $ show sRunning
, B.pack $ show sLocked
, B.pack $ show sSchedAt
]
type FuncStatList = IOMap FuncName FuncStat
funcStat :: FuncName -> FuncStat
funcStat sFuncName = FuncStat
{ sSchedAt = 0
, sWorker = 0
, sJob = 0
, sRunning = 0
, sLocked = 0
, sBroadcast = False
, ..
}
| null | https://raw.githubusercontent.com/Lupino/haskell-periodic/cb8be30a37400c1fa3f2bebafb2b6ebc165bd634/periodic-server/src/Periodic/Server/FuncStat.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE RecordWildCards #
module Periodic.Server.FuncStat
( FuncStat (..)
, funcStat
, FuncStatList
) where
import qualified Data.ByteString.Char8 as B (intercalate, pack)
import Data.Byteable
import Data.IOMap (IOMap)
import Data.Int (Int64)
import Periodic.Types (FuncName (..))
data FuncStat = FuncStat
{ sSchedAt :: Int64
, sWorker :: Int64
, sJob :: Int64
, sRunning :: Int64
, sLocked :: Int64
, sFuncName :: FuncName
, sBroadcast :: Bool
}
instance Byteable FuncStat where
toBytes FuncStat{..} = B.intercalate ","
[ unFN sFuncName
, B.pack $ show sWorker
, B.pack $ show sJob
, B.pack $ show sRunning
, B.pack $ show sLocked
, B.pack $ show sSchedAt
]
type FuncStatList = IOMap FuncName FuncStat
funcStat :: FuncName -> FuncStat
funcStat sFuncName = FuncStat
{ sSchedAt = 0
, sWorker = 0
, sJob = 0
, sRunning = 0
, sLocked = 0
, sBroadcast = False
, ..
}
|
adeefa13e08ce4ad06127288ddb584a0c30efaca559b0a18c7dd625d686c8139 | eshamster/watson | import.lisp | (defpackage :watson/t/definer/import
(:use #:cl
#:rove
#:watson/definer/import)
(:import-from #:watson/env/environment
#:with-cloned-wenvironment
#:wsymbol-import
#:wenv-import-body-generators
#:intern.wat)
(:import-from #:watson/env/reserved-word
#:func
#:|func|
#:|import|
#:memory
#:|memory|
#:|param|)
(:import-from #:watson/env/type
#:i32
#:|i32|))
(in-package :watson/t/definer/import)
(deftest defimport.wat
(let ((tests `((:name "import function"
:init ,(lambda ()
(defimport.wat fuga fn.hoge (func ((i32) (i32)))))
:expect (|import| "fn" "hoge"
(|func| $fuga (|param| |i32|) (|param| |i32|))))
(:name "import memory"
:init ,(lambda ()
(defimport.wat m js.mem (memory 1)))
:expect (|import| "js" "mem" (|memory| $m 1))))))
(dolist (tt tests)
(destructuring-bind (&key name init expect) tt
(with-cloned-wenvironment
(testing name
(funcall init)
(let ((imports (wenv-import-body-generators *package*)))
(ok (= (length imports) 1))
(ok (equalp (funcall (car imports))
expect)))))))))
| null | https://raw.githubusercontent.com/eshamster/watson/0525f4a657298cec74121162c3cd3dec953c7a25/t/definer/import.lisp | lisp | (defpackage :watson/t/definer/import
(:use #:cl
#:rove
#:watson/definer/import)
(:import-from #:watson/env/environment
#:with-cloned-wenvironment
#:wsymbol-import
#:wenv-import-body-generators
#:intern.wat)
(:import-from #:watson/env/reserved-word
#:func
#:|func|
#:|import|
#:memory
#:|memory|
#:|param|)
(:import-from #:watson/env/type
#:i32
#:|i32|))
(in-package :watson/t/definer/import)
(deftest defimport.wat
(let ((tests `((:name "import function"
:init ,(lambda ()
(defimport.wat fuga fn.hoge (func ((i32) (i32)))))
:expect (|import| "fn" "hoge"
(|func| $fuga (|param| |i32|) (|param| |i32|))))
(:name "import memory"
:init ,(lambda ()
(defimport.wat m js.mem (memory 1)))
:expect (|import| "js" "mem" (|memory| $m 1))))))
(dolist (tt tests)
(destructuring-bind (&key name init expect) tt
(with-cloned-wenvironment
(testing name
(funcall init)
(let ((imports (wenv-import-body-generators *package*)))
(ok (= (length imports) 1))
(ok (equalp (funcall (car imports))
expect)))))))))
| |
1860295c79ccf5027ce7ae29d07c12e1be37b8674978b22bce71136c84aa2484 | replikativ/filesync-replikativ | core.clj | (ns filesync-replikativ.core
(:gen-class)
(:require [clojure.core.async :as async :refer [chan timeout]]
[filesync-replikativ.filesystem :refer :all]
[superv.async :refer [<? <?? go-loop-try S]]
[clj-ipfs-api.core :as ipfs]
[konserve
[core :as k]
[filestore :refer [new-fs-store]]]
[replikativ
[peer :refer [client-peer]]
[stage :refer [connect! create-stage!]]]
[replikativ.crdt.cdvcs
[realize :as r]
[stage :as cs]]))
1 . list all files
;; how to deal with special files? folder/symlinks etc.?
2 . calculate reasonable delta
3 . store delta
4 . restore delta(s ) into separate folder
(defn -main [config-path]
(let [{:keys [sync-path store-path user cdvcs-id remotes
blob-backend] :as config}
(read-string (slurp config-path))
_ (prn "Syncing folder with config:" config)
_ (def store (<?? S (new-fs-store store-path)))
_ (def peer (<?? S (client-peer S store)))
_ (def stage (<?? S (create-stage! user peer)))
_ (<?? S (cs/create-cdvcs! stage :id cdvcs-id))
c (chan)]
(when (= blob-backend :ipfs-block)
(ipfs/setup!))
(def sync-in-loop (r/stream-into-identity! stage [user cdvcs-id]
(eval-fs-fns blob-backend store)
sync-path
;; do not re-sync on startup
;; :applied-log [sync-path :in-loop]
))
(doseq [r remotes] (connect! stage r))
(def sync-out-loop
(go-loop-try S
[before (or (<? S (k/get-in store [[sync-path :stored]]))
{})]
(<? S (timeout 10000))
TODO let 's try to wait if data is currently being written
;; we randomize, so we do not get in lock-step with some application
;; this should ensure liveness
(if (> (- (.getTime (java.util.Date.))
(.getTime (last-modified-time sync-path)))
(rand-int 5000))
(recur (try
(let [after (list-dir sync-path)]
(let [txs (->> (delta before after)
(add-blobs-to-deltas blob-backend)
(relative-paths sync-path))]
(when (not (empty? txs))
(prn "New txs:" txs)
(<? S (cs/transact! stage [user cdvcs-id] txs))
(<? S (k/assoc-in store [[sync-path :stored]] after))))
after
)
(catch Exception e
(prn "Retry after exception during sync:" e)
before)))
(recur before))))
HACK block main thread
(<?? S c)))
(comment
(-main "resources/example-config.edn")
(list-dir "/var/tmp/input")
(get-in @stage ["mail:" #uuid "34db9ec4-82bf-4c61-8e2a-a86294f0e6d4" :state])
(let [{:keys [commit-graph heads]}
(get-in @stage ["mail:" #uuid "34db9ec4-82bf-4c61-8e2a-a86294f0e6d4" :state])]
(<?? (r/commit-history-values store commit-graph (first heads))))
)
| null | https://raw.githubusercontent.com/replikativ/filesync-replikativ/68ef904d2eb0918dfb4a05bcad17497a02cf7541/src/filesync_replikativ/core.clj | clojure | how to deal with special files? folder/symlinks etc.?
do not re-sync on startup
:applied-log [sync-path :in-loop]
we randomize, so we do not get in lock-step with some application
this should ensure liveness | (ns filesync-replikativ.core
(:gen-class)
(:require [clojure.core.async :as async :refer [chan timeout]]
[filesync-replikativ.filesystem :refer :all]
[superv.async :refer [<? <?? go-loop-try S]]
[clj-ipfs-api.core :as ipfs]
[konserve
[core :as k]
[filestore :refer [new-fs-store]]]
[replikativ
[peer :refer [client-peer]]
[stage :refer [connect! create-stage!]]]
[replikativ.crdt.cdvcs
[realize :as r]
[stage :as cs]]))
1 . list all files
2 . calculate reasonable delta
3 . store delta
4 . restore delta(s ) into separate folder
(defn -main [config-path]
(let [{:keys [sync-path store-path user cdvcs-id remotes
blob-backend] :as config}
(read-string (slurp config-path))
_ (prn "Syncing folder with config:" config)
_ (def store (<?? S (new-fs-store store-path)))
_ (def peer (<?? S (client-peer S store)))
_ (def stage (<?? S (create-stage! user peer)))
_ (<?? S (cs/create-cdvcs! stage :id cdvcs-id))
c (chan)]
(when (= blob-backend :ipfs-block)
(ipfs/setup!))
(def sync-in-loop (r/stream-into-identity! stage [user cdvcs-id]
(eval-fs-fns blob-backend store)
sync-path
))
(doseq [r remotes] (connect! stage r))
(def sync-out-loop
(go-loop-try S
[before (or (<? S (k/get-in store [[sync-path :stored]]))
{})]
(<? S (timeout 10000))
TODO let 's try to wait if data is currently being written
(if (> (- (.getTime (java.util.Date.))
(.getTime (last-modified-time sync-path)))
(rand-int 5000))
(recur (try
(let [after (list-dir sync-path)]
(let [txs (->> (delta before after)
(add-blobs-to-deltas blob-backend)
(relative-paths sync-path))]
(when (not (empty? txs))
(prn "New txs:" txs)
(<? S (cs/transact! stage [user cdvcs-id] txs))
(<? S (k/assoc-in store [[sync-path :stored]] after))))
after
)
(catch Exception e
(prn "Retry after exception during sync:" e)
before)))
(recur before))))
HACK block main thread
(<?? S c)))
(comment
(-main "resources/example-config.edn")
(list-dir "/var/tmp/input")
(get-in @stage ["mail:" #uuid "34db9ec4-82bf-4c61-8e2a-a86294f0e6d4" :state])
(let [{:keys [commit-graph heads]}
(get-in @stage ["mail:" #uuid "34db9ec4-82bf-4c61-8e2a-a86294f0e6d4" :state])]
(<?? (r/commit-history-values store commit-graph (first heads))))
)
|
65086c2e3e6364aa9b8dc082e1adb51e55dffcc9c95b25cf9a6d22fc9d64be13 | roddyyaga/finch | load.ml | open Jingoo
open Core
let split_front_matter s =
let s = String.strip s ^ "\n" in
let front_matter_start_opt = String.substr_index ~pattern:"---\n" s in
match front_matter_start_opt with
| None -> (None, s)
| Some fm_start -> (
let frontmatter_end_opt = String.substr_index ~pattern:"\n---\n" s in
match frontmatter_end_opt with
| Some fm_end ->
let frontmatter = String.slice s (fm_start + 4) (fm_end + 1) in
let content = String.slice s (fm_end + 5) 0 in
(Some frontmatter, content)
| None -> failwith "Frontmatter start with no corresponding end" )
let frontmatter_of_string yaml =
match Yaml.of_string_exn yaml with
| `O pairs -> pairs
| _ -> failwith "Frontmatter must be YAML object"
let get_string frontmatter k =
List.Assoc.find frontmatter k ~equal:String.equal
|> Option.map ~f:(function
| `String v -> v
| other ->
Printf.failwithf "'%s' must have string value in frontmatter, got %s"
k (Yaml.to_string_exn other) ())
type data_file = { yaml: string option; markdown: string; file: string }
let data root file =
let qualified_file = Filename.concat root file in
let _, extension = Filename.split_extension file in
match extension with
| Some "yml" | Some "yaml" ->
let yaml = In_channel.read_all qualified_file in
{ yaml = Some yaml; markdown = ""; file }
| _ ->
let yaml, markdown =
split_front_matter (In_channel.read_all qualified_file)
in
{ yaml; markdown; file }
type layout = {
frontmatter: (string * Yaml.value) list option;
template: Jg_template2.Loaded.t;
}
let layout_cache = Hashtbl.create (module String)
let layout ~env file =
Hashtbl.find_or_add layout_cache file ~default:(fun () ->
let frontmatter, body = split_front_matter (In_channel.read_all file) in
let frontmatter = Option.map frontmatter ~f:frontmatter_of_string in
{ frontmatter; template = Jg_template2.Loaded.from_string ~env body })
| null | https://raw.githubusercontent.com/roddyyaga/finch/685b661b987c7b57fe07e1e67b0ce4f688d87d67/lib/load.ml | ocaml | open Jingoo
open Core
let split_front_matter s =
let s = String.strip s ^ "\n" in
let front_matter_start_opt = String.substr_index ~pattern:"---\n" s in
match front_matter_start_opt with
| None -> (None, s)
| Some fm_start -> (
let frontmatter_end_opt = String.substr_index ~pattern:"\n---\n" s in
match frontmatter_end_opt with
| Some fm_end ->
let frontmatter = String.slice s (fm_start + 4) (fm_end + 1) in
let content = String.slice s (fm_end + 5) 0 in
(Some frontmatter, content)
| None -> failwith "Frontmatter start with no corresponding end" )
let frontmatter_of_string yaml =
match Yaml.of_string_exn yaml with
| `O pairs -> pairs
| _ -> failwith "Frontmatter must be YAML object"
let get_string frontmatter k =
List.Assoc.find frontmatter k ~equal:String.equal
|> Option.map ~f:(function
| `String v -> v
| other ->
Printf.failwithf "'%s' must have string value in frontmatter, got %s"
k (Yaml.to_string_exn other) ())
type data_file = { yaml: string option; markdown: string; file: string }
let data root file =
let qualified_file = Filename.concat root file in
let _, extension = Filename.split_extension file in
match extension with
| Some "yml" | Some "yaml" ->
let yaml = In_channel.read_all qualified_file in
{ yaml = Some yaml; markdown = ""; file }
| _ ->
let yaml, markdown =
split_front_matter (In_channel.read_all qualified_file)
in
{ yaml; markdown; file }
type layout = {
frontmatter: (string * Yaml.value) list option;
template: Jg_template2.Loaded.t;
}
let layout_cache = Hashtbl.create (module String)
let layout ~env file =
Hashtbl.find_or_add layout_cache file ~default:(fun () ->
let frontmatter, body = split_front_matter (In_channel.read_all file) in
let frontmatter = Option.map frontmatter ~f:frontmatter_of_string in
{ frontmatter; template = Jg_template2.Loaded.from_string ~env body })
| |
5d5517c8400647ec803c3b75e873230afc66063cfd37a0141f931378edf0f02b | bryal/carth | GetConfig.hs | # LANGUAGE TupleSections , TemplateHaskell , RankNTypes #
| Read all the different kinds of configurtion options for Carth . Command line options , config
-- files, environment variables, etc.
module GetConfig (getConfig, Conf(..)) where
import System.Console.GetOpt
import System.Environment
import System.Exit
import System.FilePath
import Data.List
import Data.Foldable
import Data.Function
import Control.Monad
import Control . Monad . Except
import Conf
import Prebaked
getConfig :: IO Conf
getConfig = do
as <- getArgs
let subCompile a = a == "c" || a == "compile"
let subRun a = a == "r" || a == "run"
case as of
a : as' | subCompile a -> compileCfg as'
| subRun a -> runCfg as'
a : _ | a == "-h" || a == "--help" -> do
putStrLn usageSubs
exitFailure
["help"] -> do
putStrLn usageSubs
exitFailure
"help" : a : _ | subCompile a -> usageCompile
| subRun a -> usageRun
"version" : _ -> printVersion >> exitSuccess
a : _ -> do
putStrLn ("Error: `" ++ a ++ "` is not a valid subcommand\n")
putStrLn usageSubs
exitFailure
[] -> do
putStrLn "Error: No subcommand given\n"
putStrLn usageSubs
exitFailure
usageSubs :: String
usageSubs = unlines
[ "Usage: carth SUBCOMMAND ..."
, ""
, "Available subcommands are:"
, " c, compile Compile a source file"
, " r, run JIT run a source file"
, " version Show version information"
, ""
, "See `carth help SUBCOMMAND` for help on a specific subcommand"
]
compileCfg :: [String] -> IO Conf
compileCfg args = do
(fs, inf) <- get args compileOpts usageCompile
let outf = replaceExtension inf "bin"
when (inf == outf) $ do
putStrLn
$ ("Error: Input file \"" ++ inf ++ "\" ")
++ "would be overwritten by the generated executable"
exitFailure
let defaultCfg = defaultCompileConfig inf
cfg <- case foldlM (&) defaultCfg fs of
Left e -> putStrLn e >> usageCompile
Right cfg -> pure cfg
pure (CompileConf cfg)
runCfg :: [String] -> IO Conf
runCfg args = do
(fs, inf) <- get args runOpts usageRun
let defaultCfg = defaultRunConfig inf
cfg <- case foldlM (&) defaultCfg fs of
Left e -> putStrLn e >> usageRun
Right cfg -> pure cfg
pure (RunConf cfg)
get
:: [String]
-> [OptDescr (cfg -> Either String cfg)]
-> (forall a . IO a)
-> IO ([cfg -> Either String cfg], FilePath)
get args opts usage = do
let (fs, extras, errs) = getOpt Permute opts args
unless (null errs) $ putStrLn (concat errs) *> usage
inf <- case extras of
[f] -> pure f
_ : es -> do
putStrLn ("Unexpected extra arguments: " ++ intercalate ", " es)
usage
[] -> putStrLn "Missing input source file" *> usage
pure (fs, inf)
usageCompile :: IO a
usageCompile = do
putStrLn $ unlines
[ "Carth compile"
, "Compile a Carth program to an executable"
, ""
, usageInfo "Usage: carth c [OPTIONS] SOURCE-FILE" compileOpts
]
exitFailure
usageRun :: IO a
usageRun = do
putStrLn $ unlines
[ "Carth run"
, "JIT run Carth program"
, ""
, usageInfo "Usage: carth r [OPTIONS] SOURCE-FILE" runOpts
]
exitFailure
compileOpts :: [OptDescr (CompileConfig -> Either String CompileConfig)]
compileOpts =
[ Option []
["cc"]
(ReqArg (\cc' c -> Right c { cCompiler = cc' }) "PROGRAM")
"C compiler to use when compiling C source & linking objects"
, Option []
["ld"]
(ReqArg (\ld' c -> Right c { cLinker = ld' }) "PROGRAM")
"Linker to use when linking objects, passed to C compiler via -fuse-ld=..."
, Option
[]
["backend"]
(ReqArg
(\bend c -> case bend of
"llvm" -> Right c { cBackend = BendLLVM }
"c" -> Right c { cBackend = BendC }
_ -> Left ("Undefined backend '" ++ bend ++ "'")
)
"BACKEND"
)
"Code generator backend (llvm, c)"
, Option ['o'] ["outfile"] (ReqArg (\f c -> Right c { cOutfile = f }) "FILE") "Output filepath"
, Option [] ["debug"] (NoArg (\c -> Right c { cDebug = True })) "Enable debugging"
, Option ['v'] ["verbose"] (NoArg (\c -> Right c { cVerbose = True })) "Verbose output"
]
runOpts :: [OptDescr (RunConfig -> Either String RunConfig)]
runOpts =
[ Option [] ["debug"] (NoArg (\c -> Right c { rDebug = True })) "Enable debugging"
, Option ['v'] ["verbose"] (NoArg (\c -> Right c { rVerbose = True })) "Verbose output"
]
printVersion :: IO ()
printVersion = do
let (major, minor, patch) = version
let versionStr = concat [show major, ".", show minor, ".", show patch]
putStrLn ("Carth " ++ versionStr)
version :: (Int, Int, Int)
version = $(readCompilerVersion)
| null | https://raw.githubusercontent.com/bryal/carth/8b11c27abe5d6db5501eebb826422aa2c73aacdb/app/GetConfig.hs | haskell | files, environment variables, etc. | # LANGUAGE TupleSections , TemplateHaskell , RankNTypes #
| Read all the different kinds of configurtion options for Carth . Command line options , config
module GetConfig (getConfig, Conf(..)) where
import System.Console.GetOpt
import System.Environment
import System.Exit
import System.FilePath
import Data.List
import Data.Foldable
import Data.Function
import Control.Monad
import Control . Monad . Except
import Conf
import Prebaked
getConfig :: IO Conf
getConfig = do
as <- getArgs
let subCompile a = a == "c" || a == "compile"
let subRun a = a == "r" || a == "run"
case as of
a : as' | subCompile a -> compileCfg as'
| subRun a -> runCfg as'
a : _ | a == "-h" || a == "--help" -> do
putStrLn usageSubs
exitFailure
["help"] -> do
putStrLn usageSubs
exitFailure
"help" : a : _ | subCompile a -> usageCompile
| subRun a -> usageRun
"version" : _ -> printVersion >> exitSuccess
a : _ -> do
putStrLn ("Error: `" ++ a ++ "` is not a valid subcommand\n")
putStrLn usageSubs
exitFailure
[] -> do
putStrLn "Error: No subcommand given\n"
putStrLn usageSubs
exitFailure
usageSubs :: String
usageSubs = unlines
[ "Usage: carth SUBCOMMAND ..."
, ""
, "Available subcommands are:"
, " c, compile Compile a source file"
, " r, run JIT run a source file"
, " version Show version information"
, ""
, "See `carth help SUBCOMMAND` for help on a specific subcommand"
]
compileCfg :: [String] -> IO Conf
compileCfg args = do
(fs, inf) <- get args compileOpts usageCompile
let outf = replaceExtension inf "bin"
when (inf == outf) $ do
putStrLn
$ ("Error: Input file \"" ++ inf ++ "\" ")
++ "would be overwritten by the generated executable"
exitFailure
let defaultCfg = defaultCompileConfig inf
cfg <- case foldlM (&) defaultCfg fs of
Left e -> putStrLn e >> usageCompile
Right cfg -> pure cfg
pure (CompileConf cfg)
runCfg :: [String] -> IO Conf
runCfg args = do
(fs, inf) <- get args runOpts usageRun
let defaultCfg = defaultRunConfig inf
cfg <- case foldlM (&) defaultCfg fs of
Left e -> putStrLn e >> usageRun
Right cfg -> pure cfg
pure (RunConf cfg)
get
:: [String]
-> [OptDescr (cfg -> Either String cfg)]
-> (forall a . IO a)
-> IO ([cfg -> Either String cfg], FilePath)
get args opts usage = do
let (fs, extras, errs) = getOpt Permute opts args
unless (null errs) $ putStrLn (concat errs) *> usage
inf <- case extras of
[f] -> pure f
_ : es -> do
putStrLn ("Unexpected extra arguments: " ++ intercalate ", " es)
usage
[] -> putStrLn "Missing input source file" *> usage
pure (fs, inf)
usageCompile :: IO a
usageCompile = do
putStrLn $ unlines
[ "Carth compile"
, "Compile a Carth program to an executable"
, ""
, usageInfo "Usage: carth c [OPTIONS] SOURCE-FILE" compileOpts
]
exitFailure
usageRun :: IO a
usageRun = do
putStrLn $ unlines
[ "Carth run"
, "JIT run Carth program"
, ""
, usageInfo "Usage: carth r [OPTIONS] SOURCE-FILE" runOpts
]
exitFailure
compileOpts :: [OptDescr (CompileConfig -> Either String CompileConfig)]
compileOpts =
[ Option []
["cc"]
(ReqArg (\cc' c -> Right c { cCompiler = cc' }) "PROGRAM")
"C compiler to use when compiling C source & linking objects"
, Option []
["ld"]
(ReqArg (\ld' c -> Right c { cLinker = ld' }) "PROGRAM")
"Linker to use when linking objects, passed to C compiler via -fuse-ld=..."
, Option
[]
["backend"]
(ReqArg
(\bend c -> case bend of
"llvm" -> Right c { cBackend = BendLLVM }
"c" -> Right c { cBackend = BendC }
_ -> Left ("Undefined backend '" ++ bend ++ "'")
)
"BACKEND"
)
"Code generator backend (llvm, c)"
, Option ['o'] ["outfile"] (ReqArg (\f c -> Right c { cOutfile = f }) "FILE") "Output filepath"
, Option [] ["debug"] (NoArg (\c -> Right c { cDebug = True })) "Enable debugging"
, Option ['v'] ["verbose"] (NoArg (\c -> Right c { cVerbose = True })) "Verbose output"
]
runOpts :: [OptDescr (RunConfig -> Either String RunConfig)]
runOpts =
[ Option [] ["debug"] (NoArg (\c -> Right c { rDebug = True })) "Enable debugging"
, Option ['v'] ["verbose"] (NoArg (\c -> Right c { rVerbose = True })) "Verbose output"
]
printVersion :: IO ()
printVersion = do
let (major, minor, patch) = version
let versionStr = concat [show major, ".", show minor, ".", show patch]
putStrLn ("Carth " ++ versionStr)
version :: (Int, Int, Int)
version = $(readCompilerVersion)
|
ac609fbb172bc65b2bc87ea7bcf43e026924ab846e35f591fccbcdbedd7f8e77 | bluelisp/hemlock | indent.lisp | ;;;; -*- Mode: Lisp; indent-tabs-mode: nil -*-
;;;
;;; **********************************************************************
This code was written as part of the CMU Common Lisp project at
Carnegie Mellon University , and has been placed in the public domain .
;;;
;;;
;;; **********************************************************************
;;;
Hemlock indentation commands
;;;
Written by and
;;;
(in-package :hemlock)
(defhvar "Spaces per Tab"
"The number of spaces a tab is equivalent to. NOTE: This is not incorporated
everywhere in Hemlock yet, so do not change it."
:value 8)
(defun indent-using-tabs (mark column)
"Inserts at mark a maximum number of tabs and a minimum number of spaces to
move mark to column. This assumes mark is at the beginning of a line."
(multiple-value-bind (tabs spaces) (floor column (value spaces-per-tab))
(dotimes (i tabs) (insert-character mark #\tab))
(dotimes (i spaces) (insert-character mark #\space))))
(defun indent-using-spaces (mark column)
"Inserts some spaces at MARK so that it moves to COLUMN. This assumes
mark is at the beginning of a line."
(insert-string mark (make-string column :initial-element #\space)))
(defhvar "Indent with Tabs"
"Function that takes a mark and a number of spaces and inserts tabs and spaces
to indent that number of spaces using \"Spaces per Tab\"."
:value t)
Note the name of this option has been chosen to be compatible with Emacs .
(define-file-option "indent-tabs-mode" (buffer value)
(let ((value (ignore-errors (let ((*read-eval* nil))
(read-from-string value)))))
(defhvar "Indent with Tabs" "override by file-option"
:buffer buffer
:value value)))
(defun indent-to-column (mark column)
"Insert white space at MARK so that it moves to COLUMN. This assumes mark is
at the beginning of a line. When 'indent-with-tabs is true it uses tabs a
maximum number of tabs and a minimum number os spaces to move mark to column,
otherwise spaces are used."
(if (value indent-with-tabs)
(indent-using-tabs mark column)
(indent-using-spaces mark column)))
(defun indent-to-tab-stop (mark)
(cond ((value indent-with-tabs)
(insert-character mark #\tab))
(t
(let ((tab-size (value spaces-per-tab)))
(indent-using-spaces mark (* (ceiling (1+ (mark-column mark))
tab-size)
tab-size))))))
(defhvar "Indent Function"
"Indentation function which is invoked by \"Indent\" command.
It takes a :left-inserting mark that may be moved."
:value #'indent-to-tab-stop)
(defun generic-indent (mark)
(let* ((line (mark-line mark))
(prev (do ((line (line-previous line) (line-previous line)))
((or (null line) (not (blank-line-p line))) line))))
(unless prev (editor-error))
(line-start mark prev)
(find-attribute mark :space #'zerop)
(let ((indentation (mark-column mark)))
(line-start mark line)
(delete-horizontal-space mark)
(indent-to-column mark indentation))))
(defcommand "Indent New Line" (p)
"Moves point to a new blank line and indents it.
Any whitespace before point is deleted. The value of \"Indent Function\"
is used for indentation unless there is a Fill Prefix, in which case it is
used. Any argument is passed onto \"New Line\"."
"Moves point to a new blank line and indents it.
Any whitespace before point is deleted. The value of \"Indent Function\"
is used for indentation unless there is a Fill Prefix, in which case it is
used. Any argument is passed onto \"New Line\"."
(let ((point (current-point))
(prefix (value fill-prefix)))
(delete-horizontal-space point)
(new-line-command p)
(if prefix
(insert-string point prefix)
(funcall (value indent-function) point))))
(defcommand "Indent" (p)
"Invokes function held by the Hemlock variable \"Indent Function\",
moving point past region if called with argument."
"Invokes function held by the Hemlock variable \"Indent Function\"
moving point past region if called with argument."
(let ((point (current-point)))
(with-mark ((mark point :left-inserting))
(cond ((or (not p) (zerop p))
(funcall (value indent-function) mark))
(t
(if (plusp p)
(unless (line-offset point (1- p))
(buffer-end point))
(unless (line-offset mark (1+ p))
(buffer-start mark)))
(indent-region-for-commands (region mark point))
(find-attribute (line-start point) :whitespace #'zerop))))))
(defcommand "Indent Region" (p)
"Invokes function held by Hemlock variable \"Indent Function\" on every
line between point and mark, inclusively."
"Invokes function held by Hemlock variable \"Indent Function\" on every
line between point and mark, inclusively."
(declare (ignore p))
(let* ((region (current-region)))
(with-mark ((start (region-start region) :left-inserting)
(end (region-end region) :left-inserting))
(indent-region-for-commands (region start end)))))
(defun indent-region-for-commands (region)
"Indents region undoably with INDENT-REGION."
(let* ((start (region-start region))
(end (region-end region))
(undo-region (copy-region (region (line-start start) (line-end end)))))
(indent-region region)
(make-region-undo :twiddle "Indent"
(region (line-start (copy-mark start :left-inserting))
(line-end (copy-mark end :right-inserting)))
undo-region)))
(defun indent-region (region)
"Invokes function held by Hemlock variable \"Indent Function\" on every
line of region."
(let ((indent-function (value indent-function)))
(with-mark ((start (region-start region) :left-inserting)
(end (region-end region)))
(line-start start)
(line-start end)
(loop (when (mark= start end)
(funcall indent-function start)
(return))
(funcall indent-function start)
(line-offset start 1 0)))))
(defcommand "Center Line" (p)
"Centers current line using \"Fill Column\". If an argument is supplied,
it is used instead of the \"Fill Column\"."
"Centers current line using fill-column."
(let* ((region (if (region-active-p)
(current-region)
(region (current-point) (current-point))))
(end (region-end region)))
(with-mark ((temp (region-start region) :left-inserting))
(loop
(when (mark> temp end) (return))
(delete-horizontal-space (line-end temp))
(delete-horizontal-space (line-start temp))
(let* ((len (line-length (mark-line temp)))
(spaces (- (or p (value fill-column)) len)))
(if (and (plusp spaces)
(not (zerop len)))
(indent-to-column temp (ceiling spaces 2)))
(unless (line-offset temp 1) (return))
(line-start temp))))))
(defcommand "Quote Tab" (p)
"Insert tab character."
"Insert tab character."
(if (and p (> p 1))
(insert-string (current-point) (make-string p :initial-element #\tab))
(insert-character (current-point) #\tab)))
(defcommand "Open Line" (p)
"Inserts a newline into the buffer without moving the point."
"Inserts a newline into the buffer without moving the point.
With argument, inserts p newlines."
(let ((point (current-point))
(count (if p p 1)))
(if (not (minusp count))
(dotimes (i count)
(insert-character point #\newline)
(mark-before point))
(editor-error))))
(defcommand "New Line" (p)
"Moves the point to a new blank line.
A newline is inserted if the next two lines are not already blank.
With an argument, repeats p times."
"Moves the point to a new blank line."
(let ((point (current-point))
(count (if p p 1)))
(if (not (minusp count))
(do* ((next (line-next (mark-line point))
(line-next (mark-line point)))
(i 1 (1+ i)))
((> i count))
(cond ((and (blank-after-p point)
next (blank-line-p next)
(let ((after (line-next next)))
(or (not after) (blank-line-p after))))
(line-start point next)
(let ((len (line-length next)))
(unless (zerop len)
(delete-characters point len))))
(t
(insert-character point #\newline))))
(editor-error))))
(defattribute "Space"
"This attribute is used by the indentation commands to determine which
characters are treated as space."
'(mod 2) 0)
(setf (character-attribute :space #\space) 1)
(setf (character-attribute :space #\tab) 1)
(defun delete-horizontal-space (mark)
"Deletes all :space characters on either side of mark."
(with-mark ((start mark))
(reverse-find-attribute start :space #'zerop)
(find-attribute mark :space #'zerop)
(delete-region (region start mark))))
(defcommand "Delete Indentation" (p)
"Join current line with the previous one, deleting excess whitespace.
All whitespace is replaced with a single space, unless it is at the beginning
of a line, immmediately following a \"(\", or immediately preceding a \")\",
in which case the whitespace is merely deleted. If the preceeding character
is a sentence terminator, two spaces are left instead of one. If a prefix
argument is given, the following line is joined with the current line."
"Join current line with the previous one, deleting excess whitespace."
(with-mark ((m (current-point) :right-inserting))
(when p (line-offset m 1))
(line-start m)
(unless (delete-characters m -1) (editor-error "No previous line."))
(delete-horizontal-space m)
(let ((prev (previous-character m)))
(when (and prev (char/= prev #\newline))
(cond ((not (zerop (character-attribute :sentence-terminator prev)))
(insert-string m " "))
((not (or (eq (character-attribute :lisp-syntax prev) :open-paren)
(eq (character-attribute :lisp-syntax (next-character m))
:close-paren)))
(insert-character m #\space)))))))
(defcommand "Delete Horizontal Space" (p)
"Delete spaces and tabs surrounding the point."
"Delete spaces and tabs surrounding the point."
(declare (ignore p))
(delete-horizontal-space (current-point)))
(defcommand "Just One Space" (p)
"Leave one space.
Surrounding space is deleted, and then one space is inserted.
with prefix argument insert that number of spaces."
"Delete surrounding space and insert P spaces."
(let ((point (current-point)))
(delete-horizontal-space point)
(dotimes (i (or p 1)) (insert-character point #\space))))
(defcommand "Back to Indentation" (p)
"Move point to the first non-whitespace character on the line."
"Move point to the first non-whitespace character on the line."
(declare (ignore p))
(let ((point (current-point)))
(line-start point)
(find-attribute point :whitespace #'zerop)))
(defcommand "Indent Rigidly" (p)
"Indent the region rigidly by p spaces.
Each line in the region is moved p spaces to the right (left if p is
negative). When moving a line to the left, tabs are converted to spaces."
"Indent the region rigidly p spaces to the right (left if p is negative)."
(let ((p (or p (value spaces-per-tab)))
(region (current-region)))
(with-mark ((mark1 (region-start region) :left-inserting)
(mark2 (region-end region) :left-inserting))
(line-start mark1)
(line-start mark2)
(do ()
((mark= mark1 mark2))
(cond ((empty-line-p mark1))
((blank-after-p mark1)
(delete-characters mark1 (line-length (mark-line mark1))))
(t (find-attribute mark1 :whitespace #'zerop)
(let ((new-column (+ p (mark-column mark1))))
(delete-characters mark1 (- (mark-charpos mark1)))
(when (plusp new-column)
(indent-to-column mark1 new-column)))))
(line-offset mark1 1 0)))))
| null | https://raw.githubusercontent.com/bluelisp/hemlock/47e16ba731a0cf4ffd7fb2110e17c764ae757170/src/indent.lisp | lisp | -*- Mode: Lisp; indent-tabs-mode: nil -*-
**********************************************************************
**********************************************************************
| This code was written as part of the CMU Common Lisp project at
Carnegie Mellon University , and has been placed in the public domain .
Hemlock indentation commands
Written by and
(in-package :hemlock)
(defhvar "Spaces per Tab"
"The number of spaces a tab is equivalent to. NOTE: This is not incorporated
everywhere in Hemlock yet, so do not change it."
:value 8)
(defun indent-using-tabs (mark column)
"Inserts at mark a maximum number of tabs and a minimum number of spaces to
move mark to column. This assumes mark is at the beginning of a line."
(multiple-value-bind (tabs spaces) (floor column (value spaces-per-tab))
(dotimes (i tabs) (insert-character mark #\tab))
(dotimes (i spaces) (insert-character mark #\space))))
(defun indent-using-spaces (mark column)
"Inserts some spaces at MARK so that it moves to COLUMN. This assumes
mark is at the beginning of a line."
(insert-string mark (make-string column :initial-element #\space)))
(defhvar "Indent with Tabs"
"Function that takes a mark and a number of spaces and inserts tabs and spaces
to indent that number of spaces using \"Spaces per Tab\"."
:value t)
Note the name of this option has been chosen to be compatible with Emacs .
(define-file-option "indent-tabs-mode" (buffer value)
(let ((value (ignore-errors (let ((*read-eval* nil))
(read-from-string value)))))
(defhvar "Indent with Tabs" "override by file-option"
:buffer buffer
:value value)))
(defun indent-to-column (mark column)
"Insert white space at MARK so that it moves to COLUMN. This assumes mark is
at the beginning of a line. When 'indent-with-tabs is true it uses tabs a
maximum number of tabs and a minimum number os spaces to move mark to column,
otherwise spaces are used."
(if (value indent-with-tabs)
(indent-using-tabs mark column)
(indent-using-spaces mark column)))
(defun indent-to-tab-stop (mark)
(cond ((value indent-with-tabs)
(insert-character mark #\tab))
(t
(let ((tab-size (value spaces-per-tab)))
(indent-using-spaces mark (* (ceiling (1+ (mark-column mark))
tab-size)
tab-size))))))
(defhvar "Indent Function"
"Indentation function which is invoked by \"Indent\" command.
It takes a :left-inserting mark that may be moved."
:value #'indent-to-tab-stop)
(defun generic-indent (mark)
(let* ((line (mark-line mark))
(prev (do ((line (line-previous line) (line-previous line)))
((or (null line) (not (blank-line-p line))) line))))
(unless prev (editor-error))
(line-start mark prev)
(find-attribute mark :space #'zerop)
(let ((indentation (mark-column mark)))
(line-start mark line)
(delete-horizontal-space mark)
(indent-to-column mark indentation))))
(defcommand "Indent New Line" (p)
"Moves point to a new blank line and indents it.
Any whitespace before point is deleted. The value of \"Indent Function\"
is used for indentation unless there is a Fill Prefix, in which case it is
used. Any argument is passed onto \"New Line\"."
"Moves point to a new blank line and indents it.
Any whitespace before point is deleted. The value of \"Indent Function\"
is used for indentation unless there is a Fill Prefix, in which case it is
used. Any argument is passed onto \"New Line\"."
(let ((point (current-point))
(prefix (value fill-prefix)))
(delete-horizontal-space point)
(new-line-command p)
(if prefix
(insert-string point prefix)
(funcall (value indent-function) point))))
(defcommand "Indent" (p)
"Invokes function held by the Hemlock variable \"Indent Function\",
moving point past region if called with argument."
"Invokes function held by the Hemlock variable \"Indent Function\"
moving point past region if called with argument."
(let ((point (current-point)))
(with-mark ((mark point :left-inserting))
(cond ((or (not p) (zerop p))
(funcall (value indent-function) mark))
(t
(if (plusp p)
(unless (line-offset point (1- p))
(buffer-end point))
(unless (line-offset mark (1+ p))
(buffer-start mark)))
(indent-region-for-commands (region mark point))
(find-attribute (line-start point) :whitespace #'zerop))))))
(defcommand "Indent Region" (p)
"Invokes function held by Hemlock variable \"Indent Function\" on every
line between point and mark, inclusively."
"Invokes function held by Hemlock variable \"Indent Function\" on every
line between point and mark, inclusively."
(declare (ignore p))
(let* ((region (current-region)))
(with-mark ((start (region-start region) :left-inserting)
(end (region-end region) :left-inserting))
(indent-region-for-commands (region start end)))))
(defun indent-region-for-commands (region)
"Indents region undoably with INDENT-REGION."
(let* ((start (region-start region))
(end (region-end region))
(undo-region (copy-region (region (line-start start) (line-end end)))))
(indent-region region)
(make-region-undo :twiddle "Indent"
(region (line-start (copy-mark start :left-inserting))
(line-end (copy-mark end :right-inserting)))
undo-region)))
(defun indent-region (region)
"Invokes function held by Hemlock variable \"Indent Function\" on every
line of region."
(let ((indent-function (value indent-function)))
(with-mark ((start (region-start region) :left-inserting)
(end (region-end region)))
(line-start start)
(line-start end)
(loop (when (mark= start end)
(funcall indent-function start)
(return))
(funcall indent-function start)
(line-offset start 1 0)))))
(defcommand "Center Line" (p)
"Centers current line using \"Fill Column\". If an argument is supplied,
it is used instead of the \"Fill Column\"."
"Centers current line using fill-column."
(let* ((region (if (region-active-p)
(current-region)
(region (current-point) (current-point))))
(end (region-end region)))
(with-mark ((temp (region-start region) :left-inserting))
(loop
(when (mark> temp end) (return))
(delete-horizontal-space (line-end temp))
(delete-horizontal-space (line-start temp))
(let* ((len (line-length (mark-line temp)))
(spaces (- (or p (value fill-column)) len)))
(if (and (plusp spaces)
(not (zerop len)))
(indent-to-column temp (ceiling spaces 2)))
(unless (line-offset temp 1) (return))
(line-start temp))))))
(defcommand "Quote Tab" (p)
"Insert tab character."
"Insert tab character."
(if (and p (> p 1))
(insert-string (current-point) (make-string p :initial-element #\tab))
(insert-character (current-point) #\tab)))
(defcommand "Open Line" (p)
"Inserts a newline into the buffer without moving the point."
"Inserts a newline into the buffer without moving the point.
With argument, inserts p newlines."
(let ((point (current-point))
(count (if p p 1)))
(if (not (minusp count))
(dotimes (i count)
(insert-character point #\newline)
(mark-before point))
(editor-error))))
(defcommand "New Line" (p)
"Moves the point to a new blank line.
A newline is inserted if the next two lines are not already blank.
With an argument, repeats p times."
"Moves the point to a new blank line."
(let ((point (current-point))
(count (if p p 1)))
(if (not (minusp count))
(do* ((next (line-next (mark-line point))
(line-next (mark-line point)))
(i 1 (1+ i)))
((> i count))
(cond ((and (blank-after-p point)
next (blank-line-p next)
(let ((after (line-next next)))
(or (not after) (blank-line-p after))))
(line-start point next)
(let ((len (line-length next)))
(unless (zerop len)
(delete-characters point len))))
(t
(insert-character point #\newline))))
(editor-error))))
(defattribute "Space"
"This attribute is used by the indentation commands to determine which
characters are treated as space."
'(mod 2) 0)
(setf (character-attribute :space #\space) 1)
(setf (character-attribute :space #\tab) 1)
(defun delete-horizontal-space (mark)
"Deletes all :space characters on either side of mark."
(with-mark ((start mark))
(reverse-find-attribute start :space #'zerop)
(find-attribute mark :space #'zerop)
(delete-region (region start mark))))
(defcommand "Delete Indentation" (p)
"Join current line with the previous one, deleting excess whitespace.
All whitespace is replaced with a single space, unless it is at the beginning
of a line, immmediately following a \"(\", or immediately preceding a \")\",
in which case the whitespace is merely deleted. If the preceeding character
is a sentence terminator, two spaces are left instead of one. If a prefix
argument is given, the following line is joined with the current line."
"Join current line with the previous one, deleting excess whitespace."
(with-mark ((m (current-point) :right-inserting))
(when p (line-offset m 1))
(line-start m)
(unless (delete-characters m -1) (editor-error "No previous line."))
(delete-horizontal-space m)
(let ((prev (previous-character m)))
(when (and prev (char/= prev #\newline))
(cond ((not (zerop (character-attribute :sentence-terminator prev)))
(insert-string m " "))
((not (or (eq (character-attribute :lisp-syntax prev) :open-paren)
(eq (character-attribute :lisp-syntax (next-character m))
:close-paren)))
(insert-character m #\space)))))))
(defcommand "Delete Horizontal Space" (p)
"Delete spaces and tabs surrounding the point."
"Delete spaces and tabs surrounding the point."
(declare (ignore p))
(delete-horizontal-space (current-point)))
(defcommand "Just One Space" (p)
"Leave one space.
Surrounding space is deleted, and then one space is inserted.
with prefix argument insert that number of spaces."
"Delete surrounding space and insert P spaces."
(let ((point (current-point)))
(delete-horizontal-space point)
(dotimes (i (or p 1)) (insert-character point #\space))))
(defcommand "Back to Indentation" (p)
"Move point to the first non-whitespace character on the line."
"Move point to the first non-whitespace character on the line."
(declare (ignore p))
(let ((point (current-point)))
(line-start point)
(find-attribute point :whitespace #'zerop)))
(defcommand "Indent Rigidly" (p)
"Indent the region rigidly by p spaces.
Each line in the region is moved p spaces to the right (left if p is
negative). When moving a line to the left, tabs are converted to spaces."
"Indent the region rigidly p spaces to the right (left if p is negative)."
(let ((p (or p (value spaces-per-tab)))
(region (current-region)))
(with-mark ((mark1 (region-start region) :left-inserting)
(mark2 (region-end region) :left-inserting))
(line-start mark1)
(line-start mark2)
(do ()
((mark= mark1 mark2))
(cond ((empty-line-p mark1))
((blank-after-p mark1)
(delete-characters mark1 (line-length (mark-line mark1))))
(t (find-attribute mark1 :whitespace #'zerop)
(let ((new-column (+ p (mark-column mark1))))
(delete-characters mark1 (- (mark-charpos mark1)))
(when (plusp new-column)
(indent-to-column mark1 new-column)))))
(line-offset mark1 1 0)))))
|
d320ae318fb8e4e9f75418b366aa040928d992b7fcd927edfd5b976c5a52d0bd | mirage/irmin | type.ml |
* Copyright ( c ) 2013 - 2022 < >
*
* 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) 2013-2022 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.
*)
include Repr
module type Defaultable = sig
include S
val default : t
end
| null | https://raw.githubusercontent.com/mirage/irmin/abeee121a6db7b085b3c68af50ef24a8d8f9ed05/src/irmin/type.ml | ocaml |
* Copyright ( c ) 2013 - 2022 < >
*
* 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) 2013-2022 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.
*)
include Repr
module type Defaultable = sig
include S
val default : t
end
| |
a06604f4f974da0da36204620ff2f50b51df1c81cccb74c688d9feb2e48a50eb | danielsz/sente-system | server.clj | (ns example.server
"Official Sente reference example: server"
{:author "Peter Taoussanis (@ptaoussanis)"}
(:require
[ring.middleware.defaults]
[com.stuartsierra.component :as component]
[compojure.core :as comp :refer [routes GET POST]]
[compojure.route :as route]
[hiccup.core :as hiccup]
[clojure.core.async :as async :refer [<! <!! >! >!! put! chan go go-loop]]
[taoensso.timbre :as timbre :refer [tracef debugf infof warnf errorf]]
[taoensso.sente :as sente]))
;; (timbre/set-level! :trace) ; Uncomment for more logging
(reset! sente/debug-mode?_ true) ; Uncomment for extra debug info
;;;; Ring handlers
(defn landing-pg-handler [ring-req]
(hiccup/html
[:h1 "Sente reference example"]
[:p "An Ajax/WebSocket" [:strong " (random choice!)"] " has been configured for this example"]
[:hr]
[:p [:strong "Step 1: "] " try hitting the buttons:"]
[:p
[:button#btn1 {:type "button"} "chsk-send! (w/o reply)"]
[:button#btn2 {:type "button"} "chsk-send! (with reply)"]]
[:p
[:button#btn3 {:type "button"} "Test rapid server>user async pushes"]
[:button#btn4 {:type "button"} "Toggle server>user async broadcast push loop"]]
[:p
[:button#btn5 {:type "button"} "Disconnect"]
[:button#btn6 {:type "button"} "Reconnect"]]
;;
[:p [:strong "Step 2: "] " observe std-out (for server output) and below (for client output):"]
[:textarea#output {:style "width: 100%; height: 200px;"}]
;;
[:hr]
[:h2 "Step 3: try login with a user-id"]
[:p "The server can use this id to send events to *you* specifically."]
[:p
[:input#input-login {:type :text :placeholder "User-id"}]
[:button#btn-login {:type "button"} "Secure login!"]]
;;
[:hr]
[:h2 "Step 4: want to re-randomize Ajax/WebSocket connection type?"]
[:p "Hit your browser's reload/refresh button"]
[:script {:src "js/main.js"}] ; Include our cljs target
))
(defn login-handler
"Here's where you'll add your server-side login/auth procedure (Friend, etc.).
In our simplified example we'll just always successfully authenticate the user
with whatever user-id they provided in the auth request."
[ring-req]
(let [{:keys [session params]} ring-req
{:keys [user-id]} params]
(debugf "Login request: %s" params)
{:status 200 :session (assoc session :uid user-id)}))
(defn ring-routes
[_]
(routes
(GET "/" ring-req (landing-pg-handler ring-req))
(POST "/login" ring-req (login-handler ring-req))
Static files , notably public / main.js ( our cljs target )
(route/not-found "<h1>Page not found</h1>")))
;;;; Some server>user async push examples
(defn test-fast-server>user-pushes
"Quickly pushes 100 events to all connected users. Note that this'll be
fast+reliable even over Ajax!"
[{:keys [chsk-send! connected-uids]}]
(doseq [uid (:any @connected-uids)]
(doseq [i (range 100)]
(chsk-send! uid [:fast-push/is-fast (str "hello " i "!!")]))))
(defn start-example-broadcaster!
"As an example of server>user async pushes, setup a loop to broadcast an
event to all connected users every 10 seconds"
[{{:keys [chsk-send! connected-uids]} :sente :keys [broadcast-enabled?_]}]
(let [broadcast!
(fn [i]
(let [uids (:any @connected-uids)]
(debugf "Broadcasting server>user: %s uids" (count uids))
(doseq [uid uids]
(chsk-send! uid
[:some/broadcast
{:what-is-this "An async broadcast pushed from server"
:how-often "Every 10 seconds"
:to-whom uid
:i i}]))))]
(go-loop [i 0]
(<! (async/timeout 10000))
(when @broadcast-enabled?_ (broadcast! i))
(recur (inc i)))))
(defrecord ExampleBroadcaster [sente broadcast-enabled?_]
component/Lifecycle
(start [component]
(start-example-broadcaster! component)
component)
(stop [component]
component))
(defn new-example-broadcaster
[]
(map->ExampleBroadcaster {}))
;;;; Sente event handlers
(defmulti -event-msg-handler
"Multimethod to handle Sente `event-msg`s"
#(:id %2) ; Dispatch on event-id
)
(defn event-msg-handler
"Wraps `-event-msg-handler` with logging, error catching, etc."
[component]
(fn [ev-msg]
(-event-msg-handler component ev-msg) ; Handle event-msgs on a single thread
;; (future (-event-msg-handler component ev-msg)) ; Handle event-msgs on a thread pool
))
(defmethod -event-msg-handler
:default ; Default/fallback case (no other matching handler)
[component {:as ev-msg :keys [event id ?data ring-req ?reply-fn send-fn]}]
(let [session (:session ring-req)
uid (:uid session)]
(debugf "Unhandled event: %s" event)
(when ?reply-fn
(?reply-fn {:umatched-event-as-echoed-from-from-server event}))))
(defmethod -event-msg-handler :example/test-rapid-push
[component ev-msg] (test-fast-server>user-pushes component))
(defmethod -event-msg-handler :example/toggle-broadcast
[{:keys [broadcast-enabled?_]} {:as ev-msg :keys [?reply-fn]}]
(let [loop-enabled? (swap! broadcast-enabled?_ not)]
(?reply-fn loop-enabled?)))
;; TODO Add your (defmethod -event-msg-handler <event-id> [ev-msg] <body>)s here...
| null | https://raw.githubusercontent.com/danielsz/sente-system/e5dbe8549b6e6082591284699bca5779b3712f90/src/clj/example/server.clj | clojure | (timbre/set-level! :trace) ; Uncomment for more logging
Uncomment for extra debug info
Ring handlers
Include our cljs target
Some server>user async push examples
Sente event handlers
Dispatch on event-id
Handle event-msgs on a single thread
(future (-event-msg-handler component ev-msg)) ; Handle event-msgs on a thread pool
Default/fallback case (no other matching handler)
TODO Add your (defmethod -event-msg-handler <event-id> [ev-msg] <body>)s here... | (ns example.server
"Official Sente reference example: server"
{:author "Peter Taoussanis (@ptaoussanis)"}
(:require
[ring.middleware.defaults]
[com.stuartsierra.component :as component]
[compojure.core :as comp :refer [routes GET POST]]
[compojure.route :as route]
[hiccup.core :as hiccup]
[clojure.core.async :as async :refer [<! <!! >! >!! put! chan go go-loop]]
[taoensso.timbre :as timbre :refer [tracef debugf infof warnf errorf]]
[taoensso.sente :as sente]))
(defn landing-pg-handler [ring-req]
(hiccup/html
[:h1 "Sente reference example"]
[:p "An Ajax/WebSocket" [:strong " (random choice!)"] " has been configured for this example"]
[:hr]
[:p [:strong "Step 1: "] " try hitting the buttons:"]
[:p
[:button#btn1 {:type "button"} "chsk-send! (w/o reply)"]
[:button#btn2 {:type "button"} "chsk-send! (with reply)"]]
[:p
[:button#btn3 {:type "button"} "Test rapid server>user async pushes"]
[:button#btn4 {:type "button"} "Toggle server>user async broadcast push loop"]]
[:p
[:button#btn5 {:type "button"} "Disconnect"]
[:button#btn6 {:type "button"} "Reconnect"]]
[:p [:strong "Step 2: "] " observe std-out (for server output) and below (for client output):"]
[:textarea#output {:style "width: 100%; height: 200px;"}]
[:hr]
[:h2 "Step 3: try login with a user-id"]
[:p "The server can use this id to send events to *you* specifically."]
[:p
[:input#input-login {:type :text :placeholder "User-id"}]
[:button#btn-login {:type "button"} "Secure login!"]]
[:hr]
[:h2 "Step 4: want to re-randomize Ajax/WebSocket connection type?"]
[:p "Hit your browser's reload/refresh button"]
))
(defn login-handler
"Here's where you'll add your server-side login/auth procedure (Friend, etc.).
In our simplified example we'll just always successfully authenticate the user
with whatever user-id they provided in the auth request."
[ring-req]
(let [{:keys [session params]} ring-req
{:keys [user-id]} params]
(debugf "Login request: %s" params)
{:status 200 :session (assoc session :uid user-id)}))
(defn ring-routes
[_]
(routes
(GET "/" ring-req (landing-pg-handler ring-req))
(POST "/login" ring-req (login-handler ring-req))
Static files , notably public / main.js ( our cljs target )
(route/not-found "<h1>Page not found</h1>")))
(defn test-fast-server>user-pushes
"Quickly pushes 100 events to all connected users. Note that this'll be
fast+reliable even over Ajax!"
[{:keys [chsk-send! connected-uids]}]
(doseq [uid (:any @connected-uids)]
(doseq [i (range 100)]
(chsk-send! uid [:fast-push/is-fast (str "hello " i "!!")]))))
(defn start-example-broadcaster!
"As an example of server>user async pushes, setup a loop to broadcast an
event to all connected users every 10 seconds"
[{{:keys [chsk-send! connected-uids]} :sente :keys [broadcast-enabled?_]}]
(let [broadcast!
(fn [i]
(let [uids (:any @connected-uids)]
(debugf "Broadcasting server>user: %s uids" (count uids))
(doseq [uid uids]
(chsk-send! uid
[:some/broadcast
{:what-is-this "An async broadcast pushed from server"
:how-often "Every 10 seconds"
:to-whom uid
:i i}]))))]
(go-loop [i 0]
(<! (async/timeout 10000))
(when @broadcast-enabled?_ (broadcast! i))
(recur (inc i)))))
(defrecord ExampleBroadcaster [sente broadcast-enabled?_]
component/Lifecycle
(start [component]
(start-example-broadcaster! component)
component)
(stop [component]
component))
(defn new-example-broadcaster
[]
(map->ExampleBroadcaster {}))
(defmulti -event-msg-handler
"Multimethod to handle Sente `event-msg`s"
)
(defn event-msg-handler
"Wraps `-event-msg-handler` with logging, error catching, etc."
[component]
(fn [ev-msg]
))
(defmethod -event-msg-handler
[component {:as ev-msg :keys [event id ?data ring-req ?reply-fn send-fn]}]
(let [session (:session ring-req)
uid (:uid session)]
(debugf "Unhandled event: %s" event)
(when ?reply-fn
(?reply-fn {:umatched-event-as-echoed-from-from-server event}))))
(defmethod -event-msg-handler :example/test-rapid-push
[component ev-msg] (test-fast-server>user-pushes component))
(defmethod -event-msg-handler :example/toggle-broadcast
[{:keys [broadcast-enabled?_]} {:as ev-msg :keys [?reply-fn]}]
(let [loop-enabled? (swap! broadcast-enabled?_ not)]
(?reply-fn loop-enabled?)))
|
239fd85034f1d97fede903e44eada600342615a4f4cc321fdc5d878400f34718 | probprog/bopp | core.clj | (ns bopp.core
"User interface for BOPP"
(require [deodorant.core :as bo]
[bopp.program-transformations :as pt]
[bopp.helper-functions :refer [argmax]]
[bopp.error-handling :refer [changing-types?]]
[anglican.inference :refer [log-marginal infer]]
[anglican.state :refer [get-log-weight get-result]]
[anglican.trap :refer [primitive-procedure-cps]]
[anglican.ais]
[anglican.importance]))
(defn- get-result-vector [sample]
(into [] (get-result sample)))
(defmacro opt [& args]
(if (apply changing-types? args)
(throw (Exception. "Query contains distribution assignments to optimization variables that have different type (continuous, discrete)."))
`(with-meta
{:prior-query (pt/prior-query ~@args)
:acq-query (pt/acq-query ~@args)
:mmap-query (pt/mmap-query ~@args)
:ml2-query (pt/ml2-query ~@args)}
{:source '(~'opt ~@args)})))
(defmacro defopt
"Binds variable to a BOPP query. Synatx is the
same as Anglican's defquery, except that an
additional input is specified to dictate the
variables to be optimized.
Example:
(defopt opt-query
<docstring>
[y] [theta]
(let [a (sample (normal 0 10))
theta (sample (normal a 20))
b (sample (normal a (* theta theta)))]
(observe (normal (* a theta) (* b b)) y)
[a b]))
For more details please see the README and the
paper.
-bayesian-optimization-for-probabilistic-programs"
[name & args]
(let [[docstring source]
(if (string? (first args))
[(first args) (rest args)]
[(format "BOPP program '%s'" name) args])]
`(def ~(with-meta name {:doc docstring})
(opt ~@source))))
(defn- bo-target
"Calculates the value of a the BO target given a marginal query and a
point to evaluate. Target will typically be the log-marginal for
MMAP problems and (- (log-marginal samples)) for risk minimization.
However, also allows overide capabilities from different transformations
of the target (e.g. WASABI), to using completely different opt-sample-summarizers for
the sample populations (e.g. variance on the weights). Also provides
flexibility in the additional return values taken (e.g. get-result-vector
or get-predicts).
Inputs: marg-q = transformed marginal query
query-args = fixed arguments to the defopt (i.e. its first argument)
algorithm = inner inference algorithm to use
num-samples = number of samples to take in inner inference algorithm
inf-options = options to use in inner inferenec algorithm
output-extractor = extracts additional outputs from the inner query,
e.g get-result-vector or get-predicts
opt-bo-target-transformation = transformation function applied to the output of
the opt-sample-summarizer calculation.
opt-sample-summarizer = function used to calculate the desired untransformed target
from the samples.
f-theta-inf = Value of f-theta set to if evaluates as +/- infinity (sign is maintained)
Outputs: f-theta = Evaluated value as used for the bayes opt. Note that the bayes
opt always carries out maximization. Minimization is thus done
by maximiziation a function where f-theta = -target.
inner-outputs = additional outputs from the inner query."
[theta
marg-q
query-args
algorithm
num-samples
inf-options
opt-bo-target-transformation
opt-sample-summarizer
f-theta-inf
output-extractor]
(let [samples (take num-samples
(apply infer
algorithm
marg-q
(concat query-args theta)
inf-options))
f-theta (opt-bo-target-transformation (opt-sample-summarizer samples)) ;; Could be +-Infinity
f-theta (if (= f-theta (/ -1. 0))
(do (println "BOPP WARNING: Target evaluation has underflown!")
(- f-theta-inf))
(if (= f-theta (/ 1. 0))
(do (println "BOPP WARNING: Target evaluation has overflown!")
f-theta-inf)
f-theta))
outputs (map output-extractor samples)]
[f-theta outputs]))
(defn- distributed-aq-optimizer
"Performs parallelized calls of infer on an optimization query and takes
the best sample from any of the runs."
[acq-fn opt-query-args acq-q acq-opt-num-starts ais-num-steps ais-start-exponent ais-end-exponent]
(let [log-acq-fn (fn [theta & args]
(Math/log (apply acq-fn theta args)))
cpsd-acq-fn (fn [cont state & args]
(fn []
(cont (apply log-acq-fn args) state)))
outputs (pmap (fn [unused] (first (infer :ais
acq-q
(conj opt-query-args cpsd-acq-fn)
:number-of-steps ais-num-steps
:start-exponent ais-start-exponent
:end-exponent ais-end-exponent)))
(range acq-opt-num-starts))
log-weights (map get-log-weight outputs)
i-best (argmax log-weights)
best-output (get-result-vector (nth outputs i-best))]
best-output))
(defn doopt
"Calls BOPP on a target query as defined by defopt, returning a lazy
infinite sequence of increasingly optimal estimates.
For more details please see the README and the
paper.
-bayesian-optimization-for-probabilistic-programs
Input:
algorithm ... Inference algorithm
[:smc, :pcascade, :importance]
opt-query ... Query to be optimized, defined by defopt.
opt-query-args ... Arguments of opt-query.
num-samples ... Number of samples for constructing the estimator to be
optimized
Optional keyword arguments:
Speed option:
speed-option ... Set the default options to a set of pre-tuned values to
be able to switch between the different modes of running depending on
speed. Can be overriden by user post-hoc.
[:careful, :fast] (Default: :fast)
Bayesian optimization (BO) options:
bo-options ... look at documentation of Deodorant, this should be a map
with those options, i.e.:
{:initial-points <initial-points>
:num-scaling-thetas <num-scaling-thetas>
:num-initial-points <num-initial-points>
:cov-fn-form <cov-fn-form>
... etc.}
You only need to provide options whose defaults that you want to
override.
(Default:
if :speed-option is :careful
{:hmc-num-leapfrog-steps 5
:hmc-num-mcmc-steps 50
:hmc-num-opt-steps 15
:hmc-num-chains 8
:hmc-max-gps 50}
if :speed-option is :fast
{:hmc-num-leapfrog-steps 2
:hmc-num-mcmc-steps 20
:hmc-num-opt-steps 10
:hmc-num-chains 4
:hmc-max-gps 20})
Optimization options:
opt-type ... Optimization type. Use :custom to customize the
optimization; must provide opt-program-transformation,
opt-sample-summarizer, opt-bo-target-transformation in this case.
[:mmap, :ml2, :risk-minimization :custom] (Default: :mmap)
opt-program-transformation ... Custom program transformation for
optimization.
[nil, :mmap, :ml2] (Default: nil)
opt-sample-summarizer ... Custom sample summarizer for optimizer. Takes
in a sequence of Anglican samples, outputs target scalar for BO.
(Default: nil; Suggested: anglican.inference/log-marginal)
opt-bo-target-transformation ... Custom BO target transformation for
optimization. Takes in BO target, outputs alternative target.
(Default: nil; Suggested: identity, - for minimization)
Inference options:
inf-options ... Options to be passed to the inference scheme. Note
that default options are merged as with bo-options and so these with
overwrite the inference algorithm defaults if not set
(Default:
if algorithm is :pcascade
{:number-of-threads (int (* 2 num-samples))
:number-of-particles num-samples}
otherwise
{:number-of-particles num-samples})
Acquisition optimization/AIS options:
acq-opt-num-starts ... Number of parallel optimizations to prevent
multimodality. (Default: 4 if :speed-option is :fast 16 if :careful)
ais-num-steps ... Number of MCMC steps performed during acquisition
function optimization.
(Default: (max 100 (int (* 2 (/ num-samples acq-opt-num-starts)))))
ais-start-exponent ... Start exponent for annealed importance sampling
(Default: 0.001)
ais-end-exponent ... End exponent for annealed importance sampling
(Default: 10)
Other options
output-extractor ... Takes in an Anglican sample, returns its output.
(Default: #(into [] (anglican.state/get-result sample));
Alternatives: anglican.state/get-result, anglican.state/get-predicts)
f-theta-inf ... Replace -Infinity during BO by this. (Default: -1e5)
Output:
Lazy list of increasingly optimal (in the MMAP sense) triples
(opt-vars, log-marginal-gp, log-marginal-raw, program-results):
opt-vars ... optimization variables
log-marginal-raw ... the log marginal likelihood p(observes, opt-vars) as
estimated by the gps (i.e. gp mixture means at this point)
log-marginal-raw ... estimate of log marginal when evaluated
program-results ... program results associated with opt-vars
See paper for details."
[algorithm opt-query opt-query-args num-samples &
{:keys [;; Speed option
speed-option
;; BO options
bo-options
;; Optimization options
opt-type opt-program-transformation opt-sample-summarizer opt-bo-target-transformation
;; Inference options
inf-options
Acquisition optimization / AIS options
acq-opt-num-starts ais-num-steps ais-start-exponent ais-end-exponent
;; Other options
output-extractor f-theta-inf]
:or {speed-option :fast
;; Default optimization options
opt-type :mmap
Default acquisition optimization / AIS options
ais-start-exponent 0.001
ais-end-exponent 10
;; Default other options
output-extractor get-result-vector
f-theta-inf -1e5 ; FIXME: Don't replace -Infinity with f-theta-inf; resample a random point instead.
}}]
(let [;; Set default parameters based on speed-option
[acq-opt-num-starts-default
bo-options-default]
(case speed-option
:careful [16 {:hmc-num-leapfrog-steps 5
:hmc-num-mcmc-steps 50
:hmc-num-opt-steps 15
:hmc-num-chains 8
:hmc-max-gps 50}]
:fast [4 {:hmc-num-leapfrog-steps 2
:hmc-num-mcmc-steps 20
:hmc-num-opt-steps 10
:hmc-num-chains 4
:hmc-max-gps 20}]
(throw (Exception. (str "speed-option must be one of [:careful, :fast]. Supplied speed-option: " speed-option))))
;; Override these parameters by ones provided by the user
[acq-opt-num-starts bo-options]
[(or acq-opt-num-starts acq-opt-num-starts-default)
(merge bo-options-default bo-options)]
;; Optimization options error checking
_ (if (and (not (= opt-type :custom))
(not (some nil? [opt-program-transformation opt-sample-summarizer opt-bo-target-transformation])))
(throw (Exception. ("If opt-type is not :custom, opt-program-transformation, opt-sample-summarizer- opt-bo-target-transformation must not be supplied."))))
Override Optimization options
[opt-program-transformation opt-sample-summarizer opt-bo-target-transformation]
(case opt-type
:mmap [:mmap log-marginal identity]
:ml2 [:ml2 log-marginal identity]
:risk-minimization [:ml2 log-marginal -]
:custom [opt-program-transformation opt-sample-summarizer opt-bo-target-transformation]
(throw (Exception. (str "Optimization type " opt-type " not supported. Supported: :mmap, :ml2, :risk-minimization, :custom."))))
;; Optimization options error checking
_ (if (some nil? [opt-program-transformation opt-sample-summarizer opt-bo-target-transformation])
(throw (Exception. ("If opt-type is :custom, opt-program-transformation, opt-sample-summarizer- opt-bo-target-transformation must be supplied."))))
;; Compiled transformed queries
prior-q (:prior-query opt-query)
acq-q (:acq-query opt-query)
marg-q (case opt-program-transformation
:mmap (:mmap-query opt-query)
:ml2 (:ml2-query opt-query)
(throw (Exception. (str "opt-program-transformation " opt-program-transformation " not supported. Supported: :mmap, :ml2."))))
bo-options (if (= opt-type :risk-minimization)
(merge bo-options {:invert-output-display true})
bo-options)
;; Inference options
inf-options-default (case algorithm
:pcascade {:number-of-threads (int (* 2 num-samples))
:number-of-particles num-samples}
{:number-of-particles num-samples})
inf-options (flatten
(into []
(merge inf-options-default inf-options)))
;; Setup the target function for BO
f (fn [theta]
(bo-target
theta marg-q opt-query-args algorithm num-samples inf-options opt-bo-target-transformation opt-sample-summarizer f-theta-inf output-extractor))
ais-num-steps (or ais-num-steps
(max 100 (int (* 2 (/ num-samples acq-opt-num-starts)))))
;; Setup the acqusition function optimizer
aq-optimizer (fn [acq-fn]
(distributed-aq-optimizer acq-fn opt-query-args acq-q acq-opt-num-starts ais-num-steps ais-start-exponent ais-end-exponent))
;; Setup the sampler for cheaply sampling valid theta's
theta-sampler (fn [n-samples]
(map get-result-vector
(take n-samples
(infer :importance prior-q opt-query-args))))
;; Setup BO options to pass in an apply
bo-options (flatten (into [] (filter second bo-options)))]
(let [output (apply bo/deodorant f aq-optimizer theta-sampler bo-options)]
(if (= :risk-minimization opt-type)
(map #(update % 1 -)
(map #(update % 2 -)
output))
output))))
| null | https://raw.githubusercontent.com/probprog/bopp/cfb93c22cd7f97ec303eb47b6748b6124b9b5914/src/bopp/core.clj | clojure | Could be +-Infinity
must provide opt-program-transformation,
Suggested: anglican.inference/log-marginal)
Suggested: identity, - for minimization)
Speed option
BO options
Optimization options
Inference options
Other options
Default optimization options
Default other options
FIXME: Don't replace -Infinity with f-theta-inf; resample a random point instead.
Set default parameters based on speed-option
Override these parameters by ones provided by the user
Optimization options error checking
Optimization options error checking
Compiled transformed queries
Inference options
Setup the target function for BO
Setup the acqusition function optimizer
Setup the sampler for cheaply sampling valid theta's
Setup BO options to pass in an apply | (ns bopp.core
"User interface for BOPP"
(require [deodorant.core :as bo]
[bopp.program-transformations :as pt]
[bopp.helper-functions :refer [argmax]]
[bopp.error-handling :refer [changing-types?]]
[anglican.inference :refer [log-marginal infer]]
[anglican.state :refer [get-log-weight get-result]]
[anglican.trap :refer [primitive-procedure-cps]]
[anglican.ais]
[anglican.importance]))
(defn- get-result-vector [sample]
(into [] (get-result sample)))
(defmacro opt [& args]
(if (apply changing-types? args)
(throw (Exception. "Query contains distribution assignments to optimization variables that have different type (continuous, discrete)."))
`(with-meta
{:prior-query (pt/prior-query ~@args)
:acq-query (pt/acq-query ~@args)
:mmap-query (pt/mmap-query ~@args)
:ml2-query (pt/ml2-query ~@args)}
{:source '(~'opt ~@args)})))
(defmacro defopt
"Binds variable to a BOPP query. Synatx is the
same as Anglican's defquery, except that an
additional input is specified to dictate the
variables to be optimized.
Example:
(defopt opt-query
<docstring>
[y] [theta]
(let [a (sample (normal 0 10))
theta (sample (normal a 20))
b (sample (normal a (* theta theta)))]
(observe (normal (* a theta) (* b b)) y)
[a b]))
For more details please see the README and the
paper.
-bayesian-optimization-for-probabilistic-programs"
[name & args]
(let [[docstring source]
(if (string? (first args))
[(first args) (rest args)]
[(format "BOPP program '%s'" name) args])]
`(def ~(with-meta name {:doc docstring})
(opt ~@source))))
(defn- bo-target
"Calculates the value of a the BO target given a marginal query and a
point to evaluate. Target will typically be the log-marginal for
MMAP problems and (- (log-marginal samples)) for risk minimization.
However, also allows overide capabilities from different transformations
of the target (e.g. WASABI), to using completely different opt-sample-summarizers for
the sample populations (e.g. variance on the weights). Also provides
flexibility in the additional return values taken (e.g. get-result-vector
or get-predicts).
Inputs: marg-q = transformed marginal query
query-args = fixed arguments to the defopt (i.e. its first argument)
algorithm = inner inference algorithm to use
num-samples = number of samples to take in inner inference algorithm
inf-options = options to use in inner inferenec algorithm
output-extractor = extracts additional outputs from the inner query,
e.g get-result-vector or get-predicts
opt-bo-target-transformation = transformation function applied to the output of
the opt-sample-summarizer calculation.
opt-sample-summarizer = function used to calculate the desired untransformed target
from the samples.
f-theta-inf = Value of f-theta set to if evaluates as +/- infinity (sign is maintained)
Outputs: f-theta = Evaluated value as used for the bayes opt. Note that the bayes
opt always carries out maximization. Minimization is thus done
by maximiziation a function where f-theta = -target.
inner-outputs = additional outputs from the inner query."
[theta
marg-q
query-args
algorithm
num-samples
inf-options
opt-bo-target-transformation
opt-sample-summarizer
f-theta-inf
output-extractor]
(let [samples (take num-samples
(apply infer
algorithm
marg-q
(concat query-args theta)
inf-options))
f-theta (if (= f-theta (/ -1. 0))
(do (println "BOPP WARNING: Target evaluation has underflown!")
(- f-theta-inf))
(if (= f-theta (/ 1. 0))
(do (println "BOPP WARNING: Target evaluation has overflown!")
f-theta-inf)
f-theta))
outputs (map output-extractor samples)]
[f-theta outputs]))
(defn- distributed-aq-optimizer
"Performs parallelized calls of infer on an optimization query and takes
the best sample from any of the runs."
[acq-fn opt-query-args acq-q acq-opt-num-starts ais-num-steps ais-start-exponent ais-end-exponent]
(let [log-acq-fn (fn [theta & args]
(Math/log (apply acq-fn theta args)))
cpsd-acq-fn (fn [cont state & args]
(fn []
(cont (apply log-acq-fn args) state)))
outputs (pmap (fn [unused] (first (infer :ais
acq-q
(conj opt-query-args cpsd-acq-fn)
:number-of-steps ais-num-steps
:start-exponent ais-start-exponent
:end-exponent ais-end-exponent)))
(range acq-opt-num-starts))
log-weights (map get-log-weight outputs)
i-best (argmax log-weights)
best-output (get-result-vector (nth outputs i-best))]
best-output))
(defn doopt
"Calls BOPP on a target query as defined by defopt, returning a lazy
infinite sequence of increasingly optimal estimates.
For more details please see the README and the
paper.
-bayesian-optimization-for-probabilistic-programs
Input:
algorithm ... Inference algorithm
[:smc, :pcascade, :importance]
opt-query ... Query to be optimized, defined by defopt.
opt-query-args ... Arguments of opt-query.
num-samples ... Number of samples for constructing the estimator to be
optimized
Optional keyword arguments:
Speed option:
speed-option ... Set the default options to a set of pre-tuned values to
be able to switch between the different modes of running depending on
speed. Can be overriden by user post-hoc.
[:careful, :fast] (Default: :fast)
Bayesian optimization (BO) options:
bo-options ... look at documentation of Deodorant, this should be a map
with those options, i.e.:
{:initial-points <initial-points>
:num-scaling-thetas <num-scaling-thetas>
:num-initial-points <num-initial-points>
:cov-fn-form <cov-fn-form>
... etc.}
You only need to provide options whose defaults that you want to
override.
(Default:
if :speed-option is :careful
{:hmc-num-leapfrog-steps 5
:hmc-num-mcmc-steps 50
:hmc-num-opt-steps 15
:hmc-num-chains 8
:hmc-max-gps 50}
if :speed-option is :fast
{:hmc-num-leapfrog-steps 2
:hmc-num-mcmc-steps 20
:hmc-num-opt-steps 10
:hmc-num-chains 4
:hmc-max-gps 20})
Optimization options:
opt-type ... Optimization type. Use :custom to customize the
opt-sample-summarizer, opt-bo-target-transformation in this case.
[:mmap, :ml2, :risk-minimization :custom] (Default: :mmap)
opt-program-transformation ... Custom program transformation for
optimization.
[nil, :mmap, :ml2] (Default: nil)
opt-sample-summarizer ... Custom sample summarizer for optimizer. Takes
in a sequence of Anglican samples, outputs target scalar for BO.
opt-bo-target-transformation ... Custom BO target transformation for
optimization. Takes in BO target, outputs alternative target.
Inference options:
inf-options ... Options to be passed to the inference scheme. Note
that default options are merged as with bo-options and so these with
overwrite the inference algorithm defaults if not set
(Default:
if algorithm is :pcascade
{:number-of-threads (int (* 2 num-samples))
:number-of-particles num-samples}
otherwise
{:number-of-particles num-samples})
Acquisition optimization/AIS options:
acq-opt-num-starts ... Number of parallel optimizations to prevent
multimodality. (Default: 4 if :speed-option is :fast 16 if :careful)
ais-num-steps ... Number of MCMC steps performed during acquisition
function optimization.
(Default: (max 100 (int (* 2 (/ num-samples acq-opt-num-starts)))))
ais-start-exponent ... Start exponent for annealed importance sampling
(Default: 0.001)
ais-end-exponent ... End exponent for annealed importance sampling
(Default: 10)
Other options
output-extractor ... Takes in an Anglican sample, returns its output.
Alternatives: anglican.state/get-result, anglican.state/get-predicts)
f-theta-inf ... Replace -Infinity during BO by this. (Default: -1e5)
Output:
Lazy list of increasingly optimal (in the MMAP sense) triples
(opt-vars, log-marginal-gp, log-marginal-raw, program-results):
opt-vars ... optimization variables
log-marginal-raw ... the log marginal likelihood p(observes, opt-vars) as
estimated by the gps (i.e. gp mixture means at this point)
log-marginal-raw ... estimate of log marginal when evaluated
program-results ... program results associated with opt-vars
See paper for details."
[algorithm opt-query opt-query-args num-samples &
speed-option
bo-options
opt-type opt-program-transformation opt-sample-summarizer opt-bo-target-transformation
inf-options
Acquisition optimization / AIS options
acq-opt-num-starts ais-num-steps ais-start-exponent ais-end-exponent
output-extractor f-theta-inf]
:or {speed-option :fast
opt-type :mmap
Default acquisition optimization / AIS options
ais-start-exponent 0.001
ais-end-exponent 10
output-extractor get-result-vector
}}]
[acq-opt-num-starts-default
bo-options-default]
(case speed-option
:careful [16 {:hmc-num-leapfrog-steps 5
:hmc-num-mcmc-steps 50
:hmc-num-opt-steps 15
:hmc-num-chains 8
:hmc-max-gps 50}]
:fast [4 {:hmc-num-leapfrog-steps 2
:hmc-num-mcmc-steps 20
:hmc-num-opt-steps 10
:hmc-num-chains 4
:hmc-max-gps 20}]
(throw (Exception. (str "speed-option must be one of [:careful, :fast]. Supplied speed-option: " speed-option))))
[acq-opt-num-starts bo-options]
[(or acq-opt-num-starts acq-opt-num-starts-default)
(merge bo-options-default bo-options)]
_ (if (and (not (= opt-type :custom))
(not (some nil? [opt-program-transformation opt-sample-summarizer opt-bo-target-transformation])))
(throw (Exception. ("If opt-type is not :custom, opt-program-transformation, opt-sample-summarizer- opt-bo-target-transformation must not be supplied."))))
Override Optimization options
[opt-program-transformation opt-sample-summarizer opt-bo-target-transformation]
(case opt-type
:mmap [:mmap log-marginal identity]
:ml2 [:ml2 log-marginal identity]
:risk-minimization [:ml2 log-marginal -]
:custom [opt-program-transformation opt-sample-summarizer opt-bo-target-transformation]
(throw (Exception. (str "Optimization type " opt-type " not supported. Supported: :mmap, :ml2, :risk-minimization, :custom."))))
_ (if (some nil? [opt-program-transformation opt-sample-summarizer opt-bo-target-transformation])
(throw (Exception. ("If opt-type is :custom, opt-program-transformation, opt-sample-summarizer- opt-bo-target-transformation must be supplied."))))
prior-q (:prior-query opt-query)
acq-q (:acq-query opt-query)
marg-q (case opt-program-transformation
:mmap (:mmap-query opt-query)
:ml2 (:ml2-query opt-query)
(throw (Exception. (str "opt-program-transformation " opt-program-transformation " not supported. Supported: :mmap, :ml2."))))
bo-options (if (= opt-type :risk-minimization)
(merge bo-options {:invert-output-display true})
bo-options)
inf-options-default (case algorithm
:pcascade {:number-of-threads (int (* 2 num-samples))
:number-of-particles num-samples}
{:number-of-particles num-samples})
inf-options (flatten
(into []
(merge inf-options-default inf-options)))
f (fn [theta]
(bo-target
theta marg-q opt-query-args algorithm num-samples inf-options opt-bo-target-transformation opt-sample-summarizer f-theta-inf output-extractor))
ais-num-steps (or ais-num-steps
(max 100 (int (* 2 (/ num-samples acq-opt-num-starts)))))
aq-optimizer (fn [acq-fn]
(distributed-aq-optimizer acq-fn opt-query-args acq-q acq-opt-num-starts ais-num-steps ais-start-exponent ais-end-exponent))
theta-sampler (fn [n-samples]
(map get-result-vector
(take n-samples
(infer :importance prior-q opt-query-args))))
bo-options (flatten (into [] (filter second bo-options)))]
(let [output (apply bo/deodorant f aq-optimizer theta-sampler bo-options)]
(if (= :risk-minimization opt-type)
(map #(update % 1 -)
(map #(update % 2 -)
output))
output))))
|
8219945c15bdf89242d90ee1f6b6249ef7fc0bbfa6ddab969880a0c0bf532a8f | mejgun/haskell-tdlib | ChatMember.hs | {-# LANGUAGE OverloadedStrings #-}
-- |
module TD.Data.ChatMember where
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as T
import qualified TD.Data.ChatMemberStatus as ChatMemberStatus
import qualified TD.Data.MessageSender as MessageSender
import qualified Utils as U
-- |
data ChatMember = -- | Describes a user or a chat as a member of another chat
ChatMember
{ -- | Status of the member in the chat
status :: Maybe ChatMemberStatus.ChatMemberStatus,
-- | Point in time (Unix timestamp) when the user joined/was promoted/was banned in the chat
joined_chat_date :: Maybe Int,
-- | Identifier of a user that invited/promoted/banned this member in the chat; 0 if unknown
inviter_user_id :: Maybe Int,
-- | Identifier of the chat member. Currently, other chats can be only Left or Banned. Only supergroups and channels can have other chats as Left or Banned members and these chats must be supergroups or channels
member_id :: Maybe MessageSender.MessageSender
}
deriving (Eq)
instance Show ChatMember where
show
ChatMember
{ status = status_,
joined_chat_date = joined_chat_date_,
inviter_user_id = inviter_user_id_,
member_id = member_id_
} =
"ChatMember"
++ U.cc
[ U.p "status" status_,
U.p "joined_chat_date" joined_chat_date_,
U.p "inviter_user_id" inviter_user_id_,
U.p "member_id" member_id_
]
instance T.FromJSON ChatMember where
parseJSON v@(T.Object obj) = do
t <- obj A..: "@type" :: T.Parser String
case t of
"chatMember" -> parseChatMember v
_ -> mempty
where
parseChatMember :: A.Value -> T.Parser ChatMember
parseChatMember = A.withObject "ChatMember" $ \o -> do
status_ <- o A..:? "status"
joined_chat_date_ <- o A..:? "joined_chat_date"
inviter_user_id_ <- o A..:? "inviter_user_id"
member_id_ <- o A..:? "member_id"
return $ ChatMember {status = status_, joined_chat_date = joined_chat_date_, inviter_user_id = inviter_user_id_, member_id = member_id_}
parseJSON _ = mempty
instance T.ToJSON ChatMember where
toJSON
ChatMember
{ status = status_,
joined_chat_date = joined_chat_date_,
inviter_user_id = inviter_user_id_,
member_id = member_id_
} =
A.object
[ "@type" A..= T.String "chatMember",
"status" A..= status_,
"joined_chat_date" A..= joined_chat_date_,
"inviter_user_id" A..= inviter_user_id_,
"member_id" A..= member_id_
]
| null | https://raw.githubusercontent.com/mejgun/haskell-tdlib/e81b9b3096f4b5bb3e10ca9f895ee469efa47a37/src/TD/Data/ChatMember.hs | haskell | # LANGUAGE OverloadedStrings #
|
|
| Describes a user or a chat as a member of another chat
| Status of the member in the chat
| Point in time (Unix timestamp) when the user joined/was promoted/was banned in the chat
| Identifier of a user that invited/promoted/banned this member in the chat; 0 if unknown
| Identifier of the chat member. Currently, other chats can be only Left or Banned. Only supergroups and channels can have other chats as Left or Banned members and these chats must be supergroups or channels |
module TD.Data.ChatMember where
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as T
import qualified TD.Data.ChatMemberStatus as ChatMemberStatus
import qualified TD.Data.MessageSender as MessageSender
import qualified Utils as U
ChatMember
status :: Maybe ChatMemberStatus.ChatMemberStatus,
joined_chat_date :: Maybe Int,
inviter_user_id :: Maybe Int,
member_id :: Maybe MessageSender.MessageSender
}
deriving (Eq)
instance Show ChatMember where
show
ChatMember
{ status = status_,
joined_chat_date = joined_chat_date_,
inviter_user_id = inviter_user_id_,
member_id = member_id_
} =
"ChatMember"
++ U.cc
[ U.p "status" status_,
U.p "joined_chat_date" joined_chat_date_,
U.p "inviter_user_id" inviter_user_id_,
U.p "member_id" member_id_
]
instance T.FromJSON ChatMember where
parseJSON v@(T.Object obj) = do
t <- obj A..: "@type" :: T.Parser String
case t of
"chatMember" -> parseChatMember v
_ -> mempty
where
parseChatMember :: A.Value -> T.Parser ChatMember
parseChatMember = A.withObject "ChatMember" $ \o -> do
status_ <- o A..:? "status"
joined_chat_date_ <- o A..:? "joined_chat_date"
inviter_user_id_ <- o A..:? "inviter_user_id"
member_id_ <- o A..:? "member_id"
return $ ChatMember {status = status_, joined_chat_date = joined_chat_date_, inviter_user_id = inviter_user_id_, member_id = member_id_}
parseJSON _ = mempty
instance T.ToJSON ChatMember where
toJSON
ChatMember
{ status = status_,
joined_chat_date = joined_chat_date_,
inviter_user_id = inviter_user_id_,
member_id = member_id_
} =
A.object
[ "@type" A..= T.String "chatMember",
"status" A..= status_,
"joined_chat_date" A..= joined_chat_date_,
"inviter_user_id" A..= inviter_user_id_,
"member_id" A..= member_id_
]
|
36303040221b2d1d7717ff027f631dd2b82d1fd0b85ba16f0f27794e3057529e | ghc/testsuite | tcfail169.hs |
Trac # 958
module ShoulFail where
NB : deriving Show omitted
data Seq a = Cons a (Seq (Succ a)) | Nil deriving Show
| null | https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/typecheck/should_fail/tcfail169.hs | haskell |
Trac # 958
module ShoulFail where
NB : deriving Show omitted
data Seq a = Cons a (Seq (Succ a)) | Nil deriving Show
| |
59c32cecc4a707491f1c13a0abfd86ee22b8595f53efe0b22f84106d190dec77 | cwi-swat/monadic-frp | PaperExample.hs | -- | The example from the paper
# LANGUAGE TupleSections , ViewPatterns , NoMonomorphismRestriction #
module PaperExample where
import Control.Monad.State.Lazy
import Control.MonadicFRP
import Data.Set hiding (map,filter)
import Prelude hiding (null,map,filter,filter,until,repeat,cycle,scanl,span,break,tail )
import qualified Prelude as P
import Data.Maybe
import SDLSFRP
import Control.Monad
import qualified Data.Set as Set
mdown :: React GUIEv GUIEv
mdown = exper (MouseDown Request)
mouseDown :: React GUIEv (Set MouseBtn)
mouseDown = exper (MouseDown Request) >>= get
where get (MouseDown (Occurred s)) = return s
-- stuff implicit in paper:
mouseUp = exper (MouseUp Request) >>= get
where get (MouseUp (Occurred t)) = return t
mouseMove = exper (MouseMove Request) >>= get
where get (MouseMove (Occurred t)) = return t
deltaTime = exper (DeltaTime Request) >>= get
where get (DeltaTime (Occurred t)) = return t
tryWait t = exper (TryWait t Request) >>= get
where get (TryWait _ (Occurred t)) = return t
sameClick :: Reactg Bool
sameClick = mouseDown >>= (\pressed ->
mouseDown >>= (\pressed2 ->
return (pressed == pressed2)))
sameClick2 = do pressed <- mouseDown
pressed2 <- mouseDown
return (pressed == pressed2)
clickOn :: MouseBtn -> Reactg ()
clickOn b = do bs <- mouseDown
if (b `member` bs) then return () else clickOn b
leftClick = clickOn MLeft
middleClick = clickOn MMiddle
rightClick = clickOn MRight
--implicit in paper
releaseOf :: MouseBtn -> Reactg ()
releaseOf b = do bs <- mouseUp
if (b `member` bs) then return () else releaseOf b
leftUp = releaseOf MLeft
middleUp = releaseOf MMiddle
rightUp = releaseOf MRight
before :: Reactg a -> Reactg b -> Reactg Bool
before a b = do (a',b') <- first a b
case (done a', done b') of
(Just _, Nothing) -> return True
_ -> return False
doubler :: Reactg ()
doubler = do rightClick
r <- rightClick `before` sleep 0.2
if r then return () else doubler
cycleColor :: Sigg Color Int
cycleColor = cc colors 0 where
cc (h:t) i =
do emit h
r <- waitFor (before middleClick rightClick)
if r then cc t (i+1) else return i
mousePos :: Sigg Point ()
mousePos = repeat mouseMove
curRect :: Point -> Sigg Rect ()
curRect p1 = map (Rect p1) mousePos
elapsed :: Sigg Time ()
elapsed = scanl (+) 0 (repeat deltaTime)
wiggleRect :: Rect -> Sigg Rect ()
wiggleRect (Rect lu rd) = map rectAtTime elapsed
where rectAtTime t = Rect (lu +. dx) (rd +. dx)
where dx = (sin (t * 5) * 15, 0)
(x,y) +. (x',y') = (x + x', y + y')
posInside :: Rect -> Sigg Point y -> Reactg (Maybe Point)
posInside r = find (`inside` r)
inside :: Point -> Rect -> Bool
(x,y) `inside` (normalize -> Rect (lx,uy) (rx,dy)) =
x >= lx && x <= rx && y >= uy && y <= dy
firstPoint :: Reactg Point
firstPoint = do r <- mousePos `at` leftClick
case r of
Just a -> return a
Nothing -> firstPoint
completeRect :: Point -> Sigg Rect (Maybe Rect)
completeRect p1 = do (r,_) <- curRect p1 `until` leftUp
return (cur r)
defineRect :: Sigg Rect Rect
defineRect = do p1 <- waitFor firstPoint
r <- completeRect p1 -- slight difference with paper: if the user does not move the mouse the pattern match will fail (this would define an empty rectangle) here we fix this.
case r of
Just r -> return r
Nothing -> defineRect
chooseBoxColor :: Rect -> Sigg Box ()
chooseBoxColor r =
do always Box <^> wiggleRect r <^> cycleColor
return ()
drClickOn :: Rect -> Reactg (Maybe Point)
drClickOn r =
posInside r (mousePos `indexBy` repeat doubler)
box :: Sigg Box ()
box = do r <- map setColor defineRect
chooseBoxColor r
waitFor (drClickOn r)
return ()
where setColor r = Box r (head colors)
boxes :: Sigg [Box] ()
boxes = parList (spawn box)
type Reactg = React GUIEv
sleep :: Time -> React GUIEv ()
sleep t = do t' <- tryWait t
if t' == t then return () else sleep (t - t')
type Sigg = Sig GUIEv
type ISigg = ISig GUIEv
-- implicit in paper
colors = P.cycle [Color 1 0 0 , Color 0 1 0 , Color 0 0 1 , Color 1 1 0, Color 0 1 1 , Color 1 0 1, Color 0 1 1]
| null | https://raw.githubusercontent.com/cwi-swat/monadic-frp/c0c40fdfe4a2c77df66173338b109831b35b7672/PaperExample.hs | haskell | | The example from the paper
stuff implicit in paper:
implicit in paper
slight difference with paper: if the user does not move the mouse the pattern match will fail (this would define an empty rectangle) here we fix this.
implicit in paper | # LANGUAGE TupleSections , ViewPatterns , NoMonomorphismRestriction #
module PaperExample where
import Control.Monad.State.Lazy
import Control.MonadicFRP
import Data.Set hiding (map,filter)
import Prelude hiding (null,map,filter,filter,until,repeat,cycle,scanl,span,break,tail )
import qualified Prelude as P
import Data.Maybe
import SDLSFRP
import Control.Monad
import qualified Data.Set as Set
mdown :: React GUIEv GUIEv
mdown = exper (MouseDown Request)
mouseDown :: React GUIEv (Set MouseBtn)
mouseDown = exper (MouseDown Request) >>= get
where get (MouseDown (Occurred s)) = return s
mouseUp = exper (MouseUp Request) >>= get
where get (MouseUp (Occurred t)) = return t
mouseMove = exper (MouseMove Request) >>= get
where get (MouseMove (Occurred t)) = return t
deltaTime = exper (DeltaTime Request) >>= get
where get (DeltaTime (Occurred t)) = return t
tryWait t = exper (TryWait t Request) >>= get
where get (TryWait _ (Occurred t)) = return t
sameClick :: Reactg Bool
sameClick = mouseDown >>= (\pressed ->
mouseDown >>= (\pressed2 ->
return (pressed == pressed2)))
sameClick2 = do pressed <- mouseDown
pressed2 <- mouseDown
return (pressed == pressed2)
clickOn :: MouseBtn -> Reactg ()
clickOn b = do bs <- mouseDown
if (b `member` bs) then return () else clickOn b
leftClick = clickOn MLeft
middleClick = clickOn MMiddle
rightClick = clickOn MRight
releaseOf :: MouseBtn -> Reactg ()
releaseOf b = do bs <- mouseUp
if (b `member` bs) then return () else releaseOf b
leftUp = releaseOf MLeft
middleUp = releaseOf MMiddle
rightUp = releaseOf MRight
before :: Reactg a -> Reactg b -> Reactg Bool
before a b = do (a',b') <- first a b
case (done a', done b') of
(Just _, Nothing) -> return True
_ -> return False
doubler :: Reactg ()
doubler = do rightClick
r <- rightClick `before` sleep 0.2
if r then return () else doubler
cycleColor :: Sigg Color Int
cycleColor = cc colors 0 where
cc (h:t) i =
do emit h
r <- waitFor (before middleClick rightClick)
if r then cc t (i+1) else return i
mousePos :: Sigg Point ()
mousePos = repeat mouseMove
curRect :: Point -> Sigg Rect ()
curRect p1 = map (Rect p1) mousePos
elapsed :: Sigg Time ()
elapsed = scanl (+) 0 (repeat deltaTime)
wiggleRect :: Rect -> Sigg Rect ()
wiggleRect (Rect lu rd) = map rectAtTime elapsed
where rectAtTime t = Rect (lu +. dx) (rd +. dx)
where dx = (sin (t * 5) * 15, 0)
(x,y) +. (x',y') = (x + x', y + y')
posInside :: Rect -> Sigg Point y -> Reactg (Maybe Point)
posInside r = find (`inside` r)
inside :: Point -> Rect -> Bool
(x,y) `inside` (normalize -> Rect (lx,uy) (rx,dy)) =
x >= lx && x <= rx && y >= uy && y <= dy
firstPoint :: Reactg Point
firstPoint = do r <- mousePos `at` leftClick
case r of
Just a -> return a
Nothing -> firstPoint
completeRect :: Point -> Sigg Rect (Maybe Rect)
completeRect p1 = do (r,_) <- curRect p1 `until` leftUp
return (cur r)
defineRect :: Sigg Rect Rect
defineRect = do p1 <- waitFor firstPoint
case r of
Just r -> return r
Nothing -> defineRect
chooseBoxColor :: Rect -> Sigg Box ()
chooseBoxColor r =
do always Box <^> wiggleRect r <^> cycleColor
return ()
drClickOn :: Rect -> Reactg (Maybe Point)
drClickOn r =
posInside r (mousePos `indexBy` repeat doubler)
box :: Sigg Box ()
box = do r <- map setColor defineRect
chooseBoxColor r
waitFor (drClickOn r)
return ()
where setColor r = Box r (head colors)
boxes :: Sigg [Box] ()
boxes = parList (spawn box)
type Reactg = React GUIEv
sleep :: Time -> React GUIEv ()
sleep t = do t' <- tryWait t
if t' == t then return () else sleep (t - t')
type Sigg = Sig GUIEv
type ISigg = ISig GUIEv
colors = P.cycle [Color 1 0 0 , Color 0 1 0 , Color 0 0 1 , Color 1 1 0, Color 0 1 1 , Color 1 0 1, Color 0 1 1]
|
8fa229f7eb1779faf896fb44925e9d6277ace1bf8a7b5831367537010304c54c | skanev/playground | 28-tests.scm | (require rackunit rackunit/text-ui)
(load-relative "../../support/eopl.scm")
(load-relative "../28.scm")
(load-relative "helpers/proc.scm")
(define eopl-3.28-tests
(test-suite
"Tests for EOPL exercise 3.28"
(check-equal? (run "let a = 3
in let p = proc (x) -(x, a)
in let a = 5
in -(a, (p 2))")
8)))
(exit (run-tests eopl-3.28-tests))
| null | https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/eopl/03/tests/28-tests.scm | scheme | (require rackunit rackunit/text-ui)
(load-relative "../../support/eopl.scm")
(load-relative "../28.scm")
(load-relative "helpers/proc.scm")
(define eopl-3.28-tests
(test-suite
"Tests for EOPL exercise 3.28"
(check-equal? (run "let a = 3
in let p = proc (x) -(x, a)
in let a = 5
in -(a, (p 2))")
8)))
(exit (run-tests eopl-3.28-tests))
| |
e3172a4f5dcfd75449ad0c8a25eef0d6385dddc7ccaa14eb116da41fb4ec3708 | heyoka/faxe | esp_first.erl | Date : 09.12.16 - 18:02
Ⓒ 2016 heyoka
-module(esp_first).
-author("Alexander Minichmair").
-behavior(esp_stats).
%% API
-export([execute/2, options/0]).
options() ->
esp_stats:get_options() ++ [{module, atom, ?MODULE}].
execute({_Tss, Values}, _Opts) ->
{first, lists:last(Values)}. | null | https://raw.githubusercontent.com/heyoka/faxe/e539afe8b62790a6037914751deef7d815be11a2/apps/faxe/src/components/stats/esp_first.erl | erlang | API | Date : 09.12.16 - 18:02
Ⓒ 2016 heyoka
-module(esp_first).
-author("Alexander Minichmair").
-behavior(esp_stats).
-export([execute/2, options/0]).
options() ->
esp_stats:get_options() ++ [{module, atom, ?MODULE}].
execute({_Tss, Values}, _Opts) ->
{first, lists:last(Values)}. |
b8ccfdbd38398e8c0a8230f7ad269a34b1ad684bdef61147c1e9b50c44016a5f | UU-ComputerScience/js-asteroids | Asteroids.hs | # LANGUAGE CPP #
{-# OPTIONS -pgmP cpp #-}
module Asteroids where
import Graphics.UI.WX
import Graphics.UI.WXCore hiding (window,bitmap)
import Control.Monad
#ifdef __UHC__
import Language.UHC.JS.Marshal
import Language.UHC.JS.Types
import Language.UHC.JS.Prelude
foreign import js "Math.random()"
random :: IO Double
#else
random = undefined
_trace = undefined
str = undefined
#endif
rand _ = unsafePerformIO random
randoms :: [Double]
randoms =
let inf = undefined : inf
in map rand inf
height :: Int
height = 300
width :: Int
width = 300
diameter :: Int
diameter = 24
chance :: Double
chance = 0.1
asteroids :: IO ()
asteroids =
do
vrocks <- varCreate randomRocks
vship <- varCreate $ div width 2
w <- window Nothing [area := rect (pt 0 0) (sz width height)]
t <- timer w [ interval := 50
, on command := advance vrocks w
]
set w [
on paint := draw vrocks vship
, on leftKey := varUpdate vship (\x -> max 0 (x - 5)) >> return ()
, on rightKey := varUpdate vship (\x -> min width (x + 5)) >> return ()
, on (charKey 'q') := set t [interval :~ \i -> i * 2]
, on (charKey 'w') := (_trace (str "slowdown") >> set t [interval :~ \i -> max 10 (div i 2)])
]
--advance :: (Textual w, Paint w1) => w -> Var [[a]] -> w1 -> IO ()
advance :: (Paint w) => Var [[a]] -> w -> IO ()
advance vrocks f =
do
(r : rs) <- varGet vrocks
varSet vrocks rs
repaint f
randomRocks = flatten [] (map fresh randoms)
flatten :: [[a]] -> [[[a]]] -> [[a]]
flatten rocks (t : ts) =
let now = map head rocks
later = filter (not . null) (map tail rocks)
in now : flatten (t ++ later) ts
flatten rocks [] = error "Empty rocks list not expected in function flatten"
fresh :: Double -> [[Point2 Int]]
fresh r
| r > chance = []
| otherwise = [track (floor (fromIntegral width * r / chance))]
track :: Int -> [Point2 Int]
track x = [point x (y - diameter) | y <- [0, 6 .. height + 2 * diameter]]
draw : : [ [ Point2 Int ] ] - > a - > b - > IO ( )
draw :: Var [[Point2 Int]] -> Var Int -> GraphicsContext -> b -> IO ()
draw vrocks vship dc _view =
do
rocks <- varGet vrocks
x <- varGet vship
let
shipLocation = point x (height - 2 * diameter)
positions = head rocks
collisions = map (collide shipLocation) positions
drawShip dc shipLocation
mapM (drawRock dc) (zip positions collisions)
--when (or collisions) (play explode)
when (or collisions) (return ())
collide :: Point2 Int -> Point2 Int -> Bool
collide pos0 pos1 =
let distance = vecLength (vecBetween pos0 pos1)
in distance <= fromIntegral diameter
drawShip : : DC a - > Point - > IO ( )
drawShip :: GraphicsContext_ a -> Point -> IO ()
drawShip dc pos = drawBitmap dc ship pos True []
drawRock : : DC a - > ( Point , Bool ) - > IO ( )
drawRock :: GraphicsContext_ a -> (Point, Bool) -> IO ()
drawRock dc (pos, collides)=
let rockPicture = if collides then burning else rock
in do --consoleLog (str (show (pointX pos) ++ "," ++ show (pointY pos)))
drawBitmap dc rockPicture pos True []
rock :: GraphicsBitmap
rock = bitmap "../resources/rock.ico"
burning :: GraphicsBitmap
burning = bitmap "../resources/burning.ico"
ship :: GraphicsBitmap
ship = bitmap "../resources/ship.ico"
main :: IO ()
main = start asteroids
| null | https://raw.githubusercontent.com/UU-ComputerScience/js-asteroids/b7015d8ad4aa57ff30f2631e0945462f6e1ef47a/wxasteroids/src/Asteroids.hs | haskell | # OPTIONS -pgmP cpp #
advance :: (Textual w, Paint w1) => w -> Var [[a]] -> w1 -> IO ()
when (or collisions) (play explode)
consoleLog (str (show (pointX pos) ++ "," ++ show (pointY pos)))
| # LANGUAGE CPP #
module Asteroids where
import Graphics.UI.WX
import Graphics.UI.WXCore hiding (window,bitmap)
import Control.Monad
#ifdef __UHC__
import Language.UHC.JS.Marshal
import Language.UHC.JS.Types
import Language.UHC.JS.Prelude
foreign import js "Math.random()"
random :: IO Double
#else
random = undefined
_trace = undefined
str = undefined
#endif
rand _ = unsafePerformIO random
randoms :: [Double]
randoms =
let inf = undefined : inf
in map rand inf
height :: Int
height = 300
width :: Int
width = 300
diameter :: Int
diameter = 24
chance :: Double
chance = 0.1
asteroids :: IO ()
asteroids =
do
vrocks <- varCreate randomRocks
vship <- varCreate $ div width 2
w <- window Nothing [area := rect (pt 0 0) (sz width height)]
t <- timer w [ interval := 50
, on command := advance vrocks w
]
set w [
on paint := draw vrocks vship
, on leftKey := varUpdate vship (\x -> max 0 (x - 5)) >> return ()
, on rightKey := varUpdate vship (\x -> min width (x + 5)) >> return ()
, on (charKey 'q') := set t [interval :~ \i -> i * 2]
, on (charKey 'w') := (_trace (str "slowdown") >> set t [interval :~ \i -> max 10 (div i 2)])
]
advance :: (Paint w) => Var [[a]] -> w -> IO ()
advance vrocks f =
do
(r : rs) <- varGet vrocks
varSet vrocks rs
repaint f
randomRocks = flatten [] (map fresh randoms)
flatten :: [[a]] -> [[[a]]] -> [[a]]
flatten rocks (t : ts) =
let now = map head rocks
later = filter (not . null) (map tail rocks)
in now : flatten (t ++ later) ts
flatten rocks [] = error "Empty rocks list not expected in function flatten"
fresh :: Double -> [[Point2 Int]]
fresh r
| r > chance = []
| otherwise = [track (floor (fromIntegral width * r / chance))]
track :: Int -> [Point2 Int]
track x = [point x (y - diameter) | y <- [0, 6 .. height + 2 * diameter]]
draw : : [ [ Point2 Int ] ] - > a - > b - > IO ( )
draw :: Var [[Point2 Int]] -> Var Int -> GraphicsContext -> b -> IO ()
draw vrocks vship dc _view =
do
rocks <- varGet vrocks
x <- varGet vship
let
shipLocation = point x (height - 2 * diameter)
positions = head rocks
collisions = map (collide shipLocation) positions
drawShip dc shipLocation
mapM (drawRock dc) (zip positions collisions)
when (or collisions) (return ())
collide :: Point2 Int -> Point2 Int -> Bool
collide pos0 pos1 =
let distance = vecLength (vecBetween pos0 pos1)
in distance <= fromIntegral diameter
drawShip : : DC a - > Point - > IO ( )
drawShip :: GraphicsContext_ a -> Point -> IO ()
drawShip dc pos = drawBitmap dc ship pos True []
drawRock : : DC a - > ( Point , Bool ) - > IO ( )
drawRock :: GraphicsContext_ a -> (Point, Bool) -> IO ()
drawRock dc (pos, collides)=
let rockPicture = if collides then burning else rock
drawBitmap dc rockPicture pos True []
rock :: GraphicsBitmap
rock = bitmap "../resources/rock.ico"
burning :: GraphicsBitmap
burning = bitmap "../resources/burning.ico"
ship :: GraphicsBitmap
ship = bitmap "../resources/ship.ico"
main :: IO ()
main = start asteroids
|
1b0aed04988180673a7ffcb6c85c2d63533c424d5f43841625ed61f1d5ab240d | backtracking/mlpost | types.mli | (**************************************************************************)
(* *)
Copyright ( C ) Johannes Kanig ,
, 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. *)
(* *)
(**************************************************************************)
type color = Concrete_types.color
type name = string
type corner =
[ `Northwest
| `Northeast
| `Southwest
| `Southeast
| `Upleft
| `Upright
| `Lowleft
| `Lowright
| `Upperleft
| `Upperright
| `Lowerleft
| `Lowerright
| `Topleft
| `Topright
| `Bottomleft
| `Bottomright ]
type corner_red = [ `Northwest | `Northeast | `Southwest | `Southeast ]
type hposition = [ `Center | `West | `East | `Left | `Right ]
type vposition =
[ `Center | `North | `South | `Top | `Bot (** deprecated *) | `Bottom ]
type hposition_red = [ `Center | `West | `East ]
type vposition_red = [ `Center | `North | `South ]
type position = [ hposition | vposition | corner ]
type position_red = [ hposition_red | vposition_red | corner_red ]
open Hashcons
type num = float
type point = Point_lib.t
and on_off_node = private On of num | Off of num
and on_off = on_off_node hash_consed
and direction_node = private Vec of point | Curl of float | NoDir
and direction = direction_node hash_consed
and joint_node = private
| JLine
| JCurve
| JCurveNoInflex
| JTension of float * float
| JControls of point * point
and joint = joint_node hash_consed
and knot_node = private {
knot_in : direction;
knot_p : point;
knot_out : direction;
}
and knot = knot_node hash_consed
and metapath_node = private
| MPAConcat of knot * joint * metapath
| MPAKnot of knot
| MPAAppend of metapath * joint * metapath
| MPAofPA of path
(*| MPATransformed of metapath * transform*)
and metapath = metapath_node hash_consed
and path_node = private
| PAofMPA of metapath
| MPACycle of direction * joint * metapath
| PAFullCircle
| PAHalfCircle
| PAQuarterCircle
| PAUnitSquare
| PATransformed of path * transform
| PACutAfter of path * path
| PACutBefore of path * path
| PABuildCycle of path list
| PASub of num * num * path
| PABBox of commandpic
and path = path_node hash_consed
and matrix = Matrix.t
and transform = Matrix.t list
and dash_node = private
| DEvenly
| DWithdots
| DScaled of num * dash
| DShifted of point * dash
| DPattern of on_off list
and dash = dash_node hash_consed
and pen_node = private
| PenCircle
| PenSquare
| PenFromPath of path
| PenTransformed of pen * transform
and pen = pen_node hash_consed
and picture_node = private
| PITex of string
| PITransformed of commandpic * transform
| PIClip of commandpic * path
and picture = picture_node hash_consed
and command_node = private
| CDraw of path * brush
| CFill of path * color option
| CLabel of commandpic * position * point
| CDotLabel of commandpic * position * point
| CExternalImage of string * spec_image
and commandpic_node = private
| Picture of picture
| Command of command
| Seq of commandpic list
| BBox of commandpic * path
and commandpic = commandpic_node hash_consed
and spec_image =
[ `None
| `Width of num (* keep the proportion of the image *)
| `Height of num
| `Inside of num * num (* must be inside a box of this height and width *)
| `Exact of num * num ]
and command = command_node hash_consed
and brush_node = { pen : pen option; dash : dash option; color : color option }
and brush = brush_node hash_consed
(* smart constructors *)
(* knot *)
val mkKnot : direction -> point -> direction -> knot
(* metapath *)
val mkMPAKnot : knot -> metapath
val mkMPAConcat : knot -> joint -> metapath -> metapath
val mkMPAAppend : metapath -> joint -> metapath -> metapath
val mkMPAofPA : path -> metapath
mkMPATransformed : path - > transform - > path
(* path *)
val mkPAofMPA : metapath -> path
val mkPAKnot : knot -> path
val mkPAConcat : knot -> joint -> path -> path
val mkPACycle : direction -> joint -> path -> path
val mkMPACycle : direction -> joint -> metapath -> path
val mkPAAppend : path -> joint -> path -> path
val mkPAFullCircle : path
val mkPAHalfCircle : path
val mkPAQuarterCircle : path
val mkPAUnitSquare : path
val mkPATransformed : path -> transform -> path
val mkPACutAfter : path -> path -> path
val mkPACutBefore : path -> path -> path
val mkPABuildCycle : path list -> path
val mkPASub : num -> num -> path -> path
val mkPABBox : commandpic -> path
(* joint *)
val mkJCurve : joint
val mkJLine : joint
val mkJCurveNoInflex : joint
val mkJTension : float -> float -> joint
val mkJControls : point -> point -> joint
(* direction *)
val mkNoDir : direction
val mkVec : point -> direction
val mkCurl : float -> direction
(* picture *)
val mkPITex : string -> picture
val mkPITransformed : commandpic -> transform -> picture
val mkPIClip : commandpic -> path -> picture
(* command *)
val mkCDraw : path -> brush -> command
val mkCFill : path -> color option -> command
val mkCLabel : commandpic -> position -> point -> command
val mkCDotLabel : commandpic -> position -> point -> command
val mkCExternalImage : string -> spec_image -> command
(* commandpic *)
val mkPicture : picture -> commandpic
val mkCommand : command -> commandpic
val mkSeq : commandpic list -> commandpic
val mkBBox : commandpic -> path -> commandpic
(* dash *)
val mkDEvenly : dash
val mkDWithdots : dash
val mkDScaled : num -> dash -> dash
val mkDShifted : point -> dash -> dash
val mkDPattern : on_off list -> dash
(* pen *)
val mkPenCircle : pen
val mkPenSquare : pen
val mkPenFromPath : path -> pen
val mkPenTransformed : pen -> transform -> pen
(* brush *)
val mkBrush : color option -> pen option -> dash option -> brush
val mkBrushOpt :
brush option -> color option -> pen option -> dash option -> brush
(* on_off *)
val mkOn : num -> on_off
val mkOff : num -> on_off
val pos_reduce : position -> position_red
val corner_reduce : corner -> corner_red
val vreduce : vposition -> vposition_red
val hreduce : hposition -> hposition_red
val opposite_position : position -> position_red
| null | https://raw.githubusercontent.com/backtracking/mlpost/e82db2d3766f24392956478496fa26c8837c1fef/src/types.mli | 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.
************************************************************************
* deprecated
| MPATransformed of metapath * transform
keep the proportion of the image
must be inside a box of this height and width
smart constructors
knot
metapath
path
joint
direction
picture
command
commandpic
dash
pen
brush
on_off | Copyright ( C ) Johannes Kanig ,
, and
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
type color = Concrete_types.color
type name = string
type corner =
[ `Northwest
| `Northeast
| `Southwest
| `Southeast
| `Upleft
| `Upright
| `Lowleft
| `Lowright
| `Upperleft
| `Upperright
| `Lowerleft
| `Lowerright
| `Topleft
| `Topright
| `Bottomleft
| `Bottomright ]
type corner_red = [ `Northwest | `Northeast | `Southwest | `Southeast ]
type hposition = [ `Center | `West | `East | `Left | `Right ]
type vposition =
type hposition_red = [ `Center | `West | `East ]
type vposition_red = [ `Center | `North | `South ]
type position = [ hposition | vposition | corner ]
type position_red = [ hposition_red | vposition_red | corner_red ]
open Hashcons
type num = float
type point = Point_lib.t
and on_off_node = private On of num | Off of num
and on_off = on_off_node hash_consed
and direction_node = private Vec of point | Curl of float | NoDir
and direction = direction_node hash_consed
and joint_node = private
| JLine
| JCurve
| JCurveNoInflex
| JTension of float * float
| JControls of point * point
and joint = joint_node hash_consed
and knot_node = private {
knot_in : direction;
knot_p : point;
knot_out : direction;
}
and knot = knot_node hash_consed
and metapath_node = private
| MPAConcat of knot * joint * metapath
| MPAKnot of knot
| MPAAppend of metapath * joint * metapath
| MPAofPA of path
and metapath = metapath_node hash_consed
and path_node = private
| PAofMPA of metapath
| MPACycle of direction * joint * metapath
| PAFullCircle
| PAHalfCircle
| PAQuarterCircle
| PAUnitSquare
| PATransformed of path * transform
| PACutAfter of path * path
| PACutBefore of path * path
| PABuildCycle of path list
| PASub of num * num * path
| PABBox of commandpic
and path = path_node hash_consed
and matrix = Matrix.t
and transform = Matrix.t list
and dash_node = private
| DEvenly
| DWithdots
| DScaled of num * dash
| DShifted of point * dash
| DPattern of on_off list
and dash = dash_node hash_consed
and pen_node = private
| PenCircle
| PenSquare
| PenFromPath of path
| PenTransformed of pen * transform
and pen = pen_node hash_consed
and picture_node = private
| PITex of string
| PITransformed of commandpic * transform
| PIClip of commandpic * path
and picture = picture_node hash_consed
and command_node = private
| CDraw of path * brush
| CFill of path * color option
| CLabel of commandpic * position * point
| CDotLabel of commandpic * position * point
| CExternalImage of string * spec_image
and commandpic_node = private
| Picture of picture
| Command of command
| Seq of commandpic list
| BBox of commandpic * path
and commandpic = commandpic_node hash_consed
and spec_image =
[ `None
| `Height of num
| `Exact of num * num ]
and command = command_node hash_consed
and brush_node = { pen : pen option; dash : dash option; color : color option }
and brush = brush_node hash_consed
val mkKnot : direction -> point -> direction -> knot
val mkMPAKnot : knot -> metapath
val mkMPAConcat : knot -> joint -> metapath -> metapath
val mkMPAAppend : metapath -> joint -> metapath -> metapath
val mkMPAofPA : path -> metapath
mkMPATransformed : path - > transform - > path
val mkPAofMPA : metapath -> path
val mkPAKnot : knot -> path
val mkPAConcat : knot -> joint -> path -> path
val mkPACycle : direction -> joint -> path -> path
val mkMPACycle : direction -> joint -> metapath -> path
val mkPAAppend : path -> joint -> path -> path
val mkPAFullCircle : path
val mkPAHalfCircle : path
val mkPAQuarterCircle : path
val mkPAUnitSquare : path
val mkPATransformed : path -> transform -> path
val mkPACutAfter : path -> path -> path
val mkPACutBefore : path -> path -> path
val mkPABuildCycle : path list -> path
val mkPASub : num -> num -> path -> path
val mkPABBox : commandpic -> path
val mkJCurve : joint
val mkJLine : joint
val mkJCurveNoInflex : joint
val mkJTension : float -> float -> joint
val mkJControls : point -> point -> joint
val mkNoDir : direction
val mkVec : point -> direction
val mkCurl : float -> direction
val mkPITex : string -> picture
val mkPITransformed : commandpic -> transform -> picture
val mkPIClip : commandpic -> path -> picture
val mkCDraw : path -> brush -> command
val mkCFill : path -> color option -> command
val mkCLabel : commandpic -> position -> point -> command
val mkCDotLabel : commandpic -> position -> point -> command
val mkCExternalImage : string -> spec_image -> command
val mkPicture : picture -> commandpic
val mkCommand : command -> commandpic
val mkSeq : commandpic list -> commandpic
val mkBBox : commandpic -> path -> commandpic
val mkDEvenly : dash
val mkDWithdots : dash
val mkDScaled : num -> dash -> dash
val mkDShifted : point -> dash -> dash
val mkDPattern : on_off list -> dash
val mkPenCircle : pen
val mkPenSquare : pen
val mkPenFromPath : path -> pen
val mkPenTransformed : pen -> transform -> pen
val mkBrush : color option -> pen option -> dash option -> brush
val mkBrushOpt :
brush option -> color option -> pen option -> dash option -> brush
val mkOn : num -> on_off
val mkOff : num -> on_off
val pos_reduce : position -> position_red
val corner_reduce : corner -> corner_red
val vreduce : vposition -> vposition_red
val hreduce : hposition -> hposition_red
val opposite_position : position -> position_red
|
6fef88f1aca461e6e4ae0ae80240fe89c53ee8496981a32d8e1d202960345bff | callum-oakley/advent-of-code | 05.clj | (ns aoc.2018.05
(:require
[clojure.test :refer [deftest is]]))
(defn parse [s]
(map int s))
(defn react [polymer]
(reduce (fn [acc x]
(let [y (first acc)]
uppercase and lowercase differ by 32
(if (and y (= 32 (abs (- x y))))
(rest acc)
(cons x acc))))
nil
polymer))
(defn part-1 [polymer]
(->> polymer react count))
(defn part-2 [polymer]
(let [polymer (->> polymer react)]
(apply min (map #(count (react (remove #{% (+ % 32)} polymer)))
(range 65 91)))))
(deftest test-example
(is (= 10 (count (react (map int "dabAcCaCBAcCcaDA"))))))
| null | https://raw.githubusercontent.com/callum-oakley/advent-of-code/da5233fc0fd3d3773d35ee747fd837c59c2b1c04/src/aoc/2018/05.clj | clojure | (ns aoc.2018.05
(:require
[clojure.test :refer [deftest is]]))
(defn parse [s]
(map int s))
(defn react [polymer]
(reduce (fn [acc x]
(let [y (first acc)]
uppercase and lowercase differ by 32
(if (and y (= 32 (abs (- x y))))
(rest acc)
(cons x acc))))
nil
polymer))
(defn part-1 [polymer]
(->> polymer react count))
(defn part-2 [polymer]
(let [polymer (->> polymer react)]
(apply min (map #(count (react (remove #{% (+ % 32)} polymer)))
(range 65 91)))))
(deftest test-example
(is (= 10 (count (react (map int "dabAcCaCBAcCcaDA"))))))
| |
2241f47a8b24d17ac5dc5d2700529f2d1238982e9cad5d497ee434c563c07700 | TrustInSoft/tis-kernel | bag.ml | (**************************************************************************)
(* *)
This file is part of .
(* *)
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
(* *)
is released under GPLv2
(* *)
(**************************************************************************)
(**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
(* ------------------------------------------------------------------------ *)
(* --- List with constant-time concat --- *)
(* ------------------------------------------------------------------------ *)
type 'a t =
| Empty
| Elt of 'a
| Add of 'a * 'a t
| App of 'a t * 'a
| List of 'a list
| Concat of 'a t * 'a t
let empty = Empty
let elt x = Elt x
let length t =
let rec scan n = function
| Empty -> n
| Elt _ -> succ n
| Add(_,t) | App(t,_) -> scan (succ n) t
| List xs -> n + List.length xs
| Concat(a,b) -> scan (scan n a) b
in scan 0 t
let add x = function
| Empty -> Elt x
| t -> Add(x,t)
let append t x = match t with
| Empty -> Elt x
| t -> App(t,x)
let list = function
| [] -> Empty
| [x] -> Elt x
| xs -> List xs
let concat a b =
match a,b with
| Empty,c | c,Empty -> c
| Elt x,t -> Add(x,t)
| t,Elt x -> App(t,x)
1 - time
| _ -> Concat(a,b)
let rec ulist = function
| [] -> Empty
| x::xs -> concat x (ulist xs)
let rec map f = function
| Empty -> Empty
| Elt x -> Elt (f x)
| Add(x,t) -> Add(f x,map f t)
| App(t,x) -> App(map f t,f x)
| List xs -> List(List.map f xs)
| Concat(a,b) -> Concat(map f a,map f b)
let rec umap f = function
| Empty -> Empty
| Elt x -> f x
| Add(x,t) -> concat (f x) (umap f t)
| App(t,x) -> concat (umap f t) (f x)
| List xs -> umap_list f xs
| Concat(a,b) -> concat (umap f a) (umap f b)
and umap_list f = function
| [] -> Empty
| x::xs -> concat (f x) (umap_list f xs)
let rec iter f = function
| Empty -> ()
| Elt x -> f x
| Add(x,t) -> f x ; iter f t
| App(t,x) -> iter f t ; f x
| List xs -> List.iter f xs
| Concat(a,b) -> iter f a ; iter f b
let rec fold_left f w = function
| Empty -> w
| Elt x -> f w x
| Add(x,t) -> fold_left f (f w x) t
| App(t,x) -> f (fold_left f w t) x
| List xs -> List.fold_left f w xs
| Concat(a,b) -> fold_left f (fold_left f w a) b
let rec fold_right f t w = match t with
| Empty -> w
| Elt x -> f x w
| Add(x,t) -> f x (fold_right f t w)
| App(t,x) -> fold_right f t (f x w)
| List xs -> List.fold_right f xs w
| Concat(a,b) -> fold_right f a (fold_right f b w)
let rec filter f = function
| Empty -> Empty
| Elt x as e -> if f x then e else Empty
| Add(x,ts) -> if f x then add x (filter f ts) else filter f ts
| App(ts,x) -> let ts = filter f ts in if f x then append ts x else ts
| List xs -> list (List.filter f xs)
| Concat(a,b) -> concat (filter f a) (filter f b)
let rec partition f = function
| Empty -> Empty , Empty
| Elt x as e -> if f x then e,Empty else Empty,e
| Add(x,ts) ->
let pos,neg = partition f ts in
if f x then add x pos , neg else pos , add x neg
| App(ts,x) ->
let ok = f x in
let pos,neg = partition f ts in
if ok then append pos x , neg else pos , append neg x
| List xs ->
let pos,neg = List.partition f xs in
list pos , list neg
| Concat(a,b) ->
let apos,aneg = partition f a in
let bpos,bneg = partition f b in
concat apos bpos , concat aneg bneg
let rec is_empty = function
| Empty | List [] -> true
| Add _ | App _ | Elt _ | List _ -> false
| Concat(a,b) -> is_empty a && is_empty b
let rec singleton = function
| Elt x | List [x] -> Some x
| Empty | List _ -> None
| Add(x,t) | App(t,x) -> if is_empty t then Some x else None
| Concat(a,b) ->
begin match singleton a with
| Some x -> if is_empty b then Some x else None
| None -> if is_empty a then singleton b else None
end
let rec collect t xs =
match t with
| Elt x -> x :: xs
| Empty -> xs
| Add(x,t) -> x :: collect t xs
| App(t,x) -> collect t (x::xs)
| List ys -> ys @ xs
| Concat(a,b) -> collect a (collect b xs)
let elements t = collect t []
| null | https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/libraries/utils/bag.ml | ocaml | ************************************************************************
************************************************************************
************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
------------------------------------------------------------------------
--- List with constant-time concat ---
------------------------------------------------------------------------ | This file is part of .
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
is released under GPLv2
This file is part of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
type 'a t =
| Empty
| Elt of 'a
| Add of 'a * 'a t
| App of 'a t * 'a
| List of 'a list
| Concat of 'a t * 'a t
let empty = Empty
let elt x = Elt x
let length t =
let rec scan n = function
| Empty -> n
| Elt _ -> succ n
| Add(_,t) | App(t,_) -> scan (succ n) t
| List xs -> n + List.length xs
| Concat(a,b) -> scan (scan n a) b
in scan 0 t
let add x = function
| Empty -> Elt x
| t -> Add(x,t)
let append t x = match t with
| Empty -> Elt x
| t -> App(t,x)
let list = function
| [] -> Empty
| [x] -> Elt x
| xs -> List xs
let concat a b =
match a,b with
| Empty,c | c,Empty -> c
| Elt x,t -> Add(x,t)
| t,Elt x -> App(t,x)
1 - time
| _ -> Concat(a,b)
let rec ulist = function
| [] -> Empty
| x::xs -> concat x (ulist xs)
let rec map f = function
| Empty -> Empty
| Elt x -> Elt (f x)
| Add(x,t) -> Add(f x,map f t)
| App(t,x) -> App(map f t,f x)
| List xs -> List(List.map f xs)
| Concat(a,b) -> Concat(map f a,map f b)
let rec umap f = function
| Empty -> Empty
| Elt x -> f x
| Add(x,t) -> concat (f x) (umap f t)
| App(t,x) -> concat (umap f t) (f x)
| List xs -> umap_list f xs
| Concat(a,b) -> concat (umap f a) (umap f b)
and umap_list f = function
| [] -> Empty
| x::xs -> concat (f x) (umap_list f xs)
let rec iter f = function
| Empty -> ()
| Elt x -> f x
| Add(x,t) -> f x ; iter f t
| App(t,x) -> iter f t ; f x
| List xs -> List.iter f xs
| Concat(a,b) -> iter f a ; iter f b
let rec fold_left f w = function
| Empty -> w
| Elt x -> f w x
| Add(x,t) -> fold_left f (f w x) t
| App(t,x) -> f (fold_left f w t) x
| List xs -> List.fold_left f w xs
| Concat(a,b) -> fold_left f (fold_left f w a) b
let rec fold_right f t w = match t with
| Empty -> w
| Elt x -> f x w
| Add(x,t) -> f x (fold_right f t w)
| App(t,x) -> fold_right f t (f x w)
| List xs -> List.fold_right f xs w
| Concat(a,b) -> fold_right f a (fold_right f b w)
let rec filter f = function
| Empty -> Empty
| Elt x as e -> if f x then e else Empty
| Add(x,ts) -> if f x then add x (filter f ts) else filter f ts
| App(ts,x) -> let ts = filter f ts in if f x then append ts x else ts
| List xs -> list (List.filter f xs)
| Concat(a,b) -> concat (filter f a) (filter f b)
let rec partition f = function
| Empty -> Empty , Empty
| Elt x as e -> if f x then e,Empty else Empty,e
| Add(x,ts) ->
let pos,neg = partition f ts in
if f x then add x pos , neg else pos , add x neg
| App(ts,x) ->
let ok = f x in
let pos,neg = partition f ts in
if ok then append pos x , neg else pos , append neg x
| List xs ->
let pos,neg = List.partition f xs in
list pos , list neg
| Concat(a,b) ->
let apos,aneg = partition f a in
let bpos,bneg = partition f b in
concat apos bpos , concat aneg bneg
let rec is_empty = function
| Empty | List [] -> true
| Add _ | App _ | Elt _ | List _ -> false
| Concat(a,b) -> is_empty a && is_empty b
let rec singleton = function
| Elt x | List [x] -> Some x
| Empty | List _ -> None
| Add(x,t) | App(t,x) -> if is_empty t then Some x else None
| Concat(a,b) ->
begin match singleton a with
| Some x -> if is_empty b then Some x else None
| None -> if is_empty a then singleton b else None
end
let rec collect t xs =
match t with
| Elt x -> x :: xs
| Empty -> xs
| Add(x,t) -> x :: collect t xs
| App(t,x) -> collect t (x::xs)
| List ys -> ys @ xs
| Concat(a,b) -> collect a (collect b xs)
let elements t = collect t []
|
370bac87c63e29bc9a23d652c0daabbb9c9af896b2308606e30db43cdd72884c | khmelevskii/emotion-cljs | styled.cljs | (ns helix-emotion.components.button.styled
(:require
[emotion.core :refer [defcss-when defstyled]]))
(defcss-when --color-primary [color]
(= color "primary")
{:color "#fff"
:background-color "#006cda"
:&:hover {:background-color "#3690df"}})
(defcss-when --color-secondary [color]
(= color "secondary")
{:color "#fff"
:background-color "#068d63"
:&:hover {:background-color "#25c186"}})
(defstyled button :button
{:font-family "Arial"
:font-size 18
:border :none
:padding "8px 16px"
:border-radius 4
:cursor :pointer}
--color-primary
--color-secondary)
| null | https://raw.githubusercontent.com/khmelevskii/emotion-cljs/4baaccfa19c0808e11f3a8e838f62ac6382b8860/examples/helix-emotion/src/main/helix_emotion/components/button/styled.cljs | clojure | (ns helix-emotion.components.button.styled
(:require
[emotion.core :refer [defcss-when defstyled]]))
(defcss-when --color-primary [color]
(= color "primary")
{:color "#fff"
:background-color "#006cda"
:&:hover {:background-color "#3690df"}})
(defcss-when --color-secondary [color]
(= color "secondary")
{:color "#fff"
:background-color "#068d63"
:&:hover {:background-color "#25c186"}})
(defstyled button :button
{:font-family "Arial"
:font-size 18
:border :none
:padding "8px 16px"
:border-radius 4
:cursor :pointer}
--color-primary
--color-secondary)
| |
22bf1019ad6f07196b451867a108b85c85b7c5af4b1a288e6d6579d18c0ac741 | dhess/sicp-solutions | ex2.35.scm | (define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))))
(define (count-leaves t)
(accumulate (lambda (leaves total) (+ leaves total))
0
(map (lambda (sub-tree)
(if (pair? sub-tree)
(count-leaves sub-tree)
1))
t)))
| null | https://raw.githubusercontent.com/dhess/sicp-solutions/2cf78db98917e9cb1252efda76fddc8e45fe4140/chap2/ex2.35.scm | scheme | (define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))))
(define (count-leaves t)
(accumulate (lambda (leaves total) (+ leaves total))
0
(map (lambda (sub-tree)
(if (pair? sub-tree)
(count-leaves sub-tree)
1))
t)))
| |
b9ef93e4547cad3b9b6e2effdf074ad1ec590efe5effd86f9ba08d62bac57947 | coco-team/lustrec | compiler_common.ml | (********************************************************************)
(* *)
The LustreC compiler toolset / The LustreC Development Team
Copyright 2012 - -- ONERA - CNRS - INPT
(* *)
(* LustreC is free software, distributed WITHOUT ANY WARRANTY *)
(* under the terms of the GNU Lesser General Public License *)
version 2.1 .
(* *)
(********************************************************************)
open Utils
open Format
open Lustre_types
open Corelang
let check_main () =
if !Options.main_node = "" then
begin
eprintf "Code generation error: %a@." Error.pp_error_msg Error.No_main_specified;
raise (Error (Location.dummy_loc, Error.No_main_specified))
end
let create_dest_dir () =
begin
if not (Sys.file_exists !Options.dest_dir) then
begin
Log.report ~level:1 (fun fmt -> fprintf fmt ".. creating destination directory@ ");
Unix.mkdir !Options.dest_dir (Unix.stat ".").Unix.st_perm
end;
if (Unix.stat !Options.dest_dir).Unix.st_kind <> Unix.S_DIR then
begin
eprintf "Failure: destination %s is not a directory.@.@." !Options.dest_dir;
exit 1
end
end
(* Loading Lusi file and filling type tables with parsed
functions/nodes *)
let parse_header own filename =
Location.set_input filename;
let h_in = open_in filename in
let lexbuf = Lexing.from_channel h_in in
Location.init lexbuf filename;
(* Parsing *)
Log.report ~level:1 (fun fmt -> fprintf fmt ".. parsing header file %s@ " filename);
try
let header = Parse.header Parser_lustre.header Lexer_lustre.token lexbuf in
ignore ( Modules.load_header ISet.empty header ) ;
close_in h_in;
header
with
| (Parse.Error err) as exc ->
Parse.report_error err;
raise exc
| Corelang.Error (loc, err) as exc -> (
eprintf "Parsing error: %a%a@."
Error.pp_error_msg err
Location.pp_loc loc;
raise exc
)
let parse_source source_name =
(* Loading the input file *)
Location.set_input source_name;
let s_in = open_in source_name in
let lexbuf = Lexing.from_channel s_in in
Location.init lexbuf source_name;
(* Parsing *)
Log.report ~level:1
(fun fmt -> fprintf fmt ".. parsing source file %s@ " source_name);
try
let prog = Parse.prog Parser_lustre.prog Lexer_lustre.token lexbuf in
ignore ( Modules.load_program ISet.empty prog ) ;
close_in s_in;
prog
with
| (Parse.Error err) as exc ->
Parse.report_error err;
raise exc
| Corelang.Error (loc, err) as exc ->
eprintf "Parsing error: %a%a@."
Error.pp_error_msg err
Location.pp_loc loc;
raise exc
let expand_automata decls =
Log.report ~level:1 (fun fmt -> fprintf fmt ".. expanding automata@ ");
try
Automata.expand_decls decls
with (Corelang.Error (loc, err)) as exc ->
eprintf "Automata error: %a%a@."
Error.pp_error_msg err
Location.pp_loc loc;
raise exc
let check_stateless_decls decls =
Log.report ~level:1 (fun fmt -> fprintf fmt ".. checking stateless/stateful status@ ");
try
Stateless.check_prog decls
with (Stateless.Error (loc, err)) as exc ->
eprintf "Stateless status error: %a%a@."
Stateless.pp_error err
Location.pp_loc loc;
raise exc
let force_stateful_decls decls =
Log.report ~level:1 (fun fmt -> fprintf fmt ".. forcing stateful status@ ");
try
Stateless.force_prog decls
with (Stateless.Error (loc, err)) as exc ->
eprintf "Stateless status error: %a%a@."
Stateless.pp_error err
Location.pp_loc loc;
raise exc
let type_decls env decls =
Log.report ~level:1 (fun fmt -> fprintf fmt ".. typing@ ");
let new_env =
begin
try
Typing.type_prog env decls
with (Types.Error (loc,err)) as exc ->
eprintf "Typing error: %a%a@."
Types.pp_error err
Location.pp_loc loc;
raise exc
end
in
if !Options.print_types || !Options.verbose_level > 2 then
Log.report ~level:1 (fun fmt -> fprintf fmt "@[<v 2> %a@]@ " Corelang.pp_prog_type decls);
new_env
let clock_decls env decls =
Log.report ~level:1 (fun fmt -> fprintf fmt ".. clock calculus@ ");
let new_env =
begin
try
Clock_calculus.clock_prog env decls
with (Clocks.Error (loc,err)) as exc ->
eprintf "Clock calculus error: %a%a@." Clocks.pp_error err Location.pp_loc loc;
raise exc
end
in
if !Options.print_clocks || !Options.verbose_level > 2 then
Log.report ~level:1 (fun fmt -> fprintf fmt "@[<v 2> %a@]@ " Corelang.pp_prog_clock decls);
new_env
let check_top_decls header =
let new_tenv = type_decls Basic_library.type_env header in (* Typing *)
let new_cenv = clock_decls Basic_library.clock_env header in (* Clock calculus *)
header, new_tenv, new_cenv
let get_envs_from_const const_decl (ty_env, ck_env) =
(Env.add_value ty_env const_decl.const_id const_decl.const_type,
Env.add_value ck_env const_decl.const_id (Clocks.new_var true))
let get_envs_from_consts const_decls (ty_env, ck_env) =
List.fold_right get_envs_from_const const_decls (ty_env, ck_env)
let rec get_envs_from_top_decl (ty_env, ck_env) top_decl =
match top_decl.top_decl_desc with
| Node nd -> (Env.add_value ty_env nd.node_id nd.node_type,
Env.add_value ck_env nd.node_id nd.node_clock)
| ImportedNode ind -> (Env.add_value ty_env ind.nodei_id ind.nodei_type,
Env.add_value ck_env ind.nodei_id ind.nodei_clock)
| Const c -> get_envs_from_const c (ty_env, ck_env)
| TypeDef _ -> List.fold_left get_envs_from_top_decl (ty_env, ck_env) (consts_of_enum_type top_decl)
| Open _ -> (ty_env, ck_env)
(* get type and clock environments from a header *)
let get_envs_from_top_decls header =
List.fold_left get_envs_from_top_decl (Env.initial, Env.initial) header
List.fold_right
( fun top_decl ( ty_env , ck_env ) - >
match top_decl.top_decl_desc with
| Node nd - > ( Env.add_value ty_env nd.node_id nd.node_type ,
Env.add_value ck_env nd.node_id nd.node_clock )
| ImportedNode ind - > ( Env.add_value ty_env ind.nodei_id ind.nodei_type ,
Env.add_value ck_env ind.nodei_id ind.nodei_clock )
| Const c - > get_envs_from_const c ( ty_env , ck_env )
| TypeDef _ - > List.fold_left ( fun envs top - > consts_of_enum_type top_decl
| Open _ - > ( ty_env , ck_env ) )
header
( Env.initial , Env.initial )
List.fold_right
(fun top_decl (ty_env, ck_env) ->
match top_decl.top_decl_desc with
| Node nd -> (Env.add_value ty_env nd.node_id nd.node_type,
Env.add_value ck_env nd.node_id nd.node_clock)
| ImportedNode ind -> (Env.add_value ty_env ind.nodei_id ind.nodei_type,
Env.add_value ck_env ind.nodei_id ind.nodei_clock)
| Const c -> get_envs_from_const c (ty_env, ck_env)
| TypeDef _ -> List.fold_left (fun envs top -> consts_of_enum_type top_decl
| Open _ -> (ty_env, ck_env))
header
(Env.initial, Env.initial)
*)
let generate_lusic_header destname lusic_ext =
match !Options.output with
| "C" -> C_backend_lusic.print_lusic_to_h destname lusic_ext
| _ -> ()
let check_compatibility (prog, computed_types_env, computed_clocks_env) (header, declared_types_env, declared_clocks_env) =
try
(* checking defined types are compatible with declared types*)
Typing.check_typedef_compat header;
(* checking type compatibility with computed types*)
Typing.check_env_compat header declared_types_env computed_types_env;
(* checking clocks compatibility with computed clocks*)
Clock_calculus.check_env_compat header declared_clocks_env computed_clocks_env;
(* checking stateless status compatibility *)
Stateless.check_compat header
with
| (Types.Error (loc,err)) as exc ->
eprintf "Type mismatch between computed type and declared type in lustre interface file: %a%a@."
Types.pp_error err
Location.pp_loc loc;
raise exc
| Clocks.Error (loc, err) as exc ->
eprintf "Clock mismatch between computed clock and declared clock in lustre interface file: %a%a@."
Clocks.pp_error err
Location.pp_loc loc;
raise exc
| Stateless.Error (loc, err) as exc ->
eprintf "Stateless status mismatch between defined status and declared status in lustre interface file: %a%a@."
Stateless.pp_error err
Location.pp_loc loc;
raise exc
let is_stateful topdecl =
match topdecl.top_decl_desc with
| Node nd -> (match nd.node_stateless with Some b -> not b | None -> not nd.node_dec_stateless)
| ImportedNode nd -> not nd.nodei_stateless
| _ -> false
let rec import_dependencies prog =
Log.report ~level:1 (fun fmt -> fprintf fmt "@[<v 4>.. extracting dependencies");
let dependencies = Corelang.get_dependencies prog in
let deps =
List.fold_left
(fun (compilation_dep, type_env, clock_env) dep ->
let (local, s) = Corelang.dependency_of_top dep in
let basename = Options_management.name_dependency (local, s) in
Log.report ~level:1 (fun fmt -> Format.fprintf fmt "@ Library %s@ " basename);
let lusic = Modules.import_dependency dep.top_decl_loc (local, s) in
(*Log.report ~level:1 (fun fmt -> Format.fprintf fmt "");*)
let lusic_deps, type_env', clock_env' = import_dependencies lusic.Lusic.contents in
let type_env = Env.overwrite type_env type_env' in
let clock_env = Env.overwrite clock_env clock_env' in
let (lusi_type_env, lusi_clock_env) = get_envs_from_top_decls lusic.Lusic.contents in
let is_stateful = List.exists is_stateful lusic.Lusic.contents in
let new_dep = Dep (local, s, lusic.Lusic.contents, is_stateful ) in
new_dep::lusic_deps@compilation_dep,
Env.overwrite type_env lusi_type_env,
Env.overwrite clock_env lusi_clock_env)
([], Basic_library.type_env, Basic_library.clock_env)
dependencies in
begin
Log.report ~level:1 (fun fmt -> fprintf fmt "@]@ ");
deps
end
let track_exception () =
if !Options.track_exceptions
then (Printexc.print_backtrace stdout; flush stdout)
else ()
let update_vdecl_parents_prog prog =
let update_vdecl_parents parent v =
v.var_parent_nodeid <- Some parent
in
List.iter (
fun top -> match top.top_decl_desc with
| Node nd ->
List.iter
(update_vdecl_parents nd.node_id)
(nd.node_inputs @ nd.node_outputs @ nd.node_locals )
| ImportedNode ind ->
List.iter
(update_vdecl_parents ind.nodei_id)
(ind.nodei_inputs @ ind.nodei_outputs )
| _ -> ()
) prog
| null | https://raw.githubusercontent.com/coco-team/lustrec/b21f9820df97e661633cd4418fdab68a6c6ca67d/src/compiler_common.ml | ocaml | ******************************************************************
LustreC is free software, distributed WITHOUT ANY WARRANTY
under the terms of the GNU Lesser General Public License
******************************************************************
Loading Lusi file and filling type tables with parsed
functions/nodes
Parsing
Loading the input file
Parsing
Typing
Clock calculus
get type and clock environments from a header
checking defined types are compatible with declared types
checking type compatibility with computed types
checking clocks compatibility with computed clocks
checking stateless status compatibility
Log.report ~level:1 (fun fmt -> Format.fprintf fmt ""); | The LustreC compiler toolset / The LustreC Development Team
Copyright 2012 - -- ONERA - CNRS - INPT
version 2.1 .
open Utils
open Format
open Lustre_types
open Corelang
let check_main () =
if !Options.main_node = "" then
begin
eprintf "Code generation error: %a@." Error.pp_error_msg Error.No_main_specified;
raise (Error (Location.dummy_loc, Error.No_main_specified))
end
let create_dest_dir () =
begin
if not (Sys.file_exists !Options.dest_dir) then
begin
Log.report ~level:1 (fun fmt -> fprintf fmt ".. creating destination directory@ ");
Unix.mkdir !Options.dest_dir (Unix.stat ".").Unix.st_perm
end;
if (Unix.stat !Options.dest_dir).Unix.st_kind <> Unix.S_DIR then
begin
eprintf "Failure: destination %s is not a directory.@.@." !Options.dest_dir;
exit 1
end
end
let parse_header own filename =
Location.set_input filename;
let h_in = open_in filename in
let lexbuf = Lexing.from_channel h_in in
Location.init lexbuf filename;
Log.report ~level:1 (fun fmt -> fprintf fmt ".. parsing header file %s@ " filename);
try
let header = Parse.header Parser_lustre.header Lexer_lustre.token lexbuf in
ignore ( Modules.load_header ISet.empty header ) ;
close_in h_in;
header
with
| (Parse.Error err) as exc ->
Parse.report_error err;
raise exc
| Corelang.Error (loc, err) as exc -> (
eprintf "Parsing error: %a%a@."
Error.pp_error_msg err
Location.pp_loc loc;
raise exc
)
let parse_source source_name =
Location.set_input source_name;
let s_in = open_in source_name in
let lexbuf = Lexing.from_channel s_in in
Location.init lexbuf source_name;
Log.report ~level:1
(fun fmt -> fprintf fmt ".. parsing source file %s@ " source_name);
try
let prog = Parse.prog Parser_lustre.prog Lexer_lustre.token lexbuf in
ignore ( Modules.load_program ISet.empty prog ) ;
close_in s_in;
prog
with
| (Parse.Error err) as exc ->
Parse.report_error err;
raise exc
| Corelang.Error (loc, err) as exc ->
eprintf "Parsing error: %a%a@."
Error.pp_error_msg err
Location.pp_loc loc;
raise exc
let expand_automata decls =
Log.report ~level:1 (fun fmt -> fprintf fmt ".. expanding automata@ ");
try
Automata.expand_decls decls
with (Corelang.Error (loc, err)) as exc ->
eprintf "Automata error: %a%a@."
Error.pp_error_msg err
Location.pp_loc loc;
raise exc
let check_stateless_decls decls =
Log.report ~level:1 (fun fmt -> fprintf fmt ".. checking stateless/stateful status@ ");
try
Stateless.check_prog decls
with (Stateless.Error (loc, err)) as exc ->
eprintf "Stateless status error: %a%a@."
Stateless.pp_error err
Location.pp_loc loc;
raise exc
let force_stateful_decls decls =
Log.report ~level:1 (fun fmt -> fprintf fmt ".. forcing stateful status@ ");
try
Stateless.force_prog decls
with (Stateless.Error (loc, err)) as exc ->
eprintf "Stateless status error: %a%a@."
Stateless.pp_error err
Location.pp_loc loc;
raise exc
let type_decls env decls =
Log.report ~level:1 (fun fmt -> fprintf fmt ".. typing@ ");
let new_env =
begin
try
Typing.type_prog env decls
with (Types.Error (loc,err)) as exc ->
eprintf "Typing error: %a%a@."
Types.pp_error err
Location.pp_loc loc;
raise exc
end
in
if !Options.print_types || !Options.verbose_level > 2 then
Log.report ~level:1 (fun fmt -> fprintf fmt "@[<v 2> %a@]@ " Corelang.pp_prog_type decls);
new_env
let clock_decls env decls =
Log.report ~level:1 (fun fmt -> fprintf fmt ".. clock calculus@ ");
let new_env =
begin
try
Clock_calculus.clock_prog env decls
with (Clocks.Error (loc,err)) as exc ->
eprintf "Clock calculus error: %a%a@." Clocks.pp_error err Location.pp_loc loc;
raise exc
end
in
if !Options.print_clocks || !Options.verbose_level > 2 then
Log.report ~level:1 (fun fmt -> fprintf fmt "@[<v 2> %a@]@ " Corelang.pp_prog_clock decls);
new_env
let check_top_decls header =
header, new_tenv, new_cenv
let get_envs_from_const const_decl (ty_env, ck_env) =
(Env.add_value ty_env const_decl.const_id const_decl.const_type,
Env.add_value ck_env const_decl.const_id (Clocks.new_var true))
let get_envs_from_consts const_decls (ty_env, ck_env) =
List.fold_right get_envs_from_const const_decls (ty_env, ck_env)
let rec get_envs_from_top_decl (ty_env, ck_env) top_decl =
match top_decl.top_decl_desc with
| Node nd -> (Env.add_value ty_env nd.node_id nd.node_type,
Env.add_value ck_env nd.node_id nd.node_clock)
| ImportedNode ind -> (Env.add_value ty_env ind.nodei_id ind.nodei_type,
Env.add_value ck_env ind.nodei_id ind.nodei_clock)
| Const c -> get_envs_from_const c (ty_env, ck_env)
| TypeDef _ -> List.fold_left get_envs_from_top_decl (ty_env, ck_env) (consts_of_enum_type top_decl)
| Open _ -> (ty_env, ck_env)
let get_envs_from_top_decls header =
List.fold_left get_envs_from_top_decl (Env.initial, Env.initial) header
List.fold_right
( fun top_decl ( ty_env , ck_env ) - >
match top_decl.top_decl_desc with
| Node nd - > ( Env.add_value ty_env nd.node_id nd.node_type ,
Env.add_value ck_env nd.node_id nd.node_clock )
| ImportedNode ind - > ( Env.add_value ty_env ind.nodei_id ind.nodei_type ,
Env.add_value ck_env ind.nodei_id ind.nodei_clock )
| Const c - > get_envs_from_const c ( ty_env , ck_env )
| TypeDef _ - > List.fold_left ( fun envs top - > consts_of_enum_type top_decl
| Open _ - > ( ty_env , ck_env ) )
header
( Env.initial , Env.initial )
List.fold_right
(fun top_decl (ty_env, ck_env) ->
match top_decl.top_decl_desc with
| Node nd -> (Env.add_value ty_env nd.node_id nd.node_type,
Env.add_value ck_env nd.node_id nd.node_clock)
| ImportedNode ind -> (Env.add_value ty_env ind.nodei_id ind.nodei_type,
Env.add_value ck_env ind.nodei_id ind.nodei_clock)
| Const c -> get_envs_from_const c (ty_env, ck_env)
| TypeDef _ -> List.fold_left (fun envs top -> consts_of_enum_type top_decl
| Open _ -> (ty_env, ck_env))
header
(Env.initial, Env.initial)
*)
let generate_lusic_header destname lusic_ext =
match !Options.output with
| "C" -> C_backend_lusic.print_lusic_to_h destname lusic_ext
| _ -> ()
let check_compatibility (prog, computed_types_env, computed_clocks_env) (header, declared_types_env, declared_clocks_env) =
try
Typing.check_typedef_compat header;
Typing.check_env_compat header declared_types_env computed_types_env;
Clock_calculus.check_env_compat header declared_clocks_env computed_clocks_env;
Stateless.check_compat header
with
| (Types.Error (loc,err)) as exc ->
eprintf "Type mismatch between computed type and declared type in lustre interface file: %a%a@."
Types.pp_error err
Location.pp_loc loc;
raise exc
| Clocks.Error (loc, err) as exc ->
eprintf "Clock mismatch between computed clock and declared clock in lustre interface file: %a%a@."
Clocks.pp_error err
Location.pp_loc loc;
raise exc
| Stateless.Error (loc, err) as exc ->
eprintf "Stateless status mismatch between defined status and declared status in lustre interface file: %a%a@."
Stateless.pp_error err
Location.pp_loc loc;
raise exc
let is_stateful topdecl =
match topdecl.top_decl_desc with
| Node nd -> (match nd.node_stateless with Some b -> not b | None -> not nd.node_dec_stateless)
| ImportedNode nd -> not nd.nodei_stateless
| _ -> false
let rec import_dependencies prog =
Log.report ~level:1 (fun fmt -> fprintf fmt "@[<v 4>.. extracting dependencies");
let dependencies = Corelang.get_dependencies prog in
let deps =
List.fold_left
(fun (compilation_dep, type_env, clock_env) dep ->
let (local, s) = Corelang.dependency_of_top dep in
let basename = Options_management.name_dependency (local, s) in
Log.report ~level:1 (fun fmt -> Format.fprintf fmt "@ Library %s@ " basename);
let lusic = Modules.import_dependency dep.top_decl_loc (local, s) in
let lusic_deps, type_env', clock_env' = import_dependencies lusic.Lusic.contents in
let type_env = Env.overwrite type_env type_env' in
let clock_env = Env.overwrite clock_env clock_env' in
let (lusi_type_env, lusi_clock_env) = get_envs_from_top_decls lusic.Lusic.contents in
let is_stateful = List.exists is_stateful lusic.Lusic.contents in
let new_dep = Dep (local, s, lusic.Lusic.contents, is_stateful ) in
new_dep::lusic_deps@compilation_dep,
Env.overwrite type_env lusi_type_env,
Env.overwrite clock_env lusi_clock_env)
([], Basic_library.type_env, Basic_library.clock_env)
dependencies in
begin
Log.report ~level:1 (fun fmt -> fprintf fmt "@]@ ");
deps
end
let track_exception () =
if !Options.track_exceptions
then (Printexc.print_backtrace stdout; flush stdout)
else ()
let update_vdecl_parents_prog prog =
let update_vdecl_parents parent v =
v.var_parent_nodeid <- Some parent
in
List.iter (
fun top -> match top.top_decl_desc with
| Node nd ->
List.iter
(update_vdecl_parents nd.node_id)
(nd.node_inputs @ nd.node_outputs @ nd.node_locals )
| ImportedNode ind ->
List.iter
(update_vdecl_parents ind.nodei_id)
(ind.nodei_inputs @ ind.nodei_outputs )
| _ -> ()
) prog
|
2cfb18f6b18efea40da5f0f497e0869092320c27bd4d1ed9d7972def3b0ad2aa | tlehman/sicp-exercises | ex-2.18.scm | Exercise 2.18 : Define a procedure reverse that takes a list as argument
; and returns a list of the same elements in reverse order:
;
; (reverse (list 1 4 9 16 25))
( 25 16 9 4 1 )
(define (reverse my-list)
( last ' ( 1 2 3 ) ) # = > 3
(define (last lst)
(if (null? lst) lst
(if (null? (cdr lst)) (car lst)
(last (cdr lst)))))
( beginning ' ( 1 2 3 ) ) # = > ( 1 2 )
(define (beginning lst)
(if (or (null? lst) (null? (cdr lst)))
'() ; throw away the last element
(cons (car lst) (beginning (cdr lst)))))
(define (recurse lst)
(if (null? lst) lst
(cons (last lst)
(recurse (beginning lst)))))
(recurse my-list))
( reverse ' ( 1 2 3 4 5 ) )
= > ( 5 4 3 2 1 )
| null | https://raw.githubusercontent.com/tlehman/sicp-exercises/57151ec07d09a98318e91c83b6eacaa49361d156/ex-2.18.scm | scheme | and returns a list of the same elements in reverse order:
(reverse (list 1 4 9 16 25))
throw away the last element | Exercise 2.18 : Define a procedure reverse that takes a list as argument
( 25 16 9 4 1 )
(define (reverse my-list)
( last ' ( 1 2 3 ) ) # = > 3
(define (last lst)
(if (null? lst) lst
(if (null? (cdr lst)) (car lst)
(last (cdr lst)))))
( beginning ' ( 1 2 3 ) ) # = > ( 1 2 )
(define (beginning lst)
(if (or (null? lst) (null? (cdr lst)))
(cons (car lst) (beginning (cdr lst)))))
(define (recurse lst)
(if (null? lst) lst
(cons (last lst)
(recurse (beginning lst)))))
(recurse my-list))
( reverse ' ( 1 2 3 4 5 ) )
= > ( 5 4 3 2 1 )
|
ac118616b09f23a7959acc70c1c6c9b3765fa98ad3992c16bdfa075d48be20dc | funcool/promesa | protocols.cljc | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
;;
Copyright ( c ) < >
(ns promesa.protocols
"A generic promise abstraction and related protocols.")
(defprotocol IPromise
(-fmap [it f] [it f executor]
"Apply function to a computation")
(-merr [it f] [it f executor]
"Apply function to a failed computation and flatten 1 level")
(-mcat [it f] [it f executor]
"Apply function to a computation and flatten 1 level")
(-hmap [it f] [it f executor]
"Apply function to a computation independently if is failed or
successful.")
(-fnly [it f] [it f executor]
"Apply function to a computation independently if is failed or
successful; the return value is ignored.")
(-then [it f] [it f executor]
"Apply function to a computation and flatten multiple levels")
)
(defprotocol IState
"Additional state/introspection abstraction."
(-extract [it] [it default] "Extract the current value.")
(-resolved? [it] "Returns true if a promise is resolved.")
(-rejected? [it] "Returns true if a promise is rejected.")
(-pending? [it] "Retutns true if a promise is pending."))
(defprotocol IPromiseFactory
"A promise constructor abstraction."
(-promise [it] "Create a promise instance from other types"))
(defprotocol ICancellable
"A cancellation abstraction."
(-cancel! [it])
(-cancelled? [it]))
(defprotocol ICompletable
(-resolve! [it v] "Deliver a value to empty promise.")
(-reject! [it e] "Deliver an error to empty promise."))
(defprotocol IExecutor
(-exec! [it task] "Submit a task and return nil")
(-run! [it task] "Submit a task and return a promise.")
(-submit! [it task] "Submit a task and return a promise."))
(defprotocol IScheduler
"A generic abstraction for scheduler facilities."
(-schedule! [it ms func] "Schedule a function to be executed in future."))
(defprotocol ISemaphore
"An experimental semaphore protocol, used internally; no public api"
(-try-acquire! [it] [it n] [it n t] "Try acquire n or n permits, non-blocking or optional timeout")
(-acquire! [it] [it n] "Acquire 1 or N permits")
(-release! [it] [it n] "Release 1 or N permits"))
(defprotocol ILock
"An experimental lock protocol, used internally; no public api"
(-lock! [it])
(-unlock! [it]))
(defprotocol IReadChannel
(-take! [it handler]))
(defprotocol IWriteChannel
(-put! [it val handler]))
(defprotocol IChannelInternal
(^:no-doc -cleanup! [it]))
(defprotocol IChannelMultiplexer
(^:no-doc -tap! [it ch close?])
(^:no-doc -untap! [it ch]))
(defprotocol ICloseable
(-closed? [it])
(-close! [it] [it reason]))
(defprotocol IBuffer
(-full? [it])
(-poll! [it])
(-offer! [it val])
(-size [it]))
(defprotocol IHandler
(-active? [it])
(-commit! [it])
(-blockable? [it]))
#?(:clj
(defprotocol IAwaitable
(-await! [it] [it duration] "block current thread await termination")))
| null | https://raw.githubusercontent.com/funcool/promesa/19491a4ea476f80ae741c6d8072c1a4612b1b654/src/promesa/protocols.cljc | clojure |
the return value is ignored.") | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
Copyright ( c ) < >
(ns promesa.protocols
"A generic promise abstraction and related protocols.")
(defprotocol IPromise
(-fmap [it f] [it f executor]
"Apply function to a computation")
(-merr [it f] [it f executor]
"Apply function to a failed computation and flatten 1 level")
(-mcat [it f] [it f executor]
"Apply function to a computation and flatten 1 level")
(-hmap [it f] [it f executor]
"Apply function to a computation independently if is failed or
successful.")
(-fnly [it f] [it f executor]
"Apply function to a computation independently if is failed or
(-then [it f] [it f executor]
"Apply function to a computation and flatten multiple levels")
)
(defprotocol IState
"Additional state/introspection abstraction."
(-extract [it] [it default] "Extract the current value.")
(-resolved? [it] "Returns true if a promise is resolved.")
(-rejected? [it] "Returns true if a promise is rejected.")
(-pending? [it] "Retutns true if a promise is pending."))
(defprotocol IPromiseFactory
"A promise constructor abstraction."
(-promise [it] "Create a promise instance from other types"))
(defprotocol ICancellable
"A cancellation abstraction."
(-cancel! [it])
(-cancelled? [it]))
(defprotocol ICompletable
(-resolve! [it v] "Deliver a value to empty promise.")
(-reject! [it e] "Deliver an error to empty promise."))
(defprotocol IExecutor
(-exec! [it task] "Submit a task and return nil")
(-run! [it task] "Submit a task and return a promise.")
(-submit! [it task] "Submit a task and return a promise."))
(defprotocol IScheduler
"A generic abstraction for scheduler facilities."
(-schedule! [it ms func] "Schedule a function to be executed in future."))
(defprotocol ISemaphore
"An experimental semaphore protocol, used internally; no public api"
(-try-acquire! [it] [it n] [it n t] "Try acquire n or n permits, non-blocking or optional timeout")
(-acquire! [it] [it n] "Acquire 1 or N permits")
(-release! [it] [it n] "Release 1 or N permits"))
(defprotocol ILock
"An experimental lock protocol, used internally; no public api"
(-lock! [it])
(-unlock! [it]))
(defprotocol IReadChannel
(-take! [it handler]))
(defprotocol IWriteChannel
(-put! [it val handler]))
(defprotocol IChannelInternal
(^:no-doc -cleanup! [it]))
(defprotocol IChannelMultiplexer
(^:no-doc -tap! [it ch close?])
(^:no-doc -untap! [it ch]))
(defprotocol ICloseable
(-closed? [it])
(-close! [it] [it reason]))
(defprotocol IBuffer
(-full? [it])
(-poll! [it])
(-offer! [it val])
(-size [it]))
(defprotocol IHandler
(-active? [it])
(-commit! [it])
(-blockable? [it]))
#?(:clj
(defprotocol IAwaitable
(-await! [it] [it duration] "block current thread await termination")))
|
c2fcbdff92d9c6fe746a5f69b7d551784c3755db5be54cfe5f3b153fa3627735 | thheller/shadow-cljs | node_test.clj | (ns shadow.build.targets.node-test
(:refer-clojure :exclude (compile flush resolve))
(:require
[shadow.build :as build]
[shadow.build.modules :as modules]
[shadow.build.classpath :as cp]
[shadow.build.targets.node-script :as node-script]
[shadow.cljs.util :as util]
[shadow.cljs.devtools.server.util :refer (pipe)]
[shadow.build.async :as async]
[shadow.build.test-util :as tu]
[shadow.build.targets.shared :as shared]
[shadow.jvm-log :as log]))
(defn configure [{::build/keys [config mode] :as state}]
(let [runner-ns (or (when-let [main (:main config)]
(-> main namespace symbol))
'shadow.test.node)]
(-> state
(tu/configure-common)
(assoc ::tu/runner-ns runner-ns)
(assoc-in [:compiler-options :closure-defines 'cljs.core/*target*] "nodejs")
(update :build-options merge {:greedy true
:dynamic-resolve true})
(update ::build/config merge {:main (get config :main 'shadow.test.node/main)})
;; (update-in [::build/config :devtools] assoc :enabled false)
(cond->
(and (:ui-driven config) (:worker-info state))
;; just the defines, preloads are added in resolve
(-> (shared/inject-node-repl config)
(assoc-in [:compiler-options :closure-defines 'shadow.test.env/UI-DRIVEN] true))
))))
;; since :configure is only called once in :dev
;; we delay setting the :entries until compile-prepare which is called every cycle
;; need to come up with a cleaner API for this
(defn test-resolve
[{::build/keys [mode config] :as state}]
(let [test-namespaces
(tu/find-test-namespaces state config)
entries
(-> '[shadow.test.env] ;; must be included before any deftest because of the cljs.test mod
(cond->
(and (:ui-driven config) (:worker-info state))
(conj 'shadow.cljs.devtools.client.node 'shadow.remote.runtime.cljs.node 'shadow.test.remote-inject)
(= :dev mode)
(into (get-in config [:devtools :preloads])))
(into test-namespaces)
(conj (::tu/runner-ns state)))]
(log/debug ::test-resolve {:config config
:test-namespaces test-namespaces})
(-> state
(assoc ::tu/test-namespaces test-namespaces)
(assoc-in [::modules/config :main :entries] entries)
;; re-analyze modules since we modified the entries
(modules/analyze)
(tu/inject-extra-requires)
)))
(defn autorun-test [{::build/keys [config] :as state}]
(util/with-logged-time
[state {:type ::autorun}]
(let [script-args
["node" (:output-to config)]
proc
(-> (ProcessBuilder. (into-array script-args))
(.directory nil)
(.start))]
(println "========= Running Tests =======================")
(.start (Thread. (bound-fn [] (pipe proc (.getInputStream proc) *out*))))
(.start (Thread. (bound-fn [] (pipe proc (.getErrorStream proc) *err*))))
;; FIXME: what if this doesn't terminate?
(let [exit-code (.waitFor proc)]
(println "===============================================")
(assoc state ::exit-code exit-code)))))
(defn process
[{::build/keys [stage mode config] :as state}]
(-> state
(cond->
(= stage :configure)
(configure)
(= stage :resolve)
(test-resolve))
(node-script/process)
(cond->
(and (= stage :flush)
(:autorun config))
(-> (async/wait-for-pending-tasks!)
(autorun-test))
))) | null | https://raw.githubusercontent.com/thheller/shadow-cljs/ba0a02aec050c6bc8db1932916009400f99d3cce/src/main/shadow/build/targets/node_test.clj | clojure | (update-in [::build/config :devtools] assoc :enabled false)
just the defines, preloads are added in resolve
since :configure is only called once in :dev
we delay setting the :entries until compile-prepare which is called every cycle
need to come up with a cleaner API for this
must be included before any deftest because of the cljs.test mod
re-analyze modules since we modified the entries
FIXME: what if this doesn't terminate? | (ns shadow.build.targets.node-test
(:refer-clojure :exclude (compile flush resolve))
(:require
[shadow.build :as build]
[shadow.build.modules :as modules]
[shadow.build.classpath :as cp]
[shadow.build.targets.node-script :as node-script]
[shadow.cljs.util :as util]
[shadow.cljs.devtools.server.util :refer (pipe)]
[shadow.build.async :as async]
[shadow.build.test-util :as tu]
[shadow.build.targets.shared :as shared]
[shadow.jvm-log :as log]))
(defn configure [{::build/keys [config mode] :as state}]
(let [runner-ns (or (when-let [main (:main config)]
(-> main namespace symbol))
'shadow.test.node)]
(-> state
(tu/configure-common)
(assoc ::tu/runner-ns runner-ns)
(assoc-in [:compiler-options :closure-defines 'cljs.core/*target*] "nodejs")
(update :build-options merge {:greedy true
:dynamic-resolve true})
(update ::build/config merge {:main (get config :main 'shadow.test.node/main)})
(cond->
(and (:ui-driven config) (:worker-info state))
(-> (shared/inject-node-repl config)
(assoc-in [:compiler-options :closure-defines 'shadow.test.env/UI-DRIVEN] true))
))))
(defn test-resolve
[{::build/keys [mode config] :as state}]
(let [test-namespaces
(tu/find-test-namespaces state config)
entries
(cond->
(and (:ui-driven config) (:worker-info state))
(conj 'shadow.cljs.devtools.client.node 'shadow.remote.runtime.cljs.node 'shadow.test.remote-inject)
(= :dev mode)
(into (get-in config [:devtools :preloads])))
(into test-namespaces)
(conj (::tu/runner-ns state)))]
(log/debug ::test-resolve {:config config
:test-namespaces test-namespaces})
(-> state
(assoc ::tu/test-namespaces test-namespaces)
(assoc-in [::modules/config :main :entries] entries)
(modules/analyze)
(tu/inject-extra-requires)
)))
(defn autorun-test [{::build/keys [config] :as state}]
(util/with-logged-time
[state {:type ::autorun}]
(let [script-args
["node" (:output-to config)]
proc
(-> (ProcessBuilder. (into-array script-args))
(.directory nil)
(.start))]
(println "========= Running Tests =======================")
(.start (Thread. (bound-fn [] (pipe proc (.getInputStream proc) *out*))))
(.start (Thread. (bound-fn [] (pipe proc (.getErrorStream proc) *err*))))
(let [exit-code (.waitFor proc)]
(println "===============================================")
(assoc state ::exit-code exit-code)))))
(defn process
[{::build/keys [stage mode config] :as state}]
(-> state
(cond->
(= stage :configure)
(configure)
(= stage :resolve)
(test-resolve))
(node-script/process)
(cond->
(and (= stage :flush)
(:autorun config))
(-> (async/wait-for-pending-tasks!)
(autorun-test))
))) |
e04fec83bde416674625653a3cc229f2d335bfa014bfcaff23e4f97ab2f7897d | balayette/blockchan | listext.ml | module List =
struct
include List
let repr_of_hashes l =
let rec aux l acc = match l with
| e::[] -> acc ^ e
| e::l -> aux l (acc ^ e ^ ", ")
| [] -> acc
in aux l ""
let remove_options l =
let rec aux l acc = match l with
| [] -> acc
| e::l -> (
match e with
| None -> aux l acc
| Some x -> aux l (x::acc)
)
in List.rev (aux l [])
end
| null | https://raw.githubusercontent.com/balayette/blockchan/3b7e292ec9e9574eefcdebd0a6036698a80febdb/src/listext.ml | ocaml | module List =
struct
include List
let repr_of_hashes l =
let rec aux l acc = match l with
| e::[] -> acc ^ e
| e::l -> aux l (acc ^ e ^ ", ")
| [] -> acc
in aux l ""
let remove_options l =
let rec aux l acc = match l with
| [] -> acc
| e::l -> (
match e with
| None -> aux l acc
| Some x -> aux l (x::acc)
)
in List.rev (aux l [])
end
| |
2a5ccea03142437a4fc81d90b52d5d259732811143cb1ffc0f4d2adb6634d716 | expipiplus1/vulkan | Peek.hs | # LANGUAGE AllowAmbiguousTypes #
module Render.Peek
( peekStmt
, peekStmtDirect
, getLenRef
, storablePeek
, vectorPeekWithLenRef
, unwrapIdiomaticType
) where
import qualified Data.Text as T
import Data.Vector (Vector)
import Data.Vector.Extra
( pattern Empty
, pattern (:<|)
)
import qualified Data.Vector.Extra as V
import Polysemy
import Polysemy.Fail
import Polysemy.Input
import Polysemy.NonDet hiding (Empty)
import Prettyprinter
import Relude hiding
( Const
, State
, Type
, init
, last
)
import qualified Data.ByteString as BS
import Foreign.C.Types (CChar)
import Foreign.Marshal.Utils
import Foreign.Ptr
import Foreign.Storable
import CType as C
import Error
import Haskell
import Marshal.Marshalable
import Marshal.Scheme
import Render.Element
import Render.Scheme
import Render.SpecInfo
import Render.Stmts
import Render.Stmts.Poke
import Render.Type
peekStmt
:: ( HasErr r
, Marshalable a
, Show a
, HasRenderElem r
, HasSpecInfo r
, HasRenderParams r
, HasSiblingInfo a r
, HasStmts r
)
=> a
-> Ref s AddrDoc
-> MarshalScheme a
-> Stmt s r (Maybe (Ref s ValueDoc))
peekStmt a addr scheme =
runNonDetMaybe $
peekIdiomatic (name a) (lengths a) (Ptr Const (type' a)) addr scheme
peekStmtDirect
:: ( HasErr r
, Marshalable a
, Show a
, HasRenderElem r
, HasSpecInfo r
, HasRenderParams r
, HasSiblingInfo a r
, HasStmts r
)
=> a
-> Ref s AddrDoc
-> MarshalScheme a
-> Stmt s r (Maybe (Ref s ValueDoc))
peekStmtDirect a addr scheme =
runNonDetMaybe $ peekIdiomatic (name a) (lengths a) (type' a) addr scheme
type Lengths = Vector ParameterLength
peekIdiomatic
:: ( HasErr r
, HasRenderElem r
, HasSpecInfo r
, HasRenderParams r
, HasSiblingInfo a r
, Show a
, HasStmts r
)
=> CName
-> Lengths
-> CType
-> Ref s AddrDoc
-> MarshalScheme a
-> Sem (NonDet ': StmtE s r ': r) (Ref s ValueDoc)
peekIdiomatic name lengths fromType addr scheme = context "peekIdiomatic" $ do
r <- peekWrapped name lengths fromType addr scheme
t <- raise $ refType r
-- TODO: probably shouldn't ignore these here
(_, _, toTy) <- runRenderTypeContext $ schemeTypeNegativeWithContext scheme
-- If this is already the correct type don't try wrapping it
if Just t == toTy
then pure r
else raise $ unwrapIdiomaticType (Just (unCName name)) r
-- | Make a type idiomatic, CFloat to Float for example
unwrapIdiomaticType
:: (HasRenderParams r, HasErr r, HasRenderElem r)
=> Maybe Text
-> Ref s ValueDoc
-> Stmt s r (Ref s ValueDoc)
unwrapIdiomaticType name value = do
RenderParams{..} <- input
t <- refType value
case mkIdiomaticType t of
Nothing -> pure value
Just (IdiomaticType w _ to) -> stmt (Just w) name $ do
ValueDoc d <- use value
to <&> \case
PureFunction fun -> Pure InlineOnce $ ValueDoc (fun <+> d)
IOFunction fun -> IOAction $ ValueDoc (fun <+> d)
-- | Render a peek and don't do any unwrapping to idiomatic haskell types
peekWrapped
:: forall a r s
. ( HasErr r
, HasRenderElem r
, HasSpecInfo r
, HasRenderParams r
, HasSiblingInfo a r
, Show a
, HasStmts r
)
=> CName
-> Lengths
-> CType
-> Ref s AddrDoc
-> MarshalScheme a
-> Sem (NonDet ': StmtE s r ': r) (Ref s ValueDoc)
peekWrapped name lengths fromType addr = \case
Normal toType -> raise $ normalPeek name addr toType fromType
Length toType _ _ -> raise $ normalPeek name addr toType fromType
Preserve _toType -> raise $ storablePeek name addr fromType
ElidedVoid -> empty
-- TODO: Should this take into account the type?
ElidedLength{} -> raise $ storablePeek name addr fromType
ElidedUnivalued _ -> empty
ByteString -> raise $ byteStringPeek @a name lengths addr fromType
VoidPtr -> raise $ storablePeek name addr fromType
Maybe toType -> raise $ maybePeek' name lengths addr fromType toType
Vector nullable toElem ->
raise $ vectorPeek name lengths addr fromType toElem nullable
Tupled _ toElem -> raise $ tuplePeek name addr fromType toElem
WrappedStruct toName -> raise $ wrappedStructPeek name addr toName fromType
WrappedChildStruct toName ->
raise $ wrappedChildStructPeek name addr toName fromType
EitherWord32 toElem ->
raise $ eitherWord32Peek name lengths addr fromType toElem
ElidedCustom CustomSchemeElided{..} ->
maybe (const empty) (raise .) csePeek addr
Custom CustomScheme{..} -> raise $ csPeek addr
s -> throw ("Unhandled peek " <> show s)
----------------------------------------------------------------
-- Peeks
----------------------------------------------------------------
storablePeek
:: forall r a s
. ( HasErr r
, HasRenderElem r
, HasRenderParams r
, HasSpecInfo r
, Coercible a (Doc ())
, Typeable a
)
=> CName
-> Ref s AddrDoc
-> CType
-> Stmt s r (Ref s a)
storablePeek name addr fromPtr = case fromPtr of
Ptr _ from -> do
t <- cToHsTypeWithHoles DoLower from
stmtC @a (Just t) name $ do
tDoc <- renderTypeHighPrec t
tellImportWith ''Storable 'peek
AddrDoc addrDoc <- use addr
pure $ IOAction (coerce ("peek @" <> tDoc <+> addrDoc))
_ -> throw "Trying to generate a storable peek for a non-pointer"
normalPeek
:: forall r s
. (HasErr r, HasRenderElem r, HasRenderParams r, HasSpecInfo r)
=> CName
-> Ref s AddrDoc
-> CType
-> CType
-> Stmt s r (Ref s ValueDoc)
normalPeek name addrRef to fromPtr =
context (unCName name) $
runNonDet (asum [same, inlineStruct, pointerStruct, pointerHandle, union])
>>= \case
Nothing ->
throw
("Unhandled " <> show fromPtr <> " conversion to: " <> show to)
Just ps -> pure ps
where
raise2 = raise . raise
same
, inlineStruct
, pointerStruct
, union
:: Sem (NonDet ': StmtE s r ': r) (Ref s ValueDoc)
same = failToNonDet $ do
Ptr _ from <- pure fromPtr
guard (from == to)
case to of
TypeName n -> do
guard . isNothing =<< getStruct n
guard . isNothing =<< getUnion n
_ -> pure ()
-- Assume a storable instance...
raise2 $ storablePeek name addrRef fromPtr
inlineStruct = failToNonDet $ do
Ptr _ from@(TypeName n) <- pure fromPtr
guard (from == to)
Just _ <- getStruct n
ty <- cToHsTypeWithHoles DoPreserve from
raise2 $ stmtC (Just ty) name $ do
tDoc <- renderTypeHighPrec ty
AddrDoc addr <- use addrRef
tellImportWithAll (TyConName "FromCStruct")
pure $ IOAction (ValueDoc ("peekCStruct @" <> tDoc <+> addr))
pointerHandle = failToNonDet $ do
Ptr _ from <- pure fromPtr
Ptr Const (TypeName n) <- pure from
guard (TypeName n == to)
Just _ <- getHandle n
ty <- cToHsTypeWithHoles DoPreserve (TypeName n)
raise2 $ stmtC (Just ty) name $ do
tDoc <- renderTypeHighPrec ty
AddrDoc addr <- use addrRef
pure $ IOAction (ValueDoc ("peek @" <> tDoc <+> "=<< peek" <+> addr))
pointerStruct = failToNonDet $ do
Ptr _ from <- pure fromPtr
Ptr Const (TypeName n) <- pure from
guard (TypeName n == to)
Just _ <- getStruct n
ty <- cToHsTypeWithHoles DoPreserve (TypeName n)
raise2 $ stmtC (Just ty) name $ do
tDoc <- renderTypeHighPrec ty
AddrDoc addr <- use addrRef
pure $ IOAction (ValueDoc ("peekCStruct @" <> tDoc <+> "=<< peek" <+> addr))
union = failToNonDet $ do
Ptr _ from <- pure fromPtr
TypeName n <- pure from
Just _ <- getUnion n
guard (from == to)
raise2 $ unionPeek name addrRef to fromPtr
wrappedStructPeek
:: forall r s
. (HasErr r, HasRenderElem r, HasRenderParams r, HasSpecInfo r)
=> CName
-> Ref s AddrDoc
-> CName
-> CType
-> Stmt s r (Ref s ValueDoc)
wrappedStructPeek name addrRef toName fromPtr = case fromPtr of
Ptr _ from@(TypeName n) | n == toName -> do
ty <- cToHsTypeWithHoles DoPreserve from
stmtC (Just ty) name $ do
AddrDoc addr <- use addrRef
tellImport (TermName "peekSomeCStruct")
tellImport (TermName "forgetExtensions")
pure $
IOAction
( ValueDoc
("peekSomeCStruct" <+> parens ("forgetExtensions" <+> addr))
)
Ptr _ from@(Ptr Const (TypeName n)) | n == toName -> do
ty <- cToHsTypeWithHoles DoPreserve from
stmtC (Just ty) name $ do
AddrDoc addr <- use addrRef
tellImport (TermName "peekSomeCStruct")
tellImport (TermName "forgetExtensions")
tellImportWith ''Storable 'peek
pure $
IOAction
(ValueDoc ("peekSomeCStruct . forgetExtensions =<< peek" <+> addr))
_ -> throw $ "Unhandled WrappedStruct peek from " <> show fromPtr
wrappedChildStructPeek
:: forall r s
. (HasErr r, HasRenderElem r, HasRenderParams r, HasSpecInfo r)
=> CName
-> Ref s AddrDoc
-> CName
-> CType
-> Stmt s r (Ref s ValueDoc)
wrappedChildStructPeek name addrRef toName fromPtr = case fromPtr of
Ptr _ from@(TypeName n) | n == toName -> do
ty <- cToHsTypeWithHoles DoPreserve from
stmtC (Just ty) name $ do
AddrDoc addr <- use addrRef
tellImportWith (TyConName "Inheritable") (TermName "peekSomeCChild")
pure $ IOAction (ValueDoc ("peekSomeCChild" <+> addr))
Ptr _ from@(Ptr Const (TypeName n)) | n == toName -> do
ty <- cToHsTypeWithHoles DoPreserve from
stmtC (Just ty) name $ do
AddrDoc addr <- use addrRef
tellImportWith (TyConName "Inheritable") (TermName "peekSomeCChild")
tellImportWith ''Storable 'peek
pure $ IOAction (ValueDoc ("peekSomeCChild =<< peek" <+> addr))
_ -> throw $ "Unhandled WrappedStruct peek from " <> show fromPtr
unionPeek
:: forall r s
. (HasErr r, HasRenderElem r, HasSpecInfo r, HasRenderParams r)
=> CName
-> Ref s AddrDoc
-> CType
-> CType
-> Stmt s r (Ref s ValueDoc)
unionPeek name addrRef _to fromPtr = failToError (V.singleton . T.pack) $ do
RenderParams{..} <- input
Ptr _ from <- pure fromPtr
TypeName n <- pure from
ty <- cToHsTypeWithHoles DoPreserve from
raise $ stmtC (Just ty) name $ do
discs <-
catMaybes
<$> sequenceV
[ useViaNameMaybe (unCName udSiblingName)
| UnionDiscriminator{..} <- toList unionDiscriminators
, udUnionType == n
]
ValueDoc discDoc <- case discs of
[] -> throw ("Unable to find union discriminator for " <> unCName n)
[d] -> pure d
_ -> throw ("Found multiple union discriminators for " <> unCName n)
let peekName = TermName $ "peek" <> unName (mkTyName n)
AddrDoc addr <- use addrRef
tellImport peekName
pure $ IOAction (ValueDoc (pretty peekName <+> discDoc <+> addr))
-- TODO: Check lengths here for null termination
byteStringPeek
:: forall a r s
. ( HasErr r
, HasRenderElem r
, HasSpecInfo r
, HasRenderParams r
, HasSiblingInfo a r
, Show a
)
=> CName
-> Lengths
-> Ref s AddrDoc
-> CType
-> Stmt s r (Ref s ValueDoc)
byteStringPeek name lengths addrRef =
stmtC (Just (ConT ''ByteString)) name . \case
Ptr _ (Ptr Const Char) -> do
AddrDoc addr <- use addrRef
tellImport 'BS.packCString
tellImportWith ''Storable 'peek
pure . IOAction $ ValueDoc ("packCString =<< peek" <+> addr)
-- TODO: abstract away this repetition
Ptr _ Char -> do
tellImport 'BS.packCString
AddrDoc addr <- use addrRef
pure . IOAction $ ValueDoc ("packCString" <+> addr)
Ptr _ Void | _ :<| V.Empty <- lengths -> do
lenRef <- getLenRef @a lengths
tellImport 'BS.packCStringLen
tellImport 'castPtr
tellImport ''CChar
AddrDoc addr <- use addrRef
ValueDoc lenVal <- use lenRef
let castAddr = "castPtr @() @CChar" <+> addr
pure . IOAction $
ValueDoc
("packCStringLen " <+> align (tupled [castAddr, lenVal]))
TODO : These next two patterns have different " levelness " but the same
-- code, it works because this function is not called consistently. Fix!
Ptr _ (Array NonConst (SymbolicArraySize _) Char) -> do
tellImport 'BS.packCString
tellImport (TermName "lowerArrayPtr")
AddrDoc addr <- use addrRef
pure . IOAction $
ValueDoc
("packCString" <+> parens ("lowerArrayPtr" <+> addr))
Array NonConst (SymbolicArraySize p) Char -> do
RenderParams{..} <- input
tellImport 'BS.packCString
tellImport (TermName "lowerArrayPtr")
AddrDoc addr <- use addrRef
let size = mkPatternName p
tellImport size
pure . IOAction $
ValueDoc
("packCString . lowerArrayPtr @CChar @" <> pretty size <+> "$" <+> addr)
Ptr _ (Array NonConst size (TypeName "uint8_t"))
| case size of
SymbolicArraySize _ -> True
NumericArraySize _ -> True
_ -> False ->
do
let fn = "peekByteStringFromSizedVectorPtr"
tellImport (TermName fn)
AddrDoc addr <- use addrRef
pure . IOAction $ ValueDoc (pretty fn <+> addr)
t -> throw ("Unhandled conversion to ByteString from " <> show t)
maybePeek'
:: ( HasErr r
, HasRenderElem r
, HasSpecInfo r
, HasRenderParams r
, HasSiblingInfo a r
, Show a
, HasStmts r
)
=> CName
-> Lengths
-> Ref s AddrDoc
-> CType
-> MarshalScheme a
-> Stmt s r (Ref s ValueDoc)
maybePeek' name lengths addrRef fromPtr to = case fromPtr of
Ptr _ from@(Ptr _ fromElem) -> do
let maybePtrDoc = name
notNullPtrDoc <- freshName (Just "j")
ptrTy <- cToHsTypeWithHoles DoPreserve from
-- Load the pointer which might be null
ptr <- stmtC (Just ptrTy) maybePtrDoc $ do
AddrDoc addr <- use addrRef
ptrTDoc <- renderTypeHighPrec =<< cToHsTypeWithHoles DoPreserve from
tellImportWith ''Storable 'peek
pure $ IOAction (AddrDoc ("peek @" <> ptrTDoc <+> addr))
elemTy <- cToHsTypeWithHoles DoPreserve fromElem
r <- stmtC (Just (ConT ''Maybe :@ elemTy)) name $ do
AddrDoc ptrDoc <- use ptr
subPeek <- renderSubStmtsIO $ do
ptrRef <- pureStmt (AddrDoc (pretty notNullPtrDoc))
runNonDetMaybe (peekIdiomatic name lengths from ptrRef to) >>= \case
Nothing -> throw "Nothing to peek to fill Maybe"
Just p -> pure p
tellImport 'maybePeek
pure
. IOAction
. ValueDoc
$ "maybePeek"
<+> parens ("\\" <> pretty notNullPtrDoc <+> "->" <+> subPeek)
<+> ptrDoc
freeNames [notNullPtrDoc]
pure r
t -> throw ("Unhandled conversion to Maybe from " <> show t)
vectorPeek
:: forall a r s
. ( HasErr r
, HasRenderElem r
, HasSpecInfo r
, HasRenderParams r
, HasSiblingInfo a r
, Show a
, HasStmts r
)
=> CName
-> Vector ParameterLength
-> Ref s AddrDoc
-> CType
-> MarshalScheme a
-> Nullable
-> Stmt s r (Ref s ValueDoc)
vectorPeek name lengths addrRef fromPtr toElem nullable = case fromPtr of
Ptr _ (Ptr _ fromElem) | NamedLength _ :<| lenTail <- lengths -> do
elemPtrRef <- storablePeek name addrRef fromPtr
lenRef <- getLenRef @a lengths
vectorPeekWithLenRef name toElem elemPtrRef fromElem lenTail lenRef nullable
Ptr _ (Array _ (SymbolicArraySize len) fromElem) -> do
RenderParams{..} <- input
tDoc <- renderTypeHighPrec =<< cToHsTypeWithHoles DoPreserve fromElem
let lenName = mkPatternName len
castedAddrRef <-
stmt Nothing Nothing $
Pure InlineOnce <$> do
tellImport (TermName "lowerArrayPtr")
tellImport lenName
AddrDoc addr <- use addrRef
pure . AddrDoc $ "lowerArrayPtr @" <> tDoc <+> addr
lenRef <- pureStmt (ValueDoc (pretty lenName))
vectorPeekWithLenRef
name
toElem
castedAddrRef
fromElem
V.empty
lenRef
nullable
FIXME : , do this initial pointer peeking elsewhere please !
Ptr _ fromElem | (V.uncons -> Just (_, lenTail)) <- lengths -> do
lenRef <- getLenRef @a lengths
vectorPeekWithLenRef name toElem addrRef fromElem lenTail lenRef nullable
t -> throw ("Unhandled conversion to Vector from " <> show t)
vectorPeekWithLenRef
:: forall a r s
. ( HasErr r
, HasRenderElem r
, HasSpecInfo r
, HasRenderParams r
, HasSiblingInfo a r
, Show a
, HasStmts r
)
=> CName
-> MarshalScheme a
-> Ref s AddrDoc
-> CType
-> Vector ParameterLength
-> Ref s ValueDoc
-> Nullable
-> Stmt s r (Ref s ValueDoc)
vectorPeekWithLenRef name toElem addrRef fromElem lenTail lenRef nullable = do
t <- cToHsTypeWithHoles DoPreserve fromElem
stmtC (Just (ConT ''Vector :@ t)) name $ do
indexVar <- freshName (Just "i")
ValueDoc lenDoc <- case nullable of
NotNullable -> use lenRef
Nullable ->
use
=<< stmt
Nothing
(Just (unCName name <> "Length"))
( do
AddrDoc addr <- use addrRef
ValueDoc lenDoc <- use lenRef
tellImport 'nullPtr
pure
. Pure NeverInline
. ValueDoc
$ "if"
<+> addr
<+> "== nullPtr then 0 else"
<+> lenDoc
)
-- Render a peeker for the elements
subPeek <- renderSubStmtsIO $ do
-- Get a name for the index variable
indexRef <- pureStmt (pretty indexVar)
-- Get the value of the pointer to this element
elemAddrRef <- stmt Nothing Nothing $ do
(elemSize, _elemAlign) <- getTypeSize fromElem
indexDoc <- use indexRef
-- TODO: be able to coerce refs
AddrDoc addr <- raise $ use addrRef
Pure InlineOnce . AddrDoc <$> do
tellImport (TermName "advancePtrBytes")
elemPtrTyDoc <-
renderType
. (ConT ''Ptr :@)
=<< cToHsTypeWithHoles DoPreserve fromElem
pure $
parens
( addr
<+> "`advancePtrBytes`"
<+> parens (viaShow elemSize <+> "*" <+> indexDoc)
<+> "::"
<+> elemPtrTyDoc
)
runNonDetMaybe
( peekIdiomatic
(CName (unCName name <> "Elem"))
lenTail
(Ptr Const fromElem)
elemAddrRef
toElem
)
>>= \case
Nothing -> throw "Nothing to peek to fill Vector"
Just p -> pure p
freeNames [indexVar]
tellImport 'V.generateM
pure . IOAction . ValueDoc $
"generateM"
<+> lenDoc
<+> parens
("\\" <> pretty indexVar <+> "->" <+> subPeek)
eitherWord32Peek
:: forall a r s
. ( HasErr r
, HasRenderElem r
, HasSpecInfo r
, HasRenderParams r
, HasSiblingInfo a r
, Show a
, HasStmts r
)
=> CName
-> Lengths
-> Ref s AddrDoc
-> CType
-> MarshalScheme a
-> Stmt s r (Ref s ValueDoc)
eitherWord32Peek name lengths addr fromPtr toElem = case fromPtr of
Ptr _ (Ptr _ fromElem) | (NamedLength len) :<| _ <- lengths -> do
mRef <-
note "Unable to get wrapped peek for EitherWord32"
=<< runNonDetMaybe
( peekIdiomatic
name
lengths
fromPtr
addr
(Maybe (Vector NotNullable toElem))
)
elemTy <- cToHsTypeWithHoles DoPreserve fromElem
stmtC
(Just (ConT ''Either :@ ConT ''Word32 :@ (ConT ''Vector :@ elemTy)))
name
. fmap (Pure NeverInline)
$ do
ValueDoc lenName <- useViaName (unCName len)
ValueDoc m <- use mRef
pure
. ValueDoc
$ "maybe"
<+> parens ("Left" <+> lenName)
<+> "Right"
<+> m
t -> throw ("Unhandled conversion to EitherWord32 from " <> show t)
tuplePeek
:: forall a r s
. ( HasErr r
, HasRenderElem r
, HasSpecInfo r
, HasRenderParams r
, HasSiblingInfo a r
, Show a
, HasStmts r
)
=> CName
-> Ref s AddrDoc
-> CType
-> MarshalScheme a
-> Stmt s r (Ref s ValueDoc)
tuplePeek name addrRef fromPtr toElem = case fromPtr of
Ptr _ aTy@(Array NonConst (NumericArraySize len) fromElem) -> do
(elemSize, _elemAlign) <- getTypeSize fromElem
tupT <- cToHsTypeWithHoles DoNotPreserve aTy
stmtC (Just tupT) name $ do
Case the array pointer to a pointer to the first element
tupPtrRef <-
stmt Nothing (Just ("p" <> unCName name)) . fmap (Pure InlineOnce) $ do
tellImport (TermName "lowerArrayPtr")
tDoc <- renderTypeHighPrec =<< cToHsTypeWithHoles DoPreserve fromElem
AddrDoc addr <- use addrRef
pure $ "lowerArrayPtr @" <> tDoc <+> addr
let
advance i =
stmt Nothing Nothing . fmap (Pure InlineOnce . AddrDoc) $ do
tellImport (TermName "advancePtrBytes")
tupPtrDoc <- use tupPtrRef
elemPtrTyDoc <-
renderType
. (ConT ''Ptr :@)
=<< cToHsTypeWithHoles DoPreserve fromElem
pure
( parens
( tupPtrDoc
<+> "`advancePtrBytes`"
<+> viaShow (elemSize * i)
<+> "::"
<+> elemPtrTyDoc
)
)
subPeeks <- forV [0 .. len - 1] $ \i -> do
elemPtrRef <- advance (fromIntegral i)
note "Unable to get tuple element peek"
=<< runNonDetMaybe
( peekIdiomatic
(CName (unCName name <> show i))
mempty
(Ptr Const fromElem)
elemPtrRef
toElem
)
Pure InlineOnce . ValueDoc <$> do
subPeekDocs <- traverseV (fmap unValueDoc . use @r) subPeeks
pure $ align (tupled subPeekDocs)
t -> throw ("Unhandled conversion to Tuple from " <> show t)
----------------------------------------------------------------
-- Getting lengths
----------------------------------------------------------------
getLenRef
:: forall a r s
. ( HasErr r
, HasRenderElem r
, HasRenderParams r
, HasSpecInfo r
, HasSiblingInfo a r
, Show a
)
=> Lengths
-> Stmt s r (Ref s ValueDoc)
getLenRef lengths = context "getLenRef" $ do
RenderParams{..} <- input
stmt Nothing Nothing $ case lengths of
Empty -> throw "Trying to allocate something with no length"
NamedLength len :<| _ -> do
ValueDoc value <- useViaName (unCName len)
pure . Pure AlwaysInline . ValueDoc $ "fromIntegral" <+> value
NamedMemberLength struct member :<| _ -> do
ValueDoc structValue <- useViaName (unCName struct)
case complexMemberLengthFunction struct member structValue of
Just complex -> Pure InlineOnce . ValueDoc <$> complex
Nothing -> do
SiblingInfo{..} <- getSiblingInfo @a struct
structName <-
let nonStruct =
throw $
"Trying to get length member from a non-struct type "
<> show siScheme
in case siScheme of
Length (TypeName n) _ _ ->
getStruct n >>= \case
Nothing -> nonStruct
Just _ -> pure n
Normal (TypeName n) ->
getStruct n >>= \case
Nothing -> nonStruct
Just _ -> pure n
_ -> nonStruct
structTyDoc <-
renderType
=<< note
"Unable to get type for struct with length specifying member for allocation"
=<< schemeTypeNegative siScheme
tellImportWithAll (mkTyName structName)
pure
. Pure AlwaysInline
. ValueDoc
$ "fromIntegral $"
<+> pretty (mkMemberName structName member)
<+> parens (structValue <+> "::" <+> structTyDoc)
NamedConstantLength n :<| _ ->
pure . Pure AlwaysInline . ValueDoc . pretty . mkPatternName $ n
NullTerminated :<| _ -> throw "Trying to allocate a null terminated array"
-- _ -> throw "Trying to allocate something with multiple lengths"
----------------------------------------------------------------
Utils
----------------------------------------------------------------
stmtC
:: forall a r s
. (Typeable a, Coercible a (Doc ()))
=> Maybe Type
-> CName
-> Stmt s r (Value a)
-> Stmt s r (Ref s a)
stmtC t n = stmt t (Just (unCName n))
| null | https://raw.githubusercontent.com/expipiplus1/vulkan/73cacc1696011047dcf0c66e9d3fb483762c15cf/generate-new/src/Render/Peek.hs | haskell | TODO: probably shouldn't ignore these here
If this is already the correct type don't try wrapping it
| Make a type idiomatic, CFloat to Float for example
| Render a peek and don't do any unwrapping to idiomatic haskell types
TODO: Should this take into account the type?
--------------------------------------------------------------
Peeks
--------------------------------------------------------------
Assume a storable instance...
TODO: Check lengths here for null termination
TODO: abstract away this repetition
code, it works because this function is not called consistently. Fix!
Load the pointer which might be null
Render a peeker for the elements
Get a name for the index variable
Get the value of the pointer to this element
TODO: be able to coerce refs
--------------------------------------------------------------
Getting lengths
--------------------------------------------------------------
_ -> throw "Trying to allocate something with multiple lengths"
--------------------------------------------------------------
-------------------------------------------------------------- | # LANGUAGE AllowAmbiguousTypes #
module Render.Peek
( peekStmt
, peekStmtDirect
, getLenRef
, storablePeek
, vectorPeekWithLenRef
, unwrapIdiomaticType
) where
import qualified Data.Text as T
import Data.Vector (Vector)
import Data.Vector.Extra
( pattern Empty
, pattern (:<|)
)
import qualified Data.Vector.Extra as V
import Polysemy
import Polysemy.Fail
import Polysemy.Input
import Polysemy.NonDet hiding (Empty)
import Prettyprinter
import Relude hiding
( Const
, State
, Type
, init
, last
)
import qualified Data.ByteString as BS
import Foreign.C.Types (CChar)
import Foreign.Marshal.Utils
import Foreign.Ptr
import Foreign.Storable
import CType as C
import Error
import Haskell
import Marshal.Marshalable
import Marshal.Scheme
import Render.Element
import Render.Scheme
import Render.SpecInfo
import Render.Stmts
import Render.Stmts.Poke
import Render.Type
peekStmt
:: ( HasErr r
, Marshalable a
, Show a
, HasRenderElem r
, HasSpecInfo r
, HasRenderParams r
, HasSiblingInfo a r
, HasStmts r
)
=> a
-> Ref s AddrDoc
-> MarshalScheme a
-> Stmt s r (Maybe (Ref s ValueDoc))
peekStmt a addr scheme =
runNonDetMaybe $
peekIdiomatic (name a) (lengths a) (Ptr Const (type' a)) addr scheme
peekStmtDirect
:: ( HasErr r
, Marshalable a
, Show a
, HasRenderElem r
, HasSpecInfo r
, HasRenderParams r
, HasSiblingInfo a r
, HasStmts r
)
=> a
-> Ref s AddrDoc
-> MarshalScheme a
-> Stmt s r (Maybe (Ref s ValueDoc))
peekStmtDirect a addr scheme =
runNonDetMaybe $ peekIdiomatic (name a) (lengths a) (type' a) addr scheme
type Lengths = Vector ParameterLength
peekIdiomatic
:: ( HasErr r
, HasRenderElem r
, HasSpecInfo r
, HasRenderParams r
, HasSiblingInfo a r
, Show a
, HasStmts r
)
=> CName
-> Lengths
-> CType
-> Ref s AddrDoc
-> MarshalScheme a
-> Sem (NonDet ': StmtE s r ': r) (Ref s ValueDoc)
peekIdiomatic name lengths fromType addr scheme = context "peekIdiomatic" $ do
r <- peekWrapped name lengths fromType addr scheme
t <- raise $ refType r
(_, _, toTy) <- runRenderTypeContext $ schemeTypeNegativeWithContext scheme
if Just t == toTy
then pure r
else raise $ unwrapIdiomaticType (Just (unCName name)) r
unwrapIdiomaticType
:: (HasRenderParams r, HasErr r, HasRenderElem r)
=> Maybe Text
-> Ref s ValueDoc
-> Stmt s r (Ref s ValueDoc)
unwrapIdiomaticType name value = do
RenderParams{..} <- input
t <- refType value
case mkIdiomaticType t of
Nothing -> pure value
Just (IdiomaticType w _ to) -> stmt (Just w) name $ do
ValueDoc d <- use value
to <&> \case
PureFunction fun -> Pure InlineOnce $ ValueDoc (fun <+> d)
IOFunction fun -> IOAction $ ValueDoc (fun <+> d)
peekWrapped
:: forall a r s
. ( HasErr r
, HasRenderElem r
, HasSpecInfo r
, HasRenderParams r
, HasSiblingInfo a r
, Show a
, HasStmts r
)
=> CName
-> Lengths
-> CType
-> Ref s AddrDoc
-> MarshalScheme a
-> Sem (NonDet ': StmtE s r ': r) (Ref s ValueDoc)
peekWrapped name lengths fromType addr = \case
Normal toType -> raise $ normalPeek name addr toType fromType
Length toType _ _ -> raise $ normalPeek name addr toType fromType
Preserve _toType -> raise $ storablePeek name addr fromType
ElidedVoid -> empty
ElidedLength{} -> raise $ storablePeek name addr fromType
ElidedUnivalued _ -> empty
ByteString -> raise $ byteStringPeek @a name lengths addr fromType
VoidPtr -> raise $ storablePeek name addr fromType
Maybe toType -> raise $ maybePeek' name lengths addr fromType toType
Vector nullable toElem ->
raise $ vectorPeek name lengths addr fromType toElem nullable
Tupled _ toElem -> raise $ tuplePeek name addr fromType toElem
WrappedStruct toName -> raise $ wrappedStructPeek name addr toName fromType
WrappedChildStruct toName ->
raise $ wrappedChildStructPeek name addr toName fromType
EitherWord32 toElem ->
raise $ eitherWord32Peek name lengths addr fromType toElem
ElidedCustom CustomSchemeElided{..} ->
maybe (const empty) (raise .) csePeek addr
Custom CustomScheme{..} -> raise $ csPeek addr
s -> throw ("Unhandled peek " <> show s)
storablePeek
:: forall r a s
. ( HasErr r
, HasRenderElem r
, HasRenderParams r
, HasSpecInfo r
, Coercible a (Doc ())
, Typeable a
)
=> CName
-> Ref s AddrDoc
-> CType
-> Stmt s r (Ref s a)
storablePeek name addr fromPtr = case fromPtr of
Ptr _ from -> do
t <- cToHsTypeWithHoles DoLower from
stmtC @a (Just t) name $ do
tDoc <- renderTypeHighPrec t
tellImportWith ''Storable 'peek
AddrDoc addrDoc <- use addr
pure $ IOAction (coerce ("peek @" <> tDoc <+> addrDoc))
_ -> throw "Trying to generate a storable peek for a non-pointer"
normalPeek
:: forall r s
. (HasErr r, HasRenderElem r, HasRenderParams r, HasSpecInfo r)
=> CName
-> Ref s AddrDoc
-> CType
-> CType
-> Stmt s r (Ref s ValueDoc)
normalPeek name addrRef to fromPtr =
context (unCName name) $
runNonDet (asum [same, inlineStruct, pointerStruct, pointerHandle, union])
>>= \case
Nothing ->
throw
("Unhandled " <> show fromPtr <> " conversion to: " <> show to)
Just ps -> pure ps
where
raise2 = raise . raise
same
, inlineStruct
, pointerStruct
, union
:: Sem (NonDet ': StmtE s r ': r) (Ref s ValueDoc)
same = failToNonDet $ do
Ptr _ from <- pure fromPtr
guard (from == to)
case to of
TypeName n -> do
guard . isNothing =<< getStruct n
guard . isNothing =<< getUnion n
_ -> pure ()
raise2 $ storablePeek name addrRef fromPtr
inlineStruct = failToNonDet $ do
Ptr _ from@(TypeName n) <- pure fromPtr
guard (from == to)
Just _ <- getStruct n
ty <- cToHsTypeWithHoles DoPreserve from
raise2 $ stmtC (Just ty) name $ do
tDoc <- renderTypeHighPrec ty
AddrDoc addr <- use addrRef
tellImportWithAll (TyConName "FromCStruct")
pure $ IOAction (ValueDoc ("peekCStruct @" <> tDoc <+> addr))
pointerHandle = failToNonDet $ do
Ptr _ from <- pure fromPtr
Ptr Const (TypeName n) <- pure from
guard (TypeName n == to)
Just _ <- getHandle n
ty <- cToHsTypeWithHoles DoPreserve (TypeName n)
raise2 $ stmtC (Just ty) name $ do
tDoc <- renderTypeHighPrec ty
AddrDoc addr <- use addrRef
pure $ IOAction (ValueDoc ("peek @" <> tDoc <+> "=<< peek" <+> addr))
pointerStruct = failToNonDet $ do
Ptr _ from <- pure fromPtr
Ptr Const (TypeName n) <- pure from
guard (TypeName n == to)
Just _ <- getStruct n
ty <- cToHsTypeWithHoles DoPreserve (TypeName n)
raise2 $ stmtC (Just ty) name $ do
tDoc <- renderTypeHighPrec ty
AddrDoc addr <- use addrRef
pure $ IOAction (ValueDoc ("peekCStruct @" <> tDoc <+> "=<< peek" <+> addr))
union = failToNonDet $ do
Ptr _ from <- pure fromPtr
TypeName n <- pure from
Just _ <- getUnion n
guard (from == to)
raise2 $ unionPeek name addrRef to fromPtr
wrappedStructPeek
:: forall r s
. (HasErr r, HasRenderElem r, HasRenderParams r, HasSpecInfo r)
=> CName
-> Ref s AddrDoc
-> CName
-> CType
-> Stmt s r (Ref s ValueDoc)
wrappedStructPeek name addrRef toName fromPtr = case fromPtr of
Ptr _ from@(TypeName n) | n == toName -> do
ty <- cToHsTypeWithHoles DoPreserve from
stmtC (Just ty) name $ do
AddrDoc addr <- use addrRef
tellImport (TermName "peekSomeCStruct")
tellImport (TermName "forgetExtensions")
pure $
IOAction
( ValueDoc
("peekSomeCStruct" <+> parens ("forgetExtensions" <+> addr))
)
Ptr _ from@(Ptr Const (TypeName n)) | n == toName -> do
ty <- cToHsTypeWithHoles DoPreserve from
stmtC (Just ty) name $ do
AddrDoc addr <- use addrRef
tellImport (TermName "peekSomeCStruct")
tellImport (TermName "forgetExtensions")
tellImportWith ''Storable 'peek
pure $
IOAction
(ValueDoc ("peekSomeCStruct . forgetExtensions =<< peek" <+> addr))
_ -> throw $ "Unhandled WrappedStruct peek from " <> show fromPtr
wrappedChildStructPeek
:: forall r s
. (HasErr r, HasRenderElem r, HasRenderParams r, HasSpecInfo r)
=> CName
-> Ref s AddrDoc
-> CName
-> CType
-> Stmt s r (Ref s ValueDoc)
wrappedChildStructPeek name addrRef toName fromPtr = case fromPtr of
Ptr _ from@(TypeName n) | n == toName -> do
ty <- cToHsTypeWithHoles DoPreserve from
stmtC (Just ty) name $ do
AddrDoc addr <- use addrRef
tellImportWith (TyConName "Inheritable") (TermName "peekSomeCChild")
pure $ IOAction (ValueDoc ("peekSomeCChild" <+> addr))
Ptr _ from@(Ptr Const (TypeName n)) | n == toName -> do
ty <- cToHsTypeWithHoles DoPreserve from
stmtC (Just ty) name $ do
AddrDoc addr <- use addrRef
tellImportWith (TyConName "Inheritable") (TermName "peekSomeCChild")
tellImportWith ''Storable 'peek
pure $ IOAction (ValueDoc ("peekSomeCChild =<< peek" <+> addr))
_ -> throw $ "Unhandled WrappedStruct peek from " <> show fromPtr
unionPeek
:: forall r s
. (HasErr r, HasRenderElem r, HasSpecInfo r, HasRenderParams r)
=> CName
-> Ref s AddrDoc
-> CType
-> CType
-> Stmt s r (Ref s ValueDoc)
unionPeek name addrRef _to fromPtr = failToError (V.singleton . T.pack) $ do
RenderParams{..} <- input
Ptr _ from <- pure fromPtr
TypeName n <- pure from
ty <- cToHsTypeWithHoles DoPreserve from
raise $ stmtC (Just ty) name $ do
discs <-
catMaybes
<$> sequenceV
[ useViaNameMaybe (unCName udSiblingName)
| UnionDiscriminator{..} <- toList unionDiscriminators
, udUnionType == n
]
ValueDoc discDoc <- case discs of
[] -> throw ("Unable to find union discriminator for " <> unCName n)
[d] -> pure d
_ -> throw ("Found multiple union discriminators for " <> unCName n)
let peekName = TermName $ "peek" <> unName (mkTyName n)
AddrDoc addr <- use addrRef
tellImport peekName
pure $ IOAction (ValueDoc (pretty peekName <+> discDoc <+> addr))
byteStringPeek
:: forall a r s
. ( HasErr r
, HasRenderElem r
, HasSpecInfo r
, HasRenderParams r
, HasSiblingInfo a r
, Show a
)
=> CName
-> Lengths
-> Ref s AddrDoc
-> CType
-> Stmt s r (Ref s ValueDoc)
byteStringPeek name lengths addrRef =
stmtC (Just (ConT ''ByteString)) name . \case
Ptr _ (Ptr Const Char) -> do
AddrDoc addr <- use addrRef
tellImport 'BS.packCString
tellImportWith ''Storable 'peek
pure . IOAction $ ValueDoc ("packCString =<< peek" <+> addr)
Ptr _ Char -> do
tellImport 'BS.packCString
AddrDoc addr <- use addrRef
pure . IOAction $ ValueDoc ("packCString" <+> addr)
Ptr _ Void | _ :<| V.Empty <- lengths -> do
lenRef <- getLenRef @a lengths
tellImport 'BS.packCStringLen
tellImport 'castPtr
tellImport ''CChar
AddrDoc addr <- use addrRef
ValueDoc lenVal <- use lenRef
let castAddr = "castPtr @() @CChar" <+> addr
pure . IOAction $
ValueDoc
("packCStringLen " <+> align (tupled [castAddr, lenVal]))
TODO : These next two patterns have different " levelness " but the same
Ptr _ (Array NonConst (SymbolicArraySize _) Char) -> do
tellImport 'BS.packCString
tellImport (TermName "lowerArrayPtr")
AddrDoc addr <- use addrRef
pure . IOAction $
ValueDoc
("packCString" <+> parens ("lowerArrayPtr" <+> addr))
Array NonConst (SymbolicArraySize p) Char -> do
RenderParams{..} <- input
tellImport 'BS.packCString
tellImport (TermName "lowerArrayPtr")
AddrDoc addr <- use addrRef
let size = mkPatternName p
tellImport size
pure . IOAction $
ValueDoc
("packCString . lowerArrayPtr @CChar @" <> pretty size <+> "$" <+> addr)
Ptr _ (Array NonConst size (TypeName "uint8_t"))
| case size of
SymbolicArraySize _ -> True
NumericArraySize _ -> True
_ -> False ->
do
let fn = "peekByteStringFromSizedVectorPtr"
tellImport (TermName fn)
AddrDoc addr <- use addrRef
pure . IOAction $ ValueDoc (pretty fn <+> addr)
t -> throw ("Unhandled conversion to ByteString from " <> show t)
maybePeek'
:: ( HasErr r
, HasRenderElem r
, HasSpecInfo r
, HasRenderParams r
, HasSiblingInfo a r
, Show a
, HasStmts r
)
=> CName
-> Lengths
-> Ref s AddrDoc
-> CType
-> MarshalScheme a
-> Stmt s r (Ref s ValueDoc)
maybePeek' name lengths addrRef fromPtr to = case fromPtr of
Ptr _ from@(Ptr _ fromElem) -> do
let maybePtrDoc = name
notNullPtrDoc <- freshName (Just "j")
ptrTy <- cToHsTypeWithHoles DoPreserve from
ptr <- stmtC (Just ptrTy) maybePtrDoc $ do
AddrDoc addr <- use addrRef
ptrTDoc <- renderTypeHighPrec =<< cToHsTypeWithHoles DoPreserve from
tellImportWith ''Storable 'peek
pure $ IOAction (AddrDoc ("peek @" <> ptrTDoc <+> addr))
elemTy <- cToHsTypeWithHoles DoPreserve fromElem
r <- stmtC (Just (ConT ''Maybe :@ elemTy)) name $ do
AddrDoc ptrDoc <- use ptr
subPeek <- renderSubStmtsIO $ do
ptrRef <- pureStmt (AddrDoc (pretty notNullPtrDoc))
runNonDetMaybe (peekIdiomatic name lengths from ptrRef to) >>= \case
Nothing -> throw "Nothing to peek to fill Maybe"
Just p -> pure p
tellImport 'maybePeek
pure
. IOAction
. ValueDoc
$ "maybePeek"
<+> parens ("\\" <> pretty notNullPtrDoc <+> "->" <+> subPeek)
<+> ptrDoc
freeNames [notNullPtrDoc]
pure r
t -> throw ("Unhandled conversion to Maybe from " <> show t)
vectorPeek
:: forall a r s
. ( HasErr r
, HasRenderElem r
, HasSpecInfo r
, HasRenderParams r
, HasSiblingInfo a r
, Show a
, HasStmts r
)
=> CName
-> Vector ParameterLength
-> Ref s AddrDoc
-> CType
-> MarshalScheme a
-> Nullable
-> Stmt s r (Ref s ValueDoc)
vectorPeek name lengths addrRef fromPtr toElem nullable = case fromPtr of
Ptr _ (Ptr _ fromElem) | NamedLength _ :<| lenTail <- lengths -> do
elemPtrRef <- storablePeek name addrRef fromPtr
lenRef <- getLenRef @a lengths
vectorPeekWithLenRef name toElem elemPtrRef fromElem lenTail lenRef nullable
Ptr _ (Array _ (SymbolicArraySize len) fromElem) -> do
RenderParams{..} <- input
tDoc <- renderTypeHighPrec =<< cToHsTypeWithHoles DoPreserve fromElem
let lenName = mkPatternName len
castedAddrRef <-
stmt Nothing Nothing $
Pure InlineOnce <$> do
tellImport (TermName "lowerArrayPtr")
tellImport lenName
AddrDoc addr <- use addrRef
pure . AddrDoc $ "lowerArrayPtr @" <> tDoc <+> addr
lenRef <- pureStmt (ValueDoc (pretty lenName))
vectorPeekWithLenRef
name
toElem
castedAddrRef
fromElem
V.empty
lenRef
nullable
FIXME : , do this initial pointer peeking elsewhere please !
Ptr _ fromElem | (V.uncons -> Just (_, lenTail)) <- lengths -> do
lenRef <- getLenRef @a lengths
vectorPeekWithLenRef name toElem addrRef fromElem lenTail lenRef nullable
t -> throw ("Unhandled conversion to Vector from " <> show t)
vectorPeekWithLenRef
:: forall a r s
. ( HasErr r
, HasRenderElem r
, HasSpecInfo r
, HasRenderParams r
, HasSiblingInfo a r
, Show a
, HasStmts r
)
=> CName
-> MarshalScheme a
-> Ref s AddrDoc
-> CType
-> Vector ParameterLength
-> Ref s ValueDoc
-> Nullable
-> Stmt s r (Ref s ValueDoc)
vectorPeekWithLenRef name toElem addrRef fromElem lenTail lenRef nullable = do
t <- cToHsTypeWithHoles DoPreserve fromElem
stmtC (Just (ConT ''Vector :@ t)) name $ do
indexVar <- freshName (Just "i")
ValueDoc lenDoc <- case nullable of
NotNullable -> use lenRef
Nullable ->
use
=<< stmt
Nothing
(Just (unCName name <> "Length"))
( do
AddrDoc addr <- use addrRef
ValueDoc lenDoc <- use lenRef
tellImport 'nullPtr
pure
. Pure NeverInline
. ValueDoc
$ "if"
<+> addr
<+> "== nullPtr then 0 else"
<+> lenDoc
)
subPeek <- renderSubStmtsIO $ do
indexRef <- pureStmt (pretty indexVar)
elemAddrRef <- stmt Nothing Nothing $ do
(elemSize, _elemAlign) <- getTypeSize fromElem
indexDoc <- use indexRef
AddrDoc addr <- raise $ use addrRef
Pure InlineOnce . AddrDoc <$> do
tellImport (TermName "advancePtrBytes")
elemPtrTyDoc <-
renderType
. (ConT ''Ptr :@)
=<< cToHsTypeWithHoles DoPreserve fromElem
pure $
parens
( addr
<+> "`advancePtrBytes`"
<+> parens (viaShow elemSize <+> "*" <+> indexDoc)
<+> "::"
<+> elemPtrTyDoc
)
runNonDetMaybe
( peekIdiomatic
(CName (unCName name <> "Elem"))
lenTail
(Ptr Const fromElem)
elemAddrRef
toElem
)
>>= \case
Nothing -> throw "Nothing to peek to fill Vector"
Just p -> pure p
freeNames [indexVar]
tellImport 'V.generateM
pure . IOAction . ValueDoc $
"generateM"
<+> lenDoc
<+> parens
("\\" <> pretty indexVar <+> "->" <+> subPeek)
eitherWord32Peek
:: forall a r s
. ( HasErr r
, HasRenderElem r
, HasSpecInfo r
, HasRenderParams r
, HasSiblingInfo a r
, Show a
, HasStmts r
)
=> CName
-> Lengths
-> Ref s AddrDoc
-> CType
-> MarshalScheme a
-> Stmt s r (Ref s ValueDoc)
eitherWord32Peek name lengths addr fromPtr toElem = case fromPtr of
Ptr _ (Ptr _ fromElem) | (NamedLength len) :<| _ <- lengths -> do
mRef <-
note "Unable to get wrapped peek for EitherWord32"
=<< runNonDetMaybe
( peekIdiomatic
name
lengths
fromPtr
addr
(Maybe (Vector NotNullable toElem))
)
elemTy <- cToHsTypeWithHoles DoPreserve fromElem
stmtC
(Just (ConT ''Either :@ ConT ''Word32 :@ (ConT ''Vector :@ elemTy)))
name
. fmap (Pure NeverInline)
$ do
ValueDoc lenName <- useViaName (unCName len)
ValueDoc m <- use mRef
pure
. ValueDoc
$ "maybe"
<+> parens ("Left" <+> lenName)
<+> "Right"
<+> m
t -> throw ("Unhandled conversion to EitherWord32 from " <> show t)
tuplePeek
:: forall a r s
. ( HasErr r
, HasRenderElem r
, HasSpecInfo r
, HasRenderParams r
, HasSiblingInfo a r
, Show a
, HasStmts r
)
=> CName
-> Ref s AddrDoc
-> CType
-> MarshalScheme a
-> Stmt s r (Ref s ValueDoc)
tuplePeek name addrRef fromPtr toElem = case fromPtr of
Ptr _ aTy@(Array NonConst (NumericArraySize len) fromElem) -> do
(elemSize, _elemAlign) <- getTypeSize fromElem
tupT <- cToHsTypeWithHoles DoNotPreserve aTy
stmtC (Just tupT) name $ do
Case the array pointer to a pointer to the first element
tupPtrRef <-
stmt Nothing (Just ("p" <> unCName name)) . fmap (Pure InlineOnce) $ do
tellImport (TermName "lowerArrayPtr")
tDoc <- renderTypeHighPrec =<< cToHsTypeWithHoles DoPreserve fromElem
AddrDoc addr <- use addrRef
pure $ "lowerArrayPtr @" <> tDoc <+> addr
let
advance i =
stmt Nothing Nothing . fmap (Pure InlineOnce . AddrDoc) $ do
tellImport (TermName "advancePtrBytes")
tupPtrDoc <- use tupPtrRef
elemPtrTyDoc <-
renderType
. (ConT ''Ptr :@)
=<< cToHsTypeWithHoles DoPreserve fromElem
pure
( parens
( tupPtrDoc
<+> "`advancePtrBytes`"
<+> viaShow (elemSize * i)
<+> "::"
<+> elemPtrTyDoc
)
)
subPeeks <- forV [0 .. len - 1] $ \i -> do
elemPtrRef <- advance (fromIntegral i)
note "Unable to get tuple element peek"
=<< runNonDetMaybe
( peekIdiomatic
(CName (unCName name <> show i))
mempty
(Ptr Const fromElem)
elemPtrRef
toElem
)
Pure InlineOnce . ValueDoc <$> do
subPeekDocs <- traverseV (fmap unValueDoc . use @r) subPeeks
pure $ align (tupled subPeekDocs)
t -> throw ("Unhandled conversion to Tuple from " <> show t)
getLenRef
:: forall a r s
. ( HasErr r
, HasRenderElem r
, HasRenderParams r
, HasSpecInfo r
, HasSiblingInfo a r
, Show a
)
=> Lengths
-> Stmt s r (Ref s ValueDoc)
getLenRef lengths = context "getLenRef" $ do
RenderParams{..} <- input
stmt Nothing Nothing $ case lengths of
Empty -> throw "Trying to allocate something with no length"
NamedLength len :<| _ -> do
ValueDoc value <- useViaName (unCName len)
pure . Pure AlwaysInline . ValueDoc $ "fromIntegral" <+> value
NamedMemberLength struct member :<| _ -> do
ValueDoc structValue <- useViaName (unCName struct)
case complexMemberLengthFunction struct member structValue of
Just complex -> Pure InlineOnce . ValueDoc <$> complex
Nothing -> do
SiblingInfo{..} <- getSiblingInfo @a struct
structName <-
let nonStruct =
throw $
"Trying to get length member from a non-struct type "
<> show siScheme
in case siScheme of
Length (TypeName n) _ _ ->
getStruct n >>= \case
Nothing -> nonStruct
Just _ -> pure n
Normal (TypeName n) ->
getStruct n >>= \case
Nothing -> nonStruct
Just _ -> pure n
_ -> nonStruct
structTyDoc <-
renderType
=<< note
"Unable to get type for struct with length specifying member for allocation"
=<< schemeTypeNegative siScheme
tellImportWithAll (mkTyName structName)
pure
. Pure AlwaysInline
. ValueDoc
$ "fromIntegral $"
<+> pretty (mkMemberName structName member)
<+> parens (structValue <+> "::" <+> structTyDoc)
NamedConstantLength n :<| _ ->
pure . Pure AlwaysInline . ValueDoc . pretty . mkPatternName $ n
NullTerminated :<| _ -> throw "Trying to allocate a null terminated array"
Utils
stmtC
:: forall a r s
. (Typeable a, Coercible a (Doc ()))
=> Maybe Type
-> CName
-> Stmt s r (Value a)
-> Stmt s r (Ref s a)
stmtC t n = stmt t (Just (unCName n))
|
df727d41dbfaf8f6747b892b3ba83f9de6d7b1552541a182e12084d768c8c652 | input-output-hk/project-icarus-importer | Abstract.hs | # OPTIONS_GHC -fno - warn - orphans #
-- | Abstract definition of a wallet
module Wallet.Abstract (
-- * Abstract definition of a wallet
Wallet(..)
, Ours
, Pending
, WalletConstr
, mkDefaultWallet
, walletBoot
, applyBlocks
-- * Auxiliary operations
, balance
, txIns
, txOuts
, updateUtxo
, updatePending
, utxoRestrictToOurs
) where
import Universum
import qualified Data.Foldable as Fold
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Text.Buildable
import Formatting (bprint)
import Pos.Util.Chrono
import Serokell.Util (mapJson)
import Util
import UTxO.DSL
{-------------------------------------------------------------------------------
Wallet type class
-------------------------------------------------------------------------------}
-- | Check if an address is ours
type Ours a = a -> Bool
-- | Pending transactions
type Pending h a = Map (h (Transaction h a)) (Transaction h a)
-- | Abstract wallet interface
data Wallet h a = Wallet {
-- MAIN API
-- | Return the total balance of the wallet (see 'available')
totalBalance :: Value
-- | Return the available balance of the wallet (see 'total')
, availableBalance :: Value
-- | Notify the wallet of a new block
, applyBlock :: Block h a -> Wallet h a
-- | Submit a new transaction to be included in the blockchain
, newPending :: Transaction h a -> Maybe (Wallet h a)
-- | Rollback
, rollback :: Wallet h a
-- AUXILIARY API
-- | Current set of pending transactions
, pending :: Pending h a
| Wallet 's current ( ignoring pending transactions )
, utxo :: Utxo h a
| Wallet 's expected ( if supported )
, expectedUtxo :: Utxo h a
-- | Addresses that belong to the wallet
, ours :: Ours a
-- | Change from the pending transactions
, change :: Utxo h a
| Available
--
-- This is the UTxO with the inputs spent by the pending transactions
-- removed.
, available :: Utxo h a
-- | Total UTxO
--
This is the available where we add back the change from the
-- pending transactions.
, total :: Utxo h a
-- | Internal state for debugging purposes
, dumpState :: Text
}
-- | Apply multiple blocks
applyBlocks :: Wallet h a -> Chain h a -> Wallet h a
applyBlocks w0 bs = foldl' applyBlock w0 bs
-- | Type of a wallet constructor
--
-- See <-typed.com/blog/2018/03/oop-in-haskell/> for a
-- detailed discussion of the approach we take.
type WalletConstr h a st = (st -> Wallet h a) -> (st -> Wallet h a)
-- | Default wallet constructor
--
-- This does not pick any particular implementation, but provides some
-- default implementations of some of the wallet methods in terms of the
-- other methods.
mkDefaultWallet
:: forall h a st. (Hash h a, Ord a, Buildable st)
=> Lens' st (Pending h a)
-> WalletConstr h a st
mkDefaultWallet l self st = Wallet {
-- Dealing with pending
pending = st ^. l
, newPending = \tx -> do
-- Here we check that the inputs to the given transaction are a
-- subset of the available unspent transaction outputs that aren't
-- part of a currently pending transaction.
let x = trIns tx :: Set (Input h a)
y = utxoDomain (available this) :: Set (Input h a)
case x `Set.isSubsetOf` y of
True -> Just $ self (st & l %~ Map.insert (hash tx) tx)
False -> Nothing
-- UTxOs
, available = utxoRemoveInputs (txIns (pending this)) (utxo this)
, change = utxoRestrictToOurs (ours this) (txOuts (pending this))
, total = available this `utxoUnion` change this
-- Balance
, availableBalance = balance $ available this
, totalBalance = balance $ total this
-- Debugging
, dumpState = pretty st
-- Functions without a default
, utxo = error "mkDefaultWallet: no default for utxo"
, expectedUtxo = error "mkDefaultWallet: no default for expectedUtxo"
, ours = error "mkDefaultWallet: no default for ours"
, applyBlock = error "mkDefaultWallet: no default for applyBlock"
, rollback = error "mkDefaultWallet: no default for rollback"
}
where
this = self st
-- | Wallet state after the bootstrap transaction
walletBoot :: (Ours a -> Wallet h a) -- ^ Wallet constructor
-> Ours a -> Transaction h a -> Wallet h a
walletBoot mkWallet p boot = applyBlock (mkWallet p) (OldestFirst [boot])
{-------------------------------------------------------------------------------
Auxiliary operations
-------------------------------------------------------------------------------}
balance :: Utxo h a -> Value
balance = sum . map outVal . Map.elems . utxoToMap
txIns :: (Hash h a, Foldable f) => f (Transaction h a) -> Set (Input h a)
txIns = Set.unions . map trIns . Fold.toList
txOuts :: (Hash h a, Foldable f) => f (Transaction h a) -> Utxo h a
txOuts = utxoUnions . map trUtxo . Fold.toList
updateUtxo :: forall h a. Hash h a
=> Ours a -> Block h a -> Utxo h a -> Utxo h a
updateUtxo p b = remSpent . addNew
where
addNew, remSpent :: Utxo h a -> Utxo h a
addNew = utxoUnion (utxoRestrictToOurs p (txOuts b))
remSpent = utxoRemoveInputs (txIns b)
updatePending :: forall h a. Hash h a => Block h a -> Pending h a -> Pending h a
updatePending b = Map.filter $ \t -> disjoint (trIns t) (txIns b)
utxoRestrictToOurs :: Ours a -> Utxo h a -> Utxo h a
utxoRestrictToOurs = utxoRestrictToAddr
{-------------------------------------------------------------------------------
Pretty-printing
-------------------------------------------------------------------------------}
instance (Hash h a, Buildable a) => Buildable (Pending h a) where
build = bprint mapJson
| null | https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/wallet-new/test/unit/Wallet/Abstract.hs | haskell | | Abstract definition of a wallet
* Abstract definition of a wallet
* Auxiliary operations
------------------------------------------------------------------------------
Wallet type class
------------------------------------------------------------------------------
| Check if an address is ours
| Pending transactions
| Abstract wallet interface
MAIN API
| Return the total balance of the wallet (see 'available')
| Return the available balance of the wallet (see 'total')
| Notify the wallet of a new block
| Submit a new transaction to be included in the blockchain
| Rollback
AUXILIARY API
| Current set of pending transactions
| Addresses that belong to the wallet
| Change from the pending transactions
This is the UTxO with the inputs spent by the pending transactions
removed.
| Total UTxO
pending transactions.
| Internal state for debugging purposes
| Apply multiple blocks
| Type of a wallet constructor
See <-typed.com/blog/2018/03/oop-in-haskell/> for a
detailed discussion of the approach we take.
| Default wallet constructor
This does not pick any particular implementation, but provides some
default implementations of some of the wallet methods in terms of the
other methods.
Dealing with pending
Here we check that the inputs to the given transaction are a
subset of the available unspent transaction outputs that aren't
part of a currently pending transaction.
UTxOs
Balance
Debugging
Functions without a default
| Wallet state after the bootstrap transaction
^ Wallet constructor
------------------------------------------------------------------------------
Auxiliary operations
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Pretty-printing
------------------------------------------------------------------------------ | # OPTIONS_GHC -fno - warn - orphans #
module Wallet.Abstract (
Wallet(..)
, Ours
, Pending
, WalletConstr
, mkDefaultWallet
, walletBoot
, applyBlocks
, balance
, txIns
, txOuts
, updateUtxo
, updatePending
, utxoRestrictToOurs
) where
import Universum
import qualified Data.Foldable as Fold
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Text.Buildable
import Formatting (bprint)
import Pos.Util.Chrono
import Serokell.Util (mapJson)
import Util
import UTxO.DSL
type Ours a = a -> Bool
type Pending h a = Map (h (Transaction h a)) (Transaction h a)
data Wallet h a = Wallet {
totalBalance :: Value
, availableBalance :: Value
, applyBlock :: Block h a -> Wallet h a
, newPending :: Transaction h a -> Maybe (Wallet h a)
, rollback :: Wallet h a
, pending :: Pending h a
| Wallet 's current ( ignoring pending transactions )
, utxo :: Utxo h a
| Wallet 's expected ( if supported )
, expectedUtxo :: Utxo h a
, ours :: Ours a
, change :: Utxo h a
| Available
, available :: Utxo h a
This is the available where we add back the change from the
, total :: Utxo h a
, dumpState :: Text
}
applyBlocks :: Wallet h a -> Chain h a -> Wallet h a
applyBlocks w0 bs = foldl' applyBlock w0 bs
type WalletConstr h a st = (st -> Wallet h a) -> (st -> Wallet h a)
mkDefaultWallet
:: forall h a st. (Hash h a, Ord a, Buildable st)
=> Lens' st (Pending h a)
-> WalletConstr h a st
mkDefaultWallet l self st = Wallet {
pending = st ^. l
, newPending = \tx -> do
let x = trIns tx :: Set (Input h a)
y = utxoDomain (available this) :: Set (Input h a)
case x `Set.isSubsetOf` y of
True -> Just $ self (st & l %~ Map.insert (hash tx) tx)
False -> Nothing
, available = utxoRemoveInputs (txIns (pending this)) (utxo this)
, change = utxoRestrictToOurs (ours this) (txOuts (pending this))
, total = available this `utxoUnion` change this
, availableBalance = balance $ available this
, totalBalance = balance $ total this
, dumpState = pretty st
, utxo = error "mkDefaultWallet: no default for utxo"
, expectedUtxo = error "mkDefaultWallet: no default for expectedUtxo"
, ours = error "mkDefaultWallet: no default for ours"
, applyBlock = error "mkDefaultWallet: no default for applyBlock"
, rollback = error "mkDefaultWallet: no default for rollback"
}
where
this = self st
-> Ours a -> Transaction h a -> Wallet h a
walletBoot mkWallet p boot = applyBlock (mkWallet p) (OldestFirst [boot])
balance :: Utxo h a -> Value
balance = sum . map outVal . Map.elems . utxoToMap
txIns :: (Hash h a, Foldable f) => f (Transaction h a) -> Set (Input h a)
txIns = Set.unions . map trIns . Fold.toList
txOuts :: (Hash h a, Foldable f) => f (Transaction h a) -> Utxo h a
txOuts = utxoUnions . map trUtxo . Fold.toList
updateUtxo :: forall h a. Hash h a
=> Ours a -> Block h a -> Utxo h a -> Utxo h a
updateUtxo p b = remSpent . addNew
where
addNew, remSpent :: Utxo h a -> Utxo h a
addNew = utxoUnion (utxoRestrictToOurs p (txOuts b))
remSpent = utxoRemoveInputs (txIns b)
updatePending :: forall h a. Hash h a => Block h a -> Pending h a -> Pending h a
updatePending b = Map.filter $ \t -> disjoint (trIns t) (txIns b)
utxoRestrictToOurs :: Ours a -> Utxo h a -> Utxo h a
utxoRestrictToOurs = utxoRestrictToAddr
instance (Hash h a, Buildable a) => Buildable (Pending h a) where
build = bprint mapJson
|
a4de8a699c239854411ff5acc7218994a44fd20d2852f8806b4eea65ca3337e9 | mirage/ocaml-xenstore-server | sockets.ml |
* Copyright ( C ) Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
open Sexplib.Std
open Xenstore
* A byte - level transport over the Unix domain socket
(* The unix domain socket may not exist, or we may get a connection
refused error if the server is in the middle of restarting. *)
let initial_retry_interval = 0.1 (* seconds *)
let max_retry_interval = 5.0 (* seconds *)
let retry_max = 100 (* attempts *)
let xenstored_socket = ref "/var/run/xenstored/socket"
open Lwt
type 'a t = 'a Lwt.t
let return x = return x
let ( >>= ) m f = m >>= f
module Input = struct
type t = {
fd : Lwt_unix.file_descr ;
full_buffer : Cstruct.t ; ( * the maximum amount of space used for buffering
module Input = struct
type t = {
fd: Lwt_unix.file_descr;
full_buffer: Cstruct.t; (* the maximum amount of space used for buffering *)
remaining un - acknowledged data
seq of next , un - acknowledged byte . See
}
let make fd size =
let full_buffer = Cstruct.create size in
let available = Cstruct.sub full_buffer 0 0 in
let seq = 0L in
{ fd; full_buffer; available; seq }
let next t =
if Cstruct.len t.available > 0
then return (t.seq, t.available)
else begin
Lwt_bytes.read t.fd t.full_buffer.Cstruct.buffer t.full_buffer.Cstruct.off t.full_buffer.Cstruct.len >>= fun n ->
t.available <- Cstruct.sub t.full_buffer 0 n;
if n = 0
then fail End_of_file
else return (t.seq, t.available)
end
let ack t seq =
let bytes_consumed = Int64.(to_int (sub seq t.seq)) in
t.available <- Cstruct.shift t.available bytes_consumed;
t.seq <- seq;
return ()
end
*)
let complete op fd buf =
let ofs = buf.Cstruct.off in
let len = buf.Cstruct.len in
let buf = buf.Cstruct.buffer in
let rec loop acc fd buf ofs len =
op fd buf ofs len >>= fun n ->
let len' = len - n in
let acc' = acc + n in
if len' = 0 || n = 0
then return acc'
else loop acc' fd buf (ofs + n) len' in
loop 0 fd buf ofs len >>= fun n ->
if n = 0 && len <> 0
then fail End_of_file
else return ()
module Output = struct
type t = {
fd : Lwt_unix.file_descr ;
full_buffer : Cstruct.t ;
mutable available : Cstruct.t ;
mutable seq : int64 ; ( * seq of next byte to write
module Output = struct
type t = {
fd: Lwt_unix.file_descr;
full_buffer: Cstruct.t;
mutable available: Cstruct.t;
mutable seq: int64; (* seq of next byte to write *)
}
let make fd size =
let full_buffer = Cstruct.create size in
let available = full_buffer in
let seq = 0L in
{ fd; full_buffer; available; seq }
let next t =
if Cstruct.len t.available = 0 then t.available <- t.full_buffer;
return (t.seq, t.available)
let ack t seq =
let bytes_to_send = Int64.(to_int (sub seq t.seq)) in
complete Lwt_bytes.write t.fd (Cstruct.sub t.available 0 bytes_to_send) >>= fun () ->
t.available <- Cstruct.shift t.available bytes_to_send;
t.seq <- seq;
return ()
end
*)
(* Individual connections *)
type connection = {
fd: Lwt_unix.file_descr;
sockaddr: Lwt_unix.sockaddr;
read_buffer: Cstruct.t;
write_buffer: Cstruct.t;
(*
input: Input.t;
output: Output.t;
*)
}
let alloc (fd, sockaddr) =
let read_buffer = Cstruct.create (Protocol.Header.sizeof + Protocol.xenstore_payload_max) in
let write_buffer = Cstruct.create (Protocol.Header.sizeof + Protocol.xenstore_payload_max) in
return { fd; sockaddr; read_buffer; write_buffer }
let create () =
let sockaddr = Lwt_unix.ADDR_UNIX(!xenstored_socket) in
let fd = Lwt_unix.socket Lwt_unix.PF_UNIX Lwt_unix.SOCK_STREAM 0 in
let start = Unix.gettimeofday () in
let rec retry n interval =
if n > retry_max
then fail (Failure (Printf.sprintf "Failed to connect to xenstore after %.0f seconds" (Unix.gettimeofday () -. start)))
else
Lwt.catch
(fun () ->
Lwt_unix.connect fd sockaddr
) (fun _ ->
Lwt_unix.sleep interval
>>= fun () ->
retry (n + 1) (interval +. 0.1)
) in
retry 0 initial_retry_interval >>= fun () ->
alloc (fd, sockaddr)
let destroy { fd } = Lwt_unix.close fd
module Reader = struct
type t = connection
let next t = Input.next t.input
let ack t seq = Input.ack t.input seq
end
module = struct
type t = connection
let next t = Output.next t.output
let ack t seq = Output.ack t.output seq
end
module PBuffer = struct
type handle = int64
type t = {
handle : handle ;
buffer : Cstruct.t ;
}
let table : ( int64 , t ) = Hashtbl.create 10
open Lwt
let fresh_handle =
let next = ref 0L in
fun ( ) - >
let this = ! next in
next : = Int64.succ ! next ;
this
let create size =
let handle = fresh_handle ( ) in
let buffer = Cstruct.create size in
let t = { handle ; buffer } in
Hashtbl.replace table handle t ;
return t
let destroy t =
Hashtbl.remove table t.handle ;
return ( )
let get_cstruct t = t.buffer
let handle t = t.handle
let lookup handle =
if table handle
then return ( Some ( Hashtbl.find table handle ) )
else return None
end
module Reader = struct
type t = connection
let next t = Input.next t.input
let ack t seq = Input.ack t.input seq
end
module Writer = struct
type t = connection
let next t = Output.next t.output
let ack t seq = Output.ack t.output seq
end
module PBuffer = struct
type handle = int64
type t = {
handle: handle;
buffer: Cstruct.t;
}
let table : (int64, t) Hashtbl.t = Hashtbl.create 10
open Lwt
let fresh_handle =
let next = ref 0L in
fun () ->
let this = !next in
next := Int64.succ !next;
this
let create size =
let handle = fresh_handle () in
let buffer = Cstruct.create size in
let t = { handle; buffer } in
Hashtbl.replace table handle t;
return t
let destroy t =
Hashtbl.remove table t.handle;
return ()
let get_cstruct t = t.buffer
let handle t = t.handle
let lookup handle =
if Hashtbl.mem table handle
then return (Some (Hashtbl.find table handle))
else return None
end
*)
let read { fd } = complete Lwt_bytes.read fd
let write { fd } = complete Lwt_bytes.write fd
let int_of_file_descr fd =
let fd = Lwt_unix.unix_file_descr fd in
let (fd: int) = Obj.magic fd in
fd
let address_of { fd } =
let creds = Lwt_unix.get_credentials fd in
let pid = creds.Lwt_unix.cred_pid in
Lwt.catch
(fun () ->
Lwt_io.with_file ~mode:Lwt_io.input
(Printf.sprintf "/proc/%d/cmdline" pid)
(fun ic ->
Lwt_io.read_line_opt ic
>>= fun cmdline ->
match cmdline with
| Some x -> return x
| None -> return "unknown")
>>= fun cmdline ->
(* Take only the binary name, stripped of directories *)
let filename =
try
let i = String.index cmdline '\000' in
String.sub cmdline 0 i
with Not_found -> cmdline in
let basename = Filename.basename filename in
let name = Printf.sprintf "%d:%s:%d" pid basename (int_of_file_descr fd) in
return (Uri.make ~scheme:"unix" ~path:name ())
) (fun _ ->
return (Uri.make ~scheme:"unix" ~path:(string_of_int pid) ())
)
let domain_of _ = 0
(* Servers which accept connections *)
type server = Lwt_unix.file_descr
let _ =
Make sure a write to a closed fd does n't cause us to quit
with
with SIGPIPE *)
Sys.set_signal Sys.sigpipe Sys.Signal_ignore
let listen () =
let sockaddr = Lwt_unix.ADDR_UNIX(!xenstored_socket) in
let fd = Lwt_unix.socket Lwt_unix.PF_UNIX Lwt_unix.SOCK_STREAM 0 in
Lwt.catch (fun () -> Lwt_unix.unlink !xenstored_socket) (fun _ -> return ())
>>= fun () ->
Lwt_unix.bind fd sockaddr;
Lwt_unix.listen fd 5;
return fd
let rec accept_forever fd process =
Lwt_unix.accept_n fd 16
>>= fun (conns, _exn_option) ->
let (_: unit Lwt.t list) = List.map (fun x -> alloc x >>= process) conns in
accept_forever fd process
type offset = unit [@@deriving sexp]
let get_read_offset _ = return ()
let get_write_offset _ = return ()
let flush _ _ = return ()
let enqueue t hdr response =
let reply_buf = t.write_buffer in
let payload_buf = Cstruct.shift reply_buf Protocol.Header.sizeof in
let next = Protocol.Response.marshal response payload_buf in
let length = next.Cstruct.off - payload_buf.Cstruct.off in
let hdr = Protocol.Header.({ hdr with len = length }) in
ignore (Protocol.Header.marshal hdr reply_buf);
write t (Cstruct.sub t.write_buffer 0 (Protocol.Header.sizeof + length))
let recv t _ =
let hdr = Cstruct.sub t.read_buffer 0 Protocol.Header.sizeof in
read t hdr >>= fun () ->
match Protocol.Header.unmarshal hdr with
| `Error x -> return ((), `Error x)
| `Ok x ->
let payload = Cstruct.sub t.read_buffer Protocol.Header.sizeof x.Protocol.Header.len in
read t payload >>= fun () ->
begin match Protocol.Request.unmarshal x payload with
| `Error y -> return ((), `BadRequest (x, y))
| `Ok y -> return ((), `Ok (x, y))
end
module Introspect = struct
let read { fd } = function
| [ "readable" ] -> Some (string_of_bool (Lwt_unix.readable fd))
| [ "writable" ] -> Some (string_of_bool (Lwt_unix.writable fd))
| _ -> None
let ls t = function
| [] -> [ "readable"; "writable" ]
| _ -> []
let write _ _ _ = false
end
| null | https://raw.githubusercontent.com/mirage/ocaml-xenstore-server/2a8ae397d2f9291107b5d9e9cfc6085fde8c0982/unix/sockets.ml | ocaml | The unix domain socket may not exist, or we may get a connection
refused error if the server is in the middle of restarting.
seconds
seconds
attempts
the maximum amount of space used for buffering
seq of next byte to write
Individual connections
input: Input.t;
output: Output.t;
Take only the binary name, stripped of directories
Servers which accept connections |
* Copyright ( C ) Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
open Sexplib.Std
open Xenstore
* A byte - level transport over the Unix domain socket
let xenstored_socket = ref "/var/run/xenstored/socket"
open Lwt
type 'a t = 'a Lwt.t
let return x = return x
let ( >>= ) m f = m >>= f
module Input = struct
type t = {
fd : Lwt_unix.file_descr ;
full_buffer : Cstruct.t ; ( * the maximum amount of space used for buffering
module Input = struct
type t = {
fd: Lwt_unix.file_descr;
remaining un - acknowledged data
seq of next , un - acknowledged byte . See
}
let make fd size =
let full_buffer = Cstruct.create size in
let available = Cstruct.sub full_buffer 0 0 in
let seq = 0L in
{ fd; full_buffer; available; seq }
let next t =
if Cstruct.len t.available > 0
then return (t.seq, t.available)
else begin
Lwt_bytes.read t.fd t.full_buffer.Cstruct.buffer t.full_buffer.Cstruct.off t.full_buffer.Cstruct.len >>= fun n ->
t.available <- Cstruct.sub t.full_buffer 0 n;
if n = 0
then fail End_of_file
else return (t.seq, t.available)
end
let ack t seq =
let bytes_consumed = Int64.(to_int (sub seq t.seq)) in
t.available <- Cstruct.shift t.available bytes_consumed;
t.seq <- seq;
return ()
end
*)
let complete op fd buf =
let ofs = buf.Cstruct.off in
let len = buf.Cstruct.len in
let buf = buf.Cstruct.buffer in
let rec loop acc fd buf ofs len =
op fd buf ofs len >>= fun n ->
let len' = len - n in
let acc' = acc + n in
if len' = 0 || n = 0
then return acc'
else loop acc' fd buf (ofs + n) len' in
loop 0 fd buf ofs len >>= fun n ->
if n = 0 && len <> 0
then fail End_of_file
else return ()
module Output = struct
type t = {
fd : Lwt_unix.file_descr ;
full_buffer : Cstruct.t ;
mutable available : Cstruct.t ;
mutable seq : int64 ; ( * seq of next byte to write
module Output = struct
type t = {
fd: Lwt_unix.file_descr;
full_buffer: Cstruct.t;
mutable available: Cstruct.t;
}
let make fd size =
let full_buffer = Cstruct.create size in
let available = full_buffer in
let seq = 0L in
{ fd; full_buffer; available; seq }
let next t =
if Cstruct.len t.available = 0 then t.available <- t.full_buffer;
return (t.seq, t.available)
let ack t seq =
let bytes_to_send = Int64.(to_int (sub seq t.seq)) in
complete Lwt_bytes.write t.fd (Cstruct.sub t.available 0 bytes_to_send) >>= fun () ->
t.available <- Cstruct.shift t.available bytes_to_send;
t.seq <- seq;
return ()
end
*)
type connection = {
fd: Lwt_unix.file_descr;
sockaddr: Lwt_unix.sockaddr;
read_buffer: Cstruct.t;
write_buffer: Cstruct.t;
}
let alloc (fd, sockaddr) =
let read_buffer = Cstruct.create (Protocol.Header.sizeof + Protocol.xenstore_payload_max) in
let write_buffer = Cstruct.create (Protocol.Header.sizeof + Protocol.xenstore_payload_max) in
return { fd; sockaddr; read_buffer; write_buffer }
let create () =
let sockaddr = Lwt_unix.ADDR_UNIX(!xenstored_socket) in
let fd = Lwt_unix.socket Lwt_unix.PF_UNIX Lwt_unix.SOCK_STREAM 0 in
let start = Unix.gettimeofday () in
let rec retry n interval =
if n > retry_max
then fail (Failure (Printf.sprintf "Failed to connect to xenstore after %.0f seconds" (Unix.gettimeofday () -. start)))
else
Lwt.catch
(fun () ->
Lwt_unix.connect fd sockaddr
) (fun _ ->
Lwt_unix.sleep interval
>>= fun () ->
retry (n + 1) (interval +. 0.1)
) in
retry 0 initial_retry_interval >>= fun () ->
alloc (fd, sockaddr)
let destroy { fd } = Lwt_unix.close fd
module Reader = struct
type t = connection
let next t = Input.next t.input
let ack t seq = Input.ack t.input seq
end
module = struct
type t = connection
let next t = Output.next t.output
let ack t seq = Output.ack t.output seq
end
module PBuffer = struct
type handle = int64
type t = {
handle : handle ;
buffer : Cstruct.t ;
}
let table : ( int64 , t ) = Hashtbl.create 10
open Lwt
let fresh_handle =
let next = ref 0L in
fun ( ) - >
let this = ! next in
next : = Int64.succ ! next ;
this
let create size =
let handle = fresh_handle ( ) in
let buffer = Cstruct.create size in
let t = { handle ; buffer } in
Hashtbl.replace table handle t ;
return t
let destroy t =
Hashtbl.remove table t.handle ;
return ( )
let get_cstruct t = t.buffer
let handle t = t.handle
let lookup handle =
if table handle
then return ( Some ( Hashtbl.find table handle ) )
else return None
end
module Reader = struct
type t = connection
let next t = Input.next t.input
let ack t seq = Input.ack t.input seq
end
module Writer = struct
type t = connection
let next t = Output.next t.output
let ack t seq = Output.ack t.output seq
end
module PBuffer = struct
type handle = int64
type t = {
handle: handle;
buffer: Cstruct.t;
}
let table : (int64, t) Hashtbl.t = Hashtbl.create 10
open Lwt
let fresh_handle =
let next = ref 0L in
fun () ->
let this = !next in
next := Int64.succ !next;
this
let create size =
let handle = fresh_handle () in
let buffer = Cstruct.create size in
let t = { handle; buffer } in
Hashtbl.replace table handle t;
return t
let destroy t =
Hashtbl.remove table t.handle;
return ()
let get_cstruct t = t.buffer
let handle t = t.handle
let lookup handle =
if Hashtbl.mem table handle
then return (Some (Hashtbl.find table handle))
else return None
end
*)
let read { fd } = complete Lwt_bytes.read fd
let write { fd } = complete Lwt_bytes.write fd
let int_of_file_descr fd =
let fd = Lwt_unix.unix_file_descr fd in
let (fd: int) = Obj.magic fd in
fd
let address_of { fd } =
let creds = Lwt_unix.get_credentials fd in
let pid = creds.Lwt_unix.cred_pid in
Lwt.catch
(fun () ->
Lwt_io.with_file ~mode:Lwt_io.input
(Printf.sprintf "/proc/%d/cmdline" pid)
(fun ic ->
Lwt_io.read_line_opt ic
>>= fun cmdline ->
match cmdline with
| Some x -> return x
| None -> return "unknown")
>>= fun cmdline ->
let filename =
try
let i = String.index cmdline '\000' in
String.sub cmdline 0 i
with Not_found -> cmdline in
let basename = Filename.basename filename in
let name = Printf.sprintf "%d:%s:%d" pid basename (int_of_file_descr fd) in
return (Uri.make ~scheme:"unix" ~path:name ())
) (fun _ ->
return (Uri.make ~scheme:"unix" ~path:(string_of_int pid) ())
)
let domain_of _ = 0
type server = Lwt_unix.file_descr
let _ =
Make sure a write to a closed fd does n't cause us to quit
with
with SIGPIPE *)
Sys.set_signal Sys.sigpipe Sys.Signal_ignore
let listen () =
let sockaddr = Lwt_unix.ADDR_UNIX(!xenstored_socket) in
let fd = Lwt_unix.socket Lwt_unix.PF_UNIX Lwt_unix.SOCK_STREAM 0 in
Lwt.catch (fun () -> Lwt_unix.unlink !xenstored_socket) (fun _ -> return ())
>>= fun () ->
Lwt_unix.bind fd sockaddr;
Lwt_unix.listen fd 5;
return fd
let rec accept_forever fd process =
Lwt_unix.accept_n fd 16
>>= fun (conns, _exn_option) ->
let (_: unit Lwt.t list) = List.map (fun x -> alloc x >>= process) conns in
accept_forever fd process
type offset = unit [@@deriving sexp]
let get_read_offset _ = return ()
let get_write_offset _ = return ()
let flush _ _ = return ()
let enqueue t hdr response =
let reply_buf = t.write_buffer in
let payload_buf = Cstruct.shift reply_buf Protocol.Header.sizeof in
let next = Protocol.Response.marshal response payload_buf in
let length = next.Cstruct.off - payload_buf.Cstruct.off in
let hdr = Protocol.Header.({ hdr with len = length }) in
ignore (Protocol.Header.marshal hdr reply_buf);
write t (Cstruct.sub t.write_buffer 0 (Protocol.Header.sizeof + length))
let recv t _ =
let hdr = Cstruct.sub t.read_buffer 0 Protocol.Header.sizeof in
read t hdr >>= fun () ->
match Protocol.Header.unmarshal hdr with
| `Error x -> return ((), `Error x)
| `Ok x ->
let payload = Cstruct.sub t.read_buffer Protocol.Header.sizeof x.Protocol.Header.len in
read t payload >>= fun () ->
begin match Protocol.Request.unmarshal x payload with
| `Error y -> return ((), `BadRequest (x, y))
| `Ok y -> return ((), `Ok (x, y))
end
module Introspect = struct
let read { fd } = function
| [ "readable" ] -> Some (string_of_bool (Lwt_unix.readable fd))
| [ "writable" ] -> Some (string_of_bool (Lwt_unix.writable fd))
| _ -> None
let ls t = function
| [] -> [ "readable"; "writable" ]
| _ -> []
let write _ _ _ = false
end
|
ea8e28cd066938c763d8c728888d7b9ba3c38d94bc2146b531309f524a108b15 | Clojure2D/clojure2d-examples | oscillating_objects_3_7.clj | (ns NOC.ch03.oscillating-objects-3-7
(:require [clojure2d.core :refer :all]
[fastmath.core :as m]
[fastmath.vector :as v]
[fastmath.random :as r])
(:import [fastmath.vector Vec2]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(def ^:const ^int w 640)
(def ^:const ^int h 360)
(defprotocol OscillatorProto
(oscillate [o])
(display [o canvas]))
(deftype Oscillator [^Vec2 angle ^Vec2 velocity ^Vec2 amplitude]
OscillatorProto
(oscillate [_]
(Oscillator. (v/add angle velocity) velocity amplitude))
(display [o canvas]
(let [^Vec2 xy (-> angle
(v/applyf #(m/sin %))
(v/emult amplitude))]
(-> canvas
(set-stroke 2.0)
(push-matrix)
(translate (/ w 2) (/ h 2))
(set-color :black)
(set-color 127 127 127 127)
(ellipse (.x xy) (.y xy) 32 32)
(set-color :black)
(line 0 0 (.x xy) (.y xy))
(ellipse (.x xy) (.y xy) 32 32 true)
(pop-matrix)))
o))
(defn make-oscillator
"Create random oscillator"
[]
(Oscillator. (Vec2. 0.0 0.0)
(v/generate-vec2 #(r/drand -0.05 0.05))
(Vec2. (r/drand 20 (/ w 2)) (r/drand 20 (/ h 2)))))
(defn draw
""
[canvas window _ state]
(let [movers (or state (repeatedly 10 #(make-oscillator)))]
(set-background canvas :white)
(mapv #(display (oscillate %) canvas) movers)))
(def window (show-window (canvas w h) "Oscillating objects 3_7" draw))
| null | https://raw.githubusercontent.com/Clojure2D/clojure2d-examples/9de82f5ac0737b7e78e07a17cf03ac577d973817/src/NOC/ch03/oscillating_objects_3_7.clj | clojure | (ns NOC.ch03.oscillating-objects-3-7
(:require [clojure2d.core :refer :all]
[fastmath.core :as m]
[fastmath.vector :as v]
[fastmath.random :as r])
(:import [fastmath.vector Vec2]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(def ^:const ^int w 640)
(def ^:const ^int h 360)
(defprotocol OscillatorProto
(oscillate [o])
(display [o canvas]))
(deftype Oscillator [^Vec2 angle ^Vec2 velocity ^Vec2 amplitude]
OscillatorProto
(oscillate [_]
(Oscillator. (v/add angle velocity) velocity amplitude))
(display [o canvas]
(let [^Vec2 xy (-> angle
(v/applyf #(m/sin %))
(v/emult amplitude))]
(-> canvas
(set-stroke 2.0)
(push-matrix)
(translate (/ w 2) (/ h 2))
(set-color :black)
(set-color 127 127 127 127)
(ellipse (.x xy) (.y xy) 32 32)
(set-color :black)
(line 0 0 (.x xy) (.y xy))
(ellipse (.x xy) (.y xy) 32 32 true)
(pop-matrix)))
o))
(defn make-oscillator
"Create random oscillator"
[]
(Oscillator. (Vec2. 0.0 0.0)
(v/generate-vec2 #(r/drand -0.05 0.05))
(Vec2. (r/drand 20 (/ w 2)) (r/drand 20 (/ h 2)))))
(defn draw
""
[canvas window _ state]
(let [movers (or state (repeatedly 10 #(make-oscillator)))]
(set-background canvas :white)
(mapv #(display (oscillate %) canvas) movers)))
(def window (show-window (canvas w h) "Oscillating objects 3_7" draw))
| |
f8015acb24eaf2ee94a887a3e460c4731ecdd1345ada2a8514af63e865711007 | Armael/cdcl | verif.ml | open Prelude
let verif (nb_vars, nb_clauses, clauses) values =
let tbl = Hashtbl.create nb_vars in
Initialize a hashtable with the values of the variables
Array.iteri (fun i b -> Hashtbl.add tbl (i+1) b) values;
let verif_clause clause =
List.fold_left (fun acc v ->
(if v > 0 then (Hashtbl.find tbl v)
else not (Hashtbl.find tbl (abs v))) || acc) false clause in
fold_stop (fun acc c ->
let nacc = acc && (verif_clause c) in
(nacc, nacc)) true clauses
| null | https://raw.githubusercontent.com/Armael/cdcl/44c9c0e48549a0433fe7f3819b15b5ca2f369ea6/src/verif.ml | ocaml | open Prelude
let verif (nb_vars, nb_clauses, clauses) values =
let tbl = Hashtbl.create nb_vars in
Initialize a hashtable with the values of the variables
Array.iteri (fun i b -> Hashtbl.add tbl (i+1) b) values;
let verif_clause clause =
List.fold_left (fun acc v ->
(if v > 0 then (Hashtbl.find tbl v)
else not (Hashtbl.find tbl (abs v))) || acc) false clause in
fold_stop (fun acc c ->
let nacc = acc && (verif_clause c) in
(nacc, nacc)) true clauses
| |
f55afba581fc506c81e71bbb14221a34252322d86f9b05f83d43464478ba66f6 | Helium4Haskell/helium | RightSection.hs | module RightSection where
test :: [Int]
test = filter (False `eqBool`) [1..10]
| null | https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/simple/typeerrors/Examples/RightSection.hs | haskell | module RightSection where
test :: [Int]
test = filter (False `eqBool`) [1..10]
| |
25bbf3ccd7e0b5daaa1d6033a12cc29edb226778a258774c98fb2bd5c40cc991 | na4zagin3/satyrographos | command_build__doc_make.ml | module StdList = List
open Satyrographos_testlib
open TestLib
open Shexp_process
let satyristes =
{|
(lang "0.0.3")
(doc
(name "example-doc")
(build
((make "build-doc")))
(dependencies (grcnum fonts-theano)))
|}
let makefile =
{|
PHONY: build-doc
build-doc:
@echo "Target: build-doc"
@echo "=============================="
@echo "$(SATYROGRAPHOS_PROJECT)" | grep -e 'pkg/Satyristes' >/dev/null ; echo "$$?"
|}
let env ~dest_dir:_ ~temp_dir : Satyrographos.Environment.t t =
let open Shexp_process.Infix in
let pkg_dir = FilePath.concat temp_dir "pkg" in
let prepare_pkg =
PrepareDist.empty pkg_dir
>> stdout_to (FilePath.concat pkg_dir "Satyristes") (echo satyristes)
>> stdout_to (FilePath.concat pkg_dir "README.md") (echo "@@README.md@@")
>> stdout_to (FilePath.concat pkg_dir "doc-example.saty") (echo "@@doc-example.saty@@")
>> stdout_to (FilePath.concat pkg_dir "Makefile") (echo makefile)
in
let empty_dist = FilePath.concat temp_dir "empty_dist" in
let prepare_dist = PrepareDist.empty empty_dist in
let opam_reg = FilePath.concat temp_dir "opam_reg" in
let log_file = exec_log_file_path temp_dir in
let prepare_opam_reg =
PrepareOpamReg.(prepare opam_reg theanoFiles)
>> PrepareOpamReg.(prepare opam_reg grcnumFiles)
>> PrepareOpamReg.(prepare opam_reg classGreekFiles)
>> PrepareOpamReg.(prepare opam_reg baseFiles)
in
let bin = FilePath.concat temp_dir "bin" in
prepare_pkg
>> prepare_dist
>> prepare_opam_reg
>> PrepareBin.prepare_bin bin log_file
>>| read_env ~opam_reg ~dist_library_dir:empty_dist
let () =
let verbose = false in
let main env ~dest_dir:_ ~temp_dir ~outf =
let names = Some ["example-doc"] in
let dest_dir = FilePath.concat dest_dir " dest " in
Satyrographos_command.Build.build_command
~outf
~verbose
~buildscript_path:(FilePath.concat temp_dir "pkg/Satyristes")
~build_dir:(FilePath.concat temp_dir "pkg/_build" |> Core.Option.some)
~env
~names
in
eval (test_install env main)
| null | https://raw.githubusercontent.com/na4zagin3/satyrographos/d2943bac9659d20746720ab36ebe11ae59203d32/test/testcases/command_build__doc_make.ml | ocaml | module StdList = List
open Satyrographos_testlib
open TestLib
open Shexp_process
let satyristes =
{|
(lang "0.0.3")
(doc
(name "example-doc")
(build
((make "build-doc")))
(dependencies (grcnum fonts-theano)))
|}
let makefile =
{|
PHONY: build-doc
build-doc:
@echo "Target: build-doc"
@echo "=============================="
@echo "$(SATYROGRAPHOS_PROJECT)" | grep -e 'pkg/Satyristes' >/dev/null ; echo "$$?"
|}
let env ~dest_dir:_ ~temp_dir : Satyrographos.Environment.t t =
let open Shexp_process.Infix in
let pkg_dir = FilePath.concat temp_dir "pkg" in
let prepare_pkg =
PrepareDist.empty pkg_dir
>> stdout_to (FilePath.concat pkg_dir "Satyristes") (echo satyristes)
>> stdout_to (FilePath.concat pkg_dir "README.md") (echo "@@README.md@@")
>> stdout_to (FilePath.concat pkg_dir "doc-example.saty") (echo "@@doc-example.saty@@")
>> stdout_to (FilePath.concat pkg_dir "Makefile") (echo makefile)
in
let empty_dist = FilePath.concat temp_dir "empty_dist" in
let prepare_dist = PrepareDist.empty empty_dist in
let opam_reg = FilePath.concat temp_dir "opam_reg" in
let log_file = exec_log_file_path temp_dir in
let prepare_opam_reg =
PrepareOpamReg.(prepare opam_reg theanoFiles)
>> PrepareOpamReg.(prepare opam_reg grcnumFiles)
>> PrepareOpamReg.(prepare opam_reg classGreekFiles)
>> PrepareOpamReg.(prepare opam_reg baseFiles)
in
let bin = FilePath.concat temp_dir "bin" in
prepare_pkg
>> prepare_dist
>> prepare_opam_reg
>> PrepareBin.prepare_bin bin log_file
>>| read_env ~opam_reg ~dist_library_dir:empty_dist
let () =
let verbose = false in
let main env ~dest_dir:_ ~temp_dir ~outf =
let names = Some ["example-doc"] in
let dest_dir = FilePath.concat dest_dir " dest " in
Satyrographos_command.Build.build_command
~outf
~verbose
~buildscript_path:(FilePath.concat temp_dir "pkg/Satyristes")
~build_dir:(FilePath.concat temp_dir "pkg/_build" |> Core.Option.some)
~env
~names
in
eval (test_install env main)
| |
ca9812510189a16b77db020f32a2f92f24a53a2f731444959f4703a07cb2fd99 | expipiplus1/vulkan | Requirement.hs | # LANGUAGE DataKinds #
# LANGUAGE DerivingStrategies #
{-# LANGUAGE DeriveTraversable #-}
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE GADTs #-}
# LANGUAGE MagicHash #
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE PatternSynonyms #-}
# LANGUAGE PolyKinds #
# LANGUAGE RecordWildCards #
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Strict #-}
# LANGUAGE TypeApplications #
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
# LANGUAGE UndecidableSuperClasses #
module Vulkan.Requirement
* Vulkan requirements
InstanceRequirement(..)
, DeviceRequirement(..)
, -- * Utility functionality for handling structure chains
KnownFeatureStruct(..)
, KnownPropertyStruct(..)
, SFeatureStruct(..)
, SPropertyStruct(..)
) where
-- base
import Data.Typeable
( Typeable )
import Data.Word
( Word32 )
-- bytestring
import Data.ByteString
( ByteString )
-- vulkan
import Vulkan.Core10.Device
( DeviceCreateInfo(..)
)
import Vulkan.Core10.DeviceInitialization
( PhysicalDeviceFeatures, PhysicalDeviceProperties
)
import Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2
( PhysicalDeviceFeatures2(..), PhysicalDeviceProperties2(..) )
import Vulkan.CStruct
( FromCStruct, ToCStruct )
import Vulkan.CStruct.Extends
( Extends )
import Vulkan.Zero
----------------------------------------------------------------
-- Instance Requirements
----------------------------------------------------------------
| A requirement on a Vulkan ' Instance ' .
data InstanceRequirement where
| Require a minimum Vulkan instance version .
RequireInstanceVersion
:: { version :: Word32 }
-> InstanceRequirement
| Require a Vulkan layer .
RequireInstanceLayer
:: { instanceLayerName :: ByteString
, instanceLayerMinVersion :: Word32
-- ^ The 'implementationVersion' of the layer must meet or exceed this
-- version
}
-> InstanceRequirement
| Require a Vulkan instance extension .
RequireInstanceExtension
:: { instanceExtensionLayerName :: Maybe ByteString
, instanceExtensionName :: ByteString
, instanceExtensionMinVersion :: Word32
}
-> InstanceRequirement
----------------------------------------------------------------
-- Device Requirements
----------------------------------------------------------------
A requirement on a Vulkan ' PhysicalDevice ' .
data DeviceRequirement where
-- | Require a minimum device version.
RequireDeviceVersion
:: { version :: Word32 }
-> DeviceRequirement
| Require a Vulkan physical device feature .
RequireDeviceFeature
:: forall struct
. KnownFeatureStruct struct
=> { featureName :: ByteString
, checkFeature :: struct -> Bool
, enableFeature :: struct -> struct
}
-> DeviceRequirement
| Require a Vulkan physical device property .
RequireDeviceProperty
:: forall struct
. KnownPropertyStruct struct
=> { propertyName :: ByteString
, checkProperty :: struct -> Bool
}
-> DeviceRequirement
| Require a Vulkan device extension .
RequireDeviceExtension
:: { deviceExtensionLayerName :: Maybe ByteString
, deviceExtensionName :: ByteString
, deviceExtensionMinVersion :: Word32
}
-> DeviceRequirement
| Singleton for a Vulkan structure that can appear in ' PhysicalDeviceFeatures2 ' .
--
It is either ' PhysicalDeviceFeatures ' , or it ' Extends ' ' PhysicalDeviceFeatures2 ' .
data SFeatureStruct feat where
BasicFeatureStruct
:: SFeatureStruct PhysicalDeviceFeatures
ExtendedFeatureStruct
:: ( Show feat
, Extends PhysicalDeviceFeatures2 feat, Extends DeviceCreateInfo feat
, Zero feat, FromCStruct feat, ToCStruct feat
)
=> SFeatureStruct feat
| A Vulkan structure that can appear in ' PhysicalDeviceFeatures2 ' .
class Typeable feat => KnownFeatureStruct feat where
sFeatureStruct :: SFeatureStruct feat
instance KnownFeatureStruct PhysicalDeviceFeatures where
sFeatureStruct = BasicFeatureStruct
instance {-# OVERLAPPABLE #-}
( Typeable feat, Show feat
, Extends PhysicalDeviceFeatures2 feat, Extends DeviceCreateInfo feat
, Zero feat, FromCStruct feat, ToCStruct feat
)
=> KnownFeatureStruct feat where
sFeatureStruct = ExtendedFeatureStruct
| Singleton for a Vulkan structure that can appear in ' PhysicalDeviceProperties2 ' .
--
It is either ' PhysicalDeviceProperties ' , or it ' Extends ' ' PhysicalDeviceProperties2 ' .
data SPropertyStruct prop where
BasicPropertyStruct
:: SPropertyStruct PhysicalDeviceProperties
ExtendedPropertyStruct
:: ( Typeable prop, Extends PhysicalDeviceProperties2 prop, FromCStruct prop, ToCStruct prop )
=> SPropertyStruct prop
| A Vulkan structure that can appear in ' PhysicalDeviceProperties2 ' .
class Typeable prop => KnownPropertyStruct prop where
sPropertyStruct :: SPropertyStruct prop
instance KnownPropertyStruct PhysicalDeviceProperties where
sPropertyStruct = BasicPropertyStruct
instance {-# OVERLAPPABLE #-}
( Typeable prop, Extends PhysicalDeviceProperties2 prop, FromCStruct prop, ToCStruct prop )
=> KnownPropertyStruct prop where
sPropertyStruct = ExtendedPropertyStruct
| null | https://raw.githubusercontent.com/expipiplus1/vulkan/b1e33d1031779b4740c279c68879d05aee371659/src-manual/Vulkan/Requirement.hs | haskell | # LANGUAGE DeriveTraversable #
# LANGUAGE GADTs #
# LANGUAGE NamedFieldPuns #
# LANGUAGE PatternSynonyms #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE Strict #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
* Utility functionality for handling structure chains
base
bytestring
vulkan
--------------------------------------------------------------
Instance Requirements
--------------------------------------------------------------
^ The 'implementationVersion' of the layer must meet or exceed this
version
--------------------------------------------------------------
Device Requirements
--------------------------------------------------------------
| Require a minimum device version.
# OVERLAPPABLE #
# OVERLAPPABLE # | # LANGUAGE DataKinds #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE MagicHash #
# LANGUAGE PolyKinds #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeApplications #
# LANGUAGE UndecidableSuperClasses #
module Vulkan.Requirement
* Vulkan requirements
InstanceRequirement(..)
, DeviceRequirement(..)
KnownFeatureStruct(..)
, KnownPropertyStruct(..)
, SFeatureStruct(..)
, SPropertyStruct(..)
) where
import Data.Typeable
( Typeable )
import Data.Word
( Word32 )
import Data.ByteString
( ByteString )
import Vulkan.Core10.Device
( DeviceCreateInfo(..)
)
import Vulkan.Core10.DeviceInitialization
( PhysicalDeviceFeatures, PhysicalDeviceProperties
)
import Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2
( PhysicalDeviceFeatures2(..), PhysicalDeviceProperties2(..) )
import Vulkan.CStruct
( FromCStruct, ToCStruct )
import Vulkan.CStruct.Extends
( Extends )
import Vulkan.Zero
| A requirement on a Vulkan ' Instance ' .
data InstanceRequirement where
| Require a minimum Vulkan instance version .
RequireInstanceVersion
:: { version :: Word32 }
-> InstanceRequirement
| Require a Vulkan layer .
RequireInstanceLayer
:: { instanceLayerName :: ByteString
, instanceLayerMinVersion :: Word32
}
-> InstanceRequirement
| Require a Vulkan instance extension .
RequireInstanceExtension
:: { instanceExtensionLayerName :: Maybe ByteString
, instanceExtensionName :: ByteString
, instanceExtensionMinVersion :: Word32
}
-> InstanceRequirement
A requirement on a Vulkan ' PhysicalDevice ' .
data DeviceRequirement where
RequireDeviceVersion
:: { version :: Word32 }
-> DeviceRequirement
| Require a Vulkan physical device feature .
RequireDeviceFeature
:: forall struct
. KnownFeatureStruct struct
=> { featureName :: ByteString
, checkFeature :: struct -> Bool
, enableFeature :: struct -> struct
}
-> DeviceRequirement
| Require a Vulkan physical device property .
RequireDeviceProperty
:: forall struct
. KnownPropertyStruct struct
=> { propertyName :: ByteString
, checkProperty :: struct -> Bool
}
-> DeviceRequirement
| Require a Vulkan device extension .
RequireDeviceExtension
:: { deviceExtensionLayerName :: Maybe ByteString
, deviceExtensionName :: ByteString
, deviceExtensionMinVersion :: Word32
}
-> DeviceRequirement
| Singleton for a Vulkan structure that can appear in ' PhysicalDeviceFeatures2 ' .
It is either ' PhysicalDeviceFeatures ' , or it ' Extends ' ' PhysicalDeviceFeatures2 ' .
data SFeatureStruct feat where
BasicFeatureStruct
:: SFeatureStruct PhysicalDeviceFeatures
ExtendedFeatureStruct
:: ( Show feat
, Extends PhysicalDeviceFeatures2 feat, Extends DeviceCreateInfo feat
, Zero feat, FromCStruct feat, ToCStruct feat
)
=> SFeatureStruct feat
| A Vulkan structure that can appear in ' PhysicalDeviceFeatures2 ' .
class Typeable feat => KnownFeatureStruct feat where
sFeatureStruct :: SFeatureStruct feat
instance KnownFeatureStruct PhysicalDeviceFeatures where
sFeatureStruct = BasicFeatureStruct
( Typeable feat, Show feat
, Extends PhysicalDeviceFeatures2 feat, Extends DeviceCreateInfo feat
, Zero feat, FromCStruct feat, ToCStruct feat
)
=> KnownFeatureStruct feat where
sFeatureStruct = ExtendedFeatureStruct
| Singleton for a Vulkan structure that can appear in ' PhysicalDeviceProperties2 ' .
It is either ' PhysicalDeviceProperties ' , or it ' Extends ' ' PhysicalDeviceProperties2 ' .
data SPropertyStruct prop where
BasicPropertyStruct
:: SPropertyStruct PhysicalDeviceProperties
ExtendedPropertyStruct
:: ( Typeable prop, Extends PhysicalDeviceProperties2 prop, FromCStruct prop, ToCStruct prop )
=> SPropertyStruct prop
| A Vulkan structure that can appear in ' PhysicalDeviceProperties2 ' .
class Typeable prop => KnownPropertyStruct prop where
sPropertyStruct :: SPropertyStruct prop
instance KnownPropertyStruct PhysicalDeviceProperties where
sPropertyStruct = BasicPropertyStruct
( Typeable prop, Extends PhysicalDeviceProperties2 prop, FromCStruct prop, ToCStruct prop )
=> KnownPropertyStruct prop where
sPropertyStruct = ExtendedPropertyStruct
|
cd1cc0e0944effad0d4aa0feda28a8bf6243d58353ff5313b1c02ea519f1b538 | macourtney/Dark-Exchange | 003_create_users.clj | (ns darkexchange.database.migrations.003-create-users
(:use darkexchange.database.util))
(defn
#^{:doc "Creates the users table in the database."}
up []
(create-table :users
(id)
(string :name)
(string :encrypted_password)
(string :salt)
(string :encrypted_password_algorithm)
(integer :encrypted_password_n)
(text :public_key)
(string :public_key_algorithm)
(text :private_key)
(string :private_key_algorithm)
(string :private_key_encryption_algorithm)))
(defn
#^{:doc "Drops the users table in the database."}
down []
(drop-table :users)) | null | https://raw.githubusercontent.com/macourtney/Dark-Exchange/1654d05cda0c81585da7b8e64f9ea3e2944b27f1/src/darkexchange/database/migrations/003_create_users.clj | clojure | (ns darkexchange.database.migrations.003-create-users
(:use darkexchange.database.util))
(defn
#^{:doc "Creates the users table in the database."}
up []
(create-table :users
(id)
(string :name)
(string :encrypted_password)
(string :salt)
(string :encrypted_password_algorithm)
(integer :encrypted_password_n)
(text :public_key)
(string :public_key_algorithm)
(text :private_key)
(string :private_key_algorithm)
(string :private_key_encryption_algorithm)))
(defn
#^{:doc "Drops the users table in the database."}
down []
(drop-table :users)) | |
00dc70ff008da6c48220805be9405db52658130f596717a3b0ec4751503bbcc7 | tov/memoize | test2.hs | # language TemplateHaskell #
import Data.Function.Memoize
import Data.Function ( fix )
data List a = Nil | Cons a (List a)
$(deriveMemoizable ''List)
main = print $
let lcs = memoFix2 -- exponential time if you put fix here
$ \ f -> \ a b -> case (a,b) of
(Cons x a', Cons y b') ->
maximum [ if x == y then 1 + f a' b' else 0, f a b', f a' b ]
_ -> 0
a = iterate (Cons ()) Nil !! 20
in lcs a a
| null | https://raw.githubusercontent.com/tov/memoize/21ec2da556c9c870560d40e67236f52da1e4a41c/test/test2.hs | haskell | exponential time if you put fix here | # language TemplateHaskell #
import Data.Function.Memoize
import Data.Function ( fix )
data List a = Nil | Cons a (List a)
$(deriveMemoizable ''List)
main = print $
$ \ f -> \ a b -> case (a,b) of
(Cons x a', Cons y b') ->
maximum [ if x == y then 1 + f a' b' else 0, f a b', f a' b ]
_ -> 0
a = iterate (Cons ()) Nil !! 20
in lcs a a
|
481a9b5808a1dadd2523dd13a1abc8da41d6e8485c925fbdf1e5a60e1e2718bc | kraison/vivace-graph-v3 | mmap.lisp | (in-package :graph-db)
#+lispworks(deftype word () '(unsigned-byte 64))
(cffi:defctype size :unsigned-int)
(deftype uint32 () '(integer 0 4294967295))
(deftype uint40 () '(integer 0 1099511627775))
(deftype uint64 () '(integer 0 18446744073709551615))
(defstruct (mapped-file
(:conc-name m-)
(:predicate mapped-file-p))
path pointer fd
;;(remap-lock (make-rw-lock))
)
(defstruct mpointer mmap loc)
(defmethod mapped-file-length ((mapped-file mapped-file))
(osicat-posix:stat-size (osicat-posix:fstat (m-fd mapped-file))))
(defmethod set-byte :around (mf offset byte)
(handler-case
(call-next-method)
#+sbcl
(sb-kernel::memory-fault-error (c)
(log:error "SEGV: GOT ~A in ~A; retrying." c mf)
(set-byte mf offset byte))
#+ccl
(CCL::INVALID-MEMORY-ACCESS (c)
(log:error "SEGV: GOT ~A in ~A; retrying." c mf)
(set-byte mf offset byte))
))
(defmethod set-byte ((mapped-file mapped-file) offset byte)
(declare (type word offset))
(declare (type (integer 0 255) byte))
( log : debug " SET - BYTE : ~A ADDR ~A TO ~A " ( m - path mapped - file ) offset byte )
(setf (cffi:mem-aref (m-pointer mapped-file) :unsigned-char offset) byte))
(defmethod get-byte :around (mf offset)
(handler-case
(call-next-method)
#+sbcl
(sb-kernel::memory-fault-error (c)
(log:error "SEGV: GOT ~A in ~A; retrying." c mf)
(get-byte mf offset))
#+ccl
(CCL::INVALID-MEMORY-ACCESS (c)
(log:error "SEGV: GOT ~A in ~A; retrying." c mf)
(get-byte mf offset))))
(defmethod get-byte ((mapped-file mapped-file) offset)
(declare (type word offset))
(cffi:mem-aref (m-pointer mapped-file) :unsigned-char offset))
(defmethod get-bytes :around (mf offset length)
(handler-case
(call-next-method)
#+sbcl
(sb-kernel::memory-fault-error (c)
(log:error "SEGV: GOT ~A in ~A; retrying." c mf)
(get-bytes mf offset length))
#+ccl
(CCL::INVALID-MEMORY-ACCESS (c)
(log:error "SEGV: GOT ~A in ~A; retrying." c mf)
(get-bytes mf offset length))))
(defmethod get-bytes ((mapped-file mapped-file) offset length)
(declare (type word offset length))
(let ((vec (make-byte-vector length)))
(dotimes (i length)
(setf (aref vec i) (get-byte mapped-file (+ i offset))))
vec))
(defmethod set-bytes :around (mf vec offset length)
(handler-case
(call-next-method)
#+sbcl
(sb-kernel::memory-fault-error (c)
(log:error "SEGV: GOT ~A in ~A; retrying." c mf)
(set-bytes mf offset length))
#+ccl
(CCL::INVALID-MEMORY-ACCESS (c)
(log:error "SEGV: GOT ~A in ~A; retrying." c mf)
(set-bytes mf offset length))))
(defmethod set-bytes ((mapped-file mapped-file) vec offset length)
(declare (type word offset length))
(dotimes (i length)
(set-byte mapped-file (+ i offset) (aref vec i)))
vec)
(defmethod size-of ((mmap mapped-file))
(osicat-posix:stat-size (osicat-posix:stat (m-path mmap))))
(defun mmap-file (file &key (create-p t) (size (* 4096 25600)))
"Use mmap() to map FILE into memory."
(log:debug "Opening mmap ~A" file)
(when (and (not create-p) (not (probe-file file)))
(error "mmap-file: ~A does not exist and create-p is not true." file))
(let* ((fd (osicat-posix:open
file
(if create-p
(logior osicat-posix:O-CREAT osicat-posix:O-RDWR)
osicat-posix:O-RDWR))))
(when create-p
(osicat-posix:lseek fd (1- size) osicat-posix:seek-set)
(cffi:with-foreign-string (null (format nil "~A" (code-char 0)))
(cffi:foreign-funcall "write"
:int fd
:pointer null
size 1)))
;; Make sure the file size is set right!
(setq size (osicat-posix:stat-size (osicat-posix:fstat fd)))
(let* ((pointer
(osicat-posix:mmap
(cffi:null-pointer)
size
(logior osicat-posix:prot-read osicat-posix:prot-write)
osicat-posix:map-shared
fd
0)))
; (cffi:foreign-funcall "madvise"
; :int fd
; size size
; :int MADV_RANDOM))) ;; NEED MADV_RANDOM FROM ?
(make-mapped-file :path (truename file)
:fd fd
:pointer pointer))))
(defmethod sync-region ((mapped-file mapped-file) &key addr length
(sync osicat-posix:ms-sync))
(osicat-posix:msync (or addr (m-pointer mapped-file))
(or length (mapped-file-length mapped-file))
sync))
(defmethod munmap-file ((mapped-file mapped-file) &key (save-p nil)
(sync osicat-posix:ms-sync))
(when save-p
;;(log:debug "Calling msync on ~S" mapped-file)
(osicat-posix:msync (m-pointer mapped-file)
(mapped-file-length mapped-file)
sync))
;;(log:debug "Calling munmap on ~S" mapped-file)
(osicat-posix:munmap (m-pointer mapped-file) (mapped-file-length mapped-file))
(osicat-posix:close (m-fd mapped-file))
(setf (m-pointer mapped-file) nil)
nil)
#+linux
(defmethod extend-mapped-file ((mapped-file mapped-file) (length integer))
(log:debug "EXTENDING MMAP ~A" mapped-file)
(let ((ptr (osicat-posix:mremap (m-pointer mapped-file)
(mapped-file-length mapped-file)
(+ length (mapped-file-length mapped-file))
osicat-posix:MREMAP-MAYMOVE)))
(setf (m-pointer mapped-file) ptr)
(osicat-posix:lseek (m-fd mapped-file)
(1- (+ length (mapped-file-length mapped-file)))
osicat-posix:seek-set)
(cffi:with-foreign-string (null (format nil "~A" (code-char 0)))
(cffi:foreign-funcall "write"
:int (m-fd mapped-file)
:pointer null
size 1))
mapped-file))
#+darwin
(defmethod extend-mapped-file ((mapped-file mapped-file) (length integer))
(log:debug "EXTENDING MMAP ~A" mapped-file)
(let ((len (mapped-file-length mapped-file)))
(munmap-file mapped-file)
(setf (m-pointer mapped-file)
(osicat-posix:mmap (cffi:null-pointer) (+ len length)
(logior osicat-posix:PROT-READ osicat-posix:PROT-WRITE)
osicat-posix:MAP-SHARED (m-fd mapped-file) 0))
(osicat-posix:lseek (m-fd mapped-file)
(1- (+ length (mapped-file-length mapped-file)))
osicat-posix:seek-set)
(cffi:with-foreign-string (null (format nil "~A" (code-char 0)))
(cffi:foreign-funcall "write"
:int (m-fd mapped-file)
:pointer null
size 1))
mapped-file))
(defmethod serialize-uint64 ((mf mapped-file) int offset)
(declare (type word int offset))
( log : debug " MMAP : SERIALIZING UINT64 ~A TO ADDR ~A " int offset )
(dotimes (i 8)
( log : debug " WRITING BYTE ~X " ( ldb ( byte 8 0 ) int ) )
(set-byte mf offset (ldb (byte 8 (* i 8)) int))
( log : debug " WROTE BYTE ~A AT OFFSET ~X " ( ldb ( byte 8 0 ) int ) offset )
(incf offset))
;; (incf offset))
offset)
(defmethod deserialize-uint64 ((mf mapped-file) offset)
"Decode a UINT64."
(declare (type word offset))
(let ((int 0))
(declare (type word int))
(dotimes (i 8)
(setq int (dpb (get-byte mf (+ i offset)) (byte 8 (* i 8)) int)))
int))
(defmethod deserialize-uint64 ((array array) offset)
"Decode a UINT64."
(let ((int 0))
(declare (type word int))
(dotimes (i 8)
(setq int (dpb (aref array (+ i offset)) (byte 8 (* i 8)) int)))
int))
(defmethod incf-uint64 ((mf mapped-file) offset)
(declare (type word offset))
(let ((int (deserialize-uint64 mf offset)))
(incf int)
(serialize-uint64 mf int offset)
int))
(defmethod decf-uint64 ((mf mapped-file) offset)
(declare (type word offset))
(let ((int (deserialize-uint64 mf offset)))
(serialize-uint64 mf (decf int) offset)
int))
(defmethod serialize-pointer ((mf mapped-file) pointer offset)
( log : debug " SERIALIZING POINTER ~A TO ADDR ~A " pointer offset )
(serialize-uint64 mf pointer offset))
(defmethod deserialize-pointer ((mf mapped-file) offset)
( log : debug " DESERIALIZING POINTER AT ADDR ~A " offset )
(deserialize-uint64 mf offset))
(defmethod serialize-uint32 ((mf mapped-file) int offset)
(declare (type uint32 int))
(declare (type word offset))
(dotimes (i 4)
(set-byte mf offset (ldb (byte 8 (* i 8)) int))
(incf offset))
(incf offset))
(defmethod deserialize-uint32 ((mf mapped-file) offset)
(declare (type word offset))
(let ((int 0))
(declare (type uint32 int))
(dotimes (i 4)
(setq int (dpb (get-byte mf (+ i offset)) (byte 8 (* i 8)) int)))
int))
(defmethod serialize-uint40 ((mf mapped-file) int offset)
(declare (type uint40 int))
(declare (type word offset))
(dotimes (i 5)
(set-byte mf offset (ldb (byte 8 (* i 8)) int))
(incf offset))
(incf offset))
(defmethod deserialize-uint40 ((mf mapped-file) offset)
(declare (type word offset))
(let ((int 0))
(declare (type uint40 int))
(dotimes (i 5)
(setq int (dpb (get-byte mf (+ i offset)) (byte 8 (* i 8)) int)))
int))
| null | https://raw.githubusercontent.com/kraison/vivace-graph-v3/cf2caaf26baccec9afd4d6a79375cd9ff5fe0613/mmap.lisp | lisp | (remap-lock (make-rw-lock))
Make sure the file size is set right!
(cffi:foreign-funcall "madvise"
:int fd
size size
:int MADV_RANDOM))) ;; NEED MADV_RANDOM FROM ?
(log:debug "Calling msync on ~S" mapped-file)
(log:debug "Calling munmap on ~S" mapped-file)
(incf offset)) | (in-package :graph-db)
#+lispworks(deftype word () '(unsigned-byte 64))
(cffi:defctype size :unsigned-int)
(deftype uint32 () '(integer 0 4294967295))
(deftype uint40 () '(integer 0 1099511627775))
(deftype uint64 () '(integer 0 18446744073709551615))
(defstruct (mapped-file
(:conc-name m-)
(:predicate mapped-file-p))
path pointer fd
)
(defstruct mpointer mmap loc)
(defmethod mapped-file-length ((mapped-file mapped-file))
(osicat-posix:stat-size (osicat-posix:fstat (m-fd mapped-file))))
(defmethod set-byte :around (mf offset byte)
(handler-case
(call-next-method)
#+sbcl
(sb-kernel::memory-fault-error (c)
(log:error "SEGV: GOT ~A in ~A; retrying." c mf)
(set-byte mf offset byte))
#+ccl
(CCL::INVALID-MEMORY-ACCESS (c)
(log:error "SEGV: GOT ~A in ~A; retrying." c mf)
(set-byte mf offset byte))
))
(defmethod set-byte ((mapped-file mapped-file) offset byte)
(declare (type word offset))
(declare (type (integer 0 255) byte))
( log : debug " SET - BYTE : ~A ADDR ~A TO ~A " ( m - path mapped - file ) offset byte )
(setf (cffi:mem-aref (m-pointer mapped-file) :unsigned-char offset) byte))
(defmethod get-byte :around (mf offset)
(handler-case
(call-next-method)
#+sbcl
(sb-kernel::memory-fault-error (c)
(log:error "SEGV: GOT ~A in ~A; retrying." c mf)
(get-byte mf offset))
#+ccl
(CCL::INVALID-MEMORY-ACCESS (c)
(log:error "SEGV: GOT ~A in ~A; retrying." c mf)
(get-byte mf offset))))
(defmethod get-byte ((mapped-file mapped-file) offset)
(declare (type word offset))
(cffi:mem-aref (m-pointer mapped-file) :unsigned-char offset))
(defmethod get-bytes :around (mf offset length)
(handler-case
(call-next-method)
#+sbcl
(sb-kernel::memory-fault-error (c)
(log:error "SEGV: GOT ~A in ~A; retrying." c mf)
(get-bytes mf offset length))
#+ccl
(CCL::INVALID-MEMORY-ACCESS (c)
(log:error "SEGV: GOT ~A in ~A; retrying." c mf)
(get-bytes mf offset length))))
(defmethod get-bytes ((mapped-file mapped-file) offset length)
(declare (type word offset length))
(let ((vec (make-byte-vector length)))
(dotimes (i length)
(setf (aref vec i) (get-byte mapped-file (+ i offset))))
vec))
(defmethod set-bytes :around (mf vec offset length)
(handler-case
(call-next-method)
#+sbcl
(sb-kernel::memory-fault-error (c)
(log:error "SEGV: GOT ~A in ~A; retrying." c mf)
(set-bytes mf offset length))
#+ccl
(CCL::INVALID-MEMORY-ACCESS (c)
(log:error "SEGV: GOT ~A in ~A; retrying." c mf)
(set-bytes mf offset length))))
(defmethod set-bytes ((mapped-file mapped-file) vec offset length)
(declare (type word offset length))
(dotimes (i length)
(set-byte mapped-file (+ i offset) (aref vec i)))
vec)
(defmethod size-of ((mmap mapped-file))
(osicat-posix:stat-size (osicat-posix:stat (m-path mmap))))
(defun mmap-file (file &key (create-p t) (size (* 4096 25600)))
"Use mmap() to map FILE into memory."
(log:debug "Opening mmap ~A" file)
(when (and (not create-p) (not (probe-file file)))
(error "mmap-file: ~A does not exist and create-p is not true." file))
(let* ((fd (osicat-posix:open
file
(if create-p
(logior osicat-posix:O-CREAT osicat-posix:O-RDWR)
osicat-posix:O-RDWR))))
(when create-p
(osicat-posix:lseek fd (1- size) osicat-posix:seek-set)
(cffi:with-foreign-string (null (format nil "~A" (code-char 0)))
(cffi:foreign-funcall "write"
:int fd
:pointer null
size 1)))
(setq size (osicat-posix:stat-size (osicat-posix:fstat fd)))
(let* ((pointer
(osicat-posix:mmap
(cffi:null-pointer)
size
(logior osicat-posix:prot-read osicat-posix:prot-write)
osicat-posix:map-shared
fd
0)))
(make-mapped-file :path (truename file)
:fd fd
:pointer pointer))))
(defmethod sync-region ((mapped-file mapped-file) &key addr length
(sync osicat-posix:ms-sync))
(osicat-posix:msync (or addr (m-pointer mapped-file))
(or length (mapped-file-length mapped-file))
sync))
(defmethod munmap-file ((mapped-file mapped-file) &key (save-p nil)
(sync osicat-posix:ms-sync))
(when save-p
(osicat-posix:msync (m-pointer mapped-file)
(mapped-file-length mapped-file)
sync))
(osicat-posix:munmap (m-pointer mapped-file) (mapped-file-length mapped-file))
(osicat-posix:close (m-fd mapped-file))
(setf (m-pointer mapped-file) nil)
nil)
#+linux
(defmethod extend-mapped-file ((mapped-file mapped-file) (length integer))
(log:debug "EXTENDING MMAP ~A" mapped-file)
(let ((ptr (osicat-posix:mremap (m-pointer mapped-file)
(mapped-file-length mapped-file)
(+ length (mapped-file-length mapped-file))
osicat-posix:MREMAP-MAYMOVE)))
(setf (m-pointer mapped-file) ptr)
(osicat-posix:lseek (m-fd mapped-file)
(1- (+ length (mapped-file-length mapped-file)))
osicat-posix:seek-set)
(cffi:with-foreign-string (null (format nil "~A" (code-char 0)))
(cffi:foreign-funcall "write"
:int (m-fd mapped-file)
:pointer null
size 1))
mapped-file))
#+darwin
(defmethod extend-mapped-file ((mapped-file mapped-file) (length integer))
(log:debug "EXTENDING MMAP ~A" mapped-file)
(let ((len (mapped-file-length mapped-file)))
(munmap-file mapped-file)
(setf (m-pointer mapped-file)
(osicat-posix:mmap (cffi:null-pointer) (+ len length)
(logior osicat-posix:PROT-READ osicat-posix:PROT-WRITE)
osicat-posix:MAP-SHARED (m-fd mapped-file) 0))
(osicat-posix:lseek (m-fd mapped-file)
(1- (+ length (mapped-file-length mapped-file)))
osicat-posix:seek-set)
(cffi:with-foreign-string (null (format nil "~A" (code-char 0)))
(cffi:foreign-funcall "write"
:int (m-fd mapped-file)
:pointer null
size 1))
mapped-file))
(defmethod serialize-uint64 ((mf mapped-file) int offset)
(declare (type word int offset))
( log : debug " MMAP : SERIALIZING UINT64 ~A TO ADDR ~A " int offset )
(dotimes (i 8)
( log : debug " WRITING BYTE ~X " ( ldb ( byte 8 0 ) int ) )
(set-byte mf offset (ldb (byte 8 (* i 8)) int))
( log : debug " WROTE BYTE ~A AT OFFSET ~X " ( ldb ( byte 8 0 ) int ) offset )
(incf offset))
offset)
(defmethod deserialize-uint64 ((mf mapped-file) offset)
"Decode a UINT64."
(declare (type word offset))
(let ((int 0))
(declare (type word int))
(dotimes (i 8)
(setq int (dpb (get-byte mf (+ i offset)) (byte 8 (* i 8)) int)))
int))
(defmethod deserialize-uint64 ((array array) offset)
"Decode a UINT64."
(let ((int 0))
(declare (type word int))
(dotimes (i 8)
(setq int (dpb (aref array (+ i offset)) (byte 8 (* i 8)) int)))
int))
(defmethod incf-uint64 ((mf mapped-file) offset)
(declare (type word offset))
(let ((int (deserialize-uint64 mf offset)))
(incf int)
(serialize-uint64 mf int offset)
int))
(defmethod decf-uint64 ((mf mapped-file) offset)
(declare (type word offset))
(let ((int (deserialize-uint64 mf offset)))
(serialize-uint64 mf (decf int) offset)
int))
(defmethod serialize-pointer ((mf mapped-file) pointer offset)
( log : debug " SERIALIZING POINTER ~A TO ADDR ~A " pointer offset )
(serialize-uint64 mf pointer offset))
(defmethod deserialize-pointer ((mf mapped-file) offset)
( log : debug " DESERIALIZING POINTER AT ADDR ~A " offset )
(deserialize-uint64 mf offset))
(defmethod serialize-uint32 ((mf mapped-file) int offset)
(declare (type uint32 int))
(declare (type word offset))
(dotimes (i 4)
(set-byte mf offset (ldb (byte 8 (* i 8)) int))
(incf offset))
(incf offset))
(defmethod deserialize-uint32 ((mf mapped-file) offset)
(declare (type word offset))
(let ((int 0))
(declare (type uint32 int))
(dotimes (i 4)
(setq int (dpb (get-byte mf (+ i offset)) (byte 8 (* i 8)) int)))
int))
(defmethod serialize-uint40 ((mf mapped-file) int offset)
(declare (type uint40 int))
(declare (type word offset))
(dotimes (i 5)
(set-byte mf offset (ldb (byte 8 (* i 8)) int))
(incf offset))
(incf offset))
(defmethod deserialize-uint40 ((mf mapped-file) offset)
(declare (type word offset))
(let ((int 0))
(declare (type uint40 int))
(dotimes (i 5)
(setq int (dpb (get-byte mf (+ i offset)) (byte 8 (* i 8)) int)))
int))
|
cc997c349993f81fbf41f8eba6fb4ab1ac2ae5608ffd02967d42fbaa4a7ad521 | expipiplus1/vulkan | ComponentSwizzle.hs | {-# language CPP #-}
No documentation found for Chapter " ComponentSwizzle "
module Vulkan.Core10.Enums.ComponentSwizzle (ComponentSwizzle( COMPONENT_SWIZZLE_IDENTITY
, COMPONENT_SWIZZLE_ZERO
, COMPONENT_SWIZZLE_ONE
, COMPONENT_SWIZZLE_R
, COMPONENT_SWIZZLE_G
, COMPONENT_SWIZZLE_B
, COMPONENT_SWIZZLE_A
, ..
)) where
import Vulkan.Internal.Utils (enumReadPrec)
import Vulkan.Internal.Utils (enumShowsPrec)
import GHC.Show (showsPrec)
import Vulkan.Zero (Zero)
import Foreign.Storable (Storable)
import Data.Int (Int32)
import GHC.Read (Read(readPrec))
import GHC.Show (Show(showsPrec))
-- | VkComponentSwizzle - Specify how a component is swizzled
--
-- = Description
--
-- Setting the identity swizzle on a component is equivalent to setting the
-- identity mapping on that component. That is:
--
-- +-----------------------------------+-----------------------------------+
-- | Component | Identity Mapping |
-- +===================================+===================================+
-- | @components.r@ | 'COMPONENT_SWIZZLE_R' |
-- +-----------------------------------+-----------------------------------+
-- | @components.g@ | 'COMPONENT_SWIZZLE_G' |
-- +-----------------------------------+-----------------------------------+
-- | @components.b@ | 'COMPONENT_SWIZZLE_B' |
-- +-----------------------------------+-----------------------------------+
| @components.a@ | ' ' |
-- +-----------------------------------+-----------------------------------+
--
-- Component Mappings Equivalent To 'COMPONENT_SWIZZLE_IDENTITY'
--
-- = See Also
--
-- <-extensions/html/vkspec.html#VK_VERSION_1_0 VK_VERSION_1_0>,
' Vulkan . Core10.ImageView . ComponentMapping '
newtype ComponentSwizzle = ComponentSwizzle Int32
deriving newtype (Eq, Ord, Storable, Zero)
-- | 'COMPONENT_SWIZZLE_IDENTITY' specifies that the component is set to the
-- identity swizzle.
pattern COMPONENT_SWIZZLE_IDENTITY = ComponentSwizzle 0
| ' COMPONENT_SWIZZLE_ZERO ' specifies that the component is set to zero .
pattern COMPONENT_SWIZZLE_ZERO = ComponentSwizzle 1
| ' COMPONENT_SWIZZLE_ONE ' specifies that the component is set to either 1
or 1.0 , depending on whether the type of the image view format is
-- integer or floating-point respectively, as determined by the
-- <-extensions/html/vkspec.html#formats-definition Format Definition>
section for each ' Vulkan . Core10.Enums . Format . Format ' .
pattern COMPONENT_SWIZZLE_ONE = ComponentSwizzle 2
-- | 'COMPONENT_SWIZZLE_R' specifies that the component is set to the value
-- of the R component of the image.
pattern COMPONENT_SWIZZLE_R = ComponentSwizzle 3
| ' COMPONENT_SWIZZLE_G ' specifies that the component is set to the value
-- of the G component of the image.
pattern COMPONENT_SWIZZLE_G = ComponentSwizzle 4
-- | 'COMPONENT_SWIZZLE_B' specifies that the component is set to the value
-- of the B component of the image.
pattern COMPONENT_SWIZZLE_B = ComponentSwizzle 5
| ' ' specifies that the component is set to the value
-- of the A component of the image.
pattern COMPONENT_SWIZZLE_A = ComponentSwizzle 6
# COMPLETE
, COMPONENT_SWIZZLE_ZERO
, , COMPONENT_SWIZZLE_R
, COMPONENT_SWIZZLE_G
, COMPONENT_SWIZZLE_B
, : :
ComponentSwizzle
#
COMPONENT_SWIZZLE_IDENTITY
, COMPONENT_SWIZZLE_ZERO
, COMPONENT_SWIZZLE_ONE
, COMPONENT_SWIZZLE_R
, COMPONENT_SWIZZLE_G
, COMPONENT_SWIZZLE_B
, COMPONENT_SWIZZLE_A ::
ComponentSwizzle
#-}
conNameComponentSwizzle :: String
conNameComponentSwizzle = "ComponentSwizzle"
enumPrefixComponentSwizzle :: String
enumPrefixComponentSwizzle = "COMPONENT_SWIZZLE_"
showTableComponentSwizzle :: [(ComponentSwizzle, String)]
showTableComponentSwizzle =
[ (COMPONENT_SWIZZLE_IDENTITY, "IDENTITY")
, (COMPONENT_SWIZZLE_ZERO, "ZERO")
, (COMPONENT_SWIZZLE_ONE, "ONE")
, (COMPONENT_SWIZZLE_R, "R")
, (COMPONENT_SWIZZLE_G, "G")
, (COMPONENT_SWIZZLE_B, "B")
, (COMPONENT_SWIZZLE_A, "A")
]
instance Show ComponentSwizzle where
showsPrec =
enumShowsPrec
enumPrefixComponentSwizzle
showTableComponentSwizzle
conNameComponentSwizzle
(\(ComponentSwizzle x) -> x)
(showsPrec 11)
instance Read ComponentSwizzle where
readPrec =
enumReadPrec
enumPrefixComponentSwizzle
showTableComponentSwizzle
conNameComponentSwizzle
ComponentSwizzle
| null | https://raw.githubusercontent.com/expipiplus1/vulkan/ebc0dde0bcd9cf251f18538de6524eb4f2ab3e9d/src/Vulkan/Core10/Enums/ComponentSwizzle.hs | haskell | # language CPP #
| VkComponentSwizzle - Specify how a component is swizzled
= Description
Setting the identity swizzle on a component is equivalent to setting the
identity mapping on that component. That is:
+-----------------------------------+-----------------------------------+
| Component | Identity Mapping |
+===================================+===================================+
| @components.r@ | 'COMPONENT_SWIZZLE_R' |
+-----------------------------------+-----------------------------------+
| @components.g@ | 'COMPONENT_SWIZZLE_G' |
+-----------------------------------+-----------------------------------+
| @components.b@ | 'COMPONENT_SWIZZLE_B' |
+-----------------------------------+-----------------------------------+
+-----------------------------------+-----------------------------------+
Component Mappings Equivalent To 'COMPONENT_SWIZZLE_IDENTITY'
= See Also
<-extensions/html/vkspec.html#VK_VERSION_1_0 VK_VERSION_1_0>,
| 'COMPONENT_SWIZZLE_IDENTITY' specifies that the component is set to the
identity swizzle.
integer or floating-point respectively, as determined by the
<-extensions/html/vkspec.html#formats-definition Format Definition>
| 'COMPONENT_SWIZZLE_R' specifies that the component is set to the value
of the R component of the image.
of the G component of the image.
| 'COMPONENT_SWIZZLE_B' specifies that the component is set to the value
of the B component of the image.
of the A component of the image. | No documentation found for Chapter " ComponentSwizzle "
module Vulkan.Core10.Enums.ComponentSwizzle (ComponentSwizzle( COMPONENT_SWIZZLE_IDENTITY
, COMPONENT_SWIZZLE_ZERO
, COMPONENT_SWIZZLE_ONE
, COMPONENT_SWIZZLE_R
, COMPONENT_SWIZZLE_G
, COMPONENT_SWIZZLE_B
, COMPONENT_SWIZZLE_A
, ..
)) where
import Vulkan.Internal.Utils (enumReadPrec)
import Vulkan.Internal.Utils (enumShowsPrec)
import GHC.Show (showsPrec)
import Vulkan.Zero (Zero)
import Foreign.Storable (Storable)
import Data.Int (Int32)
import GHC.Read (Read(readPrec))
import GHC.Show (Show(showsPrec))
| @components.a@ | ' ' |
' Vulkan . Core10.ImageView . ComponentMapping '
newtype ComponentSwizzle = ComponentSwizzle Int32
deriving newtype (Eq, Ord, Storable, Zero)
pattern COMPONENT_SWIZZLE_IDENTITY = ComponentSwizzle 0
| ' COMPONENT_SWIZZLE_ZERO ' specifies that the component is set to zero .
pattern COMPONENT_SWIZZLE_ZERO = ComponentSwizzle 1
| ' COMPONENT_SWIZZLE_ONE ' specifies that the component is set to either 1
or 1.0 , depending on whether the type of the image view format is
section for each ' Vulkan . Core10.Enums . Format . Format ' .
pattern COMPONENT_SWIZZLE_ONE = ComponentSwizzle 2
pattern COMPONENT_SWIZZLE_R = ComponentSwizzle 3
| ' COMPONENT_SWIZZLE_G ' specifies that the component is set to the value
pattern COMPONENT_SWIZZLE_G = ComponentSwizzle 4
pattern COMPONENT_SWIZZLE_B = ComponentSwizzle 5
| ' ' specifies that the component is set to the value
pattern COMPONENT_SWIZZLE_A = ComponentSwizzle 6
# COMPLETE
, COMPONENT_SWIZZLE_ZERO
, , COMPONENT_SWIZZLE_R
, COMPONENT_SWIZZLE_G
, COMPONENT_SWIZZLE_B
, : :
ComponentSwizzle
#
COMPONENT_SWIZZLE_IDENTITY
, COMPONENT_SWIZZLE_ZERO
, COMPONENT_SWIZZLE_ONE
, COMPONENT_SWIZZLE_R
, COMPONENT_SWIZZLE_G
, COMPONENT_SWIZZLE_B
, COMPONENT_SWIZZLE_A ::
ComponentSwizzle
#-}
conNameComponentSwizzle :: String
conNameComponentSwizzle = "ComponentSwizzle"
enumPrefixComponentSwizzle :: String
enumPrefixComponentSwizzle = "COMPONENT_SWIZZLE_"
showTableComponentSwizzle :: [(ComponentSwizzle, String)]
showTableComponentSwizzle =
[ (COMPONENT_SWIZZLE_IDENTITY, "IDENTITY")
, (COMPONENT_SWIZZLE_ZERO, "ZERO")
, (COMPONENT_SWIZZLE_ONE, "ONE")
, (COMPONENT_SWIZZLE_R, "R")
, (COMPONENT_SWIZZLE_G, "G")
, (COMPONENT_SWIZZLE_B, "B")
, (COMPONENT_SWIZZLE_A, "A")
]
instance Show ComponentSwizzle where
showsPrec =
enumShowsPrec
enumPrefixComponentSwizzle
showTableComponentSwizzle
conNameComponentSwizzle
(\(ComponentSwizzle x) -> x)
(showsPrec 11)
instance Read ComponentSwizzle where
readPrec =
enumReadPrec
enumPrefixComponentSwizzle
showTableComponentSwizzle
conNameComponentSwizzle
ComponentSwizzle
|
c56ae31b06bf1660b8271f2c103bd163dd5945f3527677a9c14bc8b60c7624e6 | kappamodeler/kappa | acyclicity.ml | open Data_structures
let is_acyclic pb =
try (
match pb.Pb_sig.first_encoding
with None -> raise Exit
| Some cpb ->
let add_relation x y (set,map,mapop) =
if x=y then raise Exit
else
let set' = String2Set.add x (String2Set.add y set) in
let map' =
let old =
try Pb_sig.String2Map.find x map
with Not_found -> String2Set.empty in
Pb_sig.String2Map.add x (String2Set.add y old) map in
let mapop' =
let old =
try Pb_sig.String2Map.find y mapop
with Not_found -> String2Set.empty in
Pb_sig.String2Map.add y (String2Set.add x old) mapop in
set',map',mapop' in
let empty =
String2Set.empty,Pb_sig.String2Map.empty,Pb_sig.String2Map.empty in
let g (x,(a,s)) =
List.fold_right
(fun s' -> if s=s' then (fun x -> x)
else add_relation x (a,s')
)
(snd (StringMap.find a cpb.Pb_sig.cpb_interface_of_agent))
in
let (set,map,map') =
Pb_sig.String22Set.fold
(fun (x,x') sol -> g (x,x') (g (x',x) sol))
(match pb.Pb_sig.contact_map
with None -> raise Exit
| Some a -> a.Pb_sig.relation_set )
empty
in
let rec aux next to_visit =
match next with
[] ->
begin
if String2Set.is_empty to_visit
then
true
else
let next = String2Set.min_elt to_visit
in
aux [next,None,String2Set.singleton next] (String2Set.remove next to_visit)
end
| (t,from,black)::q ->
let succ =
try
Pb_sig.String2Map.find t map
with
Not_found -> String2Set.empty
in
let succ =
match from with None -> succ
| Some a -> String2Set.remove a succ
in
aux
(String2Set.fold
(fun a l ->
if String2Set.mem a black
then raise Exit
else
(a,Some t,String2Set.add t black)::l
)
succ
q)
(String2Set.diff to_visit succ)
in
if String2Set.is_empty set then true
else
let start = String2Set.min_elt set in
aux
[start,None,String2Set.singleton start]
(String2Set.remove start set)
)
with Exit -> false
| null | https://raw.githubusercontent.com/kappamodeler/kappa/de63d1857898b1fc3b7f112f1027768b851ce14d/complx_rep/backend/contact_map/acyclicity.ml | ocaml | open Data_structures
let is_acyclic pb =
try (
match pb.Pb_sig.first_encoding
with None -> raise Exit
| Some cpb ->
let add_relation x y (set,map,mapop) =
if x=y then raise Exit
else
let set' = String2Set.add x (String2Set.add y set) in
let map' =
let old =
try Pb_sig.String2Map.find x map
with Not_found -> String2Set.empty in
Pb_sig.String2Map.add x (String2Set.add y old) map in
let mapop' =
let old =
try Pb_sig.String2Map.find y mapop
with Not_found -> String2Set.empty in
Pb_sig.String2Map.add y (String2Set.add x old) mapop in
set',map',mapop' in
let empty =
String2Set.empty,Pb_sig.String2Map.empty,Pb_sig.String2Map.empty in
let g (x,(a,s)) =
List.fold_right
(fun s' -> if s=s' then (fun x -> x)
else add_relation x (a,s')
)
(snd (StringMap.find a cpb.Pb_sig.cpb_interface_of_agent))
in
let (set,map,map') =
Pb_sig.String22Set.fold
(fun (x,x') sol -> g (x,x') (g (x',x) sol))
(match pb.Pb_sig.contact_map
with None -> raise Exit
| Some a -> a.Pb_sig.relation_set )
empty
in
let rec aux next to_visit =
match next with
[] ->
begin
if String2Set.is_empty to_visit
then
true
else
let next = String2Set.min_elt to_visit
in
aux [next,None,String2Set.singleton next] (String2Set.remove next to_visit)
end
| (t,from,black)::q ->
let succ =
try
Pb_sig.String2Map.find t map
with
Not_found -> String2Set.empty
in
let succ =
match from with None -> succ
| Some a -> String2Set.remove a succ
in
aux
(String2Set.fold
(fun a l ->
if String2Set.mem a black
then raise Exit
else
(a,Some t,String2Set.add t black)::l
)
succ
q)
(String2Set.diff to_visit succ)
in
if String2Set.is_empty set then true
else
let start = String2Set.min_elt set in
aux
[start,None,String2Set.singleton start]
(String2Set.remove start set)
)
with Exit -> false
| |
c97663d185e8caad256854c4971b2648da975a83412c060fb789452219a33d6d | sgbj/MaximaSharp | ztpsv.lisp | ;;; Compiled by f2cl version:
( " f2cl1.l , v 2edcbd958861 2012/05/30 03:34:52 toy $ "
" f2cl2.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl5.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ " )
;;; Using Lisp CMU Common Lisp 20d (20D Unicode)
;;;
;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
;;; (:coerce-assigns :as-needed) (:array-type ':array)
;;; (:array-slicing t) (:declare-common nil)
;;; (:float-format double-float))
(in-package :blas)
(let* ((zero (f2cl-lib:cmplx 0.0 0.0)))
(declare (type (f2cl-lib:complex16) zero) (ignorable zero))
(defun ztpsv (uplo trans diag n ap x incx)
(declare (type (array f2cl-lib:complex16 (*)) x ap)
(type (f2cl-lib:integer4) incx n)
(type (simple-string *) diag trans uplo))
(f2cl-lib:with-multi-array-data
((uplo character uplo-%data% uplo-%offset%)
(trans character trans-%data% trans-%offset%)
(diag character diag-%data% diag-%offset%)
(ap f2cl-lib:complex16 ap-%data% ap-%offset%)
(x f2cl-lib:complex16 x-%data% x-%offset%))
(prog ((noconj nil) (nounit nil) (i 0) (info 0) (ix 0) (j 0) (jx 0) (k 0)
(kk 0) (kx 0) (temp #C(0.0 0.0)))
(declare (type f2cl-lib:logical noconj nounit)
(type (f2cl-lib:integer4) i info ix j jx k kk kx)
(type (f2cl-lib:complex16) temp))
(setf info 0)
(cond
((and (not (lsame uplo "U")) (not (lsame uplo "L")))
(setf info 1))
((and (not (lsame trans "N"))
(not (lsame trans "T"))
(not (lsame trans "C")))
(setf info 2))
((and (not (lsame diag "U")) (not (lsame diag "N")))
(setf info 3))
((< n 0)
(setf info 4))
((= incx 0)
(setf info 7)))
(cond
((/= info 0)
(xerbla "ZTPSV " info)
(go end_label)))
(if (= n 0) (go end_label))
(setf noconj (lsame trans "T"))
(setf nounit (lsame diag "N"))
(cond
((<= incx 0)
(setf kx
(f2cl-lib:int-sub 1
(f2cl-lib:int-mul (f2cl-lib:int-sub n 1)
incx))))
((/= incx 1)
(setf kx 1)))
(cond
((lsame trans "N")
(cond
((lsame uplo "U")
(setf kk (the f2cl-lib:integer4 (truncate (* n (+ n 1)) 2)))
(cond
((= incx 1)
(f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1)))
((> j 1) nil)
(tagbody
(cond
((/= (f2cl-lib:fref x (j) ((1 *))) zero)
(if nounit
(setf (f2cl-lib:fref x-%data%
(j)
((1 *))
x-%offset%)
(/
(f2cl-lib:fref x-%data%
(j)
((1 *))
x-%offset%)
(f2cl-lib:fref ap-%data%
(kk)
((1 *))
ap-%offset%))))
(setf temp
(f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%))
(setf k (f2cl-lib:int-sub kk 1))
(f2cl-lib:fdo (i
(f2cl-lib:int-add j
(f2cl-lib:int-sub 1))
(f2cl-lib:int-add i
(f2cl-lib:int-sub 1)))
((> i 1) nil)
(tagbody
(setf (f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%)
(-
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%)
(* temp
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%))))
(setf k (f2cl-lib:int-sub k 1))
label10))))
(setf kk (f2cl-lib:int-sub kk j))
label20)))
(t
(setf jx
(f2cl-lib:int-add kx
(f2cl-lib:int-mul
(f2cl-lib:int-sub n 1)
incx)))
(f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1)))
((> j 1) nil)
(tagbody
(cond
((/= (f2cl-lib:fref x (jx) ((1 *))) zero)
(if nounit
(setf (f2cl-lib:fref x-%data%
(jx)
((1 *))
x-%offset%)
(/
(f2cl-lib:fref x-%data%
(jx)
((1 *))
x-%offset%)
(f2cl-lib:fref ap-%data%
(kk)
((1 *))
ap-%offset%))))
(setf temp
(f2cl-lib:fref x-%data%
(jx)
((1 *))
x-%offset%))
(setf ix jx)
(f2cl-lib:fdo (k
(f2cl-lib:int-add kk
(f2cl-lib:int-sub 1))
(f2cl-lib:int-add k
(f2cl-lib:int-sub 1)))
((> k
(f2cl-lib:int-add kk
(f2cl-lib:int-sub
j)
1))
nil)
(tagbody
(setf ix (f2cl-lib:int-sub ix incx))
(setf (f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%)
(-
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%)
(* temp
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%))))
label30))))
(setf jx (f2cl-lib:int-sub jx incx))
(setf kk (f2cl-lib:int-sub kk j))
label40)))))
(t
(setf kk 1)
(cond
((= incx 1)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(cond
((/= (f2cl-lib:fref x (j) ((1 *))) zero)
(if nounit
(setf (f2cl-lib:fref x-%data%
(j)
((1 *))
x-%offset%)
(/
(f2cl-lib:fref x-%data%
(j)
((1 *))
x-%offset%)
(f2cl-lib:fref ap-%data%
(kk)
((1 *))
ap-%offset%))))
(setf temp
(f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%))
(setf k (f2cl-lib:int-add kk 1))
(f2cl-lib:fdo (i (f2cl-lib:int-add j 1)
(f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%)
(-
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%)
(* temp
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%))))
(setf k (f2cl-lib:int-add k 1))
label50))))
(setf kk
(f2cl-lib:int-add kk
(f2cl-lib:int-add
(f2cl-lib:int-sub n j)
1)))
label60)))
(t
(setf jx kx)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(cond
((/= (f2cl-lib:fref x (jx) ((1 *))) zero)
(if nounit
(setf (f2cl-lib:fref x-%data%
(jx)
((1 *))
x-%offset%)
(/
(f2cl-lib:fref x-%data%
(jx)
((1 *))
x-%offset%)
(f2cl-lib:fref ap-%data%
(kk)
((1 *))
ap-%offset%))))
(setf temp
(f2cl-lib:fref x-%data%
(jx)
((1 *))
x-%offset%))
(setf ix jx)
(f2cl-lib:fdo (k (f2cl-lib:int-add kk 1)
(f2cl-lib:int-add k 1))
((> k
(f2cl-lib:int-add kk
n
(f2cl-lib:int-sub
j)))
nil)
(tagbody
(setf ix (f2cl-lib:int-add ix incx))
(setf (f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%)
(-
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%)
(* temp
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%))))
label70))))
(setf jx (f2cl-lib:int-add jx incx))
(setf kk
(f2cl-lib:int-add kk
(f2cl-lib:int-add
(f2cl-lib:int-sub n j)
1)))
label80)))))))
(t
(cond
((lsame uplo "U")
(setf kk 1)
(cond
((= incx 1)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp
(f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%))
(setf k kk)
(cond
(noconj
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i
(f2cl-lib:int-add j
(f2cl-lib:int-sub
1)))
nil)
(tagbody
(setf temp
(- temp
(*
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%)
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%))))
(setf k (f2cl-lib:int-add k 1))
label90))
(if nounit
(setf temp
(/ temp
(f2cl-lib:fref ap-%data%
((f2cl-lib:int-sub
(f2cl-lib:int-add kk j)
1))
((1 *))
ap-%offset%)))))
(t
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i
(f2cl-lib:int-add j
(f2cl-lib:int-sub
1)))
nil)
(tagbody
(setf temp
(- temp
(*
(f2cl-lib:dconjg
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%))
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%))))
(setf k (f2cl-lib:int-add k 1))
label100))
(if nounit
(setf temp
(/ temp
(f2cl-lib:dconjg
(f2cl-lib:fref ap-%data%
((f2cl-lib:int-sub
(f2cl-lib:int-add kk
j)
1))
((1 *))
ap-%offset%)))))))
(setf (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)
temp)
(setf kk (f2cl-lib:int-add kk j))
label110)))
(t
(setf jx kx)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp
(f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%))
(setf ix kx)
(cond
(noconj
(f2cl-lib:fdo (k kk (f2cl-lib:int-add k 1))
((> k
(f2cl-lib:int-add kk
j
(f2cl-lib:int-sub
2)))
nil)
(tagbody
(setf temp
(- temp
(*
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%)
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%))))
(setf ix (f2cl-lib:int-add ix incx))
label120))
(if nounit
(setf temp
(/ temp
(f2cl-lib:fref ap-%data%
((f2cl-lib:int-sub
(f2cl-lib:int-add kk j)
1))
((1 *))
ap-%offset%)))))
(t
(f2cl-lib:fdo (k kk (f2cl-lib:int-add k 1))
((> k
(f2cl-lib:int-add kk
j
(f2cl-lib:int-sub
2)))
nil)
(tagbody
(setf temp
(- temp
(*
(f2cl-lib:dconjg
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%))
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%))))
(setf ix (f2cl-lib:int-add ix incx))
label130))
(if nounit
(setf temp
(/ temp
(f2cl-lib:dconjg
(f2cl-lib:fref ap-%data%
((f2cl-lib:int-sub
(f2cl-lib:int-add kk
j)
1))
((1 *))
ap-%offset%)))))))
(setf (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)
temp)
(setf jx (f2cl-lib:int-add jx incx))
(setf kk (f2cl-lib:int-add kk j))
label140)))))
(t
(setf kk (the f2cl-lib:integer4 (truncate (* n (+ n 1)) 2)))
(cond
((= incx 1)
(f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1)))
((> j 1) nil)
(tagbody
(setf temp
(f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%))
(setf k kk)
(cond
(noconj
(f2cl-lib:fdo (i n
(f2cl-lib:int-add i
(f2cl-lib:int-sub 1)))
((> i (f2cl-lib:int-add j 1)) nil)
(tagbody
(setf temp
(- temp
(*
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%)
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%))))
(setf k (f2cl-lib:int-sub k 1))
label150))
(if nounit
(setf temp
(/ temp
(f2cl-lib:fref ap-%data%
((f2cl-lib:int-add
(f2cl-lib:int-sub kk n)
j))
((1 *))
ap-%offset%)))))
(t
(f2cl-lib:fdo (i n
(f2cl-lib:int-add i
(f2cl-lib:int-sub 1)))
((> i (f2cl-lib:int-add j 1)) nil)
(tagbody
(setf temp
(- temp
(*
(f2cl-lib:dconjg
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%))
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%))))
(setf k (f2cl-lib:int-sub k 1))
label160))
(if nounit
(setf temp
(/ temp
(f2cl-lib:dconjg
(f2cl-lib:fref ap-%data%
((f2cl-lib:int-add
(f2cl-lib:int-sub kk
n)
j))
((1 *))
ap-%offset%)))))))
(setf (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)
temp)
(setf kk
(f2cl-lib:int-sub kk
(f2cl-lib:int-add
(f2cl-lib:int-sub n j)
1)))
label170)))
(t
(setf kx
(f2cl-lib:int-add kx
(f2cl-lib:int-mul
(f2cl-lib:int-sub n 1)
incx)))
(setf jx kx)
(f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1)))
((> j 1) nil)
(tagbody
(setf temp
(f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%))
(setf ix kx)
(cond
(noconj
(f2cl-lib:fdo (k kk
(f2cl-lib:int-add k
(f2cl-lib:int-sub 1)))
((> k
(f2cl-lib:int-add kk
(f2cl-lib:int-sub
(f2cl-lib:int-add
n
(f2cl-lib:int-sub
(f2cl-lib:int-add
j
1))))))
nil)
(tagbody
(setf temp
(- temp
(*
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%)
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%))))
(setf ix (f2cl-lib:int-sub ix incx))
label180))
(if nounit
(setf temp
(/ temp
(f2cl-lib:fref ap-%data%
((f2cl-lib:int-add
(f2cl-lib:int-sub kk n)
j))
((1 *))
ap-%offset%)))))
(t
(f2cl-lib:fdo (k kk
(f2cl-lib:int-add k
(f2cl-lib:int-sub 1)))
((> k
(f2cl-lib:int-add kk
(f2cl-lib:int-sub
(f2cl-lib:int-add
n
(f2cl-lib:int-sub
(f2cl-lib:int-add
j
1))))))
nil)
(tagbody
(setf temp
(- temp
(*
(f2cl-lib:dconjg
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%))
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%))))
(setf ix (f2cl-lib:int-sub ix incx))
label190))
(if nounit
(setf temp
(/ temp
(f2cl-lib:dconjg
(f2cl-lib:fref ap-%data%
((f2cl-lib:int-add
(f2cl-lib:int-sub kk
n)
j))
((1 *))
ap-%offset%)))))))
(setf (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)
temp)
(setf jx (f2cl-lib:int-sub jx incx))
(setf kk
(f2cl-lib:int-sub kk
(f2cl-lib:int-add
(f2cl-lib:int-sub n j)
1)))
label200))))))))
(go end_label)
end_label
(return (values nil nil nil nil nil nil nil))))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::ztpsv fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((simple-string) (simple-string) (simple-string)
(fortran-to-lisp::integer4)
(array fortran-to-lisp::complex16 (*))
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4))
:return-values '(nil nil nil nil nil nil nil)
:calls '(fortran-to-lisp::xerbla fortran-to-lisp::lsame))))
| null | https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/share/lapack/blas/ztpsv.lisp | lisp | Compiled by f2cl version:
Using Lisp CMU Common Lisp 20d (20D Unicode)
Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
(:coerce-assigns :as-needed) (:array-type ':array)
(:array-slicing t) (:declare-common nil)
(:float-format double-float)) | ( " f2cl1.l , v 2edcbd958861 2012/05/30 03:34:52 toy $ "
" f2cl2.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl5.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ " )
(in-package :blas)
(let* ((zero (f2cl-lib:cmplx 0.0 0.0)))
(declare (type (f2cl-lib:complex16) zero) (ignorable zero))
(defun ztpsv (uplo trans diag n ap x incx)
(declare (type (array f2cl-lib:complex16 (*)) x ap)
(type (f2cl-lib:integer4) incx n)
(type (simple-string *) diag trans uplo))
(f2cl-lib:with-multi-array-data
((uplo character uplo-%data% uplo-%offset%)
(trans character trans-%data% trans-%offset%)
(diag character diag-%data% diag-%offset%)
(ap f2cl-lib:complex16 ap-%data% ap-%offset%)
(x f2cl-lib:complex16 x-%data% x-%offset%))
(prog ((noconj nil) (nounit nil) (i 0) (info 0) (ix 0) (j 0) (jx 0) (k 0)
(kk 0) (kx 0) (temp #C(0.0 0.0)))
(declare (type f2cl-lib:logical noconj nounit)
(type (f2cl-lib:integer4) i info ix j jx k kk kx)
(type (f2cl-lib:complex16) temp))
(setf info 0)
(cond
((and (not (lsame uplo "U")) (not (lsame uplo "L")))
(setf info 1))
((and (not (lsame trans "N"))
(not (lsame trans "T"))
(not (lsame trans "C")))
(setf info 2))
((and (not (lsame diag "U")) (not (lsame diag "N")))
(setf info 3))
((< n 0)
(setf info 4))
((= incx 0)
(setf info 7)))
(cond
((/= info 0)
(xerbla "ZTPSV " info)
(go end_label)))
(if (= n 0) (go end_label))
(setf noconj (lsame trans "T"))
(setf nounit (lsame diag "N"))
(cond
((<= incx 0)
(setf kx
(f2cl-lib:int-sub 1
(f2cl-lib:int-mul (f2cl-lib:int-sub n 1)
incx))))
((/= incx 1)
(setf kx 1)))
(cond
((lsame trans "N")
(cond
((lsame uplo "U")
(setf kk (the f2cl-lib:integer4 (truncate (* n (+ n 1)) 2)))
(cond
((= incx 1)
(f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1)))
((> j 1) nil)
(tagbody
(cond
((/= (f2cl-lib:fref x (j) ((1 *))) zero)
(if nounit
(setf (f2cl-lib:fref x-%data%
(j)
((1 *))
x-%offset%)
(/
(f2cl-lib:fref x-%data%
(j)
((1 *))
x-%offset%)
(f2cl-lib:fref ap-%data%
(kk)
((1 *))
ap-%offset%))))
(setf temp
(f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%))
(setf k (f2cl-lib:int-sub kk 1))
(f2cl-lib:fdo (i
(f2cl-lib:int-add j
(f2cl-lib:int-sub 1))
(f2cl-lib:int-add i
(f2cl-lib:int-sub 1)))
((> i 1) nil)
(tagbody
(setf (f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%)
(-
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%)
(* temp
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%))))
(setf k (f2cl-lib:int-sub k 1))
label10))))
(setf kk (f2cl-lib:int-sub kk j))
label20)))
(t
(setf jx
(f2cl-lib:int-add kx
(f2cl-lib:int-mul
(f2cl-lib:int-sub n 1)
incx)))
(f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1)))
((> j 1) nil)
(tagbody
(cond
((/= (f2cl-lib:fref x (jx) ((1 *))) zero)
(if nounit
(setf (f2cl-lib:fref x-%data%
(jx)
((1 *))
x-%offset%)
(/
(f2cl-lib:fref x-%data%
(jx)
((1 *))
x-%offset%)
(f2cl-lib:fref ap-%data%
(kk)
((1 *))
ap-%offset%))))
(setf temp
(f2cl-lib:fref x-%data%
(jx)
((1 *))
x-%offset%))
(setf ix jx)
(f2cl-lib:fdo (k
(f2cl-lib:int-add kk
(f2cl-lib:int-sub 1))
(f2cl-lib:int-add k
(f2cl-lib:int-sub 1)))
((> k
(f2cl-lib:int-add kk
(f2cl-lib:int-sub
j)
1))
nil)
(tagbody
(setf ix (f2cl-lib:int-sub ix incx))
(setf (f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%)
(-
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%)
(* temp
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%))))
label30))))
(setf jx (f2cl-lib:int-sub jx incx))
(setf kk (f2cl-lib:int-sub kk j))
label40)))))
(t
(setf kk 1)
(cond
((= incx 1)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(cond
((/= (f2cl-lib:fref x (j) ((1 *))) zero)
(if nounit
(setf (f2cl-lib:fref x-%data%
(j)
((1 *))
x-%offset%)
(/
(f2cl-lib:fref x-%data%
(j)
((1 *))
x-%offset%)
(f2cl-lib:fref ap-%data%
(kk)
((1 *))
ap-%offset%))))
(setf temp
(f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%))
(setf k (f2cl-lib:int-add kk 1))
(f2cl-lib:fdo (i (f2cl-lib:int-add j 1)
(f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%)
(-
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%)
(* temp
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%))))
(setf k (f2cl-lib:int-add k 1))
label50))))
(setf kk
(f2cl-lib:int-add kk
(f2cl-lib:int-add
(f2cl-lib:int-sub n j)
1)))
label60)))
(t
(setf jx kx)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(cond
((/= (f2cl-lib:fref x (jx) ((1 *))) zero)
(if nounit
(setf (f2cl-lib:fref x-%data%
(jx)
((1 *))
x-%offset%)
(/
(f2cl-lib:fref x-%data%
(jx)
((1 *))
x-%offset%)
(f2cl-lib:fref ap-%data%
(kk)
((1 *))
ap-%offset%))))
(setf temp
(f2cl-lib:fref x-%data%
(jx)
((1 *))
x-%offset%))
(setf ix jx)
(f2cl-lib:fdo (k (f2cl-lib:int-add kk 1)
(f2cl-lib:int-add k 1))
((> k
(f2cl-lib:int-add kk
n
(f2cl-lib:int-sub
j)))
nil)
(tagbody
(setf ix (f2cl-lib:int-add ix incx))
(setf (f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%)
(-
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%)
(* temp
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%))))
label70))))
(setf jx (f2cl-lib:int-add jx incx))
(setf kk
(f2cl-lib:int-add kk
(f2cl-lib:int-add
(f2cl-lib:int-sub n j)
1)))
label80)))))))
(t
(cond
((lsame uplo "U")
(setf kk 1)
(cond
((= incx 1)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp
(f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%))
(setf k kk)
(cond
(noconj
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i
(f2cl-lib:int-add j
(f2cl-lib:int-sub
1)))
nil)
(tagbody
(setf temp
(- temp
(*
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%)
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%))))
(setf k (f2cl-lib:int-add k 1))
label90))
(if nounit
(setf temp
(/ temp
(f2cl-lib:fref ap-%data%
((f2cl-lib:int-sub
(f2cl-lib:int-add kk j)
1))
((1 *))
ap-%offset%)))))
(t
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i
(f2cl-lib:int-add j
(f2cl-lib:int-sub
1)))
nil)
(tagbody
(setf temp
(- temp
(*
(f2cl-lib:dconjg
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%))
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%))))
(setf k (f2cl-lib:int-add k 1))
label100))
(if nounit
(setf temp
(/ temp
(f2cl-lib:dconjg
(f2cl-lib:fref ap-%data%
((f2cl-lib:int-sub
(f2cl-lib:int-add kk
j)
1))
((1 *))
ap-%offset%)))))))
(setf (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)
temp)
(setf kk (f2cl-lib:int-add kk j))
label110)))
(t
(setf jx kx)
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(setf temp
(f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%))
(setf ix kx)
(cond
(noconj
(f2cl-lib:fdo (k kk (f2cl-lib:int-add k 1))
((> k
(f2cl-lib:int-add kk
j
(f2cl-lib:int-sub
2)))
nil)
(tagbody
(setf temp
(- temp
(*
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%)
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%))))
(setf ix (f2cl-lib:int-add ix incx))
label120))
(if nounit
(setf temp
(/ temp
(f2cl-lib:fref ap-%data%
((f2cl-lib:int-sub
(f2cl-lib:int-add kk j)
1))
((1 *))
ap-%offset%)))))
(t
(f2cl-lib:fdo (k kk (f2cl-lib:int-add k 1))
((> k
(f2cl-lib:int-add kk
j
(f2cl-lib:int-sub
2)))
nil)
(tagbody
(setf temp
(- temp
(*
(f2cl-lib:dconjg
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%))
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%))))
(setf ix (f2cl-lib:int-add ix incx))
label130))
(if nounit
(setf temp
(/ temp
(f2cl-lib:dconjg
(f2cl-lib:fref ap-%data%
((f2cl-lib:int-sub
(f2cl-lib:int-add kk
j)
1))
((1 *))
ap-%offset%)))))))
(setf (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)
temp)
(setf jx (f2cl-lib:int-add jx incx))
(setf kk (f2cl-lib:int-add kk j))
label140)))))
(t
(setf kk (the f2cl-lib:integer4 (truncate (* n (+ n 1)) 2)))
(cond
((= incx 1)
(f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1)))
((> j 1) nil)
(tagbody
(setf temp
(f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%))
(setf k kk)
(cond
(noconj
(f2cl-lib:fdo (i n
(f2cl-lib:int-add i
(f2cl-lib:int-sub 1)))
((> i (f2cl-lib:int-add j 1)) nil)
(tagbody
(setf temp
(- temp
(*
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%)
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%))))
(setf k (f2cl-lib:int-sub k 1))
label150))
(if nounit
(setf temp
(/ temp
(f2cl-lib:fref ap-%data%
((f2cl-lib:int-add
(f2cl-lib:int-sub kk n)
j))
((1 *))
ap-%offset%)))))
(t
(f2cl-lib:fdo (i n
(f2cl-lib:int-add i
(f2cl-lib:int-sub 1)))
((> i (f2cl-lib:int-add j 1)) nil)
(tagbody
(setf temp
(- temp
(*
(f2cl-lib:dconjg
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%))
(f2cl-lib:fref x-%data%
(i)
((1 *))
x-%offset%))))
(setf k (f2cl-lib:int-sub k 1))
label160))
(if nounit
(setf temp
(/ temp
(f2cl-lib:dconjg
(f2cl-lib:fref ap-%data%
((f2cl-lib:int-add
(f2cl-lib:int-sub kk
n)
j))
((1 *))
ap-%offset%)))))))
(setf (f2cl-lib:fref x-%data% (j) ((1 *)) x-%offset%)
temp)
(setf kk
(f2cl-lib:int-sub kk
(f2cl-lib:int-add
(f2cl-lib:int-sub n j)
1)))
label170)))
(t
(setf kx
(f2cl-lib:int-add kx
(f2cl-lib:int-mul
(f2cl-lib:int-sub n 1)
incx)))
(setf jx kx)
(f2cl-lib:fdo (j n (f2cl-lib:int-add j (f2cl-lib:int-sub 1)))
((> j 1) nil)
(tagbody
(setf temp
(f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%))
(setf ix kx)
(cond
(noconj
(f2cl-lib:fdo (k kk
(f2cl-lib:int-add k
(f2cl-lib:int-sub 1)))
((> k
(f2cl-lib:int-add kk
(f2cl-lib:int-sub
(f2cl-lib:int-add
n
(f2cl-lib:int-sub
(f2cl-lib:int-add
j
1))))))
nil)
(tagbody
(setf temp
(- temp
(*
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%)
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%))))
(setf ix (f2cl-lib:int-sub ix incx))
label180))
(if nounit
(setf temp
(/ temp
(f2cl-lib:fref ap-%data%
((f2cl-lib:int-add
(f2cl-lib:int-sub kk n)
j))
((1 *))
ap-%offset%)))))
(t
(f2cl-lib:fdo (k kk
(f2cl-lib:int-add k
(f2cl-lib:int-sub 1)))
((> k
(f2cl-lib:int-add kk
(f2cl-lib:int-sub
(f2cl-lib:int-add
n
(f2cl-lib:int-sub
(f2cl-lib:int-add
j
1))))))
nil)
(tagbody
(setf temp
(- temp
(*
(f2cl-lib:dconjg
(f2cl-lib:fref ap-%data%
(k)
((1 *))
ap-%offset%))
(f2cl-lib:fref x-%data%
(ix)
((1 *))
x-%offset%))))
(setf ix (f2cl-lib:int-sub ix incx))
label190))
(if nounit
(setf temp
(/ temp
(f2cl-lib:dconjg
(f2cl-lib:fref ap-%data%
((f2cl-lib:int-add
(f2cl-lib:int-sub kk
n)
j))
((1 *))
ap-%offset%)))))))
(setf (f2cl-lib:fref x-%data% (jx) ((1 *)) x-%offset%)
temp)
(setf jx (f2cl-lib:int-sub jx incx))
(setf kk
(f2cl-lib:int-sub kk
(f2cl-lib:int-add
(f2cl-lib:int-sub n j)
1)))
label200))))))))
(go end_label)
end_label
(return (values nil nil nil nil nil nil nil))))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::ztpsv fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((simple-string) (simple-string) (simple-string)
(fortran-to-lisp::integer4)
(array fortran-to-lisp::complex16 (*))
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4))
:return-values '(nil nil nil nil nil nil nil)
:calls '(fortran-to-lisp::xerbla fortran-to-lisp::lsame))))
|
3a28081b7b63e67158a18de6886462c17c6aa156785c309e4390ffcf28c28852 | scrintal/heroicons-reagent | chat_bubble_left_ellipsis.cljs | (ns com.scrintal.heroicons.outline.chat-bubble-left-ellipsis)
(defn render []
[:svg {:xmlns ""
:fill "none"
:viewBox "0 0 24 24"
:strokeWidth "1.5"
:stroke "currentColor"
:aria-hidden "true"}
[:path {:strokeLinecap "round"
:strokeLinejoin "round"
:d "M8.625 9.75a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0H8.25m4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0H12m4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0h-.375m-13.5 3.01c0 1.6 1.123 2.994 2.707 3.227 1.087.16 2.185.283 3.293.369V21l4.184-4.183a1.14 1.14 0 01.778-.332 48.294 48.294 0 005.83-.498c1.585-.233 2.708-1.626 2.708-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0012 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018z"}]]) | null | https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/outline/chat_bubble_left_ellipsis.cljs | clojure | (ns com.scrintal.heroicons.outline.chat-bubble-left-ellipsis)
(defn render []
[:svg {:xmlns ""
:fill "none"
:viewBox "0 0 24 24"
:strokeWidth "1.5"
:stroke "currentColor"
:aria-hidden "true"}
[:path {:strokeLinecap "round"
:strokeLinejoin "round"
:d "M8.625 9.75a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0H8.25m4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0H12m4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0h-.375m-13.5 3.01c0 1.6 1.123 2.994 2.707 3.227 1.087.16 2.185.283 3.293.369V21l4.184-4.183a1.14 1.14 0 01.778-.332 48.294 48.294 0 005.83-.498c1.585-.233 2.708-1.626 2.708-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0012 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018z"}]]) | |
d98e811214436383f34f25006a76f3c518757799f2044a11488de3c3e782ff52 | eryx67/etracker | etracker_db_mgr.erl | %%%-------------------------------------------------------------------
@author < >
( C ) 2012 ,
%%% @doc
%%%
%%% @end
Created : 14 Nov 2012 by < >
%%%-------------------------------------------------------------------
-module(etracker_db_mgr).
%% API
-export([start_link/0, stop/0]).
-define(SERVER, ?MODULE).
start_link() ->
DefaultOpts = {etracker_ets_mgr, [{dir, "etracker_data"},
{dump_interval, 3600},
{ db_type , ets }
{db_type, dict}
]},
{Module, Args} = confval(db_mgr, DefaultOpts),
Ret = Module:start_link(Args),
case Ret of
{ok, Pid} ->
register(?SERVER, Pid);
_ ->
ok
end,
Ret.
stop() ->
?SERVER ! stop,
ok.
confval(Key, Default) ->
etracker_env:get(Key, Default).
| null | https://raw.githubusercontent.com/eryx67/etracker/f41f5d2172d2a0cf5aeebcc7442c7523a9338340/src/etracker_db_mgr.erl | erlang | -------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
API | @author < >
( C ) 2012 ,
Created : 14 Nov 2012 by < >
-module(etracker_db_mgr).
-export([start_link/0, stop/0]).
-define(SERVER, ?MODULE).
start_link() ->
DefaultOpts = {etracker_ets_mgr, [{dir, "etracker_data"},
{dump_interval, 3600},
{ db_type , ets }
{db_type, dict}
]},
{Module, Args} = confval(db_mgr, DefaultOpts),
Ret = Module:start_link(Args),
case Ret of
{ok, Pid} ->
register(?SERVER, Pid);
_ ->
ok
end,
Ret.
stop() ->
?SERVER ! stop,
ok.
confval(Key, Default) ->
etracker_env:get(Key, Default).
|
0fb6ba48ea2c44f1f4f752e4618f686ba5aa14939bc7e5071664a05b4eec7822 | VinylRecords/Vinyl | Lens.hs | # LANGUAGE TypeApplications #
# LANGUAGE AllowAmbiguousTypes #
# LANGUAGE UndecidableInstances #
# LANGUAGE FunctionalDependencies #
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PolyKinds #
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE CPP #-}
#if __GLASGOW_HASKELL__ < 806
{-# LANGUAGE TypeInType #-}
#endif
-- | Lenses into record fields.
module Data.Vinyl.Lens
( RecElem(..)
, rget, rput, rput', rlens, rlens'
, RElem
, RecSubset(..)
, rsubset, rcast, rreplace
, rdowncast
, RSubset
, REquivalent
, type (∈)
, type (⊆)
, type (≅)
, type (<:)
, type (:~:)
) where
import Data.Kind (Constraint)
import Data.Vinyl.Core
import Data.Vinyl.Functor
import Data.Vinyl.TypeLevel
#if __GLASGOW_HASKELL__ < 806
import Data.Kind
#endif
-- | The presence of a field in a record is witnessed by a lens into
its value . The fifth parameter to ' RecElem ' , @i@ , is there to help
-- the constraint solver realize that this is a decidable predicate
-- with respect to the judgemental equality in @k@.
class (i ~ RIndex r rs, NatToInt i)
=> RecElem (record :: (k -> *) -> [k] -> *) (r :: k) (r' :: k) (rs :: [k]) (rs' :: [k]) (i :: Nat) | r r' rs i -> rs' where
-- | An opportunity for instances to generate constraints based on
-- the functor parameter of records passed to class methods.
type RecElemFCtx record (f :: k -> *) :: Constraint
type RecElemFCtx record f = ()
-- | We can get a lens for getting and setting the value of a field which is
-- in a record. As a convenience, we take a proxy argument to fix the
-- particular field being viewed. These lenses are compatible with the @lens@
-- library. Morally:
--
> rlensC : : ' ( Rec f rs ) ( Rec f rs ' ) ( f r ) ( f r ' )
rlensC
:: (Functor g, RecElemFCtx record f)
=> (f r -> g (f r'))
-> record f rs
-> g (record f rs')
-- | For Vinyl users who are not using the @lens@ package, we provide a getter.
rgetC
:: (RecElemFCtx record f, r ~ r')
=> record f rs
-> f r
-- | For Vinyl users who are not using the @lens@ package, we also provide a
-- setter. In general, it will be unambiguous what field is being written to,
-- and so we do not take a proxy argument here.
rputC
:: RecElemFCtx record f
=> f r'
-> record f rs
-> record f rs'
-- | 'RecElem' for classic vinyl 'Rec' types.
type RElem x rs = RecElem Rec x x rs rs
-- This is an internal convenience stolen from the @lens@ library.
lens
:: Functor f
=> (s -> a)
-> (s -> b -> t)
-> (a -> f b)
-> s
-> f t
lens sa sbt afb s = fmap (sbt s) $ afb (sa s)
# INLINE lens #
instance RecElem Rec r r' (r ': rs) (r' ': rs) 'Z where
rlensC f (x :& xs) = fmap (:& xs) (f x)
# INLINE rlensC #
rgetC = getConst . rlensC Const
# INLINE rgetC #
rputC y = getIdentity . rlensC @_ @_ @r (\_ -> Identity y)
# INLINE rputC #
instance (RIndex r (s ': rs) ~ 'S i, RecElem Rec r r' rs rs' i)
=> RecElem Rec r r' (s ': rs) (s ': rs') ('S i) where
rlensC f (x :& xs) = fmap (x :&) (rlensC f xs)
# INLINE rlensC #
rgetC = getConst . rlensC @_ @_ @r @r' Const
# INLINE rgetC #
rputC y = getIdentity . rlensC @_ @_ @r (\_ -> Identity y)
# INLINE rputC #
-- | The 'rgetC' field getter with the type arguments re-ordered for
-- more convenient usage with @TypeApplications@.
rget :: forall r rs f record.
(RecElem record r r rs rs (RIndex r rs), RecElemFCtx record f)
=> record f rs -> f r
rget = rgetC
-- | The type-changing field setter 'rputC' with the type arguments
-- re-ordered for more convenient usage with @TypeApplications@.
rput' :: forall k (r :: k) (r' :: k) (rs :: [k]) (rs' :: [k]) record f
. (RecElem record r r' rs rs' (RIndex r rs), RecElemFCtx record f)
=> f r' -> record f rs -> record f rs'
rput' = rputC @k @record @r @r' @rs @rs'
-- | Type-preserving field setter. This type is simpler to work with
than that of ' rput '' .
rput :: forall k (r :: k) rs record f. (RecElem record r r rs rs (RIndex r rs), RecElemFCtx record f)
=> f r -> record f rs -> record f rs
rput = rput' @_ @r @r @rs @rs @record
-- | Type-changing field lens 'rlensC' with the type arguments
-- re-ordered for more convenient usage with @TypeApplications@.
rlens' :: forall r r' record rs rs' f g.
(RecElem record r r' rs rs' (RIndex r rs), RecElemFCtx record f, Functor g)
=> (f r -> g (f r')) -> record f rs -> g (record f rs')
rlens' = rlensC
-- | Type-preserving field lens. This type is simpler to work with
-- than that of 'rlens''.
rlens :: forall r record rs f g.
(RecElem record r r rs rs (RIndex r rs), RecElemFCtx record f, Functor g)
=> (f r -> g (f r)) -> record f rs -> g (record f rs)
rlens = rlensC
| If one field set is a subset another , then a lens of from the latter 's
-- record to the former's is evident. That is, we can either cast a larger
-- record to a smaller one, or we may replace the values in a slice of a
-- record.
class is ~ RImage rs ss => RecSubset record rs ss is where
-- | An opportunity for instances to generate constraints based on
-- the functor parameter of records passed to class methods.
type RecSubsetFCtx record (f :: k -> *) :: Constraint
type RecSubsetFCtx record f = ()
-- | This is a lens into a slice of the larger record. Morally, we have:
--
> rsubset : : ' ( Rec f ss ) ( Rec f rs )
rsubsetC
:: (Functor g, RecSubsetFCtx record f)
=> (record f rs -> g (record f rs))
-> record f ss
-> g (record f ss)
-- | The getter of the 'rsubset' lens is 'rcast', which takes a larger record
-- to a smaller one by forgetting fields.
rcastC
:: RecSubsetFCtx record f
=> record f ss
-> record f rs
rcastC = getConst . rsubsetC Const
# INLINE rcastC #
-- | The setter of the 'rsubset' lens is 'rreplace', which allows a slice of
-- a record to be replaced with different values.
rreplaceC
:: RecSubsetFCtx record f
=> record f rs
-> record f ss
-> record f ss
rreplaceC rs = getIdentity . rsubsetC (\_ -> Identity rs)
# INLINE rreplaceC #
-- | A lens into a slice of the larger record. This is 'rsubsetC' with
-- the type arguments reordered for more convenient usage with
-- @TypeApplications@.
rsubset :: forall k rs ss f g record is.
(RecSubset record (rs :: [k]) (ss :: [k]) is,
Functor g, RecSubsetFCtx record f)
=> (record f rs -> g (record f rs)) -> record f ss -> g (record f ss)
rsubset = rsubsetC
-- | Takes a larger record to a smaller one by forgetting fields. This
-- is 'rcastC' with the type arguments reordered for more convenient
-- usage with @TypeApplications@.
rcast :: forall rs ss f record is.
(RecSubset record rs ss is, RecSubsetFCtx record f)
=> record f ss -> record f rs
rcast = rcastC
-- | Allows a slice of a record to be replaced with different
-- values. This is 'rreplaceC' with the type arguments reordered for
-- more convenient usage with @TypeApplications@.
rreplace :: forall rs ss f record is.
(RecSubset record rs ss is, RecSubsetFCtx record f)
=> record f rs -> record f ss -> record f ss
rreplace = rreplaceC
-- | Takes a smaller record to a larger one, a /downcast/, by layering a
-- 'Maybe' interpretation that lets us use 'Nothing' for the fields
-- not present in the smaller record.
rdowncast :: (RecApplicative ss, RMap rs, rs ⊆ ss)
=> Rec f rs -> Rec (Maybe :. f) ss
rdowncast = flip rreplace (rpure (Compose Nothing)) . rmap (Compose . Just)
type RSubset = RecSubset Rec
instance RecSubset Rec '[] ss '[] where
rsubsetC = lens (const RNil) const
instance (RElem r ss i , RSubset rs ss is) => RecSubset Rec (r ': rs) ss (i ': is) where
rsubsetC = lens (\ss -> rget ss :& rcastC ss) set
where
set :: Rec f ss -> Rec f (r ': rs) -> Rec f ss
set ss (r :& rs) = rput r $ rreplaceC rs ss
-- | Two record types are equivalent when they are subtypes of each other.
type REquivalent rs ss is js = (RSubset rs ss is, RSubset ss rs js)
-- | A shorthand for 'RElem' which supplies its index.
type r ∈ rs = RElem r rs (RIndex r rs)
-- | A shorthand for 'RSubset' which supplies its image.
type rs ⊆ ss = RSubset rs ss (RImage rs ss)
-- | A shorthand for 'REquivalent' which supplies its images.
type rs ≅ ss = REquivalent rs ss (RImage rs ss) (RImage ss rs)
-- | A non-unicode equivalent of @(⊆)@.
type rs <: ss = rs ⊆ ss
| A non - unicode equivalent of @(≅)@.
type rs :~: ss = rs ≅ ss
| null | https://raw.githubusercontent.com/VinylRecords/Vinyl/0ed0fa278e96c6036a4eef1ae86bf5f66dabdc62/Data/Vinyl/Lens.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators #
# LANGUAGE CPP #
# LANGUAGE TypeInType #
| Lenses into record fields.
| The presence of a field in a record is witnessed by a lens into
the constraint solver realize that this is a decidable predicate
with respect to the judgemental equality in @k@.
| An opportunity for instances to generate constraints based on
the functor parameter of records passed to class methods.
| We can get a lens for getting and setting the value of a field which is
in a record. As a convenience, we take a proxy argument to fix the
particular field being viewed. These lenses are compatible with the @lens@
library. Morally:
| For Vinyl users who are not using the @lens@ package, we provide a getter.
| For Vinyl users who are not using the @lens@ package, we also provide a
setter. In general, it will be unambiguous what field is being written to,
and so we do not take a proxy argument here.
| 'RecElem' for classic vinyl 'Rec' types.
This is an internal convenience stolen from the @lens@ library.
| The 'rgetC' field getter with the type arguments re-ordered for
more convenient usage with @TypeApplications@.
| The type-changing field setter 'rputC' with the type arguments
re-ordered for more convenient usage with @TypeApplications@.
| Type-preserving field setter. This type is simpler to work with
| Type-changing field lens 'rlensC' with the type arguments
re-ordered for more convenient usage with @TypeApplications@.
| Type-preserving field lens. This type is simpler to work with
than that of 'rlens''.
record to the former's is evident. That is, we can either cast a larger
record to a smaller one, or we may replace the values in a slice of a
record.
| An opportunity for instances to generate constraints based on
the functor parameter of records passed to class methods.
| This is a lens into a slice of the larger record. Morally, we have:
| The getter of the 'rsubset' lens is 'rcast', which takes a larger record
to a smaller one by forgetting fields.
| The setter of the 'rsubset' lens is 'rreplace', which allows a slice of
a record to be replaced with different values.
| A lens into a slice of the larger record. This is 'rsubsetC' with
the type arguments reordered for more convenient usage with
@TypeApplications@.
| Takes a larger record to a smaller one by forgetting fields. This
is 'rcastC' with the type arguments reordered for more convenient
usage with @TypeApplications@.
| Allows a slice of a record to be replaced with different
values. This is 'rreplaceC' with the type arguments reordered for
more convenient usage with @TypeApplications@.
| Takes a smaller record to a larger one, a /downcast/, by layering a
'Maybe' interpretation that lets us use 'Nothing' for the fields
not present in the smaller record.
| Two record types are equivalent when they are subtypes of each other.
| A shorthand for 'RElem' which supplies its index.
| A shorthand for 'RSubset' which supplies its image.
| A shorthand for 'REquivalent' which supplies its images.
| A non-unicode equivalent of @(⊆)@. | # LANGUAGE TypeApplications #
# LANGUAGE AllowAmbiguousTypes #
# LANGUAGE UndecidableInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PolyKinds #
# LANGUAGE TypeFamilies #
#if __GLASGOW_HASKELL__ < 806
#endif
module Data.Vinyl.Lens
( RecElem(..)
, rget, rput, rput', rlens, rlens'
, RElem
, RecSubset(..)
, rsubset, rcast, rreplace
, rdowncast
, RSubset
, REquivalent
, type (∈)
, type (⊆)
, type (≅)
, type (<:)
, type (:~:)
) where
import Data.Kind (Constraint)
import Data.Vinyl.Core
import Data.Vinyl.Functor
import Data.Vinyl.TypeLevel
#if __GLASGOW_HASKELL__ < 806
import Data.Kind
#endif
its value . The fifth parameter to ' RecElem ' , @i@ , is there to help
class (i ~ RIndex r rs, NatToInt i)
=> RecElem (record :: (k -> *) -> [k] -> *) (r :: k) (r' :: k) (rs :: [k]) (rs' :: [k]) (i :: Nat) | r r' rs i -> rs' where
type RecElemFCtx record (f :: k -> *) :: Constraint
type RecElemFCtx record f = ()
> rlensC : : ' ( Rec f rs ) ( Rec f rs ' ) ( f r ) ( f r ' )
rlensC
:: (Functor g, RecElemFCtx record f)
=> (f r -> g (f r'))
-> record f rs
-> g (record f rs')
rgetC
:: (RecElemFCtx record f, r ~ r')
=> record f rs
-> f r
rputC
:: RecElemFCtx record f
=> f r'
-> record f rs
-> record f rs'
type RElem x rs = RecElem Rec x x rs rs
lens
:: Functor f
=> (s -> a)
-> (s -> b -> t)
-> (a -> f b)
-> s
-> f t
lens sa sbt afb s = fmap (sbt s) $ afb (sa s)
# INLINE lens #
instance RecElem Rec r r' (r ': rs) (r' ': rs) 'Z where
rlensC f (x :& xs) = fmap (:& xs) (f x)
# INLINE rlensC #
rgetC = getConst . rlensC Const
# INLINE rgetC #
rputC y = getIdentity . rlensC @_ @_ @r (\_ -> Identity y)
# INLINE rputC #
instance (RIndex r (s ': rs) ~ 'S i, RecElem Rec r r' rs rs' i)
=> RecElem Rec r r' (s ': rs) (s ': rs') ('S i) where
rlensC f (x :& xs) = fmap (x :&) (rlensC f xs)
# INLINE rlensC #
rgetC = getConst . rlensC @_ @_ @r @r' Const
# INLINE rgetC #
rputC y = getIdentity . rlensC @_ @_ @r (\_ -> Identity y)
# INLINE rputC #
rget :: forall r rs f record.
(RecElem record r r rs rs (RIndex r rs), RecElemFCtx record f)
=> record f rs -> f r
rget = rgetC
rput' :: forall k (r :: k) (r' :: k) (rs :: [k]) (rs' :: [k]) record f
. (RecElem record r r' rs rs' (RIndex r rs), RecElemFCtx record f)
=> f r' -> record f rs -> record f rs'
rput' = rputC @k @record @r @r' @rs @rs'
than that of ' rput '' .
rput :: forall k (r :: k) rs record f. (RecElem record r r rs rs (RIndex r rs), RecElemFCtx record f)
=> f r -> record f rs -> record f rs
rput = rput' @_ @r @r @rs @rs @record
rlens' :: forall r r' record rs rs' f g.
(RecElem record r r' rs rs' (RIndex r rs), RecElemFCtx record f, Functor g)
=> (f r -> g (f r')) -> record f rs -> g (record f rs')
rlens' = rlensC
rlens :: forall r record rs f g.
(RecElem record r r rs rs (RIndex r rs), RecElemFCtx record f, Functor g)
=> (f r -> g (f r)) -> record f rs -> g (record f rs)
rlens = rlensC
| If one field set is a subset another , then a lens of from the latter 's
class is ~ RImage rs ss => RecSubset record rs ss is where
type RecSubsetFCtx record (f :: k -> *) :: Constraint
type RecSubsetFCtx record f = ()
> rsubset : : ' ( Rec f ss ) ( Rec f rs )
rsubsetC
:: (Functor g, RecSubsetFCtx record f)
=> (record f rs -> g (record f rs))
-> record f ss
-> g (record f ss)
rcastC
:: RecSubsetFCtx record f
=> record f ss
-> record f rs
rcastC = getConst . rsubsetC Const
# INLINE rcastC #
rreplaceC
:: RecSubsetFCtx record f
=> record f rs
-> record f ss
-> record f ss
rreplaceC rs = getIdentity . rsubsetC (\_ -> Identity rs)
# INLINE rreplaceC #
rsubset :: forall k rs ss f g record is.
(RecSubset record (rs :: [k]) (ss :: [k]) is,
Functor g, RecSubsetFCtx record f)
=> (record f rs -> g (record f rs)) -> record f ss -> g (record f ss)
rsubset = rsubsetC
rcast :: forall rs ss f record is.
(RecSubset record rs ss is, RecSubsetFCtx record f)
=> record f ss -> record f rs
rcast = rcastC
rreplace :: forall rs ss f record is.
(RecSubset record rs ss is, RecSubsetFCtx record f)
=> record f rs -> record f ss -> record f ss
rreplace = rreplaceC
rdowncast :: (RecApplicative ss, RMap rs, rs ⊆ ss)
=> Rec f rs -> Rec (Maybe :. f) ss
rdowncast = flip rreplace (rpure (Compose Nothing)) . rmap (Compose . Just)
type RSubset = RecSubset Rec
instance RecSubset Rec '[] ss '[] where
rsubsetC = lens (const RNil) const
instance (RElem r ss i , RSubset rs ss is) => RecSubset Rec (r ': rs) ss (i ': is) where
rsubsetC = lens (\ss -> rget ss :& rcastC ss) set
where
set :: Rec f ss -> Rec f (r ': rs) -> Rec f ss
set ss (r :& rs) = rput r $ rreplaceC rs ss
type REquivalent rs ss is js = (RSubset rs ss is, RSubset ss rs js)
type r ∈ rs = RElem r rs (RIndex r rs)
type rs ⊆ ss = RSubset rs ss (RImage rs ss)
type rs ≅ ss = REquivalent rs ss (RImage rs ss) (RImage ss rs)
type rs <: ss = rs ⊆ ss
| A non - unicode equivalent of @(≅)@.
type rs :~: ss = rs ≅ ss
|
775a3440261a2cf1f1b3702ced1707a5f11e605c2712d263540374d7860f029b | K2InformaticsGmbH/egambo | egambo_tictac_win_5_5_4_p.erl | -module(egambo_tictac_win_5_5_4_p).
-export([win/2]).
% generated in egambo_tictac_wip
win(<<P:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<P:8, P:8, P:8, _:8, P:8, _/binary>>, P) -> true;
win(<<P:8, P:8, _:8, P:8, P:8, _/binary>>, P) -> true;
win(<<P:8, _:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<P:8, _:32, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<P:8, _:32, P:8, _:32, P:8, _:72, P:8, _/binary>>, P) -> true;
win(<<P:8, _:32, P:8, _:72, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<P:8, _:40, P:8, _:40, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<P:8, _:40, P:8, _:40, P:8, _:88, P:8, _/binary>>, P) -> true;
win(<<P:8, _:40, P:8, _:88, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<P:8, _:64, P:8, _:24, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<P:8, _:64, P:8, _:24, P:8, _:56, P:8, _/binary>>, P) -> true;
win(<<P:8, _:64, P:8, _:56, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<P:8, _:72, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<P:8, _:88, P:8, _:40, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<P:8, _:96, P:8, _:24, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:24, P:8, _:64, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:24, P:8, _:64, P:8, _:56, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:24, P:8, _:96, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:32, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:32, P:8, _:32, P:8, _:72, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:32, P:8, _:72, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:40, P:8, _:40, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:40, P:8, _:40, P:8, _:48, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:40, P:8, _:88, P:8, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:72, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:88, P:8, _:40, P:8, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:96, P:8, _:24, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:24, P:8, _:24, P:8, _:64, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:24, P:8, _:24, P:8, _:96, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:24, P:8, _:96, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:32, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:32, P:8, _:32, P:8, _:72, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:32, P:8, _:72, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:40, P:8, _:40, P:8, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:40, P:8, _:40, P:8, _:48, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:40, P:8, _:48, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:56, P:8, _:64, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:72, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:88, P:8, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:24, P:8, _:24, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:24, P:8, _:24, P:8, _:96, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:24, P:8, _:56, P:8, _:64, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:32, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:32, P:8, _:32, P:8, _:72, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:32, P:8, _:72, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:40, P:8, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:40, P:8, P:8, _:88, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:40, P:8, _:48, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:48, P:8, _:40, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:56, P:8, _:24, P:8, _:64, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:72, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, P:8, _:40, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, P:8, _:40, P:8, _:88, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, P:8, _:88, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, _:24, P:8, _:24, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, _:24, P:8, _:24, P:8, _:56, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, _:24, P:8, _:56, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, _:32, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, _:32, P:8, _:32, P:8, _:72, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, _:32, P:8, _:72, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, _:48, P:8, _:40, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, _:56, P:8, _:24, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, _:72, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:40, P:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:40, P:8, P:8, P:8, _:8, P:8, _/binary>>, P) -> true;
win(<<_:40, P:8, P:8, _:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:40, P:8, _:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:40, P:8, _:32, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:40, P:8, _:40, P:8, _:40, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:40, P:8, _:64, P:8, _:24, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:48, P:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:48, P:8, _:24, P:8, _:64, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:48, P:8, _:32, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:48, P:8, _:40, P:8, _:40, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:56, P:8, _:24, P:8, _:24, P:8, _:64, P:8, _/binary>>, P) -> true;
win(<<_:56, P:8, _:32, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:56, P:8, _:40, P:8, _:40, P:8, P:8, _/binary>>, P) -> true;
win(<<_:64, P:8, _:24, P:8, _:24, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:64, P:8, _:32, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:64, P:8, _:40, P:8, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:72, P:8, P:8, _:40, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:72, P:8, _:24, P:8, _:24, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:72, P:8, _:32, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:80, P:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:80, P:8, P:8, P:8, _:8, P:8, _/binary>>, P) -> true;
win(<<_:80, P:8, P:8, _:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:80, P:8, _:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:88, P:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:120, P:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:120, P:8, P:8, P:8, _:8, P:8, _/binary>>, P) -> true;
win(<<_:120, P:8, P:8, _:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:120, P:8, _:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:128, P:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:160, P:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:160, P:8, P:8, P:8, _:8, P:8, _/binary>>, P) -> true;
win(<<_:160, P:8, P:8, _:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:160, P:8, _:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:168, P:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(_, _) -> false.
| null | https://raw.githubusercontent.com/K2InformaticsGmbH/egambo/e8bdf971f188a2139db52712ab5b9d87b2f11520/src/egambo_tictac_win_5_5_4_p.erl | erlang | generated in egambo_tictac_wip | -module(egambo_tictac_win_5_5_4_p).
-export([win/2]).
win(<<P:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<P:8, P:8, P:8, _:8, P:8, _/binary>>, P) -> true;
win(<<P:8, P:8, _:8, P:8, P:8, _/binary>>, P) -> true;
win(<<P:8, _:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<P:8, _:32, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<P:8, _:32, P:8, _:32, P:8, _:72, P:8, _/binary>>, P) -> true;
win(<<P:8, _:32, P:8, _:72, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<P:8, _:40, P:8, _:40, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<P:8, _:40, P:8, _:40, P:8, _:88, P:8, _/binary>>, P) -> true;
win(<<P:8, _:40, P:8, _:88, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<P:8, _:64, P:8, _:24, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<P:8, _:64, P:8, _:24, P:8, _:56, P:8, _/binary>>, P) -> true;
win(<<P:8, _:64, P:8, _:56, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<P:8, _:72, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<P:8, _:88, P:8, _:40, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<P:8, _:96, P:8, _:24, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:24, P:8, _:64, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:24, P:8, _:64, P:8, _:56, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:24, P:8, _:96, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:32, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:32, P:8, _:32, P:8, _:72, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:32, P:8, _:72, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:40, P:8, _:40, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:40, P:8, _:40, P:8, _:48, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:40, P:8, _:88, P:8, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:72, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:88, P:8, _:40, P:8, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:96, P:8, _:24, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:24, P:8, _:24, P:8, _:64, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:24, P:8, _:24, P:8, _:96, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:24, P:8, _:96, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:32, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:32, P:8, _:32, P:8, _:72, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:32, P:8, _:72, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:40, P:8, _:40, P:8, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:40, P:8, _:40, P:8, _:48, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:40, P:8, _:48, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:56, P:8, _:64, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:72, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:88, P:8, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:24, P:8, _:24, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:24, P:8, _:24, P:8, _:96, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:24, P:8, _:56, P:8, _:64, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:32, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:32, P:8, _:32, P:8, _:72, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:32, P:8, _:72, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:40, P:8, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:40, P:8, P:8, _:88, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:40, P:8, _:48, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:48, P:8, _:40, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:56, P:8, _:24, P:8, _:64, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, _:72, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, P:8, _:40, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, P:8, _:40, P:8, _:88, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, P:8, _:88, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, _:24, P:8, _:24, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, _:24, P:8, _:24, P:8, _:56, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, _:24, P:8, _:56, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, _:32, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, _:32, P:8, _:32, P:8, _:72, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, _:32, P:8, _:72, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, _:48, P:8, _:40, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, _:56, P:8, _:24, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:32, P:8, _:72, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:40, P:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:40, P:8, P:8, P:8, _:8, P:8, _/binary>>, P) -> true;
win(<<_:40, P:8, P:8, _:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:40, P:8, _:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:40, P:8, _:32, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:40, P:8, _:40, P:8, _:40, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:40, P:8, _:64, P:8, _:24, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:48, P:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:48, P:8, _:24, P:8, _:64, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:48, P:8, _:32, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:48, P:8, _:40, P:8, _:40, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:56, P:8, _:24, P:8, _:24, P:8, _:64, P:8, _/binary>>, P) -> true;
win(<<_:56, P:8, _:32, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:56, P:8, _:40, P:8, _:40, P:8, P:8, _/binary>>, P) -> true;
win(<<_:64, P:8, _:24, P:8, _:24, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:64, P:8, _:32, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:64, P:8, _:40, P:8, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:72, P:8, P:8, _:40, P:8, _:40, P:8, _/binary>>, P) -> true;
win(<<_:72, P:8, _:24, P:8, _:24, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:72, P:8, _:32, P:8, _:32, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:80, P:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:80, P:8, P:8, P:8, _:8, P:8, _/binary>>, P) -> true;
win(<<_:80, P:8, P:8, _:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:80, P:8, _:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:88, P:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:120, P:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:120, P:8, P:8, P:8, _:8, P:8, _/binary>>, P) -> true;
win(<<_:120, P:8, P:8, _:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:120, P:8, _:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:128, P:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:160, P:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:160, P:8, P:8, P:8, _:8, P:8, _/binary>>, P) -> true;
win(<<_:160, P:8, P:8, _:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:160, P:8, _:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:168, P:8, P:8, P:8, P:8, _/binary>>, P) -> true;
win(_, _) -> false.
|
70ba4fbfb5a6d183c3357f12db96c679a5bea919b88de8b9ee771b031e4b0d8b | penpot/penpot | color_selection.cljs | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
;;
;; Copyright (c) KALEIDOS INC
(ns app.main.ui.workspace.sidebar.options.menus.color-selection
(:require
[app.common.data :as d]
[app.common.data.macros :as dm]
[app.common.text :as txt]
[app.main.data.workspace.colors :as dc]
[app.main.data.workspace.selection :as dws]
[app.main.store :as st]
[app.main.ui.icons :as i]
[app.main.ui.workspace.sidebar.options.rows.color-row :refer [color-row]]
[app.util.i18n :as i18n :refer [tr]]
[cuerdas.core :as str]
[rumext.v2 :as mf]))
(defn fill->color-att
[fill file-id shared-libs]
(let [color-file-id (:fill-color-ref-file fill)
color-id (:fill-color-ref-id fill)
shared-libs-colors (dm/get-in shared-libs [color-file-id :data :colors])
is-shared? (contains? shared-libs-colors color-id)
attrs (if (or is-shared? (= color-file-id file-id))
(d/without-nils {:color (str/lower (:fill-color fill))
:opacity (:fill-opacity fill)
:id color-id
:file-id color-file-id
:gradient (:fill-color-gradient fill)})
(d/without-nils {:color (str/lower (:fill-color fill))
:opacity (:fill-opacity fill)
:gradient (:fill-color-gradient fill)}))]
{:attrs attrs
:prop :fill
:shape-id (:shape-id fill)
:index (:index fill)}))
(defn stroke->color-att
[stroke file-id shared-libs]
(let [color-file-id (:stroke-color-ref-file stroke)
color-id (:stroke-color-ref-id stroke)
shared-libs-colors (dm/get-in shared-libs [color-file-id :data :colors])
is-shared? (contains? shared-libs-colors color-id)
has-color? (not (nil? (:stroke-color stroke)))
attrs (if (or is-shared? (= color-file-id file-id))
(d/without-nils {:color (str/lower (:stroke-color stroke))
:opacity (:stroke-opacity stroke)
:id color-id
:file-id color-file-id
:gradient (:stroke-color-gradient stroke)})
(d/without-nils {:color (str/lower (:stroke-color stroke))
:opacity (:stroke-opacity stroke)
:gradient (:stroke-color-gradient stroke)}))]
(when has-color?
{:attrs attrs
:prop :stroke
:shape-id (:shape-id stroke)
:index (:index stroke)})))
(defn shadow->color-att
[shadow file-id shared-libs]
(let [color-file-id (dm/get-in shadow [:color :file-id])
color-id (dm/get-in shadow [:color :id])
shared-libs-colors (dm/get-in shared-libs [color-file-id :data :colors])
is-shared? (contains? shared-libs-colors color-id)
attrs (if (or is-shared? (= color-file-id file-id))
(d/without-nils {:color (str/lower (dm/get-in shadow [:color :color]))
:opacity (dm/get-in shadow [:color :opacity])
:id color-id
:file-id (dm/get-in shadow [:color :file-id])
:gradient (dm/get-in shadow [:color :gradient])})
(d/without-nils {:color (str/lower (dm/get-in shadow [:color :color]))
:opacity (dm/get-in shadow [:color :opacity])
:gradient (dm/get-in shadow [:color :gradient])}))]
{:attrs attrs
:prop :shadow
:shape-id (:shape-id shadow)
:index (:index shadow)}))
(defn text->color-att
[fill file-id shared-libs]
(let [color-file-id (:fill-color-ref-file fill)
color-id (:fill-color-ref-id fill)
shared-libs-colors (dm/get-in shared-libs [color-file-id :data :colors])
is-shared? (contains? shared-libs-colors color-id)
attrs (if (or is-shared? (= color-file-id file-id))
(d/without-nils {:color (str/lower (:fill-color fill))
:opacity (:fill-opacity fill)
:id color-id
:file-id color-file-id
:gradient (:fill-color-gradient fill)})
(d/without-nils {:color (str/lower (:fill-color fill))
:opacity (:fill-opacity fill)
:gradient (:fill-color-gradient fill)}))]
{:attrs attrs
:prop :content
:shape-id (:shape-id fill)
:index (:index fill)}))
(defn treat-node
[node shape-id]
(map-indexed #(assoc %2 :shape-id shape-id :index %1) node))
(defn extract-text-colors
[text file-id shared-libs]
(let [content (txt/node-seq txt/is-text-node? (:content text))
content-filtered (map :fills content)
indexed (mapcat #(treat-node % (:id text)) content-filtered)]
(map #(text->color-att % file-id shared-libs) indexed)))
(defn- extract-all-colors
[shapes file-id shared-libs]
(reduce
(fn [list shape]
(let [fill-obj (map-indexed #(assoc %2 :shape-id (:id shape) :index %1) (:fills shape))
stroke-obj (map-indexed #(assoc %2 :shape-id (:id shape) :index %1) (:strokes shape))
shadow-obj (map-indexed #(assoc %2 :shape-id (:id shape) :index %1) (:shadow shape))]
(if (= :text (:type shape))
(-> list
(into (map #(stroke->color-att % file-id shared-libs)) stroke-obj)
(into (map #(shadow->color-att % file-id shared-libs)) shadow-obj)
(into (extract-text-colors shape file-id shared-libs)))
(-> list
(into (map #(fill->color-att % file-id shared-libs)) fill-obj)
(into (map #(stroke->color-att % file-id shared-libs)) stroke-obj)
(into (map #(shadow->color-att % file-id shared-libs)) shadow-obj)))))
[]
shapes))
(defn- prepare-colors
[shapes file-id shared-libs]
(let [data (into [] (remove nil? (extract-all-colors shapes file-id shared-libs)))
grouped-colors (group-by :attrs data)
all-colors (distinct (mapv :attrs data))
tmp (group-by #(some? (:id %)) all-colors)
library-colors (get tmp true)
colors (get tmp false)]
{:grouped-colors grouped-colors
:all-colors all-colors
:colors colors
:library-colors library-colors}))
(mf/defc color-selection-menu
{::mf/wrap [#(mf/memo' % (mf/check-props ["shapes"]))]}
[{:keys [shapes file-id shared-libs] :as props}]
(let [{:keys [all-colors grouped-colors library-colors colors]} (mf/with-memo [shapes file-id shared-libs]
(prepare-colors shapes file-id shared-libs))
expand-lib-color (mf/use-state false)
expand-color (mf/use-state false)
grouped-colors* (mf/use-var nil)
prev-color* (mf/use-var nil)
on-change
(mf/use-fn
(fn [new-color old-color]
(let [old-color (-> old-color
(dissoc :name)
(dissoc :path)
(d/without-nils))
prev-color (-> @prev-color*
(dissoc :name)
(dissoc :path)
(d/without-nils))
;; When dragging on the color picker sometimes all the shapes hasn't updated the color to the prev value so we need this extra calculation
shapes-by-old-color (get @grouped-colors* old-color)
shapes-by-prev-color (get @grouped-colors* prev-color)
shapes-by-color (or shapes-by-prev-color shapes-by-old-color)]
(reset! prev-color* new-color)
(st/emit! (dc/change-color-in-selected new-color shapes-by-color old-color)))))
on-open (mf/use-fn
(fn [color]
(reset! prev-color* color)))
on-detach
(mf/use-fn
(fn [color]
(let [shapes-by-color (get @grouped-colors* color)
new-color (assoc color :id nil :file-id nil)]
(st/emit! (dc/change-color-in-selected new-color shapes-by-color color)))))
select-only
(mf/use-fn
(fn [color]
(let [shapes-by-color (get @grouped-colors* color)
ids (into (d/ordered-set) (map :shape-id) shapes-by-color)]
(st/emit! (dws/select-shapes ids)))))]
(mf/with-effect [grouped-colors]
(reset! grouped-colors* grouped-colors))
(when (> (count all-colors) 1)
[:div.element-set
[:div.element-set-title
[:span (tr "workspace.options.selection-color")]]
[:div.element-set-content
[:div.selected-colors
(for [[index color] (d/enumerate (take 3 library-colors))]
[:& color-row {:key (dm/str "library-color-" index)
:color color
:index index
:on-detach on-detach
:select-only select-only
:on-change #(on-change % color)
:on-open on-open}])
(when (and (false? @expand-lib-color) (< 3 (count library-colors)))
[:div.expand-colors {:on-click #(reset! expand-lib-color true)}
[:span i/actions]
[:span.text (tr "workspace.options.more-lib-colors")]])
(when @expand-lib-color
(for [[index color] (d/enumerate (drop 3 library-colors))]
[:& color-row {:key (dm/str "library-color-" index)
:color color
:index index
:on-detach on-detach
:select-only select-only
:on-change #(on-change % color)
:on-open on-open}]))]
[:div.selected-colors
(for [[index color] (d/enumerate (take 3 colors))]
[:& color-row {:key (dm/str "color-" index)
:color color
:index index
:select-only select-only
:on-change #(on-change % color)
:on-open on-open}])
(when (and (false? @expand-color) (< 3 (count colors)))
[:div.expand-colors {:on-click #(reset! expand-color true)}
[:span i/actions]
[:span.text (tr "workspace.options.more-colors")]])
(when @expand-color
(for [[index color] (d/enumerate (drop 3 colors))]
[:& color-row {:key (dm/str "color-" index)
:color color
:index index
:select-only select-only
:on-change #(on-change % color)
:on-open on-open}]))]]])))
| null | https://raw.githubusercontent.com/penpot/penpot/7303d311d5f23d515fa3fcdc6cd13cf7f429d1fe/frontend/src/app/main/ui/workspace/sidebar/options/menus/color_selection.cljs | clojure |
Copyright (c) KALEIDOS INC
When dragging on the color picker sometimes all the shapes hasn't updated the color to the prev value so we need this extra calculation | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
(ns app.main.ui.workspace.sidebar.options.menus.color-selection
(:require
[app.common.data :as d]
[app.common.data.macros :as dm]
[app.common.text :as txt]
[app.main.data.workspace.colors :as dc]
[app.main.data.workspace.selection :as dws]
[app.main.store :as st]
[app.main.ui.icons :as i]
[app.main.ui.workspace.sidebar.options.rows.color-row :refer [color-row]]
[app.util.i18n :as i18n :refer [tr]]
[cuerdas.core :as str]
[rumext.v2 :as mf]))
(defn fill->color-att
[fill file-id shared-libs]
(let [color-file-id (:fill-color-ref-file fill)
color-id (:fill-color-ref-id fill)
shared-libs-colors (dm/get-in shared-libs [color-file-id :data :colors])
is-shared? (contains? shared-libs-colors color-id)
attrs (if (or is-shared? (= color-file-id file-id))
(d/without-nils {:color (str/lower (:fill-color fill))
:opacity (:fill-opacity fill)
:id color-id
:file-id color-file-id
:gradient (:fill-color-gradient fill)})
(d/without-nils {:color (str/lower (:fill-color fill))
:opacity (:fill-opacity fill)
:gradient (:fill-color-gradient fill)}))]
{:attrs attrs
:prop :fill
:shape-id (:shape-id fill)
:index (:index fill)}))
(defn stroke->color-att
[stroke file-id shared-libs]
(let [color-file-id (:stroke-color-ref-file stroke)
color-id (:stroke-color-ref-id stroke)
shared-libs-colors (dm/get-in shared-libs [color-file-id :data :colors])
is-shared? (contains? shared-libs-colors color-id)
has-color? (not (nil? (:stroke-color stroke)))
attrs (if (or is-shared? (= color-file-id file-id))
(d/without-nils {:color (str/lower (:stroke-color stroke))
:opacity (:stroke-opacity stroke)
:id color-id
:file-id color-file-id
:gradient (:stroke-color-gradient stroke)})
(d/without-nils {:color (str/lower (:stroke-color stroke))
:opacity (:stroke-opacity stroke)
:gradient (:stroke-color-gradient stroke)}))]
(when has-color?
{:attrs attrs
:prop :stroke
:shape-id (:shape-id stroke)
:index (:index stroke)})))
(defn shadow->color-att
[shadow file-id shared-libs]
(let [color-file-id (dm/get-in shadow [:color :file-id])
color-id (dm/get-in shadow [:color :id])
shared-libs-colors (dm/get-in shared-libs [color-file-id :data :colors])
is-shared? (contains? shared-libs-colors color-id)
attrs (if (or is-shared? (= color-file-id file-id))
(d/without-nils {:color (str/lower (dm/get-in shadow [:color :color]))
:opacity (dm/get-in shadow [:color :opacity])
:id color-id
:file-id (dm/get-in shadow [:color :file-id])
:gradient (dm/get-in shadow [:color :gradient])})
(d/without-nils {:color (str/lower (dm/get-in shadow [:color :color]))
:opacity (dm/get-in shadow [:color :opacity])
:gradient (dm/get-in shadow [:color :gradient])}))]
{:attrs attrs
:prop :shadow
:shape-id (:shape-id shadow)
:index (:index shadow)}))
(defn text->color-att
[fill file-id shared-libs]
(let [color-file-id (:fill-color-ref-file fill)
color-id (:fill-color-ref-id fill)
shared-libs-colors (dm/get-in shared-libs [color-file-id :data :colors])
is-shared? (contains? shared-libs-colors color-id)
attrs (if (or is-shared? (= color-file-id file-id))
(d/without-nils {:color (str/lower (:fill-color fill))
:opacity (:fill-opacity fill)
:id color-id
:file-id color-file-id
:gradient (:fill-color-gradient fill)})
(d/without-nils {:color (str/lower (:fill-color fill))
:opacity (:fill-opacity fill)
:gradient (:fill-color-gradient fill)}))]
{:attrs attrs
:prop :content
:shape-id (:shape-id fill)
:index (:index fill)}))
(defn treat-node
[node shape-id]
(map-indexed #(assoc %2 :shape-id shape-id :index %1) node))
(defn extract-text-colors
[text file-id shared-libs]
(let [content (txt/node-seq txt/is-text-node? (:content text))
content-filtered (map :fills content)
indexed (mapcat #(treat-node % (:id text)) content-filtered)]
(map #(text->color-att % file-id shared-libs) indexed)))
(defn- extract-all-colors
[shapes file-id shared-libs]
(reduce
(fn [list shape]
(let [fill-obj (map-indexed #(assoc %2 :shape-id (:id shape) :index %1) (:fills shape))
stroke-obj (map-indexed #(assoc %2 :shape-id (:id shape) :index %1) (:strokes shape))
shadow-obj (map-indexed #(assoc %2 :shape-id (:id shape) :index %1) (:shadow shape))]
(if (= :text (:type shape))
(-> list
(into (map #(stroke->color-att % file-id shared-libs)) stroke-obj)
(into (map #(shadow->color-att % file-id shared-libs)) shadow-obj)
(into (extract-text-colors shape file-id shared-libs)))
(-> list
(into (map #(fill->color-att % file-id shared-libs)) fill-obj)
(into (map #(stroke->color-att % file-id shared-libs)) stroke-obj)
(into (map #(shadow->color-att % file-id shared-libs)) shadow-obj)))))
[]
shapes))
(defn- prepare-colors
[shapes file-id shared-libs]
(let [data (into [] (remove nil? (extract-all-colors shapes file-id shared-libs)))
grouped-colors (group-by :attrs data)
all-colors (distinct (mapv :attrs data))
tmp (group-by #(some? (:id %)) all-colors)
library-colors (get tmp true)
colors (get tmp false)]
{:grouped-colors grouped-colors
:all-colors all-colors
:colors colors
:library-colors library-colors}))
(mf/defc color-selection-menu
{::mf/wrap [#(mf/memo' % (mf/check-props ["shapes"]))]}
[{:keys [shapes file-id shared-libs] :as props}]
(let [{:keys [all-colors grouped-colors library-colors colors]} (mf/with-memo [shapes file-id shared-libs]
(prepare-colors shapes file-id shared-libs))
expand-lib-color (mf/use-state false)
expand-color (mf/use-state false)
grouped-colors* (mf/use-var nil)
prev-color* (mf/use-var nil)
on-change
(mf/use-fn
(fn [new-color old-color]
(let [old-color (-> old-color
(dissoc :name)
(dissoc :path)
(d/without-nils))
prev-color (-> @prev-color*
(dissoc :name)
(dissoc :path)
(d/without-nils))
shapes-by-old-color (get @grouped-colors* old-color)
shapes-by-prev-color (get @grouped-colors* prev-color)
shapes-by-color (or shapes-by-prev-color shapes-by-old-color)]
(reset! prev-color* new-color)
(st/emit! (dc/change-color-in-selected new-color shapes-by-color old-color)))))
on-open (mf/use-fn
(fn [color]
(reset! prev-color* color)))
on-detach
(mf/use-fn
(fn [color]
(let [shapes-by-color (get @grouped-colors* color)
new-color (assoc color :id nil :file-id nil)]
(st/emit! (dc/change-color-in-selected new-color shapes-by-color color)))))
select-only
(mf/use-fn
(fn [color]
(let [shapes-by-color (get @grouped-colors* color)
ids (into (d/ordered-set) (map :shape-id) shapes-by-color)]
(st/emit! (dws/select-shapes ids)))))]
(mf/with-effect [grouped-colors]
(reset! grouped-colors* grouped-colors))
(when (> (count all-colors) 1)
[:div.element-set
[:div.element-set-title
[:span (tr "workspace.options.selection-color")]]
[:div.element-set-content
[:div.selected-colors
(for [[index color] (d/enumerate (take 3 library-colors))]
[:& color-row {:key (dm/str "library-color-" index)
:color color
:index index
:on-detach on-detach
:select-only select-only
:on-change #(on-change % color)
:on-open on-open}])
(when (and (false? @expand-lib-color) (< 3 (count library-colors)))
[:div.expand-colors {:on-click #(reset! expand-lib-color true)}
[:span i/actions]
[:span.text (tr "workspace.options.more-lib-colors")]])
(when @expand-lib-color
(for [[index color] (d/enumerate (drop 3 library-colors))]
[:& color-row {:key (dm/str "library-color-" index)
:color color
:index index
:on-detach on-detach
:select-only select-only
:on-change #(on-change % color)
:on-open on-open}]))]
[:div.selected-colors
(for [[index color] (d/enumerate (take 3 colors))]
[:& color-row {:key (dm/str "color-" index)
:color color
:index index
:select-only select-only
:on-change #(on-change % color)
:on-open on-open}])
(when (and (false? @expand-color) (< 3 (count colors)))
[:div.expand-colors {:on-click #(reset! expand-color true)}
[:span i/actions]
[:span.text (tr "workspace.options.more-colors")]])
(when @expand-color
(for [[index color] (d/enumerate (drop 3 colors))]
[:& color-row {:key (dm/str "color-" index)
:color color
:index index
:select-only select-only
:on-change #(on-change % color)
:on-open on-open}]))]]])))
|
d8cf3948a6575ed32f0de8a19a69f4b93d77a9a9acf1c044f469afd05cbd847d | malcolmreynolds/GSLL | matrix-product-nonsquare.lisp | Regression test MATRIX - PRODUCT - NONSQUARE for GSLL , automatically generated
(in-package :gsl)
(LISP-UNIT:DEFINE-TEST MATRIX-PRODUCT-NONSQUARE
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST #2A((-1488.7347 959.9901) (774.94495 1312.0566)))
(MULTIPLE-VALUE-LIST
(LET ((M1
(MAKE-MARRAY 'SINGLE-FLOAT :INITIAL-CONTENTS
'((-34.5 8.24 3.29)
(-8.93 34.12 -6.15))))
(M2
(MAKE-MARRAY 'SINGLE-FLOAT :INITIAL-CONTENTS
'((49.27 -13.49) (32.5 42.73)
(-17.24 43.31)))))
(CL-ARRAY (MATRIX-PRODUCT M1 M2)))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST
#2A((-1488.7346d0 959.9901d0)
(774.9448999999998d0 1312.0567999999996d0)))
(MULTIPLE-VALUE-LIST
(LET ((M1
(MAKE-MARRAY 'DOUBLE-FLOAT :INITIAL-CONTENTS
'((-34.5d0 8.24d0 3.29d0)
(-8.93d0 34.12d0 -6.15d0))))
(M2
(MAKE-MARRAY 'DOUBLE-FLOAT :INITIAL-CONTENTS
'((49.27d0 -13.49d0)
(32.5d0 42.73d0)
(-17.24d0 43.31d0)))))
(CL-ARRAY (MATRIX-PRODUCT M1 M2)))))
#+fsbv
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST
#2A((#C(-1422.0259 2305.5098)
#C(-1744.0583 -1092.294))
(#C(-3459.892 1995.4918)
#C(-3290.4465 -801.0577))))
(MULTIPLE-VALUE-LIST
(LET ((M1
(MAKE-MARRAY '(COMPLEX SINGLE-FLOAT)
:INITIAL-CONTENTS
'((-34.5 8.24 3.29 -8.93 34.12
-6.15)
(-8.93 34.12 -6.15 49.27 -13.49
32.5))))
(M2
(MAKE-MARRAY '(COMPLEX SINGLE-FLOAT)
:INITIAL-CONTENTS
'((49.27 -13.49 32.5 42.73)
(32.5 42.73 -17.24 43.31)
(-17.24 43.31 -16.12 -8.25)))))
(CL-ARRAY (MATRIX-PRODUCT M1 M2)))))
#+fsbv
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST
#2A((#C(-1422.0258d0 2305.5097000000005d0)
#C(-1744.0584d0 -1092.2939d0))
(#C(-3459.8918d0 1995.4917d0)
#C(-3290.4465d0 -801.0577000000002d0))))
(MULTIPLE-VALUE-LIST
(LET ((M1
(MAKE-MARRAY '(COMPLEX DOUBLE-FLOAT)
:INITIAL-CONTENTS
'((-34.5d0 8.24d0 3.29d0 -8.93d0
34.12d0 -6.15d0)
(-8.93d0 34.12d0 -6.15d0 49.27d0
-13.49d0 32.5d0))))
(M2
(MAKE-MARRAY '(COMPLEX DOUBLE-FLOAT)
:INITIAL-CONTENTS
'((49.27d0 -13.49d0 32.5d0
42.73d0)
(32.5d0 42.73d0 -17.24d0
43.31d0)
(-17.24d0 43.31d0 -16.12d0
-8.25d0)))))
(CL-ARRAY (MATRIX-PRODUCT M1 M2))))))
| null | https://raw.githubusercontent.com/malcolmreynolds/GSLL/2f722f12f1d08e1b9550a46e2a22adba8e1e52c4/tests/matrix-product-nonsquare.lisp | lisp | Regression test MATRIX - PRODUCT - NONSQUARE for GSLL , automatically generated
(in-package :gsl)
(LISP-UNIT:DEFINE-TEST MATRIX-PRODUCT-NONSQUARE
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST #2A((-1488.7347 959.9901) (774.94495 1312.0566)))
(MULTIPLE-VALUE-LIST
(LET ((M1
(MAKE-MARRAY 'SINGLE-FLOAT :INITIAL-CONTENTS
'((-34.5 8.24 3.29)
(-8.93 34.12 -6.15))))
(M2
(MAKE-MARRAY 'SINGLE-FLOAT :INITIAL-CONTENTS
'((49.27 -13.49) (32.5 42.73)
(-17.24 43.31)))))
(CL-ARRAY (MATRIX-PRODUCT M1 M2)))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST
#2A((-1488.7346d0 959.9901d0)
(774.9448999999998d0 1312.0567999999996d0)))
(MULTIPLE-VALUE-LIST
(LET ((M1
(MAKE-MARRAY 'DOUBLE-FLOAT :INITIAL-CONTENTS
'((-34.5d0 8.24d0 3.29d0)
(-8.93d0 34.12d0 -6.15d0))))
(M2
(MAKE-MARRAY 'DOUBLE-FLOAT :INITIAL-CONTENTS
'((49.27d0 -13.49d0)
(32.5d0 42.73d0)
(-17.24d0 43.31d0)))))
(CL-ARRAY (MATRIX-PRODUCT M1 M2)))))
#+fsbv
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST
#2A((#C(-1422.0259 2305.5098)
#C(-1744.0583 -1092.294))
(#C(-3459.892 1995.4918)
#C(-3290.4465 -801.0577))))
(MULTIPLE-VALUE-LIST
(LET ((M1
(MAKE-MARRAY '(COMPLEX SINGLE-FLOAT)
:INITIAL-CONTENTS
'((-34.5 8.24 3.29 -8.93 34.12
-6.15)
(-8.93 34.12 -6.15 49.27 -13.49
32.5))))
(M2
(MAKE-MARRAY '(COMPLEX SINGLE-FLOAT)
:INITIAL-CONTENTS
'((49.27 -13.49 32.5 42.73)
(32.5 42.73 -17.24 43.31)
(-17.24 43.31 -16.12 -8.25)))))
(CL-ARRAY (MATRIX-PRODUCT M1 M2)))))
#+fsbv
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST
#2A((#C(-1422.0258d0 2305.5097000000005d0)
#C(-1744.0584d0 -1092.2939d0))
(#C(-3459.8918d0 1995.4917d0)
#C(-3290.4465d0 -801.0577000000002d0))))
(MULTIPLE-VALUE-LIST
(LET ((M1
(MAKE-MARRAY '(COMPLEX DOUBLE-FLOAT)
:INITIAL-CONTENTS
'((-34.5d0 8.24d0 3.29d0 -8.93d0
34.12d0 -6.15d0)
(-8.93d0 34.12d0 -6.15d0 49.27d0
-13.49d0 32.5d0))))
(M2
(MAKE-MARRAY '(COMPLEX DOUBLE-FLOAT)
:INITIAL-CONTENTS
'((49.27d0 -13.49d0 32.5d0
42.73d0)
(32.5d0 42.73d0 -17.24d0
43.31d0)
(-17.24d0 43.31d0 -16.12d0
-8.25d0)))))
(CL-ARRAY (MATRIX-PRODUCT M1 M2))))))
| |
b700538e163ebc3ddf44dae4d4d84256d922e4a31b82b8cb7170e431ce7e32a7 | ktakashi/sagittarius-scheme | test-ed25519.scm | (define ed25519-signer (make-eddsa-signer ed25519-scheme))
(define ed25519-verifier (make-eddsa-verifier ed25519-scheme))
(define test-ed25519 (make-test-eddsa Ed25519 ed25519-signer ed25519-verifier))
(test-ed25519
#x9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60
#xd75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a
#vu8()
#xe5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b)
(test-ed25519
#x4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb
#x3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c
#vu8(#x72)
#x92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00)
(test-ed25519
#xc5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7
#xfc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025
#vu8(#xaf #x82)
#x6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a)
(test-ed25519
#xf5e5767cf153319517630f226876b86c8160cc583bc013744c6bf255f5cc0ee5
#x278117fc144c72340f67d0f2316e8386ceffbf2b2428c9c51fef7c597f1d426e
(integer->bytevector
(string->number
"08b8b2b733424243760fe426a4b54908\
632110a66c2f6591eabd3345e3e4eb98\
fa6e264bf09efe12ee50f8f54e9f77b1\
e355f6c50544e23fb1433ddf73be84d8\
79de7c0046dc4996d9e773f4bc9efe57\
38829adb26c81b37c93a1b270b20329d\
658675fc6ea534e0810a4432826bf58c\
941efb65d57a338bbd2e26640f89ffbc\
1a858efcb8550ee3a5e1998bd177e93a\
7363c344fe6b199ee5d02e82d522c4fe\
ba15452f80288a821a579116ec6dad2b\
3b310da903401aa62100ab5d1a36553e\
06203b33890cc9b832f79ef80560ccb9\
a39ce767967ed628c6ad573cb116dbef\
efd75499da96bd68a8a97b928a8bbc10\
3b6621fcde2beca1231d206be6cd9ec7\
aff6f6c94fcd7204ed3455c68c83f4a4\
1da4af2b74ef5c53f1d8ac70bdcb7ed1\
85ce81bd84359d44254d95629e9855a9\
4a7c1958d1f8ada5d0532ed8a5aa3fb2\
d17ba70eb6248e594e1a2297acbbb39d\
502f1a8c6eb6f1ce22b3de1a1f40cc24\
554119a831a9aad6079cad88425de6bd\
e1a9187ebb6092cf67bf2b13fd65f270\
88d78b7e883c8759d2c4f5c65adb7553\
878ad575f9fad878e80a0c9ba63bcbcc\
2732e69485bbc9c90bfbd62481d9089b\
eccf80cfe2df16a2cf65bd92dd597b07\
07e0917af48bbb75fed413d238f5555a\
7a569d80c3414a8d0859dc65a46128ba\
b27af87a71314f318c782b23ebfe808b\
82b0ce26401d2e22f04d83d1255dc51a\
ddd3b75a2b1ae0784504df543af8969b\
e3ea7082ff7fc9888c144da2af58429e\
c96031dbcad3dad9af0dcbaaaf268cb8\
fcffead94f3c7ca495e056a9b47acdb7\
51fb73e666c6c655ade8297297d07ad1\
ba5e43f1bca32301651339e22904cc8c\
42f58c30c04aafdb038dda0847dd988d\
cda6f3bfd15c4b4c4525004aa06eeff8\
ca61783aacec57fb3d1f92b0fe2fd1a8\
5f6724517b65e614ad6808d6f6ee34df\
f7310fdc82aebfd904b01e1dc54b2927\
094b2db68d6f903b68401adebf5a7e08\
d78ff4ef5d63653a65040cf9bfd4aca7\
984a74d37145986780fc0b16ac451649\
de6188a7dbdf191f64b5fc5e2ab47b57\
f7f7276cd419c17a3ca8e1b939ae49e4\
88acba6b965610b5480109c8b17b80e1\
b7b750dfc7598d5d5011fd2dcc5600a3\
2ef5b52a1ecc820e308aa342721aac09\
43bf6686b64b2579376504ccc493d97e\
6aed3fb0f9cd71a43dd497f01f17c0e2\
cb3797aa2a2f256656168e6c496afc5f\
b93246f6b1116398a346f1a641f3b041\
e989f7914f90cc2c7fff357876e506b5\
0d334ba77c225bc307ba537152f3f161\
0e4eafe595f6d9d90d11faa933a15ef1\
369546868a7f3a45a96768d40fd9d034\
12c091c6315cf4fde7cb68606937380d\
b2eaaa707b4c4185c32eddcdd306705e\
4dc1ffc872eeee475a64dfac86aba41c\
0618983f8741c5ef68d3a101e8a3b8ca\
c60c905c15fc910840b94c00a0b9d0" 16))
#x0aab4c900501b3e24d7cdf4663326a3a87df5e4843b2cbdb67cbf6e460fec350aa5371b1508f9f4528ecea23c436d94b5e8fcd4f681e30a6ac00a9704a188a03)
(test-ed25519
#x833fe62409237b9d62ec77587520911e9a759cec1d19755b7da901b96dca3d42
#xec172b93ad5e563bf4932c70e1245034c35467ef2efd4d64ebf819683467e2bf
(integer->bytevector
#xddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f)
#xdc2a4459e7369633a52b1bf277839a00201009a3efbf3ecb69bea2186c26b58909351fc9ac90b3ecfdfbc7c66431e0303dca179c138ac17ad9bef1177331a704)
| null | https://raw.githubusercontent.com/ktakashi/sagittarius-scheme/d068f29df5fefaf23700c62f7be1a68c08864060/ext/crypto/tests/test-ed25519.scm | scheme | (define ed25519-signer (make-eddsa-signer ed25519-scheme))
(define ed25519-verifier (make-eddsa-verifier ed25519-scheme))
(define test-ed25519 (make-test-eddsa Ed25519 ed25519-signer ed25519-verifier))
(test-ed25519
#x9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60
#xd75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a
#vu8()
#xe5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b)
(test-ed25519
#x4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb
#x3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c
#vu8(#x72)
#x92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00)
(test-ed25519
#xc5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7
#xfc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025
#vu8(#xaf #x82)
#x6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a)
(test-ed25519
#xf5e5767cf153319517630f226876b86c8160cc583bc013744c6bf255f5cc0ee5
#x278117fc144c72340f67d0f2316e8386ceffbf2b2428c9c51fef7c597f1d426e
(integer->bytevector
(string->number
"08b8b2b733424243760fe426a4b54908\
632110a66c2f6591eabd3345e3e4eb98\
fa6e264bf09efe12ee50f8f54e9f77b1\
e355f6c50544e23fb1433ddf73be84d8\
79de7c0046dc4996d9e773f4bc9efe57\
38829adb26c81b37c93a1b270b20329d\
658675fc6ea534e0810a4432826bf58c\
941efb65d57a338bbd2e26640f89ffbc\
1a858efcb8550ee3a5e1998bd177e93a\
7363c344fe6b199ee5d02e82d522c4fe\
ba15452f80288a821a579116ec6dad2b\
3b310da903401aa62100ab5d1a36553e\
06203b33890cc9b832f79ef80560ccb9\
a39ce767967ed628c6ad573cb116dbef\
efd75499da96bd68a8a97b928a8bbc10\
3b6621fcde2beca1231d206be6cd9ec7\
aff6f6c94fcd7204ed3455c68c83f4a4\
1da4af2b74ef5c53f1d8ac70bdcb7ed1\
85ce81bd84359d44254d95629e9855a9\
4a7c1958d1f8ada5d0532ed8a5aa3fb2\
d17ba70eb6248e594e1a2297acbbb39d\
502f1a8c6eb6f1ce22b3de1a1f40cc24\
554119a831a9aad6079cad88425de6bd\
e1a9187ebb6092cf67bf2b13fd65f270\
88d78b7e883c8759d2c4f5c65adb7553\
878ad575f9fad878e80a0c9ba63bcbcc\
2732e69485bbc9c90bfbd62481d9089b\
eccf80cfe2df16a2cf65bd92dd597b07\
07e0917af48bbb75fed413d238f5555a\
7a569d80c3414a8d0859dc65a46128ba\
b27af87a71314f318c782b23ebfe808b\
82b0ce26401d2e22f04d83d1255dc51a\
ddd3b75a2b1ae0784504df543af8969b\
e3ea7082ff7fc9888c144da2af58429e\
c96031dbcad3dad9af0dcbaaaf268cb8\
fcffead94f3c7ca495e056a9b47acdb7\
51fb73e666c6c655ade8297297d07ad1\
ba5e43f1bca32301651339e22904cc8c\
42f58c30c04aafdb038dda0847dd988d\
cda6f3bfd15c4b4c4525004aa06eeff8\
ca61783aacec57fb3d1f92b0fe2fd1a8\
5f6724517b65e614ad6808d6f6ee34df\
f7310fdc82aebfd904b01e1dc54b2927\
094b2db68d6f903b68401adebf5a7e08\
d78ff4ef5d63653a65040cf9bfd4aca7\
984a74d37145986780fc0b16ac451649\
de6188a7dbdf191f64b5fc5e2ab47b57\
f7f7276cd419c17a3ca8e1b939ae49e4\
88acba6b965610b5480109c8b17b80e1\
b7b750dfc7598d5d5011fd2dcc5600a3\
2ef5b52a1ecc820e308aa342721aac09\
43bf6686b64b2579376504ccc493d97e\
6aed3fb0f9cd71a43dd497f01f17c0e2\
cb3797aa2a2f256656168e6c496afc5f\
b93246f6b1116398a346f1a641f3b041\
e989f7914f90cc2c7fff357876e506b5\
0d334ba77c225bc307ba537152f3f161\
0e4eafe595f6d9d90d11faa933a15ef1\
369546868a7f3a45a96768d40fd9d034\
12c091c6315cf4fde7cb68606937380d\
b2eaaa707b4c4185c32eddcdd306705e\
4dc1ffc872eeee475a64dfac86aba41c\
0618983f8741c5ef68d3a101e8a3b8ca\
c60c905c15fc910840b94c00a0b9d0" 16))
#x0aab4c900501b3e24d7cdf4663326a3a87df5e4843b2cbdb67cbf6e460fec350aa5371b1508f9f4528ecea23c436d94b5e8fcd4f681e30a6ac00a9704a188a03)
(test-ed25519
#x833fe62409237b9d62ec77587520911e9a759cec1d19755b7da901b96dca3d42
#xec172b93ad5e563bf4932c70e1245034c35467ef2efd4d64ebf819683467e2bf
(integer->bytevector
#xddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f)
#xdc2a4459e7369633a52b1bf277839a00201009a3efbf3ecb69bea2186c26b58909351fc9ac90b3ecfdfbc7c66431e0303dca179c138ac17ad9bef1177331a704)
| |
7ea0d1d387765c7ac06ee524d80b14a77715d339dfb2c151b581aebb20ecf840 | NetComposer/nksip | path_test_ua2.erl | %% -------------------------------------------------------------------
%%
%% path_test: Path (RFC3327) Tests
%%
Copyright ( c ) 2013 . All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
-module(path_test_ua2).
-include_lib("nkserver/include/nkserver_module.hrl").
-export([sip_invite/2, sip_options/2]).
sip_invite(Req, _Call) ->
case nksip_request:header(<<"x-nk-op">>, Req) of
{ok, [<<"ok">>]} -> {reply, ok};
{ok, _} -> {reply, 603}
end.
sip_options(Req, _Call) ->
{ok, Ids} = nksip_request:header(<<"x-nk-id">>, Req),
Hds = [{add, "x-nk-id", nklib_util:bjoin([?MODULE|Ids])}],
{reply, {ok, [contact|Hds]}}.
| null | https://raw.githubusercontent.com/NetComposer/nksip/7fbcc66806635dc8ecc5d11c30322e4d1df36f0a/test/callbacks/path_test_ua2.erl | erlang | -------------------------------------------------------------------
path_test: Path (RFC3327) Tests
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
------------------------------------------------------------------- | Copyright ( c ) 2013 . All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(path_test_ua2).
-include_lib("nkserver/include/nkserver_module.hrl").
-export([sip_invite/2, sip_options/2]).
sip_invite(Req, _Call) ->
case nksip_request:header(<<"x-nk-op">>, Req) of
{ok, [<<"ok">>]} -> {reply, ok};
{ok, _} -> {reply, 603}
end.
sip_options(Req, _Call) ->
{ok, Ids} = nksip_request:header(<<"x-nk-id">>, Req),
Hds = [{add, "x-nk-id", nklib_util:bjoin([?MODULE|Ids])}],
{reply, {ok, [contact|Hds]}}.
|
6071166dd5dd4ed8ff303c6dabc96013d87a9b05601672af60b3967f8ee155c0 | nebularis/systest | systest_hooks.erl | -*- tab - width : 4;erlang - indent - level : 4;indent - tabs - mode : nil -*-
%% ex: ts=4 sw=4 et
%% ----------------------------------------------------------------------------
%%
Copyright ( c ) 2005 - 2012 Nebularis .
%%
%% Permission is hereby granted, free of charge, to any person obtaining a copy
%% of this software and associated documentation files (the "Software"), deal
in the Software without restriction , including without limitation the rights
%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software , and to permit persons to whom the Software is
%% furnished to do so, subject to the following conditions:
%%
%% The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software .
%%
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
%% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
%% IN THE SOFTWARE.
%% ----------------------------------------------------------------------------
%% @hidden
%% ----------------------------------------------------------------------------
-module(systest_hooks).
-include("systest.hrl").
-export([run/3]).
-type arg() :: {'proc', atom()} |
{'call', module(), function(), [term()]} |
{'call_with_item', module(), function(), [term()]} |
{'call_with_context', module(), function(), [term()]} |
term().
-type systest_hook() :: {'eval', atom(), module(), function(), [arg()]} |
{'remote', atom(), module(), function(), [arg()]} |
{'local', module(), function(), [arg()]} |
{module(), function(), [term()]} |
string().
%% TODO: think about the return type for this...
-spec run(Item::term(), Hook::systest_hook(), Context::term()) -> any().
run(Item, Hook, Context) ->
try
run_it(Item, Hook, Context)
catch
_:Error ->
systest_log:log(framework,
"Hook ~p failed: ~p~n",
[Hook, Error]),
throw({hook_failed, Hook, Error})
end.
run_it(Item, {eval, Where, Mod, Func, Args}, Context) ->
Argv = lists:reverse(lists:foldl(fun proc_interact/2,
{Item, Context, []}, Args)),
run_it(Item, {Where, Mod, Func, Argv}, Context);
run_it(#proc{id=Node}, {Mod, Func, Args}, _) ->
rpc:call(Node, Mod, Func, Args);
run_it(_Context, {remote, Where, Mod, Func, Args}, _) ->
rpc:call(Where, Mod, Func, Args);
run_it(Context, {local, Mod, Func, Args}, _) ->
apply(Mod, Func, [Context|Args]);
run_it(NI=#proc{handler=Handler}, Inputs, HState) ->
Handler:handle_interaction(Inputs, NI, HState).
proc_interact({call, M, F, A}, {_Item, _Context, Acc}) ->
[apply(M, F, A)|Acc];
proc_interact({call_with_item, M, F, A}, {Item, _Context, Acc}) ->
[apply(M, F, [Item|A])|Acc];
proc_interact({call_with_context, M, F, A}, {Item, Context, Acc}) ->
[apply(M, F, [Item, Context|A])|Acc];
proc_interact({proc, Field}, {Item, _Context, Acc}) ->
[systest_proc:get(Field, Item)|Acc];
proc_interact(Term, {_, _, Acc}) ->
[Term|Acc].
| null | https://raw.githubusercontent.com/nebularis/systest/fbef181fd0203137f9f6ca6a471c75ca180ec375/src/systest_hooks.erl | erlang | ex: ts=4 sw=4 et
----------------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), deal
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
----------------------------------------------------------------------------
@hidden
----------------------------------------------------------------------------
TODO: think about the return type for this... | -*- tab - width : 4;erlang - indent - level : 4;indent - tabs - mode : nil -*-
Copyright ( c ) 2005 - 2012 Nebularis .
in the Software without restriction , including without limitation the rights
copies of the Software , and to permit persons to whom the Software is
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
-module(systest_hooks).
-include("systest.hrl").
-export([run/3]).
-type arg() :: {'proc', atom()} |
{'call', module(), function(), [term()]} |
{'call_with_item', module(), function(), [term()]} |
{'call_with_context', module(), function(), [term()]} |
term().
-type systest_hook() :: {'eval', atom(), module(), function(), [arg()]} |
{'remote', atom(), module(), function(), [arg()]} |
{'local', module(), function(), [arg()]} |
{module(), function(), [term()]} |
string().
-spec run(Item::term(), Hook::systest_hook(), Context::term()) -> any().
run(Item, Hook, Context) ->
try
run_it(Item, Hook, Context)
catch
_:Error ->
systest_log:log(framework,
"Hook ~p failed: ~p~n",
[Hook, Error]),
throw({hook_failed, Hook, Error})
end.
run_it(Item, {eval, Where, Mod, Func, Args}, Context) ->
Argv = lists:reverse(lists:foldl(fun proc_interact/2,
{Item, Context, []}, Args)),
run_it(Item, {Where, Mod, Func, Argv}, Context);
run_it(#proc{id=Node}, {Mod, Func, Args}, _) ->
rpc:call(Node, Mod, Func, Args);
run_it(_Context, {remote, Where, Mod, Func, Args}, _) ->
rpc:call(Where, Mod, Func, Args);
run_it(Context, {local, Mod, Func, Args}, _) ->
apply(Mod, Func, [Context|Args]);
run_it(NI=#proc{handler=Handler}, Inputs, HState) ->
Handler:handle_interaction(Inputs, NI, HState).
proc_interact({call, M, F, A}, {_Item, _Context, Acc}) ->
[apply(M, F, A)|Acc];
proc_interact({call_with_item, M, F, A}, {Item, _Context, Acc}) ->
[apply(M, F, [Item|A])|Acc];
proc_interact({call_with_context, M, F, A}, {Item, Context, Acc}) ->
[apply(M, F, [Item, Context|A])|Acc];
proc_interact({proc, Field}, {Item, _Context, Acc}) ->
[systest_proc:get(Field, Item)|Acc];
proc_interact(Term, {_, _, Acc}) ->
[Term|Acc].
|
81693b160ffad4a72217aafb4137c7b083b88d521619687477102876a56fc9f5 | alexandergunnarson/quantum | core.cljc | (ns
^{:doc "Some useful macros, like de-repetitivizing protocol extensions.
Also some plumbing macros for `for` loops and the like."
:attribution "alexandergunnarson"}
quantum.core.type.core
(:refer-clojure :exclude
[class])
(:require
[quantum.untyped.core.type.core :as u]
[quantum.untyped.core.vars
:refer [defaliases]]))
(defaliases u
class boxed-type-map
#?@(:clj [boxed->unboxed unboxed->boxed unboxed->convertible
convertible? unboxed-type-map])
prim-types prim-types|unevaled prim|unevaled?
primitive-types primitive-types|unevaled primitive|unevaled?
primitive-boxed-types primitive-boxed-types|unevaled
auto-unboxable|unevaled?
most-primitive-class-of
;;
primitive-array-types
cljs-typed-array-convertible-classes
java-array-type-regex
#?@(:clj [nth-elem-type|clj primitive-array-type?])
default-types type-casts-map return-types-map
->boxed|sym ->unboxed|sym boxed?|sym
#?@(:clj [class>prim-subclasses]))
| null | https://raw.githubusercontent.com/alexandergunnarson/quantum/0c655af439734709566110949f9f2f482e468509/src/quantum/core/type/core.cljc | clojure | (ns
^{:doc "Some useful macros, like de-repetitivizing protocol extensions.
Also some plumbing macros for `for` loops and the like."
:attribution "alexandergunnarson"}
quantum.core.type.core
(:refer-clojure :exclude
[class])
(:require
[quantum.untyped.core.type.core :as u]
[quantum.untyped.core.vars
:refer [defaliases]]))
(defaliases u
class boxed-type-map
#?@(:clj [boxed->unboxed unboxed->boxed unboxed->convertible
convertible? unboxed-type-map])
prim-types prim-types|unevaled prim|unevaled?
primitive-types primitive-types|unevaled primitive|unevaled?
primitive-boxed-types primitive-boxed-types|unevaled
auto-unboxable|unevaled?
most-primitive-class-of
primitive-array-types
cljs-typed-array-convertible-classes
java-array-type-regex
#?@(:clj [nth-elem-type|clj primitive-array-type?])
default-types type-casts-map return-types-map
->boxed|sym ->unboxed|sym boxed?|sym
#?@(:clj [class>prim-subclasses]))
| |
ccbba041704bbeee2e1f51d7f10d91ace370d078117cb988819a9bf33902dda4 | exoscale/collmann | project.clj | (defproject io.exo/collmann "0.1.0"
:description "riemann events for collectd"
:url ""
:license {:name "MIT"
:url ""}
:aot :all
:dependencies [[org.clojure/clojure "1.5.1"]
[org.clojure/tools.logging "0.2.6"]
[org.collectd/plugin-api "5.4.0"]
[riemann "0.2.2"]
[log4j/log4j "1.2.16" :exclusions [javax.mail/mail
javax.jms/jms
com.sun.jdmk/jmxtools
com.sun.jmx/jmxri]]])
| null | https://raw.githubusercontent.com/exoscale/collmann/e786a6e65b4a446c0f4380152b10f6ec52d20304/project.clj | clojure | (defproject io.exo/collmann "0.1.0"
:description "riemann events for collectd"
:url ""
:license {:name "MIT"
:url ""}
:aot :all
:dependencies [[org.clojure/clojure "1.5.1"]
[org.clojure/tools.logging "0.2.6"]
[org.collectd/plugin-api "5.4.0"]
[riemann "0.2.2"]
[log4j/log4j "1.2.16" :exclusions [javax.mail/mail
javax.jms/jms
com.sun.jdmk/jmxtools
com.sun.jmx/jmxri]]])
| |
9372d9d1d08d66713975f9e030edff4f49b051ca46ad94b1f9ffa135ca849b63 | CRogers/obc | stack.ml |
* Oxford Oberon-2 compiler
* stack.ml
* Copyright ( C ) 1995 , 1998
* Oxford Oberon-2 compiler
* stack.ml
* Copyright (C) J. M. Spivey 1995, 1998
*)
open Icode
open Symtab
open Print
open Dict
let rcsid = "$Id: stack.ml 1678 2011-03-15 20:27:21Z mike $"
We keep a stack of Booleans , each indicating whether an item on the
evaluation stack at runtime is a pointer or not .
evaluation stack at runtime is a pointer or not. *)
let stk = ref []
let maxd = ref 0
let labstate = Hashtbl.create 100
let push_stack flag s = flag :: s
let rec pop_stack r s = Util.drop r s
let rec nth_stack s r = List.nth s r
let arity =
let f = false and t = true in
function
ERROR (_, _) | STKMAP _ -> (0, [])
| CONST _ | TCONST (FloatT, _) -> (0, [f])
| TCONST ((DoubleT|LongT), _) -> (0, [f; f])
| (LOCAL _ | GLOBAL _) -> (0, [f])
| LOAD (LongT|DoubleT) -> (1, [f; f]) | LOAD _ -> (1, [f])
| CHECK (NullPtr, _) -> (1, [t])
| ALIGN _ -> (1, [f])
| BOUND _ | EASSERT _ -> (1, [])
| POP n -> (n, [])
| STORE (LongT|DoubleT) -> (3, []) | STORE _ -> (2, [])
| FLEXCOPY -> (2, []) | FIXCOPY -> (3, [])
| RETURN VoidT -> (0, [])
| RETURN (DoubleT|LongT) -> (2, [])
| RETURN _ -> (1, [])
| TYPETEST _ -> (2, [f])
| NOP -> (0, [])
| CALL (n, VoidT) -> (n+1, [])
| CALL (n, (DoubleT|LongT)) -> (n+1, [f; f])
| CALL (n, _) -> (n+1, [f])
| (CHECK (GlobProc, _) | LINK) -> (1, [])
| SAVELINK -> (0, [])
| MONOP ((DoubleT|LongT), _) -> (2, [f; f])
| CHECK (DivZero (DoubleT|LongT), _) -> (2, [f; f])
| (MONOP (_, _) | CHECK (DivZero _, _)) -> (1, [f])
| BINOP ((DoubleT|LongT), (Eq|Lt|Gt|Leq|Geq|Neq)) -> (4, [f])
| BINOP ((DoubleT|LongT), _) -> (4, [f; f])
| BINOP (PtrT, _) -> (2, [t])
| BINOP (_, _) -> (2, [f])
| CONV ((DoubleT|LongT), (DoubleT|LongT)) -> (2, [f; f])
| CONV ((DoubleT|LongT), _) -> (2, [f])
| CONV (_, (DoubleT|LongT)) -> (1, [f; f])
| CONV (_, _) -> (1, [f])
| _ -> raise Not_found
let simulate i =
begin match i with
JUMP lab ->
Hashtbl.add labstate lab !stk
| DUP n ->
stk := push_stack (nth_stack !stk n) !stk
| JUMPB (_, lab) ->
let s = pop_stack 1 !stk in
Hashtbl.add labstate lab s; stk := s
| JUMPC (_, _, lab) ->
let s = pop_stack 2 !stk in
Hashtbl.add labstate lab s; stk := s
| SWAP ->
stk := push_stack (nth_stack !stk 1) (push_stack (nth_stack !stk 0)
(pop_stack 2 !stk))
| LABEL lab ->
(* This assumes that a label immediately following an unconditional
branch is the target of some other forward branch. *)
(try stk := Hashtbl.find labstate lab with Not_found -> ())
| _ ->
(try
let (k, xs) = arity i in
stk := List.fold_right push_stack xs (pop_stack k !stk)
with Not_found ->
failwith (sprintf "stack_sim $" [fInst i]))
end;
maxd := max !maxd (List.length !stk)
let reset () =
Hashtbl.clear labstate; stk := []
let pop n =
stk := pop_stack n !stk
let mark () =
stk := push_stack true (pop_stack 1 !stk)
The stack map for a procedure call shows the pointer layout of the
eval stack of the calling procedure . It 's based at ( bp+HEAD+args ) ,
the address of the stack word just beyond the parameters of the
callee . Thus the stack map will be zero except in the rare case that
extra pointers stay on the stack of the caller throughout execution of
the callee .
When make_map is called , the n parameters ( maybe including a static
link ) and the code address of the callee are on the simulated stack ;
so we drop n+1 stack items before computing the map .
eval stack of the calling procedure. It's based at (bp+HEAD+args),
the address of the stack word just beyond the parameters of the
callee. Thus the stack map will be zero except in the rare case that
extra pointers stay on the stack of the caller throughout execution of
the callee.
When make_map is called, the n parameters (maybe including a static
link) and the code address of the callee are on the simulated stack;
so we drop n+1 stack items before computing the map. *)
let make_map n =
let rec loop i =
function
[] -> []
| k::ks ->
let m = loop (i+1) ks in
if k then GC_Offset (4*i) :: m else m in
loop 0 (pop_stack (n+1) !stk)
let max_depth () = !maxd
let fStack =
let f prf =
let n = List.length !stk in
for i = 0 to n-1 do
prf "$" [fChr (if nth_stack !stk i then 't' else 'f')]
done in
fExt f
| null | https://raw.githubusercontent.com/CRogers/obc/49064db244e0c9d2ec2a83420c8d0ee917b54196/compiler/stack.ml | ocaml | This assumes that a label immediately following an unconditional
branch is the target of some other forward branch. |
* Oxford Oberon-2 compiler
* stack.ml
* Copyright ( C ) 1995 , 1998
* Oxford Oberon-2 compiler
* stack.ml
* Copyright (C) J. M. Spivey 1995, 1998
*)
open Icode
open Symtab
open Print
open Dict
let rcsid = "$Id: stack.ml 1678 2011-03-15 20:27:21Z mike $"
We keep a stack of Booleans , each indicating whether an item on the
evaluation stack at runtime is a pointer or not .
evaluation stack at runtime is a pointer or not. *)
let stk = ref []
let maxd = ref 0
let labstate = Hashtbl.create 100
let push_stack flag s = flag :: s
let rec pop_stack r s = Util.drop r s
let rec nth_stack s r = List.nth s r
let arity =
let f = false and t = true in
function
ERROR (_, _) | STKMAP _ -> (0, [])
| CONST _ | TCONST (FloatT, _) -> (0, [f])
| TCONST ((DoubleT|LongT), _) -> (0, [f; f])
| (LOCAL _ | GLOBAL _) -> (0, [f])
| LOAD (LongT|DoubleT) -> (1, [f; f]) | LOAD _ -> (1, [f])
| CHECK (NullPtr, _) -> (1, [t])
| ALIGN _ -> (1, [f])
| BOUND _ | EASSERT _ -> (1, [])
| POP n -> (n, [])
| STORE (LongT|DoubleT) -> (3, []) | STORE _ -> (2, [])
| FLEXCOPY -> (2, []) | FIXCOPY -> (3, [])
| RETURN VoidT -> (0, [])
| RETURN (DoubleT|LongT) -> (2, [])
| RETURN _ -> (1, [])
| TYPETEST _ -> (2, [f])
| NOP -> (0, [])
| CALL (n, VoidT) -> (n+1, [])
| CALL (n, (DoubleT|LongT)) -> (n+1, [f; f])
| CALL (n, _) -> (n+1, [f])
| (CHECK (GlobProc, _) | LINK) -> (1, [])
| SAVELINK -> (0, [])
| MONOP ((DoubleT|LongT), _) -> (2, [f; f])
| CHECK (DivZero (DoubleT|LongT), _) -> (2, [f; f])
| (MONOP (_, _) | CHECK (DivZero _, _)) -> (1, [f])
| BINOP ((DoubleT|LongT), (Eq|Lt|Gt|Leq|Geq|Neq)) -> (4, [f])
| BINOP ((DoubleT|LongT), _) -> (4, [f; f])
| BINOP (PtrT, _) -> (2, [t])
| BINOP (_, _) -> (2, [f])
| CONV ((DoubleT|LongT), (DoubleT|LongT)) -> (2, [f; f])
| CONV ((DoubleT|LongT), _) -> (2, [f])
| CONV (_, (DoubleT|LongT)) -> (1, [f; f])
| CONV (_, _) -> (1, [f])
| _ -> raise Not_found
let simulate i =
begin match i with
JUMP lab ->
Hashtbl.add labstate lab !stk
| DUP n ->
stk := push_stack (nth_stack !stk n) !stk
| JUMPB (_, lab) ->
let s = pop_stack 1 !stk in
Hashtbl.add labstate lab s; stk := s
| JUMPC (_, _, lab) ->
let s = pop_stack 2 !stk in
Hashtbl.add labstate lab s; stk := s
| SWAP ->
stk := push_stack (nth_stack !stk 1) (push_stack (nth_stack !stk 0)
(pop_stack 2 !stk))
| LABEL lab ->
(try stk := Hashtbl.find labstate lab with Not_found -> ())
| _ ->
(try
let (k, xs) = arity i in
stk := List.fold_right push_stack xs (pop_stack k !stk)
with Not_found ->
failwith (sprintf "stack_sim $" [fInst i]))
end;
maxd := max !maxd (List.length !stk)
let reset () =
Hashtbl.clear labstate; stk := []
let pop n =
stk := pop_stack n !stk
let mark () =
stk := push_stack true (pop_stack 1 !stk)
The stack map for a procedure call shows the pointer layout of the
eval stack of the calling procedure . It 's based at ( bp+HEAD+args ) ,
the address of the stack word just beyond the parameters of the
callee . Thus the stack map will be zero except in the rare case that
extra pointers stay on the stack of the caller throughout execution of
the callee .
When make_map is called , the n parameters ( maybe including a static
link ) and the code address of the callee are on the simulated stack ;
so we drop n+1 stack items before computing the map .
eval stack of the calling procedure. It's based at (bp+HEAD+args),
the address of the stack word just beyond the parameters of the
callee. Thus the stack map will be zero except in the rare case that
extra pointers stay on the stack of the caller throughout execution of
the callee.
When make_map is called, the n parameters (maybe including a static
link) and the code address of the callee are on the simulated stack;
so we drop n+1 stack items before computing the map. *)
let make_map n =
let rec loop i =
function
[] -> []
| k::ks ->
let m = loop (i+1) ks in
if k then GC_Offset (4*i) :: m else m in
loop 0 (pop_stack (n+1) !stk)
let max_depth () = !maxd
let fStack =
let f prf =
let n = List.length !stk in
for i = 0 to n-1 do
prf "$" [fChr (if nth_stack !stk i then 't' else 'f')]
done in
fExt f
|
77279ed1c3fb1a029880c574010d69eebb9daab941bb9603e650e21c941492a2 | ygrek/mldonkey | donkeyStats.ml | Copyright 2001 , 2002 b8_bavard , b8_fee_carabine ,
This file is part of mldonkey .
mldonkey 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 .
mldonkey 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 mldonkey ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This file is part of mldonkey.
mldonkey 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.
mldonkey 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 mldonkey; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Int64ops
open Printf2
open Options
open CommonTypes
open CommonOptions
open CommonNetwork
open CommonStats
open DonkeyTypes
open DonkeyGlobals
open DonkeyComplexOptions
let start_session = ref (BasicSocket.last_time ())
let stats_array = Array.init brand_count (fun _ ->
{ dummy_stats with brand_seen = 0 }
)
let stats_mod_array = Array.init brand_mod_count (fun _ ->
{ dummy_stats with brand_seen = 0 }
)
let count_seen c =
let i = brand_to_int c.client_brand in
stats_array.(i).brand_seen <- stats_array.(i).brand_seen + 1;
!!gstats_array.(i).brand_seen <- !!gstats_array.(i).brand_seen + 1;
check_client_country_code c;
CommonStats.country_seen c.client_country_code;
if !!emule_mods_count then begin
let i = brand_mod_to_int c.client_brand_mod in
stats_mod_array.(i).brand_seen <- stats_mod_array.(i).brand_seen + 1;
!!gstats_mod_array.(i).brand_seen <- !!gstats_mod_array.(i).brand_seen + 1
end
let count_banned c =
let i = brand_to_int c.client_brand in
stats_array.(i).brand_banned <- stats_array.(i).brand_banned + 1;
!!gstats_array.(i).brand_banned <- !!gstats_array.(i).brand_banned + 1;
if !!emule_mods_count then begin
let i = brand_mod_to_int c.client_brand_mod in
stats_mod_array.(i).brand_banned <- stats_mod_array.(i).brand_banned + 1;
!!gstats_mod_array.(i).brand_banned <- !!gstats_mod_array.(i).brand_banned + 1
end
let count_filerequest c =
let i = brand_to_int c.client_brand in
stats_array.(i).brand_filerequest <- stats_array.(i).brand_filerequest + 1;
!!gstats_array.(i).brand_filerequest <- !!gstats_array.(i).brand_filerequest + 1;
if !!emule_mods_count then begin
let i = brand_mod_to_int c.client_brand_mod in
stats_mod_array.(i).brand_filerequest <- stats_mod_array.(i).brand_filerequest + 1;
!!gstats_mod_array.(i).brand_filerequest <- !!gstats_mod_array.(i).brand_filerequest + 1
end
let count_download c v =
let i = brand_to_int c.client_brand in
stats_array.(i).brand_download <- stats_array.(i).brand_download ++ v;
!!gstats_array.(i).brand_download <- !!gstats_array.(i).brand_download ++ v;
if !!emule_mods_count then begin
let i = brand_mod_to_int c.client_brand_mod in
stats_mod_array.(i).brand_download <- stats_mod_array.(i).brand_download ++ v;
!!gstats_mod_array.(i).brand_download <- !!gstats_mod_array.(i).brand_download ++ v;
end;
c.client_total_downloaded <- c.client_total_downloaded ++ v;
c.client_session_downloaded <- c.client_session_downloaded ++ v;
donkey_download_counter := !donkey_download_counter ++ v;
check_client_country_code c;
global_count_download network c.client_country_code v
let count_upload c v =
let i = brand_to_int c.client_brand in
stats_array.(i).brand_upload <- stats_array.(i).brand_upload ++ v;
!!gstats_array.(i).brand_upload <- !!gstats_array.(i).brand_upload ++ v;
if !!emule_mods_count then begin
let i = brand_mod_to_int c.client_brand_mod in
stats_mod_array.(i).brand_upload <- stats_mod_array.(i).brand_upload ++ v;
!!gstats_mod_array.(i).brand_upload <- !!gstats_mod_array.(i).brand_upload ++ v;
end;
c.client_total_uploaded <- c.client_total_uploaded ++ v;
c.client_session_uploaded <- c.client_session_uploaded ++ v;
donkey_upload_counter := !donkey_upload_counter ++ v;
check_client_country_code c;
global_count_upload network c.client_country_code v
let print_stats_mods o style =
let buf = o.conn_buf in
let u1 = BasicSocket.last_time () - !start_session in
let u2 = (guptime() + u1) in
let t1 = build_title "eMule Mods" "Session" u1 in
let t2 = build_title "eMule Mods" "Total" u2 in
let l = brand_mod_list in
match style with
| Old -> print_stats_old buf stats_mod_array l t1 u1
| _ ->
if !!emule_mods_count then begin
if use_html_mods o then begin
print_stats_html_mods buf stats_mod_array l t1 u1;
print_stats_html_mods buf !!gstats_mod_array l t2 u2
end else begin
print_stats_ascii buf stats_mod_array l t1 u1;
print_stats_ascii buf !!gstats_mod_array l t2 u2
end
end else
begin
if use_html_mods o then begin
Printf.bprintf buf "\\<div class=\\\"cs\\\"\\>";
html_mods_table_header buf "emodsTable" "cs" [];
Printf.bprintf buf "\\<tr class=\\\"dl-1\\\"\\>";
html_mods_td buf [
("", "sr", "eMule mods statistics are disabled, to activate set emule_mods_count true in the \\<a href=\\\"/submit?q=voo+8\\\"\\>misc options\\</a\\> tab." );
];
Printf.bprintf buf "\\</tr\\>\\</table\\>\\</div\\>\\</div\\>\n"
end else
Printf.bprintf buf "eMule mods statistics are disabled, to activate set emule_mods_count true \n"
end
let print_stats o style mods =
let buf = o.conn_buf in
let u1 = BasicSocket.last_time () - !start_session in
let u2 = (guptime() + u1) in
let t1 = build_title "eDonkey" "Session" u1 in
let t2 = build_title "eDonkey" "Total" u2 in
let l = brand_list in
if mods then print_stats_mods o style else
match style with
| Old -> print_stats_old buf stats_array l t1 u1
| _ ->
if use_html_mods o then begin
print_stats_html_mods buf stats_array l t1 u1;
print_stats_html_mods buf !!gstats_array l t2 u2
end else begin
print_stats_ascii buf stats_array l t1 u1;
print_stats_ascii buf !!gstats_array l t2 u2
end
let _ =
network.op_network_display_stats <- (fun o -> print_stats o New false);
network.op_network_stat_info_list <- (fun _ ->
let r = ref [] in
let l1 = stats_list brand_list stats_array in
let l2 = stats_list brand_list !!gstats_array in
let u1 = BasicSocket.last_time () - !start_session in
let u2 = (guptime() + u1) in
r := [("Session clients", u1, l1); ("Global clients", u2, l2)];
if !!emule_mods_count then begin
let l3 = stats_list brand_mod_list stats_mod_array in
let l4 = stats_list brand_mod_list !!gstats_mod_array in
r := !r @ [ ("Session mods", u1, l3); ("Global mods", u2, l4)]
end;
!r
);
register_commands
[
"client_stats", "Network/Donkey",Arg_none (fun o ->
print_stats o Old false;
""
), ":\t\t\t\tshow breakdown of download/upload by clients brand";
"cs", "Network/Donkey",Arg_none (fun o ->
print_stats o New false;
""
), ":\t\t\t\t\tshow table of download/upload by ED2K clients brand";
"csm", "Network/Donkey",Arg_none (fun o ->
print_stats o New true;
""
), ":\t\t\t\t\tshow table of download/upload by eMule MODs";
"reset_stats", "Network/Donkey",Arg_none (fun o ->
Array.iteri (fun x _ ->
stats_array.(x).brand_seen <- 0;
stats_array.(x).brand_banned <- 0;
stats_array.(x).brand_filerequest <- 0;
stats_array.(x).brand_download <- 0L;
stats_array.(x).brand_upload <- 0L;
) stats_array;
Array.iteri (fun x _ ->
stats_mod_array.(x).brand_seen <- 0;
stats_mod_array.(x).brand_banned <- 0;
stats_mod_array.(x).brand_filerequest <- 0;
stats_mod_array.(x).brand_download <- Int64.zero;
stats_mod_array.(x).brand_upload <- Int64.zero
) stats_mod_array;
start_session := BasicSocket.last_time ();
"done"
), ":\t\t\t\treset session statistics";
]
let save_download_history file =
let buf = Buffer.create 100 in
( * Some opcode for edonkey downloads
let save_download_history file =
let buf = Buffer.create 100 in
(* Some opcode for edonkey downloads *)
buf_int8 buf 153; (* opcode = stats *)
client md4 , and NOT IP
let time = Unix.time () in
let time = Unix.localtime time in
date on 5 bytes
buf_int8 buf time.Unix.tm_hour;
buf_int8 buf time.Unix.tm_mday;
buf_int8 buf time.Unix.tm_mon;
buf_int16 buf time.Unix.tm_year;
(* ANONYMISED Informations on the downloads: *)
Send the hash of the MD4+size , so that they can not be recovered ,
but they can be used to compare downloads .
but they can be used to compare downloads. *)
let m = Printf.sprintf "%s%Ld"
(Md4.Md4.direct_to_string file.file_md4) (file_size file) in
compute of the string
SENT : 20 bytes
Buffer.add_string buf (Md4.Sha1.direct_to_string m);
Send the magnitude of the size ( power of 10 )
let size = ref (file_size file) in
let m = ref 0 in
while !size <> Int64.zero do
incr m;
size := !size // 10L
done;
SENT : 1 byte
buf_int8 buf !m;
let current = ref [] in
Intmap.iter (fun _ c ->
let location =
match c.client_kind with
Indirect_location (name, md4) ->
Printf.sprintf "%s%s" name
(Md4.Md4.direct_to_string md4)
| Known_location (ip,port) ->
Printf.sprintf "%s%d"
(Ip.to_string ip) port
in
ANONYMISATION of the source : we compute the Sha1 digest of the source ,
which can not be recovered from this information
which cannot be recovered from this information *)
compute of the string
current := location :: !current;
) file.file_locations;
buf_list (fun buf s ->
Buffer.add_string buf (Md4.Sha1.direct_to_string s)
) buf !current;
let file_history = "downloads.stats" in
let oc = append_out file_history in
output_string oc (Buffer.contents buf);
close_out oc
*)
| null | https://raw.githubusercontent.com/ygrek/mldonkey/333868a12bb6cd25fed49391dd2c3a767741cb51/src/networks/donkey/donkeyStats.ml | ocaml | Some opcode for edonkey downloads
opcode = stats
ANONYMISED Informations on the downloads: | Copyright 2001 , 2002 b8_bavard , b8_fee_carabine ,
This file is part of mldonkey .
mldonkey 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 .
mldonkey 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 mldonkey ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This file is part of mldonkey.
mldonkey 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.
mldonkey 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 mldonkey; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Int64ops
open Printf2
open Options
open CommonTypes
open CommonOptions
open CommonNetwork
open CommonStats
open DonkeyTypes
open DonkeyGlobals
open DonkeyComplexOptions
let start_session = ref (BasicSocket.last_time ())
let stats_array = Array.init brand_count (fun _ ->
{ dummy_stats with brand_seen = 0 }
)
let stats_mod_array = Array.init brand_mod_count (fun _ ->
{ dummy_stats with brand_seen = 0 }
)
let count_seen c =
let i = brand_to_int c.client_brand in
stats_array.(i).brand_seen <- stats_array.(i).brand_seen + 1;
!!gstats_array.(i).brand_seen <- !!gstats_array.(i).brand_seen + 1;
check_client_country_code c;
CommonStats.country_seen c.client_country_code;
if !!emule_mods_count then begin
let i = brand_mod_to_int c.client_brand_mod in
stats_mod_array.(i).brand_seen <- stats_mod_array.(i).brand_seen + 1;
!!gstats_mod_array.(i).brand_seen <- !!gstats_mod_array.(i).brand_seen + 1
end
let count_banned c =
let i = brand_to_int c.client_brand in
stats_array.(i).brand_banned <- stats_array.(i).brand_banned + 1;
!!gstats_array.(i).brand_banned <- !!gstats_array.(i).brand_banned + 1;
if !!emule_mods_count then begin
let i = brand_mod_to_int c.client_brand_mod in
stats_mod_array.(i).brand_banned <- stats_mod_array.(i).brand_banned + 1;
!!gstats_mod_array.(i).brand_banned <- !!gstats_mod_array.(i).brand_banned + 1
end
let count_filerequest c =
let i = brand_to_int c.client_brand in
stats_array.(i).brand_filerequest <- stats_array.(i).brand_filerequest + 1;
!!gstats_array.(i).brand_filerequest <- !!gstats_array.(i).brand_filerequest + 1;
if !!emule_mods_count then begin
let i = brand_mod_to_int c.client_brand_mod in
stats_mod_array.(i).brand_filerequest <- stats_mod_array.(i).brand_filerequest + 1;
!!gstats_mod_array.(i).brand_filerequest <- !!gstats_mod_array.(i).brand_filerequest + 1
end
let count_download c v =
let i = brand_to_int c.client_brand in
stats_array.(i).brand_download <- stats_array.(i).brand_download ++ v;
!!gstats_array.(i).brand_download <- !!gstats_array.(i).brand_download ++ v;
if !!emule_mods_count then begin
let i = brand_mod_to_int c.client_brand_mod in
stats_mod_array.(i).brand_download <- stats_mod_array.(i).brand_download ++ v;
!!gstats_mod_array.(i).brand_download <- !!gstats_mod_array.(i).brand_download ++ v;
end;
c.client_total_downloaded <- c.client_total_downloaded ++ v;
c.client_session_downloaded <- c.client_session_downloaded ++ v;
donkey_download_counter := !donkey_download_counter ++ v;
check_client_country_code c;
global_count_download network c.client_country_code v
let count_upload c v =
let i = brand_to_int c.client_brand in
stats_array.(i).brand_upload <- stats_array.(i).brand_upload ++ v;
!!gstats_array.(i).brand_upload <- !!gstats_array.(i).brand_upload ++ v;
if !!emule_mods_count then begin
let i = brand_mod_to_int c.client_brand_mod in
stats_mod_array.(i).brand_upload <- stats_mod_array.(i).brand_upload ++ v;
!!gstats_mod_array.(i).brand_upload <- !!gstats_mod_array.(i).brand_upload ++ v;
end;
c.client_total_uploaded <- c.client_total_uploaded ++ v;
c.client_session_uploaded <- c.client_session_uploaded ++ v;
donkey_upload_counter := !donkey_upload_counter ++ v;
check_client_country_code c;
global_count_upload network c.client_country_code v
let print_stats_mods o style =
let buf = o.conn_buf in
let u1 = BasicSocket.last_time () - !start_session in
let u2 = (guptime() + u1) in
let t1 = build_title "eMule Mods" "Session" u1 in
let t2 = build_title "eMule Mods" "Total" u2 in
let l = brand_mod_list in
match style with
| Old -> print_stats_old buf stats_mod_array l t1 u1
| _ ->
if !!emule_mods_count then begin
if use_html_mods o then begin
print_stats_html_mods buf stats_mod_array l t1 u1;
print_stats_html_mods buf !!gstats_mod_array l t2 u2
end else begin
print_stats_ascii buf stats_mod_array l t1 u1;
print_stats_ascii buf !!gstats_mod_array l t2 u2
end
end else
begin
if use_html_mods o then begin
Printf.bprintf buf "\\<div class=\\\"cs\\\"\\>";
html_mods_table_header buf "emodsTable" "cs" [];
Printf.bprintf buf "\\<tr class=\\\"dl-1\\\"\\>";
html_mods_td buf [
("", "sr", "eMule mods statistics are disabled, to activate set emule_mods_count true in the \\<a href=\\\"/submit?q=voo+8\\\"\\>misc options\\</a\\> tab." );
];
Printf.bprintf buf "\\</tr\\>\\</table\\>\\</div\\>\\</div\\>\n"
end else
Printf.bprintf buf "eMule mods statistics are disabled, to activate set emule_mods_count true \n"
end
let print_stats o style mods =
let buf = o.conn_buf in
let u1 = BasicSocket.last_time () - !start_session in
let u2 = (guptime() + u1) in
let t1 = build_title "eDonkey" "Session" u1 in
let t2 = build_title "eDonkey" "Total" u2 in
let l = brand_list in
if mods then print_stats_mods o style else
match style with
| Old -> print_stats_old buf stats_array l t1 u1
| _ ->
if use_html_mods o then begin
print_stats_html_mods buf stats_array l t1 u1;
print_stats_html_mods buf !!gstats_array l t2 u2
end else begin
print_stats_ascii buf stats_array l t1 u1;
print_stats_ascii buf !!gstats_array l t2 u2
end
let _ =
network.op_network_display_stats <- (fun o -> print_stats o New false);
network.op_network_stat_info_list <- (fun _ ->
let r = ref [] in
let l1 = stats_list brand_list stats_array in
let l2 = stats_list brand_list !!gstats_array in
let u1 = BasicSocket.last_time () - !start_session in
let u2 = (guptime() + u1) in
r := [("Session clients", u1, l1); ("Global clients", u2, l2)];
if !!emule_mods_count then begin
let l3 = stats_list brand_mod_list stats_mod_array in
let l4 = stats_list brand_mod_list !!gstats_mod_array in
r := !r @ [ ("Session mods", u1, l3); ("Global mods", u2, l4)]
end;
!r
);
register_commands
[
"client_stats", "Network/Donkey",Arg_none (fun o ->
print_stats o Old false;
""
), ":\t\t\t\tshow breakdown of download/upload by clients brand";
"cs", "Network/Donkey",Arg_none (fun o ->
print_stats o New false;
""
), ":\t\t\t\t\tshow table of download/upload by ED2K clients brand";
"csm", "Network/Donkey",Arg_none (fun o ->
print_stats o New true;
""
), ":\t\t\t\t\tshow table of download/upload by eMule MODs";
"reset_stats", "Network/Donkey",Arg_none (fun o ->
Array.iteri (fun x _ ->
stats_array.(x).brand_seen <- 0;
stats_array.(x).brand_banned <- 0;
stats_array.(x).brand_filerequest <- 0;
stats_array.(x).brand_download <- 0L;
stats_array.(x).brand_upload <- 0L;
) stats_array;
Array.iteri (fun x _ ->
stats_mod_array.(x).brand_seen <- 0;
stats_mod_array.(x).brand_banned <- 0;
stats_mod_array.(x).brand_filerequest <- 0;
stats_mod_array.(x).brand_download <- Int64.zero;
stats_mod_array.(x).brand_upload <- Int64.zero
) stats_mod_array;
start_session := BasicSocket.last_time ();
"done"
), ":\t\t\t\treset session statistics";
]
let save_download_history file =
let buf = Buffer.create 100 in
( * Some opcode for edonkey downloads
let save_download_history file =
let buf = Buffer.create 100 in
client md4 , and NOT IP
let time = Unix.time () in
let time = Unix.localtime time in
date on 5 bytes
buf_int8 buf time.Unix.tm_hour;
buf_int8 buf time.Unix.tm_mday;
buf_int8 buf time.Unix.tm_mon;
buf_int16 buf time.Unix.tm_year;
Send the hash of the MD4+size , so that they can not be recovered ,
but they can be used to compare downloads .
but they can be used to compare downloads. *)
let m = Printf.sprintf "%s%Ld"
(Md4.Md4.direct_to_string file.file_md4) (file_size file) in
compute of the string
SENT : 20 bytes
Buffer.add_string buf (Md4.Sha1.direct_to_string m);
Send the magnitude of the size ( power of 10 )
let size = ref (file_size file) in
let m = ref 0 in
while !size <> Int64.zero do
incr m;
size := !size // 10L
done;
SENT : 1 byte
buf_int8 buf !m;
let current = ref [] in
Intmap.iter (fun _ c ->
let location =
match c.client_kind with
Indirect_location (name, md4) ->
Printf.sprintf "%s%s" name
(Md4.Md4.direct_to_string md4)
| Known_location (ip,port) ->
Printf.sprintf "%s%d"
(Ip.to_string ip) port
in
ANONYMISATION of the source : we compute the Sha1 digest of the source ,
which can not be recovered from this information
which cannot be recovered from this information *)
compute of the string
current := location :: !current;
) file.file_locations;
buf_list (fun buf s ->
Buffer.add_string buf (Md4.Sha1.direct_to_string s)
) buf !current;
let file_history = "downloads.stats" in
let oc = append_out file_history in
output_string oc (Buffer.contents buf);
close_out oc
*)
|
52a16e23d593585ef2a672cca2ff68b663d4e5abad56ecbf29c23b5e43986091 | TrustInSoft/tis-interpreter | partitioning.ml | Modified by TrustInSoft
(**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
open Eval
module type StateSet = sig
type state
type t
val empty: t
val is_empty: t -> bool
val singleton: state -> t
val singleton': state or_bottom -> t
val uncheck_add: state -> t -> t
val add: state -> t -> t
val add': state or_bottom -> t -> t
val length: t -> int
val merge: into:t -> t -> t * bool
val join: ?into:state or_bottom -> t -> state or_bottom
val fold: (state -> 'a -> 'a) -> t -> 'a -> 'a
val iter: (state -> unit) -> t -> unit
val map: (state -> state) -> t -> t
val reorder: t -> t
val of_list: state list -> t
val to_list: t -> state list
val pretty : Format.formatter -> t -> unit
end
module type Partition = sig
type state
type state_set
type t
val empty: unit -> t
val fold: (state -> 'a -> 'a) -> t -> 'a -> 'a
val merge_set_return_new: state_set -> t -> state_set
val join: t -> state or_bottom
val to_set: t -> state_set
val to_list: t -> state list
val pretty : Format.formatter -> t -> unit
end
(** Set of states, propagated through the edges by the dataflow analysis. *)
module Make_Set (Domain : Abstract_domain.S) = struct
type state = Domain.t
type t = Domain.t list
let empty = []
let is_empty = function [] -> true | _ -> false
let singleton s = [s]
let singleton' s = match s with `Bottom -> [] | `Value s -> [s]
let uncheck_add s states = s :: states
let length = List.length
let join ?(into=`Bottom) states =
List.fold_left
(fun acc v -> Bottom.join Domain.join acc (`Value v))
into states
let fold f states acc = List.fold_left (fun acc s -> f s acc) acc states
let iter = List.iter
let map = List.map
let of_list l = l
let to_list l = l
exception Unchanged
let add_exn v s =
if (List.exists (fun e -> Domain.is_included v e) s)
then raise Unchanged;
v :: s
let add v s =
try add_exn v s
with Unchanged -> s
let add' v s = match v with
| `Bottom -> s
| `Value v -> add v s
let merge ~into set =
let f e (acc, unchanged) =
try add_exn e acc, false
with Unchanged -> acc, unchanged
in
fold f set (into, true)
let reorder = List.rev
let pretty fmt state =
iter (fun s -> Format.fprintf fmt "set contains %a@\n" Domain.pretty s) state
end
(** Partition of the abstract states, computed for each node by the
dataflow analysis. *)
module Make_Partition
(Domain : Abstract_domain.External)
(States : StateSet with type state = Domain.t)
= struct
type state = Domain.t
type state_set = States.t
module Index = Hashtbl.Make (Cvalue_domain.Subpart)
type t = {
mutable states : Domain.t Index.t; (* Indexed states. *)
mutable prefix : Cvalue_domain.prefix option; (* Prefix for the index. *)
States not indexed .
}
let sentinel = Index.create 1
let empty () = { states = sentinel ; prefix = None ; others = [] }
let fold f {states; others} acc =
let acc = Index.fold (fun _k s acc -> f s acc) states acc in
List.fold_left (fun acc s -> f s acc) acc others
(* Optimizations relying on specific features of the cvalue domain. *)
let distinct_subpart = match Domain.get Cvalue_domain.key with
| None -> fun _ _ -> None
| Some get ->
fun s1 s2 -> Cvalue_domain.distinct_subpart (get s1) (get s2)
let find_subpart = match Domain.get Cvalue_domain.key with
| None -> fun _ _ -> None
| Some get ->
fun state prefix -> Cvalue_domain.find_subpart (get state) prefix
let add state partition =
let {states; prefix; others} = partition in
match prefix with
| None -> begin match others with
| [] -> partition.others <- [state]; true
| s :: tail ->
if List.exists (fun s -> Domain.is_included state s) others
then false
else match distinct_subpart state s with
| None -> partition.others <- state :: others; true
| Some (prefix, part1, part2) ->
let states = Index.create 13 in
Index.add states part1 state;
Index.add states part2 s;
let others =
List.fold_left
(fun acc s -> match find_subpart s prefix with
| None -> s :: acc
| Some part -> Index.add states part s; acc)
[] tail
in
partition.states <- states;
partition.prefix <- Some prefix;
partition.others <- others;
true
end
| Some prefix ->
match find_subpart state prefix with
| None ->
if List.exists (fun s -> Domain.is_included state s) others
then false
else (partition.others <- state :: others; true)
| Some prefix ->
let candidates = Index.find_all states prefix in
if List.exists (fun s -> Domain.is_included state s) candidates
then false
else (Index.add states prefix state; true)
let merge_set_return_new states partition =
let f state acc =
let added = add state partition in
if added then States.uncheck_add state acc else acc
in
States.fold f states States.empty
let join partition =
fold (fun v acc -> Bottom.join Domain.join (`Value v) acc) partition `Bottom
let to_list p = Index.fold (fun _k v a -> v :: a) p.states p.others
let to_set partition = States.of_list (to_list partition)
let iter f { states; others } =
Index.iter (fun _k v -> f v) states;
List.iter f others
let pretty fmt s =
iter
(fun state ->
Format.fprintf fmt "set contains %a@\n"
Domain.pretty state)
s
end
(*
Local Variables:
compile-command: "make -C ../../../.."
End:
*)
| null | https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/value/engine/partitioning.ml | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
* Set of states, propagated through the edges by the dataflow analysis.
* Partition of the abstract states, computed for each node by the
dataflow analysis.
Indexed states.
Prefix for the index.
Optimizations relying on specific features of the cvalue domain.
Local Variables:
compile-command: "make -C ../../../.."
End:
| Modified by TrustInSoft
This file is part of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
open Eval
module type StateSet = sig
type state
type t
val empty: t
val is_empty: t -> bool
val singleton: state -> t
val singleton': state or_bottom -> t
val uncheck_add: state -> t -> t
val add: state -> t -> t
val add': state or_bottom -> t -> t
val length: t -> int
val merge: into:t -> t -> t * bool
val join: ?into:state or_bottom -> t -> state or_bottom
val fold: (state -> 'a -> 'a) -> t -> 'a -> 'a
val iter: (state -> unit) -> t -> unit
val map: (state -> state) -> t -> t
val reorder: t -> t
val of_list: state list -> t
val to_list: t -> state list
val pretty : Format.formatter -> t -> unit
end
module type Partition = sig
type state
type state_set
type t
val empty: unit -> t
val fold: (state -> 'a -> 'a) -> t -> 'a -> 'a
val merge_set_return_new: state_set -> t -> state_set
val join: t -> state or_bottom
val to_set: t -> state_set
val to_list: t -> state list
val pretty : Format.formatter -> t -> unit
end
module Make_Set (Domain : Abstract_domain.S) = struct
type state = Domain.t
type t = Domain.t list
let empty = []
let is_empty = function [] -> true | _ -> false
let singleton s = [s]
let singleton' s = match s with `Bottom -> [] | `Value s -> [s]
let uncheck_add s states = s :: states
let length = List.length
let join ?(into=`Bottom) states =
List.fold_left
(fun acc v -> Bottom.join Domain.join acc (`Value v))
into states
let fold f states acc = List.fold_left (fun acc s -> f s acc) acc states
let iter = List.iter
let map = List.map
let of_list l = l
let to_list l = l
exception Unchanged
let add_exn v s =
if (List.exists (fun e -> Domain.is_included v e) s)
then raise Unchanged;
v :: s
let add v s =
try add_exn v s
with Unchanged -> s
let add' v s = match v with
| `Bottom -> s
| `Value v -> add v s
let merge ~into set =
let f e (acc, unchanged) =
try add_exn e acc, false
with Unchanged -> acc, unchanged
in
fold f set (into, true)
let reorder = List.rev
let pretty fmt state =
iter (fun s -> Format.fprintf fmt "set contains %a@\n" Domain.pretty s) state
end
module Make_Partition
(Domain : Abstract_domain.External)
(States : StateSet with type state = Domain.t)
= struct
type state = Domain.t
type state_set = States.t
module Index = Hashtbl.Make (Cvalue_domain.Subpart)
type t = {
States not indexed .
}
let sentinel = Index.create 1
let empty () = { states = sentinel ; prefix = None ; others = [] }
let fold f {states; others} acc =
let acc = Index.fold (fun _k s acc -> f s acc) states acc in
List.fold_left (fun acc s -> f s acc) acc others
let distinct_subpart = match Domain.get Cvalue_domain.key with
| None -> fun _ _ -> None
| Some get ->
fun s1 s2 -> Cvalue_domain.distinct_subpart (get s1) (get s2)
let find_subpart = match Domain.get Cvalue_domain.key with
| None -> fun _ _ -> None
| Some get ->
fun state prefix -> Cvalue_domain.find_subpart (get state) prefix
let add state partition =
let {states; prefix; others} = partition in
match prefix with
| None -> begin match others with
| [] -> partition.others <- [state]; true
| s :: tail ->
if List.exists (fun s -> Domain.is_included state s) others
then false
else match distinct_subpart state s with
| None -> partition.others <- state :: others; true
| Some (prefix, part1, part2) ->
let states = Index.create 13 in
Index.add states part1 state;
Index.add states part2 s;
let others =
List.fold_left
(fun acc s -> match find_subpart s prefix with
| None -> s :: acc
| Some part -> Index.add states part s; acc)
[] tail
in
partition.states <- states;
partition.prefix <- Some prefix;
partition.others <- others;
true
end
| Some prefix ->
match find_subpart state prefix with
| None ->
if List.exists (fun s -> Domain.is_included state s) others
then false
else (partition.others <- state :: others; true)
| Some prefix ->
let candidates = Index.find_all states prefix in
if List.exists (fun s -> Domain.is_included state s) candidates
then false
else (Index.add states prefix state; true)
let merge_set_return_new states partition =
let f state acc =
let added = add state partition in
if added then States.uncheck_add state acc else acc
in
States.fold f states States.empty
let join partition =
fold (fun v acc -> Bottom.join Domain.join (`Value v) acc) partition `Bottom
let to_list p = Index.fold (fun _k v a -> v :: a) p.states p.others
let to_set partition = States.of_list (to_list partition)
let iter f { states; others } =
Index.iter (fun _k v -> f v) states;
List.iter f others
let pretty fmt s =
iter
(fun state ->
Format.fprintf fmt "set contains %a@\n"
Domain.pretty state)
s
end
|
6af009168c3a3817b67582e91cb571bb03aa36d1f5cc86811873ce631d4fe8a8 | uscensusbureau/citysdk | tests.cljs | (ns test.wmsAPI.tests
(:require
[cljs.core.async :refer [chan close! >! <!]
:refer-macros [go]]
[cljs.test :refer-macros [deftest is run-tests]]
[test.fixtures.core :refer [GG test-async] :as ts]
[census.wmsAPI.core :refer [$g$->wms-cfg
lookup-id->match?
search-id->match?
C->GIS-url
configed-map
try-census-wms
wms-engage?
=>args=GIS=args=>
I-<wms=I=]]))
(def wms-only {:vintage 2014,
:geoHierarchy {:state {:lat 28.2639, :lng -80.7214}, :county "*"}})
(deftest $g$->wms-cfg-test
(is (= ($g$->wms-cfg GG wms-only)
{:vintage 2014,
:layers ["82"],
:cur-layer-idx 0,
:lat 28.2639,
:lng -80.7214,
:sub-levels '([:county "*"]), ;; don't ask
:geo [:STATE],
:looked-up-in :2010})))
(deftest lookup-id->match?-test
(is (= (lookup-id->match? :CONCITY ; ↓ seq'd inverted geoKeyMap ↓
[{:2017 {:wms {:layers ["24"], :lookup [:STATE :CONCITY]}}
:2016 {:wms {:layers ["24"], :lookup [:STATE :CONCITY]}}}
:consolidated-cities
{:2014 {:wms {:layers ["24"], :lookup [:BLOOP]}}
:2016 {:wms {:layers ["24"], :lookup [:BLOOP]}}}
:something-else])
:consolidated-cities)))
(deftest search-id->match?-test
(is (= (search-id->match? GG :CONCITY)
'(:consolidated-cities))))
(deftest configed-map-test
(is (= (configed-map GG {:STATE "51", :COUNTY "013"})
{:STATE {:state "51"}, :COUNTY {:county "013"}})))
(def WMS_GO {:vintage "2014",
:geoHierarchy {:state {:lat 28.2639, :lng -80.7214}, :county "*"}})
(deftest C->GIS-url-test
(is (= (C->GIS-url GG WMS_GO)
"=-80.7214,28.2639&geometryType=esriGeometryPoint&inSR=4269&spatialRel=esriSpatialRelIntersects&returnGeometry=false&f=json&outFields=STATE")))
(deftest try-census-wms-test
(let [=O= (chan 1)]
(test-async
(go (try-census-wms GG WMS_GO 0 =O=)
(let [res (<! =O=)]
(is (= res
{:STATE {:state "12"}}))
(close! =O=))))))
(deftest test-atom-via-chan
(let [=O= (chan 1)
$A$ (atom {})]
(test-async
(go (>! =O= (reset! $A$ {:key "val"}))
(let [res (<! =O=)]
(is (= res
{:key "val"}))
(>! =O= @$A$)
(is (identical? (<! =O=)
res))
(close! =O=))))))
(deftest wms-engage?-test
(is (and (= (wms-engage? {:geoHierarchy {:county {:lat 1 :lng -7} :tract "*"}})
true)
(= (wms-engage? {:geoHierarchy {:county "01" :tract "*"}})
false))))
(deftest =>args=GIS=args=>-test
(let [args-in {:vintage "2017",
:geoHierarchy {:state {:lat 38.8816, :lng -77.0910}, :county "*"}}
args-out {:vintage "2017",
:geoHierarchy {:state "51", :county "*"}}
=>args= (chan 1)
=args=> (chan 1)]
(test-async
(go (>! =>args= args-in)
((=>args=GIS=args=> GG) =>args= =args=>)
(is (= (<! =args=>)
args-out))
(close! =>args=)
(close! =args=>)))))
(deftest I-<wms=I=-test
(let [args-in {:vintage "2017",
:geoHierarchy {:state {:lat 38.8816, :lng -77.0910}, :county "*"}}
args-na {:vintage "1997"
:geoHierarchy {:county {:lat 22.2222, :lng -66.6666}}}
=args=> (chan 1)]
(test-async
(go ((I-<wms=I= GG) args-in =args=>)
(is (= (<! =args=>)
{:vintage "2017",
:geoHierarchy {:state "51", :county "*"}}))
((I-<wms=I= GG) args-na =args=>)
(is (= (<! =args=>)
"No FIPS (Census geocodes) found for given arguments"))
(close! =args=>)))))
(run-tests)
| null | https://raw.githubusercontent.com/uscensusbureau/citysdk/ae5c1c2d826dec76dfca903d6784750811ec24bc/v2/src/test/wmsAPI/tests.cljs | clojure | don't ask
↓ seq'd inverted geoKeyMap ↓
| (ns test.wmsAPI.tests
(:require
[cljs.core.async :refer [chan close! >! <!]
:refer-macros [go]]
[cljs.test :refer-macros [deftest is run-tests]]
[test.fixtures.core :refer [GG test-async] :as ts]
[census.wmsAPI.core :refer [$g$->wms-cfg
lookup-id->match?
search-id->match?
C->GIS-url
configed-map
try-census-wms
wms-engage?
=>args=GIS=args=>
I-<wms=I=]]))
(def wms-only {:vintage 2014,
:geoHierarchy {:state {:lat 28.2639, :lng -80.7214}, :county "*"}})
(deftest $g$->wms-cfg-test
(is (= ($g$->wms-cfg GG wms-only)
{:vintage 2014,
:layers ["82"],
:cur-layer-idx 0,
:lat 28.2639,
:lng -80.7214,
:geo [:STATE],
:looked-up-in :2010})))
(deftest lookup-id->match?-test
[{:2017 {:wms {:layers ["24"], :lookup [:STATE :CONCITY]}}
:2016 {:wms {:layers ["24"], :lookup [:STATE :CONCITY]}}}
:consolidated-cities
{:2014 {:wms {:layers ["24"], :lookup [:BLOOP]}}
:2016 {:wms {:layers ["24"], :lookup [:BLOOP]}}}
:something-else])
:consolidated-cities)))
(deftest search-id->match?-test
(is (= (search-id->match? GG :CONCITY)
'(:consolidated-cities))))
(deftest configed-map-test
(is (= (configed-map GG {:STATE "51", :COUNTY "013"})
{:STATE {:state "51"}, :COUNTY {:county "013"}})))
(def WMS_GO {:vintage "2014",
:geoHierarchy {:state {:lat 28.2639, :lng -80.7214}, :county "*"}})
(deftest C->GIS-url-test
(is (= (C->GIS-url GG WMS_GO)
"=-80.7214,28.2639&geometryType=esriGeometryPoint&inSR=4269&spatialRel=esriSpatialRelIntersects&returnGeometry=false&f=json&outFields=STATE")))
(deftest try-census-wms-test
(let [=O= (chan 1)]
(test-async
(go (try-census-wms GG WMS_GO 0 =O=)
(let [res (<! =O=)]
(is (= res
{:STATE {:state "12"}}))
(close! =O=))))))
(deftest test-atom-via-chan
(let [=O= (chan 1)
$A$ (atom {})]
(test-async
(go (>! =O= (reset! $A$ {:key "val"}))
(let [res (<! =O=)]
(is (= res
{:key "val"}))
(>! =O= @$A$)
(is (identical? (<! =O=)
res))
(close! =O=))))))
(deftest wms-engage?-test
(is (and (= (wms-engage? {:geoHierarchy {:county {:lat 1 :lng -7} :tract "*"}})
true)
(= (wms-engage? {:geoHierarchy {:county "01" :tract "*"}})
false))))
(deftest =>args=GIS=args=>-test
(let [args-in {:vintage "2017",
:geoHierarchy {:state {:lat 38.8816, :lng -77.0910}, :county "*"}}
args-out {:vintage "2017",
:geoHierarchy {:state "51", :county "*"}}
=>args= (chan 1)
=args=> (chan 1)]
(test-async
(go (>! =>args= args-in)
((=>args=GIS=args=> GG) =>args= =args=>)
(is (= (<! =args=>)
args-out))
(close! =>args=)
(close! =args=>)))))
(deftest I-<wms=I=-test
(let [args-in {:vintage "2017",
:geoHierarchy {:state {:lat 38.8816, :lng -77.0910}, :county "*"}}
args-na {:vintage "1997"
:geoHierarchy {:county {:lat 22.2222, :lng -66.6666}}}
=args=> (chan 1)]
(test-async
(go ((I-<wms=I= GG) args-in =args=>)
(is (= (<! =args=>)
{:vintage "2017",
:geoHierarchy {:state "51", :county "*"}}))
((I-<wms=I= GG) args-na =args=>)
(is (= (<! =args=>)
"No FIPS (Census geocodes) found for given arguments"))
(close! =args=>)))))
(run-tests)
|
c2bbff10db33b8930c40413b75d99ef5512b5e6567d1fa8397cfa4139e3fc8a5 | rudymatela/speculate | bool.hs | import Test.QuickSpec
main =
quickSpec
[ ["p", "q", "r"] `vars` (undefined :: Bool)
, "False" `fun0` False
, "True" `fun0` True
, "not" `fun1` not
, "&&" `fun2` (&&)
, "||" `fun2` (||)
]
| null | https://raw.githubusercontent.com/rudymatela/speculate/8ec39747d03033db4349d554467d4b78bb72935d/bench/qs1/bool.hs | haskell | import Test.QuickSpec
main =
quickSpec
[ ["p", "q", "r"] `vars` (undefined :: Bool)
, "False" `fun0` False
, "True" `fun0` True
, "not" `fun1` not
, "&&" `fun2` (&&)
, "||" `fun2` (||)
]
| |
14045f246be60ca8787f043f8e80bea0589fd1b5b0b1115c593f05b55d754c73 | agda/agda | Strict.hs | -- | A strict version of the 'Maybe' type.
--
-- Import qualified, as in
-- @
import qualified . Utils . Maybe . Strict as Strict
-- @
module Agda.Utils.Maybe.Strict
( module Data.Strict.Maybe
, module Data.Strict.Classes
, module Agda.Utils.Maybe.Strict
) where
import Prelude hiding (Maybe(..), maybe)
import Data.Strict.Classes
import Data.Strict.Maybe
import Agda.Utils.Null
-- | Note that strict Maybe is an 'Applicative' only modulo strictness.
-- The laws only hold in the strict semantics.
-- Eg. @pure f <*> pure _|_ = _|_@, but according to the laws for
' Applicative ' it should be @pure ( f _ |_)@.
We ignore this issue here , it applies also to ' Foldable ' and ' ' .
instance Applicative Maybe where
pure = Just
Just f <*> Just x = Just $ f x
_ <*> _ = Nothing
instance Null (Maybe a) where
empty = Nothing
null = isNothing
-- * Collection operations.
| @unionWith@ for collections of size < = 1 .
unionMaybeWith :: (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a
unionMaybeWith f Nothing mb = mb
unionMaybeWith f ma Nothing = ma
unionMaybeWith f (Just a) (Just b) = Just $ f a b
| Unzipping a list of length < = 1 .
unzipMaybe :: Maybe (a,b) -> (Maybe a, Maybe b)
unzipMaybe Nothing = (Nothing, Nothing)
unzipMaybe (Just (a,b)) = (Just a, Just b)
-- | Filtering a singleton list.
--
-- @filterMaybe p a = 'listToMaybe' ('filter' p [a])@
filterMaybe :: (a -> Bool) -> a -> Maybe a
filterMaybe p a
| p a = Just a
| otherwise = Nothing
-- * Conditionals and loops.
-- | Version of 'mapMaybe' with different argument ordering.
forMaybe :: [a] -> (a -> Maybe b) -> [b]
forMaybe = flip mapMaybe
-- | Version of 'maybe' with different argument ordering.
-- Often, we want to case on a 'Maybe', do something interesting
-- in the 'Just' case, but only a default action in the 'Nothing'
case . Then , the argument ordering of @caseMaybe@ is preferable .
--
-- @caseMaybe m err f = flip (maybe err) m f@
caseMaybe :: Maybe a -> b -> (a -> b) -> b
caseMaybe m err f = maybe err f m
-- * Monads and Maybe.
| Monadic version of ' maybe ' .
maybeM :: Monad m => m b -> (a -> m b) -> m (Maybe a) -> m b
maybeM n j mm = maybe n j =<< mm
| Monadic version of ' fromMaybe ' .
fromMaybeM :: Monad m => m a -> m (Maybe a) -> m a
fromMaybeM m mm = maybeM m return mm
| Monadic version of ' ' .
-- That is, 'maybeM' with a different argument ordering.
caseMaybeM :: Monad m => m (Maybe a) -> m b -> (a -> m b) -> m b
caseMaybeM mm err f = maybeM err f mm
-- | 'caseMaybeM' with flipped branches.
ifJustM :: Monad m => m (Maybe a) -> (a -> m b) -> m b -> m b
ifJustM mm = flip (caseMaybeM mm)
-- | A more telling name for 'Traversable.forM' for the 'Maybe' collection type.
Or : ' ' without the ' Nothing ' case .
whenJust :: Monad m => Maybe a -> (a -> m ()) -> m ()
whenJust m k = caseMaybe m (return ()) k
-- | 'caseMaybeM' without the 'Nothing' case.
whenJustM :: Monad m => m (Maybe a) -> (a -> m ()) -> m ()
whenJustM c m = c >>= (`whenJust` m)
| null | https://raw.githubusercontent.com/agda/agda/5d251d98739480692350221442e48d9f246c83e6/src/full/Agda/Utils/Maybe/Strict.hs | haskell | | A strict version of the 'Maybe' type.
Import qualified, as in
@
@
| Note that strict Maybe is an 'Applicative' only modulo strictness.
The laws only hold in the strict semantics.
Eg. @pure f <*> pure _|_ = _|_@, but according to the laws for
* Collection operations.
| Filtering a singleton list.
@filterMaybe p a = 'listToMaybe' ('filter' p [a])@
* Conditionals and loops.
| Version of 'mapMaybe' with different argument ordering.
| Version of 'maybe' with different argument ordering.
Often, we want to case on a 'Maybe', do something interesting
in the 'Just' case, but only a default action in the 'Nothing'
@caseMaybe m err f = flip (maybe err) m f@
* Monads and Maybe.
That is, 'maybeM' with a different argument ordering.
| 'caseMaybeM' with flipped branches.
| A more telling name for 'Traversable.forM' for the 'Maybe' collection type.
| 'caseMaybeM' without the 'Nothing' case. | import qualified . Utils . Maybe . Strict as Strict
module Agda.Utils.Maybe.Strict
( module Data.Strict.Maybe
, module Data.Strict.Classes
, module Agda.Utils.Maybe.Strict
) where
import Prelude hiding (Maybe(..), maybe)
import Data.Strict.Classes
import Data.Strict.Maybe
import Agda.Utils.Null
' Applicative ' it should be @pure ( f _ |_)@.
We ignore this issue here , it applies also to ' Foldable ' and ' ' .
instance Applicative Maybe where
pure = Just
Just f <*> Just x = Just $ f x
_ <*> _ = Nothing
instance Null (Maybe a) where
empty = Nothing
null = isNothing
| @unionWith@ for collections of size < = 1 .
unionMaybeWith :: (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a
unionMaybeWith f Nothing mb = mb
unionMaybeWith f ma Nothing = ma
unionMaybeWith f (Just a) (Just b) = Just $ f a b
| Unzipping a list of length < = 1 .
unzipMaybe :: Maybe (a,b) -> (Maybe a, Maybe b)
unzipMaybe Nothing = (Nothing, Nothing)
unzipMaybe (Just (a,b)) = (Just a, Just b)
filterMaybe :: (a -> Bool) -> a -> Maybe a
filterMaybe p a
| p a = Just a
| otherwise = Nothing
forMaybe :: [a] -> (a -> Maybe b) -> [b]
forMaybe = flip mapMaybe
case . Then , the argument ordering of @caseMaybe@ is preferable .
caseMaybe :: Maybe a -> b -> (a -> b) -> b
caseMaybe m err f = maybe err f m
| Monadic version of ' maybe ' .
maybeM :: Monad m => m b -> (a -> m b) -> m (Maybe a) -> m b
maybeM n j mm = maybe n j =<< mm
| Monadic version of ' fromMaybe ' .
fromMaybeM :: Monad m => m a -> m (Maybe a) -> m a
fromMaybeM m mm = maybeM m return mm
| Monadic version of ' ' .
caseMaybeM :: Monad m => m (Maybe a) -> m b -> (a -> m b) -> m b
caseMaybeM mm err f = maybeM err f mm
ifJustM :: Monad m => m (Maybe a) -> (a -> m b) -> m b -> m b
ifJustM mm = flip (caseMaybeM mm)
Or : ' ' without the ' Nothing ' case .
whenJust :: Monad m => Maybe a -> (a -> m ()) -> m ()
whenJust m k = caseMaybe m (return ()) k
whenJustM :: Monad m => m (Maybe a) -> (a -> m ()) -> m ()
whenJustM c m = c >>= (`whenJust` m)
|
561aa321513ab8950655456eec55db89dfa31701a5e854ccccbb18c271e00ba0 | mirage/orm | simple.ml | pp camlp4orf
open Printf
type x = {
foo: int;
bar: string
} with
orm
open OUnit
open Test_utils
let name = "simple.db"
let x = { foo = (Random.int 100); bar="hello world" }
let x2 = { foo = (Random.int 100); bar="bye world" }
let test_init () =
ignore(open_db x_init name);
ignore(open_db ~rm:false x_init name);
ignore(open_db ~rm:false x_init name)
let test_order () =
let db = open_db x_init name in
x_save db x;
x_save db x2;
match x_get ~order_by:`foo db with
| [y1; y2] -> "query is ordered" @? (y1.foo <= y2.foo)
| _ -> "get error" @? false
let test_id () =
let db = open_db x_init name in
x_save db x;
let i = x_id db x in
"id is 1" @? (ORMID_x.to_int64 i = 1L);
let x' = x_get_by_id (`Eq i) db in
"bar eq" @? (x'.bar = x.bar);
let x2 = { foo=100; bar="x2222" } in
assert_raises ~msg:"test_id_not_found" Not_found (fun () -> x_id db x2);
assert_raises ~msg:"test_id_not_found2" Not_found (fun () -> x_get_by_id ~id:(`Eq (ORMID_x.of_int64 5L)) db)
let test_save () =
let db = open_db x_init name in
let _ = open_db ~rm:false x_init_read_only name in
x_save db x;
x_save db x
let test_update () =
let db = open_db x_init name in
x_save db x;
x_save db x
let test_subtype () =
let module A = struct
type x = {
foo: int64;
} with orm
end in
let db = open_db ~rm:false A.x_init_read_only name in
let i = A.x_get ~foo:(`Eq (Int64.of_int x.foo)) db in
"2 in db" @? (List.length i = 1);
let i = List.hd i in
"values match" @? (i.A.foo = Int64.of_int x.foo)
let test_get () =
let db = open_db x_init name in
x_save db x;
x_save db x2;
let i = x_get ~bar:(`Eq "hello world") db in
"1 in db" @? (List.length i = 1);
let i = List.hd i in
"values match" @? (i.foo = x.foo && (i.bar = x.bar))
let test_contains_get () =
let db = open_db x_init name in
x_save db x;
x_save db x2;
let i = x_get ~bar:(`Contains "hello") db in
"1 in db" @? (List.length i = 1);
let i = List.hd i in
"values match" @? (i.foo = x.foo && (i.bar = x.bar))
let test_custom_get () =
let db = open_db x_init name in
x_save db x;
x_save db x2;
let nb = ref 0 in
let subs = ref [] in
let i = x_get ~custom:(fun x -> let s = String.sub x.bar 3 2 in subs := s :: !subs; if s="lo" then (incr nb; true) else false) db in
(Printf.sprintf "1 in db (nb=%d, subs={%s})" !nb (String.concat ", " !subs)) @? (List.length i = 1)
let test_save_get () =
let db = open_db x_init name in
x_save db x;
let i = x_get db in
"1 in db" @? (List.length i = 1);
let i = List.hd i in
"structurally equal after get" @? ( x == i)
let test_delete () =
let db = open_db ~rm:false x_init name in
let x1 = match x_get db with [x] -> x |_ -> assert false in
let x2 = { foo = (Random.int 100); bar="x2" } in
let x3 = { foo = (Random.int 100); bar="x3" } in
"1 in db" @? (List.length (x_get db) = 1);
x_delete db x1;
"0 in db" @? (List.length (x_get db) = 0);
x_save db x1;
x_save db x2;
x_save db x3;
"3 in db" @? (List.length (x_get db) = 3);
x_delete db x2;
"2 in db" @? (List.length (x_get db) = 2);
match x_get db with
[a1;a3] -> "equal" @? (a3=x3 && a1=x1)
|_ -> assert false
let test_lazy_get () =
let db = open_db x_init name in
x_save db x;
x_save db x2;
let next = x_lazy_get db in
(match next () with
| Some a1 -> "1 in db" @? (x.bar = a1.bar)
| _ -> "1 in db" @? false);
(match next () with
| Some a2 -> "2 in db" @? (x2.bar = a2.bar)
| _ -> "2 in db" @? false);
(match next () with
| None -> "nothing in db" @? true
| _ -> "nothing in db" @? false);
(match next () with
| None -> "really nothing in db" @? true
| _ -> "really nothing in db" @? false)
let suite = [
"simple_order" >:: test_order;
"simple_init" >:: test_init;
"simple_id" >:: test_id;
"simple_save" >:: test_save;
"simple_update" >:: test_update;
"simple_get" >:: test_get;
"simple_contains_get" >:: test_contains_get;
"simple_lazy_get" >:: test_lazy_get;
"simple_custom_get" >:: test_custom_get;
"simple_subtype" >:: test_subtype;
"simple_save_get" >:: test_save_get;
"simple_delete" >:: test_delete;
]
| null | https://raw.githubusercontent.com/mirage/orm/24c2e0e3157853b2328d09feacdbe637e34d354c/lib_test/simple.ml | ocaml | pp camlp4orf
open Printf
type x = {
foo: int;
bar: string
} with
orm
open OUnit
open Test_utils
let name = "simple.db"
let x = { foo = (Random.int 100); bar="hello world" }
let x2 = { foo = (Random.int 100); bar="bye world" }
let test_init () =
ignore(open_db x_init name);
ignore(open_db ~rm:false x_init name);
ignore(open_db ~rm:false x_init name)
let test_order () =
let db = open_db x_init name in
x_save db x;
x_save db x2;
match x_get ~order_by:`foo db with
| [y1; y2] -> "query is ordered" @? (y1.foo <= y2.foo)
| _ -> "get error" @? false
let test_id () =
let db = open_db x_init name in
x_save db x;
let i = x_id db x in
"id is 1" @? (ORMID_x.to_int64 i = 1L);
let x' = x_get_by_id (`Eq i) db in
"bar eq" @? (x'.bar = x.bar);
let x2 = { foo=100; bar="x2222" } in
assert_raises ~msg:"test_id_not_found" Not_found (fun () -> x_id db x2);
assert_raises ~msg:"test_id_not_found2" Not_found (fun () -> x_get_by_id ~id:(`Eq (ORMID_x.of_int64 5L)) db)
let test_save () =
let db = open_db x_init name in
let _ = open_db ~rm:false x_init_read_only name in
x_save db x;
x_save db x
let test_update () =
let db = open_db x_init name in
x_save db x;
x_save db x
let test_subtype () =
let module A = struct
type x = {
foo: int64;
} with orm
end in
let db = open_db ~rm:false A.x_init_read_only name in
let i = A.x_get ~foo:(`Eq (Int64.of_int x.foo)) db in
"2 in db" @? (List.length i = 1);
let i = List.hd i in
"values match" @? (i.A.foo = Int64.of_int x.foo)
let test_get () =
let db = open_db x_init name in
x_save db x;
x_save db x2;
let i = x_get ~bar:(`Eq "hello world") db in
"1 in db" @? (List.length i = 1);
let i = List.hd i in
"values match" @? (i.foo = x.foo && (i.bar = x.bar))
let test_contains_get () =
let db = open_db x_init name in
x_save db x;
x_save db x2;
let i = x_get ~bar:(`Contains "hello") db in
"1 in db" @? (List.length i = 1);
let i = List.hd i in
"values match" @? (i.foo = x.foo && (i.bar = x.bar))
let test_custom_get () =
let db = open_db x_init name in
x_save db x;
x_save db x2;
let nb = ref 0 in
let subs = ref [] in
let i = x_get ~custom:(fun x -> let s = String.sub x.bar 3 2 in subs := s :: !subs; if s="lo" then (incr nb; true) else false) db in
(Printf.sprintf "1 in db (nb=%d, subs={%s})" !nb (String.concat ", " !subs)) @? (List.length i = 1)
let test_save_get () =
let db = open_db x_init name in
x_save db x;
let i = x_get db in
"1 in db" @? (List.length i = 1);
let i = List.hd i in
"structurally equal after get" @? ( x == i)
let test_delete () =
let db = open_db ~rm:false x_init name in
let x1 = match x_get db with [x] -> x |_ -> assert false in
let x2 = { foo = (Random.int 100); bar="x2" } in
let x3 = { foo = (Random.int 100); bar="x3" } in
"1 in db" @? (List.length (x_get db) = 1);
x_delete db x1;
"0 in db" @? (List.length (x_get db) = 0);
x_save db x1;
x_save db x2;
x_save db x3;
"3 in db" @? (List.length (x_get db) = 3);
x_delete db x2;
"2 in db" @? (List.length (x_get db) = 2);
match x_get db with
[a1;a3] -> "equal" @? (a3=x3 && a1=x1)
|_ -> assert false
let test_lazy_get () =
let db = open_db x_init name in
x_save db x;
x_save db x2;
let next = x_lazy_get db in
(match next () with
| Some a1 -> "1 in db" @? (x.bar = a1.bar)
| _ -> "1 in db" @? false);
(match next () with
| Some a2 -> "2 in db" @? (x2.bar = a2.bar)
| _ -> "2 in db" @? false);
(match next () with
| None -> "nothing in db" @? true
| _ -> "nothing in db" @? false);
(match next () with
| None -> "really nothing in db" @? true
| _ -> "really nothing in db" @? false)
let suite = [
"simple_order" >:: test_order;
"simple_init" >:: test_init;
"simple_id" >:: test_id;
"simple_save" >:: test_save;
"simple_update" >:: test_update;
"simple_get" >:: test_get;
"simple_contains_get" >:: test_contains_get;
"simple_lazy_get" >:: test_lazy_get;
"simple_custom_get" >:: test_custom_get;
"simple_subtype" >:: test_subtype;
"simple_save_get" >:: test_save_get;
"simple_delete" >:: test_delete;
]
| |
0b8184dd801bbca20b7711db9e58dffe0b0afcb478e319c074c5b1cfdad93346 | ericclack/overtone-loops | rap1.clj | (ns overtone-loops.music.rap1
(:use [overtone.live]
[overtone-loops.loops]
[overtone-loops.samples]))
;; Stop any currently playing music and clear any patterns
(set-up)
;; 1 & 2 & 3 & 4 &
(def ticks (loop-player 1/2 cymbal-closed [7 5 6 5 7 5 _ 3 ]))
(def hats (loop-player 1/2 cymbal-pedal [_ _ _ _ _ _ 6 _ ]))
(def kicks (loop-player 1/2 bass-hard [6 6 _ _ 6 _ _ _ ]))
(def snares (loop-player 1/2 snare-hard [_ _ 7 _ _ _ 9 _ ]))
(def extra-kicks [6 6 _ _ 6 5 _ 6 ])
(def extra-snares [_ 2 7 7 _ _ 9 3 ])
;; TO DO...
(defn late-halves
"Play half beats a bit late"
[b]
(if (half-beat? b) (+ b 1/3)
b))
;; ---------------------------------------------
(bpm 140)
(beats-in-bar 4)
(at-bar 1
(ticks)
(hats ))
(at-bar 3
(kicks)
(snares))
all play for only 2 - 3 phrases
(kicks (metro) extra-kicks)
(kicks (metro) [6 _ _ 3 6 _ _ 3 ])
(kicks (metro) :first)
(snares (metro) extra-snares)
(snares (metro) :first)
)
(comment
(silence (metro) ticks hats kicks snares)
(stop)
)
| null | https://raw.githubusercontent.com/ericclack/overtone-loops/54b0c230c1e6bd3d378583af982db4e9ae4bda69/src/overtone_loops/music/rap1.clj | clojure | Stop any currently playing music and clear any patterns
1 & 2 & 3 & 4 &
TO DO...
--------------------------------------------- | (ns overtone-loops.music.rap1
(:use [overtone.live]
[overtone-loops.loops]
[overtone-loops.samples]))
(set-up)
(def ticks (loop-player 1/2 cymbal-closed [7 5 6 5 7 5 _ 3 ]))
(def hats (loop-player 1/2 cymbal-pedal [_ _ _ _ _ _ 6 _ ]))
(def kicks (loop-player 1/2 bass-hard [6 6 _ _ 6 _ _ _ ]))
(def snares (loop-player 1/2 snare-hard [_ _ 7 _ _ _ 9 _ ]))
(def extra-kicks [6 6 _ _ 6 5 _ 6 ])
(def extra-snares [_ 2 7 7 _ _ 9 3 ])
(defn late-halves
"Play half beats a bit late"
[b]
(if (half-beat? b) (+ b 1/3)
b))
(bpm 140)
(beats-in-bar 4)
(at-bar 1
(ticks)
(hats ))
(at-bar 3
(kicks)
(snares))
all play for only 2 - 3 phrases
(kicks (metro) extra-kicks)
(kicks (metro) [6 _ _ 3 6 _ _ 3 ])
(kicks (metro) :first)
(snares (metro) extra-snares)
(snares (metro) :first)
)
(comment
(silence (metro) ticks hats kicks snares)
(stop)
)
|
080bc0680120c46890399dd3e94af583126ce625ee070700f5e22a8335e1dc4c | disco-lang/disco | Parsing2.hs | Version 1 , 18 Oct 2016
This is just like , but re - exports the general versions of
operators like ( < * > ) and so on from the Prelude , instead of
Parser - specific versions .
# OPTIONS_GHC -fno - warn - missing - signatures #
module Parsing2
* Lexing
TokenParser, makeTokenParser, emptyDef, GenLanguageDef(..)
, getIdentifier, getReserved, getReservedOp
, getNatural, getInteger, getFloat, getNaturalOrFloat
, getSymbol
, getWhiteSpace, getParens, getAngles
-- * Parsing
, Parser, parse, parseFile, parseSome
, (<|>), (<$>), (<*>), (<$), (<*), (*>)
, module Text.Parsec.Expr
, module Text.Parsec.Combinator
, module Text.Parsec.Char
, try
)
where
import qualified Text.Parsec as P
import Text.Parsec.Char
import Text.Parsec.Combinator
import Text.Parsec.Expr hiding (Operator)
import Text.Parsec.Language (emptyDef)
import Text.Parsec.Pos
import Text.Parsec.Prim (Consumed (..), Reply (..), State (..),
runParsecT, try)
import Text.Parsec.String (Parser, parseFromFile)
import Text.Parsec.Token
import Control.Applicative
import Data.Functor.Identity
------------------------------------------------------------
Lexing
------------------------------------------------------------
getIdentifier = identifier
getReserved = reserved
getReservedOp = reservedOp
getNatural = natural
getInteger = integer
getFloat = float
getNaturalOrFloat = naturalOrFloat
getSymbol = symbol
getWhiteSpace = whiteSpace
getParens = parens
getAngles = angles
-- For more, see -3.1.11/docs/Text-Parsec-Token.html
------------------------------------------------------------
-- Parsing
------------------------------------------------------------
parse :: Parser a -> String -> Either P.ParseError a
parse p = P.parse p ""
parseFile :: Parser a -> FilePath -> IO (Either P.ParseError a)
parseFile = parseFromFile
parseSome :: Parser a -> String -> Either P.ParseError (a, String)
parseSome p s =
case runIdentity . getReply . runIdentity $ runParsecT p (State s (initialPos "") ()) of
Ok a (State rest _ _) _ -> Right (a, rest)
Error err -> Left err
where
getReply (Consumed r) = r
getReply (Empty r) = r
| null | https://raw.githubusercontent.com/disco-lang/disco/68b96b233b04f26229fe6277678eeb8710422523/explore/sub/Parsing2.hs | haskell | * Parsing
----------------------------------------------------------
----------------------------------------------------------
For more, see -3.1.11/docs/Text-Parsec-Token.html
----------------------------------------------------------
Parsing
---------------------------------------------------------- | Version 1 , 18 Oct 2016
This is just like , but re - exports the general versions of
operators like ( < * > ) and so on from the Prelude , instead of
Parser - specific versions .
# OPTIONS_GHC -fno - warn - missing - signatures #
module Parsing2
* Lexing
TokenParser, makeTokenParser, emptyDef, GenLanguageDef(..)
, getIdentifier, getReserved, getReservedOp
, getNatural, getInteger, getFloat, getNaturalOrFloat
, getSymbol
, getWhiteSpace, getParens, getAngles
, Parser, parse, parseFile, parseSome
, (<|>), (<$>), (<*>), (<$), (<*), (*>)
, module Text.Parsec.Expr
, module Text.Parsec.Combinator
, module Text.Parsec.Char
, try
)
where
import qualified Text.Parsec as P
import Text.Parsec.Char
import Text.Parsec.Combinator
import Text.Parsec.Expr hiding (Operator)
import Text.Parsec.Language (emptyDef)
import Text.Parsec.Pos
import Text.Parsec.Prim (Consumed (..), Reply (..), State (..),
runParsecT, try)
import Text.Parsec.String (Parser, parseFromFile)
import Text.Parsec.Token
import Control.Applicative
import Data.Functor.Identity
Lexing
getIdentifier = identifier
getReserved = reserved
getReservedOp = reservedOp
getNatural = natural
getInteger = integer
getFloat = float
getNaturalOrFloat = naturalOrFloat
getSymbol = symbol
getWhiteSpace = whiteSpace
getParens = parens
getAngles = angles
parse :: Parser a -> String -> Either P.ParseError a
parse p = P.parse p ""
parseFile :: Parser a -> FilePath -> IO (Either P.ParseError a)
parseFile = parseFromFile
parseSome :: Parser a -> String -> Either P.ParseError (a, String)
parseSome p s =
case runIdentity . getReply . runIdentity $ runParsecT p (State s (initialPos "") ()) of
Ok a (State rest _ _) _ -> Right (a, rest)
Error err -> Left err
where
getReply (Consumed r) = r
getReply (Empty r) = r
|
b819ddd1aabc1a298fcad5d4d8a12bd40ef2157b7455f2e2a92d7b7553c17261 | zippy/anansi | compose.cljs | (ns ss.compose
(:require [clojure.string :as string]
[ss.dom-helpers :as d]
[ss.debug :as debug]
[ss.utils :as u]
[ss.ui :as ui]
[ss.ss-utils :as ssu]
[ss.streamscapes :as sss]
[ss.ceptr :as ceptr]
[ss.state :as s]
))
(defn open
"displays the compose dialog"
[]
(let [scapes (:scapes s/*current-state*)]
(ui/modal-dialog "compose" "SETUP"
[
[:div [:h4 "Channels"]
(ui/make-button "New E-mail Channel" #(email-form :compose-work nil make-email))
(ui/make-button "New Twitter Channel" #(twitter-form :compose-work nil make-twitter))
(ui/make-button "New IRC Channel" #(irc-form :compose-work nil make-irc))
(ui/make-button "New XMPP Channel" #(xmpp-form :compose-work nil make-xmpp))
(ui/make-button "New Socket Channel" #(socket-form :compose-work nil make-socket))
]
(apply conj [:div.channels]
(map (fn [[cname caddr]]
(let [type (ssu/get-channel-type caddr)
chan ((keyword caddr) (:receptors s/*current-state*))
]
[:div.channel
(d/html (ssu/channel-icon-html cname type))
(ui/make-click-link (name cname)
(fn [] (condp = type
:irc (irc-form :compose-work
(assoc (get-vals-from-controller chan) :name (name cname))
(fn [p] (update-channel caddr p)))
:xmpp (xmpp-form :compose-work
(assoc (get-vals-from-controller chan) :name (name cname))
(fn [p] (update-channel caddr p)))
:email (email-form :compose-work
(assoc (get-email-vals chan) :name (name cname))
(fn [p] (update-email caddr p))
)
:twitter (twitter-form :compose-work
(assoc (get-vals-from-controller chan) :name (name cname))
(fn [p] (update-channel caddr p)))
:socket (twitter-form :compose-work
(assoc (get-vals-from-controller chan) :name (name cname))
(fn [p] (update-channel caddr p)))
(js/alert "Updating not implemented for this channel!"))
)
)
[:p.delete (ui/make-click-link "delete" #(delete-channel cname)) ]
]))
(filter (fn [[n _]] (not= n :streamscapes)) (:values (:channel-scape scapes))))
)
[:div#compose-work {:style "display:none"} ""]
[:div [:h4 "Scapes"]
(ui/make-button "New Scape" #(make-scape :scape-work))
(into [:div.my-scapes]
(map (fn [sn] (let [{key-rel :key value-rel :address} (:relationship ((keyword (str (name sn) "-scape")) scapes))]
(debug/alert (sn scapes))
[:p (str (name sn) ": " key-rel "->" value-rel " ")
(ui/make-button "Add Scape Entry" #(set-scape sn key-rel value-rel :scape-work))
])) (keys (:values (:my-scapes-scape scapes)))))]
[:div#scape-work {:style "display:none"} ""]
[:div [:h4 "Tags"]
(ui/make-button "New Tag" #(tag-form :tag-work nil))
(apply conj [:div.my-tags] (map (fn [tag-name] [:p.tag (ui/make-click-link tag-name #(tag-form :tag-work tag-name))
[:p.delete (ui/make-click-link "delete"
#(delete-tag tag-name)) ]])
(filter #(not (= % "touched")) (vals (:values (:tag-scapes-scape scapes))))))
]
[:div#tag-work {:style "display:none"} ""]]
)))
(defn delete-channel [cname]
(ui/confirm-dialog (str "All droplets associated with this channel will be deleted! Are you sure you want to delete the channel: " cname "?")
(fn [e] (if (= (.key e) "ok")
(ssu/send-ss-signal {:aspect "setup" :signal "delete-channel"
:params {:name cname}} sss/refresh-stream-callback)))))
(defn delete-tag [tag-name]
(ui/confirm-dialog (str "Are you sure you want to delete the tag: " tag-name)
(fn [e] (if (= (.key e) "ok")
(let [tag-scape-name (build-tag-scape-name tag-name)]
(ceptr/start-chain
{:cleanup sss/refresh-stream
:error (fn [result] (js/alert (str "Server reported error:" result)))
:chain [
(fn [result chain]
(ssu/send-ss-signal {:aspect "setup" :signal "delete-scape"
:params {:name tag-scape-name :relationship {:key "droplet-address" :address "boolean"}}} (ceptr/nextc chain)))
(fn [result chain]
(ssu/send-ss-signal {:aspect "scape" :signal "delete"
:params {:name :tag-scapes :key tag-scape-name}} (ceptr/nextc chain)))]}))))))
(defn get-vals-from-controller [chan]
(let [a (keyword (first (-> chan :scapes :controller-scape :values :controller)))]
(-> chan :receptors a)))
(defn get-email-vals [chan]
(let [oa (keyword (first (-> chan :scapes :deliverer-scape :values :deliverer)))
ia (keyword (first (-> chan :scapes :receiver-scape :values :receiver)))
i (-> chan :receptors ia)
o (-> chan :receptors oa)
fs ["host" "account" "password" "protocol" "port"]
]
(merge (into {} (map (fn [f] [(keyword (str "in-" f)) ((keyword f) i)]) fs))
(map (fn [f] [(keyword (str "out-" f)) ((keyword f) o)]) fs)
)))
(defn do-make-scape [{scape-name :scape-name key-rel :key-rel val-rel :value-rel}]
(ceptr/start-chain
{:cleanup sss/refresh-stream
:error (fn [result] (js/alert (str "Server reported error:" result)))
:chain [
(fn [result chain]
(ssu/send-ss-signal {:aspect "setup" :signal "new-scape"
:params {:name scape-name :relationship {:key key-rel :address val-rel}}} (ceptr/nextc chain)))
(fn [result chain]
(ssu/send-ss-signal {:aspect "scape" :signal "set"
:params {:name "my-scapes" :key scape-name :address true}} (ceptr/nextc chain)))]}))
(defn make-scape [parent-id]
(ui/make-dialog parent-id
[{:field :scape-name :label "Scape Name" :hint "name should be singular"}
{:field :key-rel :label "Key Relationship" :hint "dash-separated-type"}
{:field :value-rel :label "Value Relationship" :hint "dash-separated-type"}]
do-make-scape)
)
(defn build-tag-scape-name [tag-name]
(str (string/replace (string/replace (string/lower-case tag-name) #"\W"+ "-") #"[^a-zA-Z0-9_-]" "X") "-tag")
)
(defn make-tag [{tag-name :tag-name}]
(let [tag-scape-name (build-tag-scape-name tag-name)]
(ceptr/start-chain
{:cleanup sss/refresh-stream
:error (fn [result] (js/alert (str "Server reported error:" result)))
:chain [
(fn [result chain]
(ssu/send-ss-signal {:aspect "setup" :signal "new-scape"
:params {:name tag-scape-name :relationship {:key "droplet-address" :address "boolean"}}} (ceptr/nextc chain)))
(fn [result chain]
(ssu/send-ss-signal {:aspect "scape" :signal "set"
:params {:name :tag-scapes :key tag-scape-name :address tag-name}} (ceptr/nextc chain)))
]})))
(defn update-tag [orig-name {tag-name :tag-name}]
(if (not (= orig-name tag-name))
(let [orig-tag-scape-name (build-tag-scape-name orig-name)
tag-scape-name (build-tag-scape-name tag-name)]
(ceptr/start-chain
{:cleanup sss/refresh-stream
:error (fn [result] (js/alert (str "Server reported error:" result)))
:chain [
(fn [result chain]
(ssu/send-ss-signal {:aspect "setup" :signal "rename-scape"
:params {:name orig-tag-scape-name :new-name tag-scape-name}} (ceptr/nextc chain)))
(fn [result chain]
(ssu/send-ss-signal {:aspect "scape" :signal "delete"
:params {:name :tag-scapes :key orig-tag-scape-name}} (ceptr/nextc chain)))
(fn [result chain]
(ssu/send-ss-signal {:aspect "scape" :signal "set"
:params {:name :tag-scapes :key tag-scape-name :address tag-name}} (ceptr/nextc chain)))
]}))))
(defn tag-form [parent-id name]
(ui/make-dialog parent-id
[{:field :tag-name :default name :label "Tag Name"}]
(if (nil? name) make-tag #(update-tag name %)))
)
(defn do-set-scape [scape-name {key :key-val val :value-val}]
(ssu/send-ss-signal {:aspect "scape" :signal "set"
:params {:name scape-name :key key :address val}} sss/refresh-stream-callback))
(defn set-scape [scape-name key-rel val-rel parent-id]
(ui/make-dialog parent-id
[{:field :key-val :label "Key" :hint key-rel}
{:field :value-val :label "Value" :hint val-rel}]
(fn [p] (do-set-scape scape-name p))))
(defn make-twitter [p]
(let [q (:search-query p)
params {:type :twitter
:name (if (u/blank? (:name p)) (str "twitter-" q) (:name p))
:search-query q}]
(ssu/send-ss-signal {:aspect "setup" :signal "new-channel"
:params params} sss/refresh-stream-callback)))
(defn twitter-form [parent-id defs fun]
(let [defaults (if (nil? defs)
{:search-query "metacurrency"}
defs)]
(ui/make-dialog parent-id
[{:field :name :default (:name defaults) :label "Channel Name:" :hint "<twitter search>"}
{:field :search-query :default (:search-query defaults) :label "Twitter search query"}]
fun)))
(defn make-irc [params]
(ssu/send-ss-signal {:aspect "setup" :signal "new-channel"
:params (merge {:type :irc :contact-address (s/get-my-contact-address)} params)} sss/refresh-stream-callback))
(defn make-xmpp [params]
(ssu/send-ss-signal {:aspect "setup" :signal "new-channel"
:params (merge {:type :xmpp :contact-address (s/get-my-contact-address)} params)} sss/refresh-stream-callback))
(defn make-socket [params]
(ssu/send-ss-signal {:aspect "setup" :signal "new-channel"
:params (merge {:type :socket} params)} sss/refresh-stream-callback))
(defn update-channel [channel-address params]
(ssu/send-ss-signal {:aspect "setup" :signal "update-channel"
:params (assoc params :channel-address channel-address)} sss/refresh-stream-callback))
(defn irc-form [parent-id defs fun]
(let [defaults (if (nil? defs)
{:name "irc-freenode" :host "irc.freenode.net" :port 6667 :user "Eric" :nick "erichb"}
defs
) ]
(ui/make-dialog parent-id
[{:field :name :default (:name defaults) :label "Channel Name:"}
{:field :host :default (:host defaults) :label "IRC host:"}
{:field :port :default (:port defaults) :label "Port:"}
{:field :user :default (:user defaults) :label "IRC User" :hint "<your user name>"}
{:field :nick :default (:nick defaults) :label "IRC Nick" :hint "<your nick>"}
]
fun
)))
(defn xmpp-form [parent-id defs fun]
(let [defaults (if (nil? defs)
{:name "jabber" :host "jabber.org" :domain "jabber.org"}
defs
) ]
(ui/make-dialog parent-id
[{:field :name :default (:name defaults) :label "Channel Name:"}
{:field :host :default (:host defaults) :label "Jabber host:"}
{:field :domain :default (:domain defaults) :label "Domain:"}
{:field :username :default (:username defaults) :label "Username" :hint "<your jabber user name>"}
{:field :password :default (:password defaults) :label "Password" :hint "<your password>"}
]
fun
)))
(defn socket-form [parent-id defs fun]
(let [defaults (if (nil? defs)
{:name "a-socket" :port 31415}
defs
) ]
(ui/make-dialog parent-id
[{:field :name :default (:name defaults) :label "Channel Name:"}
{:field :port :default (:port defaults) :label "Port:"}
]
fun
)))
(defn update-email [channel-address p]
(let [params {:in {:host (:in-host p) :account (:in-account p) :password (:in-password p) :protocol (:in-protocol p) :port (:in-port p)}
:out {:host (:out-host p) :account (:out-account p) :password (:out-password p) :protocol (:out-protocol p) :port (:out-port p)}}]
(ssu/send-ss-signal {:aspect "setup" :signal "update-channel"
:params (assoc params :channel-address channel-address :name (:name p))} sss/refresh-stream-callback)))
(defn make-email [p]
(let [params {:type :email :name (:name p)
:in {:host (:in-host p) :account (:in-account p) :password (:in-password p) :protocol (:in-protocol p) :port (:in-port p)}
:out {:host (:out-host p) :account (:out-account p) :password (:out-password p) :protocol (:out-protocol p) :port (:out-port p)}}]
(ssu/send-ss-signal {:aspect "setup" :signal "new-channel"
:params params} sss/refresh-stream-callback)))
(defn email-form [parent-id defs fun]
(let [defaults (if (nil? defs)
{:name "gmail" :in-host "imap.gmail.com" :in-protocol "imaps" :in-port ""
:out-host "smtp.googlemail.com" :out-protocol "smtps" :out-port 465}
defs
) ]
(ui/make-dialog parent-id
[{:field :name :default (:name defaults) :label "Channel Name:"}
{:field :in-host :default (:in-host defaults) :label "Incoming Mail server host:"}
{:field :in-account :default (:in-account defaults) :hint "<email address>" :label "Incoming Mail server account:"}
{:field :in-password :hint "<your password>" :label "Password:"}
{:field :in-protocol :default (:in-protocol defaults) :hint "<pop3 or imaps>" :label "Incoming Mail sever protocol:"}
{:field :in-port :default (:in-port defaults) :label "Incoming Mail sever port:"}
{:field :out-host :default (:out-host defaults) :label "Outgoing Mail server host:"}
{:field :out-account :default (:out-account defaults) :hint "<email>" :label "Outgoing Mail server account:"}
{:field :out-password :hint "<password>" :label "Password:"}
{:field :out-protocol :default (:out-protocol defaults) :label "Outgoing Mail sever protocol:"}
{:field :out-port :default (:in-port defaults) :label "Outgoing Mail sever port:"}
]
fun)))
| null | https://raw.githubusercontent.com/zippy/anansi/881aa279e5e7836f3002fc2ef7623f2ee1860c9a/public/ss/src/compose.cljs | clojure | (ns ss.compose
(:require [clojure.string :as string]
[ss.dom-helpers :as d]
[ss.debug :as debug]
[ss.utils :as u]
[ss.ui :as ui]
[ss.ss-utils :as ssu]
[ss.streamscapes :as sss]
[ss.ceptr :as ceptr]
[ss.state :as s]
))
(defn open
"displays the compose dialog"
[]
(let [scapes (:scapes s/*current-state*)]
(ui/modal-dialog "compose" "SETUP"
[
[:div [:h4 "Channels"]
(ui/make-button "New E-mail Channel" #(email-form :compose-work nil make-email))
(ui/make-button "New Twitter Channel" #(twitter-form :compose-work nil make-twitter))
(ui/make-button "New IRC Channel" #(irc-form :compose-work nil make-irc))
(ui/make-button "New XMPP Channel" #(xmpp-form :compose-work nil make-xmpp))
(ui/make-button "New Socket Channel" #(socket-form :compose-work nil make-socket))
]
(apply conj [:div.channels]
(map (fn [[cname caddr]]
(let [type (ssu/get-channel-type caddr)
chan ((keyword caddr) (:receptors s/*current-state*))
]
[:div.channel
(d/html (ssu/channel-icon-html cname type))
(ui/make-click-link (name cname)
(fn [] (condp = type
:irc (irc-form :compose-work
(assoc (get-vals-from-controller chan) :name (name cname))
(fn [p] (update-channel caddr p)))
:xmpp (xmpp-form :compose-work
(assoc (get-vals-from-controller chan) :name (name cname))
(fn [p] (update-channel caddr p)))
:email (email-form :compose-work
(assoc (get-email-vals chan) :name (name cname))
(fn [p] (update-email caddr p))
)
:twitter (twitter-form :compose-work
(assoc (get-vals-from-controller chan) :name (name cname))
(fn [p] (update-channel caddr p)))
:socket (twitter-form :compose-work
(assoc (get-vals-from-controller chan) :name (name cname))
(fn [p] (update-channel caddr p)))
(js/alert "Updating not implemented for this channel!"))
)
)
[:p.delete (ui/make-click-link "delete" #(delete-channel cname)) ]
]))
(filter (fn [[n _]] (not= n :streamscapes)) (:values (:channel-scape scapes))))
)
[:div#compose-work {:style "display:none"} ""]
[:div [:h4 "Scapes"]
(ui/make-button "New Scape" #(make-scape :scape-work))
(into [:div.my-scapes]
(map (fn [sn] (let [{key-rel :key value-rel :address} (:relationship ((keyword (str (name sn) "-scape")) scapes))]
(debug/alert (sn scapes))
[:p (str (name sn) ": " key-rel "->" value-rel " ")
(ui/make-button "Add Scape Entry" #(set-scape sn key-rel value-rel :scape-work))
])) (keys (:values (:my-scapes-scape scapes)))))]
[:div#scape-work {:style "display:none"} ""]
[:div [:h4 "Tags"]
(ui/make-button "New Tag" #(tag-form :tag-work nil))
(apply conj [:div.my-tags] (map (fn [tag-name] [:p.tag (ui/make-click-link tag-name #(tag-form :tag-work tag-name))
[:p.delete (ui/make-click-link "delete"
#(delete-tag tag-name)) ]])
(filter #(not (= % "touched")) (vals (:values (:tag-scapes-scape scapes))))))
]
[:div#tag-work {:style "display:none"} ""]]
)))
(defn delete-channel [cname]
(ui/confirm-dialog (str "All droplets associated with this channel will be deleted! Are you sure you want to delete the channel: " cname "?")
(fn [e] (if (= (.key e) "ok")
(ssu/send-ss-signal {:aspect "setup" :signal "delete-channel"
:params {:name cname}} sss/refresh-stream-callback)))))
(defn delete-tag [tag-name]
(ui/confirm-dialog (str "Are you sure you want to delete the tag: " tag-name)
(fn [e] (if (= (.key e) "ok")
(let [tag-scape-name (build-tag-scape-name tag-name)]
(ceptr/start-chain
{:cleanup sss/refresh-stream
:error (fn [result] (js/alert (str "Server reported error:" result)))
:chain [
(fn [result chain]
(ssu/send-ss-signal {:aspect "setup" :signal "delete-scape"
:params {:name tag-scape-name :relationship {:key "droplet-address" :address "boolean"}}} (ceptr/nextc chain)))
(fn [result chain]
(ssu/send-ss-signal {:aspect "scape" :signal "delete"
:params {:name :tag-scapes :key tag-scape-name}} (ceptr/nextc chain)))]}))))))
(defn get-vals-from-controller [chan]
(let [a (keyword (first (-> chan :scapes :controller-scape :values :controller)))]
(-> chan :receptors a)))
(defn get-email-vals [chan]
(let [oa (keyword (first (-> chan :scapes :deliverer-scape :values :deliverer)))
ia (keyword (first (-> chan :scapes :receiver-scape :values :receiver)))
i (-> chan :receptors ia)
o (-> chan :receptors oa)
fs ["host" "account" "password" "protocol" "port"]
]
(merge (into {} (map (fn [f] [(keyword (str "in-" f)) ((keyword f) i)]) fs))
(map (fn [f] [(keyword (str "out-" f)) ((keyword f) o)]) fs)
)))
(defn do-make-scape [{scape-name :scape-name key-rel :key-rel val-rel :value-rel}]
(ceptr/start-chain
{:cleanup sss/refresh-stream
:error (fn [result] (js/alert (str "Server reported error:" result)))
:chain [
(fn [result chain]
(ssu/send-ss-signal {:aspect "setup" :signal "new-scape"
:params {:name scape-name :relationship {:key key-rel :address val-rel}}} (ceptr/nextc chain)))
(fn [result chain]
(ssu/send-ss-signal {:aspect "scape" :signal "set"
:params {:name "my-scapes" :key scape-name :address true}} (ceptr/nextc chain)))]}))
(defn make-scape [parent-id]
(ui/make-dialog parent-id
[{:field :scape-name :label "Scape Name" :hint "name should be singular"}
{:field :key-rel :label "Key Relationship" :hint "dash-separated-type"}
{:field :value-rel :label "Value Relationship" :hint "dash-separated-type"}]
do-make-scape)
)
(defn build-tag-scape-name [tag-name]
(str (string/replace (string/replace (string/lower-case tag-name) #"\W"+ "-") #"[^a-zA-Z0-9_-]" "X") "-tag")
)
(defn make-tag [{tag-name :tag-name}]
(let [tag-scape-name (build-tag-scape-name tag-name)]
(ceptr/start-chain
{:cleanup sss/refresh-stream
:error (fn [result] (js/alert (str "Server reported error:" result)))
:chain [
(fn [result chain]
(ssu/send-ss-signal {:aspect "setup" :signal "new-scape"
:params {:name tag-scape-name :relationship {:key "droplet-address" :address "boolean"}}} (ceptr/nextc chain)))
(fn [result chain]
(ssu/send-ss-signal {:aspect "scape" :signal "set"
:params {:name :tag-scapes :key tag-scape-name :address tag-name}} (ceptr/nextc chain)))
]})))
(defn update-tag [orig-name {tag-name :tag-name}]
(if (not (= orig-name tag-name))
(let [orig-tag-scape-name (build-tag-scape-name orig-name)
tag-scape-name (build-tag-scape-name tag-name)]
(ceptr/start-chain
{:cleanup sss/refresh-stream
:error (fn [result] (js/alert (str "Server reported error:" result)))
:chain [
(fn [result chain]
(ssu/send-ss-signal {:aspect "setup" :signal "rename-scape"
:params {:name orig-tag-scape-name :new-name tag-scape-name}} (ceptr/nextc chain)))
(fn [result chain]
(ssu/send-ss-signal {:aspect "scape" :signal "delete"
:params {:name :tag-scapes :key orig-tag-scape-name}} (ceptr/nextc chain)))
(fn [result chain]
(ssu/send-ss-signal {:aspect "scape" :signal "set"
:params {:name :tag-scapes :key tag-scape-name :address tag-name}} (ceptr/nextc chain)))
]}))))
(defn tag-form [parent-id name]
(ui/make-dialog parent-id
[{:field :tag-name :default name :label "Tag Name"}]
(if (nil? name) make-tag #(update-tag name %)))
)
(defn do-set-scape [scape-name {key :key-val val :value-val}]
(ssu/send-ss-signal {:aspect "scape" :signal "set"
:params {:name scape-name :key key :address val}} sss/refresh-stream-callback))
(defn set-scape [scape-name key-rel val-rel parent-id]
(ui/make-dialog parent-id
[{:field :key-val :label "Key" :hint key-rel}
{:field :value-val :label "Value" :hint val-rel}]
(fn [p] (do-set-scape scape-name p))))
(defn make-twitter [p]
(let [q (:search-query p)
params {:type :twitter
:name (if (u/blank? (:name p)) (str "twitter-" q) (:name p))
:search-query q}]
(ssu/send-ss-signal {:aspect "setup" :signal "new-channel"
:params params} sss/refresh-stream-callback)))
(defn twitter-form [parent-id defs fun]
(let [defaults (if (nil? defs)
{:search-query "metacurrency"}
defs)]
(ui/make-dialog parent-id
[{:field :name :default (:name defaults) :label "Channel Name:" :hint "<twitter search>"}
{:field :search-query :default (:search-query defaults) :label "Twitter search query"}]
fun)))
(defn make-irc [params]
(ssu/send-ss-signal {:aspect "setup" :signal "new-channel"
:params (merge {:type :irc :contact-address (s/get-my-contact-address)} params)} sss/refresh-stream-callback))
(defn make-xmpp [params]
(ssu/send-ss-signal {:aspect "setup" :signal "new-channel"
:params (merge {:type :xmpp :contact-address (s/get-my-contact-address)} params)} sss/refresh-stream-callback))
(defn make-socket [params]
(ssu/send-ss-signal {:aspect "setup" :signal "new-channel"
:params (merge {:type :socket} params)} sss/refresh-stream-callback))
(defn update-channel [channel-address params]
(ssu/send-ss-signal {:aspect "setup" :signal "update-channel"
:params (assoc params :channel-address channel-address)} sss/refresh-stream-callback))
(defn irc-form [parent-id defs fun]
(let [defaults (if (nil? defs)
{:name "irc-freenode" :host "irc.freenode.net" :port 6667 :user "Eric" :nick "erichb"}
defs
) ]
(ui/make-dialog parent-id
[{:field :name :default (:name defaults) :label "Channel Name:"}
{:field :host :default (:host defaults) :label "IRC host:"}
{:field :port :default (:port defaults) :label "Port:"}
{:field :user :default (:user defaults) :label "IRC User" :hint "<your user name>"}
{:field :nick :default (:nick defaults) :label "IRC Nick" :hint "<your nick>"}
]
fun
)))
(defn xmpp-form [parent-id defs fun]
(let [defaults (if (nil? defs)
{:name "jabber" :host "jabber.org" :domain "jabber.org"}
defs
) ]
(ui/make-dialog parent-id
[{:field :name :default (:name defaults) :label "Channel Name:"}
{:field :host :default (:host defaults) :label "Jabber host:"}
{:field :domain :default (:domain defaults) :label "Domain:"}
{:field :username :default (:username defaults) :label "Username" :hint "<your jabber user name>"}
{:field :password :default (:password defaults) :label "Password" :hint "<your password>"}
]
fun
)))
(defn socket-form [parent-id defs fun]
(let [defaults (if (nil? defs)
{:name "a-socket" :port 31415}
defs
) ]
(ui/make-dialog parent-id
[{:field :name :default (:name defaults) :label "Channel Name:"}
{:field :port :default (:port defaults) :label "Port:"}
]
fun
)))
(defn update-email [channel-address p]
(let [params {:in {:host (:in-host p) :account (:in-account p) :password (:in-password p) :protocol (:in-protocol p) :port (:in-port p)}
:out {:host (:out-host p) :account (:out-account p) :password (:out-password p) :protocol (:out-protocol p) :port (:out-port p)}}]
(ssu/send-ss-signal {:aspect "setup" :signal "update-channel"
:params (assoc params :channel-address channel-address :name (:name p))} sss/refresh-stream-callback)))
(defn make-email [p]
(let [params {:type :email :name (:name p)
:in {:host (:in-host p) :account (:in-account p) :password (:in-password p) :protocol (:in-protocol p) :port (:in-port p)}
:out {:host (:out-host p) :account (:out-account p) :password (:out-password p) :protocol (:out-protocol p) :port (:out-port p)}}]
(ssu/send-ss-signal {:aspect "setup" :signal "new-channel"
:params params} sss/refresh-stream-callback)))
(defn email-form [parent-id defs fun]
(let [defaults (if (nil? defs)
{:name "gmail" :in-host "imap.gmail.com" :in-protocol "imaps" :in-port ""
:out-host "smtp.googlemail.com" :out-protocol "smtps" :out-port 465}
defs
) ]
(ui/make-dialog parent-id
[{:field :name :default (:name defaults) :label "Channel Name:"}
{:field :in-host :default (:in-host defaults) :label "Incoming Mail server host:"}
{:field :in-account :default (:in-account defaults) :hint "<email address>" :label "Incoming Mail server account:"}
{:field :in-password :hint "<your password>" :label "Password:"}
{:field :in-protocol :default (:in-protocol defaults) :hint "<pop3 or imaps>" :label "Incoming Mail sever protocol:"}
{:field :in-port :default (:in-port defaults) :label "Incoming Mail sever port:"}
{:field :out-host :default (:out-host defaults) :label "Outgoing Mail server host:"}
{:field :out-account :default (:out-account defaults) :hint "<email>" :label "Outgoing Mail server account:"}
{:field :out-password :hint "<password>" :label "Password:"}
{:field :out-protocol :default (:out-protocol defaults) :label "Outgoing Mail sever protocol:"}
{:field :out-port :default (:in-port defaults) :label "Outgoing Mail sever port:"}
]
fun)))
| |
7f06de130b2b763f4a9c1d9e6dd5ef90b6de1c401e4b4b477bc9051a9d1ef92c | plumatic/grab-bag | cache_test.clj | (ns plumbing.cache-test
(:use plumbing.core clojure.test plumbing.cache plumbing.test)
(:require
[plumbing.parallel :as parallel]))
(set! *warn-on-reflection* true)
(deftest strong-interner-test
(let [i (strong-interner :key)
v1 {:key 1 :val 10}
v2 {:key 2 :val 20}]
(is (identical? v1 (i v1)))
(is (identical? v2 (i v2)))
(is (identical? v1 (i {:key 1})))))
(deftest ^{:unit true} bounded-memoize-test
(let [op-count (atom 0)
c (bounded-memoize 2 #(do (swap! op-count inc) (inc %)))]
(is (= (c 1) 2))
(is (= (c 2) 3))
(is (= @op-count 2))
(is (= (c 1) 2))
(is (= (c 2) 3))
(is (= @op-count 2))
(is (= (c 3) 4))
(is (= (c 2) 3))
(is (= @op-count 3))
(is (= (c 1) 2))
(is (= (c 2) 3))
(is (= @op-count 4))))
(deftest bounded-memoize-nil-test
(is (thrown? Exception ((bounded-memoize 2 identity) nil))))
(deftest volatile-bounded-memoize-test
(testing "entries expire"
(let [state (atom {})
f (fn [x] (get (swap! state update x conj x) x))
mem-f (volatile-bounded-memoize 5 100 f)]
(testing "soon enough"
(is (= (mem-f 1) '(1)))
(Thread/sleep 100)
(is (= (mem-f 1) '(1 1))))
(testing "but not too soon"
(is (= (mem-f 5)
(mem-f 5)
'(5))))))
(testing "entries evict"
(let [state (atom 0)
f (fn [_] (swap! state inc))
mem-f (volatile-bounded-memoize 10 50000 f)]
(is-= (for [i (range 1 11)]
(mem-f i))
(range 1 11))
(is-= (for [i (range 1 11)]
(mem-f i))
(range 1 11))
(is (= (mem-f 50) 11))
(is (= (mem-f 1) 12))))
(testing "don't cache nil"
(let [state (atom nil)
f (fn [x] @state)
mem-f (volatile-bounded-memoize 100 100000 f)
present-result (fn [result input]
(reset! state result)
(mem-f input))]
(is (= nil (present-result nil 0)))
(is (= 5 (present-result 5 0)))
(is (= 5 (present-result 4 0)))
(is (= 5 (present-result nil 0)))))
(testing "handle key functions"
(let [f (fnk [mem-arg result]
result)
mem-f (volatile-bounded-memoize 100 100000 f :mem-arg)]
(is (= 5 (mem-f {:mem-arg 0 :result 5})))
(is (= 5 (mem-f {:mem-arg 0 :result 3})))
(is (= 3 (mem-f {:mem-arg 1 :result 3}))))))
(deftest thread-local-test
(let [r (atom 0)
a (thread-local #(atom 1))
ts (repeatedly 10 #(doto (Thread. ^Runnable (fn [] (swap! @a inc) (swap! r + @@a))) (.start)))]
(doseq [^Thread t ts] (.join t))
(is (= @r 20))))
(deftest cache-with-test
(let [m (java.util.HashMap.)
computed (atom 0)]
(parallel/do-work
10
#(cache-with m % (do (Thread/sleep 1) (swap! computed inc) (* % 10)))
(shuffle (apply concat (repeat 10 (range 100)))))
(is (= @computed 100))
(is-= (map-vals deref m)
(for-map [i (range 100)] i (* i 10)))))
(set! *warn-on-reflection* false)
| null | https://raw.githubusercontent.com/plumatic/grab-bag/a15e943322fbbf6f00790ce5614ba6f90de1a9b5/lib/plumbing/test/plumbing/cache_test.clj | clojure | (ns plumbing.cache-test
(:use plumbing.core clojure.test plumbing.cache plumbing.test)
(:require
[plumbing.parallel :as parallel]))
(set! *warn-on-reflection* true)
(deftest strong-interner-test
(let [i (strong-interner :key)
v1 {:key 1 :val 10}
v2 {:key 2 :val 20}]
(is (identical? v1 (i v1)))
(is (identical? v2 (i v2)))
(is (identical? v1 (i {:key 1})))))
(deftest ^{:unit true} bounded-memoize-test
(let [op-count (atom 0)
c (bounded-memoize 2 #(do (swap! op-count inc) (inc %)))]
(is (= (c 1) 2))
(is (= (c 2) 3))
(is (= @op-count 2))
(is (= (c 1) 2))
(is (= (c 2) 3))
(is (= @op-count 2))
(is (= (c 3) 4))
(is (= (c 2) 3))
(is (= @op-count 3))
(is (= (c 1) 2))
(is (= (c 2) 3))
(is (= @op-count 4))))
(deftest bounded-memoize-nil-test
(is (thrown? Exception ((bounded-memoize 2 identity) nil))))
(deftest volatile-bounded-memoize-test
(testing "entries expire"
(let [state (atom {})
f (fn [x] (get (swap! state update x conj x) x))
mem-f (volatile-bounded-memoize 5 100 f)]
(testing "soon enough"
(is (= (mem-f 1) '(1)))
(Thread/sleep 100)
(is (= (mem-f 1) '(1 1))))
(testing "but not too soon"
(is (= (mem-f 5)
(mem-f 5)
'(5))))))
(testing "entries evict"
(let [state (atom 0)
f (fn [_] (swap! state inc))
mem-f (volatile-bounded-memoize 10 50000 f)]
(is-= (for [i (range 1 11)]
(mem-f i))
(range 1 11))
(is-= (for [i (range 1 11)]
(mem-f i))
(range 1 11))
(is (= (mem-f 50) 11))
(is (= (mem-f 1) 12))))
(testing "don't cache nil"
(let [state (atom nil)
f (fn [x] @state)
mem-f (volatile-bounded-memoize 100 100000 f)
present-result (fn [result input]
(reset! state result)
(mem-f input))]
(is (= nil (present-result nil 0)))
(is (= 5 (present-result 5 0)))
(is (= 5 (present-result 4 0)))
(is (= 5 (present-result nil 0)))))
(testing "handle key functions"
(let [f (fnk [mem-arg result]
result)
mem-f (volatile-bounded-memoize 100 100000 f :mem-arg)]
(is (= 5 (mem-f {:mem-arg 0 :result 5})))
(is (= 5 (mem-f {:mem-arg 0 :result 3})))
(is (= 3 (mem-f {:mem-arg 1 :result 3}))))))
(deftest thread-local-test
(let [r (atom 0)
a (thread-local #(atom 1))
ts (repeatedly 10 #(doto (Thread. ^Runnable (fn [] (swap! @a inc) (swap! r + @@a))) (.start)))]
(doseq [^Thread t ts] (.join t))
(is (= @r 20))))
(deftest cache-with-test
(let [m (java.util.HashMap.)
computed (atom 0)]
(parallel/do-work
10
#(cache-with m % (do (Thread/sleep 1) (swap! computed inc) (* % 10)))
(shuffle (apply concat (repeat 10 (range 100)))))
(is (= @computed 100))
(is-= (map-vals deref m)
(for-map [i (range 100)] i (* i 10)))))
(set! *warn-on-reflection* false)
| |
dc81adf419936f0e5663a69c4a230f2e273ace017d4127bb4ed6b9dbf750290d | pariyatti/kosa | views.clj | (ns kosa.mobile.today.pali-word.views
(:require [clojure.string :as str]
[hiccup2.core :as h]
[hiccup.form :as f]
[kosa.config :as config]
[kosa.layouts.mobile :as p]
[kosa.views :as v]))
(defn show-index-preview [card]
[:div {:class "card-index-content flex"}
[:table
[:tr
[:td "Pali Word:"]
[:td (:pali-word/pali card)]]
(for [t (:pali-word/translations card)]
(when-not (str/blank? (second t))
[:tr
[:td (first t)]
[:td (second t)]]))]
[:ul {:class "card-action-links"}
[:li {:class "card-action-link"} "Show"]
[:li {:class "card-action-link"} "Edit"]
[:li {:class "card-action-link"} "Destroy"]]])
(defn index [req cards]
(p/app req "Pali Word Card Index"
[:p {:id "notice"}
"<%= notice %>"]
[:div {:class "page-heading"}
[:div {:class "breadcrumb"}
[:a {:href (v/index-path req :mobile)}
[:clr-icon {:shape "grid-view" :size "24"}]
" Back to Mobile Admin"]]
[:div {:class "header-and-link flex"}
[:h1 {:class "page-header"} "Pali Cards"]
[:a {:href (v/new-path req :pali-words)}
[:clr-icon {:shape "plus-circle" :size "24"}]
" Create Pali Word Card"]]]
(for [card cards]
(show-index-preview card))))
(defn show* [card]
(h/html
[:table
[:tr
[:td "Pali Word:"]
[:td (:pali-word/pali card)]]
(for [t (:pali-word/translations card)]
[:tr
[:td (first t)]
[:td (second t)]])]))
(defn show [req card]
(p/app req "Show Pali Word Card"
(show* card)
[:ul {:class "card-action-links"}
[:li {:class "card-action-link"} "Edit"]
[:li {:class "card-action-link"} "Destroy"]]
[:a {:href (v/index-path req :pali-words)} "Go Back"]))
(defn new-form [req]
(f/form-to [:post (v/create-path req :pali-words)]
[:div {:class "field"}
(f/hidden-field :kuti/type :pali-word)]
[:a {:href "#"
:onclick "document.getElementById('defaults').classList.toggle('form-defaults-hidden');"}
"Show / Hide Defaults"]
[:div#defaults {:class "form-defaults-hidden"}
[:div {:class "field"}
(f/label :pali-word/header "Header")
(f/text-field :pali-word/header "Pali Word")]]
[:div {:class "field"}
(f/label :pali-word/pali "Pali")
(f/text-field :pali-word/pali)]
[:div#translations-list
(for [lang (:supported-languages config/config)]
[:div
[:div {:class "field language"}
(f/text-field {:readonly "readonly"} :language lang)]
[:div {:class "field translation"}
(f/text-field :translation)]])]
;; TODO: include these fields also
;; [:div {:class "field"} "<%= form.label :audio_file, "Audio clip to upload:" %>\n <%= form.file_field :audio_file %>"]
[: div { : class " field " } " & lt;%= form.label : language % & gt;\n & lt;%= form.text_field : language % & gt ; " ]
[:div {:class "actions"}
(f/submit-button {:name "submit"} "Save")])
;; TODO: signal errors to user
" & lt;% if card.errors.any ? % & gt ; "
;; [:div {:id "error_explanation"}
[: h2 " & lt;%= pluralize(card.errors.count , & quot;error" ;) % & gt ; prohibited this card from being saved : " ]
[: ul " & lt;% card.errors.full_messages.each do |message| % & gt ; "
;; [:li "<%= message %>"]"<% end %>"]]
)
(defn new [req]
(p/app req "New Pali Word Card"
[:div {:class "page-heading"}
[:div {:class "breadcrumb"}
[:a {:href (v/index-path req :mobile)}
"Back to Mobile Admin"]]
[:div {:class "header-and-link flex"}
[:h1 {:class "page-header"} "New Pali Word Card"]]]
[:div {:class "form-and-preview flex row"}
(new-form req)
( show card ) ; ; TODO : requires javascript to do anything meaningful
]))
| null | https://raw.githubusercontent.com/pariyatti/kosa/68099ccb830b99a9d0ead81ccfd878ba72020e78/src/kosa/mobile/today/pali_word/views.clj | clojure | TODO: include these fields also
[:div {:class "field"} "<%= form.label :audio_file, "Audio clip to upload:" %>\n <%= form.file_field :audio_file %>"]
TODO: signal errors to user
[:div {:id "error_explanation"}
[:li "<%= message %>"]"<% end %>"]]
; TODO : requires javascript to do anything meaningful | (ns kosa.mobile.today.pali-word.views
(:require [clojure.string :as str]
[hiccup2.core :as h]
[hiccup.form :as f]
[kosa.config :as config]
[kosa.layouts.mobile :as p]
[kosa.views :as v]))
(defn show-index-preview [card]
[:div {:class "card-index-content flex"}
[:table
[:tr
[:td "Pali Word:"]
[:td (:pali-word/pali card)]]
(for [t (:pali-word/translations card)]
(when-not (str/blank? (second t))
[:tr
[:td (first t)]
[:td (second t)]]))]
[:ul {:class "card-action-links"}
[:li {:class "card-action-link"} "Show"]
[:li {:class "card-action-link"} "Edit"]
[:li {:class "card-action-link"} "Destroy"]]])
(defn index [req cards]
(p/app req "Pali Word Card Index"
[:p {:id "notice"}
"<%= notice %>"]
[:div {:class "page-heading"}
[:div {:class "breadcrumb"}
[:a {:href (v/index-path req :mobile)}
[:clr-icon {:shape "grid-view" :size "24"}]
" Back to Mobile Admin"]]
[:div {:class "header-and-link flex"}
[:h1 {:class "page-header"} "Pali Cards"]
[:a {:href (v/new-path req :pali-words)}
[:clr-icon {:shape "plus-circle" :size "24"}]
" Create Pali Word Card"]]]
(for [card cards]
(show-index-preview card))))
(defn show* [card]
(h/html
[:table
[:tr
[:td "Pali Word:"]
[:td (:pali-word/pali card)]]
(for [t (:pali-word/translations card)]
[:tr
[:td (first t)]
[:td (second t)]])]))
(defn show [req card]
(p/app req "Show Pali Word Card"
(show* card)
[:ul {:class "card-action-links"}
[:li {:class "card-action-link"} "Edit"]
[:li {:class "card-action-link"} "Destroy"]]
[:a {:href (v/index-path req :pali-words)} "Go Back"]))
(defn new-form [req]
(f/form-to [:post (v/create-path req :pali-words)]
[:div {:class "field"}
(f/hidden-field :kuti/type :pali-word)]
[:a {:href "#"
:onclick "document.getElementById('defaults').classList.toggle('form-defaults-hidden');"}
"Show / Hide Defaults"]
[:div#defaults {:class "form-defaults-hidden"}
[:div {:class "field"}
(f/label :pali-word/header "Header")
(f/text-field :pali-word/header "Pali Word")]]
[:div {:class "field"}
(f/label :pali-word/pali "Pali")
(f/text-field :pali-word/pali)]
[:div#translations-list
(for [lang (:supported-languages config/config)]
[:div
[:div {:class "field language"}
(f/text-field {:readonly "readonly"} :language lang)]
[:div {:class "field translation"}
(f/text-field :translation)]])]
[: div { : class " field " } " & lt;%= form.label : language % & gt;\n & lt;%= form.text_field : language % & gt ; " ]
[:div {:class "actions"}
(f/submit-button {:name "submit"} "Save")])
" & lt;% if card.errors.any ? % & gt ; "
[: h2 " & lt;%= pluralize(card.errors.count , & quot;error" ;) % & gt ; prohibited this card from being saved : " ]
[: ul " & lt;% card.errors.full_messages.each do |message| % & gt ; "
)
(defn new [req]
(p/app req "New Pali Word Card"
[:div {:class "page-heading"}
[:div {:class "breadcrumb"}
[:a {:href (v/index-path req :mobile)}
"Back to Mobile Admin"]]
[:div {:class "header-and-link flex"}
[:h1 {:class "page-header"} "New Pali Word Card"]]]
[:div {:class "form-and-preview flex row"}
(new-form req)
]))
|
95a155976722f20c6d2ca25c19acfd66d9db3481dd520864f83b7ddff7eece72 | Clojure2D/clojure2d-examples | ex38_old_school_xor.clj | (ns ex38-old-school-xor
(:require [clojure2d.core :refer :all]
[fastmath.core :as m]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(def cnvs (canvas 600 600 :mid))
(defn draw-rings
"Draw rings"
[canvas posx posy]
(dotimes [x 17]
(let [size (* (inc x) 80)]
(ellipse canvas posx posy size size true)))
canvas)
(defn draw
"Frames"
[canvas _ ^long fps _]
(let [t (/ fps 60.0)
sa (m/mnorm (m/qsin (* 0.5 t)) -1.0 1.0 100.0 500.0)
ca (m/mnorm (m/qcos t) -1.0 1.0 100.0 500.0)
sb (m/mnorm (m/qsin (inc t)) -1.0 1.0 100.0 500.0)
cb (m/mnorm (m/qcos (* 2.0 (dec t))) -1.0 1.0 200.0 500.0)]
(-> canvas
(set-background :black)
(set-color :white)
(xor-mode :black)
(set-stroke 20)
(draw-rings sb cb)
(draw-rings sa ca))))
(def window (show-window cnvs "Oldschool XOR" #(draw %1 %2 %3 %4)))
(defmethod key-pressed [(:window-name window) \space] [_ _]
(save cnvs (next-filename "results/ex38/" ".jpg")))
| null | https://raw.githubusercontent.com/Clojure2D/clojure2d-examples/9de82f5ac0737b7e78e07a17cf03ac577d973817/src/ex38_old_school_xor.clj | clojure | (ns ex38-old-school-xor
(:require [clojure2d.core :refer :all]
[fastmath.core :as m]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(def cnvs (canvas 600 600 :mid))
(defn draw-rings
"Draw rings"
[canvas posx posy]
(dotimes [x 17]
(let [size (* (inc x) 80)]
(ellipse canvas posx posy size size true)))
canvas)
(defn draw
"Frames"
[canvas _ ^long fps _]
(let [t (/ fps 60.0)
sa (m/mnorm (m/qsin (* 0.5 t)) -1.0 1.0 100.0 500.0)
ca (m/mnorm (m/qcos t) -1.0 1.0 100.0 500.0)
sb (m/mnorm (m/qsin (inc t)) -1.0 1.0 100.0 500.0)
cb (m/mnorm (m/qcos (* 2.0 (dec t))) -1.0 1.0 200.0 500.0)]
(-> canvas
(set-background :black)
(set-color :white)
(xor-mode :black)
(set-stroke 20)
(draw-rings sb cb)
(draw-rings sa ca))))
(def window (show-window cnvs "Oldschool XOR" #(draw %1 %2 %3 %4)))
(defmethod key-pressed [(:window-name window) \space] [_ _]
(save cnvs (next-filename "results/ex38/" ".jpg")))
| |
b2b8685d866079c45a51e23c469265b7649055b4256605d20d5a10b27aef8e05 | mfikes/fifth-postulate | ns259.cljs | (ns fifth-postulate.ns259)
(defn solve-for01 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for02 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for03 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for04 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for05 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for06 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for07 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for08 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for09 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for10 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for11 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for12 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for13 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for14 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for15 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for16 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for17 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for18 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for19 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
| null | https://raw.githubusercontent.com/mfikes/fifth-postulate/22cfd5f8c2b4a2dead1c15a96295bfeb4dba235e/src/fifth_postulate/ns259.cljs | clojure | (ns fifth-postulate.ns259)
(defn solve-for01 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for02 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for03 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for04 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for05 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for06 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for07 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for08 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for09 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for10 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for11 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for12 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for13 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for14 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for15 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for16 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for17 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for18 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for19 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
| |
7c29cc0bb3b168bc40df8d75e9b3b13bf48dd568c35ec273233e96bab85214a9 | byorgey/diagrams-play | Sized.hs | # LANGUAGE NoMonomorphismRestriction #
import Diagrams.Prelude
import Diagrams.Backend.Cairo.CmdLine
d = circle 1 ||| circle 2 ||| circle 3
main = defaultMain (d # sized (Dims 3 3)) | null | https://raw.githubusercontent.com/byorgey/diagrams-play/5362c715db394be6848ff5de1bbe71178e5f173f/Sized.hs | haskell | # LANGUAGE NoMonomorphismRestriction #
import Diagrams.Prelude
import Diagrams.Backend.Cairo.CmdLine
d = circle 1 ||| circle 2 ||| circle 3
main = defaultMain (d # sized (Dims 3 3)) | |
dca431b46eed2227390d797f8dba3971849dc75406735f61e11ce657f3588050 | zellige/hastile | LayerSpec.hs | {-# LANGUAGE OverloadedStrings #-}
module Hastile.Lib.LayerSpec where
import qualified Control.Monad.IO.Class as IOClass
import qualified Data.ByteString.Char8 as ByteString
import qualified Data.LruCache.IO as LRUIO
import qualified Hasql.Pool as Pool
import Test.Hspec (Spec, before, describe, it,
runIO, shouldBe)
import qualified Hastile.DB.Token as TokenDB
import qualified Hastile.Lib.Layer as LayerLib
import qualified Hastile.Lib.Token as TokenLib
import qualified Hastile.Types.Layer as Layer
import qualified Hastile.Types.Layer.Security as LayerSecurity
import qualified Hastile.Types.Token as Token
spec :: Spec
spec = do
settings <- runIO $ readFile "db/env/test"
pool <- runIO $ Pool.acquire (1, 10, ByteString.pack settings)
testCheckLayerAuthorisation pool
testCheckPrivateLayerAuthorisation pool
testFetchAuthorisedLayersForToken pool
runIO $ Pool.release pool
beforeEach :: IOClass.MonadIO m => Pool.Pool -> m Token.Cache
beforeEach pool = do
cache <- IOClass.liftIO $ LRUIO.newLruHandle 1
_ <- IOClass.liftIO $ TokenDB.clearTokens pool
_ <- IOClass.liftIO $ TokenLib.updateOrInsertToken pool cache authorisedToken
_ <- IOClass.liftIO $ TokenLib.updateOrInsertToken pool cache unauthorisedToken
pure cache
testCheckLayerAuthorisation :: Pool.Pool -> Spec
testCheckLayerAuthorisation pool =
before (beforeEach pool) $
describe "testCheckLayerAuthorisation" $ do
it "should authorise a public layer when no token is given" $ \cache -> do
let noToken = Nothing
layerAuthorisation <- LayerLib.checkLayerAuthorisation pool cache publicLayer noToken
layerAuthorisation `shouldBe` LayerSecurity.Authorised
it "should authorise a public layer when a token is given" $ \cache -> do
let token = Just authorisedToken'
layerAuthorisation <- LayerLib.checkLayerAuthorisation pool cache publicLayer token
layerAuthorisation `shouldBe` LayerSecurity.Authorised
it "should authorise a private layer if token has access" $ \cache -> do
let token = Just authorisedToken'
layerAuthorisation <- LayerLib.checkLayerAuthorisation pool cache privateLayer token
layerAuthorisation `shouldBe` LayerSecurity.Authorised
it "should not authorise a private layer if token does not have access" $ \cache -> do
let token = Just unauthorisedToken'
layerAuthorisation <- LayerLib.checkLayerAuthorisation pool cache privateLayer token
layerAuthorisation `shouldBe` LayerSecurity.Unauthorised
it "should not authorise a private layer if no token is given" $ \cache -> do
let noToken = Nothing
layerAuthorisation <- LayerLib.checkLayerAuthorisation pool cache privateLayer noToken
layerAuthorisation `shouldBe` LayerSecurity.Unauthorised
testCheckPrivateLayerAuthorisation :: Pool.Pool -> Spec
testCheckPrivateLayerAuthorisation pool =
before (beforeEach pool) $
describe "testCheckPrivateLayerAuthorisation" $ do
it "should authorise a private layer if token has access" $ \cache -> do
let token = Just authorisedToken'
layerAuthorisation <- LayerLib.checkPrivateLayerAuthorisation pool cache privateLayer token
layerAuthorisation `shouldBe` LayerSecurity.Authorised
it "should not authorise a private layer if token does not have access" $ \cache -> do
let token = Just unauthorisedToken'
layerAuthorisation <- LayerLib.checkPrivateLayerAuthorisation pool cache privateLayer token
layerAuthorisation `shouldBe` LayerSecurity.Unauthorised
it "should not authorise a private layer if no token is given" $ \cache -> do
let noToken = Nothing
layerAuthorisation <- LayerLib.checkPrivateLayerAuthorisation pool cache privateLayer noToken
layerAuthorisation `shouldBe` LayerSecurity.Unauthorised
testFetchAuthorisedLayersForToken :: Pool.Pool -> Spec
testFetchAuthorisedLayersForToken pool =
before (beforeEach pool) $
describe "testFetchAuthorisedLayersForToken" $ do
it "should return authorised layers if token is in db" $ \_ -> do
layers <- LayerLib.fetchAuthorisedLayersForToken pool authorisedToken'
layers `shouldBe` authorisedTokenLayers
it "should return an empty list if token is not in db" $ \_ -> do
layers <- LayerLib.fetchAuthorisedLayersForToken pool "non-existent-token"
layers `shouldBe` []
authorisedToken :: Token.TokenAuthorisation
authorisedToken =
Token.TokenAuthorisation authorisedToken' authorisedTokenLayers
unauthorisedToken :: Token.TokenAuthorisation
unauthorisedToken =
Token.TokenAuthorisation unauthorisedToken' unauthorisedTokenLayers
authorisedToken' :: Token.Token
authorisedToken' = "abcd"
unauthorisedToken' :: Token.Token
unauthorisedToken' = "defg"
authorisedTokenLayers :: Token.Layers
authorisedTokenLayers = [Layer._layerName privateLayer, "other_layer"]
unauthorisedTokenLayers :: Token.Layers
unauthorisedTokenLayers = ["other_layer"]
publicLayer :: Layer.Layer
publicLayer =
Layer.Layer
{ Layer._layerName = "public_layer"
, Layer._layerSettings =
Layer.defaultLayerSettings { Layer._layerSecurity = Just LayerSecurity.Public }
}
privateLayer :: Layer.Layer
privateLayer =
Layer.Layer
{ Layer._layerName = "private_layer"
, Layer._layerSettings =
Layer.defaultLayerSettings { Layer._layerSecurity = Just LayerSecurity.Private }
}
| null | https://raw.githubusercontent.com/zellige/hastile/4dabe66bd997e91128ab4136b6f40da51c204a2b/test/Hastile/Lib/LayerSpec.hs | haskell | # LANGUAGE OverloadedStrings # |
module Hastile.Lib.LayerSpec where
import qualified Control.Monad.IO.Class as IOClass
import qualified Data.ByteString.Char8 as ByteString
import qualified Data.LruCache.IO as LRUIO
import qualified Hasql.Pool as Pool
import Test.Hspec (Spec, before, describe, it,
runIO, shouldBe)
import qualified Hastile.DB.Token as TokenDB
import qualified Hastile.Lib.Layer as LayerLib
import qualified Hastile.Lib.Token as TokenLib
import qualified Hastile.Types.Layer as Layer
import qualified Hastile.Types.Layer.Security as LayerSecurity
import qualified Hastile.Types.Token as Token
spec :: Spec
spec = do
settings <- runIO $ readFile "db/env/test"
pool <- runIO $ Pool.acquire (1, 10, ByteString.pack settings)
testCheckLayerAuthorisation pool
testCheckPrivateLayerAuthorisation pool
testFetchAuthorisedLayersForToken pool
runIO $ Pool.release pool
beforeEach :: IOClass.MonadIO m => Pool.Pool -> m Token.Cache
beforeEach pool = do
cache <- IOClass.liftIO $ LRUIO.newLruHandle 1
_ <- IOClass.liftIO $ TokenDB.clearTokens pool
_ <- IOClass.liftIO $ TokenLib.updateOrInsertToken pool cache authorisedToken
_ <- IOClass.liftIO $ TokenLib.updateOrInsertToken pool cache unauthorisedToken
pure cache
testCheckLayerAuthorisation :: Pool.Pool -> Spec
testCheckLayerAuthorisation pool =
before (beforeEach pool) $
describe "testCheckLayerAuthorisation" $ do
it "should authorise a public layer when no token is given" $ \cache -> do
let noToken = Nothing
layerAuthorisation <- LayerLib.checkLayerAuthorisation pool cache publicLayer noToken
layerAuthorisation `shouldBe` LayerSecurity.Authorised
it "should authorise a public layer when a token is given" $ \cache -> do
let token = Just authorisedToken'
layerAuthorisation <- LayerLib.checkLayerAuthorisation pool cache publicLayer token
layerAuthorisation `shouldBe` LayerSecurity.Authorised
it "should authorise a private layer if token has access" $ \cache -> do
let token = Just authorisedToken'
layerAuthorisation <- LayerLib.checkLayerAuthorisation pool cache privateLayer token
layerAuthorisation `shouldBe` LayerSecurity.Authorised
it "should not authorise a private layer if token does not have access" $ \cache -> do
let token = Just unauthorisedToken'
layerAuthorisation <- LayerLib.checkLayerAuthorisation pool cache privateLayer token
layerAuthorisation `shouldBe` LayerSecurity.Unauthorised
it "should not authorise a private layer if no token is given" $ \cache -> do
let noToken = Nothing
layerAuthorisation <- LayerLib.checkLayerAuthorisation pool cache privateLayer noToken
layerAuthorisation `shouldBe` LayerSecurity.Unauthorised
testCheckPrivateLayerAuthorisation :: Pool.Pool -> Spec
testCheckPrivateLayerAuthorisation pool =
before (beforeEach pool) $
describe "testCheckPrivateLayerAuthorisation" $ do
it "should authorise a private layer if token has access" $ \cache -> do
let token = Just authorisedToken'
layerAuthorisation <- LayerLib.checkPrivateLayerAuthorisation pool cache privateLayer token
layerAuthorisation `shouldBe` LayerSecurity.Authorised
it "should not authorise a private layer if token does not have access" $ \cache -> do
let token = Just unauthorisedToken'
layerAuthorisation <- LayerLib.checkPrivateLayerAuthorisation pool cache privateLayer token
layerAuthorisation `shouldBe` LayerSecurity.Unauthorised
it "should not authorise a private layer if no token is given" $ \cache -> do
let noToken = Nothing
layerAuthorisation <- LayerLib.checkPrivateLayerAuthorisation pool cache privateLayer noToken
layerAuthorisation `shouldBe` LayerSecurity.Unauthorised
testFetchAuthorisedLayersForToken :: Pool.Pool -> Spec
testFetchAuthorisedLayersForToken pool =
before (beforeEach pool) $
describe "testFetchAuthorisedLayersForToken" $ do
it "should return authorised layers if token is in db" $ \_ -> do
layers <- LayerLib.fetchAuthorisedLayersForToken pool authorisedToken'
layers `shouldBe` authorisedTokenLayers
it "should return an empty list if token is not in db" $ \_ -> do
layers <- LayerLib.fetchAuthorisedLayersForToken pool "non-existent-token"
layers `shouldBe` []
authorisedToken :: Token.TokenAuthorisation
authorisedToken =
Token.TokenAuthorisation authorisedToken' authorisedTokenLayers
unauthorisedToken :: Token.TokenAuthorisation
unauthorisedToken =
Token.TokenAuthorisation unauthorisedToken' unauthorisedTokenLayers
authorisedToken' :: Token.Token
authorisedToken' = "abcd"
unauthorisedToken' :: Token.Token
unauthorisedToken' = "defg"
authorisedTokenLayers :: Token.Layers
authorisedTokenLayers = [Layer._layerName privateLayer, "other_layer"]
unauthorisedTokenLayers :: Token.Layers
unauthorisedTokenLayers = ["other_layer"]
publicLayer :: Layer.Layer
publicLayer =
Layer.Layer
{ Layer._layerName = "public_layer"
, Layer._layerSettings =
Layer.defaultLayerSettings { Layer._layerSecurity = Just LayerSecurity.Public }
}
privateLayer :: Layer.Layer
privateLayer =
Layer.Layer
{ Layer._layerName = "private_layer"
, Layer._layerSettings =
Layer.defaultLayerSettings { Layer._layerSecurity = Just LayerSecurity.Private }
}
|
47ffd7d0b3f9994b1aae70834010b9bd6aea1d38ce33096505a890073a773cbb | chunsj/TH | binomial.lisp | (in-package :th)
(defgeneric score/binomial (data p n))
(defgeneric sample/binomial (p nt &optional n))
(defun of-binomial-p (data p n) (and (of-ie data 0 n) (of-it p 0 1) (> n 0)))
(defun lbc (n k)
(let ((n1 ($add n 1))
(k1 ($add k 1))
(nk1 ($add ($sub n k) 1)))
($sub ($lgammaf n1)
($add ($lgammaf k1) ($lgammaf nk1)))))
(defmethod score/binomial ((data number) (p number) (n number))
(when (of-binomial-p data p n)
(let ((lbc (lbc n data))
(lp (log p))
(lq (log (- 1 p))))
(+ lbc (+ (* data lp) (* (- n data) lq))))))
(defmethod score/binomial ((data number) (p node) (n number))
(when (of-binomial-p data ($data p) n)
(let ((lbc (lbc n data))
(lp ($log p))
(lq ($log ($sub 1 p))))
($add lbc ($add ($mul data lp) ($mul (- n data) lq))))))
(defmethod score/binomial ((data tensor) (p number) (n number))
(when (of-binomial-p data p n)
(let ((lbc (lbc n data))
(lp (log p))
(lq (log (- 1 p))))
($sum ($add lbc ($add ($mul data lp) ($mul ($sub n data) lq)))))))
(defmethod score/binomial ((data tensor) (p node) (n number))
(when (of-binomial-p data ($data p) n)
(let ((lbc (lbc n data))
(lp ($log p))
(lq ($log ($sub 1 p))))
($sum ($add lbc ($add ($mul data lp) ($mul ($sub n data) lq)))))))
(defmethod score/binomial ((data node) (p number) (n number))
(when (of-binomial-p ($data data) p n)
(let ((lbc (lbc n data))
(lp (log p))
(lq (log (- 1 p))))
($sum ($add lbc ($add ($mul data lp) ($mul ($sub n data) lq)))))))
(defmethod score/binomial ((data node) (p node) (n number))
(when (of-binomial-p ($data data) ($data p) n)
(let ((lbc (lbc n data))
(lp ($log p))
(lq ($log ($sub 1 p))))
($sum ($add lbc ($add ($mul data lp) ($mul ($sub n data) lq)))))))
(defmethod sample/binomial ((p number) (nt number) &optional (n 1))
(cond ((= n 1) (random/binomial nt p))
((> n 1) ($binomial! (tensor n) nt p))))
(defmethod sample/binomial ((p node) (nt number) &optional (n 1))
(cond ((= n 1) (random/binomial nt ($data p)))
((> n 1) ($binomial! (tensor n) nt ($data p)))))
| null | https://raw.githubusercontent.com/chunsj/TH/890f05ab81148d9fe558be3979c30c303b448480/pd/binomial.lisp | lisp | (in-package :th)
(defgeneric score/binomial (data p n))
(defgeneric sample/binomial (p nt &optional n))
(defun of-binomial-p (data p n) (and (of-ie data 0 n) (of-it p 0 1) (> n 0)))
(defun lbc (n k)
(let ((n1 ($add n 1))
(k1 ($add k 1))
(nk1 ($add ($sub n k) 1)))
($sub ($lgammaf n1)
($add ($lgammaf k1) ($lgammaf nk1)))))
(defmethod score/binomial ((data number) (p number) (n number))
(when (of-binomial-p data p n)
(let ((lbc (lbc n data))
(lp (log p))
(lq (log (- 1 p))))
(+ lbc (+ (* data lp) (* (- n data) lq))))))
(defmethod score/binomial ((data number) (p node) (n number))
(when (of-binomial-p data ($data p) n)
(let ((lbc (lbc n data))
(lp ($log p))
(lq ($log ($sub 1 p))))
($add lbc ($add ($mul data lp) ($mul (- n data) lq))))))
(defmethod score/binomial ((data tensor) (p number) (n number))
(when (of-binomial-p data p n)
(let ((lbc (lbc n data))
(lp (log p))
(lq (log (- 1 p))))
($sum ($add lbc ($add ($mul data lp) ($mul ($sub n data) lq)))))))
(defmethod score/binomial ((data tensor) (p node) (n number))
(when (of-binomial-p data ($data p) n)
(let ((lbc (lbc n data))
(lp ($log p))
(lq ($log ($sub 1 p))))
($sum ($add lbc ($add ($mul data lp) ($mul ($sub n data) lq)))))))
(defmethod score/binomial ((data node) (p number) (n number))
(when (of-binomial-p ($data data) p n)
(let ((lbc (lbc n data))
(lp (log p))
(lq (log (- 1 p))))
($sum ($add lbc ($add ($mul data lp) ($mul ($sub n data) lq)))))))
(defmethod score/binomial ((data node) (p node) (n number))
(when (of-binomial-p ($data data) ($data p) n)
(let ((lbc (lbc n data))
(lp ($log p))
(lq ($log ($sub 1 p))))
($sum ($add lbc ($add ($mul data lp) ($mul ($sub n data) lq)))))))
(defmethod sample/binomial ((p number) (nt number) &optional (n 1))
(cond ((= n 1) (random/binomial nt p))
((> n 1) ($binomial! (tensor n) nt p))))
(defmethod sample/binomial ((p node) (nt number) &optional (n 1))
(cond ((= n 1) (random/binomial nt ($data p)))
((> n 1) ($binomial! (tensor n) nt ($data p)))))
| |
3211eca12005c4ee12400b872ce1057c4bc5c070867645241d77aa1514532aa3 | lambe-lang/nethra | sources.mli | module FromList : functor (Locator : Specs.LOCATOR) ->
Specs.SOURCE with type e = Locator.e and type Construct.c = Locator.e list
module FromChars :
Specs.SOURCE with type e = char and type Construct.c = char list
| null | https://raw.githubusercontent.com/lambe-lang/nethra/d803be8005021b3ee12d45768e90bb95645b226c/lib/nethra/syntax/source/sources.mli | ocaml | module FromList : functor (Locator : Specs.LOCATOR) ->
Specs.SOURCE with type e = Locator.e and type Construct.c = Locator.e list
module FromChars :
Specs.SOURCE with type e = char and type Construct.c = char list
| |
5a12d7f7bcfd9546f8091b9816d4f9eca5607fc8cc3931d97b57ccaf3adee543 | antoniogarrote/clj-s4 | wiring.clj | (ns wordcount.wiring
(:use [clj-s4.wiring]))
(wire-app "WordCountAnalysis"
(wire-pe {:id "sentenceSplitter"
:class "cljs4.SentenceSplitter"
:keys ["Text *"]
:properties
[{:name "model" :value "/Users/antoniogarrote/Development/Projects/s4/clj-s4/sampleapps/wordcount/models/en-sent.bin"}
{:name "dispatcher" :ref "wordsDispatcher"}
{:name "stream" :value "Sentences"}]})
(wire-pe {:id "tokenizer"
:class "cljs4.Tokenizer"
:keys ["Sentences textId"]
:properties
[{:name "tokenizerModel" :value "/Users/antoniogarrote/Development/Projects/s4/clj-s4/sampleapps/wordcount/models/en-token.bin"}
{:name "posTaggerModel" :value "/Users/antoniogarrote/Development/Projects/s4/clj-s4/sampleapps/wordcount/models/en-pos-maxent.bin"}
{:name "dispatcher" :ref "wordsDispatcher"}
{:name "stream" :value "Tokens"}]})
(wire-pe {:id "stopWordsFilter"
:class "cljs4.StopWordsFilter"
:keys ["Tokens textId"]
:properties
[{:name "dispatcher" :ref "wordsDispatcher"}
{:name "stream" :value "FilteredTokens"}]})
(wire-pe {:id "posPersister"
:class "cljs4.PosPersister"
:keys ["FilteredTokens textId"]
:properties
[{:name "dispatcher" :ref "wordsDispatcher"}
{:name "filePath" :value "/tmp/postaggers"}]})
(wire-partitioner {:id "textPartitioner"
:stream-names ["Text"]
:hash-keys ["content"]})
(wire-partitioner {:id "sentencesPartitioner"
:stream-names ["Sentences" "Tokens" "FilteredTokens"]
:hash-keys ["textId"]})
(wire-dispatcher {:id "wordsDispatcher"
:partitioners ["sentencesPartitioner" "textPartitioner"]}))
(wire-adapters "WordCountAnalysisAdapter"
(wire-bean
{:id "randomTextGenerator"
:class "cljs4.RandomText"
:properties [{:name "stream" :value "Text"}]}))
| null | https://raw.githubusercontent.com/antoniogarrote/clj-s4/5d41b327682a532e4ed4672a139676adbc775714/sampleapps/wordcount/src/wordcount/wiring.clj | clojure | (ns wordcount.wiring
(:use [clj-s4.wiring]))
(wire-app "WordCountAnalysis"
(wire-pe {:id "sentenceSplitter"
:class "cljs4.SentenceSplitter"
:keys ["Text *"]
:properties
[{:name "model" :value "/Users/antoniogarrote/Development/Projects/s4/clj-s4/sampleapps/wordcount/models/en-sent.bin"}
{:name "dispatcher" :ref "wordsDispatcher"}
{:name "stream" :value "Sentences"}]})
(wire-pe {:id "tokenizer"
:class "cljs4.Tokenizer"
:keys ["Sentences textId"]
:properties
[{:name "tokenizerModel" :value "/Users/antoniogarrote/Development/Projects/s4/clj-s4/sampleapps/wordcount/models/en-token.bin"}
{:name "posTaggerModel" :value "/Users/antoniogarrote/Development/Projects/s4/clj-s4/sampleapps/wordcount/models/en-pos-maxent.bin"}
{:name "dispatcher" :ref "wordsDispatcher"}
{:name "stream" :value "Tokens"}]})
(wire-pe {:id "stopWordsFilter"
:class "cljs4.StopWordsFilter"
:keys ["Tokens textId"]
:properties
[{:name "dispatcher" :ref "wordsDispatcher"}
{:name "stream" :value "FilteredTokens"}]})
(wire-pe {:id "posPersister"
:class "cljs4.PosPersister"
:keys ["FilteredTokens textId"]
:properties
[{:name "dispatcher" :ref "wordsDispatcher"}
{:name "filePath" :value "/tmp/postaggers"}]})
(wire-partitioner {:id "textPartitioner"
:stream-names ["Text"]
:hash-keys ["content"]})
(wire-partitioner {:id "sentencesPartitioner"
:stream-names ["Sentences" "Tokens" "FilteredTokens"]
:hash-keys ["textId"]})
(wire-dispatcher {:id "wordsDispatcher"
:partitioners ["sentencesPartitioner" "textPartitioner"]}))
(wire-adapters "WordCountAnalysisAdapter"
(wire-bean
{:id "randomTextGenerator"
:class "cljs4.RandomText"
:properties [{:name "stream" :value "Text"}]}))
| |
6cece047182171faf2e7f88be9800bbd7e5e55de3d5c161ea6192c89da8f9380 | tezos/tezos-mirror | test_filter_state.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. *)
(* *)
(*****************************************************************************)
(** Testing
-------
Component: Shell (Plugin)
Invocation: dune exec src/proto_alpha/lib_plugin/test/test_filter_state.exe
Subject: Unit tests the filter state functions of the plugin
*)
open Qcheck2_helpers
open Plugin.Mempool
open Test_utils
let count = 1000
let check_filter_state_invariants filter_state =
qcheck_cond
~pp:(fun fmt filter_state ->
Format.fprintf
fmt
"The following filter_state breaks invariants:@.%a"
pp_state
filter_state)
~cond:(fun filter_state ->
filter_state.prechecked_manager_op_count
= Operation_hash.Map.cardinal filter_state.prechecked_manager_ops
&& filter_state.prechecked_manager_op_count
= ManagerOpWeightSet.cardinal filter_state.prechecked_op_weights
&& ManagerOpWeightSet.for_all
(fun {operation_hash; weight} ->
match
Operation_hash.Map.find
operation_hash
filter_state.prechecked_manager_ops
with
| None -> false
| Some info -> Q.equal weight info.weight)
filter_state.prechecked_op_weights
&& eq_op_weight_opt
(ManagerOpWeightSet.min_elt filter_state.prechecked_op_weights)
filter_state.min_prechecked_op_weight)
filter_state
()
(** Test that [add_manager_op] adds the given operation to the filter
state, and removes the replaced operation if applicable. *)
let test_add_manager_op =
let open QCheck2 in
Test.make
~count
~name:"Add a manager operation"
(Gen.pair Generators.filter_state_with_two_operations_gen Gen.bool)
(fun ((filter_state, (oph, op_info), (oph_to_replace, _)), should_replace)
->
(* Both [oph] and [oph_to_replace] have even odds of being
already present in [filter_state] or fresh. *)
let replacement =
if should_replace then (
assume (not (Operation_hash.equal oph_to_replace oph)) ;
`Replace (oph_to_replace, ()))
else `No_replace
in
let filter_state = add_manager_op filter_state oph op_info replacement in
check_filter_state_invariants filter_state
&& qcheck_cond
~pp:(fun fmt set ->
Format.fprintf
fmt
"%a was not found in prechecked_manager_ops: %a"
Operation_hash.pp
oph
pp_prechecked_manager_ops
set)
~cond:(Operation_hash.Map.mem oph)
filter_state.prechecked_manager_ops
()
&&
if should_replace then
qcheck_cond
~pp:(fun fmt () ->
Format.fprintf
fmt
"%a should have been removed from prechecked_manager_ops."
Operation_hash.pp
oph_to_replace)
~cond:(fun () ->
not
(Operation_hash.Map.mem
oph_to_replace
filter_state.prechecked_manager_ops))
()
()
else true)
(** Test that [remove] removes the operation from the filter state if
it was present, and that adding then removing is the same as doing
nothing but removing the replaced operation if there is one. *)
let test_remove_present =
let open QCheck2 in
Test.make
~count
~name:"Remove an existing operation hash"
(Gen.triple
Generators.filter_state_with_operation_gen
Generators.oph_and_info_gen
Gen.bool)
(fun ((initial_state, (oph_to_replace, _)), (oph, op_info), should_replace)
->
(* Add a fresh operation [oph] to the state. *)
assume
(not (Operation_hash.Map.mem oph initial_state.prechecked_manager_ops)) ;
let replacement =
if should_replace then `Replace (oph_to_replace, ()) else `No_replace
in
let filter_state = add_manager_op initial_state oph op_info replacement in
(* Remove [oph] from the state, in which it was present. *)
let filter_state = remove_operation filter_state oph in
let (_ : bool) =
(* Check that the state invariants are preserved and that
[oph] has been removed. *)
check_filter_state_invariants filter_state
&& qcheck_cond
~pp:(fun fmt () ->
Format.fprintf
fmt
"%a should have been removed from prechecked_manager_ops."
Operation_hash.pp
oph)
~cond:(fun () ->
not
(Operation_hash.Map.mem
oph
filter_state.prechecked_manager_ops))
()
()
in
(* Check that adding a fresh operation then removing it is the
same as doing nothing except removing any replaced operation. *)
let initial_state_without_replaced_op =
if should_replace then remove_operation initial_state oph_to_replace
else initial_state
in
qcheck_eq
~pp:pp_state
~eq:eq_state
initial_state_without_replaced_op
filter_state)
(** Test that [remove] leaves the filter state intact if the operation
hash is unknown. *)
let test_remove_unknown =
let open QCheck2 in
Test.make
~count
~name:"Remove an unknown operation hash"
(Gen.pair Generators.filter_state_gen Generators.operation_hash_gen)
(fun (initial_state, oph) ->
assume
(not (Operation_hash.Map.mem oph initial_state.prechecked_manager_ops)) ;
let filter_state = remove_operation initial_state oph in
qcheck_eq ~pp:pp_state ~eq:eq_state initial_state filter_state)
let () =
Alcotest.run
"Filter_state"
[
(Protocol.name ^ ": add_manager_op", qcheck_wrap [test_add_manager_op]);
( Protocol.name ^ ": remove",
qcheck_wrap [test_remove_present; test_remove_unknown] );
]
| null | https://raw.githubusercontent.com/tezos/tezos-mirror/b7f14148a61a8afec9bdb3c16de8f197ee6b8cff/src/proto_016_PtMumbai/lib_plugin/test/test_filter_state.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.
***************************************************************************
* Testing
-------
Component: Shell (Plugin)
Invocation: dune exec src/proto_alpha/lib_plugin/test/test_filter_state.exe
Subject: Unit tests the filter state functions of the plugin
* Test that [add_manager_op] adds the given operation to the filter
state, and removes the replaced operation if applicable.
Both [oph] and [oph_to_replace] have even odds of being
already present in [filter_state] or fresh.
* Test that [remove] removes the operation from the filter state if
it was present, and that adding then removing is the same as doing
nothing but removing the replaced operation if there is one.
Add a fresh operation [oph] to the state.
Remove [oph] from the state, in which it was present.
Check that the state invariants are preserved and that
[oph] has been removed.
Check that adding a fresh operation then removing it is the
same as doing nothing except removing any replaced operation.
* Test that [remove] leaves the filter state intact if the operation
hash is unknown. | 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 Qcheck2_helpers
open Plugin.Mempool
open Test_utils
let count = 1000
let check_filter_state_invariants filter_state =
qcheck_cond
~pp:(fun fmt filter_state ->
Format.fprintf
fmt
"The following filter_state breaks invariants:@.%a"
pp_state
filter_state)
~cond:(fun filter_state ->
filter_state.prechecked_manager_op_count
= Operation_hash.Map.cardinal filter_state.prechecked_manager_ops
&& filter_state.prechecked_manager_op_count
= ManagerOpWeightSet.cardinal filter_state.prechecked_op_weights
&& ManagerOpWeightSet.for_all
(fun {operation_hash; weight} ->
match
Operation_hash.Map.find
operation_hash
filter_state.prechecked_manager_ops
with
| None -> false
| Some info -> Q.equal weight info.weight)
filter_state.prechecked_op_weights
&& eq_op_weight_opt
(ManagerOpWeightSet.min_elt filter_state.prechecked_op_weights)
filter_state.min_prechecked_op_weight)
filter_state
()
let test_add_manager_op =
let open QCheck2 in
Test.make
~count
~name:"Add a manager operation"
(Gen.pair Generators.filter_state_with_two_operations_gen Gen.bool)
(fun ((filter_state, (oph, op_info), (oph_to_replace, _)), should_replace)
->
let replacement =
if should_replace then (
assume (not (Operation_hash.equal oph_to_replace oph)) ;
`Replace (oph_to_replace, ()))
else `No_replace
in
let filter_state = add_manager_op filter_state oph op_info replacement in
check_filter_state_invariants filter_state
&& qcheck_cond
~pp:(fun fmt set ->
Format.fprintf
fmt
"%a was not found in prechecked_manager_ops: %a"
Operation_hash.pp
oph
pp_prechecked_manager_ops
set)
~cond:(Operation_hash.Map.mem oph)
filter_state.prechecked_manager_ops
()
&&
if should_replace then
qcheck_cond
~pp:(fun fmt () ->
Format.fprintf
fmt
"%a should have been removed from prechecked_manager_ops."
Operation_hash.pp
oph_to_replace)
~cond:(fun () ->
not
(Operation_hash.Map.mem
oph_to_replace
filter_state.prechecked_manager_ops))
()
()
else true)
let test_remove_present =
let open QCheck2 in
Test.make
~count
~name:"Remove an existing operation hash"
(Gen.triple
Generators.filter_state_with_operation_gen
Generators.oph_and_info_gen
Gen.bool)
(fun ((initial_state, (oph_to_replace, _)), (oph, op_info), should_replace)
->
assume
(not (Operation_hash.Map.mem oph initial_state.prechecked_manager_ops)) ;
let replacement =
if should_replace then `Replace (oph_to_replace, ()) else `No_replace
in
let filter_state = add_manager_op initial_state oph op_info replacement in
let filter_state = remove_operation filter_state oph in
let (_ : bool) =
check_filter_state_invariants filter_state
&& qcheck_cond
~pp:(fun fmt () ->
Format.fprintf
fmt
"%a should have been removed from prechecked_manager_ops."
Operation_hash.pp
oph)
~cond:(fun () ->
not
(Operation_hash.Map.mem
oph
filter_state.prechecked_manager_ops))
()
()
in
let initial_state_without_replaced_op =
if should_replace then remove_operation initial_state oph_to_replace
else initial_state
in
qcheck_eq
~pp:pp_state
~eq:eq_state
initial_state_without_replaced_op
filter_state)
let test_remove_unknown =
let open QCheck2 in
Test.make
~count
~name:"Remove an unknown operation hash"
(Gen.pair Generators.filter_state_gen Generators.operation_hash_gen)
(fun (initial_state, oph) ->
assume
(not (Operation_hash.Map.mem oph initial_state.prechecked_manager_ops)) ;
let filter_state = remove_operation initial_state oph in
qcheck_eq ~pp:pp_state ~eq:eq_state initial_state filter_state)
let () =
Alcotest.run
"Filter_state"
[
(Protocol.name ^ ": add_manager_op", qcheck_wrap [test_add_manager_op]);
( Protocol.name ^ ": remove",
qcheck_wrap [test_remove_present; test_remove_unknown] );
]
|
925066e90b79f5dd6e197cb8a42be53f6124e4e82df9fd4dd151bf9e094f6d44 | maybevoid/casimir | Decide.hs |
module Casimir.Ops.Decide
where
import Casimir.Base
import Casimir.Free
data DecideEff s
data DecideOps s eff = DecideOps {
decideOp :: eff s
}
data DecideCoOp s a = DecideOp (s -> a)
deriving (Functor)
instance EffOps (DecideEff s) where
type Operation (DecideEff s) = DecideOps s
instance EffCoOp (DecideEff s) where
type CoOperation (DecideEff s) = DecideCoOp s
instance EffFunctor Lift (DecideOps s) where
effmap (Lift lift) ops = DecideOps {
decideOp = lift $ decideOp ops
}
instance FreeOps (DecideEff s) where
mkFreeOps liftCoOp = DecideOps {
decideOp = liftCoOp $ DecideOp id
}
instance ImplicitOps (DecideEff s) where
type OpsConstraint (DecideEff s) eff =
(?_Control_Effect_Implicit_Ops_Decide_decideOps :: DecideOps s eff)
withOps decideOps comp =
let
?_Control_Effect_Implicit_Ops_Decide_decideOps =
decideOps in comp
captureOps =
?_Control_Effect_Implicit_Ops_Decide_decideOps
decide :: forall a . Eff (DecideEff a) a
decide = decideOp captureOps
| null | https://raw.githubusercontent.com/maybevoid/casimir/ebbfa403739d6f258e6ac6793549006a0e8bff42/casimir/src/lib/Casimir/Ops/Decide.hs | haskell |
module Casimir.Ops.Decide
where
import Casimir.Base
import Casimir.Free
data DecideEff s
data DecideOps s eff = DecideOps {
decideOp :: eff s
}
data DecideCoOp s a = DecideOp (s -> a)
deriving (Functor)
instance EffOps (DecideEff s) where
type Operation (DecideEff s) = DecideOps s
instance EffCoOp (DecideEff s) where
type CoOperation (DecideEff s) = DecideCoOp s
instance EffFunctor Lift (DecideOps s) where
effmap (Lift lift) ops = DecideOps {
decideOp = lift $ decideOp ops
}
instance FreeOps (DecideEff s) where
mkFreeOps liftCoOp = DecideOps {
decideOp = liftCoOp $ DecideOp id
}
instance ImplicitOps (DecideEff s) where
type OpsConstraint (DecideEff s) eff =
(?_Control_Effect_Implicit_Ops_Decide_decideOps :: DecideOps s eff)
withOps decideOps comp =
let
?_Control_Effect_Implicit_Ops_Decide_decideOps =
decideOps in comp
captureOps =
?_Control_Effect_Implicit_Ops_Decide_decideOps
decide :: forall a . Eff (DecideEff a) a
decide = decideOp captureOps
| |
f5acda0ec7582849ddee46a9da465991f242382da290673506763ad6ae7f94ce | crategus/cl-cffi-gtk | gtk.gesture-multi-press.lisp | ;;; ----------------------------------------------------------------------------
;;; gtk.gesture-multi-press.lisp
;;;
;;; The documentation of this file is taken from the GTK 3 Reference Manual
Version 3.24 and modified to document the Lisp binding to the GTK library .
;;; See <>. The API documentation of the Lisp binding is
available from < -cffi-gtk/ > .
;;;
Copyright ( C ) 2019 - 2021
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU Lesser General Public License for Lisp
as published by the Free Software Foundation , either version 3 of the
;;; License, or (at your option) any later version and with a preamble to
the GNU Lesser General Public License that clarifies the terms for use
;;; with Lisp programs and is referred as the LLGPL.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details .
;;;
You should have received a copy of the GNU Lesser General Public
License along with this program and the preamble to the Gnu Lesser
;;; General Public License. If not, see </>
;;; and <>.
;;; ----------------------------------------------------------------------------
;;;
GtkGestureMultiPress
;;;
;;; Multipress gesture
;;;
;;; Types and Values
;;;
GtkGestureMultiPress
;;;
;;; Functions
;;;
;;; gtk_gesture_multi_press_new
;;; gtk_gesture_multi_press_set_area
gtk_gesture_multi_press_get_area
;;;
;;; Signals
;;;
;;; void pressed Run Last
;;; void released Run Last
;;; void stopped Run Last
;;;
;;; Object Hierarchy
;;;
;;; GObject
;;; ╰── GtkEventController
;;; ╰── GtkGesture
;;; ╰── GtkGestureSingle
;;; ╰── GtkGestureMultiPress
;;; ----------------------------------------------------------------------------
(in-package :gtk)
;;; ----------------------------------------------------------------------------
struct GtkGestureMultiPress
;;; ----------------------------------------------------------------------------
(define-g-object-class "GtkGestureMultiPress" gtk-gesture-multi-press
(:superclass gtk-gesture-single
:export t
:interfaces nil
:type-initializer "gtk_gesture_multi_press_get_type")
nil)
#+cl-cffi-gtk-documentation
(setf (documentation 'gtk-gesture-multi-press 'type)
"@version{2020-9-11}
@begin{short}
@sym{gtk-gesture-multi-press} is a @class{gtk-gesture} implementation able
to recognize multiple clicks on a nearby zone, which can be listened for
through the \"pressed\" signal.
@end{short}
Whenever time or distance between clicks exceed the GTK defaults, \"stopped\"
is emitted, and the click counter is reset.
Callers may also restrict the area that is considered valid for a > 1
touch/button press through the function
@fun{gtk-gesture-multi-press-area}, so any click happening outside that area
is considered to be a first click of its own.
@begin[Signal Details]{dictionary}
@subheading{The \"pressed\" signal}
@begin{pre}
lambda (gesture n-press x y) :run-last
@end{pre}
The signal is emitted whenever a button or touch press happens.
@begin[code]{table}
@entry[gesture]{The @sym{gtk-gesture-multi-press} object which
received the signal.}
@entry[n-press]{An integer with how many touch/button presses happened
with this one.}
@entry[x]{A double float with the x coordinate, in widget allocation
coordinates.}
@entry[y]{A double float with the y coordinate, in widget allocation
coordinates.}
@end{table}
@subheading{The \"released\" signal}
@begin{pre}
lambda (gesture n-press x y) :run-last
@end{pre}
The signal is emitted when a button or touch is released. The
@arg{n-press} argument will report the number of press that is paired to
this event, note that the \"stopped\" signal may have been emitted between
the press and its release, the @arg{n-press} argument will only start over
at the next press.
@begin[code]{table}
@entry[gesture]{The @sym{gtk-gesture-multi-press} object which
received the signal.}
@entry[n-press]{An integer with the number of press that is paired with
this release.}
@entry[x]{A double float with the x coordinate, in widget allocation
coordinates.}
@entry[y]{A double float with the y coordinate, in widget allocation
coordinates.}
@end{table}
@subheading{The \"stopped\" signal}
@begin{pre}
lambda (gesture) :run-last
@end{pre}
The signal is emitted whenever any time/distance threshold has been
exceeded.
@begin[code]{table}
@entry[gesture]{The @sym{gtk-gesture-multi-press} object which
received the signal.}
@end{table}
@end{dictionary}
@see-class{gtk-gesture}")
;;; ----------------------------------------------------------------------------
;;; gtk_gesture_multi_press_new ()
;;; ----------------------------------------------------------------------------
(declaim (inline gtk-gesture-multi-press-new))
(defun gtk-gesture-multi-press-new (widget)
#+cl-cffi-gtk-documentation
"@version{2020-9-11}
@argument[widget]{a @class{gtk-widget} object}
@return{A newly created @class{gtk-gesture-multi-press} object.}
@begin{short}
Returns a newly created gesture that recognizes single and multiple presses.
@end{short}
@see-function{gtk-gesture-multi-press}"
(make-instance 'gtk-gesture-multi-press
:widget widget))
(export 'gtk-gesture-multi-press-new)
;;; ----------------------------------------------------------------------------
gtk_gesture_multi_press_get_area ( )
;;; gtk_gesture_multi_press_set_area () -> gtk-gesture-multi-press-area
;;; ----------------------------------------------------------------------------
(defun (setf gtk-gesture-multi-press-area) (rect gesture)
(foreign-funcall "gtk_gesture_multi_press_set_area"
(g-object gtk-gesture-multi-press) gesture
(g-boxed-foreign gdk-rectangle) rect
:void)
rect)
(defcfun ("gtk_gesture_multi_press_get_area" %gtk-gesture-multi-press-area)
:boolean
(gesture (g-object gtk-gesture-multi-press))
(rect (g-boxed-foreign gdk-rectangle)))
(defun gtk-gesture-multi-press-area (gesture)
#+cl-cffi-gtk-documentation
"@version{2020-9-11}
@syntax[]{(gtk-gesture-multi-press-area gesture) => rect}
@syntax[]{(setf (gtk-gesture-multi-press-area gesture) rect)}
@argument[gesture]{a @class{gtk-gesture-multi-press} object}
@argument[rect]{a @class{gdk-rectangle} with the press area}
@begin{short}
Accessor of the press area of the gesture.
@end{short}
The function @sym{gtk-gesture-multi-press-area} gets the press area. The
function @sym{(setf gtk-gesture-multi-press-area)} sets the press area.
If @arg{rect} is non-@code{nil}, the press area will be checked to be confined
within the rectangle, otherwise the button count will be reset so the press is
seen as being the first one. If @arg{rect} is @code{nil}, the area will be
reset to an unrestricted state.
Note: The rectangle is only used to determine whether any non-first click
falls within the expected area. This is not akin to an input shape.
@see-class{gtk-gesture-multi-press}
@see-class{gdk-rectangle}"
(let ((rect (gdk-rectangle-new)))
(when (%gtk-gesture-multi-press-area gesture rect)
rect)))
(export 'gtk-gesture-multi-press-area)
;;; --- End of file gtk-gesture-multi-press.lisp -------------------------------
| null | https://raw.githubusercontent.com/crategus/cl-cffi-gtk/7f5a09f78d8004a71efa82794265f2587fff98ab/gtk/gtk.gesture-multi-press.lisp | lisp | ----------------------------------------------------------------------------
gtk.gesture-multi-press.lisp
The documentation of this file is taken from the GTK 3 Reference Manual
See <>. The API documentation of the Lisp binding is
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License for Lisp
License, or (at your option) any later version and with a preamble to
with Lisp programs and is referred as the LLGPL.
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
General Public License. If not, see </>
and <>.
----------------------------------------------------------------------------
Multipress gesture
Types and Values
Functions
gtk_gesture_multi_press_new
gtk_gesture_multi_press_set_area
Signals
void pressed Run Last
void released Run Last
void stopped Run Last
Object Hierarchy
GObject
╰── GtkEventController
╰── GtkGesture
╰── GtkGestureSingle
╰── GtkGestureMultiPress
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_gesture_multi_press_new ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_gesture_multi_press_set_area () -> gtk-gesture-multi-press-area
----------------------------------------------------------------------------
--- End of file gtk-gesture-multi-press.lisp ------------------------------- | Version 3.24 and modified to document the Lisp binding to the GTK library .
available from < -cffi-gtk/ > .
Copyright ( C ) 2019 - 2021
as published by the Free Software Foundation , either version 3 of the
the GNU Lesser General Public License that clarifies the terms for use
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with this program and the preamble to the Gnu Lesser
GtkGestureMultiPress
GtkGestureMultiPress
gtk_gesture_multi_press_get_area
(in-package :gtk)
struct GtkGestureMultiPress
(define-g-object-class "GtkGestureMultiPress" gtk-gesture-multi-press
(:superclass gtk-gesture-single
:export t
:interfaces nil
:type-initializer "gtk_gesture_multi_press_get_type")
nil)
#+cl-cffi-gtk-documentation
(setf (documentation 'gtk-gesture-multi-press 'type)
"@version{2020-9-11}
@begin{short}
@sym{gtk-gesture-multi-press} is a @class{gtk-gesture} implementation able
to recognize multiple clicks on a nearby zone, which can be listened for
through the \"pressed\" signal.
@end{short}
Whenever time or distance between clicks exceed the GTK defaults, \"stopped\"
is emitted, and the click counter is reset.
Callers may also restrict the area that is considered valid for a > 1
touch/button press through the function
@fun{gtk-gesture-multi-press-area}, so any click happening outside that area
is considered to be a first click of its own.
@begin[Signal Details]{dictionary}
@subheading{The \"pressed\" signal}
@begin{pre}
lambda (gesture n-press x y) :run-last
@end{pre}
The signal is emitted whenever a button or touch press happens.
@begin[code]{table}
@entry[gesture]{The @sym{gtk-gesture-multi-press} object which
received the signal.}
@entry[n-press]{An integer with how many touch/button presses happened
with this one.}
@entry[x]{A double float with the x coordinate, in widget allocation
coordinates.}
@entry[y]{A double float with the y coordinate, in widget allocation
coordinates.}
@end{table}
@subheading{The \"released\" signal}
@begin{pre}
lambda (gesture n-press x y) :run-last
@end{pre}
The signal is emitted when a button or touch is released. The
@arg{n-press} argument will report the number of press that is paired to
this event, note that the \"stopped\" signal may have been emitted between
the press and its release, the @arg{n-press} argument will only start over
at the next press.
@begin[code]{table}
@entry[gesture]{The @sym{gtk-gesture-multi-press} object which
received the signal.}
@entry[n-press]{An integer with the number of press that is paired with
this release.}
@entry[x]{A double float with the x coordinate, in widget allocation
coordinates.}
@entry[y]{A double float with the y coordinate, in widget allocation
coordinates.}
@end{table}
@subheading{The \"stopped\" signal}
@begin{pre}
lambda (gesture) :run-last
@end{pre}
The signal is emitted whenever any time/distance threshold has been
exceeded.
@begin[code]{table}
@entry[gesture]{The @sym{gtk-gesture-multi-press} object which
received the signal.}
@end{table}
@end{dictionary}
@see-class{gtk-gesture}")
(declaim (inline gtk-gesture-multi-press-new))
(defun gtk-gesture-multi-press-new (widget)
#+cl-cffi-gtk-documentation
"@version{2020-9-11}
@argument[widget]{a @class{gtk-widget} object}
@return{A newly created @class{gtk-gesture-multi-press} object.}
@begin{short}
Returns a newly created gesture that recognizes single and multiple presses.
@end{short}
@see-function{gtk-gesture-multi-press}"
(make-instance 'gtk-gesture-multi-press
:widget widget))
(export 'gtk-gesture-multi-press-new)
gtk_gesture_multi_press_get_area ( )
(defun (setf gtk-gesture-multi-press-area) (rect gesture)
(foreign-funcall "gtk_gesture_multi_press_set_area"
(g-object gtk-gesture-multi-press) gesture
(g-boxed-foreign gdk-rectangle) rect
:void)
rect)
(defcfun ("gtk_gesture_multi_press_get_area" %gtk-gesture-multi-press-area)
:boolean
(gesture (g-object gtk-gesture-multi-press))
(rect (g-boxed-foreign gdk-rectangle)))
(defun gtk-gesture-multi-press-area (gesture)
#+cl-cffi-gtk-documentation
"@version{2020-9-11}
@syntax[]{(gtk-gesture-multi-press-area gesture) => rect}
@syntax[]{(setf (gtk-gesture-multi-press-area gesture) rect)}
@argument[gesture]{a @class{gtk-gesture-multi-press} object}
@argument[rect]{a @class{gdk-rectangle} with the press area}
@begin{short}
Accessor of the press area of the gesture.
@end{short}
The function @sym{gtk-gesture-multi-press-area} gets the press area. The
function @sym{(setf gtk-gesture-multi-press-area)} sets the press area.
If @arg{rect} is non-@code{nil}, the press area will be checked to be confined
within the rectangle, otherwise the button count will be reset so the press is
seen as being the first one. If @arg{rect} is @code{nil}, the area will be
reset to an unrestricted state.
Note: The rectangle is only used to determine whether any non-first click
falls within the expected area. This is not akin to an input shape.
@see-class{gtk-gesture-multi-press}
@see-class{gdk-rectangle}"
(let ((rect (gdk-rectangle-new)))
(when (%gtk-gesture-multi-press-area gesture rect)
rect)))
(export 'gtk-gesture-multi-press-area)
|
5f25077c793925c96d1efe2c2fe2938c5651112db72b9b982eacbcf128502128 | avsm/platform | opamDarcs.ml | (**************************************************************************)
(* *)
Copyright 2012 - 2015 OCamlPro
Copyright 2012 INRIA
(* *)
(* All rights reserved. This file is distributed under the terms of the *)
GNU Lesser General Public License version 2.1 , with the special
(* exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
open OpamFilename.Op
open OpamProcess.Job.Op
module VCS = struct
let name = `darcs
let exists repo_root =
OpamFilename.exists_dir (repo_root / "_darcs")
let darcs repo_root =
let dir = OpamFilename.Dir.to_string repo_root in
fun ?verbose ?env ?stdout args ->
OpamSystem.make_command ~dir ?verbose ?env ?stdout "darcs" args
let with_tag repo_url = match repo_url.OpamUrl.hash with
| None -> fun cmd -> cmd
| Some t -> fun cmd -> cmd @ [ "-t"; t ]
let init repo_root _repo_url =
OpamFilename.mkdir repo_root;
darcs repo_root [ "init" ]
@@> fun r ->
OpamSystem.raise_on_process_error r;
Done ()
let vc_dir repo_root = repo_root / "_darcs"
Darcs has no branches , no proper diff , no way to reset , ca n't return a
workdir diff including added / removed files ... That makes it hard for
handling as a remote , and the following is a bit convoluted .
workdir diff including added/removed files... That makes it hard for
handling as a remote, and the following is a bit convoluted. *)
let opam_remote_tag = "opam-remote-tag"
Marks the last fetched state
let opam_reverse_commit = "opam-revert-laststate"
let opam_local_tag = "opam-local-tag"
Marks the current state , in the form of a reversing patch on top of the
fetched state
fetched state *)
let fetch ?cache_dir:_ repo_root repo_url =
(* Just do a fresh pull into a temp directory, and replace _darcs/
There is no easy way to diff or make sure darcs forgets about local
patches otherwise. *)
OpamFilename.with_tmp_dir_job @@ fun d ->
let repodir = d / "repo" in
darcs repo_root
(with_tag repo_url
[ "get"; OpamUrl.base_url repo_url;
"--repodir"; OpamFilename.Dir.to_string repodir;
"--quiet"; "--lazy" ])
(* --no-working-dir would be fine, except it is stored in _darcs/format *)
@@> fun r ->
OpamSystem.raise_on_process_error r;
let darcsdir = vc_dir repo_root in
OpamFilename.rmdir darcsdir;
OpamFilename.move_dir ~src:(vc_dir repodir) ~dst:darcsdir;
(* We put the patch that reverts to the current state on top *)
darcs repo_root [ "tag"; opam_remote_tag; "-A"; "opam" ] @@> fun r ->
OpamSystem.raise_on_process_error r;
darcs repo_root
[ "record"; "-l"; "--boring"; "--all";
"-m"; opam_reverse_commit; "-A"; "opam" ] @@> fun _r ->
May fail if patch empty , it 's ok , we keep the two tags for comparison
darcs repo_root [ "tag"; opam_local_tag; "-A"; "opam" ] @@> fun r ->
OpamSystem.raise_on_process_error r;
Done ()
let reset_tree repo_root _repo_url =
darcs repo_root [ "obliterate"; "--all"; "-t"; opam_local_tag ]
@@> fun r ->
OpamSystem.raise_on_process_error r;
darcs repo_root [ "obliterate"; "--all"; "-p"; opam_reverse_commit ]
@@> fun r ->
(* returns 0 even if patch doesn't exist *)
OpamSystem.raise_on_process_error r;
Done ()
let patch_applied _ _ = Done ()
let revision repo_root =
' Weak hash ' is only supported from 2.10.3 , so provide a fallback
darcs repo_root [ "show"; "repo" ] @@> fun r ->
OpamSystem.raise_on_process_error r;
try
OpamStd.List.find_map
(fun s ->
match OpamStd.String.rcut_at s ' ' with
| Some (label, value)
when OpamStd.String.contains ~sub:"Weak Hash" label ->
Some (Done (Some value))
| _ -> None)
r.OpamProcess.r_stdout
with Not_found ->
try
OpamStd.List.find_map
(fun s ->
match OpamStd.String.rcut_at s ' ' with
| Some (label, value)
when OpamStd.String.contains ~sub:"Num Patches" label ->
Some (Done (Some (Printf.sprintf "darcs-%s" value)))
| _ -> None)
r.OpamProcess.r_stdout
with Not_found ->
Done None
let is_up_to_date repo_root _repo_url =
darcs repo_root [ "log"; "-p"; opam_reverse_commit; "--last"; "2" ]
last 2 since the tag counts as one
@@> function
| { OpamProcess.r_code = 0; _ } -> Done false
| { OpamProcess.r_code = 1; _ } as r->
OpamProcess.cleanup ~force:true r;
Done true
| r -> OpamSystem.process_error r
let diff repo_root repo_url =
is_up_to_date repo_root repo_url @@+ function
| true -> Done None
| false ->
let patch_file = OpamSystem.temp_file ~auto_clean: false "darcs-diff" in
let finalise () = OpamSystem.remove_file patch_file in
OpamProcess.Job.catch (fun e -> finalise (); raise e) @@ fun () ->
darcs repo_root ~stdout:patch_file
[ "diff";
"--from-tag"; opam_remote_tag; "--to-tag"; opam_local_tag;
"--diff-command"; "diff -ruNa %2 %1"; "--no-pause-for-gui"; ]
(* changing 'from' and 'to' doesn't work, so run a reverse diff command
instead*)
@@> fun r ->
OpamSystem.raise_on_process_error r;
if OpamSystem.file_is_empty patch_file then
(finalise (); Done None)
else
Done (Some (OpamFilename.of_string patch_file))
let versioned_files repo_root =
darcs repo_root [ "show" ; "files" ]
@@> fun r ->
OpamSystem.raise_on_process_error r;
Done r.OpamProcess.r_stdout
No branches in Darcs
let is_dirty dir =
darcs dir [ "whatsnew"; "--quiet"; "--summary" ]
@@> fun r -> Done (OpamProcess.check_success_and_cleanup r)
end
module B = OpamVCS.Make(VCS)
| null | https://raw.githubusercontent.com/avsm/platform/b254e3c6b60f3c0c09dfdcde92eb1abdc267fa1c/duniverse/opam-client.2.0.5%2Bdune/src/repository/opamDarcs.ml | ocaml | ************************************************************************
All rights reserved. This file is distributed under the terms of the
exception on linking described in the file LICENSE.
************************************************************************
Just do a fresh pull into a temp directory, and replace _darcs/
There is no easy way to diff or make sure darcs forgets about local
patches otherwise.
--no-working-dir would be fine, except it is stored in _darcs/format
We put the patch that reverts to the current state on top
returns 0 even if patch doesn't exist
changing 'from' and 'to' doesn't work, so run a reverse diff command
instead | Copyright 2012 - 2015 OCamlPro
Copyright 2012 INRIA
GNU Lesser General Public License version 2.1 , with the special
open OpamFilename.Op
open OpamProcess.Job.Op
module VCS = struct
let name = `darcs
let exists repo_root =
OpamFilename.exists_dir (repo_root / "_darcs")
let darcs repo_root =
let dir = OpamFilename.Dir.to_string repo_root in
fun ?verbose ?env ?stdout args ->
OpamSystem.make_command ~dir ?verbose ?env ?stdout "darcs" args
let with_tag repo_url = match repo_url.OpamUrl.hash with
| None -> fun cmd -> cmd
| Some t -> fun cmd -> cmd @ [ "-t"; t ]
let init repo_root _repo_url =
OpamFilename.mkdir repo_root;
darcs repo_root [ "init" ]
@@> fun r ->
OpamSystem.raise_on_process_error r;
Done ()
let vc_dir repo_root = repo_root / "_darcs"
Darcs has no branches , no proper diff , no way to reset , ca n't return a
workdir diff including added / removed files ... That makes it hard for
handling as a remote , and the following is a bit convoluted .
workdir diff including added/removed files... That makes it hard for
handling as a remote, and the following is a bit convoluted. *)
let opam_remote_tag = "opam-remote-tag"
Marks the last fetched state
let opam_reverse_commit = "opam-revert-laststate"
let opam_local_tag = "opam-local-tag"
Marks the current state , in the form of a reversing patch on top of the
fetched state
fetched state *)
let fetch ?cache_dir:_ repo_root repo_url =
OpamFilename.with_tmp_dir_job @@ fun d ->
let repodir = d / "repo" in
darcs repo_root
(with_tag repo_url
[ "get"; OpamUrl.base_url repo_url;
"--repodir"; OpamFilename.Dir.to_string repodir;
"--quiet"; "--lazy" ])
@@> fun r ->
OpamSystem.raise_on_process_error r;
let darcsdir = vc_dir repo_root in
OpamFilename.rmdir darcsdir;
OpamFilename.move_dir ~src:(vc_dir repodir) ~dst:darcsdir;
darcs repo_root [ "tag"; opam_remote_tag; "-A"; "opam" ] @@> fun r ->
OpamSystem.raise_on_process_error r;
darcs repo_root
[ "record"; "-l"; "--boring"; "--all";
"-m"; opam_reverse_commit; "-A"; "opam" ] @@> fun _r ->
May fail if patch empty , it 's ok , we keep the two tags for comparison
darcs repo_root [ "tag"; opam_local_tag; "-A"; "opam" ] @@> fun r ->
OpamSystem.raise_on_process_error r;
Done ()
let reset_tree repo_root _repo_url =
darcs repo_root [ "obliterate"; "--all"; "-t"; opam_local_tag ]
@@> fun r ->
OpamSystem.raise_on_process_error r;
darcs repo_root [ "obliterate"; "--all"; "-p"; opam_reverse_commit ]
@@> fun r ->
OpamSystem.raise_on_process_error r;
Done ()
let patch_applied _ _ = Done ()
let revision repo_root =
' Weak hash ' is only supported from 2.10.3 , so provide a fallback
darcs repo_root [ "show"; "repo" ] @@> fun r ->
OpamSystem.raise_on_process_error r;
try
OpamStd.List.find_map
(fun s ->
match OpamStd.String.rcut_at s ' ' with
| Some (label, value)
when OpamStd.String.contains ~sub:"Weak Hash" label ->
Some (Done (Some value))
| _ -> None)
r.OpamProcess.r_stdout
with Not_found ->
try
OpamStd.List.find_map
(fun s ->
match OpamStd.String.rcut_at s ' ' with
| Some (label, value)
when OpamStd.String.contains ~sub:"Num Patches" label ->
Some (Done (Some (Printf.sprintf "darcs-%s" value)))
| _ -> None)
r.OpamProcess.r_stdout
with Not_found ->
Done None
let is_up_to_date repo_root _repo_url =
darcs repo_root [ "log"; "-p"; opam_reverse_commit; "--last"; "2" ]
last 2 since the tag counts as one
@@> function
| { OpamProcess.r_code = 0; _ } -> Done false
| { OpamProcess.r_code = 1; _ } as r->
OpamProcess.cleanup ~force:true r;
Done true
| r -> OpamSystem.process_error r
let diff repo_root repo_url =
is_up_to_date repo_root repo_url @@+ function
| true -> Done None
| false ->
let patch_file = OpamSystem.temp_file ~auto_clean: false "darcs-diff" in
let finalise () = OpamSystem.remove_file patch_file in
OpamProcess.Job.catch (fun e -> finalise (); raise e) @@ fun () ->
darcs repo_root ~stdout:patch_file
[ "diff";
"--from-tag"; opam_remote_tag; "--to-tag"; opam_local_tag;
"--diff-command"; "diff -ruNa %2 %1"; "--no-pause-for-gui"; ]
@@> fun r ->
OpamSystem.raise_on_process_error r;
if OpamSystem.file_is_empty patch_file then
(finalise (); Done None)
else
Done (Some (OpamFilename.of_string patch_file))
let versioned_files repo_root =
darcs repo_root [ "show" ; "files" ]
@@> fun r ->
OpamSystem.raise_on_process_error r;
Done r.OpamProcess.r_stdout
No branches in Darcs
let is_dirty dir =
darcs dir [ "whatsnew"; "--quiet"; "--summary" ]
@@> fun r -> Done (OpamProcess.check_success_and_cleanup r)
end
module B = OpamVCS.Make(VCS)
|
f4500ec54f1140a0d6af5b147c0e26d73d5e99d52ef951a3808aebf12d639748 | racket/typed-racket | float.rkt | #lang racket/base
(require syntax/parse racket/sequence racket/flonum racket/promise
syntax/parse/experimental/specialize
syntax/id-table
(for-template racket/base racket/flonum racket/unsafe/ops racket/math)
"../utils/utils.rkt"
"../utils/tc-utils.rkt"
"../types/numeric-tower.rkt"
"../types/abbrev.rkt"
"utils.rkt"
"numeric-utils.rkt"
"logging.rkt"
"fixnum.rkt")
(provide float-opt-expr float-arg-expr int-expr float-op)
(define (mk-float-tbl generic)
(mk-unsafe-tbl generic "fl~a" "unsafe-fl~a"))
(define binary-float-ops
(mk-float-tbl (list #'+ #'- #'* #'/ #'min #'max #'expt)))
(define binary-float-comps
(free-id-table-set*
(mk-float-tbl (list #'= #'<= #'< #'> #'>=))
not a comparison , but takes 2 floats and does not return a float ,
;; unlike binary-float-ops
#'make-rectangular #'unsafe-make-flrectangular
#'make-flrectangular #'unsafe-make-flrectangular))
(define unary-float-ops
(free-id-table-set
(mk-float-tbl (list #'abs #'sin #'cos #'tan #'asin #'acos #'atan #'log #'exp
#'sqrt #'round #'floor #'ceiling #'truncate))
#'magnitude #'unsafe-flabs))
(define-literal-syntax-class -)
(define-literal-syntax-class /)
(define-literal-syntax-class sqr)
(define-literal-syntax-class zero?)
(define-literal-syntax-class add1)
(define-literal-syntax-class sub1)
(define-literal-syntax-class ->float^ (exact->inexact real->double-flonum))
(define-literal-syntax-class ->single-float^ (exact->inexact real->single-flonum))
(define-literal-syntax-class random)
(define-literal-syntax-class flrandom)
(define-merged-syntax-class random-op (random^ flrandom^))
(define-syntax-class (float-op tbl)
#:commit
(pattern i:id
#:when (free-id-table-ref tbl #'i #f)
#:with unsafe (begin (add-disappeared-use #'i)
(free-id-table-ref tbl #'i))))
(define-syntax-class/specialize float-expr (subtyped-expr -Flonum))
(define-syntax-class/specialize single-float-expr (subtyped-expr -SingleFlonum))
(define-syntax-class/specialize int-expr (subtyped-expr -Integer))
(define-syntax-class/specialize real-expr (subtyped-expr -Real))
(define-syntax-class/specialize unary-float-op (float-op unary-float-ops))
(define-syntax-class/specialize binary-float-op (float-op binary-float-ops))
(define-syntax-class/specialize binary-float-comp (float-op binary-float-comps))
;; if the result of an operation is of type float, its non float arguments
;; can be promoted, and we can use unsafe float operations
;; note: none of the unary operations have types where non-float arguments
;; can result in float (as opposed to real) results
(define-syntax-class float-arg-expr
#:commit
#:attributes (opt)
#:literal-sets (kernel-literals)
;; we can convert literals right away
(pattern (quote n)
#:when (and (real? (syntax->datum #'n))
(exact? (syntax->datum #'n)))
#:with opt #`'#,(real->double-flonum (syntax->datum #'n)))
(pattern e:fixnum-expr
#:attr opt (delay #'(unsafe-fx->fl e.opt)))
(pattern e:int-expr
#:attr opt (delay #'(->fl e.opt)))
(pattern :float-expr)
;; reals within float expressions are not always valid to optimize because
;; of the exact 0 problem, but since float-opt-expr checks whether the
;; surrounding expressing is of type Float and not just Real, this is safe
(pattern e:real-expr
#:attr opt (delay #'(real->double-flonum e.opt))))
(define (log-float-real-missed-opt stx irritants)
(log-missed-optimization
"all args float-arg-expr, result not Float"
(string-append
"This expression has a Real type. The optimizer could optimize it if it had type Float."
(if (null? irritants)
""
" To fix, change the highlighted expression(s) to have Float type(s)."))
stx irritants))
(define-syntax-rule (log-fl-opt opt-label)
(log-opt opt-label "Float arithmetic specialization."))
(define (maybe-exact-rational? stx)
(and (subtypeof? stx -Real)
(not (subtypeof? stx -Flonum))
(not (subtypeof? stx -SingleFlonum))
(not (subtypeof? stx -Int))))
(define-syntax-class float-opt-expr
#:commit
#:literal-sets (kernel-literals)
(pattern (#%plain-app op:unary-float-op f:float-arg-expr)
#:when (let* ([safe-to-opt? (subtypeof? this-syntax -Flonum)]
[missed-optimization? (and (not safe-to-opt?)
(in-real-layer? this-syntax))])
(when missed-optimization?
(log-float-real-missed-opt this-syntax (list #'f)))
safe-to-opt?)
#:do [(log-fl-opt "unary float")]
#:with opt #'(op.unsafe f.opt))
(pattern (#%plain-app op:binary-float-op
;; for now, accept anything that can be coerced to float
;; finer-grained checking is done below
(~between fs:float-arg-expr 2 +inf.0) ...)
#:when (let* ([safe-to-opt?
;; For it to be safe, we need:
;; - the result to be a float, in which case coercing args to floats
;; won't change the result type
- all non - float arguments need to be provably non - zero
;; otherwise, we may hit corner cases like (* 0 <float>) => 0
or ( + 0 -0.0 ) = > -0.0 ( while ( + 0.0 -0.0 ) = > 0.0 )
- only one argument can be coerced . If more than one needs
;; coercion, we could end up turning exact (or single-float)
;; operations into float operations by accident.
;; (Note: could allow for more args, if not next to each other, but
probably not worth the trouble ( most ops have 2 args anyway ) )
(and (subtypeof? this-syntax -Flonum)
(for/and ([a (in-syntax #'(fs ...))])
flonum or provably non - zero
(or (subtypeof? a -Flonum)
(subtypeof? a (Un -PosReal -NegReal))))
(>= 1
(for/sum ([a (in-syntax #'(fs ...))]
#:when (not (subtypeof? a -Flonum)))
1)))]
;; if we don't have a return type of float, or if the return type is
;; float, but we can't optimize for some other reason, we missed an
;; optimization opportunity, report it
;; ignore operations that stay within integers or rationals, since
;; these have nothing to do with float optimizations
[missed-optimization? (and (not safe-to-opt?)
(or (in-real-layer? this-syntax)
(in-float-layer? this-syntax)))])
(when missed-optimization?
(log-float-real-missed-opt
this-syntax
(for/list ([x (in-syntax #'(fs ...))]
#:unless (subtypeof? x -Flonum))
x)))
;; If an optimization was expected (whether it was safe or not doesn't matter),
;; report subexpressions doing expensive exact arithmetic (Exact-Rational and
;; Real arithmetic), since that extra precision would be "lost" by going to
;; floating-point in this expression.
;; Since this exact behavior can be desirable, it's invalid to optimize it away,
;; but it's more likely to be there by accident. I can't really think of many
;; use cases for computing exact intermediate results, then converting them to
;; floats at the end.
(when (or safe-to-opt? missed-optimization?)
(define extra-precision-subexprs
(filter
values
(for/list ([subexpr (in-syntax #'(fs ...))]
#:when (or (and (in-real-layer? subexpr)
;; exclude single-flonums
(not (subtypeof? subexpr -InexactReal)))
(in-rational-layer? subexpr)))
(syntax-parse subexpr
;; Only warn about subexpressions that actually perform exact arithmetic.
;; There's not much point in warning about literals/variables that will
;; be coerced anyway, or about things like:
;; (vector-ref vector-of-rationals x)
;; which don't perform arithmetic despite returning numbers.
[(~and e:arith-expr (op args ...))
;; if a subexpression has any float args, it will be reported as a
;; float-real mix missed opt, so this report would be redundant
#:when (for/and ([s (in-syntax #'(args ...))])
(not (in-float-layer? s)))
#'e]
[_ #f]))))
(when (and (not (null? extra-precision-subexprs))
(subtypeof? this-syntax -InexactReal))
(log-missed-optimization
"exact ops inside float expr"
"This expression has a Float type, but the highlighted subexpression(s) use exact arithmetic. The extra precision of the exact arithmetic will be lost. Using Float types in these subexpression(s) may result in performance gains without significant precision loss."
this-syntax extra-precision-subexprs)))
safe-to-opt?)
#:do [(log-fl-opt "binary float")]
#:with opt (n-ary->binary this-syntax #'op.unsafe #'(fs.opt ...)))
(pattern (#%plain-app op:binary-float-comp f1:float-expr f2:float-expr)
#:do [(log-fl-opt "binary float comp")]
#:with opt (syntax/loc this-syntax (op.unsafe f1.opt f2.opt)))
(pattern (#%plain-app op:binary-float-comp
f1:float-expr
f2:float-expr
fs:float-expr ...)
#:do [(log-fl-opt "multi float comp")]
#:with opt (n-ary-comp->binary this-syntax #'op.unsafe #'f1.opt #'f2.opt #'(fs.opt ...)))
(pattern (#%plain-app op:binary-float-comp args:opt-expr ...)
;; some args, but not all (otherwise above would have matched) are floats
;; mixed-type comparisons are slow and block futures
#:when (let ([some-float? (for/first ([e (in-syntax #'(args ...))]
#:when (subtypeof? e -Flonum))
e)])
(when some-float?
(define non-floats ; irritants
(for/list ([e (in-syntax #'(args ...))]
#:unless (subtypeof? e -Flonum))
e))
(log-missed-optimization
"generic comparison"
(string-append
"This expression compares values of different exactnesses, "
"which prevents optimization. "
"To fix, explicitly convert the highlighted expressions to "
"be of type Float.")
this-syntax
non-floats))
#f) ; keep trying other patterns
#:with opt #f) ; will never be reached
(pattern (#%plain-app op:-^ f:float-expr)
#:do [(log-fl-opt "unary float")]
#:with opt (syntax/loc this-syntax (unsafe-fl* -1.0 f.opt)))
(pattern (#%plain-app op:/^ f:float-expr)
#:do [(log-fl-opt "unary float")]
#:with opt (syntax/loc this-syntax (unsafe-fl/ 1.0 f.opt)))
(pattern (#%plain-app op:sqr^ f:float-expr)
#:do [(log-fl-opt "unary float")]
#:with opt (syntax/loc this-syntax (let ([tmp f.opt]) (unsafe-fl* tmp tmp))))
we can optimize exact->inexact if we know we 're giving it an Integer
(pattern (#%plain-app op:->float^ n:int-expr)
#:do [(log-fl-opt "int to float")]
#:with opt #'(->fl n.opt))
;; we can get rid of it altogether if we're giving it a float
(pattern (#%plain-app op:->float^ f:float-expr)
#:do [(log-fl-opt "float to float")]
#:with opt #'f.opt)
;; same for single-flonums
(pattern (#%plain-app op:->single-float^ f:single-float-expr)
#:do [(log-fl-opt "single-float to single-float")]
#:with opt #'f.opt)
(pattern (#%plain-app op:zero?^ f:float-expr)
#:do [(log-fl-opt "float zero?")]
#:with opt (syntax/loc this-syntax (unsafe-fl= f.opt 0.0)))
(pattern (#%plain-app op:add1^ n:float-expr)
#:do [(log-fl-opt "float add1")]
#:with opt (syntax/loc this-syntax (unsafe-fl+ n.opt 1.0)))
(pattern (#%plain-app op:sub1^ n:float-expr)
#:do [(log-fl-opt "float sub1")]
#:with opt (syntax/loc this-syntax (unsafe-fl- n.opt 1.0)))
(pattern (#%plain-app op:random-op prng:opt-expr)
#:when (subtypeof? #'prng -Pseudo-Random-Generator)
#:do [(log-fl-opt "float random")]
#:with opt (syntax/loc this-syntax (unsafe-flrandom prng.opt)))
(pattern (#%plain-app op:random^) ; random with no args
#:do [(log-fl-opt "float 0-arg random")
;; We introduce a reference to `current-pseudo-random-generator',
;; but, by optimizing, we're preventing the hidden cost reports
;; from triggering down the line (see hidden-cost.rkt), so we need
;; to do the logging ourselves.
(log-optimization-info "hidden parameter (random)" #'op)]
#:with opt (syntax/loc this-syntax (unsafe-flrandom (current-pseudo-random-generator))))
;; warn about (potentially) exact real arithmetic, in general
;; Note: These patterns don't perform optimization. They only produce logging
for consumption by Optimization Coach .
(pattern (#%plain-app op:binary-float-op n:opt-expr ...)
#:when (maybe-exact-rational? this-syntax)
#:do [(log-opt-info "possible exact real arith")]
#:with opt (syntax/loc this-syntax (op n.opt ...)))
(pattern (#%plain-app op:binary-float-comp n:opt-expr ...)
;; can't look at return type, since it's always bool
#:when (andmap maybe-exact-rational? (syntax->list #'(n ...)))
#:do [(log-opt-info "possible exact real arith")]
#:with opt (syntax/loc this-syntax (op n.opt ...)))
(pattern (#%plain-app op:unary-float-op n:opt-expr ...)
#:when (maybe-exact-rational? this-syntax)
#:do [(log-opt-info "possible exact real arith")]
#:with opt (syntax/loc this-syntax (op n.opt ...)))
)
| null | https://raw.githubusercontent.com/racket/typed-racket/6ea20bec8d41e1a188d7f831c35423293a89c98e/typed-racket-lib/typed-racket/optimizer/float.rkt | racket | unlike binary-float-ops
if the result of an operation is of type float, its non float arguments
can be promoted, and we can use unsafe float operations
note: none of the unary operations have types where non-float arguments
can result in float (as opposed to real) results
we can convert literals right away
reals within float expressions are not always valid to optimize because
of the exact 0 problem, but since float-opt-expr checks whether the
surrounding expressing is of type Float and not just Real, this is safe
for now, accept anything that can be coerced to float
finer-grained checking is done below
For it to be safe, we need:
- the result to be a float, in which case coercing args to floats
won't change the result type
otherwise, we may hit corner cases like (* 0 <float>) => 0
coercion, we could end up turning exact (or single-float)
operations into float operations by accident.
(Note: could allow for more args, if not next to each other, but
if we don't have a return type of float, or if the return type is
float, but we can't optimize for some other reason, we missed an
optimization opportunity, report it
ignore operations that stay within integers or rationals, since
these have nothing to do with float optimizations
If an optimization was expected (whether it was safe or not doesn't matter),
report subexpressions doing expensive exact arithmetic (Exact-Rational and
Real arithmetic), since that extra precision would be "lost" by going to
floating-point in this expression.
Since this exact behavior can be desirable, it's invalid to optimize it away,
but it's more likely to be there by accident. I can't really think of many
use cases for computing exact intermediate results, then converting them to
floats at the end.
exclude single-flonums
Only warn about subexpressions that actually perform exact arithmetic.
There's not much point in warning about literals/variables that will
be coerced anyway, or about things like:
(vector-ref vector-of-rationals x)
which don't perform arithmetic despite returning numbers.
if a subexpression has any float args, it will be reported as a
float-real mix missed opt, so this report would be redundant
some args, but not all (otherwise above would have matched) are floats
mixed-type comparisons are slow and block futures
irritants
keep trying other patterns
will never be reached
we can get rid of it altogether if we're giving it a float
same for single-flonums
random with no args
We introduce a reference to `current-pseudo-random-generator',
but, by optimizing, we're preventing the hidden cost reports
from triggering down the line (see hidden-cost.rkt), so we need
to do the logging ourselves.
warn about (potentially) exact real arithmetic, in general
Note: These patterns don't perform optimization. They only produce logging
can't look at return type, since it's always bool | #lang racket/base
(require syntax/parse racket/sequence racket/flonum racket/promise
syntax/parse/experimental/specialize
syntax/id-table
(for-template racket/base racket/flonum racket/unsafe/ops racket/math)
"../utils/utils.rkt"
"../utils/tc-utils.rkt"
"../types/numeric-tower.rkt"
"../types/abbrev.rkt"
"utils.rkt"
"numeric-utils.rkt"
"logging.rkt"
"fixnum.rkt")
(provide float-opt-expr float-arg-expr int-expr float-op)
(define (mk-float-tbl generic)
(mk-unsafe-tbl generic "fl~a" "unsafe-fl~a"))
(define binary-float-ops
(mk-float-tbl (list #'+ #'- #'* #'/ #'min #'max #'expt)))
(define binary-float-comps
(free-id-table-set*
(mk-float-tbl (list #'= #'<= #'< #'> #'>=))
not a comparison , but takes 2 floats and does not return a float ,
#'make-rectangular #'unsafe-make-flrectangular
#'make-flrectangular #'unsafe-make-flrectangular))
(define unary-float-ops
(free-id-table-set
(mk-float-tbl (list #'abs #'sin #'cos #'tan #'asin #'acos #'atan #'log #'exp
#'sqrt #'round #'floor #'ceiling #'truncate))
#'magnitude #'unsafe-flabs))
(define-literal-syntax-class -)
(define-literal-syntax-class /)
(define-literal-syntax-class sqr)
(define-literal-syntax-class zero?)
(define-literal-syntax-class add1)
(define-literal-syntax-class sub1)
(define-literal-syntax-class ->float^ (exact->inexact real->double-flonum))
(define-literal-syntax-class ->single-float^ (exact->inexact real->single-flonum))
(define-literal-syntax-class random)
(define-literal-syntax-class flrandom)
(define-merged-syntax-class random-op (random^ flrandom^))
(define-syntax-class (float-op tbl)
#:commit
(pattern i:id
#:when (free-id-table-ref tbl #'i #f)
#:with unsafe (begin (add-disappeared-use #'i)
(free-id-table-ref tbl #'i))))
(define-syntax-class/specialize float-expr (subtyped-expr -Flonum))
(define-syntax-class/specialize single-float-expr (subtyped-expr -SingleFlonum))
(define-syntax-class/specialize int-expr (subtyped-expr -Integer))
(define-syntax-class/specialize real-expr (subtyped-expr -Real))
(define-syntax-class/specialize unary-float-op (float-op unary-float-ops))
(define-syntax-class/specialize binary-float-op (float-op binary-float-ops))
(define-syntax-class/specialize binary-float-comp (float-op binary-float-comps))
(define-syntax-class float-arg-expr
#:commit
#:attributes (opt)
#:literal-sets (kernel-literals)
(pattern (quote n)
#:when (and (real? (syntax->datum #'n))
(exact? (syntax->datum #'n)))
#:with opt #`'#,(real->double-flonum (syntax->datum #'n)))
(pattern e:fixnum-expr
#:attr opt (delay #'(unsafe-fx->fl e.opt)))
(pattern e:int-expr
#:attr opt (delay #'(->fl e.opt)))
(pattern :float-expr)
(pattern e:real-expr
#:attr opt (delay #'(real->double-flonum e.opt))))
(define (log-float-real-missed-opt stx irritants)
(log-missed-optimization
"all args float-arg-expr, result not Float"
(string-append
"This expression has a Real type. The optimizer could optimize it if it had type Float."
(if (null? irritants)
""
" To fix, change the highlighted expression(s) to have Float type(s)."))
stx irritants))
(define-syntax-rule (log-fl-opt opt-label)
(log-opt opt-label "Float arithmetic specialization."))
(define (maybe-exact-rational? stx)
(and (subtypeof? stx -Real)
(not (subtypeof? stx -Flonum))
(not (subtypeof? stx -SingleFlonum))
(not (subtypeof? stx -Int))))
(define-syntax-class float-opt-expr
#:commit
#:literal-sets (kernel-literals)
(pattern (#%plain-app op:unary-float-op f:float-arg-expr)
#:when (let* ([safe-to-opt? (subtypeof? this-syntax -Flonum)]
[missed-optimization? (and (not safe-to-opt?)
(in-real-layer? this-syntax))])
(when missed-optimization?
(log-float-real-missed-opt this-syntax (list #'f)))
safe-to-opt?)
#:do [(log-fl-opt "unary float")]
#:with opt #'(op.unsafe f.opt))
(pattern (#%plain-app op:binary-float-op
(~between fs:float-arg-expr 2 +inf.0) ...)
#:when (let* ([safe-to-opt?
- all non - float arguments need to be provably non - zero
or ( + 0 -0.0 ) = > -0.0 ( while ( + 0.0 -0.0 ) = > 0.0 )
- only one argument can be coerced . If more than one needs
probably not worth the trouble ( most ops have 2 args anyway ) )
(and (subtypeof? this-syntax -Flonum)
(for/and ([a (in-syntax #'(fs ...))])
flonum or provably non - zero
(or (subtypeof? a -Flonum)
(subtypeof? a (Un -PosReal -NegReal))))
(>= 1
(for/sum ([a (in-syntax #'(fs ...))]
#:when (not (subtypeof? a -Flonum)))
1)))]
[missed-optimization? (and (not safe-to-opt?)
(or (in-real-layer? this-syntax)
(in-float-layer? this-syntax)))])
(when missed-optimization?
(log-float-real-missed-opt
this-syntax
(for/list ([x (in-syntax #'(fs ...))]
#:unless (subtypeof? x -Flonum))
x)))
(when (or safe-to-opt? missed-optimization?)
(define extra-precision-subexprs
(filter
values
(for/list ([subexpr (in-syntax #'(fs ...))]
#:when (or (and (in-real-layer? subexpr)
(not (subtypeof? subexpr -InexactReal)))
(in-rational-layer? subexpr)))
(syntax-parse subexpr
[(~and e:arith-expr (op args ...))
#:when (for/and ([s (in-syntax #'(args ...))])
(not (in-float-layer? s)))
#'e]
[_ #f]))))
(when (and (not (null? extra-precision-subexprs))
(subtypeof? this-syntax -InexactReal))
(log-missed-optimization
"exact ops inside float expr"
"This expression has a Float type, but the highlighted subexpression(s) use exact arithmetic. The extra precision of the exact arithmetic will be lost. Using Float types in these subexpression(s) may result in performance gains without significant precision loss."
this-syntax extra-precision-subexprs)))
safe-to-opt?)
#:do [(log-fl-opt "binary float")]
#:with opt (n-ary->binary this-syntax #'op.unsafe #'(fs.opt ...)))
(pattern (#%plain-app op:binary-float-comp f1:float-expr f2:float-expr)
#:do [(log-fl-opt "binary float comp")]
#:with opt (syntax/loc this-syntax (op.unsafe f1.opt f2.opt)))
(pattern (#%plain-app op:binary-float-comp
f1:float-expr
f2:float-expr
fs:float-expr ...)
#:do [(log-fl-opt "multi float comp")]
#:with opt (n-ary-comp->binary this-syntax #'op.unsafe #'f1.opt #'f2.opt #'(fs.opt ...)))
(pattern (#%plain-app op:binary-float-comp args:opt-expr ...)
#:when (let ([some-float? (for/first ([e (in-syntax #'(args ...))]
#:when (subtypeof? e -Flonum))
e)])
(when some-float?
(for/list ([e (in-syntax #'(args ...))]
#:unless (subtypeof? e -Flonum))
e))
(log-missed-optimization
"generic comparison"
(string-append
"This expression compares values of different exactnesses, "
"which prevents optimization. "
"To fix, explicitly convert the highlighted expressions to "
"be of type Float.")
this-syntax
non-floats))
(pattern (#%plain-app op:-^ f:float-expr)
#:do [(log-fl-opt "unary float")]
#:with opt (syntax/loc this-syntax (unsafe-fl* -1.0 f.opt)))
(pattern (#%plain-app op:/^ f:float-expr)
#:do [(log-fl-opt "unary float")]
#:with opt (syntax/loc this-syntax (unsafe-fl/ 1.0 f.opt)))
(pattern (#%plain-app op:sqr^ f:float-expr)
#:do [(log-fl-opt "unary float")]
#:with opt (syntax/loc this-syntax (let ([tmp f.opt]) (unsafe-fl* tmp tmp))))
we can optimize exact->inexact if we know we 're giving it an Integer
(pattern (#%plain-app op:->float^ n:int-expr)
#:do [(log-fl-opt "int to float")]
#:with opt #'(->fl n.opt))
(pattern (#%plain-app op:->float^ f:float-expr)
#:do [(log-fl-opt "float to float")]
#:with opt #'f.opt)
(pattern (#%plain-app op:->single-float^ f:single-float-expr)
#:do [(log-fl-opt "single-float to single-float")]
#:with opt #'f.opt)
(pattern (#%plain-app op:zero?^ f:float-expr)
#:do [(log-fl-opt "float zero?")]
#:with opt (syntax/loc this-syntax (unsafe-fl= f.opt 0.0)))
(pattern (#%plain-app op:add1^ n:float-expr)
#:do [(log-fl-opt "float add1")]
#:with opt (syntax/loc this-syntax (unsafe-fl+ n.opt 1.0)))
(pattern (#%plain-app op:sub1^ n:float-expr)
#:do [(log-fl-opt "float sub1")]
#:with opt (syntax/loc this-syntax (unsafe-fl- n.opt 1.0)))
(pattern (#%plain-app op:random-op prng:opt-expr)
#:when (subtypeof? #'prng -Pseudo-Random-Generator)
#:do [(log-fl-opt "float random")]
#:with opt (syntax/loc this-syntax (unsafe-flrandom prng.opt)))
#:do [(log-fl-opt "float 0-arg random")
(log-optimization-info "hidden parameter (random)" #'op)]
#:with opt (syntax/loc this-syntax (unsafe-flrandom (current-pseudo-random-generator))))
for consumption by Optimization Coach .
(pattern (#%plain-app op:binary-float-op n:opt-expr ...)
#:when (maybe-exact-rational? this-syntax)
#:do [(log-opt-info "possible exact real arith")]
#:with opt (syntax/loc this-syntax (op n.opt ...)))
(pattern (#%plain-app op:binary-float-comp n:opt-expr ...)
#:when (andmap maybe-exact-rational? (syntax->list #'(n ...)))
#:do [(log-opt-info "possible exact real arith")]
#:with opt (syntax/loc this-syntax (op n.opt ...)))
(pattern (#%plain-app op:unary-float-op n:opt-expr ...)
#:when (maybe-exact-rational? this-syntax)
#:do [(log-opt-info "possible exact real arith")]
#:with opt (syntax/loc this-syntax (op n.opt ...)))
)
|
6766369fd81b94b984237d85c4a4db69b1006a3538841946970ab445e441609d | vans163/stargate | stargate_sup.erl | -module(stargate_sup).
-behaviour(supervisor).
-compile(export_all).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
Spec = {
stargate_child_gen, {stargate_child_gen, start_link, []},
permanent, 5000, worker, [stargate_child_gen]
},
{ok,
{{simple_one_for_one, 2, 10}, [Spec]}
}.
child_pids() ->
Children = supervisor:which_children(?MODULE),
[P || {undefined,P,worker,[stargate_child_gen]} <- Children].
start_child(StargateArgs) ->
supervisor:start_child(?MODULE, [StargateArgs]).
terminate_child(ChildPid) ->
supervisor:terminate_child(?MODULE, ChildPid). | null | https://raw.githubusercontent.com/vans163/stargate/0860dc5f8901dcb51db25224d35885ed6e0f5ff3/src/app/stargate_sup.erl | erlang | -module(stargate_sup).
-behaviour(supervisor).
-compile(export_all).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
Spec = {
stargate_child_gen, {stargate_child_gen, start_link, []},
permanent, 5000, worker, [stargate_child_gen]
},
{ok,
{{simple_one_for_one, 2, 10}, [Spec]}
}.
child_pids() ->
Children = supervisor:which_children(?MODULE),
[P || {undefined,P,worker,[stargate_child_gen]} <- Children].
start_child(StargateArgs) ->
supervisor:start_child(?MODULE, [StargateArgs]).
terminate_child(ChildPid) ->
supervisor:terminate_child(?MODULE, ChildPid). | |
465ac0921b36732fc8c4a726fbeff7c9831a00969e4a514edb0b6e389b5cf384 | ghcjs/ghcjs-dom | Document.hs | # LANGUAGE CPP #
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ConstraintKinds #-}
module GHCJS.DOM.Document (
module Export
, createElement
, createElement_
, createElementNS
, createElementNS_
) where
#ifdef GHCJS_DOM_DEBUG
import Control.Monad (void)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.IORef (atomicModifyIORef', IORef, newIORef, readIORef)
import GHC.Stack
(SrcLoc, CallStack, callStack, getCallStack, HasCallStack)
import System.IO.Unsafe (unsafePerformIO)
import Text.Read (readMaybe)
import GHCJS.DOM.Types (Element(..), MonadDOM, ToJSString, JSString)
import GHCJS.DOM.Debug.Internal (cacheStack)
import GHCJS.DOM.Element (setAttribute, getAttribute)
#ifdef MIN_VERSION_ghcjs_dom_jsffi
import qualified "ghcjs-dom-jsffi" GHCJS.DOM.Document as Raw (createElement, createElement_, createElementNS, createElementNS_)
import "ghcjs-dom-jsffi" GHCJS.DOM.Document as Export hiding (createElement, createElement_, createElementNS, createElementNS_)
#else
import qualified "jsaddle-dom" GHCJS.DOM.Document as Raw (createElement, createElement_, createElementNS, createElementNS_)
import "jsaddle-dom" GHCJS.DOM.Document as Export hiding (createElement, createElement_, createElementNS, createElementNS_)
#endif
createElement
:: (MonadDOM m, IsDocument doc, ToJSString localName, HasCallStack)
=> doc
-> localName
-> m Element
createElement doc localName = do
e <- Raw.createElement doc localName
let cs = getCallStack callStack
setAttribute e ("hs-creator"::JSString) . show =<< cacheStack cs
return e
createElement_
:: (MonadDOM m, IsDocument doc, ToJSString localName, HasCallStack)
=> doc
-> localName
-> m ()
createElement_ doc localName = void $ createElement doc localName
createElementNS
:: (MonadDOM m, IsDocument doc, ToJSString namespaceURI, ToJSString qualifiedName, HasCallStack)
=> doc
-> Maybe namespaceURI
-> qualifiedName
-> m Element
createElementNS doc namespaceURI qualifiedName = do
e <- Raw.createElementNS doc namespaceURI qualifiedName
setAttribute e ("haskell-stack"::JSString) . show =<< cacheStack (getCallStack callStack)
return e
createElementNS_
:: (MonadDOM m, IsDocument doc, ToJSString namespaceURI, ToJSString qualifiedName, HasCallStack)
=> doc
-> Maybe namespaceURI
-> qualifiedName
-> m ()
createElementNS_ doc namespaceURI qualifiedName = void $ createElementNS doc namespaceURI qualifiedName
#else
#ifdef MIN_VERSION_ghcjs_dom_jsffi
import "ghcjs-dom-jsffi" GHCJS.DOM.Document (createElement, createElement_, createElementNS, createElementNS_)
import "ghcjs-dom-jsffi" GHCJS.DOM.Document as Export hiding (createElement, createElement_, createElementNS, createElementNS_)
#else
import "jsaddle-dom" GHCJS.DOM.Document (createElement, createElement_, createElementNS, createElementNS_)
import "jsaddle-dom" GHCJS.DOM.Document as Export hiding (createElement, createElement_, createElementNS, createElementNS_)
#endif
#endif
| null | https://raw.githubusercontent.com/ghcjs/ghcjs-dom/749963557d878d866be2d0184079836f367dd0ea/ghcjs-dom/src/GHCJS/DOM/Document.hs | haskell | # LANGUAGE PackageImports #
# LANGUAGE OverloadedStrings #
# LANGUAGE ConstraintKinds # | # LANGUAGE CPP #
module GHCJS.DOM.Document (
module Export
, createElement
, createElement_
, createElementNS
, createElementNS_
) where
#ifdef GHCJS_DOM_DEBUG
import Control.Monad (void)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.IORef (atomicModifyIORef', IORef, newIORef, readIORef)
import GHC.Stack
(SrcLoc, CallStack, callStack, getCallStack, HasCallStack)
import System.IO.Unsafe (unsafePerformIO)
import Text.Read (readMaybe)
import GHCJS.DOM.Types (Element(..), MonadDOM, ToJSString, JSString)
import GHCJS.DOM.Debug.Internal (cacheStack)
import GHCJS.DOM.Element (setAttribute, getAttribute)
#ifdef MIN_VERSION_ghcjs_dom_jsffi
import qualified "ghcjs-dom-jsffi" GHCJS.DOM.Document as Raw (createElement, createElement_, createElementNS, createElementNS_)
import "ghcjs-dom-jsffi" GHCJS.DOM.Document as Export hiding (createElement, createElement_, createElementNS, createElementNS_)
#else
import qualified "jsaddle-dom" GHCJS.DOM.Document as Raw (createElement, createElement_, createElementNS, createElementNS_)
import "jsaddle-dom" GHCJS.DOM.Document as Export hiding (createElement, createElement_, createElementNS, createElementNS_)
#endif
createElement
:: (MonadDOM m, IsDocument doc, ToJSString localName, HasCallStack)
=> doc
-> localName
-> m Element
createElement doc localName = do
e <- Raw.createElement doc localName
let cs = getCallStack callStack
setAttribute e ("hs-creator"::JSString) . show =<< cacheStack cs
return e
createElement_
:: (MonadDOM m, IsDocument doc, ToJSString localName, HasCallStack)
=> doc
-> localName
-> m ()
createElement_ doc localName = void $ createElement doc localName
createElementNS
:: (MonadDOM m, IsDocument doc, ToJSString namespaceURI, ToJSString qualifiedName, HasCallStack)
=> doc
-> Maybe namespaceURI
-> qualifiedName
-> m Element
createElementNS doc namespaceURI qualifiedName = do
e <- Raw.createElementNS doc namespaceURI qualifiedName
setAttribute e ("haskell-stack"::JSString) . show =<< cacheStack (getCallStack callStack)
return e
createElementNS_
:: (MonadDOM m, IsDocument doc, ToJSString namespaceURI, ToJSString qualifiedName, HasCallStack)
=> doc
-> Maybe namespaceURI
-> qualifiedName
-> m ()
createElementNS_ doc namespaceURI qualifiedName = void $ createElementNS doc namespaceURI qualifiedName
#else
#ifdef MIN_VERSION_ghcjs_dom_jsffi
import "ghcjs-dom-jsffi" GHCJS.DOM.Document (createElement, createElement_, createElementNS, createElementNS_)
import "ghcjs-dom-jsffi" GHCJS.DOM.Document as Export hiding (createElement, createElement_, createElementNS, createElementNS_)
#else
import "jsaddle-dom" GHCJS.DOM.Document (createElement, createElement_, createElementNS, createElementNS_)
import "jsaddle-dom" GHCJS.DOM.Document as Export hiding (createElement, createElement_, createElementNS, createElementNS_)
#endif
#endif
|
ce10db1e588dafc372e88565dea0b38c4db9990a2db02350263c9173bb833994 | niquola/reframe-template | core.cljs | (ns ui.coverage.core
(:require-macros [reagent.ratom :refer [reaction]])
(:require [reagent.core :as reagent]
[re-frame.core :as rf]
[ui.routes :refer [href]]
[ui.widgets :as wgt]
[ui.widgets.lookup :as lookup]
[ui.styles :as styles]
[clojure.string :as str]
[cljs.pprint :as pp]
[re-form.core :as form]
[ui.pages :as pages]
[clojure.string :as str]))
(rf/reg-sub-raw
:coverages
(fn [db _] (reaction (:Coverage @db))))
(defn index [{pid :pt/id}]
(rf/dispatch [:fhir/search {:resourceType "Coverage" :query {:planholder-reference (str "Patient/" pid)}}])
(let [path [:form :patient :indsurance]
coverages (rf/subscribe [:coverages]) ]
(fn [_]
[:div.index.container-fluid
[:br]
(if (empty? @coverages)
[:div.text-center
[:p "There are no patient insurance"]
[:br]
[:a.btn.btn-primary
{:href (href :patients pid :coverages :new)} "Add insurance"]]
[:table.table
[:thead
[:tr
[:th "Bin"]
[:th "Status"]
[:th "Ref"]]]
[:tbody
(for [[id i] @coverages]
[:tr {:key (:id i)}
[:td [:a {:href (href :patients pid :coverages (:id i))}
(or (:bin i) "Some bin") ]]
[:td (:status i)]
[:td (pr-str (get-in i [:planholderReference :reference]))]])]])])))
(rf/reg-sub-raw
:coverages/current-coverage
(fn [db _]
(reaction (get @db :current-coverage))))
(rf/reg-event-fx
:coverages/current-coverage
(fn [coef [_ phase params]]
(if (= :init phase)
{:dispatch [:fhir/read {:resourceType "Coverage" :id (:coverage/id params) :into [:current-coverage]}]}
{:dispatch [:db/write [:current-coverage] nil]})))
(defn validate [_] {})
(defn show [{id :coverage/id}]
(let [path [:form :Coverage id]
cv (rf/subscribe [:db/by-path path])
errors (reaction (validate @cv)) ]
(rf/dispatch [:db/write path {}])
(rf/dispatch [:fhir/read {:resourceType "Coverage" :id id :into path}])
(fn [_]
[:div.form-group
[form/row {:path [:bin]
:errors errors
:label "BIN"
:base-path path
:as form/input}]
[:hr]
;[:div.form-group
;[form/submit-btn save-fn "Save"]
;" "
[ form / cancel - btn cancel - fn " Cancel " ] ]
])))
(defn new [_]
(fn [_]
[:div.container
[:h1 "New Form"]]
))
(pages/reg-page :coverages/index index)
(pages/reg-page :coverages/show show)
(pages/reg-page :coverages/new new)
| null | https://raw.githubusercontent.com/niquola/reframe-template/6482afabc1967d2b6cb39ddc3fc0158075535700/srcs/ui/coverage/core.cljs | clojure | [:div.form-group
[form/submit-btn save-fn "Save"]
" " | (ns ui.coverage.core
(:require-macros [reagent.ratom :refer [reaction]])
(:require [reagent.core :as reagent]
[re-frame.core :as rf]
[ui.routes :refer [href]]
[ui.widgets :as wgt]
[ui.widgets.lookup :as lookup]
[ui.styles :as styles]
[clojure.string :as str]
[cljs.pprint :as pp]
[re-form.core :as form]
[ui.pages :as pages]
[clojure.string :as str]))
(rf/reg-sub-raw
:coverages
(fn [db _] (reaction (:Coverage @db))))
(defn index [{pid :pt/id}]
(rf/dispatch [:fhir/search {:resourceType "Coverage" :query {:planholder-reference (str "Patient/" pid)}}])
(let [path [:form :patient :indsurance]
coverages (rf/subscribe [:coverages]) ]
(fn [_]
[:div.index.container-fluid
[:br]
(if (empty? @coverages)
[:div.text-center
[:p "There are no patient insurance"]
[:br]
[:a.btn.btn-primary
{:href (href :patients pid :coverages :new)} "Add insurance"]]
[:table.table
[:thead
[:tr
[:th "Bin"]
[:th "Status"]
[:th "Ref"]]]
[:tbody
(for [[id i] @coverages]
[:tr {:key (:id i)}
[:td [:a {:href (href :patients pid :coverages (:id i))}
(or (:bin i) "Some bin") ]]
[:td (:status i)]
[:td (pr-str (get-in i [:planholderReference :reference]))]])]])])))
(rf/reg-sub-raw
:coverages/current-coverage
(fn [db _]
(reaction (get @db :current-coverage))))
(rf/reg-event-fx
:coverages/current-coverage
(fn [coef [_ phase params]]
(if (= :init phase)
{:dispatch [:fhir/read {:resourceType "Coverage" :id (:coverage/id params) :into [:current-coverage]}]}
{:dispatch [:db/write [:current-coverage] nil]})))
(defn validate [_] {})
(defn show [{id :coverage/id}]
(let [path [:form :Coverage id]
cv (rf/subscribe [:db/by-path path])
errors (reaction (validate @cv)) ]
(rf/dispatch [:db/write path {}])
(rf/dispatch [:fhir/read {:resourceType "Coverage" :id id :into path}])
(fn [_]
[:div.form-group
[form/row {:path [:bin]
:errors errors
:label "BIN"
:base-path path
:as form/input}]
[:hr]
[ form / cancel - btn cancel - fn " Cancel " ] ]
])))
(defn new [_]
(fn [_]
[:div.container
[:h1 "New Form"]]
))
(pages/reg-page :coverages/index index)
(pages/reg-page :coverages/show show)
(pages/reg-page :coverages/new new)
|
7c4d31fbde52f14bb73f8c30646cc3d70138d58ed0fb719ac02f0990bd7203eb | flavioc/cl-hurd | port.lisp |
(in-package :hurd)
;;
;; This file implements a port abstraction like port_info from libports.
;; A port-info has send count and a receive right, we can also get new rights from it.
;;
(defclass port-info ()
((right :initform (port-allocate :right-receive)
:accessor port-right
:documentation "Right for this port")
(mscount :initform 0
:accessor mscount
:documentation "Send rights count")))
(defmethod deallocate-send-right ((port port-info))
"Deallocates the port's send right."
(port-deallocate (port-right port)))
(defmethod get-right ((port port-info))
"Gives the port right, incrementing the send count and requesting a notification when it goes away."
(when (zerop (mscount port))
(port-request-notification (port-right port)
:notify-no-senders
(1+ (mscount port))
(port-right port)
:make-send-once))
(incf (mscount port))
(port-right port))
(defmethod get-send-right ((port port-info))
"Gets a send right for 'port'."
(let ((right (get-right port)))
(port-insert-right right right :make-send)
right))
(defmethod port-cleanup ((port port-info))
"Cleanup routine for ports."
(when (port-right port)
(setf (mscount port) 0)
(port-mod-refs (port-right port) :right-receive -1)
(setf (port-right port) nil))
t)
| null | https://raw.githubusercontent.com/flavioc/cl-hurd/982232f47d1a0ff4df5fde2edad03b9df871470a/hurd/ports/port.lisp | lisp |
This file implements a port abstraction like port_info from libports.
A port-info has send count and a receive right, we can also get new rights from it.
|
(in-package :hurd)
(defclass port-info ()
((right :initform (port-allocate :right-receive)
:accessor port-right
:documentation "Right for this port")
(mscount :initform 0
:accessor mscount
:documentation "Send rights count")))
(defmethod deallocate-send-right ((port port-info))
"Deallocates the port's send right."
(port-deallocate (port-right port)))
(defmethod get-right ((port port-info))
"Gives the port right, incrementing the send count and requesting a notification when it goes away."
(when (zerop (mscount port))
(port-request-notification (port-right port)
:notify-no-senders
(1+ (mscount port))
(port-right port)
:make-send-once))
(incf (mscount port))
(port-right port))
(defmethod get-send-right ((port port-info))
"Gets a send right for 'port'."
(let ((right (get-right port)))
(port-insert-right right right :make-send)
right))
(defmethod port-cleanup ((port port-info))
"Cleanup routine for ports."
(when (port-right port)
(setf (mscount port) 0)
(port-mod-refs (port-right port) :right-receive -1)
(setf (port-right port) nil))
t)
|
ac23fd548974748d5ff594d99d55e021e83e9a105ec13c874c82edc01da8d53d | pNre/Hera | dispatcher.ml | open Core
let modules =
[ (module Module_dictionary : Bot.Module)
; (module Module_markets : Bot.Module)
; (module Module_feeds : Bot.Module)
; (module Module_air_quality : Bot.Module)
; (module Module_morejpeg : Bot.Module)
; (module Module_preferences : Bot.Module)
; (module Module_faces : Bot.Module)
]
;;
let register m =
let module M = (val m : Bot.Module) in
M.register ()
;;
let on_update m update =
let module M = (val m : Bot.Module) in
M.on_update update
;;
let register_modules () = List.iter modules ~f:register
let modules_help () =
let module_help m =
let module M = (val m : Bot.Module) in
M.help ()
in
modules |> List.map ~f:module_help |> String.concat ~sep:"\n"
;;
let dispatch update =
let handled =
List.fold_left modules ~init:false ~f:(fun handled m -> on_update m update || handled)
in
match handled, update with
| false, { Telegram.message = Some { chat = { id = chat_id; _ }; _ }; _ } ->
let text = modules_help () in
Telegram.send_message_don't_wait ~chat_id ~text ()
| _ -> ()
;;
| null | https://raw.githubusercontent.com/pNre/Hera/f3928380eb94a61637f0459818f9cec650ee8220/hera/dispatcher.ml | ocaml | open Core
let modules =
[ (module Module_dictionary : Bot.Module)
; (module Module_markets : Bot.Module)
; (module Module_feeds : Bot.Module)
; (module Module_air_quality : Bot.Module)
; (module Module_morejpeg : Bot.Module)
; (module Module_preferences : Bot.Module)
; (module Module_faces : Bot.Module)
]
;;
let register m =
let module M = (val m : Bot.Module) in
M.register ()
;;
let on_update m update =
let module M = (val m : Bot.Module) in
M.on_update update
;;
let register_modules () = List.iter modules ~f:register
let modules_help () =
let module_help m =
let module M = (val m : Bot.Module) in
M.help ()
in
modules |> List.map ~f:module_help |> String.concat ~sep:"\n"
;;
let dispatch update =
let handled =
List.fold_left modules ~init:false ~f:(fun handled m -> on_update m update || handled)
in
match handled, update with
| false, { Telegram.message = Some { chat = { id = chat_id; _ }; _ }; _ } ->
let text = modules_help () in
Telegram.send_message_don't_wait ~chat_id ~text ()
| _ -> ()
;;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.