_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
4a74a0c5e653ea70f367fc453dfe756ff7bfd1f095851342430ccf00907c4771
patricoferris/ocaml-iocp
heap.ml
* Copyright ( c ) 2021 < > * * 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) 2021 Craig Ferguson <> * * 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. *) let ( = ) : int -> int -> bool = ( = ) let ( <> ) : int -> int -> bool = ( <> ) type ptr = int let ptr_to_int = Fun.id let slot_taken = -1 let free_list_nil = -2 (* [extra_data] is for keeping pointers passed to C alive. *) type 'a entry = | Empty : 'a entry | Entry : { data : 'a; extra_data : 'b; mutable ptr : int } -> 'a entry (* Free-list allocator *) type 'a t = { data: 'a entry array (* Pool of potentially-empty data slots. Invariant: an unfreed pointer [p] into this array is valid iff [free_tail_relation.(p) = slot_taken]. *) ; mutable free_head: ptr ; free_tail_relation: ptr array A linked list of pointers to free slots , with [ free_head ] being the first element and [ free_tail_relation ] mapping each free slot to the next one . Each entry [ x ] signals a state of the corresponding [ data.(x ) ] slot : - [ x = slot_taken ] : the data slot is taken ; - [ x = free_list_nil ] : the data slot is free , and is last to be allocated ; - [ 0 < = x < length data ] : the data slot is free , and will be allocated before [ free_tail_relation.(x ) ] . The user is given only pointers [ p ] such that [ free_tail_relation.(p ) = slot_taken ] . element and [free_tail_relation] mapping each free slot to the next one. Each entry [x] signals a state of the corresponding [data.(x)] slot: - [x = slot_taken]: the data slot is taken; - [x = free_list_nil]: the data slot is free, and is last to be allocated; - [0 <= x < length data]: the data slot is free, and will be allocated before [free_tail_relation.(x)]. The user is given only pointers [p] such that [free_tail_relation.(p) = slot_taken]. *) ; mutable in_use: int } let ptr = function | Entry { ptr = -1; _ } -> invalid_arg "Entry has already been freed!" | Entry { ptr; _ } -> ptr | Empty -> assert false let create : type a. int -> a t = fun n -> if n < 0 || n > Sys.max_array_length then invalid_arg "Heap.create" ; (* Every slot is free, and all but the last have a free successor. *) let free_head = if n = 0 then free_list_nil else 0 in let free_tail_relation = Array.init n succ in if n > 0 then free_tail_relation.(n - 1) <- free_list_nil; let data = (* No slot in [free_tail_relation] is [slot_taken], so initial data is inaccessible. *) Array.make n Empty in { data; free_head; free_tail_relation; in_use = 0 } exception No_space let alloc t data ~extra_data = let ptr = t.free_head in if ptr = free_list_nil then raise No_space; let entry = Entry { data; extra_data; ptr } in t.data.(ptr) <- entry; (* Drop [ptr] from the free list. *) let tail = t.free_tail_relation.(ptr) in t.free_tail_relation.(ptr) <- slot_taken; t.free_head <- tail; t.in_use <- t.in_use + 1; entry let free t ptr = assert (ptr >= 0) (* [alloc] returns only valid pointers. *); if ptr >= Array.length t.data then invalid_arg ("Heap.free: invalid pointer " ^ string_of_int ptr); let slot_state = t.free_tail_relation.(ptr) in if slot_state <> slot_taken then invalid_arg "Heap.free: pointer already freed"; [ t.free_tail_relation.(ptr ) = slot_taken ] , so [ ) ] is valid . let datum = match t.data.(ptr) with | Empty -> assert false | Entry p -> p.ptr <- -1; p.data in (* Cons [ptr] to the free-list. *) t.free_tail_relation.(ptr) <- t.free_head; t.free_head <- ptr; We 've marked this slot as free , so [ ) ] is inaccessible . We zero it to allow it to be GC - ed . it to allow it to be GC-ed. *) assert (t.free_tail_relation.(ptr) <> slot_taken); t.data.(ptr) <- Empty; (* Extra-data can be GC'd here *) t.in_use <- t.in_use - 1; datum let in_use t = t.in_use
null
https://raw.githubusercontent.com/patricoferris/ocaml-iocp/7b1f661465acd7ff7c77f013d566182647f626d4/src/heap.ml
ocaml
[extra_data] is for keeping pointers passed to C alive. Free-list allocator Pool of potentially-empty data slots. Invariant: an unfreed pointer [p] into this array is valid iff [free_tail_relation.(p) = slot_taken]. Every slot is free, and all but the last have a free successor. No slot in [free_tail_relation] is [slot_taken], so initial data is inaccessible. Drop [ptr] from the free list. [alloc] returns only valid pointers. Cons [ptr] to the free-list. Extra-data can be GC'd here
* Copyright ( c ) 2021 < > * * 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) 2021 Craig Ferguson <> * * 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. *) let ( = ) : int -> int -> bool = ( = ) let ( <> ) : int -> int -> bool = ( <> ) type ptr = int let ptr_to_int = Fun.id let slot_taken = -1 let free_list_nil = -2 type 'a entry = | Empty : 'a entry | Entry : { data : 'a; extra_data : 'b; mutable ptr : int } -> 'a entry type 'a t = { data: 'a entry array ; mutable free_head: ptr ; free_tail_relation: ptr array A linked list of pointers to free slots , with [ free_head ] being the first element and [ free_tail_relation ] mapping each free slot to the next one . Each entry [ x ] signals a state of the corresponding [ data.(x ) ] slot : - [ x = slot_taken ] : the data slot is taken ; - [ x = free_list_nil ] : the data slot is free , and is last to be allocated ; - [ 0 < = x < length data ] : the data slot is free , and will be allocated before [ free_tail_relation.(x ) ] . The user is given only pointers [ p ] such that [ free_tail_relation.(p ) = slot_taken ] . element and [free_tail_relation] mapping each free slot to the next one. Each entry [x] signals a state of the corresponding [data.(x)] slot: - [x = slot_taken]: the data slot is taken; - [x = free_list_nil]: the data slot is free, and is last to be allocated; - [0 <= x < length data]: the data slot is free, and will be allocated before [free_tail_relation.(x)]. The user is given only pointers [p] such that [free_tail_relation.(p) = slot_taken]. *) ; mutable in_use: int } let ptr = function | Entry { ptr = -1; _ } -> invalid_arg "Entry has already been freed!" | Entry { ptr; _ } -> ptr | Empty -> assert false let create : type a. int -> a t = fun n -> if n < 0 || n > Sys.max_array_length then invalid_arg "Heap.create" ; let free_head = if n = 0 then free_list_nil else 0 in let free_tail_relation = Array.init n succ in if n > 0 then free_tail_relation.(n - 1) <- free_list_nil; let data = Array.make n Empty in { data; free_head; free_tail_relation; in_use = 0 } exception No_space let alloc t data ~extra_data = let ptr = t.free_head in if ptr = free_list_nil then raise No_space; let entry = Entry { data; extra_data; ptr } in t.data.(ptr) <- entry; let tail = t.free_tail_relation.(ptr) in t.free_tail_relation.(ptr) <- slot_taken; t.free_head <- tail; t.in_use <- t.in_use + 1; entry let free t ptr = if ptr >= Array.length t.data then invalid_arg ("Heap.free: invalid pointer " ^ string_of_int ptr); let slot_state = t.free_tail_relation.(ptr) in if slot_state <> slot_taken then invalid_arg "Heap.free: pointer already freed"; [ t.free_tail_relation.(ptr ) = slot_taken ] , so [ ) ] is valid . let datum = match t.data.(ptr) with | Empty -> assert false | Entry p -> p.ptr <- -1; p.data in t.free_tail_relation.(ptr) <- t.free_head; t.free_head <- ptr; We 've marked this slot as free , so [ ) ] is inaccessible . We zero it to allow it to be GC - ed . it to allow it to be GC-ed. *) assert (t.free_tail_relation.(ptr) <> slot_taken); t.data.(ptr) <- Empty; t.in_use <- t.in_use - 1; datum let in_use t = t.in_use
bb60874a218a75d84970bc3168a7449ddef45c21aba9d4793df767500930bd53
backtracking/functory
protocol.mli
(**************************************************************************) (* *) (* Functory: a distributed computing library for OCaml *) Copyright ( C ) 2010- and (* *) (* This software is free software; you can redistribute it and/or *) modify it under the terms of the GNU Library General Public License version 2.1 , with the special exception on linking (* described in file LICENSE. *) (* *) (* This software is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *) (* *) (**************************************************************************) (** The master/worker protocol. *) val set_magic_number : int -> unit (** if you need to change the default magic number *) exception BadMagicNumber exception BadProtocol (** Note: All IDs are assigned by the master *) module Master : sig type t = | Assign of int * string * string (* id, function, argument *) | Kill of int (* id *) | Stop of string | Ping val send : Unix.file_descr -> t -> unit val receive : Unix.file_descr -> t val print : Format.formatter -> t -> unit end module Worker : sig type t = | Pong | Completed of int * string (* id, result *) | Aborted of int (* id *) val send : Unix.file_descr -> t -> unit val receive : Unix.file_descr -> t val print : Format.formatter -> t -> unit end
null
https://raw.githubusercontent.com/backtracking/functory/75368305a853a90ebea9e306d82e4ef32649d1ce/protocol.mli
ocaml
************************************************************************ Functory: a distributed computing library for 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. ************************************************************************ * The master/worker protocol. * if you need to change the default magic number * Note: All IDs are assigned by the master id, function, argument id id, result id
Copyright ( C ) 2010- and modify it under the terms of the GNU Library General Public License version 2.1 , with the special exception on linking val set_magic_number : int -> unit exception BadMagicNumber exception BadProtocol module Master : sig type t = | Stop of string | Ping val send : Unix.file_descr -> t -> unit val receive : Unix.file_descr -> t val print : Format.formatter -> t -> unit end module Worker : sig type t = | Pong val send : Unix.file_descr -> t -> unit val receive : Unix.file_descr -> t val print : Format.formatter -> t -> unit end
9e295d0b65d9e6f01a4f051fb510f1a2f0bcf9c2aff3c350761dbd16643ac45c
uwplse/oddity
frontend-util.cljs
(ns oddity.frontend-util (:require [goog.string :as gs] [goog.string.format] [alandipert.storage-atom :refer [local-storage]])) (defonce logging-on (local-storage (atom true) :logging)) (defn toggle-logging! [] (swap! logging-on not)) (defn log [& args] (when @logging-on (.log js/console (apply gs/format args))))
null
https://raw.githubusercontent.com/uwplse/oddity/81c1a6af203a0d8e71138a27655e3c4003357127/oddity/src/cljs/oddity/frontend-util.cljs
clojure
(ns oddity.frontend-util (:require [goog.string :as gs] [goog.string.format] [alandipert.storage-atom :refer [local-storage]])) (defonce logging-on (local-storage (atom true) :logging)) (defn toggle-logging! [] (swap! logging-on not)) (defn log [& args] (when @logging-on (.log js/console (apply gs/format args))))
bf4d5e5fc421a24541486ac6cb57f3841f01e1e854a0fe34fa4d6a742da80de4
ktakashi/sagittarius-scheme
html.scm
-*- mode : scheme ; coding : utf-8 -*- ;;; ;;; text/markdown/converter/html.scm - Markdown->html converter ;;; Copyright ( c ) 2022 < > ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; #!nounbound (library (text markdown converter html) (export markdown->html-converter markdown-html-conversion-context-builder commonmark-url-encoder (rename (append-convert convert-nodes) (get-attribute html-attribute)) ) (import (rnrs) (record builder) (rfc uri) (srfi :1 lists) (srfi :13 strings) (srfi :14 char-sets) (text markdown parser nodes) (text markdown converter api) (text sxml tools)) (define-record-type markdown-html-conversion-context (fields user-attributes url-encoder url-sanitizer)) ;; This is basically only for passing tests (define (commonmark-url-encoder url) (let-values (((out e) (open-string-output-port))) (string-for-each (lambda (c) (case c ((#\") (put-string out "%22")) ((#\\) (put-string out "%5C")) ((#\`) (put-string out "%60")) ((#\[) (put-string out "%5B")) ((#\]) (put-string out "%5D")) ((#\space) (put-string out "%20")) (else (if (char-set-contains? char-set:ascii c) (put-char out c) TODO inefficient (put-string out (uri-encode-string (string c))))))) url) (e))) (define-syntax markdown-html-conversion-context-builder (make-record-builder markdown-html-conversion-context)) (define (convert-document document data next) (let ((r (append-convert next (markdown-node:children document)))) (cond ((null? r) '(*TOP*)) ((equal? "\n" (car r)) `(*TOP* ,@(cdr r))) (else `(*TOP* ,@r))))) (define (convert-paragraph paragraph data next) (convert-container 'p paragraph data next)) (define (convert-heading node data next) (let ((tag (string->symbol (string-append "h" (heading-node-level node))))) (convert-container tag node data next))) (define (convert-block-quote node data next) (convert-container/tag-line 'blockquote node data next)) (define (convert-bullet-list bullet-list data next) (convert-container/tag-line 'ul bullet-list data next)) (define (convert-ordered-list ordered-list data next) (define (wrap node tag) (let ((prev (get-attribute data node tag)) (start (ordered-list-node-start-number node))) (if (= start 1) prev (cons `(start ,(number->string start)) prev)))) (convert-container/tag-line 'ol ordered-list wrap next)) (define (convert-item node data next) (define (in-tight-list? node) (cond ((markdown-node-parent node) => (lambda (parent) (and (list-node? parent) ;; must be (string=? "true" (list-node-tight parent))))) (else #f))) (let ((tight? (in-tight-list? node))) (define (next-paragraph-strip node) (let ((r (next node))) ;; to strip paragraph, it looks like this ;; ("\n" (p ...) "\n") (if (and tight? (string? (car r)) (string=? (car r) "\n") (pair? (cadr r)) (eq? (caadr r) 'p)) (sxml:content (cadr r)) r))) `((li (@ ,@(get-attribute data node 'li)) ,@(append-convert next-paragraph-strip (markdown-node:children node))) "\n"))) (define (convert-container/tag-line tag node data next) (let* ((content (append-convert next (markdown-node:children node))) (elm `(,tag "\n" (@ ,@(get-attribute data node tag)) ,@(cond ((null? content) content) ((equal? (car content) "\n") (cdr content)) (else content)) ,@(if (or (null? content) (equal? "\n" (last content))) '() '("\n"))))) (list "\n" elm "\n"))) (define (convert-container tag node data next) (let ((r `(,tag (@ ,@(get-attribute data node tag)) ,@(append-convert next (markdown-node:children node))))) (list "\n" r "\n"))) (define (convert-link node data next) (let-values (((url sanitized?) (sanitize-url data (link-node-destination node)))) `((a (@ ,@(if sanitized? '((rel "nofollow")) '()) (href ,(encode-url data url)) ,@(cond ((link-node-title node) => (lambda (title) `((title ,title)))) (else '())) ,@(get-attribute data node 'a)) ,@(append-convert next (markdown-node:children node)))))) (define (convert-image node data next) (let-values (((out e) (open-string-output-port))) (define (alt-text-converter node) (cond ((or (linebreak-node? node) (softbreak-node? node)) (put-string out "\n")) ((text-node? node) (put-string out (text-node:content node))) (else (for-each alt-text-converter (markdown-node:children node))))) (alt-text-converter node) (let ((alt-text (e))) (let-values (((url _) (sanitize-url data (image-node-destination node)))) `((img (@ (src ,(encode-url data url)) (alt ,alt-text) ,@(cond ((image-node-title node) => (lambda (title) `((title ,title)))) (else '())) ,@(get-attribute data node 'img)))))))) (define (convert-thematic-break thematic-break data next) `("\n" (hr (@ ,@(get-attribute data thematic-break 'hr))) "\n")) (define (convert-code-block code-block data next) (let ((attrs (cond ((code-block-node-info code-block) => (lambda (info) (let ((lang (cond ((string-index info #\space) => (lambda (i) (substring info 0 i))) (else info)))) (if (zero? (string-length lang)) '() `((class ,(string-append "language-" lang))))))) (else '())))) `("\n" (pre (@ ,@(get-attribute data code-block 'pre)) (code (@ ,@(append attrs (get-attribute data code-block 'code))) ,(code-block-node:literal code-block))) "\n"))) (define (convert-code code data next) `((code (@ ,@(get-attribute data code 'code)) ,(code-node:literal code)))) (define (convert-softbreak node data next) '("\n")) (define (convert-html-block node data next) `("\n" (*RAW-HTML* ,(html-block-node:literal node)) "\n")) (define (convert-html-inline node data next) `((*RAW-HTML* ,(html-inline-node:literal node)))) (define (convert-linebreak node data next) `((br (@ ,@(get-attribute data node 'br))) "\n")) (define (convert-emphasis node data next) (convert-inline 'em node data next)) (define (convert-strong-emphasis node data next) (convert-inline 'strong node data next)) (define (convert-inline tag node data next) `((,tag (@ ,@(get-attribute data node tag)) ,@(append-convert next (markdown-node:children node))))) (define (convert-text text data next) (list (text-node:content text))) (define (get-attribute data node tag) (if (procedure? data) (or (data node tag) '()) (let ((attribute (and (markdown-html-conversion-context? data) (markdown-html-conversion-context-user-attributes data)))) (or (and (hashtable? data) (hashtable-ref data tag '())) '())))) (define (encode-url data url) (define encoder (and (markdown-html-conversion-context? data) (markdown-html-conversion-context-url-encoder data))) (if (procedure? encoder) (encoder url) url)) (define (sanitize-url data url) (define sanitizer (and (markdown-html-conversion-context? data) (markdown-html-conversion-context-url-sanitizer data))) (if (procedure? sanitizer) (values (sanitizer url) #t) (values url #f))) (define (append-convert next node*) (define (strip-linefeed r prev) FIXME this does n't handle < softbreak /><softbreak / > case ;; though that shouldn't be done, as far as I know, by parser (if (null? r) (values r "") (let ((first (car r))) (cond ((and (string? prev) (> (string-length prev) 0) (string? first)) (let ((lc (string-ref prev (- (string-length prev) 1)))) (if (and (eqv? lc #\newline) (string=? first "\n")) (values (cdr r) (last r)) (values r (last r))))) (else (values r (last r))))))) (let loop ((acc '()) (prev #f) (node* node*)) (if (null? node*) (concatenate (reverse! acc)) (let-values (((r prev) (strip-linefeed (next (car node*)) prev))) (loop (cons r acc) prev (cdr node*)))))) (define-markdown-converter markdown->html-converter html (document-node? convert-document) (paragraph-node? convert-paragraph) (code-block-node? convert-code-block) (thematic-break-node? convert-thematic-break) (bullet-list-node? convert-bullet-list) (ordered-list-node? convert-ordered-list) (item-node? convert-item) (block-quote-node? convert-block-quote) (heading-node? convert-heading) (link-node? convert-link) (image-node? convert-image) (text-node? convert-text) (code-node? convert-code) (html-block-node? convert-html-block) (html-inline-node? convert-html-inline) (softbreak-node? convert-softbreak) (linebreak-node? convert-linebreak) (emphasis-node? convert-emphasis) (strong-emphasis-node? convert-strong-emphasis)) )
null
https://raw.githubusercontent.com/ktakashi/sagittarius-scheme/46d678da9229eb4f977e00d5f3c4877020d0dd8b/sitelib/text/markdown/converter/html.scm
scheme
coding : utf-8 -*- text/markdown/converter/html.scm - Markdown->html converter Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This is basically only for passing tests must be to strip paragraph, it looks like this ("\n" (p ...) "\n") though that shouldn't be done, as far as I know, by parser
Copyright ( c ) 2022 < > " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING #!nounbound (library (text markdown converter html) (export markdown->html-converter markdown-html-conversion-context-builder commonmark-url-encoder (rename (append-convert convert-nodes) (get-attribute html-attribute)) ) (import (rnrs) (record builder) (rfc uri) (srfi :1 lists) (srfi :13 strings) (srfi :14 char-sets) (text markdown parser nodes) (text markdown converter api) (text sxml tools)) (define-record-type markdown-html-conversion-context (fields user-attributes url-encoder url-sanitizer)) (define (commonmark-url-encoder url) (let-values (((out e) (open-string-output-port))) (string-for-each (lambda (c) (case c ((#\") (put-string out "%22")) ((#\\) (put-string out "%5C")) ((#\`) (put-string out "%60")) ((#\[) (put-string out "%5B")) ((#\]) (put-string out "%5D")) ((#\space) (put-string out "%20")) (else (if (char-set-contains? char-set:ascii c) (put-char out c) TODO inefficient (put-string out (uri-encode-string (string c))))))) url) (e))) (define-syntax markdown-html-conversion-context-builder (make-record-builder markdown-html-conversion-context)) (define (convert-document document data next) (let ((r (append-convert next (markdown-node:children document)))) (cond ((null? r) '(*TOP*)) ((equal? "\n" (car r)) `(*TOP* ,@(cdr r))) (else `(*TOP* ,@r))))) (define (convert-paragraph paragraph data next) (convert-container 'p paragraph data next)) (define (convert-heading node data next) (let ((tag (string->symbol (string-append "h" (heading-node-level node))))) (convert-container tag node data next))) (define (convert-block-quote node data next) (convert-container/tag-line 'blockquote node data next)) (define (convert-bullet-list bullet-list data next) (convert-container/tag-line 'ul bullet-list data next)) (define (convert-ordered-list ordered-list data next) (define (wrap node tag) (let ((prev (get-attribute data node tag)) (start (ordered-list-node-start-number node))) (if (= start 1) prev (cons `(start ,(number->string start)) prev)))) (convert-container/tag-line 'ol ordered-list wrap next)) (define (convert-item node data next) (define (in-tight-list? node) (cond ((markdown-node-parent node) => (lambda (parent) (string=? "true" (list-node-tight parent))))) (else #f))) (let ((tight? (in-tight-list? node))) (define (next-paragraph-strip node) (let ((r (next node))) (if (and tight? (string? (car r)) (string=? (car r) "\n") (pair? (cadr r)) (eq? (caadr r) 'p)) (sxml:content (cadr r)) r))) `((li (@ ,@(get-attribute data node 'li)) ,@(append-convert next-paragraph-strip (markdown-node:children node))) "\n"))) (define (convert-container/tag-line tag node data next) (let* ((content (append-convert next (markdown-node:children node))) (elm `(,tag "\n" (@ ,@(get-attribute data node tag)) ,@(cond ((null? content) content) ((equal? (car content) "\n") (cdr content)) (else content)) ,@(if (or (null? content) (equal? "\n" (last content))) '() '("\n"))))) (list "\n" elm "\n"))) (define (convert-container tag node data next) (let ((r `(,tag (@ ,@(get-attribute data node tag)) ,@(append-convert next (markdown-node:children node))))) (list "\n" r "\n"))) (define (convert-link node data next) (let-values (((url sanitized?) (sanitize-url data (link-node-destination node)))) `((a (@ ,@(if sanitized? '((rel "nofollow")) '()) (href ,(encode-url data url)) ,@(cond ((link-node-title node) => (lambda (title) `((title ,title)))) (else '())) ,@(get-attribute data node 'a)) ,@(append-convert next (markdown-node:children node)))))) (define (convert-image node data next) (let-values (((out e) (open-string-output-port))) (define (alt-text-converter node) (cond ((or (linebreak-node? node) (softbreak-node? node)) (put-string out "\n")) ((text-node? node) (put-string out (text-node:content node))) (else (for-each alt-text-converter (markdown-node:children node))))) (alt-text-converter node) (let ((alt-text (e))) (let-values (((url _) (sanitize-url data (image-node-destination node)))) `((img (@ (src ,(encode-url data url)) (alt ,alt-text) ,@(cond ((image-node-title node) => (lambda (title) `((title ,title)))) (else '())) ,@(get-attribute data node 'img)))))))) (define (convert-thematic-break thematic-break data next) `("\n" (hr (@ ,@(get-attribute data thematic-break 'hr))) "\n")) (define (convert-code-block code-block data next) (let ((attrs (cond ((code-block-node-info code-block) => (lambda (info) (let ((lang (cond ((string-index info #\space) => (lambda (i) (substring info 0 i))) (else info)))) (if (zero? (string-length lang)) '() `((class ,(string-append "language-" lang))))))) (else '())))) `("\n" (pre (@ ,@(get-attribute data code-block 'pre)) (code (@ ,@(append attrs (get-attribute data code-block 'code))) ,(code-block-node:literal code-block))) "\n"))) (define (convert-code code data next) `((code (@ ,@(get-attribute data code 'code)) ,(code-node:literal code)))) (define (convert-softbreak node data next) '("\n")) (define (convert-html-block node data next) `("\n" (*RAW-HTML* ,(html-block-node:literal node)) "\n")) (define (convert-html-inline node data next) `((*RAW-HTML* ,(html-inline-node:literal node)))) (define (convert-linebreak node data next) `((br (@ ,@(get-attribute data node 'br))) "\n")) (define (convert-emphasis node data next) (convert-inline 'em node data next)) (define (convert-strong-emphasis node data next) (convert-inline 'strong node data next)) (define (convert-inline tag node data next) `((,tag (@ ,@(get-attribute data node tag)) ,@(append-convert next (markdown-node:children node))))) (define (convert-text text data next) (list (text-node:content text))) (define (get-attribute data node tag) (if (procedure? data) (or (data node tag) '()) (let ((attribute (and (markdown-html-conversion-context? data) (markdown-html-conversion-context-user-attributes data)))) (or (and (hashtable? data) (hashtable-ref data tag '())) '())))) (define (encode-url data url) (define encoder (and (markdown-html-conversion-context? data) (markdown-html-conversion-context-url-encoder data))) (if (procedure? encoder) (encoder url) url)) (define (sanitize-url data url) (define sanitizer (and (markdown-html-conversion-context? data) (markdown-html-conversion-context-url-sanitizer data))) (if (procedure? sanitizer) (values (sanitizer url) #t) (values url #f))) (define (append-convert next node*) (define (strip-linefeed r prev) FIXME this does n't handle < softbreak /><softbreak / > case (if (null? r) (values r "") (let ((first (car r))) (cond ((and (string? prev) (> (string-length prev) 0) (string? first)) (let ((lc (string-ref prev (- (string-length prev) 1)))) (if (and (eqv? lc #\newline) (string=? first "\n")) (values (cdr r) (last r)) (values r (last r))))) (else (values r (last r))))))) (let loop ((acc '()) (prev #f) (node* node*)) (if (null? node*) (concatenate (reverse! acc)) (let-values (((r prev) (strip-linefeed (next (car node*)) prev))) (loop (cons r acc) prev (cdr node*)))))) (define-markdown-converter markdown->html-converter html (document-node? convert-document) (paragraph-node? convert-paragraph) (code-block-node? convert-code-block) (thematic-break-node? convert-thematic-break) (bullet-list-node? convert-bullet-list) (ordered-list-node? convert-ordered-list) (item-node? convert-item) (block-quote-node? convert-block-quote) (heading-node? convert-heading) (link-node? convert-link) (image-node? convert-image) (text-node? convert-text) (code-node? convert-code) (html-block-node? convert-html-block) (html-inline-node? convert-html-inline) (softbreak-node? convert-softbreak) (linebreak-node? convert-linebreak) (emphasis-node? convert-emphasis) (strong-emphasis-node? convert-strong-emphasis)) )
f0be75b09edae0bc9ac7c1ed6c40e111ca9b27a7d21569a5c68c868e99a35021
biegunka/biegunka
RunSpec.hs
{-# LANGUAGE OverloadedStrings #-} module RunSpec (spec) where import Control.Lens import qualified Data.List as List import Data.List.Lens import System.Directory.Layout import Test.Hspec.Lens import Run (find) import SpecHelper (withBiegunkaTempDirectory) spec :: Spec spec = describe "find" $ around withBiegunkaTempDirectory $ do it "deeply traverses the directory looking for files name ‘Biegunka.hs’" $ \tmpDir -> do make tmpDir $ do dir "foo" $ file "Biegunka.hs" & contents ?~ "" dir "bar" $ do dir "baz" $ file "Biegunka.hs" & contents ?~ "" dir "qux" $ emptydir "quux" file "Biegunka.hs" & contents ?~ "" res <- find tmpDir res `shouldList` ["Biegunka.hs", "bar/baz/Biegunka.hs", "foo/Biegunka.hs"] `through` sorted.traverse.prefixed tmpDir.prefixed "/" it "ignores the directories whose name starts with a dot" $ \tmpDir -> do make tmpDir $ do dir "foo" $ file "Biegunka.hs" & contents ?~ "" dir "bar" $ do dir ".baz" $ file "Biegunka.hs" & contents ?~ "" dir "qux" $ emptydir "quux" file "Biegunka.hs" & contents ?~ "" res <- find tmpDir res `shouldList` ["Biegunka.hs", "foo/Biegunka.hs"] `through` sorted.traverse.prefixed tmpDir.prefixed "/" where sorted = to List.sort
null
https://raw.githubusercontent.com/biegunka/biegunka/74fc93326d5f29761125d7047d5418899fa2469d/test/spec/RunSpec.hs
haskell
# LANGUAGE OverloadedStrings #
module RunSpec (spec) where import Control.Lens import qualified Data.List as List import Data.List.Lens import System.Directory.Layout import Test.Hspec.Lens import Run (find) import SpecHelper (withBiegunkaTempDirectory) spec :: Spec spec = describe "find" $ around withBiegunkaTempDirectory $ do it "deeply traverses the directory looking for files name ‘Biegunka.hs’" $ \tmpDir -> do make tmpDir $ do dir "foo" $ file "Biegunka.hs" & contents ?~ "" dir "bar" $ do dir "baz" $ file "Biegunka.hs" & contents ?~ "" dir "qux" $ emptydir "quux" file "Biegunka.hs" & contents ?~ "" res <- find tmpDir res `shouldList` ["Biegunka.hs", "bar/baz/Biegunka.hs", "foo/Biegunka.hs"] `through` sorted.traverse.prefixed tmpDir.prefixed "/" it "ignores the directories whose name starts with a dot" $ \tmpDir -> do make tmpDir $ do dir "foo" $ file "Biegunka.hs" & contents ?~ "" dir "bar" $ do dir ".baz" $ file "Biegunka.hs" & contents ?~ "" dir "qux" $ emptydir "quux" file "Biegunka.hs" & contents ?~ "" res <- find tmpDir res `shouldList` ["Biegunka.hs", "foo/Biegunka.hs"] `through` sorted.traverse.prefixed tmpDir.prefixed "/" where sorted = to List.sort
0ec40428b03460c2be0ff27782f825c3ece02a3d5cac2dc50fc410218639d463
rmloveland/scheme48-0.53
type-var.scm
Copyright ( c ) 1994 by . See file COPYING . ; Type variables - what a mess (define-record-type uvar (prefix ; a name for debugging (depth) ; lexical depth of the uvar id ; a number (tuple-okay?) ; true if this can be unified with a tuple, set when merged ) ((place #f) ; used in producing type schemes (source #f) ; to let the user know where this came from (binding #f) ; known value of this uvar (temp #f) ; useful field )) (define-record-discloser type/uvar (lambda (uvar) (list 'uvar (uvar-prefix uvar) (uvar-depth uvar) (uvar-id uvar) (uvar-binding uvar)))) (define (make-uvar prefix depth . maybe-id) (uvar-maker prefix depth (if (null? maybe-id) (unique-id) (car maybe-id)) #f)) (define (make-tuple-uvar prefix depth . maybe-id) (uvar-maker prefix depth (if (null? maybe-id) (unique-id) (car maybe-id)) #t)) ; Could this safely short-circuit the chains? (define (maybe-follow-uvar type) (cond ((and (uvar? type) (uvar-binding type)) => maybe-follow-uvar) (else type))) Substitute VALUE for UVAR , if this will not introduce a circularity . ; or cause other problems. Returns an error-printing thunk if there is ; a problem. (define (bind-uvar! uvar value) (cond ((uvar? value) (bind-uvar-to-uvar! uvar value) #f) (else (bind-uvar-to-type! uvar value)))) (define (bind-uvar-to-uvar! uvar0 uvar1) (minimize-type-depth! uvar1 (uvar-depth uvar0)) (set-uvar-binding! uvar0 uvar1) (if (and (uvar-tuple-okay? uvar1) (not (uvar-tuple-okay? uvar0))) (set-uvar-tuple-okay?! uvar1 #f))) (define (bind-uvar-to-type! uvar type) (let ((errors '())) (if (uvar-in-type? uvar type) (set! errors (cons circularity-error errors))) (if (and (tuple-type? type) (not (uvar-tuple-okay? uvar))) (set! errors (cons (tuple-error type) errors))) (cond ((null? errors) ; whew! (minimize-type-depth! type (uvar-depth uvar)) (set-uvar-binding! uvar type) #f) (else (lambda () (format #t "unifying ") (display-type uvar (current-output-port)) (format #t " == ") (display-type type (current-output-port)) (format #t "~% would cause the following problem~A:" (if (null? (cdr errors)) "" "s")) (for-each (lambda (x) (x)) errors)))))) (define (circularity-error) (format #t "~% creation of a circular type")) (define (tuple-error type) (lambda () (if (null? (tuple-type-types type)) (format #t "~% returning no values where one is expected") (format #t "~% returning ~D values where one is expected" (length (tuple-type-types type)))))) Check that UVAR does not occur in EXP . (define (uvar-in-type? uvar exp) (let label ((exp exp)) (cond ((or (base-type? exp) (record-type? exp)) #f) ((uvar? exp) (if (uvar-binding exp) (label (uvar-binding exp)) (eq? exp uvar))) ((other-type? exp) (every? label (other-type-subtypes exp))) (else (identity (bug "funny type ~S" exp)))))) ; Make the depths of any uvars in TYPE be no greater than DEPTH. (define (minimize-type-depth! type depth) (let label ((type type)) (cond ((other-type? type) (for-each label (other-type-subtypes type))) ((uvar? type) (cond ((uvar-binding type) => label) ((< depth (uvar-depth type)) (set-uvar-depth! type depth))))))) ; Set the depth of all uvars in TYPE to be -1 so that it will not be made ; polymorphic at any level. (define (make-nonpolymorphic! type) (cond ((uvar? type) (set-uvar-depth! type -1)) ((other-type? type) (for-each make-nonpolymorphic! (other-type-subtypes type))) ;((type-scheme? type) ; (make-nonpolymorphic! (type-scheme-type type))) )) ;------------------------------------------------------------ ; Micro utilities (define *unique-id-counter* 0) (define (unique-id) (set! *unique-id-counter* (+ *unique-id-counter* 1)) *unique-id-counter*) (define (reset-type-vars!) (set! *unique-id-counter* 0))
null
https://raw.githubusercontent.com/rmloveland/scheme48-0.53/1ae4531fac7150bd2af42d124da9b50dd1b89ec1/ps-compiler/prescheme/type-var.scm
scheme
Type variables - what a mess a name for debugging lexical depth of the uvar a number true if this can be unified with a tuple, set when merged used in producing type schemes to let the user know where this came from known value of this uvar useful field Could this safely short-circuit the chains? or cause other problems. Returns an error-printing thunk if there is a problem. whew! Make the depths of any uvars in TYPE be no greater than DEPTH. Set the depth of all uvars in TYPE to be -1 so that it will not be made polymorphic at any level. ((type-scheme? type) (make-nonpolymorphic! (type-scheme-type type))) ------------------------------------------------------------ Micro utilities
Copyright ( c ) 1994 by . See file COPYING . (define-record-type uvar ) )) (define-record-discloser type/uvar (lambda (uvar) (list 'uvar (uvar-prefix uvar) (uvar-depth uvar) (uvar-id uvar) (uvar-binding uvar)))) (define (make-uvar prefix depth . maybe-id) (uvar-maker prefix depth (if (null? maybe-id) (unique-id) (car maybe-id)) #f)) (define (make-tuple-uvar prefix depth . maybe-id) (uvar-maker prefix depth (if (null? maybe-id) (unique-id) (car maybe-id)) #t)) (define (maybe-follow-uvar type) (cond ((and (uvar? type) (uvar-binding type)) => maybe-follow-uvar) (else type))) Substitute VALUE for UVAR , if this will not introduce a circularity . (define (bind-uvar! uvar value) (cond ((uvar? value) (bind-uvar-to-uvar! uvar value) #f) (else (bind-uvar-to-type! uvar value)))) (define (bind-uvar-to-uvar! uvar0 uvar1) (minimize-type-depth! uvar1 (uvar-depth uvar0)) (set-uvar-binding! uvar0 uvar1) (if (and (uvar-tuple-okay? uvar1) (not (uvar-tuple-okay? uvar0))) (set-uvar-tuple-okay?! uvar1 #f))) (define (bind-uvar-to-type! uvar type) (let ((errors '())) (if (uvar-in-type? uvar type) (set! errors (cons circularity-error errors))) (if (and (tuple-type? type) (not (uvar-tuple-okay? uvar))) (set! errors (cons (tuple-error type) errors))) (minimize-type-depth! type (uvar-depth uvar)) (set-uvar-binding! uvar type) #f) (else (lambda () (format #t "unifying ") (display-type uvar (current-output-port)) (format #t " == ") (display-type type (current-output-port)) (format #t "~% would cause the following problem~A:" (if (null? (cdr errors)) "" "s")) (for-each (lambda (x) (x)) errors)))))) (define (circularity-error) (format #t "~% creation of a circular type")) (define (tuple-error type) (lambda () (if (null? (tuple-type-types type)) (format #t "~% returning no values where one is expected") (format #t "~% returning ~D values where one is expected" (length (tuple-type-types type)))))) Check that UVAR does not occur in EXP . (define (uvar-in-type? uvar exp) (let label ((exp exp)) (cond ((or (base-type? exp) (record-type? exp)) #f) ((uvar? exp) (if (uvar-binding exp) (label (uvar-binding exp)) (eq? exp uvar))) ((other-type? exp) (every? label (other-type-subtypes exp))) (else (identity (bug "funny type ~S" exp)))))) (define (minimize-type-depth! type depth) (let label ((type type)) (cond ((other-type? type) (for-each label (other-type-subtypes type))) ((uvar? type) (cond ((uvar-binding type) => label) ((< depth (uvar-depth type)) (set-uvar-depth! type depth))))))) (define (make-nonpolymorphic! type) (cond ((uvar? type) (set-uvar-depth! type -1)) ((other-type? type) (for-each make-nonpolymorphic! (other-type-subtypes type))) )) (define *unique-id-counter* 0) (define (unique-id) (set! *unique-id-counter* (+ *unique-id-counter* 1)) *unique-id-counter*) (define (reset-type-vars!) (set! *unique-id-counter* 0))
e92ea6df577170b720412047c48c2eb0dd376247cf8da96503047d2a7222f0c9
logicmoo/wam_common_lisp
ibcl-patches.lisp
-*-Mode : LISP ; Package:(PCL LISP 1000 ) ; ; Syntax : Common - lisp -*- ;;; ;;; ************************************************************************* Copyright ( c ) 1985 , 1986 , 1987 , 1988 , 1989 , 1990 Xerox Corporation . ;;; All rights reserved. ;;; ;;; Use and copying of this software and preparation of derivative works ;;; based upon this software are permitted. Any distribution of this software or derivative works must comply with all applicable United ;;; States export control laws. ;;; This software is made available AS IS , and Xerox Corporation makes no ;;; warranty about the software, its performance or its conformity to any ;;; specification. ;;; ;;; Any person obtaining a copy of this software is requested to send their ;;; name and post office or electronic mail address to: CommonLoops Coordinator Xerox PARC 3333 Coyote Hill Rd . Palo Alto , CA 94304 ( or send Arpanet mail to ) ;;; ;;; Suggestions, comments and requests for improvements are also welcome. ;;; ************************************************************************* ;;; (in-package 'system) This makes DEFMACRO take & WHOLE and & ENVIRONMENT args anywhere in the lambda - list . The former allows deviation from the CL spec , ;;; but what the heck. (eval-when (compile) (proclaim '(optimize (safety 2) (space 3)))) (defvar *old-defmacro*) (defun new-defmacro (whole env) (flet ((call-old-definition (new-whole) (funcall *old-defmacro* new-whole env))) (if (not (and (consp whole) (consp (cdr whole)) (consp (cddr whole)) (consp (cdddr whole)))) (call-old-definition whole) (let* ((ll (caddr whole)) (env-tail (do ((tail ll (cdr tail))) ((not (consp tail)) nil) (when (eq '&environment (car tail)) (return tail))))) (if env-tail (call-old-definition (list* (car whole) (cadr whole) (append (list '&environment (cadr env-tail)) (ldiff ll env-tail) (cddr env-tail)) (cdddr whole))) (call-old-definition whole)))))) (eval-when (load eval) (unless (boundp '*old-defmacro*) (setq *old-defmacro* (macro-function 'defmacro)) (setf (macro-function 'defmacro) #'new-defmacro))) ;;; setf patches ;;; (in-package 'system) (defun get-setf-method (form) (multiple-value-bind (vars vals stores store-form access-form) (get-setf-method-multiple-value form) (unless (listp vars) (error "The temporary variables component, ~s, of the setf-method for ~s is not a list." vars form)) (unless (listp vals) (error "The values forms component, ~s, of the setf-method for ~s is not a list." vals form)) (unless (listp stores) (error "The store variables component, ~s, of the setf-method for ~s is not a list." stores form)) (unless (= (list-length stores) 1) (error "Multiple store-variables are not allowed.")) (values vars vals stores store-form access-form))) (defun get-setf-method-multiple-value (form) (cond ((symbolp form) (let ((store (gensym))) (values nil nil (list store) `(setq ,form ,store) form))) ((or (not (consp form)) (not (symbolp (car form)))) (error "Cannot get the setf-method of ~S." form)) ((get (car form) 'setf-method) (apply (get (car form) 'setf-method) (cdr form))) ((get (car form) 'setf-update-fn) (let ((vars (mapcar #'(lambda (x) (declare (ignore x)) (gensym)) (cdr form))) (store (gensym))) (values vars (cdr form) (list store) `(,(get (car form) 'setf-update-fn) ,@vars ,store) (cons (car form) vars)))) ((get (car form) 'setf-lambda) (let* ((vars (mapcar #'(lambda (x) (declare (ignore x)) (gensym)) (cdr form))) (store (gensym)) (l (get (car form) 'setf-lambda)) (f `(lambda ,(car l) (funcall #'(lambda ,(cadr l) ,@(cddr l)) ',store)))) (values vars (cdr form) (list store) (apply f vars) (cons (car form) vars)))) ((macro-function (car form)) (get-setf-method-multiple-value (macroexpand-1 form))) (t (error "Cannot expand the SETF form ~S." form))))
null
https://raw.githubusercontent.com/logicmoo/wam_common_lisp/4396d9e26b050f68182d65c9a2d5a939557616dd/prolog/wam_cl/src/pcl/ibcl-patches.lisp
lisp
Package:(PCL LISP 1000 ) ; ; Syntax : Common - lisp -*- ************************************************************************* All rights reserved. Use and copying of this software and preparation of derivative works based upon this software are permitted. Any distribution of this States export control laws. warranty about the software, its performance or its conformity to any specification. Any person obtaining a copy of this software is requested to send their name and post office or electronic mail address to: Suggestions, comments and requests for improvements are also welcome. ************************************************************************* but what the heck.
Copyright ( c ) 1985 , 1986 , 1987 , 1988 , 1989 , 1990 Xerox Corporation . software or derivative works must comply with all applicable United This software is made available AS IS , and Xerox Corporation makes no CommonLoops Coordinator Xerox PARC 3333 Coyote Hill Rd . Palo Alto , CA 94304 ( or send Arpanet mail to ) (in-package 'system) This makes DEFMACRO take & WHOLE and & ENVIRONMENT args anywhere in the lambda - list . The former allows deviation from the CL spec , (eval-when (compile) (proclaim '(optimize (safety 2) (space 3)))) (defvar *old-defmacro*) (defun new-defmacro (whole env) (flet ((call-old-definition (new-whole) (funcall *old-defmacro* new-whole env))) (if (not (and (consp whole) (consp (cdr whole)) (consp (cddr whole)) (consp (cdddr whole)))) (call-old-definition whole) (let* ((ll (caddr whole)) (env-tail (do ((tail ll (cdr tail))) ((not (consp tail)) nil) (when (eq '&environment (car tail)) (return tail))))) (if env-tail (call-old-definition (list* (car whole) (cadr whole) (append (list '&environment (cadr env-tail)) (ldiff ll env-tail) (cddr env-tail)) (cdddr whole))) (call-old-definition whole)))))) (eval-when (load eval) (unless (boundp '*old-defmacro*) (setq *old-defmacro* (macro-function 'defmacro)) (setf (macro-function 'defmacro) #'new-defmacro))) setf patches (in-package 'system) (defun get-setf-method (form) (multiple-value-bind (vars vals stores store-form access-form) (get-setf-method-multiple-value form) (unless (listp vars) (error "The temporary variables component, ~s, of the setf-method for ~s is not a list." vars form)) (unless (listp vals) (error "The values forms component, ~s, of the setf-method for ~s is not a list." vals form)) (unless (listp stores) (error "The store variables component, ~s, of the setf-method for ~s is not a list." stores form)) (unless (= (list-length stores) 1) (error "Multiple store-variables are not allowed.")) (values vars vals stores store-form access-form))) (defun get-setf-method-multiple-value (form) (cond ((symbolp form) (let ((store (gensym))) (values nil nil (list store) `(setq ,form ,store) form))) ((or (not (consp form)) (not (symbolp (car form)))) (error "Cannot get the setf-method of ~S." form)) ((get (car form) 'setf-method) (apply (get (car form) 'setf-method) (cdr form))) ((get (car form) 'setf-update-fn) (let ((vars (mapcar #'(lambda (x) (declare (ignore x)) (gensym)) (cdr form))) (store (gensym))) (values vars (cdr form) (list store) `(,(get (car form) 'setf-update-fn) ,@vars ,store) (cons (car form) vars)))) ((get (car form) 'setf-lambda) (let* ((vars (mapcar #'(lambda (x) (declare (ignore x)) (gensym)) (cdr form))) (store (gensym)) (l (get (car form) 'setf-lambda)) (f `(lambda ,(car l) (funcall #'(lambda ,(cadr l) ,@(cddr l)) ',store)))) (values vars (cdr form) (list store) (apply f vars) (cons (car form) vars)))) ((macro-function (car form)) (get-setf-method-multiple-value (macroexpand-1 form))) (t (error "Cannot expand the SETF form ~S." form))))
2c26de5e922009b96455627631f1d636b1ab0fb07ea3044d69bb5561dcc75188
okuoku/nausicaa
infix.sps
! ;;; ;;;Explanation at: ;;; ;;; <-yard-e.scm> ;;; Original code by : ;;; ;;; <-yard-e.scm> ;;; (import (rnrs) (checks)) (define (shunting-yard expr operands-stack binary-operators-stack) (define (log . args) (when #f (write args) (newline))) (define %precedence-table '((sentinel . 0) (= . 10) (+ . 20) (- . 20) (* . 30) (/ . 30) (^ . 40) (, . 50))) (define %operator-map '((, . cons) (^ . expt))) (define %right-associative-list '(^)) (define (%map-operator op) (or (let ((p (assq op %operator-map))) (and p (cdr p))) op)) (define %operators-table (cdr (map car %precedence-table))) (define (%precedence pred item-a item-b) (pred (cdr (assq item-a %precedence-table)) (cdr (assq item-b %precedence-table)))) (define (precedence=? item-a item-b) (or (eq? item-a item-b) (%precedence = item-a item-b))) (define (precedence>? item-a item-b) (and (not (eq? item-a item-b)) (%precedence > item-a item-b))) (define (right-associative? obj) (member obj %right-associative-list)) (define (binary-operator? obj) (member obj %operators-table)) (define top car) (define (close-binary-operator-subexpression) (log 'close-expr expr 'close-operands operands-stack 'close-operators binary-operators-stack) ;;This consumes the top of the operators stack, and changes the top ;;of the operands stack. Example: ;; ;; expression: (+ a b) ;; ;; before: operators stack (+ sentinel) ;; operands stack (b a) ;; ;; after: operators stack (sentinel) ;; operands stack (+ a b) ;; (shunting-yard expr (cons (list (%map-operator (car binary-operators-stack)) (cadr operands-stack) (car operands-stack)) (cddr operands-stack)) (cdr binary-operators-stack))) (log 'enter expr operands-stack binary-operators-stack) (if (null? expr) (if (eq? (top binary-operators-stack) 'sentinel) (car operands-stack) (close-binary-operator-subexpression)) (let ((token (car expr))) (cond ((binary-operator? token) (log 'operator token) (if (or (precedence>? token (top binary-operators-stack)) (and (right-associative? token) (precedence=? token (top binary-operators-stack)))) (shunting-yard (cdr expr) operands-stack (cons token binary-operators-stack)) (close-binary-operator-subexpression))) (else (shunting-yard (cdr expr) (cons (cond ((list? token) (log 'list-operand token) (shunting-yard token '() '(sentinel))) (else (log 'operand token) token)) operands-stack) binary-operators-stack)))))) (define-syntax infix (syntax-rules () ((_ ?token ...) (shunting-yard '(?token ...) '() '(sentinel))))) (check-set-mode! 'report-failed) (check (infix a + b) => '(+ a b)) (check (infix a + b + c) => '(+ (+ a b) c)) (check (infix a - b - c) => '(- (- a b) c)) (check (infix a - b + c) => '(+ (- a b) c)) (check (infix a + b - c) => '(- (+ a b) c)) (check (infix a * b * c) => '(* (* a b) c)) (check (infix a / b / c) => '(/ (/ a b) c)) (check (infix a * b / c) => '(/ (* a b) c)) (check (infix a / b * c) => '(* (/ a b) c)) (check (infix a + b * c) => '(+ a (* b c))) (check (infix a + b / c) => '(+ a (/ b c))) (check (infix a * b + c) => '(+ (* a b) c)) (check (infix a / b + c) => '(+ (/ a b) c)) (check (infix a * b - c) => '(- (* a b) c)) (check (infix a / b - c) => '(- (/ a b) c)) (check (infix a - b * c) => '(- a (* b c))) (check (infix a - b / c) => '(- a (/ b c))) (check (infix a = b * c) => '(= a (* b c))) (check (infix a = b / c) => '(= a (/ b c))) (check (infix (a - b) / (c + d)) => '(/ (- a b) (+ c d))) (check (infix 3 + 4 * 5 - 6 ^ 7 + 8) => '(+ (- (+ 3 (* 4 5)) (expt 6 7)) 8)) (check (infix 3 + 4 * (5 - 6) ^ 7 + 8) => '(+ (+ 3 (* 4 (expt (- 5 6) 7))) 8)) (check (infix a + b - c * d / e = f) => '(= (- (+ a b) (/ (* c d) e)) f)) ;; ^ is right associative: (check (infix a ^ b) => '(expt a b)) (check (infix a ^ b ^ c) => '(expt a (expt b c))) (check (infix a ^ b ^ c ^ d) => '(expt a (expt b (expt c d)))) (check (infix a ^ b ^ c ^ d ^ e) => '(expt a (expt b (expt c (expt d e))))) ;; (check (infix - 4) => '(- 4)) (check-report) ;;; end of file
null
https://raw.githubusercontent.com/okuoku/nausicaa/50e7b4d4141ad4d81051588608677223fe9fb715/scheme/src/scripts/infix.sps
scheme
Explanation at: <-yard-e.scm> <-yard-e.scm> This consumes the top of the operators stack, and changes the top of the operands stack. Example: expression: (+ a b) before: operators stack (+ sentinel) operands stack (b a) after: operators stack (sentinel) operands stack (+ a b) ^ is right associative: (check (infix - 4) => '(- 4)) end of file
! Original code by : (import (rnrs) (checks)) (define (shunting-yard expr operands-stack binary-operators-stack) (define (log . args) (when #f (write args) (newline))) (define %precedence-table '((sentinel . 0) (= . 10) (+ . 20) (- . 20) (* . 30) (/ . 30) (^ . 40) (, . 50))) (define %operator-map '((, . cons) (^ . expt))) (define %right-associative-list '(^)) (define (%map-operator op) (or (let ((p (assq op %operator-map))) (and p (cdr p))) op)) (define %operators-table (cdr (map car %precedence-table))) (define (%precedence pred item-a item-b) (pred (cdr (assq item-a %precedence-table)) (cdr (assq item-b %precedence-table)))) (define (precedence=? item-a item-b) (or (eq? item-a item-b) (%precedence = item-a item-b))) (define (precedence>? item-a item-b) (and (not (eq? item-a item-b)) (%precedence > item-a item-b))) (define (right-associative? obj) (member obj %right-associative-list)) (define (binary-operator? obj) (member obj %operators-table)) (define top car) (define (close-binary-operator-subexpression) (log 'close-expr expr 'close-operands operands-stack 'close-operators binary-operators-stack) (shunting-yard expr (cons (list (%map-operator (car binary-operators-stack)) (cadr operands-stack) (car operands-stack)) (cddr operands-stack)) (cdr binary-operators-stack))) (log 'enter expr operands-stack binary-operators-stack) (if (null? expr) (if (eq? (top binary-operators-stack) 'sentinel) (car operands-stack) (close-binary-operator-subexpression)) (let ((token (car expr))) (cond ((binary-operator? token) (log 'operator token) (if (or (precedence>? token (top binary-operators-stack)) (and (right-associative? token) (precedence=? token (top binary-operators-stack)))) (shunting-yard (cdr expr) operands-stack (cons token binary-operators-stack)) (close-binary-operator-subexpression))) (else (shunting-yard (cdr expr) (cons (cond ((list? token) (log 'list-operand token) (shunting-yard token '() '(sentinel))) (else (log 'operand token) token)) operands-stack) binary-operators-stack)))))) (define-syntax infix (syntax-rules () ((_ ?token ...) (shunting-yard '(?token ...) '() '(sentinel))))) (check-set-mode! 'report-failed) (check (infix a + b) => '(+ a b)) (check (infix a + b + c) => '(+ (+ a b) c)) (check (infix a - b - c) => '(- (- a b) c)) (check (infix a - b + c) => '(+ (- a b) c)) (check (infix a + b - c) => '(- (+ a b) c)) (check (infix a * b * c) => '(* (* a b) c)) (check (infix a / b / c) => '(/ (/ a b) c)) (check (infix a * b / c) => '(/ (* a b) c)) (check (infix a / b * c) => '(* (/ a b) c)) (check (infix a + b * c) => '(+ a (* b c))) (check (infix a + b / c) => '(+ a (/ b c))) (check (infix a * b + c) => '(+ (* a b) c)) (check (infix a / b + c) => '(+ (/ a b) c)) (check (infix a * b - c) => '(- (* a b) c)) (check (infix a / b - c) => '(- (/ a b) c)) (check (infix a - b * c) => '(- a (* b c))) (check (infix a - b / c) => '(- a (/ b c))) (check (infix a = b * c) => '(= a (* b c))) (check (infix a = b / c) => '(= a (/ b c))) (check (infix (a - b) / (c + d)) => '(/ (- a b) (+ c d))) (check (infix 3 + 4 * 5 - 6 ^ 7 + 8) => '(+ (- (+ 3 (* 4 5)) (expt 6 7)) 8)) (check (infix 3 + 4 * (5 - 6) ^ 7 + 8) => '(+ (+ 3 (* 4 (expt (- 5 6) 7))) 8)) (check (infix a + b - c * d / e = f) => '(= (- (+ a b) (/ (* c d) e)) f)) (check (infix a ^ b) => '(expt a b)) (check (infix a ^ b ^ c) => '(expt a (expt b c))) (check (infix a ^ b ^ c ^ d) => '(expt a (expt b (expt c d)))) (check (infix a ^ b ^ c ^ d ^ e) => '(expt a (expt b (expt c (expt d e))))) (check-report)
b9dfe421079b9f90c12421392a28a0a091a844064faceaab6fd071a372fa4299
nitrogen/NitrogenProject.com
demos_mobile_panel.erl
% vim: ts=4 sw=4 et -module (demos_mobile_panel). -include_lib ("nitrogen_core/include/wf.hrl"). -compile(export_all). main() -> #template { file="./templates/demosmobile.html" }. title() -> "Mobile Panel". headline() -> "Mobile Panel (toggleable side menu)". panel() -> #mobile_panel{ id=my_menu, position=left, display_mode=push, theme=a, body=[ #h3{text="Side Menu"}, "This is a side panel where you can put menus and other options.", #br{}, #button{text="Back to Demos", click=#redirect{url="/demos"}}, #button{text="Close Panel", click=#toggle_mobile_panel{target=my_menu}}, linecount:render() ] }. body() -> [ " <p> A mobile panel is the jQuery mobile way to present a standard toggleable mobile side menu. It's a great way to present a menu in a standardized way that's familiar to mobile users, while simultaneously saving screen real estate. <hr> ", #button{text="Open Panel", click=#toggle_mobile_panel{target=my_menu}} ].
null
https://raw.githubusercontent.com/nitrogen/NitrogenProject.com/b4b3a0dbe17394608d2ee6eaa089e3ece1285075/src/demos/demos_mobile_panel.erl
erlang
vim: ts=4 sw=4 et
-module (demos_mobile_panel). -include_lib ("nitrogen_core/include/wf.hrl"). -compile(export_all). main() -> #template { file="./templates/demosmobile.html" }. title() -> "Mobile Panel". headline() -> "Mobile Panel (toggleable side menu)". panel() -> #mobile_panel{ id=my_menu, position=left, display_mode=push, theme=a, body=[ #h3{text="Side Menu"}, "This is a side panel where you can put menus and other options.", #br{}, #button{text="Back to Demos", click=#redirect{url="/demos"}}, #button{text="Close Panel", click=#toggle_mobile_panel{target=my_menu}}, linecount:render() ] }. body() -> [ " <p> A mobile panel is the jQuery mobile way to present a standard toggleable mobile side menu. It's a great way to present a menu in a standardized way that's familiar to mobile users, while simultaneously saving screen real estate. <hr> ", #button{text="Open Panel", click=#toggle_mobile_panel{target=my_menu}} ].
cf7156ccfec9c76c93669fd44ab357d1e53b9fbd6fa7f0650c19f00ebf61c761
ghcjs/ghcjs-dom
Comment.hs
# LANGUAGE PatternSynonyms # # LANGUAGE ForeignFunctionInterface # # LANGUAGE JavaScriptFFI # -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} module GHCJS.DOM.JSFFI.Generated.Comment (js_newComment, newComment, Comment(..), gTypeComment) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import qualified Prelude (error) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull, jsUndefined) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad (void) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import Data.Maybe (fromJust) import Data.Traversable (mapM) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "new window[\"Comment\"]($1)" js_newComment :: Optional JSString -> IO Comment | < -US/docs/Web/API/Comment Mozilla Comment documentation > newComment :: (MonadIO m, ToJSString data') => Maybe data' -> m Comment newComment data' = liftIO (js_newComment (toOptionalJSString data'))
null
https://raw.githubusercontent.com/ghcjs/ghcjs-dom/749963557d878d866be2d0184079836f367dd0ea/ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/Comment.hs
haskell
For HasCallStack compatibility # LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
# LANGUAGE PatternSynonyms # # LANGUAGE ForeignFunctionInterface # # LANGUAGE JavaScriptFFI # module GHCJS.DOM.JSFFI.Generated.Comment (js_newComment, newComment, Comment(..), gTypeComment) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import qualified Prelude (error) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull, jsUndefined) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad (void) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import Data.Maybe (fromJust) import Data.Traversable (mapM) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "new window[\"Comment\"]($1)" js_newComment :: Optional JSString -> IO Comment | < -US/docs/Web/API/Comment Mozilla Comment documentation > newComment :: (MonadIO m, ToJSString data') => Maybe data' -> m Comment newComment data' = liftIO (js_newComment (toOptionalJSString data'))
b86f6c96b060787cb829625d46effd1e6c66fc1785e539a3d7f9b839a28bbcb1
kbdnr/Spednar-code-configuration
helpers.hs
let sc :: [Int] -> Pattern Int sc scale = listToPat scale -- SCALES five notes scales minPent = [0,3,5,7,10] majPent = [0,2,4,7,9] -- another mode of major pentatonic ritusen = [0,2,5,7,9] -- another mode of major pentatonic egyptian = [0,2,5,7,10] -- kumai = [0,2,3,7,9] hirajoshi = [0,2,3,7,8] iwato = [0,1,5,6,10] chinese = [0,4,6,7,11] indian = [0,4,5,7,10] pelog = [0,1,3,7,8] -- prometheus = [0,2,4,6,11] scriabin = [0,1,4,7,9] han chinese pentatonic scales gong = [0,2,4,7,9] shang = [0,2,5,7,10] jiao = [0,3,5,8,10] zhi = [0,2,5,7,9] yu = [0,3,5,7,10] 6 note scales whole = [0,2..10] augmented = [0,3,4,7,8,11] augmented2 = [0,1,4,5,8,9] -- hexatonic modes with no tritone hexMajor7 = [0,2,4,7,9,11] hexDorian = [0,2,3,5,7,10] hexPhrygian = [0,1,3,5,8,10] hexSus = [0,2,5,7,9,10] hexMajor6 = [0,2,4,5,7,9] hexAeolian = [0,3,5,7,8,10] 7 note scales major = [0,2,4,5,7,9,11] ionian = [0,2,4,5,7,9,11] dorian = [0,2,3,5,7,9,10] phrygian = [0,1,3,5,7,8,10] lydian = [0,2,4,6,7,9,11] mixolydian = [0,2,4,5,7,9,10] aeolian = [0,2,3,5,7,8,10] minor = [0,2,3,5,7,8,10] locrian = [0,1,3,5,6,8,10] harmonicMinor = [0,2,3,5,7,8,11] harmonicMajor = [0,2,4,5,7,8,11] melodicMinor = [0,2,3,5,7,9,11] melodicMinorDesc = [0,2,3,5,7,8,10] melodicMajor = [0,2,4,5,7,8,10] bartok = [0,2,4,5,7,8,10] hindu = [0,2,4,5,7,8,10] -- raga modes todi = [0,1,3,6,7,8,11] purvi = [0,1,4,6,7,8,11] marva = [0,1,4,6,7,9,11] bhairav = [0,1,4,5,7,8,11] ahirbhairav = [0,1,4,5,7,9,10] -- superLocrian = [0,1,3,4,6,8,10] romanianMinor = [0,2,3,6,7,9,10] hungarianMinor = [0,2,3,6,7,8,11] neapolitanMinor = [0,1,3,5,7,8,11] enigmatic = [0,1,4,6,8,10,11] spanish = [0,1,4,5,7,8,10] -- modes of whole tones with added note -> leadingWhole = [0,2,4,6,8,10,11] lydianMinor = [0,2,4,6,7,8,10] neapolitanMajor = [0,1,3,5,7,9,11] locrianMajor = [0,2,4,5,6,8,10] 8 note scales diminished = [0,1,3,4,6,7,9,10] diminished2 = [0,2,3,5,6,8,9,11] 12 note scales chromatic = [0..11] CHORDS maj = [0,4,7] min = [0,3,7] major7 = [0,4,7,11] dom7 = [0,4,7,10] minor7 = [0,3,7,10] aug = [0,4,8] dim = [0,3,6] dim7 = [0,3,6,9] one = [0] five = [0,7] plus = [0,4,8] sharp5 = [0,4,8] msharp5 = [0,3,8] sus2 = [0,2,7] sus4 = [0,5,7] six = [0,4,7,9] m6 = [0,3,7,9] sevenSus2 = [0,2,7,10] sevenSus4 = [0,5,7,10] sevenFlat5 = [0,4,6,10] m7flat5 = [0,3,6,10] sevenSharp5 = [0,4,8,10] m7sharp5 = [0,3,8,10] nine = [0,4,7,10,14] m9 = [0,3,7,10,14] m7sharp9 = [0,3,7,10,14] maj9 = [0,4,7,11,14] nineSus4 = [0,5,7,10,14] sixby9 = [0,4,7,9,14] m6by9 = [0,3,9,7,14] sevenFlat9 = [0,4,7,10,13] m7flat9 = [0,3,7,10,13] sevenFlat10 = [0,4,7,10,15] nineSharp5 = [0,1,13] m9sharp5 = [0,1,14] sevenSharp5flat9 = [0,4,8,10,13] m7sharp5flat9 = [0,3,8,10,13] eleven = [0,4,7,10,14,17] m11 = [0,3,7,10,14,17] maj11 = [0,4,7,11,14,17] evelenSharp = [0,4,7,10,14,18] m11sharp = [0,3,7,10,14,18] thirteen = [0,4,7,10,14,17,21] m13 = [0,3,7,10,14,17,21] let rotate :: Int -> [a] -> [a] rotate _ [] = [] rotate n xs = zipWith const (drop n (cycle xs)) xs
null
https://raw.githubusercontent.com/kbdnr/Spednar-code-configuration/14aa12b07696a6ee65f63da80de75ab2df308d6d/code/helpers.hs
haskell
SCALES another mode of major pentatonic another mode of major pentatonic hexatonic modes with no tritone raga modes modes of whole tones with added note ->
let sc :: [Int] -> Pattern Int sc scale = listToPat scale five notes scales minPent = [0,3,5,7,10] majPent = [0,2,4,7,9] ritusen = [0,2,5,7,9] egyptian = [0,2,5,7,10] kumai = [0,2,3,7,9] hirajoshi = [0,2,3,7,8] iwato = [0,1,5,6,10] chinese = [0,4,6,7,11] indian = [0,4,5,7,10] pelog = [0,1,3,7,8] prometheus = [0,2,4,6,11] scriabin = [0,1,4,7,9] han chinese pentatonic scales gong = [0,2,4,7,9] shang = [0,2,5,7,10] jiao = [0,3,5,8,10] zhi = [0,2,5,7,9] yu = [0,3,5,7,10] 6 note scales whole = [0,2..10] augmented = [0,3,4,7,8,11] augmented2 = [0,1,4,5,8,9] hexMajor7 = [0,2,4,7,9,11] hexDorian = [0,2,3,5,7,10] hexPhrygian = [0,1,3,5,8,10] hexSus = [0,2,5,7,9,10] hexMajor6 = [0,2,4,5,7,9] hexAeolian = [0,3,5,7,8,10] 7 note scales major = [0,2,4,5,7,9,11] ionian = [0,2,4,5,7,9,11] dorian = [0,2,3,5,7,9,10] phrygian = [0,1,3,5,7,8,10] lydian = [0,2,4,6,7,9,11] mixolydian = [0,2,4,5,7,9,10] aeolian = [0,2,3,5,7,8,10] minor = [0,2,3,5,7,8,10] locrian = [0,1,3,5,6,8,10] harmonicMinor = [0,2,3,5,7,8,11] harmonicMajor = [0,2,4,5,7,8,11] melodicMinor = [0,2,3,5,7,9,11] melodicMinorDesc = [0,2,3,5,7,8,10] melodicMajor = [0,2,4,5,7,8,10] bartok = [0,2,4,5,7,8,10] hindu = [0,2,4,5,7,8,10] todi = [0,1,3,6,7,8,11] purvi = [0,1,4,6,7,8,11] marva = [0,1,4,6,7,9,11] bhairav = [0,1,4,5,7,8,11] ahirbhairav = [0,1,4,5,7,9,10] superLocrian = [0,1,3,4,6,8,10] romanianMinor = [0,2,3,6,7,9,10] hungarianMinor = [0,2,3,6,7,8,11] neapolitanMinor = [0,1,3,5,7,8,11] enigmatic = [0,1,4,6,8,10,11] spanish = [0,1,4,5,7,8,10] leadingWhole = [0,2,4,6,8,10,11] lydianMinor = [0,2,4,6,7,8,10] neapolitanMajor = [0,1,3,5,7,9,11] locrianMajor = [0,2,4,5,6,8,10] 8 note scales diminished = [0,1,3,4,6,7,9,10] diminished2 = [0,2,3,5,6,8,9,11] 12 note scales chromatic = [0..11] CHORDS maj = [0,4,7] min = [0,3,7] major7 = [0,4,7,11] dom7 = [0,4,7,10] minor7 = [0,3,7,10] aug = [0,4,8] dim = [0,3,6] dim7 = [0,3,6,9] one = [0] five = [0,7] plus = [0,4,8] sharp5 = [0,4,8] msharp5 = [0,3,8] sus2 = [0,2,7] sus4 = [0,5,7] six = [0,4,7,9] m6 = [0,3,7,9] sevenSus2 = [0,2,7,10] sevenSus4 = [0,5,7,10] sevenFlat5 = [0,4,6,10] m7flat5 = [0,3,6,10] sevenSharp5 = [0,4,8,10] m7sharp5 = [0,3,8,10] nine = [0,4,7,10,14] m9 = [0,3,7,10,14] m7sharp9 = [0,3,7,10,14] maj9 = [0,4,7,11,14] nineSus4 = [0,5,7,10,14] sixby9 = [0,4,7,9,14] m6by9 = [0,3,9,7,14] sevenFlat9 = [0,4,7,10,13] m7flat9 = [0,3,7,10,13] sevenFlat10 = [0,4,7,10,15] nineSharp5 = [0,1,13] m9sharp5 = [0,1,14] sevenSharp5flat9 = [0,4,8,10,13] m7sharp5flat9 = [0,3,8,10,13] eleven = [0,4,7,10,14,17] m11 = [0,3,7,10,14,17] maj11 = [0,4,7,11,14,17] evelenSharp = [0,4,7,10,14,18] m11sharp = [0,3,7,10,14,18] thirteen = [0,4,7,10,14,17,21] m13 = [0,3,7,10,14,17,21] let rotate :: Int -> [a] -> [a] rotate _ [] = [] rotate n xs = zipWith const (drop n (cycle xs)) xs
0bc4359da8c11aed9fc26f4052af5e6d303c40418bd780e1aa668c4427028a52
synrc/nitro
element_tr.erl
-module(element_tr). -include("nitro.hrl"). -include_lib("nitro/include/event.hrl"). -compile(export_all). render_element(Record) when Record#tr.show_if==false -> [<<>>]; render_element(Record = #tr{postback= Postback}) -> Id = case Record#tr.id of [] -> nitro:temp_id(); I->I end, Cursor = case Postback of [] -> ""; P -> nitro:wire(#event {type=click, postback=P, target=Id, delegate=Record#tr.delegate}), "cursor:pointer;" end, wf_tags:emit_tag(<<"tr">>, nitro:render(Record#tr.cells), [ {<<"id">>, Id}, {<<"onclick">>, Record#tr.onclick}, {<<"class">>, Record#tr.class}, {<<"onmouseover">>, Record#tr.onmouseover}, {<<"onmouseout">>, Record#tr.onmouseout}, {<<"style">>, [Record#tr.style, Cursor]} | Record#tr.data_fields ]).
null
https://raw.githubusercontent.com/synrc/nitro/753b543626add2c014584546ec50870808a2eb90/src/elements/table/element_tr.erl
erlang
-module(element_tr). -include("nitro.hrl"). -include_lib("nitro/include/event.hrl"). -compile(export_all). render_element(Record) when Record#tr.show_if==false -> [<<>>]; render_element(Record = #tr{postback= Postback}) -> Id = case Record#tr.id of [] -> nitro:temp_id(); I->I end, Cursor = case Postback of [] -> ""; P -> nitro:wire(#event {type=click, postback=P, target=Id, delegate=Record#tr.delegate}), "cursor:pointer;" end, wf_tags:emit_tag(<<"tr">>, nitro:render(Record#tr.cells), [ {<<"id">>, Id}, {<<"onclick">>, Record#tr.onclick}, {<<"class">>, Record#tr.class}, {<<"onmouseover">>, Record#tr.onmouseover}, {<<"onmouseout">>, Record#tr.onmouseout}, {<<"style">>, [Record#tr.style, Cursor]} | Record#tr.data_fields ]).
aef20cbee75252773f580a70b974d1298a95465b45cd6b11412c30b454299e50
plum-umd/c-strider
reachingdefs.ml
Calculate reaching definitions for each instruction . * Determine when it is okay to replace some variables with * expressions . * * After calling computeRDs on a fundec , * ReachingDef.stmtStartData will contain a mapping from * statement ids to data about which definitions reach each * statement . ReachingDef.defIdStmtHash will contain a * mapping from definition ids to the statement in which * that definition takes place . * * instrRDs takes a list of instructions , and the * definitions that reach the first instruction , and * for each instruction figures out which definitions * reach into or out of each instruction . * * Determine when it is okay to replace some variables with * expressions. * * After calling computeRDs on a fundec, * ReachingDef.stmtStartData will contain a mapping from * statement ids to data about which definitions reach each * statement. ReachingDef.defIdStmtHash will contain a * mapping from definition ids to the statement in which * that definition takes place. * * instrRDs takes a list of instructions, and the * definitions that reach the first instruction, and * for each instruction figures out which definitions * reach into or out of each instruction. * *) open Cil open Pretty module E = Errormsg module DF = Dataflow module UD = Usedef module L = Liveness module IH = Inthash module U = Util module S = Stats let debug_fn = ref "" let doTime = ref false let time s f a = if !doTime then S.time s f a else f a module IOS = Set.Make(struct type t = int option let compare io1 io2 = match io1, io2 with Some i1, Some i2 -> Pervasives.compare i1 i2 | Some i1, None -> 1 | None, Some i2 -> -1 | None, None -> 0 end) let debug = ref false return the intersection of Inthashes ih1 and ih2 Inthashes ih1 and ih2 *) let ih_inter ih1 ih2 = let ih' = IH.copy ih1 in IH.iter (fun id vi -> if not(IH.mem ih2 id) then IH.remove ih' id else ()) ih1; ih' let ih_union ih1 ih2 = let ih' = IH.copy ih1 in IH.iter (fun id vi -> if not(IH.mem ih' id) then IH.add ih' id vi else ()) ih2; ih' (* Lookup varinfo in iosh. If the set contains None or is not a singleton, return None, otherwise return Some of the singleton *) IOS.t - > varinfo - > int option let iosh_singleton_lookup iosh vi = if IH.mem iosh vi.vid then let ios = IH.find iosh vi.vid in if not (IOS.cardinal ios = 1) then None else IOS.choose ios else None IOS.t - > varinfo - > IOS.t let iosh_lookup iosh vi = if IH.mem iosh vi.vid then Some(IH.find iosh vi.vid) else None return Some(vid ) if iosh contains defId . return None otherwise return None otherwise *) IOS.t - > int - > int option let iosh_defId_find iosh defId = (* int -> IOS.t -> int option -> int option*) let get_vid vid ios io = match io with Some(i) -> Some(i) | None -> let there = IOS.exists (function None -> false | Some(i') -> defId = i') ios in if there then Some(vid) else None in IH.fold get_vid iosh None The resulting iosh will contain the union of the same entries from iosh1 and iosh2 . If iosh1 has an entry that iosh2 does not , then the result will contain None in addition to the things from the entry in iosh1 . union of the same entries from iosh1 and iosh2. If iosh1 has an entry that iosh2 does not, then the result will contain None in addition to the things from the entry in iosh1. *) (* XXX this function is a performance bottleneck *) let iosh_combine iosh1 iosh2 = let iosh' = IH.copy iosh1 in IH.iter (fun id ios1 -> try let ios2 = IH.find iosh2 id in let newset = IOS.union ios1 ios2 in IH.replace iosh' id newset; with Not_found -> let newset = IOS.add None ios1 in IH.replace iosh' id newset) iosh1; IH.iter (fun id ios2 -> try ignore(IH.find iosh1 id) with Not_found -> begin if i d ) then let newset = IOS.add None ios2 in IH.add iosh' id newset end) iosh2; iosh' determine if two IOS.t s are the same let iosh_equals iosh1 iosh2 = if IH.length iosh1 = 0 & & not(IH.length iosh2 = 0 ) || IH.length = 0 & & not(IH.length iosh1 = 0 ) IH.length iosh2 = 0 && not(IH.length iosh1 = 0)*) if not(IH.length iosh1 = IH.length iosh2) then (if !debug then ignore(E.log "iosh_equals: length not same: %d %d\n" (IH.length iosh1) (IH.length iosh2)); false) else IH.fold (fun vid ios b -> if not b then b else try let ios2 = IH.find iosh2 vid in if not(IOS.compare ios ios2 = 0) then (if !debug then ignore(E.log "iosh_equals: sets for vid %d not equal\n" vid); false) else true with Not_found -> (if !debug then ignore(E.log "iosh_equals: vid %d not in iosh2\n" vid); false)) iosh1 true (* replace an entire set with a singleton. if nothing was there just add the singleton *) IOS.t - > int - > varinfo - > unit let iosh_replace iosh i vi = if IH.mem iosh vi.vid then let newset = IOS.singleton (Some i) in IH.replace iosh vi.vid newset else let newset = IOS.singleton (Some i) in IH.add iosh vi.vid newset let iosh_filter_dead iosh vs = iosh IH.iter ( fun vid _ - > if not(UD.VS.exists ( fun vi - > vid = ) vs ) then IH.remove iosh vid ) iosh ; iosh if not(UD.VS.exists (fun vi -> vid = vi.vid) vs) then IH.remove iosh vid) iosh; iosh*) (* remove definitions that are killed. add definitions that are gend *) (* Takes the defs, the data, and a function for obtaining the next def id *) VS.t - > IOS.t - > ( unit->int ) - > unit let proc_defs vs iosh f = let pd vi = let newi = f() in if !debug then ignore (E.log "proc_defs: genning %d\n" newi); iosh_replace iosh newi vi in UD.VS.iter pd vs let idMaker () start = let counter = ref start in fun () -> let ret = !counter in counter := !counter + 1; ret (* given reaching definitions into a list of instructions, figure out the definitions that reach in/out of each instruction *) (* if out is true then calculate the definitions that go out of each instruction, if it is false then calculate the definitions reaching into each instruction *) instr list - > int - > ( varinfo * int ) - > bool - > ( varinfo * int ) list let iRDsHtbl = Hashtbl.create 128 let instrRDs il sid (ivih, s, iosh) out = if Hashtbl.mem iRDsHtbl (sid,out) then Hashtbl.find iRDsHtbl (sid,out) else let print_instr i ( _ , s ' , iosh ' ) = (* let d = d_instr () i ++ line in *) (* fprint stdout 80 d; *) (* flush stdout *) (* in *) let proc_one hil i = match hil with | [] -> let _, defd = UD.computeUseDefInstr i in if UD.VS.is_empty defd then ((*if !debug then print_instr i ((), s, iosh);*) [((), s, iosh)]) else let iosh' = IH.copy iosh in proc_defs defd iosh' (idMaker () s); if ! debug then print_instr i ( ( ) , s + UD.VS.cardinal defd , iosh ' ) ; print_instr i ((), s + UD.VS.cardinal defd, iosh');*) ((), s + UD.VS.cardinal defd, iosh')::hil | (_, s', iosh')::hrst as l -> let _, defd = UD.computeUseDefInstr i in if UD.VS.is_empty defd then if ! debug then print_instr i ( ( ) , s ' , iosh ' ) ; print_instr i ((),s', iosh');*) ((), s', iosh')::l) else let iosh'' = IH.copy iosh' in proc_defs defd iosh'' (idMaker () s'); if ! debug then print_instr i ( ( ) , s ' + UD.VS.cardinal defd , iosh '' ) ; print_instr i ((), s' + UD.VS.cardinal defd, iosh'');*) ((),s' + UD.VS.cardinal defd, iosh'')::l in let folded = List.fold_left proc_one [((),s,iosh)] il in let foldedout = List.tl (List.rev folded) in let foldednotout = List.rev (List.tl folded) in Hashtbl.add iRDsHtbl (sid,true) foldedout; Hashtbl.add iRDsHtbl (sid,false) foldednotout; if out then foldedout else foldednotout (* The right hand side of an assignment is either a function call or an expression *) type rhs = RDExp of exp | RDCall of instr (* take the id number of a definition and return the rhs of the definition if there is one. Returns None if, for example, the definition is caused by an assembly instruction *) stmt IH.t - > ( ( ) * int*IOS.t ) - > int - > ( rhs * int * IOS.t ) option let rhsHtbl = IH.create 64 (* to avoid recomputation *) let getDefRhs didstmh stmdat defId = if IH.mem rhsHtbl defId then IH.find rhsHtbl defId else let stm = try IH.find didstmh defId with Not_found -> E.s (E.error "getDefRhs: defId %d not found" defId) in let (_,s,iosh) = try IH.find stmdat stm.sid with Not_found -> E.s (E.error "getDefRhs: sid %d not found" stm.sid) in match stm.skind with Instr il -> let ivihl = instrRDs il stm.sid ((),s,iosh) true in (* defs that reach out of each instr *) let ivihl_in = instrRDs il stm.sid ((),s,iosh) false in (* defs that reach into each instr *) begin try let iihl = List.combine (List.combine il ivihl) ivihl_in in (try let ((i,(_,_,diosh)),(_,_,iosh_in)) = List.find (fun ((i,(_,_,iosh')),_) -> match time "iosh_defId_find" (iosh_defId_find iosh') defId with Some vid -> (match i with _ - > _ - > | Call(None,_,_,_) -> false | Asm(_,_,sll,_,_,_) -> List.exists (function (_,_,(Var vi',NoOffset)) -> vi'.vid = vid | _ -> false) sll | _ -> false) | None -> false) iihl in (match i with Set((lh,_),e,_) -> (match lh with Var(vi') -> (IH.add rhsHtbl defId (Some(RDExp(e),stm.sid,iosh_in)); Some(RDExp(e), stm.sid, iosh_in)) | _ -> E.s (E.error "Reaching Defs getDefRhs: right vi not first")) | Call(lvo,e,el,_) -> (IH.add rhsHtbl defId (Some(RDCall(i),stm.sid,iosh_in)); Some(RDCall(i), stm.sid, iosh_in)) | Asm(a,sl,slvl,sel,sl',_) -> None) (* ? *) with Not_found -> (if !debug then ignore (E.log "getDefRhs: No instruction defines %d\n" defId); IH.add rhsHtbl defId None; None)) with Invalid_argument _ -> None end | _ -> E.s (E.error "getDefRhs: defining statement not an instruction list %d" defId) (*None*) let prettyprint didstmh stmdat () (_,s,iosh) = (*text ""*) seq line (fun (vid,ios) -> num vid ++ text ": " ++ IOS.fold (fun io d -> match io with None -> d ++ text "None " | Some i -> let = IH.find didstmh i in match getDefRhs didstmh stmdat i with None -> d ++ num i | Some(RDExp(e),_,_) -> d ++ num i ++ text " " ++ (d_exp () e) | Some(RDCall(c),_,_) -> d ++ num i ++ text " " ++ (d_instr () c)) ios nil) (IH.tolist iosh) module ReachingDef = struct let name = "Reaching Definitions" let debug = debug (* Should the analysis calculate may-reach or must-reach *) let mayReach = ref false An integer that tells the i d number of the first definition the first definition *) (* Also a hash from variable ids to a set of definition ids that reach this statement. None means there is a path to this point on which there is no definition of the variable *) type t = (unit * int * IOS.t IH.t) let copy (_, i, iosh) = ((), i, IH.copy iosh) (* entries for starting statements must be added before calling compute *) let stmtStartData = IH.create 32 (* a mapping from definition ids to the statement corresponding to that id *) let defIdStmtHash = IH.create 32 (* mapping from statement ids to statements for better performance of ok_to_replace *) let sidStmtHash = IH.create 64 (* pretty printer *) let pretty = prettyprint defIdStmtHash stmtStartData The first i d to use when computeFirstPredecessor is next called is next called *) let nextDefId = ref 0 (* Count the number of variable definitions in a statement *) let num_defs stm = match stm.skind with Instr(il) -> List.fold_left (fun s i -> let _, d = UD.computeUseDefInstr i in s + UD.VS.cardinal d) 0 il | _ -> let _, d = UD.computeUseDefStmtKind stm.skind in UD.VS.cardinal d the first predecessor is just the data in along with the i d of the first definition of the statement , which we get from the id of the first definition of the statement, which we get from nextDefId *) let computeFirstPredecessor stm (_, s, iosh) = let startDefId = max !nextDefId s in let numds = num_defs stm in let rec loop n = if n < 0 then () else (if !debug then ignore (E.log "RD: defId %d -> stm %d\n" (startDefId + n) stm.sid); IH.add defIdStmtHash (startDefId + n) stm; loop (n-1)) in loop (numds - 1); nextDefId := startDefId + numds; match L.getLiveSet stm.sid with | None -> ((), startDefId, IH.copy iosh) | Some vs -> ((), startDefId, iosh_filter_dead (IH.copy iosh) vs) let combinePredecessors (stm:stmt) ~(old:t) ((_, s, iosh):t) = match old with (_, os, oiosh) -> begin if time "iosh_equals" (iosh_equals oiosh) iosh then None else begin Some((), os, time "iosh_combine" (iosh_combine oiosh) iosh) end end (* return an action that removes things that are redefinied and adds the generated defs *) let doInstr inst (_, s, iosh) = if !debug then E.log "RD: looking at %a\n" d_instr inst; let transform (_, s', iosh') = let _, defd = UD.computeUseDefInstr inst in proc_defs defd iosh' (idMaker () s'); ((), s' + UD.VS.cardinal defd, iosh') in DF.Post transform (* all the work gets done at the instruction level *) let doStmt stm (_, s, iosh) = if not(IH.mem sidStmtHash stm.sid) then IH.add sidStmtHash stm.sid stm; if !debug then ignore(E.log "RD: looking at %a\n" d_stmt stm); match L.getLiveSet stm.sid with | None -> DF.SDefault | Some vs -> begin DF.SUse((),s,iosh_filter_dead iosh vs) (*DF.SDefault*) end let doGuard condition _ = DF.GDefault let filterStmt stm = true end module RD = DF.ForwardsDataFlow(ReachingDef) (* map all variables in vil to a set containing None in iosh *) IOS.t - > varinfo list - > ( ) let iosh_none_fill iosh vil = List.iter (fun vi -> IH.add iosh vi.vid (IOS.singleton None)) vil let clearMemos () = IH.clear rhsHtbl; Hashtbl.clear iRDsHtbl (* Computes the reaching definitions for a function. *) (* Cil.fundec -> unit *) let computeRDs fdec = try if compare fdec.svar.vname (!debug_fn) = 0 then (debug := true; ignore (E.log "%s =\n%a\n" (!debug_fn) d_block fdec.sbody)); let bdy = fdec.sbody in let slst = bdy.bstmts in IH.clear ReachingDef.stmtStartData; IH.clear ReachingDef.defIdStmtHash; IH.clear rhsHtbl; Hashtbl.clear iRDsHtbl; ReachingDef.nextDefId := 0; let fst_stm = List.hd slst in let fst_iosh = IH.create 32 in UD.onlyNoOffsetsAreDefs := true; IH.add ReachingDef.stmtStartData fst_stm.sid ((), 0, fst_iosh); time "liveness" L.computeLiveness fdec; UD.onlyNoOffsetsAreDefs := true; ignore(ReachingDef.computeFirstPredecessor fst_stm ((), 0, fst_iosh)); (match L.getLiveSet fst_stm.sid with | None -> if !debug then ignore(E.log "Nothing live at fst_stm\n") | Some vs -> ignore(iosh_filter_dead fst_iosh vs)); if !debug then ignore (E.log "computeRDs: fst_stm.sid=%d\n" fst_stm.sid); RD.compute [fst_stm]; if compare fdec.svar.vname (!debug_fn) = 0 then debug := false now ReachingDef.stmtStartData has the reaching def data in it with Failure "hd" -> if compare fdec.svar.vname (!debug_fn) = 0 then debug := false return the definitions that reach the statement with statement i d with statement id sid *) let getRDs sid = try Some (IH.find ReachingDef.stmtStartData sid) with Not_found -> None E.s ( E.error " getRDs : sid % d not found " ) let getDefIdStmt defid = try Some(IH.find ReachingDef.defIdStmtHash defid) with Not_found -> None let getStmt sid = try Some(IH.find ReachingDef.sidStmtHash sid) with Not_found -> None (* returns the rhs for the definition *) let getSimpRhs defId = let rhso = getDefRhs ReachingDef.defIdStmtHash ReachingDef.stmtStartData defId in match rhso with None -> None | Some(r,_,_) -> Some(r) check if i is responsible for defId (* instr -> int -> bool *) let isDefInstr i defId = match getSimpRhs defId with Some(RDCall i') -> Util.equals i i' | _ -> false (* Pretty print the reaching definition data for a function *) let ppFdec fdec = seq line (fun stm -> let ivih = IH.find ReachingDef.stmtStartData stm.sid in ReachingDef.pretty () ivih) fdec.sbody.bstmts (* If this class is extended with a visitor on expressions, then the current rd data is available at each expression *) class rdVisitorClass = object (self) inherit nopCilVisitor (* the statement being worked on *) val mutable sid = -1 (* if a list of instructions is being processed, then this is the corresponding list of reaching definitions *) val mutable rd_dat_lst = [] these are the reaching defs for the current instruction if there is one instruction if there is one *) val mutable cur_rd_dat = None method vstmt stm = sid <- stm.sid; match getRDs sid with None -> if !debug then ignore(E.log "rdVis: stm %d had no data\n" sid); cur_rd_dat <- None; DoChildren | Some(_,s,iosh) -> match stm.skind with Instr il -> if !debug then ignore(E.log "rdVis: visit il\n"); rd_dat_lst <- instrRDs il stm.sid ((),s,iosh) false; DoChildren | _ -> if !debug then ignore(E.log "rdVis: visit non-il\n"); cur_rd_dat <- None; DoChildren method vinst i = if !debug then ignore(E.log "rdVis: before %a, rd_dat_lst is %d long\n" d_instr i (List.length rd_dat_lst)); try cur_rd_dat <- Some(List.hd rd_dat_lst); rd_dat_lst <- List.tl rd_dat_lst; DoChildren with Failure "hd" -> if !debug then ignore(E.log "rdVis: il rd_dat_lst mismatch\n"); DoChildren method get_cur_iosh () = match cur_rd_dat with None -> (match getRDs sid with None -> None | Some(_,_,iosh) -> Some iosh) | Some(_,_,iosh) -> Some iosh end
null
https://raw.githubusercontent.com/plum-umd/c-strider/3d3a3743bc28456eb6d50e01805ce484ab3c04e6/tools/cil-1.3.7/src/ext/reachingdefs.ml
ocaml
Lookup varinfo in iosh. If the set contains None or is not a singleton, return None, otherwise return Some of the singleton int -> IOS.t -> int option -> int option XXX this function is a performance bottleneck replace an entire set with a singleton. if nothing was there just add the singleton remove definitions that are killed. add definitions that are gend Takes the defs, the data, and a function for obtaining the next def id given reaching definitions into a list of instructions, figure out the definitions that reach in/out of each instruction if out is true then calculate the definitions that go out of each instruction, if it is false then calculate the definitions reaching into each instruction let d = d_instr () i ++ line in fprint stdout 80 d; flush stdout in if !debug then print_instr i ((), s, iosh); The right hand side of an assignment is either a function call or an expression take the id number of a definition and return the rhs of the definition if there is one. Returns None if, for example, the definition is caused by an assembly instruction to avoid recomputation defs that reach out of each instr defs that reach into each instr ? None text "" Should the analysis calculate may-reach or must-reach Also a hash from variable ids to a set of definition ids that reach this statement. None means there is a path to this point on which there is no definition of the variable entries for starting statements must be added before calling compute a mapping from definition ids to the statement corresponding to that id mapping from statement ids to statements for better performance of ok_to_replace pretty printer Count the number of variable definitions in a statement return an action that removes things that are redefinied and adds the generated defs all the work gets done at the instruction level DF.SDefault map all variables in vil to a set containing None in iosh Computes the reaching definitions for a function. Cil.fundec -> unit returns the rhs for the definition instr -> int -> bool Pretty print the reaching definition data for a function If this class is extended with a visitor on expressions, then the current rd data is available at each expression the statement being worked on if a list of instructions is being processed, then this is the corresponding list of reaching definitions
Calculate reaching definitions for each instruction . * Determine when it is okay to replace some variables with * expressions . * * After calling computeRDs on a fundec , * ReachingDef.stmtStartData will contain a mapping from * statement ids to data about which definitions reach each * statement . ReachingDef.defIdStmtHash will contain a * mapping from definition ids to the statement in which * that definition takes place . * * instrRDs takes a list of instructions , and the * definitions that reach the first instruction , and * for each instruction figures out which definitions * reach into or out of each instruction . * * Determine when it is okay to replace some variables with * expressions. * * After calling computeRDs on a fundec, * ReachingDef.stmtStartData will contain a mapping from * statement ids to data about which definitions reach each * statement. ReachingDef.defIdStmtHash will contain a * mapping from definition ids to the statement in which * that definition takes place. * * instrRDs takes a list of instructions, and the * definitions that reach the first instruction, and * for each instruction figures out which definitions * reach into or out of each instruction. * *) open Cil open Pretty module E = Errormsg module DF = Dataflow module UD = Usedef module L = Liveness module IH = Inthash module U = Util module S = Stats let debug_fn = ref "" let doTime = ref false let time s f a = if !doTime then S.time s f a else f a module IOS = Set.Make(struct type t = int option let compare io1 io2 = match io1, io2 with Some i1, Some i2 -> Pervasives.compare i1 i2 | Some i1, None -> 1 | None, Some i2 -> -1 | None, None -> 0 end) let debug = ref false return the intersection of Inthashes ih1 and ih2 Inthashes ih1 and ih2 *) let ih_inter ih1 ih2 = let ih' = IH.copy ih1 in IH.iter (fun id vi -> if not(IH.mem ih2 id) then IH.remove ih' id else ()) ih1; ih' let ih_union ih1 ih2 = let ih' = IH.copy ih1 in IH.iter (fun id vi -> if not(IH.mem ih' id) then IH.add ih' id vi else ()) ih2; ih' IOS.t - > varinfo - > int option let iosh_singleton_lookup iosh vi = if IH.mem iosh vi.vid then let ios = IH.find iosh vi.vid in if not (IOS.cardinal ios = 1) then None else IOS.choose ios else None IOS.t - > varinfo - > IOS.t let iosh_lookup iosh vi = if IH.mem iosh vi.vid then Some(IH.find iosh vi.vid) else None return Some(vid ) if iosh contains defId . return None otherwise return None otherwise *) IOS.t - > int - > int option let iosh_defId_find iosh defId = let get_vid vid ios io = match io with Some(i) -> Some(i) | None -> let there = IOS.exists (function None -> false | Some(i') -> defId = i') ios in if there then Some(vid) else None in IH.fold get_vid iosh None The resulting iosh will contain the union of the same entries from iosh1 and iosh2 . If iosh1 has an entry that iosh2 does not , then the result will contain None in addition to the things from the entry in iosh1 . union of the same entries from iosh1 and iosh2. If iosh1 has an entry that iosh2 does not, then the result will contain None in addition to the things from the entry in iosh1. *) let iosh_combine iosh1 iosh2 = let iosh' = IH.copy iosh1 in IH.iter (fun id ios1 -> try let ios2 = IH.find iosh2 id in let newset = IOS.union ios1 ios2 in IH.replace iosh' id newset; with Not_found -> let newset = IOS.add None ios1 in IH.replace iosh' id newset) iosh1; IH.iter (fun id ios2 -> try ignore(IH.find iosh1 id) with Not_found -> begin if i d ) then let newset = IOS.add None ios2 in IH.add iosh' id newset end) iosh2; iosh' determine if two IOS.t s are the same let iosh_equals iosh1 iosh2 = if IH.length iosh1 = 0 & & not(IH.length iosh2 = 0 ) || IH.length = 0 & & not(IH.length iosh1 = 0 ) IH.length iosh2 = 0 && not(IH.length iosh1 = 0)*) if not(IH.length iosh1 = IH.length iosh2) then (if !debug then ignore(E.log "iosh_equals: length not same: %d %d\n" (IH.length iosh1) (IH.length iosh2)); false) else IH.fold (fun vid ios b -> if not b then b else try let ios2 = IH.find iosh2 vid in if not(IOS.compare ios ios2 = 0) then (if !debug then ignore(E.log "iosh_equals: sets for vid %d not equal\n" vid); false) else true with Not_found -> (if !debug then ignore(E.log "iosh_equals: vid %d not in iosh2\n" vid); false)) iosh1 true IOS.t - > int - > varinfo - > unit let iosh_replace iosh i vi = if IH.mem iosh vi.vid then let newset = IOS.singleton (Some i) in IH.replace iosh vi.vid newset else let newset = IOS.singleton (Some i) in IH.add iosh vi.vid newset let iosh_filter_dead iosh vs = iosh IH.iter ( fun vid _ - > if not(UD.VS.exists ( fun vi - > vid = ) vs ) then IH.remove iosh vid ) iosh ; iosh if not(UD.VS.exists (fun vi -> vid = vi.vid) vs) then IH.remove iosh vid) iosh; iosh*) VS.t - > IOS.t - > ( unit->int ) - > unit let proc_defs vs iosh f = let pd vi = let newi = f() in if !debug then ignore (E.log "proc_defs: genning %d\n" newi); iosh_replace iosh newi vi in UD.VS.iter pd vs let idMaker () start = let counter = ref start in fun () -> let ret = !counter in counter := !counter + 1; ret instr list - > int - > ( varinfo * int ) - > bool - > ( varinfo * int ) list let iRDsHtbl = Hashtbl.create 128 let instrRDs il sid (ivih, s, iosh) out = if Hashtbl.mem iRDsHtbl (sid,out) then Hashtbl.find iRDsHtbl (sid,out) else let print_instr i ( _ , s ' , iosh ' ) = let proc_one hil i = match hil with | [] -> let _, defd = UD.computeUseDefInstr i in if UD.VS.is_empty defd [((), s, iosh)]) else let iosh' = IH.copy iosh in proc_defs defd iosh' (idMaker () s); if ! debug then print_instr i ( ( ) , s + UD.VS.cardinal defd , iosh ' ) ; print_instr i ((), s + UD.VS.cardinal defd, iosh');*) ((), s + UD.VS.cardinal defd, iosh')::hil | (_, s', iosh')::hrst as l -> let _, defd = UD.computeUseDefInstr i in if UD.VS.is_empty defd then if ! debug then print_instr i ( ( ) , s ' , iosh ' ) ; print_instr i ((),s', iosh');*) ((), s', iosh')::l) else let iosh'' = IH.copy iosh' in proc_defs defd iosh'' (idMaker () s'); if ! debug then print_instr i ( ( ) , s ' + UD.VS.cardinal defd , iosh '' ) ; print_instr i ((), s' + UD.VS.cardinal defd, iosh'');*) ((),s' + UD.VS.cardinal defd, iosh'')::l in let folded = List.fold_left proc_one [((),s,iosh)] il in let foldedout = List.tl (List.rev folded) in let foldednotout = List.rev (List.tl folded) in Hashtbl.add iRDsHtbl (sid,true) foldedout; Hashtbl.add iRDsHtbl (sid,false) foldednotout; if out then foldedout else foldednotout type rhs = RDExp of exp | RDCall of instr stmt IH.t - > ( ( ) * int*IOS.t ) - > int - > ( rhs * int * IOS.t ) option let getDefRhs didstmh stmdat defId = if IH.mem rhsHtbl defId then IH.find rhsHtbl defId else let stm = try IH.find didstmh defId with Not_found -> E.s (E.error "getDefRhs: defId %d not found" defId) in let (_,s,iosh) = try IH.find stmdat stm.sid with Not_found -> E.s (E.error "getDefRhs: sid %d not found" stm.sid) in match stm.skind with Instr il -> begin try let iihl = List.combine (List.combine il ivihl) ivihl_in in (try let ((i,(_,_,diosh)),(_,_,iosh_in)) = List.find (fun ((i,(_,_,iosh')),_) -> match time "iosh_defId_find" (iosh_defId_find iosh') defId with Some vid -> (match i with _ - > _ - > | Call(None,_,_,_) -> false | Asm(_,_,sll,_,_,_) -> List.exists (function (_,_,(Var vi',NoOffset)) -> vi'.vid = vid | _ -> false) sll | _ -> false) | None -> false) iihl in (match i with Set((lh,_),e,_) -> (match lh with Var(vi') -> (IH.add rhsHtbl defId (Some(RDExp(e),stm.sid,iosh_in)); Some(RDExp(e), stm.sid, iosh_in)) | _ -> E.s (E.error "Reaching Defs getDefRhs: right vi not first")) | Call(lvo,e,el,_) -> (IH.add rhsHtbl defId (Some(RDCall(i),stm.sid,iosh_in)); Some(RDCall(i), stm.sid, iosh_in)) with Not_found -> (if !debug then ignore (E.log "getDefRhs: No instruction defines %d\n" defId); IH.add rhsHtbl defId None; None)) with Invalid_argument _ -> None end | _ -> E.s (E.error "getDefRhs: defining statement not an instruction list %d" defId) seq line (fun (vid,ios) -> num vid ++ text ": " ++ IOS.fold (fun io d -> match io with None -> d ++ text "None " | Some i -> let = IH.find didstmh i in match getDefRhs didstmh stmdat i with None -> d ++ num i | Some(RDExp(e),_,_) -> d ++ num i ++ text " " ++ (d_exp () e) | Some(RDCall(c),_,_) -> d ++ num i ++ text " " ++ (d_instr () c)) ios nil) (IH.tolist iosh) module ReachingDef = struct let name = "Reaching Definitions" let debug = debug let mayReach = ref false An integer that tells the i d number of the first definition the first definition *) type t = (unit * int * IOS.t IH.t) let copy (_, i, iosh) = ((), i, IH.copy iosh) let stmtStartData = IH.create 32 let defIdStmtHash = IH.create 32 let sidStmtHash = IH.create 64 let pretty = prettyprint defIdStmtHash stmtStartData The first i d to use when computeFirstPredecessor is next called is next called *) let nextDefId = ref 0 let num_defs stm = match stm.skind with Instr(il) -> List.fold_left (fun s i -> let _, d = UD.computeUseDefInstr i in s + UD.VS.cardinal d) 0 il | _ -> let _, d = UD.computeUseDefStmtKind stm.skind in UD.VS.cardinal d the first predecessor is just the data in along with the i d of the first definition of the statement , which we get from the id of the first definition of the statement, which we get from nextDefId *) let computeFirstPredecessor stm (_, s, iosh) = let startDefId = max !nextDefId s in let numds = num_defs stm in let rec loop n = if n < 0 then () else (if !debug then ignore (E.log "RD: defId %d -> stm %d\n" (startDefId + n) stm.sid); IH.add defIdStmtHash (startDefId + n) stm; loop (n-1)) in loop (numds - 1); nextDefId := startDefId + numds; match L.getLiveSet stm.sid with | None -> ((), startDefId, IH.copy iosh) | Some vs -> ((), startDefId, iosh_filter_dead (IH.copy iosh) vs) let combinePredecessors (stm:stmt) ~(old:t) ((_, s, iosh):t) = match old with (_, os, oiosh) -> begin if time "iosh_equals" (iosh_equals oiosh) iosh then None else begin Some((), os, time "iosh_combine" (iosh_combine oiosh) iosh) end end let doInstr inst (_, s, iosh) = if !debug then E.log "RD: looking at %a\n" d_instr inst; let transform (_, s', iosh') = let _, defd = UD.computeUseDefInstr inst in proc_defs defd iosh' (idMaker () s'); ((), s' + UD.VS.cardinal defd, iosh') in DF.Post transform let doStmt stm (_, s, iosh) = if not(IH.mem sidStmtHash stm.sid) then IH.add sidStmtHash stm.sid stm; if !debug then ignore(E.log "RD: looking at %a\n" d_stmt stm); match L.getLiveSet stm.sid with | None -> DF.SDefault | Some vs -> begin DF.SUse((),s,iosh_filter_dead iosh vs) end let doGuard condition _ = DF.GDefault let filterStmt stm = true end module RD = DF.ForwardsDataFlow(ReachingDef) IOS.t - > varinfo list - > ( ) let iosh_none_fill iosh vil = List.iter (fun vi -> IH.add iosh vi.vid (IOS.singleton None)) vil let clearMemos () = IH.clear rhsHtbl; Hashtbl.clear iRDsHtbl let computeRDs fdec = try if compare fdec.svar.vname (!debug_fn) = 0 then (debug := true; ignore (E.log "%s =\n%a\n" (!debug_fn) d_block fdec.sbody)); let bdy = fdec.sbody in let slst = bdy.bstmts in IH.clear ReachingDef.stmtStartData; IH.clear ReachingDef.defIdStmtHash; IH.clear rhsHtbl; Hashtbl.clear iRDsHtbl; ReachingDef.nextDefId := 0; let fst_stm = List.hd slst in let fst_iosh = IH.create 32 in UD.onlyNoOffsetsAreDefs := true; IH.add ReachingDef.stmtStartData fst_stm.sid ((), 0, fst_iosh); time "liveness" L.computeLiveness fdec; UD.onlyNoOffsetsAreDefs := true; ignore(ReachingDef.computeFirstPredecessor fst_stm ((), 0, fst_iosh)); (match L.getLiveSet fst_stm.sid with | None -> if !debug then ignore(E.log "Nothing live at fst_stm\n") | Some vs -> ignore(iosh_filter_dead fst_iosh vs)); if !debug then ignore (E.log "computeRDs: fst_stm.sid=%d\n" fst_stm.sid); RD.compute [fst_stm]; if compare fdec.svar.vname (!debug_fn) = 0 then debug := false now ReachingDef.stmtStartData has the reaching def data in it with Failure "hd" -> if compare fdec.svar.vname (!debug_fn) = 0 then debug := false return the definitions that reach the statement with statement i d with statement id sid *) let getRDs sid = try Some (IH.find ReachingDef.stmtStartData sid) with Not_found -> None E.s ( E.error " getRDs : sid % d not found " ) let getDefIdStmt defid = try Some(IH.find ReachingDef.defIdStmtHash defid) with Not_found -> None let getStmt sid = try Some(IH.find ReachingDef.sidStmtHash sid) with Not_found -> None let getSimpRhs defId = let rhso = getDefRhs ReachingDef.defIdStmtHash ReachingDef.stmtStartData defId in match rhso with None -> None | Some(r,_,_) -> Some(r) check if i is responsible for defId let isDefInstr i defId = match getSimpRhs defId with Some(RDCall i') -> Util.equals i i' | _ -> false let ppFdec fdec = seq line (fun stm -> let ivih = IH.find ReachingDef.stmtStartData stm.sid in ReachingDef.pretty () ivih) fdec.sbody.bstmts class rdVisitorClass = object (self) inherit nopCilVisitor val mutable sid = -1 val mutable rd_dat_lst = [] these are the reaching defs for the current instruction if there is one instruction if there is one *) val mutable cur_rd_dat = None method vstmt stm = sid <- stm.sid; match getRDs sid with None -> if !debug then ignore(E.log "rdVis: stm %d had no data\n" sid); cur_rd_dat <- None; DoChildren | Some(_,s,iosh) -> match stm.skind with Instr il -> if !debug then ignore(E.log "rdVis: visit il\n"); rd_dat_lst <- instrRDs il stm.sid ((),s,iosh) false; DoChildren | _ -> if !debug then ignore(E.log "rdVis: visit non-il\n"); cur_rd_dat <- None; DoChildren method vinst i = if !debug then ignore(E.log "rdVis: before %a, rd_dat_lst is %d long\n" d_instr i (List.length rd_dat_lst)); try cur_rd_dat <- Some(List.hd rd_dat_lst); rd_dat_lst <- List.tl rd_dat_lst; DoChildren with Failure "hd" -> if !debug then ignore(E.log "rdVis: il rd_dat_lst mismatch\n"); DoChildren method get_cur_iosh () = match cur_rd_dat with None -> (match getRDs sid with None -> None | Some(_,_,iosh) -> Some iosh) | Some(_,_,iosh) -> Some iosh end
dd0e2e7c0df5dbae4f91f153f1e1d079d25a6ec453e39e3ff01756c95ee1a3c4
samply/blaze
cql.clj
(ns blaze.fhir.operation.evaluate-measure.cql (:require [blaze.anomaly :as ba :refer [if-ok when-ok]] [blaze.db.api :as d] [blaze.elm.expression :as expr] [blaze.elm.util :as elm-util] [blaze.fhir.spec :as fhir-spec] [blaze.util :refer [conj-vec]] [clojure.core.reducers :as r] [cognitect.anomalies :as anom] [taoensso.timbre :as log]) (:import [java.lang AutoCloseable] [java.time Duration])) (set! *warn-on-reflection* true) (def eval-parallel-chunk-size "Size of chunks of resources to evaluate parallel. Each chunk consists of a vector of resources which are evaluated parallel using r/fold. The chunk size should be limited because all resources of a chunk have to fit in memory." 100000) (def eval-sequential-chunk-size "Size of chunks of resources to evaluate sequential. This size is used by r/fold as a cut-off point for the fork-join algorithm. Each chunk of those resources if evaluated sequential and the results of multiple of those parallel evaluations are combined afterwards." 512) (defn- evaluate-expression-1-error-msg [expression-name e] (format "Error while evaluating the expression `%s`: %s" expression-name (ex-message e))) (defn- evaluate-expression-1* [context subject-handle name expression] (try (expr/eval context expression subject-handle) (catch Exception e (let [ex-data (ex-data e)] ;; only log if the exception hasn't ex-data because exception with ;; ex-data are controlled by us and so are not unexpected (when-not ex-data (log/error (evaluate-expression-1-error-msg name e)) (log/error e)) (-> (ba/fault (evaluate-expression-1-error-msg name e) :fhir/issue "exception" :expression-name name) (merge ex-data)))))) (defn- timeout-millis [{:keys [timeout]}] (.toMillis ^Duration timeout)) (defn- timeout-eclipsed-msg [context] (format "Timeout of %d millis eclipsed while evaluating." (timeout-millis context))) (defn- evaluate-expression-1 [{:keys [timeout-eclipsed?] :as context} subject-handle name expression] (if (timeout-eclipsed?) {::anom/category ::anom/interrupted ::anom/message (timeout-eclipsed-msg context) :timeout (:timeout context)} (evaluate-expression-1* context subject-handle name expression))) (defn- close-batch-db! [{:keys [db]}] (.close ^AutoCloseable db)) (defn- wrap-batch-db "Wraps `combine-op`, so that when used with `r/fold`, a new batch database is created in every single-threaded reduce step. When called with no argument, it returns `context` where :db is replaced with a new batch database and ::result will be initialized to `(combine-op)`. When called with one context, it closes the batch database and returns the result of calling `combine-op` with the value at ::result. When called with two contexts, it closes the batch database from one context and returns the other context with the value at ::result combined with `combine-op`." [combine-op context] (fn batch-db-combine-op ([] (-> (update context :db d/new-batch-db) (assoc ::result (combine-op)))) ([context] (close-batch-db! context) (combine-op (::result context))) ([context-a context-b] (close-batch-db! context-b) (update context-a ::result (partial combine-op (::result context-b)))))) (defn- wrap-anomaly [combine-op] (fn anomaly-combine-op ([] (combine-op)) ([r] (if (ba/anomaly? r) r (combine-op r))) ([a b] (cond (ba/anomaly? a) a (ba/anomaly? b) b :else (combine-op a b))))) (defn- expression-combine-op [context] (-> (fn ([] (transient [])) ([x] (persistent! x)) ([a b] (reduce conj! a (persistent! b)))) (wrap-anomaly) (wrap-batch-db context))) (defn- handle [subject-handle] {:population-handle subject-handle :subject-handle subject-handle}) (defn- conj-all! [handles subject-handle population-handles] (reduce (fn [handles population-handle] (conj! handles {:population-handle population-handle :subject-handle subject-handle})) handles population-handles)) (defn- evaluate-expression** "Evaluates the expression within `def` over `subject-handles` parallel. Subject handles have to be a vector in order to ensure parallel execution." [context {:keys [name expression]} subject-handles population-basis] (r/fold eval-sequential-chunk-size (expression-combine-op context) (fn [context subject-handle] (if-ok [res (evaluate-expression-1 context subject-handle name expression)] (if (identical? :boolean population-basis) (cond-> context res (update ::result conj! (handle subject-handle))) (update context ::result conj-all! subject-handle res)) #(reduced (assoc context ::result %)))) subject-handles)) (defn evaluate-expression* [{:keys [db] :as context} expression-def subject-type population-basis] (transduce (comp (partition-all eval-parallel-chunk-size) (map #(evaluate-expression** context expression-def % population-basis))) (expression-combine-op context) (d/type-list db subject-type))) (defn- missing-expression-anom [name] (ba/incorrect (format "Missing expression with name `%s`." name) :expression-name name)) (defn- expression-def [{:keys [expression-defs]} name] (or (get expression-defs name) (missing-expression-anom name))) (defn- check-context [subject-type {:keys [context name]}] (when-not (= subject-type context) (ba/incorrect (format "The context `%s` of the expression `%s` differs from the subject type `%s`." context name subject-type) :expression-name name :subject-type subject-type :expression-context context))) (defn- def-result-type [{result-type-name :resultTypeName result-type-specifier :resultTypeSpecifier}] (if result-type-name (elm-util/parse-type {:type "NamedTypeSpecifier" :name result-type-name}) (elm-util/parse-type result-type-specifier))) (defn- check-result-type [population-basis {:keys [name] :as expression-def}] (let [result-type (def-result-type expression-def)] (if (= :boolean population-basis) (when-not (= "Boolean" result-type) (ba/incorrect (format "The result type `%s` of the expression `%s` differs from the population basis :boolean." result-type name) :expression-name name :population-basis population-basis :expression-result-type result-type)) (when-not (= (str "List<" population-basis ">") result-type) (ba/incorrect (format "The result type `%s` of the expression `%s` differs from the population basis `%s`." result-type name population-basis) :expression-name name :population-basis population-basis :expression-result-type result-type))))) (defn evaluate-expression "Evaluates the expression with `name` on each subject of `subject-type` available in :db of `context`. The context consists of: :db - the database to use for obtaining subjects and evaluating the expression :now - the evaluation time :expression-defs - a map of available expression definitions :parameters - an optional map of parameters The context of the expression has to match `subject-type`. The result type of the expression has to match the `population-basis`. Returns a list of subject-handles or an anomaly in case of errors." [context name subject-type population-basis] (when-ok [expression-def (expression-def context name) _ (check-context subject-type expression-def) _ (check-result-type population-basis expression-def)] (evaluate-expression* context expression-def subject-type population-basis))) (defn evaluate-individual-expression "Evaluates the expression with `name` according to `context`. Returns an anomaly in case of errors." [context subject-handle name] (when-ok [{:keys [name expression]} (expression-def context name)] (evaluate-expression-1 context subject-handle name expression))) (defn- stratum-result-reduce-op [result stratum subject-handle] (update result stratum conj-vec subject-handle)) (defn- stratum-combine-op [context] (-> (partial merge-with into) (wrap-anomaly) (wrap-batch-db context))) (defn- incorrect-stratum-msg [{:keys [id] :as handle} expression-name] (format "CQL expression `%s` returned more than one value for resource `%s`." expression-name (-> handle fhir-spec/fhir-type name (str "/" id)))) (defn- evaluate-stratum-expression [context subject-handle name expression] (let [result (evaluate-expression-1 context subject-handle name expression)] (if (sequential? result) (ba/incorrect (incorrect-stratum-msg subject-handle name)) result))) (defn- calc-strata** [context {:keys [name expression]} handles] (r/fold eval-sequential-chunk-size (stratum-combine-op context) (fn [context {:keys [subject-handle] :as handle}] (if-ok [stratum (evaluate-stratum-expression context subject-handle name expression)] (update context ::result stratum-result-reduce-op stratum handle) #(reduced (assoc context ::result %)))) handles)) (defn calc-strata* [context expression-def handles] (transduce (comp (partition-all eval-parallel-chunk-size) (map (partial calc-strata** context expression-def))) (stratum-combine-op context) handles)) (defn calc-strata "Returns a map of stratum value to a list of subject handles or an anomaly." [context expression-name handles] (when-ok [expression-def (expression-def context expression-name)] (calc-strata* context expression-def handles))) (defn- calc-function-strata** [context {:keys [name function]} handles] (r/fold eval-sequential-chunk-size (stratum-combine-op context) (fn [context {:keys [population-handle subject-handle] :as handle}] (if-ok [stratum (evaluate-stratum-expression context subject-handle name (function [population-handle]))] (update context ::result stratum-result-reduce-op stratum handle) #(reduced (assoc context ::result %)))) handles)) (defn- calc-function-strata* [context function-def handles] (transduce (comp (partition-all eval-parallel-chunk-size) (map (partial calc-function-strata** context function-def))) (stratum-combine-op context) handles)) (defn- missing-function-anom [name] (ba/incorrect (format "Missing function with name `%s`." name) :function-name name)) (defn- function-def [{:keys [function-defs]} name] (or (get function-defs name) (missing-function-anom name))) (defn calc-function-strata "Returns a map of stratum value to a list of subject handles or an anomaly." [context function-name handles] (when-ok [function-def (function-def context function-name)] (calc-function-strata* context function-def handles))) (defn- evaluate-multi-component-stratum-1 [context {:keys [subject-handle population-handle]} {:keys [name expression function]}] (if function (evaluate-stratum-expression context subject-handle name (function [population-handle])) (evaluate-stratum-expression context subject-handle name expression))) (defn- evaluate-multi-component-stratum [context handle defs] (transduce (comp (map (partial evaluate-multi-component-stratum-1 context handle)) (halt-when ba/anomaly?)) conj defs)) (defn calc-multi-component-strata** [context defs handles] (r/fold eval-sequential-chunk-size (stratum-combine-op context) (fn [context handle] (if-ok [stratum (evaluate-multi-component-stratum context handle defs)] (update context ::result stratum-result-reduce-op stratum handle) #(reduced (assoc context ::result %)))) handles)) (defn calc-multi-component-strata* [context defs handles] (transduce (comp (partition-all eval-parallel-chunk-size) (map (partial calc-multi-component-strata** context defs))) (stratum-combine-op context) handles)) (defn- def [{:keys [expression-defs population-basis] :as context} name] (or (get expression-defs name) (if (string? population-basis) (function-def context name) (missing-expression-anom name)))) (defn- defs [context names] (transduce (comp (map (partial def context)) (halt-when ba/anomaly?)) conj names)) (defn calc-multi-component-strata "Returns a map of list of stratum values to a list of subject handles or an anomaly." [context expression-names handles] (when-ok [defs (defs context expression-names)] (calc-multi-component-strata* context defs handles)))
null
https://raw.githubusercontent.com/samply/blaze/948eee38021467fa343c522a644a7fd4b24b6467/modules/operation-measure-evaluate-measure/src/blaze/fhir/operation/evaluate_measure/cql.clj
clojure
only log if the exception hasn't ex-data because exception with ex-data are controlled by us and so are not unexpected
(ns blaze.fhir.operation.evaluate-measure.cql (:require [blaze.anomaly :as ba :refer [if-ok when-ok]] [blaze.db.api :as d] [blaze.elm.expression :as expr] [blaze.elm.util :as elm-util] [blaze.fhir.spec :as fhir-spec] [blaze.util :refer [conj-vec]] [clojure.core.reducers :as r] [cognitect.anomalies :as anom] [taoensso.timbre :as log]) (:import [java.lang AutoCloseable] [java.time Duration])) (set! *warn-on-reflection* true) (def eval-parallel-chunk-size "Size of chunks of resources to evaluate parallel. Each chunk consists of a vector of resources which are evaluated parallel using r/fold. The chunk size should be limited because all resources of a chunk have to fit in memory." 100000) (def eval-sequential-chunk-size "Size of chunks of resources to evaluate sequential. This size is used by r/fold as a cut-off point for the fork-join algorithm. Each chunk of those resources if evaluated sequential and the results of multiple of those parallel evaluations are combined afterwards." 512) (defn- evaluate-expression-1-error-msg [expression-name e] (format "Error while evaluating the expression `%s`: %s" expression-name (ex-message e))) (defn- evaluate-expression-1* [context subject-handle name expression] (try (expr/eval context expression subject-handle) (catch Exception e (let [ex-data (ex-data e)] (when-not ex-data (log/error (evaluate-expression-1-error-msg name e)) (log/error e)) (-> (ba/fault (evaluate-expression-1-error-msg name e) :fhir/issue "exception" :expression-name name) (merge ex-data)))))) (defn- timeout-millis [{:keys [timeout]}] (.toMillis ^Duration timeout)) (defn- timeout-eclipsed-msg [context] (format "Timeout of %d millis eclipsed while evaluating." (timeout-millis context))) (defn- evaluate-expression-1 [{:keys [timeout-eclipsed?] :as context} subject-handle name expression] (if (timeout-eclipsed?) {::anom/category ::anom/interrupted ::anom/message (timeout-eclipsed-msg context) :timeout (:timeout context)} (evaluate-expression-1* context subject-handle name expression))) (defn- close-batch-db! [{:keys [db]}] (.close ^AutoCloseable db)) (defn- wrap-batch-db "Wraps `combine-op`, so that when used with `r/fold`, a new batch database is created in every single-threaded reduce step. When called with no argument, it returns `context` where :db is replaced with a new batch database and ::result will be initialized to `(combine-op)`. When called with one context, it closes the batch database and returns the result of calling `combine-op` with the value at ::result. When called with two contexts, it closes the batch database from one context and returns the other context with the value at ::result combined with `combine-op`." [combine-op context] (fn batch-db-combine-op ([] (-> (update context :db d/new-batch-db) (assoc ::result (combine-op)))) ([context] (close-batch-db! context) (combine-op (::result context))) ([context-a context-b] (close-batch-db! context-b) (update context-a ::result (partial combine-op (::result context-b)))))) (defn- wrap-anomaly [combine-op] (fn anomaly-combine-op ([] (combine-op)) ([r] (if (ba/anomaly? r) r (combine-op r))) ([a b] (cond (ba/anomaly? a) a (ba/anomaly? b) b :else (combine-op a b))))) (defn- expression-combine-op [context] (-> (fn ([] (transient [])) ([x] (persistent! x)) ([a b] (reduce conj! a (persistent! b)))) (wrap-anomaly) (wrap-batch-db context))) (defn- handle [subject-handle] {:population-handle subject-handle :subject-handle subject-handle}) (defn- conj-all! [handles subject-handle population-handles] (reduce (fn [handles population-handle] (conj! handles {:population-handle population-handle :subject-handle subject-handle})) handles population-handles)) (defn- evaluate-expression** "Evaluates the expression within `def` over `subject-handles` parallel. Subject handles have to be a vector in order to ensure parallel execution." [context {:keys [name expression]} subject-handles population-basis] (r/fold eval-sequential-chunk-size (expression-combine-op context) (fn [context subject-handle] (if-ok [res (evaluate-expression-1 context subject-handle name expression)] (if (identical? :boolean population-basis) (cond-> context res (update ::result conj! (handle subject-handle))) (update context ::result conj-all! subject-handle res)) #(reduced (assoc context ::result %)))) subject-handles)) (defn evaluate-expression* [{:keys [db] :as context} expression-def subject-type population-basis] (transduce (comp (partition-all eval-parallel-chunk-size) (map #(evaluate-expression** context expression-def % population-basis))) (expression-combine-op context) (d/type-list db subject-type))) (defn- missing-expression-anom [name] (ba/incorrect (format "Missing expression with name `%s`." name) :expression-name name)) (defn- expression-def [{:keys [expression-defs]} name] (or (get expression-defs name) (missing-expression-anom name))) (defn- check-context [subject-type {:keys [context name]}] (when-not (= subject-type context) (ba/incorrect (format "The context `%s` of the expression `%s` differs from the subject type `%s`." context name subject-type) :expression-name name :subject-type subject-type :expression-context context))) (defn- def-result-type [{result-type-name :resultTypeName result-type-specifier :resultTypeSpecifier}] (if result-type-name (elm-util/parse-type {:type "NamedTypeSpecifier" :name result-type-name}) (elm-util/parse-type result-type-specifier))) (defn- check-result-type [population-basis {:keys [name] :as expression-def}] (let [result-type (def-result-type expression-def)] (if (= :boolean population-basis) (when-not (= "Boolean" result-type) (ba/incorrect (format "The result type `%s` of the expression `%s` differs from the population basis :boolean." result-type name) :expression-name name :population-basis population-basis :expression-result-type result-type)) (when-not (= (str "List<" population-basis ">") result-type) (ba/incorrect (format "The result type `%s` of the expression `%s` differs from the population basis `%s`." result-type name population-basis) :expression-name name :population-basis population-basis :expression-result-type result-type))))) (defn evaluate-expression "Evaluates the expression with `name` on each subject of `subject-type` available in :db of `context`. The context consists of: :db - the database to use for obtaining subjects and evaluating the expression :now - the evaluation time :expression-defs - a map of available expression definitions :parameters - an optional map of parameters The context of the expression has to match `subject-type`. The result type of the expression has to match the `population-basis`. Returns a list of subject-handles or an anomaly in case of errors." [context name subject-type population-basis] (when-ok [expression-def (expression-def context name) _ (check-context subject-type expression-def) _ (check-result-type population-basis expression-def)] (evaluate-expression* context expression-def subject-type population-basis))) (defn evaluate-individual-expression "Evaluates the expression with `name` according to `context`. Returns an anomaly in case of errors." [context subject-handle name] (when-ok [{:keys [name expression]} (expression-def context name)] (evaluate-expression-1 context subject-handle name expression))) (defn- stratum-result-reduce-op [result stratum subject-handle] (update result stratum conj-vec subject-handle)) (defn- stratum-combine-op [context] (-> (partial merge-with into) (wrap-anomaly) (wrap-batch-db context))) (defn- incorrect-stratum-msg [{:keys [id] :as handle} expression-name] (format "CQL expression `%s` returned more than one value for resource `%s`." expression-name (-> handle fhir-spec/fhir-type name (str "/" id)))) (defn- evaluate-stratum-expression [context subject-handle name expression] (let [result (evaluate-expression-1 context subject-handle name expression)] (if (sequential? result) (ba/incorrect (incorrect-stratum-msg subject-handle name)) result))) (defn- calc-strata** [context {:keys [name expression]} handles] (r/fold eval-sequential-chunk-size (stratum-combine-op context) (fn [context {:keys [subject-handle] :as handle}] (if-ok [stratum (evaluate-stratum-expression context subject-handle name expression)] (update context ::result stratum-result-reduce-op stratum handle) #(reduced (assoc context ::result %)))) handles)) (defn calc-strata* [context expression-def handles] (transduce (comp (partition-all eval-parallel-chunk-size) (map (partial calc-strata** context expression-def))) (stratum-combine-op context) handles)) (defn calc-strata "Returns a map of stratum value to a list of subject handles or an anomaly." [context expression-name handles] (when-ok [expression-def (expression-def context expression-name)] (calc-strata* context expression-def handles))) (defn- calc-function-strata** [context {:keys [name function]} handles] (r/fold eval-sequential-chunk-size (stratum-combine-op context) (fn [context {:keys [population-handle subject-handle] :as handle}] (if-ok [stratum (evaluate-stratum-expression context subject-handle name (function [population-handle]))] (update context ::result stratum-result-reduce-op stratum handle) #(reduced (assoc context ::result %)))) handles)) (defn- calc-function-strata* [context function-def handles] (transduce (comp (partition-all eval-parallel-chunk-size) (map (partial calc-function-strata** context function-def))) (stratum-combine-op context) handles)) (defn- missing-function-anom [name] (ba/incorrect (format "Missing function with name `%s`." name) :function-name name)) (defn- function-def [{:keys [function-defs]} name] (or (get function-defs name) (missing-function-anom name))) (defn calc-function-strata "Returns a map of stratum value to a list of subject handles or an anomaly." [context function-name handles] (when-ok [function-def (function-def context function-name)] (calc-function-strata* context function-def handles))) (defn- evaluate-multi-component-stratum-1 [context {:keys [subject-handle population-handle]} {:keys [name expression function]}] (if function (evaluate-stratum-expression context subject-handle name (function [population-handle])) (evaluate-stratum-expression context subject-handle name expression))) (defn- evaluate-multi-component-stratum [context handle defs] (transduce (comp (map (partial evaluate-multi-component-stratum-1 context handle)) (halt-when ba/anomaly?)) conj defs)) (defn calc-multi-component-strata** [context defs handles] (r/fold eval-sequential-chunk-size (stratum-combine-op context) (fn [context handle] (if-ok [stratum (evaluate-multi-component-stratum context handle defs)] (update context ::result stratum-result-reduce-op stratum handle) #(reduced (assoc context ::result %)))) handles)) (defn calc-multi-component-strata* [context defs handles] (transduce (comp (partition-all eval-parallel-chunk-size) (map (partial calc-multi-component-strata** context defs))) (stratum-combine-op context) handles)) (defn- def [{:keys [expression-defs population-basis] :as context} name] (or (get expression-defs name) (if (string? population-basis) (function-def context name) (missing-expression-anom name)))) (defn- defs [context names] (transduce (comp (map (partial def context)) (halt-when ba/anomaly?)) conj names)) (defn calc-multi-component-strata "Returns a map of list of stratum values to a list of subject handles or an anomaly." [context expression-names handles] (when-ok [defs (defs context expression-names)] (calc-multi-component-strata* context defs handles)))
c8f79d3d92b7b5f6e2c556eb902e6e8f664cdc51352195cc6141d1868f627960
janestreet/vcaml
window.mli
open Core module Type := Nvim_internal.Phantom include module type of struct include Nvim_internal.Window end val get_height : Or_current.t -> int Api_call.Or_error.t val set_height : Or_current.t -> height:int -> unit Api_call.Or_error.t val get_cursor : Or_current.t -> Position.One_indexed_row.t Api_call.Or_error.t val set_cursor : Or_current.t -> Position.One_indexed_row.t -> unit Api_call.Or_error.t module Untested : sig val open_ : buffer:Nvim_internal.Buffer.Or_current.t -> enter:bool -> config:Msgpack.t String.Map.t -> t Api_call.Or_error.t module When_this_is_the_buffer's_last_window : sig (** When [Unload { if_modified = `Abort }] is specified, the buffer will be hidden anyway if ['hidden'] is set, if ['bufhidden'] is ['hide'], or if the [:hide] command modifier is used. If ['confirm'] is set or the [:confirm] command modifier is used, the user will be prompted to see if they want to hide the buffer instead of failing. *) type t = | Hide | Unload of { if_modified : [ `Hide | `Abort ] } end * Because closing the window in this way does not involve a cursor move , no WinLeave event will be triggered . event will be triggered. *) val close : Or_current.t -> when_this_is_the_buffer's_last_window:When_this_is_the_buffer's_last_window.t -> unit Api_call.Or_error.t val get_config : Or_current.t -> Msgpack.t String.Map.t Api_call.Or_error.t val set_config : Or_current.t -> config:Msgpack.t String.Map.t -> unit Api_call.Or_error.t val get_buf : Or_current.t -> Nvim_internal.Buffer.t Api_call.Or_error.t val get_width : Or_current.t -> int Api_call.Or_error.t val set_width : Or_current.t -> width:int -> unit Api_call.Or_error.t val get_var : Or_current.t -> name:string -> type_:'a Type.t -> 'a Api_call.Or_error.t val set_var : Or_current.t -> name:string -> type_:'a Type.t -> value:'a -> unit Api_call.Or_error.t val delete_var : Or_current.t -> name:string -> unit Api_call.Or_error.t val get_option : Or_current.t -> name:string -> type_:'a Type.t -> 'a Api_call.Or_error.t val set_option : Or_current.t -> scope:[ `Local | `Global ] -> name:string -> type_:'a Type.t -> value:'a -> unit Api_call.Or_error.t val get_position : Or_current.t -> Position.t Api_call.Or_error.t val get_tabpage : Or_current.t -> Nvim_internal.Tabpage.t Api_call.Or_error.t val get_number : Or_current.t -> int Api_call.Or_error.t val is_valid : t -> bool Api_call.Or_error.t module Expert : sig (** This is a low-level function that sets a window's buffer without any side effects. The cursor is not moved and no autocommands are triggered. This means you are bypassing the user's intent to run certain logic when certain events happen. You should be very sure this is what you want before calling this function, and you should likely only ever invoke it on buffers / windows that your plugin owns. *) val set_buf : Or_current.t -> buffer:Nvim_internal.Buffer.Or_current.t -> unit Api_call.Or_error.t (** Call a lua function from the given window. If this is actually useful we can create a wrapper similar to [wrap_viml_function] and expose it in a more type-safe way. *) val win_call : Or_current.t -> lua_callback:Nvim_internal.Luaref.t -> Msgpack.t Api_call.Or_error.t end end
null
https://raw.githubusercontent.com/janestreet/vcaml/7a53ff24276ddc3085a9b0b72b1053a6db6936cf/src/window.mli
ocaml
* When [Unload { if_modified = `Abort }] is specified, the buffer will be hidden anyway if ['hidden'] is set, if ['bufhidden'] is ['hide'], or if the [:hide] command modifier is used. If ['confirm'] is set or the [:confirm] command modifier is used, the user will be prompted to see if they want to hide the buffer instead of failing. * This is a low-level function that sets a window's buffer without any side effects. The cursor is not moved and no autocommands are triggered. This means you are bypassing the user's intent to run certain logic when certain events happen. You should be very sure this is what you want before calling this function, and you should likely only ever invoke it on buffers / windows that your plugin owns. * Call a lua function from the given window. If this is actually useful we can create a wrapper similar to [wrap_viml_function] and expose it in a more type-safe way.
open Core module Type := Nvim_internal.Phantom include module type of struct include Nvim_internal.Window end val get_height : Or_current.t -> int Api_call.Or_error.t val set_height : Or_current.t -> height:int -> unit Api_call.Or_error.t val get_cursor : Or_current.t -> Position.One_indexed_row.t Api_call.Or_error.t val set_cursor : Or_current.t -> Position.One_indexed_row.t -> unit Api_call.Or_error.t module Untested : sig val open_ : buffer:Nvim_internal.Buffer.Or_current.t -> enter:bool -> config:Msgpack.t String.Map.t -> t Api_call.Or_error.t module When_this_is_the_buffer's_last_window : sig type t = | Hide | Unload of { if_modified : [ `Hide | `Abort ] } end * Because closing the window in this way does not involve a cursor move , no WinLeave event will be triggered . event will be triggered. *) val close : Or_current.t -> when_this_is_the_buffer's_last_window:When_this_is_the_buffer's_last_window.t -> unit Api_call.Or_error.t val get_config : Or_current.t -> Msgpack.t String.Map.t Api_call.Or_error.t val set_config : Or_current.t -> config:Msgpack.t String.Map.t -> unit Api_call.Or_error.t val get_buf : Or_current.t -> Nvim_internal.Buffer.t Api_call.Or_error.t val get_width : Or_current.t -> int Api_call.Or_error.t val set_width : Or_current.t -> width:int -> unit Api_call.Or_error.t val get_var : Or_current.t -> name:string -> type_:'a Type.t -> 'a Api_call.Or_error.t val set_var : Or_current.t -> name:string -> type_:'a Type.t -> value:'a -> unit Api_call.Or_error.t val delete_var : Or_current.t -> name:string -> unit Api_call.Or_error.t val get_option : Or_current.t -> name:string -> type_:'a Type.t -> 'a Api_call.Or_error.t val set_option : Or_current.t -> scope:[ `Local | `Global ] -> name:string -> type_:'a Type.t -> value:'a -> unit Api_call.Or_error.t val get_position : Or_current.t -> Position.t Api_call.Or_error.t val get_tabpage : Or_current.t -> Nvim_internal.Tabpage.t Api_call.Or_error.t val get_number : Or_current.t -> int Api_call.Or_error.t val is_valid : t -> bool Api_call.Or_error.t module Expert : sig val set_buf : Or_current.t -> buffer:Nvim_internal.Buffer.Or_current.t -> unit Api_call.Or_error.t val win_call : Or_current.t -> lua_callback:Nvim_internal.Luaref.t -> Msgpack.t Api_call.Or_error.t end end
fa6feabf643c1d4a81e289d87cc3e1d91e641dbc3f46b0a6680066594f66249c
anuragsoni/poll
kqueue_poll.ml
open! Import type t = { kqueue : Kqueue.t ; eventlist : Kqueue.Event_list.t ; mutable ready_events : int } let backend = Backend.Kqueue let create ?(num_events = 256) () = if num_events < 1 then invalid_arg "Number of events cannot be less than 1"; let eventlist = Kqueue.Event_list.create num_events in { kqueue = Kqueue.create (); eventlist; ready_events = 0 } ;; let fill_event ident event flags filter = Kqueue.Event_list.Event.set_ident event ident; Kqueue.Event_list.Event.set_filter event filter; Kqueue.Event_list.Event.set_flags event flags; Kqueue.Event_list.Event.set_fflags event Kqueue.Note.empty; Kqueue.Event_list.Event.set_data event 0; Kqueue.Event_list.Event.set_udata event 0 ;; let register_events t changelist timeout = let len = Kqueue.kevent t.kqueue ~changelist ~eventlist:changelist timeout in for idx = 0 to len - 1 do let event = Kqueue.Event_list.get changelist idx in let flags = Kqueue.Event_list.Event.get_flags event in let data = Kqueue.Event_list.Event.get_data event in if Kqueue.Flag.(intersect flags error) && data <> 0 && data <> Import.unix_error_to_int Unix.ENOENT && data <> Import.unix_error_to_int Unix.EPIPE then raise (Unix.Unix_error (Import.unix_error_of_int data, "kevent", "")) done ;; let set t fd event = let changelist = Kqueue.Event_list.create 2 in let ident = Kqueue.Util.file_descr_to_int fd in let read_flags = if event.Event.readable then Kqueue.Flag.(add + oneshot + receipt) else Kqueue.Flag.delete in let write_flags = if event.writable then Kqueue.Flag.(add + oneshot + receipt) else Kqueue.Flag.delete in let idx = ref 0 in fill_event ident (Kqueue.Event_list.get changelist !idx) read_flags Kqueue.Filter.read; incr idx; fill_event ident (Kqueue.Event_list.get changelist !idx) write_flags Kqueue.Filter.write; register_events t changelist Kqueue.Timeout.never ;; let wait t timeout = let timeout = match timeout with | Timeout.Immediate -> Kqueue.Timeout.immediate | Never -> Kqueue.Timeout.never | After x -> Kqueue.Timeout.of_ns x in t.ready_events <- 0; t.ready_events <- Kqueue.kevent t.kqueue ~changelist:Kqueue.Event_list.null ~eventlist:t.eventlist timeout; if t.ready_events = 0 then `Timeout else `Ok ;; let clear t = t.ready_events <- 0 let iter_ready t ~f = for i = 0 to t.ready_events - 1 do let event = Kqueue.Event_list.get t.eventlist i in let ident = Kqueue.Event_list.Event.get_ident event in let flags = Kqueue.Event_list.Event.get_flags event in let filter = Kqueue.Event_list.Event.get_filter event in let readable = Kqueue.Filter.(filter = read) in let writable = Kqueue.Filter.(filter = write) || (readable && Kqueue.Flag.(intersect flags eof)) in f (Kqueue.Util.file_descr_of_int ident) { Event.readable; writable } done ;; let close t = Kqueue.close t.kqueue
null
https://raw.githubusercontent.com/anuragsoni/poll/fc5a98eed478f59c507cabefe072b73fdb633fe8/src/kqueue_poll.ml
ocaml
open! Import type t = { kqueue : Kqueue.t ; eventlist : Kqueue.Event_list.t ; mutable ready_events : int } let backend = Backend.Kqueue let create ?(num_events = 256) () = if num_events < 1 then invalid_arg "Number of events cannot be less than 1"; let eventlist = Kqueue.Event_list.create num_events in { kqueue = Kqueue.create (); eventlist; ready_events = 0 } ;; let fill_event ident event flags filter = Kqueue.Event_list.Event.set_ident event ident; Kqueue.Event_list.Event.set_filter event filter; Kqueue.Event_list.Event.set_flags event flags; Kqueue.Event_list.Event.set_fflags event Kqueue.Note.empty; Kqueue.Event_list.Event.set_data event 0; Kqueue.Event_list.Event.set_udata event 0 ;; let register_events t changelist timeout = let len = Kqueue.kevent t.kqueue ~changelist ~eventlist:changelist timeout in for idx = 0 to len - 1 do let event = Kqueue.Event_list.get changelist idx in let flags = Kqueue.Event_list.Event.get_flags event in let data = Kqueue.Event_list.Event.get_data event in if Kqueue.Flag.(intersect flags error) && data <> 0 && data <> Import.unix_error_to_int Unix.ENOENT && data <> Import.unix_error_to_int Unix.EPIPE then raise (Unix.Unix_error (Import.unix_error_of_int data, "kevent", "")) done ;; let set t fd event = let changelist = Kqueue.Event_list.create 2 in let ident = Kqueue.Util.file_descr_to_int fd in let read_flags = if event.Event.readable then Kqueue.Flag.(add + oneshot + receipt) else Kqueue.Flag.delete in let write_flags = if event.writable then Kqueue.Flag.(add + oneshot + receipt) else Kqueue.Flag.delete in let idx = ref 0 in fill_event ident (Kqueue.Event_list.get changelist !idx) read_flags Kqueue.Filter.read; incr idx; fill_event ident (Kqueue.Event_list.get changelist !idx) write_flags Kqueue.Filter.write; register_events t changelist Kqueue.Timeout.never ;; let wait t timeout = let timeout = match timeout with | Timeout.Immediate -> Kqueue.Timeout.immediate | Never -> Kqueue.Timeout.never | After x -> Kqueue.Timeout.of_ns x in t.ready_events <- 0; t.ready_events <- Kqueue.kevent t.kqueue ~changelist:Kqueue.Event_list.null ~eventlist:t.eventlist timeout; if t.ready_events = 0 then `Timeout else `Ok ;; let clear t = t.ready_events <- 0 let iter_ready t ~f = for i = 0 to t.ready_events - 1 do let event = Kqueue.Event_list.get t.eventlist i in let ident = Kqueue.Event_list.Event.get_ident event in let flags = Kqueue.Event_list.Event.get_flags event in let filter = Kqueue.Event_list.Event.get_filter event in let readable = Kqueue.Filter.(filter = read) in let writable = Kqueue.Filter.(filter = write) || (readable && Kqueue.Flag.(intersect flags eof)) in f (Kqueue.Util.file_descr_of_int ident) { Event.readable; writable } done ;; let close t = Kqueue.close t.kqueue
6c307c06edce1ea9c704c8b4c878d0194b26ce1e1c94645151f33770b77436b5
ocsigen/js_of_ocaml
js.mli
Js_of_ocaml library * / * Copyright ( C ) 2010 * Laboratoire PPS - CNRS Université Paris Diderot * * 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 , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * / * Copyright (C) 2010 Jérôme Vouillon * Laboratoire PPS - CNRS Université Paris Diderot * * 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, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) (** Javascript binding This module provides types and functions to interoperate with Javascript values, and gives access to Javascript standard objects. *) (** {2 Dealing with [null] and [undefined] values.} *) type +'a opt (** Type of possibly null values. *) type +'a optdef (** Type of possibly undefined values. *) val null : 'a opt (** The [null] value. *) val some : 'a -> 'a opt (** Consider a value into a possibly null value. *) val undefined : 'a optdef (** The [undefined] value *) val def : 'a -> 'a optdef (** Consider a value into a possibly undefined value. *) (** Signatures of a set of standard functions for manipulating optional values. *) module type OPT = sig type 'a t val empty : 'a t (** No value. *) val return : 'a -> 'a t (** Consider a value as an optional value. *) val map : 'a t -> ('a -> 'b) -> 'b t (** Apply a function to an optional value if it is available. Returns the result of the application. *) val bind : 'a t -> ('a -> 'b t) -> 'b t (** Apply a function returning an optional value to an optional value *) val test : 'a t -> bool (** Returns [true] if a value is available, [false] otherwise. *) val iter : 'a t -> ('a -> unit) -> unit (** Apply a function to an optional value if it is available. *) val case : 'a t -> (unit -> 'b) -> ('a -> 'b) -> 'b (** Pattern matching on optional values. *) val get : 'a t -> (unit -> 'a) -> 'a (** Get the value. If no value available, an alternative function is called to get a default value. *) val option : 'a option -> 'a t (** Convert option type. *) val to_option : 'a t -> 'a option (** Convert to option type. *) end module Opt : OPT with type 'a t = 'a opt (** Standard functions for manipulating possibly null values. *) module Optdef : OPT with type 'a t = 'a optdef (** Standard functions for manipulating possibly undefined values. *) (** {2 Types for specifying method and properties of Javascript objects} *) type +'a t (** Type of Javascript objects. The type parameter is used to specify more precisely an object. *) type +'a meth (** Type used to specify method types: a Javascript object [<m : t1 -> t2 -> ... -> tn -> t Js.meth> Js.t] has a Javascript method [m] expecting {i n} arguments of types [t1] to [tn] and returns a value of type [t]. *) type +'a gen_prop (** Type used to specify the properties of Javascript objects. In practice you should rarely need this type directly, but should rather use the type abbreviations below instead. *) type 'a readonly_prop = < get : 'a > gen_prop (** Type of read-only properties: a Javascript object [<p : t Js.readonly_prop> Js.t] has a read-only property [p] of type [t]. *) type 'a writeonly_prop = < set : 'a -> unit > gen_prop (** Type of write-only properties: a Javascript object [<p : t Js.writeonly_prop> Js.t] has a write-only property [p] of type [t]. *) type 'a prop = < get : 'a ; set : 'a -> unit > gen_prop (** Type of read/write properties: a Javascript object [<p : t Js.writeonly_prop> Js.t] has a read/write property [p] of type [t]. *) type 'a optdef_prop = < get : 'a optdef ; set : 'a -> unit > gen_prop (** Type of read/write properties that may be undefined: you can set them to a value of some type [t], but if you read them, you will get a value of type [t optdef] (that may be [undefined]). *) * { 2 Object constructors } type +'a constr * A value of type [ ( t1 - > ... - > tn - > t Js.t ) Js.constr ] is a Javascript constructor expecting { i n } arguments of types [ t1 ] to [ tn ] and returning a Javascript object of type [ t Js.t ] . Use the syntax extension [ new%js c e1 ... en ] to build an object using constructor [ c ] and arguments [ e1 ] to [ en ] . Javascript constructor expecting {i n} arguments of types [t1] to [tn] and returning a Javascript object of type [t Js.t]. Use the syntax extension [new%js c e1 ... en] to build an object using constructor [c] and arguments [e1] to [en]. *) * { 2 Callbacks to OCaml } type (-'a, +'b) meth_callback * Type of callback functions . A function of type [ ( u , t1 - > ... - > tn - > t ) meth_callback ] can be called from Javascript with [ this ] bound to a value of type [ u ] and up to { i n } arguments of types [ t1 ] to [ tn ] . The system takes care of currification , so less than { i n } arguments can be provided . As a special case , a callback of type [ ( t , unit - > t ) meth_callback ] can be called from Javascript with no argument . It will behave as if it was called with a single argument of type [ unit ] . [(u, t1 -> ... -> tn -> t) meth_callback] can be called from Javascript with [this] bound to a value of type [u] and up to {i n} arguments of types [t1] to [tn]. The system takes care of currification, so less than {i n} arguments can be provided. As a special case, a callback of type [(t, unit -> t) meth_callback] can be called from Javascript with no argument. It will behave as if it was called with a single argument of type [unit]. *) type 'a callback = (unit, 'a) meth_callback (** Type of callback functions intended to be called without a meaningful [this] implicit parameter. *) external wrap_callback : ('a -> 'b) -> ('c, 'a -> 'b) meth_callback = "caml_js_wrap_callback" * Wrap an OCaml function so that it can be invoked from Javascript . Javascript. *) external wrap_meth_callback : ('b -> 'a) -> ('b, 'a) meth_callback = "caml_js_wrap_meth_callback" * Wrap an OCaml function so that it can be invoked from Javascript . The first parameter of the function will be bound to the value of the [ this ] implicit parameter . Javascript. The first parameter of the function will be bound to the value of the [this] implicit parameter. *) * { 2 Javascript standard objects } val _true : bool t (** Javascript [true] boolean. *) val _false : bool t (** Javascript [false] boolean. *) type match_result_handle * A handle to a match result . Use function [ ] to get the corresponding [ MatchResult ] object . ( This type is used to resolved the mutual dependency between string and array type definitions . ) to get the corresponding [MatchResult] object. (This type is used to resolved the mutual dependency between string and array type definitions.) *) type string_array (** Opaque type for string arrays. You can get the actual [Array] object using function [Js.str_array]. (This type is used to resolved the mutual dependency between string and array type definitions.) *) type normalization * Opaque type for Unicode normalization forms . val nfd : normalization t (** Canonical Decomposition *) val nfc : normalization t * Canonical Decomposition , followed by Canonical Composition val nfkd : normalization t (** Compatibility Decomposition *) val nfkc : normalization t * Compatibility Decomposition , followed by Canonical Composition (** Specification of Javascript string objects. *) class type js_string = object method toString : js_string t meth method valueOf : js_string t meth method charAt : int -> js_string t meth method charCodeAt : int -> float meth This may return NaN ... method concat : js_string t -> js_string t meth method concat_2 : js_string t -> js_string t -> js_string t meth method concat_3 : js_string t -> js_string t -> js_string t -> js_string t meth method concat_4 : js_string t -> js_string t -> js_string t -> js_string t -> js_string t meth method indexOf : js_string t -> int meth method indexOf_from : js_string t -> int -> int meth method lastIndexOf : js_string t -> int meth method lastIndexOf_from : js_string t -> int -> int meth method localeCompare : js_string t -> float meth method _match : regExp t -> match_result_handle t opt meth method normalize : js_string t meth method normalize_form : normalization t -> js_string t meth method replace : regExp t -> js_string t -> js_string t meth (* FIX: version of replace taking a function... *) method replace_string : js_string t -> js_string t -> js_string t meth method search : regExp t -> int meth method slice : int -> int -> js_string t meth method slice_end : int -> js_string t meth method split : js_string t -> string_array t meth method split_limited : js_string t -> int -> string_array t meth method split_regExp : regExp t -> string_array t meth method split_regExpLimited : regExp t -> int -> string_array t meth method substring : int -> int -> js_string t meth method substring_toEnd : int -> js_string t meth method toLowerCase : js_string t meth method toLocaleLowerCase : js_string t meth method toUpperCase : js_string t meth method toLocaleUpperCase : js_string t meth method trim : js_string t meth method length : int readonly_prop end (** Specification of Javascript regular expression objects. *) and regExp = object method exec : js_string t -> match_result_handle t opt meth method test : js_string t -> bool t meth method toString : js_string t meth method source : js_string t readonly_prop method global : bool t readonly_prop method ignoreCase : bool t readonly_prop method multiline : bool t readonly_prop method lastIndex : int prop end (** Specification of the string constructor, considered as an object. *) class type string_constr = object method fromCharCode : int -> js_string t meth end val string_constr : string_constr t (** The string constructor, as an object. *) val regExp : (js_string t -> regExp t) constr (** Constructor of [RegExp] objects. The expression [new%js regExp s] builds the regular expression specified by string [s]. *) val regExp_withFlags : (js_string t -> js_string t -> regExp t) constr (** Constructor of [RegExp] objects. The expression [new%js regExp s f] builds the regular expression specified by string [s] using flags [f]. *) val regExp_copy : (regExp t -> regExp t) constr (** Constructor of [RegExp] objects. The expression [new%js regExp r] builds a copy of regular expression [r]. *) (** Specification of Javascript regular arrays. Use [Js.array_get] and [Js.array_set] to access and set array elements. *) class type ['a] js_array = object method toString : js_string t meth method toLocaleString : js_string t meth method concat : 'a js_array t -> 'a js_array t meth method join : js_string t -> js_string t meth method pop : 'a optdef meth method push : 'a -> int meth method push_2 : 'a -> 'a -> int meth method push_3 : 'a -> 'a -> 'a -> int meth method push_4 : 'a -> 'a -> 'a -> 'a -> int meth method reverse : 'a js_array t meth method shift : 'a optdef meth method slice : int -> int -> 'a js_array t meth method slice_end : int -> 'a js_array t meth method sort : ('a -> 'a -> float) callback -> 'a js_array t meth method sort_asStrings : 'a js_array t meth method splice : int -> int -> 'a js_array t meth method splice_1 : int -> int -> 'a -> 'a js_array t meth method splice_2 : int -> int -> 'a -> 'a -> 'a js_array t meth method splice_3 : int -> int -> 'a -> 'a -> 'a -> 'a js_array t meth method splice_4 : int -> int -> 'a -> 'a -> 'a -> 'a -> 'a js_array t meth method unshift : 'a -> int meth method unshift_2 : 'a -> 'a -> int meth method unshift_3 : 'a -> 'a -> 'a -> int meth method unshift_4 : 'a -> 'a -> 'a -> 'a -> int meth method some : ('a -> int -> 'a js_array t -> bool t) callback -> bool t meth method every : ('a -> int -> 'a js_array t -> bool t) callback -> bool t meth method forEach : ('a -> int -> 'a js_array t -> unit) callback -> unit meth method map : ('a -> int -> 'a js_array t -> 'b) callback -> 'b js_array t meth method filter : ('a -> int -> 'a js_array t -> bool t) callback -> 'a js_array t meth method reduce_init : ('b -> 'a -> int -> 'a js_array t -> 'b) callback -> 'b -> 'b meth method reduce : ('a -> 'a -> int -> 'a js_array t -> 'a) callback -> 'a meth method reduceRight_init : ('b -> 'a -> int -> 'a js_array t -> 'b) callback -> 'b -> 'b meth method reduceRight : ('a -> 'a -> int -> 'a js_array t -> 'a) callback -> 'a meth method length : int prop end val object_keys : 'a t -> js_string t js_array t (** Returns jsarray containing keys of the object as Object.keys does. *) val array_empty : 'a js_array t constr (** Constructor of [Array] objects. The expression [new%js array_empty] returns an empty array. *) val array_length : (int -> 'a js_array t) constr (** Constructor of [Array] objects. The expression [new%js array_length l] returns an array of length [l]. *) val array_get : 'a #js_array t -> int -> 'a optdef (** Array access: [array_get a i] returns the element at index [i] of array [a]. Returns [undefined] if there is no element at this index. *) val array_set : 'a #js_array t -> int -> 'a -> unit (** Array update: [array_set a i v] puts [v] at index [i] in array [a]. *) val array_map : ('a -> 'b) -> 'a #js_array t -> 'b #js_array t (** Array map: [array_map f a] is [a##map(wrap_callback (fun elt idx arr -> f elt))]. *) val array_mapi : (int -> 'a -> 'b) -> 'a #js_array t -> 'b #js_array t (** Array mapi: [array_mapi f a] is [a##map(wrap_callback (fun elt idx arr -> f idx elt))]. *) (** Specification of match result objects *) class type match_result = object inherit [js_string t] js_array method index : int readonly_prop method input : js_string t readonly_prop end val str_array : string_array t -> js_string t js_array t (** Convert an opaque [string_array t] object into an array of string. (Used to resolved the mutual dependency between string and array type definitions.) *) val match_result : match_result_handle t -> match_result t * Convert a match result handle into a [ MatchResult ] object . ( Used to resolved the mutual dependency between string and array type definitions . ) (Used to resolved the mutual dependency between string and array type definitions.) *) (** Specification of Javascript number objects. *) class type number = object method toString : js_string t meth method toString_radix : int -> js_string t meth method toLocaleString : js_string t meth method toFixed : int -> js_string t meth method toExponential : js_string t meth method toExponential_digits : int -> js_string t meth method toPrecision : int -> js_string t meth end external number_of_float : float -> number t = "caml_js_from_float" (** Conversion of OCaml floats to Javascript number objects. *) external float_of_number : number t -> float = "caml_js_to_float" (** Conversion of Javascript number objects to OCaml floats. *) (** Specification of Javascript date objects. *) class type date = object method toString : js_string t meth method toDateString : js_string t meth method toTimeString : js_string t meth method toLocaleString : js_string t meth method toLocaleDateString : js_string t meth method toLocaleTimeString : js_string t meth method valueOf : float meth method getTime : float meth method getFullYear : int meth method getUTCFullYear : int meth method getMonth : int meth method getUTCMonth : int meth method getDate : int meth method getUTCDate : int meth method getDay : int meth method getUTCDay : int meth method getHours : int meth method getUTCHours : int meth method getMinutes : int meth method getUTCMinutes : int meth method getSeconds : int meth method getUTCSeconds : int meth method getMilliseconds : int meth method getUTCMilliseconds : int meth method getTimezoneOffset : int meth method setTime : float -> float meth method setFullYear : int -> float meth method setUTCFullYear : int -> float meth method setMonth : int -> float meth method setUTCMonth : int -> float meth method setDate : int -> float meth method setUTCDate : int -> float meth method setDay : int -> float meth method setUTCDay : int -> float meth method setHours : int -> float meth method setUTCHours : int -> float meth method setMinutes : int -> float meth method setUTCMinutes : int -> float meth method setSeconds : int -> float meth method setUTCSeconds : int -> float meth method setMilliseconds : int -> float meth method setUTCMilliseconds : int -> float meth method toUTCString : js_string t meth method toISOString : js_string t meth method toJSON : 'a -> js_string t meth end val date_now : date t constr * Constructor of [ Date ] objects : [ new%js date_now ] returns a [ Date ] object initialized with the current date . [Date] object initialized with the current date. *) val date_fromTimeValue : (float -> date t) constr (** Constructor of [Date] objects: [new%js date_fromTimeValue t] returns a [Date] object initialized with the time value [t]. *) val date_month : (int -> int -> date t) constr * Constructor of [ Date ] objects : [ new%js date_fromTimeValue y m ] returns a [ Date ] object corresponding to year [ y ] and month [ m ] . returns a [Date] object corresponding to year [y] and month [m]. *) val date_day : (int -> int -> int -> date t) constr * Constructor of [ Date ] objects : [ new%js date_fromTimeValue y m d ] returns a [ Date ] object corresponding to year [ y ] , month [ m ] and day [ d ] . returns a [Date] object corresponding to year [y], month [m] and day [d]. *) val date_hour : (int -> int -> int -> int -> date t) constr (** Constructor of [Date] objects: [new%js date_fromTimeValue y m d h] returns a [Date] object corresponding to year [y] to hour [h]. *) val date_min : (int -> int -> int -> int -> int -> date t) constr (** Constructor of [Date] objects: [new%js date_fromTimeValue y m d h m'] returns a [Date] object corresponding to year [y] to minute [m']. *) val date_sec : (int -> int -> int -> int -> int -> int -> date t) constr * Constructor of [ Date ] objects : [ new%js date_fromTimeValue y m d h m ' s ] returns a [ Date ] object corresponding to year [ y ] to second [ s ] . [new%js date_fromTimeValue y m d h m' s] returns a [Date] object corresponding to year [y] to second [s]. *) val date_ms : (int -> int -> int -> int -> int -> int -> int -> date t) constr (** Constructor of [Date] objects: [new%js date_fromTimeValue y m d h m' s ms] returns a [Date] object corresponding to year [y] to millisecond [ms]. *) (** Specification of the date constructor, considered as an object. *) class type date_constr = object method parse : js_string t -> float meth method _UTC_month : int -> int -> float meth method _UTC_day : int -> int -> float meth method _UTC_hour : int -> int -> int -> int -> float meth method _UTC_min : int -> int -> int -> int -> int -> float meth method _UTC_sec : int -> int -> int -> int -> int -> int -> float meth method _UTC_ms : int -> int -> int -> int -> int -> int -> int -> float meth method now : float meth end val date : date_constr t (** The date constructor, as an object. *) (** Specification of Javascript math object. *) class type math = object method _E : float readonly_prop method _LN2 : float readonly_prop method _LN10 : float readonly_prop method _LOG2E : float readonly_prop method _LOG10E : float readonly_prop method _PI : float readonly_prop method _SQRT1_2_ : float readonly_prop method _SQRT2 : float readonly_prop method abs : float -> float meth method acos : float -> float meth method asin : float -> float meth method atan : float -> float meth method atan2 : float -> float -> float meth method ceil : float -> float meth method cos : float -> float meth method exp : float -> float meth method floor : float -> float meth method log : float -> float meth method max : float -> float -> float meth method max_3 : float -> float -> float -> float meth method max_4 : float -> float -> float -> float -> float meth method min : float -> float -> float meth method min_3 : float -> float -> float -> float meth method min_4 : float -> float -> float -> float -> float meth method pow : float -> float -> float meth method random : float meth method round : float -> float meth method sin : float -> float meth method sqrt : float -> float meth method tan : float -> float meth end val math : math t (** The Math object *) (** Specification of Javascript error object. *) class type error = object method name : js_string t prop method message : js_string t prop method stack : js_string t optdef prop method toString : js_string t meth end val error_constr : (js_string t -> error t) constr (** Constructor of [Error] objects: [new%js error_constr msg] returns an [Error] object with the message [msg]. *) module Js_error : sig type error_t = error t type t val to_string : t -> string val name : t -> string val message : t -> string val stack : t -> string option val raise_ : t -> 'a val attach_js_backtrace : exn -> force:bool -> exn * Attach a JavasScript error to an OCaml exception . if [ force = false ] and a JavasScript error is already attached , it will do nothing . This function is useful to store and retrieve information about JavaScript stack traces . Attaching JavasScript errors will happen automatically when compiling with [ --enable with - js - error ] . JavasScript error is already attached, it will do nothing. This function is useful to store and retrieve information about JavaScript stack traces. Attaching JavasScript errors will happen automatically when compiling with [--enable with-js-error]. *) val of_exn : exn -> t option (** Extract a JavaScript error attached to an OCaml exception, if any. This is useful to inspect an eventual stack strace, especially when sourcemap is enabled. *) exception Exn of t (** The [Error] exception wrap javascript exceptions when caught by OCaml code. In case the javascript exception is not an instance of javascript [Error], it will be serialized and wrapped into a [Failure] exception. *) val of_error : error_t -> t val to_error : t -> error_t end (** Specification of Javascript JSON object. *) class type json = object method parse : js_string t -> 'a meth method stringify : 'a -> js_string t meth end val _JSON : json t (** JSON object *) * { 2 Standard Javascript functions } val decodeURI : js_string t -> js_string t * Decode a URI : replace by the corresponding byte all escape sequences but the ones corresponding to a URI reserved character and convert the string from UTF-8 to UTF-16 . sequences but the ones corresponding to a URI reserved character and convert the string from UTF-8 to UTF-16. *) val decodeURIComponent : js_string t -> js_string t * Decode a URIComponent : replace all escape sequences by the corresponding byte and convert the string from UTF-8 to UTF-16 . corresponding byte and convert the string from UTF-8 to UTF-16. *) val encodeURI : js_string t -> js_string t * Encode a URI : convert the string to UTF-8 and replace all unsafe bytes by the corresponding escape sequence . bytes by the corresponding escape sequence. *) val encodeURIComponent : js_string t -> js_string t * Same as [ encodeURI ] , but also encode URI reserved characters . val escape : js_string t -> js_string t * Escape a string : unsafe UTF-16 code points are replaced by 2 - digit and 4 - digit escape sequences . 2-digit and 4-digit escape sequences. *) val unescape : js_string t -> js_string t * Unescape a string : 2 - digit and 4 - digit escape sequences are replaced by the corresponding UTF-16 code point . replaced by the corresponding UTF-16 code point. *) val isNaN : 'a -> bool val parseInt : js_string t -> int val parseFloat : js_string t -> float * { 2 Conversion functions between Javascript and OCaml types } external bool : bool -> bool t = "caml_js_from_bool" (** Conversion of booleans from OCaml to Javascript. *) external to_bool : bool t -> bool = "caml_js_to_bool" (** Conversion of booleans from Javascript to OCaml. *) external string : string -> js_string t = "caml_jsstring_of_string" * Conversion of strings from OCaml to Javascript . ( The OCaml string is considered to be encoded in UTF-8 and is converted to UTF-16 . ) string is considered to be encoded in UTF-8 and is converted to UTF-16.) *) external to_string : js_string t -> string = "caml_string_of_jsstring" (** Conversion of strings from Javascript to OCaml. *) external array : 'a array -> 'a js_array t = "caml_js_from_array" (** Conversion of arrays from OCaml to Javascript. *) external to_array : 'a js_array t -> 'a array = "caml_js_to_array" (** Conversion of arrays from Javascript to OCaml. *) external bytestring : string -> js_string t = "caml_jsbytes_of_string" (** Conversion of strings of bytes from OCaml to Javascript. (Each byte will be converted in an UTF-16 code point.) *) external to_bytestring : js_string t -> string = "caml_string_of_jsbytes" * Conversion of strings of bytes from Javascript to OCaml . ( The Javascript string should only contain UTF-16 code points below 255 . ) Javascript string should only contain UTF-16 code points below 255.) *) * { 2 Convenience coercion functions } val coerce : 'a -> ('a -> 'b Opt.t) -> ('a -> 'b) -> 'b (** Apply a possibly failing coercion function. [coerce v c f] attempts to apply coercion [c] to value [v]. If the coercion returns [null], function [f] is called. *) val coerce_opt : 'a Opt.t -> ('a -> 'b Opt.t) -> ('a -> 'b) -> 'b (** Apply a possibly failing coercion function. [coerce_opt v c f] attempts to apply coercion [c] to value [v]. If [v] is [null] or the coercion returns [null], function [f] is called. Typical usage is the following: {[Js.coerce_opt (Dom_html.document##getElementById id) Dom_html.CoerceTo.div (fun _ -> assert false)]} *) * { 2 Type checking operators . } external typeof : _ t -> js_string t = "caml_js_typeof" (** Returns the type of a Javascript object. *) external instanceof : _ t -> _ constr -> bool = "caml_js_instanceof" (** Tests whether a Javascript object is an instance of a given class. *) * { 2 Debugging operations . } external debugger : unit -> unit = "debugger" * Invokes any available debugging functionality . If no debugging functionality is available , it has no effect . In practice , it will insert a " debugger ; " statement in the generated javascript . If no debugging functionality is available, it has no effect. In practice, it will insert a "debugger;" statement in the generated javascript. *) (** {2 Export functionality.} Export values to [module.exports] if it exists or to the global object otherwise. *) val export : string -> 'a -> unit (** [export name value] export [name] *) val export_all : 'a t -> unit * [ export_all obj ] export every key of [ obj ] object . { [ export_all object%js method add x y = x + . y method abs x = abs_float x val zero = 0 . end ] } {[ export_all object%js method add x y = x +. y method abs x = abs_float x val zero = 0. end ]} *) * { 2 Unsafe operations . } (** Unsafe Javascript operations *) module Unsafe : sig type top type any = top t (** Top type. Used for putting values of different types in a same array. *) type any_js_array = any external inject : 'a -> any = "%identity" (** Coercion to top type. *) external coerce : _ t -> _ t = "%identity" (** Unsafe coercion between to Javascript objects. *) external get : 'a -> 'b -> 'c = "caml_js_get" (** Get the value of an object property. The expression [get o s] returns the value of property [s] of object [o]. *) external set : 'a -> 'b -> 'c -> unit = "caml_js_set" (** Set an object property. The expression [set o s v] set the property [s] of object [o] to value [v]. *) external delete : 'a -> 'b -> unit = "caml_js_delete" (** Delete an object property. The expression [delete o s] deletes property [s] of object [o]. *) external call : 'a -> 'b -> any array -> 'c = "caml_js_call" * Performs a Javascript function call . The expression [ call f o a ] calls the Javascript function [ f ] with the arguments given by the array [ a ] , and binding [ this ] to [ o ] . [call f o a] calls the Javascript function [f] with the arguments given by the array [a], and binding [this] to [o]. *) external fun_call : 'a -> any array -> 'b = "caml_js_fun_call" * Performs a Javascript function call . The expression [ fun_call f a ] calls the Javascript function [ f ] with the arguments given by the array [ a ] . [fun_call f a] calls the Javascript function [f] with the arguments given by the array [a]. *) external meth_call : 'a -> string -> any array -> 'b = "caml_js_meth_call" (** Performs a Javascript method call. The expression [meth_call o m a] calls the Javascript method [m] of object [o] with the arguments given by the array [a]. *) external new_obj : 'a -> any array -> 'b = "caml_js_new" * Create a Javascript object . The expression [ new_obj c a ] creates a Javascript object with constructor [ c ] using the arguments given by the array [ a ] . Example : [ ( Js.Unsafe.variable " ArrayBuffer " ) [ || ] ] creates a Javascript object with constructor [c] using the arguments given by the array [a]. Example: [Js.new_obj (Js.Unsafe.variable "ArrayBuffer") [||]] *) external new_obj_arr : 'a -> any_js_array -> 'b = "caml_ojs_new_arr" * Same Create a Javascript object . The expression [ c a ] creates a Javascript object with constructor [ c ] using the arguments given by the Javascript array [ a ] . creates a Javascript object with constructor [c] using the arguments given by the Javascript array [a]. *) external obj : (string * any) array -> 'a = "caml_js_object" (** Creates a Javascript literal object. The expression [obj a] creates a Javascript object whose fields are given by the array [a] *) external pure_expr : (unit -> 'a) -> 'a = "caml_js_pure_expr" (** Asserts that an expression is pure, and can therefore be optimized away by the compiler if unused. *) external eval_string : string -> 'a = "caml_js_eval_string" (** Evaluate Javascript code *) external js_expr : string -> 'a = "caml_js_expr" * [ js_expr e ] will parse the JavaScript expression [ e ] if [ e ] is available at compile time or will fallback to a runtime evaluation . See [ eval_string ] is available at compile time or will fallback to a runtime evaluation. See [eval_string] *) external pure_js_expr : string -> 'a = "caml_pure_js_expr" * [ pure_js_expr str ] behaves like [ pure_expr ( fun ( ) - > ) ] . val global : < .. > t (** Javascript global object *) external callback : ('a -> 'b) -> ('c, 'a -> 'b) meth_callback = "caml_js_wrap_callback_unsafe" * Wrap an OCaml function so that it can be invoked from Javascript . Contrary to [ Js.wrap_callback ] , partial application and over - application are not supported : missing arguments will be set to [ undefined ] and extra arguments are lost . Javascript. Contrary to [Js.wrap_callback], partial application and over-application are not supported: missing arguments will be set to [undefined] and extra arguments are lost. *) external callback_with_arguments : (any_js_array -> 'b) -> ('c, any_js_array -> 'b) meth_callback = "caml_js_wrap_callback_arguments" * Wrap an OCaml function so that it can be invoked from Javascript . The first parameter of the function will be bound to the [ arguments ] JavaScript Javascript. The first parameter of the function will be bound to the [arguments] JavaScript *) external callback_with_arity : int -> ('a -> 'b) -> ('c, 'a -> 'b) meth_callback = "caml_js_wrap_callback_strict" external meth_callback : ('b -> 'a) -> ('b, 'a) meth_callback = "caml_js_wrap_meth_callback_unsafe" * Wrap an OCaml function so that it can be invoked from Javascript . The first parameter of the function will be bound to the value of the [ this ] implicit parameter . Contrary to [ Js.wrap_meth_callback ] , partial application and over - application is not supported : missing arguments will be set to [ undefined ] and extra arguments are lost . Javascript. The first parameter of the function will be bound to the value of the [this] implicit parameter. Contrary to [Js.wrap_meth_callback], partial application and over-application is not supported: missing arguments will be set to [undefined] and extra arguments are lost. *) external meth_callback_with_arguments : ('b -> any_js_array -> 'a) -> ('b, any_js_array -> 'a) meth_callback = "caml_js_wrap_meth_callback_arguments" * Wrap an OCaml function so that it can be invoked from Javascript . The first parameter of the function will be bound to the value of the [ this ] implicit parameter . The second parameter of the function with be bound to the value of the [ arguments ] . The first parameter of the function will be bound to the value of the [this] implicit parameter. The second parameter of the function with be bound to the value of the [arguments]. *) external meth_callback_with_arity : int -> ('b -> 'a) -> ('b, 'a) meth_callback = "caml_js_wrap_meth_callback_strict" * { 3 Deprecated functions . } external variable : string -> 'a = "caml_js_var" [@@ocaml.deprecated "[since 2.6] use Js.Unsafe.pure_js_expr instead"] (** Access a Javascript variable. [variable "foo"] will return the current value of variable [foo]. *) end * { 2 Deprecated functions and types . } val string_of_error : error t -> string [@@ocaml.deprecated "[since 4.0] Use [Js_error.to_string] instead."] val raise_js_error : error t -> 'a [@@ocaml.deprecated "[since 4.0] Use [Js_error.raise_] instead."] val exn_with_js_backtrace : exn -> force:bool -> exn [@@ocaml.deprecated "[since 4.0] Use [Js_error.raise_] instead."] * Attach a JavasScript error to an OCaml exception . if [ force = false ] and a JavasScript error is already attached , it will do nothing . This function is useful to store and retrieve information about JavaScript stack traces . Attaching JavasScript errors will happen automatically when compiling with [ --enable with - js - error ] . JavasScript error is already attached, it will do nothing. This function is useful to store and retrieve information about JavaScript stack traces. Attaching JavasScript errors will happen automatically when compiling with [--enable with-js-error]. *) val js_error_of_exn : exn -> error t opt [@@ocaml.deprecated "[since 4.0] Use [Js_error.of_exn] instead."] (** Extract a JavaScript error attached to an OCaml exception, if any. This is useful to inspect an eventual stack strace, especially when sourcemap is enabled. *) exception Error of error t [@ocaml.deprecated "[since 4.0] Use [Js_error.Exn] instead."] (** The [Error] exception wrap javascript exceptions when caught by OCaml code. In case the javascript exception is not an instance of javascript [Error], it will be serialized and wrapped into a [Failure] exception. *) external float : float -> float = "%identity" [@@ocaml.deprecated "[since 2.0]."] (** Conversion of OCaml floats to Javascript numbers. *) external to_float : float -> float = "%identity" [@@ocaml.deprecated "[since 2.0]."] (** Conversion of Javascript numbers to OCaml floats. *) type float_prop = float prop [@@ocaml.deprecated "[since 2.0]."] (** Type of float properties. *)
null
https://raw.githubusercontent.com/ocsigen/js_of_ocaml/a2aa561b0c83be5c946336a330a6ed9b553f02ad/lib/js_of_ocaml/js.mli
ocaml
* Javascript binding This module provides types and functions to interoperate with Javascript values, and gives access to Javascript standard objects. * {2 Dealing with [null] and [undefined] values.} * Type of possibly null values. * Type of possibly undefined values. * The [null] value. * Consider a value into a possibly null value. * The [undefined] value * Consider a value into a possibly undefined value. * Signatures of a set of standard functions for manipulating optional values. * No value. * Consider a value as an optional value. * Apply a function to an optional value if it is available. Returns the result of the application. * Apply a function returning an optional value to an optional value * Returns [true] if a value is available, [false] otherwise. * Apply a function to an optional value if it is available. * Pattern matching on optional values. * Get the value. If no value available, an alternative function is called to get a default value. * Convert option type. * Convert to option type. * Standard functions for manipulating possibly null values. * Standard functions for manipulating possibly undefined values. * {2 Types for specifying method and properties of Javascript objects} * Type of Javascript objects. The type parameter is used to specify more precisely an object. * Type used to specify method types: a Javascript object [<m : t1 -> t2 -> ... -> tn -> t Js.meth> Js.t] has a Javascript method [m] expecting {i n} arguments of types [t1] to [tn] and returns a value of type [t]. * Type used to specify the properties of Javascript objects. In practice you should rarely need this type directly, but should rather use the type abbreviations below instead. * Type of read-only properties: a Javascript object [<p : t Js.readonly_prop> Js.t] has a read-only property [p] of type [t]. * Type of write-only properties: a Javascript object [<p : t Js.writeonly_prop> Js.t] has a write-only property [p] of type [t]. * Type of read/write properties: a Javascript object [<p : t Js.writeonly_prop> Js.t] has a read/write property [p] of type [t]. * Type of read/write properties that may be undefined: you can set them to a value of some type [t], but if you read them, you will get a value of type [t optdef] (that may be [undefined]). * Type of callback functions intended to be called without a meaningful [this] implicit parameter. * Javascript [true] boolean. * Javascript [false] boolean. * Opaque type for string arrays. You can get the actual [Array] object using function [Js.str_array]. (This type is used to resolved the mutual dependency between string and array type definitions.) * Canonical Decomposition * Compatibility Decomposition * Specification of Javascript string objects. FIX: version of replace taking a function... * Specification of Javascript regular expression objects. * Specification of the string constructor, considered as an object. * The string constructor, as an object. * Constructor of [RegExp] objects. The expression [new%js regExp s] builds the regular expression specified by string [s]. * Constructor of [RegExp] objects. The expression [new%js regExp s f] builds the regular expression specified by string [s] using flags [f]. * Constructor of [RegExp] objects. The expression [new%js regExp r] builds a copy of regular expression [r]. * Specification of Javascript regular arrays. Use [Js.array_get] and [Js.array_set] to access and set array elements. * Returns jsarray containing keys of the object as Object.keys does. * Constructor of [Array] objects. The expression [new%js array_empty] returns an empty array. * Constructor of [Array] objects. The expression [new%js array_length l] returns an array of length [l]. * Array access: [array_get a i] returns the element at index [i] of array [a]. Returns [undefined] if there is no element at this index. * Array update: [array_set a i v] puts [v] at index [i] in array [a]. * Array map: [array_map f a] is [a##map(wrap_callback (fun elt idx arr -> f elt))]. * Array mapi: [array_mapi f a] is [a##map(wrap_callback (fun elt idx arr -> f idx elt))]. * Specification of match result objects * Convert an opaque [string_array t] object into an array of string. (Used to resolved the mutual dependency between string and array type definitions.) * Specification of Javascript number objects. * Conversion of OCaml floats to Javascript number objects. * Conversion of Javascript number objects to OCaml floats. * Specification of Javascript date objects. * Constructor of [Date] objects: [new%js date_fromTimeValue t] returns a [Date] object initialized with the time value [t]. * Constructor of [Date] objects: [new%js date_fromTimeValue y m d h] returns a [Date] object corresponding to year [y] to hour [h]. * Constructor of [Date] objects: [new%js date_fromTimeValue y m d h m'] returns a [Date] object corresponding to year [y] to minute [m']. * Constructor of [Date] objects: [new%js date_fromTimeValue y m d h m' s ms] returns a [Date] object corresponding to year [y] to millisecond [ms]. * Specification of the date constructor, considered as an object. * The date constructor, as an object. * Specification of Javascript math object. * The Math object * Specification of Javascript error object. * Constructor of [Error] objects: [new%js error_constr msg] returns an [Error] object with the message [msg]. * Extract a JavaScript error attached to an OCaml exception, if any. This is useful to inspect an eventual stack strace, especially when sourcemap is enabled. * The [Error] exception wrap javascript exceptions when caught by OCaml code. In case the javascript exception is not an instance of javascript [Error], it will be serialized and wrapped into a [Failure] exception. * Specification of Javascript JSON object. * JSON object * Conversion of booleans from OCaml to Javascript. * Conversion of booleans from Javascript to OCaml. * Conversion of strings from Javascript to OCaml. * Conversion of arrays from OCaml to Javascript. * Conversion of arrays from Javascript to OCaml. * Conversion of strings of bytes from OCaml to Javascript. (Each byte will be converted in an UTF-16 code point.) * Apply a possibly failing coercion function. [coerce v c f] attempts to apply coercion [c] to value [v]. If the coercion returns [null], function [f] is called. * Apply a possibly failing coercion function. [coerce_opt v c f] attempts to apply coercion [c] to value [v]. If [v] is [null] or the coercion returns [null], function [f] is called. Typical usage is the following: {[Js.coerce_opt (Dom_html.document##getElementById id) Dom_html.CoerceTo.div (fun _ -> assert false)]} * Returns the type of a Javascript object. * Tests whether a Javascript object is an instance of a given class. * {2 Export functionality.} Export values to [module.exports] if it exists or to the global object otherwise. * [export name value] export [name] * Unsafe Javascript operations * Top type. Used for putting values of different types in a same array. * Coercion to top type. * Unsafe coercion between to Javascript objects. * Get the value of an object property. The expression [get o s] returns the value of property [s] of object [o]. * Set an object property. The expression [set o s v] set the property [s] of object [o] to value [v]. * Delete an object property. The expression [delete o s] deletes property [s] of object [o]. * Performs a Javascript method call. The expression [meth_call o m a] calls the Javascript method [m] of object [o] with the arguments given by the array [a]. * Creates a Javascript literal object. The expression [obj a] creates a Javascript object whose fields are given by the array [a] * Asserts that an expression is pure, and can therefore be optimized away by the compiler if unused. * Evaluate Javascript code * Javascript global object * Access a Javascript variable. [variable "foo"] will return the current value of variable [foo]. * Extract a JavaScript error attached to an OCaml exception, if any. This is useful to inspect an eventual stack strace, especially when sourcemap is enabled. * The [Error] exception wrap javascript exceptions when caught by OCaml code. In case the javascript exception is not an instance of javascript [Error], it will be serialized and wrapped into a [Failure] exception. * Conversion of OCaml floats to Javascript numbers. * Conversion of Javascript numbers to OCaml floats. * Type of float properties.
Js_of_ocaml library * / * Copyright ( C ) 2010 * Laboratoire PPS - CNRS Université Paris Diderot * * 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 , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * / * Copyright (C) 2010 Jérôme Vouillon * Laboratoire PPS - CNRS Université Paris Diderot * * 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, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) type +'a opt type +'a optdef val null : 'a opt val some : 'a -> 'a opt val undefined : 'a optdef val def : 'a -> 'a optdef module type OPT = sig type 'a t val empty : 'a t val return : 'a -> 'a t val map : 'a t -> ('a -> 'b) -> 'b t val bind : 'a t -> ('a -> 'b t) -> 'b t val test : 'a t -> bool val iter : 'a t -> ('a -> unit) -> unit val case : 'a t -> (unit -> 'b) -> ('a -> 'b) -> 'b val get : 'a t -> (unit -> 'a) -> 'a val option : 'a option -> 'a t val to_option : 'a t -> 'a option end module Opt : OPT with type 'a t = 'a opt module Optdef : OPT with type 'a t = 'a optdef type +'a t type +'a meth type +'a gen_prop type 'a readonly_prop = < get : 'a > gen_prop type 'a writeonly_prop = < set : 'a -> unit > gen_prop type 'a prop = < get : 'a ; set : 'a -> unit > gen_prop type 'a optdef_prop = < get : 'a optdef ; set : 'a -> unit > gen_prop * { 2 Object constructors } type +'a constr * A value of type [ ( t1 - > ... - > tn - > t Js.t ) Js.constr ] is a Javascript constructor expecting { i n } arguments of types [ t1 ] to [ tn ] and returning a Javascript object of type [ t Js.t ] . Use the syntax extension [ new%js c e1 ... en ] to build an object using constructor [ c ] and arguments [ e1 ] to [ en ] . Javascript constructor expecting {i n} arguments of types [t1] to [tn] and returning a Javascript object of type [t Js.t]. Use the syntax extension [new%js c e1 ... en] to build an object using constructor [c] and arguments [e1] to [en]. *) * { 2 Callbacks to OCaml } type (-'a, +'b) meth_callback * Type of callback functions . A function of type [ ( u , t1 - > ... - > tn - > t ) meth_callback ] can be called from Javascript with [ this ] bound to a value of type [ u ] and up to { i n } arguments of types [ t1 ] to [ tn ] . The system takes care of currification , so less than { i n } arguments can be provided . As a special case , a callback of type [ ( t , unit - > t ) meth_callback ] can be called from Javascript with no argument . It will behave as if it was called with a single argument of type [ unit ] . [(u, t1 -> ... -> tn -> t) meth_callback] can be called from Javascript with [this] bound to a value of type [u] and up to {i n} arguments of types [t1] to [tn]. The system takes care of currification, so less than {i n} arguments can be provided. As a special case, a callback of type [(t, unit -> t) meth_callback] can be called from Javascript with no argument. It will behave as if it was called with a single argument of type [unit]. *) type 'a callback = (unit, 'a) meth_callback external wrap_callback : ('a -> 'b) -> ('c, 'a -> 'b) meth_callback = "caml_js_wrap_callback" * Wrap an OCaml function so that it can be invoked from Javascript . Javascript. *) external wrap_meth_callback : ('b -> 'a) -> ('b, 'a) meth_callback = "caml_js_wrap_meth_callback" * Wrap an OCaml function so that it can be invoked from Javascript . The first parameter of the function will be bound to the value of the [ this ] implicit parameter . Javascript. The first parameter of the function will be bound to the value of the [this] implicit parameter. *) * { 2 Javascript standard objects } val _true : bool t val _false : bool t type match_result_handle * A handle to a match result . Use function [ ] to get the corresponding [ MatchResult ] object . ( This type is used to resolved the mutual dependency between string and array type definitions . ) to get the corresponding [MatchResult] object. (This type is used to resolved the mutual dependency between string and array type definitions.) *) type string_array type normalization * Opaque type for Unicode normalization forms . val nfd : normalization t val nfc : normalization t * Canonical Decomposition , followed by Canonical Composition val nfkd : normalization t val nfkc : normalization t * Compatibility Decomposition , followed by Canonical Composition class type js_string = object method toString : js_string t meth method valueOf : js_string t meth method charAt : int -> js_string t meth method charCodeAt : int -> float meth This may return NaN ... method concat : js_string t -> js_string t meth method concat_2 : js_string t -> js_string t -> js_string t meth method concat_3 : js_string t -> js_string t -> js_string t -> js_string t meth method concat_4 : js_string t -> js_string t -> js_string t -> js_string t -> js_string t meth method indexOf : js_string t -> int meth method indexOf_from : js_string t -> int -> int meth method lastIndexOf : js_string t -> int meth method lastIndexOf_from : js_string t -> int -> int meth method localeCompare : js_string t -> float meth method _match : regExp t -> match_result_handle t opt meth method normalize : js_string t meth method normalize_form : normalization t -> js_string t meth method replace : regExp t -> js_string t -> js_string t meth method replace_string : js_string t -> js_string t -> js_string t meth method search : regExp t -> int meth method slice : int -> int -> js_string t meth method slice_end : int -> js_string t meth method split : js_string t -> string_array t meth method split_limited : js_string t -> int -> string_array t meth method split_regExp : regExp t -> string_array t meth method split_regExpLimited : regExp t -> int -> string_array t meth method substring : int -> int -> js_string t meth method substring_toEnd : int -> js_string t meth method toLowerCase : js_string t meth method toLocaleLowerCase : js_string t meth method toUpperCase : js_string t meth method toLocaleUpperCase : js_string t meth method trim : js_string t meth method length : int readonly_prop end and regExp = object method exec : js_string t -> match_result_handle t opt meth method test : js_string t -> bool t meth method toString : js_string t meth method source : js_string t readonly_prop method global : bool t readonly_prop method ignoreCase : bool t readonly_prop method multiline : bool t readonly_prop method lastIndex : int prop end class type string_constr = object method fromCharCode : int -> js_string t meth end val string_constr : string_constr t val regExp : (js_string t -> regExp t) constr val regExp_withFlags : (js_string t -> js_string t -> regExp t) constr val regExp_copy : (regExp t -> regExp t) constr class type ['a] js_array = object method toString : js_string t meth method toLocaleString : js_string t meth method concat : 'a js_array t -> 'a js_array t meth method join : js_string t -> js_string t meth method pop : 'a optdef meth method push : 'a -> int meth method push_2 : 'a -> 'a -> int meth method push_3 : 'a -> 'a -> 'a -> int meth method push_4 : 'a -> 'a -> 'a -> 'a -> int meth method reverse : 'a js_array t meth method shift : 'a optdef meth method slice : int -> int -> 'a js_array t meth method slice_end : int -> 'a js_array t meth method sort : ('a -> 'a -> float) callback -> 'a js_array t meth method sort_asStrings : 'a js_array t meth method splice : int -> int -> 'a js_array t meth method splice_1 : int -> int -> 'a -> 'a js_array t meth method splice_2 : int -> int -> 'a -> 'a -> 'a js_array t meth method splice_3 : int -> int -> 'a -> 'a -> 'a -> 'a js_array t meth method splice_4 : int -> int -> 'a -> 'a -> 'a -> 'a -> 'a js_array t meth method unshift : 'a -> int meth method unshift_2 : 'a -> 'a -> int meth method unshift_3 : 'a -> 'a -> 'a -> int meth method unshift_4 : 'a -> 'a -> 'a -> 'a -> int meth method some : ('a -> int -> 'a js_array t -> bool t) callback -> bool t meth method every : ('a -> int -> 'a js_array t -> bool t) callback -> bool t meth method forEach : ('a -> int -> 'a js_array t -> unit) callback -> unit meth method map : ('a -> int -> 'a js_array t -> 'b) callback -> 'b js_array t meth method filter : ('a -> int -> 'a js_array t -> bool t) callback -> 'a js_array t meth method reduce_init : ('b -> 'a -> int -> 'a js_array t -> 'b) callback -> 'b -> 'b meth method reduce : ('a -> 'a -> int -> 'a js_array t -> 'a) callback -> 'a meth method reduceRight_init : ('b -> 'a -> int -> 'a js_array t -> 'b) callback -> 'b -> 'b meth method reduceRight : ('a -> 'a -> int -> 'a js_array t -> 'a) callback -> 'a meth method length : int prop end val object_keys : 'a t -> js_string t js_array t val array_empty : 'a js_array t constr val array_length : (int -> 'a js_array t) constr val array_get : 'a #js_array t -> int -> 'a optdef val array_set : 'a #js_array t -> int -> 'a -> unit val array_map : ('a -> 'b) -> 'a #js_array t -> 'b #js_array t val array_mapi : (int -> 'a -> 'b) -> 'a #js_array t -> 'b #js_array t class type match_result = object inherit [js_string t] js_array method index : int readonly_prop method input : js_string t readonly_prop end val str_array : string_array t -> js_string t js_array t val match_result : match_result_handle t -> match_result t * Convert a match result handle into a [ MatchResult ] object . ( Used to resolved the mutual dependency between string and array type definitions . ) (Used to resolved the mutual dependency between string and array type definitions.) *) class type number = object method toString : js_string t meth method toString_radix : int -> js_string t meth method toLocaleString : js_string t meth method toFixed : int -> js_string t meth method toExponential : js_string t meth method toExponential_digits : int -> js_string t meth method toPrecision : int -> js_string t meth end external number_of_float : float -> number t = "caml_js_from_float" external float_of_number : number t -> float = "caml_js_to_float" class type date = object method toString : js_string t meth method toDateString : js_string t meth method toTimeString : js_string t meth method toLocaleString : js_string t meth method toLocaleDateString : js_string t meth method toLocaleTimeString : js_string t meth method valueOf : float meth method getTime : float meth method getFullYear : int meth method getUTCFullYear : int meth method getMonth : int meth method getUTCMonth : int meth method getDate : int meth method getUTCDate : int meth method getDay : int meth method getUTCDay : int meth method getHours : int meth method getUTCHours : int meth method getMinutes : int meth method getUTCMinutes : int meth method getSeconds : int meth method getUTCSeconds : int meth method getMilliseconds : int meth method getUTCMilliseconds : int meth method getTimezoneOffset : int meth method setTime : float -> float meth method setFullYear : int -> float meth method setUTCFullYear : int -> float meth method setMonth : int -> float meth method setUTCMonth : int -> float meth method setDate : int -> float meth method setUTCDate : int -> float meth method setDay : int -> float meth method setUTCDay : int -> float meth method setHours : int -> float meth method setUTCHours : int -> float meth method setMinutes : int -> float meth method setUTCMinutes : int -> float meth method setSeconds : int -> float meth method setUTCSeconds : int -> float meth method setMilliseconds : int -> float meth method setUTCMilliseconds : int -> float meth method toUTCString : js_string t meth method toISOString : js_string t meth method toJSON : 'a -> js_string t meth end val date_now : date t constr * Constructor of [ Date ] objects : [ new%js date_now ] returns a [ Date ] object initialized with the current date . [Date] object initialized with the current date. *) val date_fromTimeValue : (float -> date t) constr val date_month : (int -> int -> date t) constr * Constructor of [ Date ] objects : [ new%js date_fromTimeValue y m ] returns a [ Date ] object corresponding to year [ y ] and month [ m ] . returns a [Date] object corresponding to year [y] and month [m]. *) val date_day : (int -> int -> int -> date t) constr * Constructor of [ Date ] objects : [ new%js date_fromTimeValue y m d ] returns a [ Date ] object corresponding to year [ y ] , month [ m ] and day [ d ] . returns a [Date] object corresponding to year [y], month [m] and day [d]. *) val date_hour : (int -> int -> int -> int -> date t) constr val date_min : (int -> int -> int -> int -> int -> date t) constr val date_sec : (int -> int -> int -> int -> int -> int -> date t) constr * Constructor of [ Date ] objects : [ new%js date_fromTimeValue y m d h m ' s ] returns a [ Date ] object corresponding to year [ y ] to second [ s ] . [new%js date_fromTimeValue y m d h m' s] returns a [Date] object corresponding to year [y] to second [s]. *) val date_ms : (int -> int -> int -> int -> int -> int -> int -> date t) constr class type date_constr = object method parse : js_string t -> float meth method _UTC_month : int -> int -> float meth method _UTC_day : int -> int -> float meth method _UTC_hour : int -> int -> int -> int -> float meth method _UTC_min : int -> int -> int -> int -> int -> float meth method _UTC_sec : int -> int -> int -> int -> int -> int -> float meth method _UTC_ms : int -> int -> int -> int -> int -> int -> int -> float meth method now : float meth end val date : date_constr t class type math = object method _E : float readonly_prop method _LN2 : float readonly_prop method _LN10 : float readonly_prop method _LOG2E : float readonly_prop method _LOG10E : float readonly_prop method _PI : float readonly_prop method _SQRT1_2_ : float readonly_prop method _SQRT2 : float readonly_prop method abs : float -> float meth method acos : float -> float meth method asin : float -> float meth method atan : float -> float meth method atan2 : float -> float -> float meth method ceil : float -> float meth method cos : float -> float meth method exp : float -> float meth method floor : float -> float meth method log : float -> float meth method max : float -> float -> float meth method max_3 : float -> float -> float -> float meth method max_4 : float -> float -> float -> float -> float meth method min : float -> float -> float meth method min_3 : float -> float -> float -> float meth method min_4 : float -> float -> float -> float -> float meth method pow : float -> float -> float meth method random : float meth method round : float -> float meth method sin : float -> float meth method sqrt : float -> float meth method tan : float -> float meth end val math : math t class type error = object method name : js_string t prop method message : js_string t prop method stack : js_string t optdef prop method toString : js_string t meth end val error_constr : (js_string t -> error t) constr module Js_error : sig type error_t = error t type t val to_string : t -> string val name : t -> string val message : t -> string val stack : t -> string option val raise_ : t -> 'a val attach_js_backtrace : exn -> force:bool -> exn * Attach a JavasScript error to an OCaml exception . if [ force = false ] and a JavasScript error is already attached , it will do nothing . This function is useful to store and retrieve information about JavaScript stack traces . Attaching JavasScript errors will happen automatically when compiling with [ --enable with - js - error ] . JavasScript error is already attached, it will do nothing. This function is useful to store and retrieve information about JavaScript stack traces. Attaching JavasScript errors will happen automatically when compiling with [--enable with-js-error]. *) val of_exn : exn -> t option exception Exn of t val of_error : error_t -> t val to_error : t -> error_t end class type json = object method parse : js_string t -> 'a meth method stringify : 'a -> js_string t meth end val _JSON : json t * { 2 Standard Javascript functions } val decodeURI : js_string t -> js_string t * Decode a URI : replace by the corresponding byte all escape sequences but the ones corresponding to a URI reserved character and convert the string from UTF-8 to UTF-16 . sequences but the ones corresponding to a URI reserved character and convert the string from UTF-8 to UTF-16. *) val decodeURIComponent : js_string t -> js_string t * Decode a URIComponent : replace all escape sequences by the corresponding byte and convert the string from UTF-8 to UTF-16 . corresponding byte and convert the string from UTF-8 to UTF-16. *) val encodeURI : js_string t -> js_string t * Encode a URI : convert the string to UTF-8 and replace all unsafe bytes by the corresponding escape sequence . bytes by the corresponding escape sequence. *) val encodeURIComponent : js_string t -> js_string t * Same as [ encodeURI ] , but also encode URI reserved characters . val escape : js_string t -> js_string t * Escape a string : unsafe UTF-16 code points are replaced by 2 - digit and 4 - digit escape sequences . 2-digit and 4-digit escape sequences. *) val unescape : js_string t -> js_string t * Unescape a string : 2 - digit and 4 - digit escape sequences are replaced by the corresponding UTF-16 code point . replaced by the corresponding UTF-16 code point. *) val isNaN : 'a -> bool val parseInt : js_string t -> int val parseFloat : js_string t -> float * { 2 Conversion functions between Javascript and OCaml types } external bool : bool -> bool t = "caml_js_from_bool" external to_bool : bool t -> bool = "caml_js_to_bool" external string : string -> js_string t = "caml_jsstring_of_string" * Conversion of strings from OCaml to Javascript . ( The OCaml string is considered to be encoded in UTF-8 and is converted to UTF-16 . ) string is considered to be encoded in UTF-8 and is converted to UTF-16.) *) external to_string : js_string t -> string = "caml_string_of_jsstring" external array : 'a array -> 'a js_array t = "caml_js_from_array" external to_array : 'a js_array t -> 'a array = "caml_js_to_array" external bytestring : string -> js_string t = "caml_jsbytes_of_string" external to_bytestring : js_string t -> string = "caml_string_of_jsbytes" * Conversion of strings of bytes from Javascript to OCaml . ( The Javascript string should only contain UTF-16 code points below 255 . ) Javascript string should only contain UTF-16 code points below 255.) *) * { 2 Convenience coercion functions } val coerce : 'a -> ('a -> 'b Opt.t) -> ('a -> 'b) -> 'b val coerce_opt : 'a Opt.t -> ('a -> 'b Opt.t) -> ('a -> 'b) -> 'b * { 2 Type checking operators . } external typeof : _ t -> js_string t = "caml_js_typeof" external instanceof : _ t -> _ constr -> bool = "caml_js_instanceof" * { 2 Debugging operations . } external debugger : unit -> unit = "debugger" * Invokes any available debugging functionality . If no debugging functionality is available , it has no effect . In practice , it will insert a " debugger ; " statement in the generated javascript . If no debugging functionality is available, it has no effect. In practice, it will insert a "debugger;" statement in the generated javascript. *) val export : string -> 'a -> unit val export_all : 'a t -> unit * [ export_all obj ] export every key of [ obj ] object . { [ export_all object%js method add x y = x + . y method abs x = abs_float x val zero = 0 . end ] } {[ export_all object%js method add x y = x +. y method abs x = abs_float x val zero = 0. end ]} *) * { 2 Unsafe operations . } module Unsafe : sig type top type any = top t type any_js_array = any external inject : 'a -> any = "%identity" external coerce : _ t -> _ t = "%identity" external get : 'a -> 'b -> 'c = "caml_js_get" external set : 'a -> 'b -> 'c -> unit = "caml_js_set" external delete : 'a -> 'b -> unit = "caml_js_delete" external call : 'a -> 'b -> any array -> 'c = "caml_js_call" * Performs a Javascript function call . The expression [ call f o a ] calls the Javascript function [ f ] with the arguments given by the array [ a ] , and binding [ this ] to [ o ] . [call f o a] calls the Javascript function [f] with the arguments given by the array [a], and binding [this] to [o]. *) external fun_call : 'a -> any array -> 'b = "caml_js_fun_call" * Performs a Javascript function call . The expression [ fun_call f a ] calls the Javascript function [ f ] with the arguments given by the array [ a ] . [fun_call f a] calls the Javascript function [f] with the arguments given by the array [a]. *) external meth_call : 'a -> string -> any array -> 'b = "caml_js_meth_call" external new_obj : 'a -> any array -> 'b = "caml_js_new" * Create a Javascript object . The expression [ new_obj c a ] creates a Javascript object with constructor [ c ] using the arguments given by the array [ a ] . Example : [ ( Js.Unsafe.variable " ArrayBuffer " ) [ || ] ] creates a Javascript object with constructor [c] using the arguments given by the array [a]. Example: [Js.new_obj (Js.Unsafe.variable "ArrayBuffer") [||]] *) external new_obj_arr : 'a -> any_js_array -> 'b = "caml_ojs_new_arr" * Same Create a Javascript object . The expression [ c a ] creates a Javascript object with constructor [ c ] using the arguments given by the Javascript array [ a ] . creates a Javascript object with constructor [c] using the arguments given by the Javascript array [a]. *) external obj : (string * any) array -> 'a = "caml_js_object" external pure_expr : (unit -> 'a) -> 'a = "caml_js_pure_expr" external eval_string : string -> 'a = "caml_js_eval_string" external js_expr : string -> 'a = "caml_js_expr" * [ js_expr e ] will parse the JavaScript expression [ e ] if [ e ] is available at compile time or will fallback to a runtime evaluation . See [ eval_string ] is available at compile time or will fallback to a runtime evaluation. See [eval_string] *) external pure_js_expr : string -> 'a = "caml_pure_js_expr" * [ pure_js_expr str ] behaves like [ pure_expr ( fun ( ) - > ) ] . val global : < .. > t external callback : ('a -> 'b) -> ('c, 'a -> 'b) meth_callback = "caml_js_wrap_callback_unsafe" * Wrap an OCaml function so that it can be invoked from Javascript . Contrary to [ Js.wrap_callback ] , partial application and over - application are not supported : missing arguments will be set to [ undefined ] and extra arguments are lost . Javascript. Contrary to [Js.wrap_callback], partial application and over-application are not supported: missing arguments will be set to [undefined] and extra arguments are lost. *) external callback_with_arguments : (any_js_array -> 'b) -> ('c, any_js_array -> 'b) meth_callback = "caml_js_wrap_callback_arguments" * Wrap an OCaml function so that it can be invoked from Javascript . The first parameter of the function will be bound to the [ arguments ] JavaScript Javascript. The first parameter of the function will be bound to the [arguments] JavaScript *) external callback_with_arity : int -> ('a -> 'b) -> ('c, 'a -> 'b) meth_callback = "caml_js_wrap_callback_strict" external meth_callback : ('b -> 'a) -> ('b, 'a) meth_callback = "caml_js_wrap_meth_callback_unsafe" * Wrap an OCaml function so that it can be invoked from Javascript . The first parameter of the function will be bound to the value of the [ this ] implicit parameter . Contrary to [ Js.wrap_meth_callback ] , partial application and over - application is not supported : missing arguments will be set to [ undefined ] and extra arguments are lost . Javascript. The first parameter of the function will be bound to the value of the [this] implicit parameter. Contrary to [Js.wrap_meth_callback], partial application and over-application is not supported: missing arguments will be set to [undefined] and extra arguments are lost. *) external meth_callback_with_arguments : ('b -> any_js_array -> 'a) -> ('b, any_js_array -> 'a) meth_callback = "caml_js_wrap_meth_callback_arguments" * Wrap an OCaml function so that it can be invoked from Javascript . The first parameter of the function will be bound to the value of the [ this ] implicit parameter . The second parameter of the function with be bound to the value of the [ arguments ] . The first parameter of the function will be bound to the value of the [this] implicit parameter. The second parameter of the function with be bound to the value of the [arguments]. *) external meth_callback_with_arity : int -> ('b -> 'a) -> ('b, 'a) meth_callback = "caml_js_wrap_meth_callback_strict" * { 3 Deprecated functions . } external variable : string -> 'a = "caml_js_var" [@@ocaml.deprecated "[since 2.6] use Js.Unsafe.pure_js_expr instead"] end * { 2 Deprecated functions and types . } val string_of_error : error t -> string [@@ocaml.deprecated "[since 4.0] Use [Js_error.to_string] instead."] val raise_js_error : error t -> 'a [@@ocaml.deprecated "[since 4.0] Use [Js_error.raise_] instead."] val exn_with_js_backtrace : exn -> force:bool -> exn [@@ocaml.deprecated "[since 4.0] Use [Js_error.raise_] instead."] * Attach a JavasScript error to an OCaml exception . if [ force = false ] and a JavasScript error is already attached , it will do nothing . This function is useful to store and retrieve information about JavaScript stack traces . Attaching JavasScript errors will happen automatically when compiling with [ --enable with - js - error ] . JavasScript error is already attached, it will do nothing. This function is useful to store and retrieve information about JavaScript stack traces. Attaching JavasScript errors will happen automatically when compiling with [--enable with-js-error]. *) val js_error_of_exn : exn -> error t opt [@@ocaml.deprecated "[since 4.0] Use [Js_error.of_exn] instead."] exception Error of error t [@ocaml.deprecated "[since 4.0] Use [Js_error.Exn] instead."] external float : float -> float = "%identity" [@@ocaml.deprecated "[since 2.0]."] external to_float : float -> float = "%identity" [@@ocaml.deprecated "[since 2.0]."] type float_prop = float prop [@@ocaml.deprecated "[since 2.0]."]
589157cc63bb98f955be52192f8a38a69c3beab217125d4ec9414cd057e4360b
dysinger/hackamore
test.clj
(ns hackamore.test (:import [org.apache.camel.component.mock MockEndpoint]) (:use [clojure.test] [hackamore.core])) (declare ^:dynamic *ctx*) (defmacro ctx [r & body] `(let [c# (doto (context) (.addRoutes ~r) (.start))] (binding [*ctx* c#] ~@body) (.stop c#))) (defn snd [msg] (-> *ctx* (.createProducerTemplate) (.sendBody "direct:start" msg))) (deftest basic-route-test (ctx (route (.from "direct:start") (.to "mock:end")) (let [end (doto (.getEndpoint *ctx* "mock:end") (.expectedBodiesReceived ["hello"]))] (snd "hello") (.assertIsSatisfied end)))) (deftest content-based-router-test (letfn [(hello [ex] (= "hello" (-> ex (.getIn) (.getBody)))) (lol [ex] (= "lol" (-> ex (.getIn) (.getBody))))] (ctx (route (.from "direct:start") (.choice) (.when (pred hello)) (.to "mock:end1") (.when (pred lol)) (.to "mock:end2") (.otherwise) (.to "mock:end3")) (let [end1 (doto (.getEndpoint *ctx* "mock:end1") (.expectedBodiesReceived ["hello"])) end2 (doto (.getEndpoint *ctx* "mock:end2") (.expectedBodiesReceived ["lol"])) end3 (doto (.getEndpoint *ctx* "mock:end3") (.expectedBodiesReceivedInAnyOrder ["cheezburger" "inurserver" "lolol"]))] (doseq [msg ["cheezburger" "hello" "inurserver" "lol" "lolol"]] (snd msg)) (.assertIsSatisfied end1) (.assertIsSatisfied end2) (.assertIsSatisfied end3))))) (deftest transformer-test (ctx (route (.from "direct:start") (.transform (expr #(str (-> % (.getIn) (.getBody)) "!"))) (.to "mock:end")) (let [end (doto (.getEndpoint *ctx* "mock:end") (.expectedBodiesReceivedInAnyOrder ["hello!" "kthxbai!"]))] (doseq [msg ["hello" "kthxbai"]] (snd msg)) (.assertIsSatisfied end)))) (deftest processor-test (let [counter (atom 0)] (ctx (route (.from "direct:start") (.process (proc #(when (= "bingo!" (-> (.getIn %) (.getBody))) (swap! counter inc)))) (.to "mock:end")) (doseq [msg ["lol" "bingo!" "ohai" "bingo!" "cheezeburger"]] (snd msg)) (is (= @counter 2))))) (deftest filter-test (ctx (route (.from "direct:start") (.filter (pred #(not (= "bad" (-> % (.getIn) (.getBody)))))) (.to "mock:end")) (let [end (doto (.getEndpoint *ctx* "mock:end") (.expectedBodiesReceivedInAnyOrder ["hello" "ohai" "lol"]))] (doseq [msg ["hello" "bad" "ohai" "bad" "lol"]] (snd msg)) (.assertIsSatisfied end))))
null
https://raw.githubusercontent.com/dysinger/hackamore/e6473004d0527ffc8d11f7d9385c81c733a159d5/test/hackamore/test.clj
clojure
(ns hackamore.test (:import [org.apache.camel.component.mock MockEndpoint]) (:use [clojure.test] [hackamore.core])) (declare ^:dynamic *ctx*) (defmacro ctx [r & body] `(let [c# (doto (context) (.addRoutes ~r) (.start))] (binding [*ctx* c#] ~@body) (.stop c#))) (defn snd [msg] (-> *ctx* (.createProducerTemplate) (.sendBody "direct:start" msg))) (deftest basic-route-test (ctx (route (.from "direct:start") (.to "mock:end")) (let [end (doto (.getEndpoint *ctx* "mock:end") (.expectedBodiesReceived ["hello"]))] (snd "hello") (.assertIsSatisfied end)))) (deftest content-based-router-test (letfn [(hello [ex] (= "hello" (-> ex (.getIn) (.getBody)))) (lol [ex] (= "lol" (-> ex (.getIn) (.getBody))))] (ctx (route (.from "direct:start") (.choice) (.when (pred hello)) (.to "mock:end1") (.when (pred lol)) (.to "mock:end2") (.otherwise) (.to "mock:end3")) (let [end1 (doto (.getEndpoint *ctx* "mock:end1") (.expectedBodiesReceived ["hello"])) end2 (doto (.getEndpoint *ctx* "mock:end2") (.expectedBodiesReceived ["lol"])) end3 (doto (.getEndpoint *ctx* "mock:end3") (.expectedBodiesReceivedInAnyOrder ["cheezburger" "inurserver" "lolol"]))] (doseq [msg ["cheezburger" "hello" "inurserver" "lol" "lolol"]] (snd msg)) (.assertIsSatisfied end1) (.assertIsSatisfied end2) (.assertIsSatisfied end3))))) (deftest transformer-test (ctx (route (.from "direct:start") (.transform (expr #(str (-> % (.getIn) (.getBody)) "!"))) (.to "mock:end")) (let [end (doto (.getEndpoint *ctx* "mock:end") (.expectedBodiesReceivedInAnyOrder ["hello!" "kthxbai!"]))] (doseq [msg ["hello" "kthxbai"]] (snd msg)) (.assertIsSatisfied end)))) (deftest processor-test (let [counter (atom 0)] (ctx (route (.from "direct:start") (.process (proc #(when (= "bingo!" (-> (.getIn %) (.getBody))) (swap! counter inc)))) (.to "mock:end")) (doseq [msg ["lol" "bingo!" "ohai" "bingo!" "cheezeburger"]] (snd msg)) (is (= @counter 2))))) (deftest filter-test (ctx (route (.from "direct:start") (.filter (pred #(not (= "bad" (-> % (.getIn) (.getBody)))))) (.to "mock:end")) (let [end (doto (.getEndpoint *ctx* "mock:end") (.expectedBodiesReceivedInAnyOrder ["hello" "ohai" "lol"]))] (doseq [msg ["hello" "bad" "ohai" "bad" "lol"]] (snd msg)) (.assertIsSatisfied end))))
8476052858038d12b548b2607ab0c6428e90e2f3e39b4644c7af81aa04c8edee
walkable-server/realworld
article.clj
(ns conduit.boundary.article (:require [clojure.java.jdbc :as jdbc] [duct.database.sql])) (defprotocol Article (article-by-slug [db article]) (create-article [db article]) (destroy-article [db author-id article-slug]) (update-article [db article]) (like [db user-id article-slug]) (unlike [db user-id article-slug])) (defprotocol Comment (create-comment [db article-slug comment]) (destroy-comment [db author-id comment-id])) (extend-protocol Article duct.database.sql.Boundary (article-by-slug [{db :spec} article-slug] (:id (first (jdbc/find-by-keys db "\"article\"" {:slug article-slug})))) (create-article [{db :spec} article] (let [tags (:tags article) article (select-keys article [:author_id :title :slug :description :body]) results (jdbc/insert! db "\"article\"" article) new-article-id (-> results ffirst val)] (when (and new-article-id (seq tags)) (jdbc/insert-multi! db "\"tag\"" (mapv (fn [tag] {:article_id new-article-id :tag tag}) tags)) new-article-id))) (destroy-article [db author-id article-slug] (jdbc/delete! (:spec db) "\"article\"" ["author_id = ? AND slug = ?" author-id article-slug])) (like [db user-id article-slug] (when-let [article-id (article-by-slug db article-slug)] (jdbc/execute! (:spec db) [(str "INSERT INTO \"favorite\" (user_id, article_id)" " SELECT ?, ?" " WHERE NOT EXISTS (SELECT * FROM \"favorite\"" " WHERE user_id = ? AND article_id = ?)") user-id article-id user-id article-id]))) (unlike [db user-id article-slug] (when-let [article-id (article-by-slug db article-slug)] (jdbc/delete! (:spec db) "\"favorite\"" ["user_id = ? AND article_id = ?" user-id article-id]))) ) (extend-protocol Comment duct.database.sql.Boundary (create-comment [db article-slug comment-item] (when-let [article-id (article-by-slug db article-slug)] (let [comment-item (-> comment-item (select-keys [:author_id :body]) (assoc :article_id article-id))] (jdbc/insert! (:spec db) "\"comment\"" comment-item)))) (destroy-comment [{db :spec} author-id comment-id] (jdbc/delete! db "\"comment\"" ["author_id = ? AND id = ?" author-id comment-id])))
null
https://raw.githubusercontent.com/walkable-server/realworld/786706f15399b827e2820877ac3e2e26184ee79a/src/conduit/boundary/article.clj
clojure
(ns conduit.boundary.article (:require [clojure.java.jdbc :as jdbc] [duct.database.sql])) (defprotocol Article (article-by-slug [db article]) (create-article [db article]) (destroy-article [db author-id article-slug]) (update-article [db article]) (like [db user-id article-slug]) (unlike [db user-id article-slug])) (defprotocol Comment (create-comment [db article-slug comment]) (destroy-comment [db author-id comment-id])) (extend-protocol Article duct.database.sql.Boundary (article-by-slug [{db :spec} article-slug] (:id (first (jdbc/find-by-keys db "\"article\"" {:slug article-slug})))) (create-article [{db :spec} article] (let [tags (:tags article) article (select-keys article [:author_id :title :slug :description :body]) results (jdbc/insert! db "\"article\"" article) new-article-id (-> results ffirst val)] (when (and new-article-id (seq tags)) (jdbc/insert-multi! db "\"tag\"" (mapv (fn [tag] {:article_id new-article-id :tag tag}) tags)) new-article-id))) (destroy-article [db author-id article-slug] (jdbc/delete! (:spec db) "\"article\"" ["author_id = ? AND slug = ?" author-id article-slug])) (like [db user-id article-slug] (when-let [article-id (article-by-slug db article-slug)] (jdbc/execute! (:spec db) [(str "INSERT INTO \"favorite\" (user_id, article_id)" " SELECT ?, ?" " WHERE NOT EXISTS (SELECT * FROM \"favorite\"" " WHERE user_id = ? AND article_id = ?)") user-id article-id user-id article-id]))) (unlike [db user-id article-slug] (when-let [article-id (article-by-slug db article-slug)] (jdbc/delete! (:spec db) "\"favorite\"" ["user_id = ? AND article_id = ?" user-id article-id]))) ) (extend-protocol Comment duct.database.sql.Boundary (create-comment [db article-slug comment-item] (when-let [article-id (article-by-slug db article-slug)] (let [comment-item (-> comment-item (select-keys [:author_id :body]) (assoc :article_id article-id))] (jdbc/insert! (:spec db) "\"comment\"" comment-item)))) (destroy-comment [{db :spec} author-id comment-id] (jdbc/delete! db "\"comment\"" ["author_id = ? AND id = ?" author-id comment-id])))
3860795c47af5fc3e7242c2ffc580dd3db5bc7481de23457b9c25821cd9041f6
goldfirere/singletons
Main.hs
GradingClient.hs ( c ) 2012 This file accesses the database described in Database.hs and performs some basic queries on it . (c) Richard Eisenberg 2012 This file accesses the database described in Database.hs and performs some basic queries on it. -} module Main where import Data.List.Singletons import Data.Singletons import Data.Singletons.TH import GradingClient.Database $(singletons [d| lastName, firstName, yearName, gradeName, majorName :: [AChar] lastName = [CL, CA, CS, CT] firstName = [CF, CI, CR, CS, CT] yearName = [CY, CE, CA, CR] gradeName = [CG, CR, CA, CD, CE] majorName = [CM, CA, CJ, CO, CR] gradingSchema :: Schema gradingSchema = Sch [Attr lastName STRING, Attr firstName STRING, Attr yearName NAT, Attr gradeName NAT, Attr majorName BOOL] names :: Schema names = Sch [Attr firstName STRING, Attr lastName STRING] |]) main :: IO () main = do h <- connect "grades" sGradingSchema let ra = Read h allStudents <- query $ Project sNames ra putStrLn $ "Names of all students: " ++ (show allStudents) ++ "\n" majors <- query $ Select (Element sGradingSchema sMajorName) ra putStrLn $ "Students in major: " ++ (show majors) ++ "\n" b_students <- query $ Project sNames $ Select (LessThan (Element sGradingSchema sGradeName) (LiteralNat 90)) ra putStrLn $ "Names of students with grade < 90: " ++ (show b_students) ++ "\n"
null
https://raw.githubusercontent.com/goldfirere/singletons/a169d3f6c0c8e962ea2983f60ed74e507bca9b2b/singletons-base/tests/compile-and-dump/GradingClient/Main.hs
haskell
GradingClient.hs ( c ) 2012 This file accesses the database described in Database.hs and performs some basic queries on it . (c) Richard Eisenberg 2012 This file accesses the database described in Database.hs and performs some basic queries on it. -} module Main where import Data.List.Singletons import Data.Singletons import Data.Singletons.TH import GradingClient.Database $(singletons [d| lastName, firstName, yearName, gradeName, majorName :: [AChar] lastName = [CL, CA, CS, CT] firstName = [CF, CI, CR, CS, CT] yearName = [CY, CE, CA, CR] gradeName = [CG, CR, CA, CD, CE] majorName = [CM, CA, CJ, CO, CR] gradingSchema :: Schema gradingSchema = Sch [Attr lastName STRING, Attr firstName STRING, Attr yearName NAT, Attr gradeName NAT, Attr majorName BOOL] names :: Schema names = Sch [Attr firstName STRING, Attr lastName STRING] |]) main :: IO () main = do h <- connect "grades" sGradingSchema let ra = Read h allStudents <- query $ Project sNames ra putStrLn $ "Names of all students: " ++ (show allStudents) ++ "\n" majors <- query $ Select (Element sGradingSchema sMajorName) ra putStrLn $ "Students in major: " ++ (show majors) ++ "\n" b_students <- query $ Project sNames $ Select (LessThan (Element sGradingSchema sGradeName) (LiteralNat 90)) ra putStrLn $ "Names of students with grade < 90: " ++ (show b_students) ++ "\n"
114b8137d13d386d3068bd75c704544d9d5fe22a4f0d4cb612ff37364125307f
shayan-najd/NativeMetaprogramming
TcRun025_B.hs
# LANGUAGE ImplicitParams , TypeSynonymInstances , FlexibleInstances , ConstrainedClassMethods # -- Similar to tc024, but cross module module TcRun025_B where import Data.List( sort ) -- This class has no tyvars in its class op context -- One uses a newtype, the other a data type class C1 a where fc1 :: (?p :: String) => a; class C2 a where fc2 :: (?p :: String) => a; opc :: a instance C1 String where fc1 = ?p; instance C2 String where fc2 = ?p; opc = "x" -- This class constrains no new type variables in -- its class op context class D1 a where fd1 :: (Ord a) => [a] -> [a] class D2 a where fd2 :: (Ord a) => [a] -> [a] opd :: a instance D1 (Maybe a) where fd1 xs = sort xs instance D2 (Maybe a) where fd2 xs = sort xs opd = Nothing
null
https://raw.githubusercontent.com/shayan-najd/NativeMetaprogramming/24e5f85990642d3f0b0044be4327b8f52fce2ba3/testsuite/tests/typecheck/should_run/TcRun025_B.hs
haskell
Similar to tc024, but cross module This class has no tyvars in its class op context One uses a newtype, the other a data type This class constrains no new type variables in its class op context
# LANGUAGE ImplicitParams , TypeSynonymInstances , FlexibleInstances , ConstrainedClassMethods # module TcRun025_B where import Data.List( sort ) class C1 a where fc1 :: (?p :: String) => a; class C2 a where fc2 :: (?p :: String) => a; opc :: a instance C1 String where fc1 = ?p; instance C2 String where fc2 = ?p; opc = "x" class D1 a where fd1 :: (Ord a) => [a] -> [a] class D2 a where fd2 :: (Ord a) => [a] -> [a] opd :: a instance D1 (Maybe a) where fd1 xs = sort xs instance D2 (Maybe a) where fd2 xs = sort xs opd = Nothing
cfa6446373a9c1b58a353cb673c7f7ef483cc0109d09450e39d5fd6959cb317d
msp-strath/TypOS
Vector.hs
{-# LANGUAGE GADTs #-} module Vector where import Data.Kind data Nat = Z | S Nat infixr 5 :* data Vector (n :: Nat) (a :: Type) where V0 :: Vector Z a (:*) :: a -> Vector n a -> Vector (S n) a hd :: Vector (S n) a -> a hd (t :* _) = t instance Functor (Vector n) where fmap f V0 = V0 fmap f (x :* xs) = f x :* fmap f xs
null
https://raw.githubusercontent.com/msp-strath/TypOS/8940ec5a5d815fc87fe1b7926a94f2d99baed752/Src/Vector.hs
haskell
# LANGUAGE GADTs #
module Vector where import Data.Kind data Nat = Z | S Nat infixr 5 :* data Vector (n :: Nat) (a :: Type) where V0 :: Vector Z a (:*) :: a -> Vector n a -> Vector (S n) a hd :: Vector (S n) a -> a hd (t :* _) = t instance Functor (Vector n) where fmap f V0 = V0 fmap f (x :* xs) = f x :* fmap f xs
f90ff2db2b2260d36af567ae00a4c48c728eb36ff9e015a871391fb116ca7546
richmit/mjrcalc
use-vec.lisp
;; -*- Mode:Lisp; Syntax:ANSI-Common-LISP; Coding:us-ascii-unix; fill-column:158 -*- ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;; @file use-vec.lisp @author < > @brief Mathematical vectors.@EOL ;; @std Common Lisp ;; @see tst-vec.lisp @parblock Copyright ( c ) 1997,1998,2004,2008 - 2013,2015 , < > All rights reserved . ;; ;; Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: ;; 1 . Redistributions of source code must retain the above copyright notice , this list of conditions , and the following disclaimer . ;; 2 . Redistributions in binary form must reproduce the above copyright notice , this list of conditions , and the following disclaimer in the documentation ;; and/or other materials provided with the distribution. ;; 3 . Neither the name of the copyright holder 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 HOLDER 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. ;; @endparblock ;; @todo Bind vectors together to form a matrix.@EOL@EOL ;; @todo Coordinate conversions (rectangular, spherical, cylindrical).@EOL@EOL @todo Rotate vector.@EOL@EOL @todo Make it so that a " mathematical vector " can be a " LISP List " , but always return " LISP Vectors".@EOL@EOL ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defpackage :MJR_VEC (:USE :COMMON-LISP :MJR_CMP :MJR_EPS :MJR_CHK :MJR_UTIL :MJR_NUMU :MJR_VVEC) (:DOCUMENTATION "Brief: Mathematical vectors.;") (:EXPORT #:mjr_vec_help #:mjr_vec_every #:mjr_vec_some #:mjr_vec_every-idx #:mjr_vec_e? #:mjr_vec_make-const #:mjr_vec_make-from-func #:mjr_vec_make-seq #:mjr_vec_make-e #:mjr_vec_ewuo #:mjr_vec_ewbo #:mjr_vec_dot #:mjr_vec_triple-cross #:mjr_vec_cross #:mjr_vec_- #:mjr_vec_+ #:mjr_vec_/ #:mjr_vec_* #:mjr_vec_norm-infinity #:mjr_vec_norm-one #:mjr_vec_norm-two #:mjr_vec_norm-two-squared #:mjr_vec_zap-eps #:mjr_vec_float #:mjr_vec_rationalize #:mjr_vec_normalize #:mjr_vec_print #:mjr_vec_code #:mjr_vec_proj #:mjr_vec_orthogonalize #:mjr_vec_< )) (in-package :MJR_VEC) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_help () "Help for MJR_VEC: VECtor math This package implements various mathematical operations with numerical vectors. This library is designed primarily to support the :MJR_MAT package; however, it is also useful as an aid in hand computation with vectors. This package grows as I require new functionality, and it is far from a complete vector arithmetic package." (documentation 'mjr_vec_help 'function)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_make-const (len-or-vector &optional (constant 0)) "Create a constant vector. If missing, constant=0." (let ((len (if (vectorp len-or-vector) (length len-or-vector) len-or-vector))) (if (> 1 len) (error "mjr_vec_make-const: Invalid vector size specified!")) (make-array len :initial-element constant))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_make-from-func (func &key len start end step) "Create a vector by evaluating FUNC on an arithmetic sequence. POINTS, START, END, STEP, and LEN are processed by MJR_VVEC_KW-NORMALIZE. If LEN is a non-empty sequence (list/vector), then the length of that sequence will be used for the length." (mjr_vvec_to-vec (mjr_util_strip-nil-val-kwarg (list :map-fun func :start start :end end :step step :len len)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_make-seq (&key points start end step len) "Compute a sequence, and put the result in a vector. See the function MJR_VVEC_KW-NORMALIZE for details of how the arguments specify the sequence." (mjr_vvec_to-vec (mjr_util_strip-nil-val-kwarg (list :start start :end end :step step :points points :len len)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_dot (vec1 vec2 &optional (hermitian 't)) "Compute the dot product of the given vectors. If vectors are of different lengths, then the product will only be for the number of elements in the shortest vector." (loop for x1 across vec1 for x2 across vec2 sum (* (if hermitian (conjugate x1) x1) x2))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_cross (&rest vecs) "Compute the cross product of the given vectors. Only the first 3 elements of the vectors are used. Returns NIL if any vector is too short." (if (< 2 (length vecs)) (reduce #'mjr_vec_cross vecs) (let ((arg1 (first vecs)) (arg2 (second vecs))) (if (not (and (= 3 (length arg1)) (= 3 (length arg2)))) (error "mjr_vec_cross: Only vectors of length three are supported!")) The aref calls below will error when arg1 or are not a vector (vector (- (* (aref arg1 1) (aref arg2 2)) (* (aref arg1 2) (aref arg2 1))) (- (* (aref arg1 2) (aref arg2 0)) (* (aref arg1 0) (aref arg2 2))) (- (* (aref arg1 0) (aref arg2 1)) (* (aref arg1 1) (aref arg2 0))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_triple-cross (vec1 vec2 vec3) "Compute the triple cross product of the given vectors $(a \\cdot ( b \\times c))$. If vectors are of different lengths, then the product will only use the first three elements." (- (+ (* (aref vec1 0) (aref vec2 1) (aref vec3 2)) (* (aref vec1 1) (aref vec2 2) (aref vec3 0)) (* (aref vec1 2) (aref vec2 0) (aref vec3 1))) (* (aref vec1 0) (aref vec2 2) (aref vec3 1)) (* (aref vec1 1) (aref vec2 0) (aref vec3 2)) (* (aref vec1 2) (aref vec2 1) (aref vec3 0)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_ewuo (vec op) "Apply unary function to each element of the vector." (typecase vec (number (vector (funcall op vec))) (vector (let ((len (length vec))) (if (> len 0) (mjr_vec_make-from-func (lambda (i) (funcall op (aref vec i))) :len vec) #()))) (otherwise (error "mjr_vec_ewuo: Only vectors are supported!")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_ewbo (vec1 vec2 op) "Apply binary function to each of the elements of vec1 and vec2 in turn." (if (numberp vec1) (mjr_vec_ewbo (vector vec1) vec2 op) (if (numberp vec2) (mjr_vec_ewbo vec1 (vector vec2) op) (if (and (vectorp vec1) (vectorp vec2)) (let ((l1 (length vec1)) (l2 (length vec2))) (if (and (> l1 0) (> l2 0)) (mjr_vec_make-from-func (lambda (i) (funcall op (aref vec1 i) (aref vec2 i))) :len (min l1 l2)) #())) (error "mjr_vec_ewuo: Only vectors are supported!"))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_* (&rest vecs) "Multiply given vectors and/or scalars. vec*vec = multiply element-wise, s*vec & vec*s = multiply s by each element, s*s = multiply numbers." (if (< 2 (length vecs)) (reduce #'mjr_vec_* vecs) (let ((arg1 (first vecs)) (arg2 (second vecs))) (if arg2 (if (numberp arg1) (if (numberp arg2) (* arg1 arg2) ; Both are numbers First is number , second is vector (if (numberp arg2) Second is number , first is vector (mjr_vec_ewbo arg1 arg2 #'*))) ; Both are vectors (so we do element-wise) One argument , return it like LISP built - in ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_/ (&rest vecs) "Divide given vectors and/or scalars. If only one argument is provided, then invert it. vec/vec = divide element-wise, vec/s = divide each element by s, s/vec = divide s by each element, s/s means = divide numbers, /vec = invert the vector element-wise, /s = invert the number." (if (< 2 (length vecs)) (reduce #'mjr_vec_/ vecs) (let ((arg1 (first vecs)) (arg2 (second vecs))) (if arg2 (if (numberp arg1) (if (numberp arg2) (/ arg1 arg2) ; Both are numbers First is number , second is vector (if (numberp arg2) Second is number , first is vector (mjr_vec_ewbo arg1 arg2 #'/))) ; Both are vectors (so we do element-wise) (if (numberp arg1) One arg , a number One arg , a vector ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_- (&rest vecs) "Subtract given vectors and/or scalars. If only one argument is provided, then negate it. vec-vec = subtract element-wise, s-vec = subtract each element from s, vec-s = subtract s from each element, s-s = subtract numbers, -vec = negate the vector (element-wise), -s = negate the number." (if (< 2 (length vecs)) (reduce #'mjr_vec_- vecs) (let ((arg1 (first vecs)) (arg2 (second vecs))) (if arg2 (if (numberp arg1) (if (numberp arg2) (- arg1 arg2) ; Both are numbers First is number , second is vector (if (numberp arg2) Second is number , first is vector (mjr_vec_ewbo arg1 arg2 #'-))) ; Both are vectors (so we do element-wise) (if (numberp arg1) One arg , a number One arg , a vector ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_+ (&rest vecs) "Add given vectors and/or scalars. vec+vec = add element-wise, s+vec & vec+s = add s to each element, s+s = add numbers." (if (< 2 (length vecs)) (reduce #'mjr_vec_+ vecs) (let ((arg1 (first vecs)) (arg2 (second vecs))) (if arg2 (if (numberp arg1) (if (numberp arg2) (+ arg1 arg2) ; Both are numbers First is number , second is vector (if (numberp arg2) Second is number , first is vector (mjr_vec_ewbo arg1 arg2 #'+))) ; Both are vectors (so we do element-wise) One argument , return it like LISP built - in ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_zap-eps (vec &optional (eps 0.0001)) "Zap small values from a vec. If EPS is NIL, then *MJR_EPS_EPS* will be used. This function uses MJR_EPS_=0 to identify zero elements." (mjr_vec_ewuo vec (lambda (x) (if (mjr_eps_=0 x eps) 0 x)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_float (vec) "Convert vec elements from rational/complex rational float/complex float" (mjr_vec_ewuo vec (lambda (x) (if (complexp x) (complex (float (realpart x)) (float (imagpart x))) (if (numberp x) (float x) x))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_rationalize (vec) "Convert vec elements from float/float complex into rational/complex rational" (mjr_vec_ewuo vec (lambda (x) (if (complexp x) (complex (rationalize (realpart x)) (rationalize (imagpart x))) (if (numberp x) (rationalize x) x))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_norm-infinity (vec) "Compute the infinity-norm of the given vector" (reduce 'max (mjr_vec_ewuo vec (lambda (x) (abs x))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_norm-one (vec) "Compute the one-norm of the given vector." (let* ((nvec (mjr_vec_ewuo vec (lambda (x) (abs x)))) (nvl (length nvec))) (if (> nvl 0) (reduce '+ nvec) (error "mjr_vec_norm-one: Only non-empty vectors supported")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_norm-two (vec &optional eps0) "Compute the two-norm (standard Euclidean distance) of the given vector. If given a number, return the ABS. The EPS0 argument is used with MJR_CHK_!=0 to avoid dividing by zero. Empty vectors are length zero. This function is careful to avoid floating point overflow when possible, but pays a price in performance. Underflow is still a problem. Also note that it still gets wrong answers for some combinations of inputs ; however, it is better than the naive implementation." (if (numberp vec) (abs vec) (let ((len (length vec))) (if (>= 1 len) (if (= 1 len) Vectors of one element are easy (error "mjr_vec_norm-two: Vector must be of dimension greater than 0"))) (multiple-value-bind (maxi) ;; Find index of element with largest magnitude (mjr_vvec_map-maxi (list :end (1- len) :map-fun (lambda (i) (abs (aref vec i))))) (let ((maxv (aref vec maxi))) ;; value of largest element (if (mjr_chk_!=0 maxv eps0) ;; avoid /0 (* (abs maxv) ;; Compute length (mjr_numu_sqrt ;; Sum of the squares of the ratios (1+ (loop for x across vec for i from 0 when (not (= maxi i)) sum (expt (abs (/ x maxv)) 2))))) (mjr_numu_sqrt (loop for xi across vec It was close to the zero vector , so use easy formula ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_norm-two-squared (vec) "Compute the two-norm squared (the standard Euclidean distance squared) of the given vector." (let* ((nvec (mjr_vec_ewuo vec (lambda (x) (expt (abs x) 2)))) (nvl (length nvec))) (if (> nvl 0) (reduce '+ nvec) (error "mjr_vec_norm-two-squared: Only non-empty vectors supported")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_normalize (vec &optional norm) "Normalize the vector" (mjr_vec_/ vec (if norm (funcall norm vec) (mjr_vec_norm-two vec)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_make-e (n &key (len 3) (zero-value 0) (one-value 1)) "Make the Nth element of the LEN-dimensional standard basis." (mjr_vec_make-from-func (lambda (i) (if (= i n) one-value zero-value)) :len len)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_every (pred &rest vecs) "Just like EVERY, but works when vec is a number" (if (numberp vecs) (apply pred vecs) (apply #'every pred vecs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_some (pred &rest vecs) "Just like SOME, but works when vec is a number" (if (numberp vecs) (apply pred vecs) (apply #'some pred vecs))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_every-idx (pred vec) "Non-nil if PRED is non-nil for every index (i). Note difference from the built-in EVERY function" (let ((len (length vec))) (dotimes (i len (not nil)) (if (not (funcall pred i)) (return-from mjr_vec_every-idx nil))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_e? (vec n &optional eps) "Non-nil if the vec is the Nth element of the standard basis. This function uses MJR_CMP_= with EPS against vector elements." (if (>= (length vec) n) (mjr_vec_every-idx (lambda (i) (if (= i n) (mjr_cmp_= 1 (aref vec i) eps) (mjr_cmp_= 0 (aref vec i) eps))) vec))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_print (vector &optional fmt-str) "Print a vector. If missing, the FMT-STR will be auto-sized (right justified ~S specifier). If a VECTOR is not a vector, then it will be printed out with ~S~& regardless of what was given for FMT-STR. Returns VECTOR so that this function may be inserted inside nested function calls." (if (vectorp vector) (let ((len (length vector))) (if (not fmt-str) (setq fmt-str (concatenate 'string "~" (format nil "~d" (+ 3 (mjr_util_max-print-width vector "~s"))) "<~S~>"))) (format 't "~%") (dotimes (i len) (format 't fmt-str (aref vector i))) (format 't "~%")) (format 't "~S~&" vector)) vector) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_code (vec &key (lang :lang-matlab)) "Print out the vector using the syntax of the selected programming language or computational environment." (if (vectorp vec) (let* ((len (length vec)) (len0 (1- len)) (str "") (bams (case lang (:lang-povray (list "<" "" "" "," ">" ",")) ((:lang-maxima :lang-matlab :lang-octave :lang-idl :lang-gap :lang-gp :lang-pari :lang-pari/gp) (list "[" "" "" "," "];" ",")) (:lang-hp48 (list "[" "" "" "," "]" ",")) (:lang-mathematica (list "{" "" "" "," "};" ",")) (:lang-python (list "(" "" "" "," ");" ",")) (:lang-maple (list "vector[" "" "" "," "]);" ",")) (:lang-ruby (list "Vector[" "" "" "," "]" ",")) (:lang-r (list "c(" "" "" "," ")" ",")) (:lang-lisp (list "#1a(" "" "" " " ")" " ")) ('t (list "" "" "" " " " " " "))))) (dotimes (i len str) (setq str (concatenate 'string str (format nil "~a~a~a" (cond ((= i 0) (nth 0 bams)) ((= i len0) (nth 1 bams)) ('t (nth 2 bams))) (mjr_numu_code (aref vec i) :lang lang) (cond ((= i 0) (nth 3 bams)) ((= i len0) (nth 4 bams)) ('t (nth 5 bams)))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_proj (u v) "Compute proj_u(v) == the projection of v along u." (mjr_vec_/ (mjr_vec_* (mjr_vec_dot u v) u) (mjr_vec_norm-two-squared u))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_orthogonalize (vec-list &key (unitize nil) (method :cgs)) "Orthogonalize the set of vectors using the specified algorithm. Use :method to specify the algorithm: :cgs -- Classical Gram-Schmidt (Don't use this for floating point vectors as it is not stable....) Set :unitize to non-nil to unitize the basis (i.e. make them orthonormal)" (cond ((eq method :cgs) (loop with new-vec-list = (list (if unitize (mjr_vec_normalize (first vec-list)) (first vec-list))) for cv in (cdr vec-list) do (nconc new-vec-list (list (loop with nv = cv for j in new-vec-list do (setq nv (mjr_vec_- nv (mjr_vec_proj j cv))) finally (return (if unitize (mjr_vec_normalize nv) nv))))) finally (return new-vec-list))) ('t nil))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_vec_< (a b &key (order :lex)) "Vector orderings All of the orderings are suitable for use as monomial orderings for commutative algebra computations -- the names used are typical" (if (not (= (length a) (length b))) (error "mjr_vec_<: Vectors must be of the same length")) lex : order for bi across b when (not (= ai bi)) do (return (< ai bi)) finally (return nil))) revlex : Reverse lexicographic order for bi across b when (not (= ai bi)) do (return (> ai bi)) finally (return nil))) grlex : maximal order dominates , lex breaks ties (sb (reduce #'+ b))) (cond ((< sa sb) 't) ((= sa sb) (mjr_vec_< a b :order :lex)) ('t nil)))) grevlex : minimal order dominates , revlex breaks ties (sb (reduce #'+ b))) (cond ((> sa sb) 't) ((= sa sb) (mjr_vec_< a b :order :revlex)) ('t nil)))) ('t (error "mjr_vec_<: Unknown ordering!"))))
null
https://raw.githubusercontent.com/richmit/mjrcalc/0c5bf50a8fe3d9bc6e2636d6629138271b99c1ae/use-vec.lisp
lisp
-*- Mode:Lisp; Syntax:ANSI-Common-LISP; Coding:us-ascii-unix; fill-column:158 -*- @file use-vec.lisp @std Common Lisp @see tst-vec.lisp Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: and/or other materials provided with the distribution. without specific prior written permission. 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. @endparblock @todo Bind vectors together to form a matrix.@EOL@EOL @todo Coordinate conversions (rectangular, spherical, cylindrical).@EOL@EOL however, it is also useful as an aid in hand computation with vectors. This package grows Both are numbers Both are vectors (so we do element-wise) Both are numbers Both are vectors (so we do element-wise) Both are numbers Both are vectors (so we do element-wise) Both are numbers Both are vectors (so we do element-wise) however, it is better than the naive implementation." Find index of element with largest magnitude value of largest element avoid /0 Compute length Sum of the squares of the ratios
@author < > @brief Mathematical vectors.@EOL @parblock Copyright ( c ) 1997,1998,2004,2008 - 2013,2015 , < > All rights reserved . 1 . Redistributions of source code must retain the above copyright notice , this list of conditions , and the following disclaimer . 2 . Redistributions in binary form must reproduce the above copyright notice , this list of conditions , and the following disclaimer in the documentation 3 . Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software 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 HOLDER OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS @todo Rotate vector.@EOL@EOL @todo Make it so that a " mathematical vector " can be a " LISP List " , but always return " LISP Vectors".@EOL@EOL (defpackage :MJR_VEC (:USE :COMMON-LISP :MJR_CMP :MJR_EPS :MJR_CHK :MJR_UTIL :MJR_NUMU :MJR_VVEC) (:DOCUMENTATION "Brief: Mathematical vectors.;") (:EXPORT #:mjr_vec_help #:mjr_vec_every #:mjr_vec_some #:mjr_vec_every-idx #:mjr_vec_e? #:mjr_vec_make-const #:mjr_vec_make-from-func #:mjr_vec_make-seq #:mjr_vec_make-e #:mjr_vec_ewuo #:mjr_vec_ewbo #:mjr_vec_dot #:mjr_vec_triple-cross #:mjr_vec_cross #:mjr_vec_- #:mjr_vec_+ #:mjr_vec_/ #:mjr_vec_* #:mjr_vec_norm-infinity #:mjr_vec_norm-one #:mjr_vec_norm-two #:mjr_vec_norm-two-squared #:mjr_vec_zap-eps #:mjr_vec_float #:mjr_vec_rationalize #:mjr_vec_normalize #:mjr_vec_print #:mjr_vec_code #:mjr_vec_proj #:mjr_vec_orthogonalize #:mjr_vec_< )) (in-package :MJR_VEC) (defun mjr_vec_help () "Help for MJR_VEC: VECtor math This package implements various mathematical operations with numerical vectors. as I require new functionality, and it is far from a complete vector arithmetic package." (documentation 'mjr_vec_help 'function)) (defun mjr_vec_make-const (len-or-vector &optional (constant 0)) "Create a constant vector. If missing, constant=0." (let ((len (if (vectorp len-or-vector) (length len-or-vector) len-or-vector))) (if (> 1 len) (error "mjr_vec_make-const: Invalid vector size specified!")) (make-array len :initial-element constant))) (defun mjr_vec_make-from-func (func &key len start end step) "Create a vector by evaluating FUNC on an arithmetic sequence. POINTS, START, END, STEP, and LEN are processed by MJR_VVEC_KW-NORMALIZE. If LEN is a non-empty sequence (list/vector), then the length of that sequence will be used for the length." (mjr_vvec_to-vec (mjr_util_strip-nil-val-kwarg (list :map-fun func :start start :end end :step step :len len)))) (defun mjr_vec_make-seq (&key points start end step len) "Compute a sequence, and put the result in a vector. See the function MJR_VVEC_KW-NORMALIZE for details of how the arguments specify the sequence." (mjr_vvec_to-vec (mjr_util_strip-nil-val-kwarg (list :start start :end end :step step :points points :len len)))) (defun mjr_vec_dot (vec1 vec2 &optional (hermitian 't)) "Compute the dot product of the given vectors. If vectors are of different lengths, then the product will only be for the number of elements in the shortest vector." (loop for x1 across vec1 for x2 across vec2 sum (* (if hermitian (conjugate x1) x1) x2))) (defun mjr_vec_cross (&rest vecs) "Compute the cross product of the given vectors. Only the first 3 elements of the vectors are used. Returns NIL if any vector is too short." (if (< 2 (length vecs)) (reduce #'mjr_vec_cross vecs) (let ((arg1 (first vecs)) (arg2 (second vecs))) (if (not (and (= 3 (length arg1)) (= 3 (length arg2)))) (error "mjr_vec_cross: Only vectors of length three are supported!")) The aref calls below will error when arg1 or are not a vector (vector (- (* (aref arg1 1) (aref arg2 2)) (* (aref arg1 2) (aref arg2 1))) (- (* (aref arg1 2) (aref arg2 0)) (* (aref arg1 0) (aref arg2 2))) (- (* (aref arg1 0) (aref arg2 1)) (* (aref arg1 1) (aref arg2 0))))))) (defun mjr_vec_triple-cross (vec1 vec2 vec3) "Compute the triple cross product of the given vectors $(a \\cdot ( b \\times c))$. If vectors are of different lengths, then the product will only use the first three elements." (- (+ (* (aref vec1 0) (aref vec2 1) (aref vec3 2)) (* (aref vec1 1) (aref vec2 2) (aref vec3 0)) (* (aref vec1 2) (aref vec2 0) (aref vec3 1))) (* (aref vec1 0) (aref vec2 2) (aref vec3 1)) (* (aref vec1 1) (aref vec2 0) (aref vec3 2)) (* (aref vec1 2) (aref vec2 1) (aref vec3 0)))) (defun mjr_vec_ewuo (vec op) "Apply unary function to each element of the vector." (typecase vec (number (vector (funcall op vec))) (vector (let ((len (length vec))) (if (> len 0) (mjr_vec_make-from-func (lambda (i) (funcall op (aref vec i))) :len vec) #()))) (otherwise (error "mjr_vec_ewuo: Only vectors are supported!")))) (defun mjr_vec_ewbo (vec1 vec2 op) "Apply binary function to each of the elements of vec1 and vec2 in turn." (if (numberp vec1) (mjr_vec_ewbo (vector vec1) vec2 op) (if (numberp vec2) (mjr_vec_ewbo vec1 (vector vec2) op) (if (and (vectorp vec1) (vectorp vec2)) (let ((l1 (length vec1)) (l2 (length vec2))) (if (and (> l1 0) (> l2 0)) (mjr_vec_make-from-func (lambda (i) (funcall op (aref vec1 i) (aref vec2 i))) :len (min l1 l2)) #())) (error "mjr_vec_ewuo: Only vectors are supported!"))))) (defun mjr_vec_* (&rest vecs) "Multiply given vectors and/or scalars. vec*vec = multiply element-wise, s*vec & vec*s = multiply s by each element, s*s = multiply numbers." (if (< 2 (length vecs)) (reduce #'mjr_vec_* vecs) (let ((arg1 (first vecs)) (arg2 (second vecs))) (if arg2 (if (numberp arg1) (if (numberp arg2) First is number , second is vector (if (numberp arg2) Second is number , first is vector One argument , return it like LISP built - in (defun mjr_vec_/ (&rest vecs) "Divide given vectors and/or scalars. If only one argument is provided, then invert it. vec/vec = divide element-wise, vec/s = divide each element by s, s/vec = divide s by each element, s/s means = divide numbers, /vec = invert the vector element-wise, /s = invert the number." (if (< 2 (length vecs)) (reduce #'mjr_vec_/ vecs) (let ((arg1 (first vecs)) (arg2 (second vecs))) (if arg2 (if (numberp arg1) (if (numberp arg2) First is number , second is vector (if (numberp arg2) Second is number , first is vector (if (numberp arg1) One arg , a number One arg , a vector (defun mjr_vec_- (&rest vecs) "Subtract given vectors and/or scalars. If only one argument is provided, then negate it. vec-vec = subtract element-wise, s-vec = subtract each element from s, vec-s = subtract s from each element, s-s = subtract numbers, -vec = negate the vector (element-wise), -s = negate the number." (if (< 2 (length vecs)) (reduce #'mjr_vec_- vecs) (let ((arg1 (first vecs)) (arg2 (second vecs))) (if arg2 (if (numberp arg1) (if (numberp arg2) First is number , second is vector (if (numberp arg2) Second is number , first is vector (if (numberp arg1) One arg , a number One arg , a vector (defun mjr_vec_+ (&rest vecs) "Add given vectors and/or scalars. vec+vec = add element-wise, s+vec & vec+s = add s to each element, s+s = add numbers." (if (< 2 (length vecs)) (reduce #'mjr_vec_+ vecs) (let ((arg1 (first vecs)) (arg2 (second vecs))) (if arg2 (if (numberp arg1) (if (numberp arg2) First is number , second is vector (if (numberp arg2) Second is number , first is vector One argument , return it like LISP built - in (defun mjr_vec_zap-eps (vec &optional (eps 0.0001)) "Zap small values from a vec. If EPS is NIL, then *MJR_EPS_EPS* will be used. This function uses MJR_EPS_=0 to identify zero elements." (mjr_vec_ewuo vec (lambda (x) (if (mjr_eps_=0 x eps) 0 x)))) (defun mjr_vec_float (vec) "Convert vec elements from rational/complex rational float/complex float" (mjr_vec_ewuo vec (lambda (x) (if (complexp x) (complex (float (realpart x)) (float (imagpart x))) (if (numberp x) (float x) x))))) (defun mjr_vec_rationalize (vec) "Convert vec elements from float/float complex into rational/complex rational" (mjr_vec_ewuo vec (lambda (x) (if (complexp x) (complex (rationalize (realpart x)) (rationalize (imagpart x))) (if (numberp x) (rationalize x) x))))) (defun mjr_vec_norm-infinity (vec) "Compute the infinity-norm of the given vector" (reduce 'max (mjr_vec_ewuo vec (lambda (x) (abs x))))) (defun mjr_vec_norm-one (vec) "Compute the one-norm of the given vector." (let* ((nvec (mjr_vec_ewuo vec (lambda (x) (abs x)))) (nvl (length nvec))) (if (> nvl 0) (reduce '+ nvec) (error "mjr_vec_norm-one: Only non-empty vectors supported")))) (defun mjr_vec_norm-two (vec &optional eps0) "Compute the two-norm (standard Euclidean distance) of the given vector. If given a number, return the ABS. The EPS0 argument is used with MJR_CHK_!=0 to avoid dividing by zero. Empty vectors are length zero. This function is careful to avoid floating point overflow when possible, but pays a price in performance. Underflow is still a problem. Also note that it (if (numberp vec) (abs vec) (let ((len (length vec))) (if (>= 1 len) (if (= 1 len) Vectors of one element are easy (error "mjr_vec_norm-two: Vector must be of dimension greater than 0"))) (mjr_vvec_map-maxi (list :end (1- len) :map-fun (lambda (i) (abs (aref vec i))))) (1+ (loop for x across vec for i from 0 when (not (= maxi i)) sum (expt (abs (/ x maxv)) 2))))) (mjr_numu_sqrt (loop for xi across vec It was close to the zero vector , so use easy formula (defun mjr_vec_norm-two-squared (vec) "Compute the two-norm squared (the standard Euclidean distance squared) of the given vector." (let* ((nvec (mjr_vec_ewuo vec (lambda (x) (expt (abs x) 2)))) (nvl (length nvec))) (if (> nvl 0) (reduce '+ nvec) (error "mjr_vec_norm-two-squared: Only non-empty vectors supported")))) (defun mjr_vec_normalize (vec &optional norm) "Normalize the vector" (mjr_vec_/ vec (if norm (funcall norm vec) (mjr_vec_norm-two vec)))) (defun mjr_vec_make-e (n &key (len 3) (zero-value 0) (one-value 1)) "Make the Nth element of the LEN-dimensional standard basis." (mjr_vec_make-from-func (lambda (i) (if (= i n) one-value zero-value)) :len len)) (defun mjr_vec_every (pred &rest vecs) "Just like EVERY, but works when vec is a number" (if (numberp vecs) (apply pred vecs) (apply #'every pred vecs))) (defun mjr_vec_some (pred &rest vecs) "Just like SOME, but works when vec is a number" (if (numberp vecs) (apply pred vecs) (apply #'some pred vecs))) (defun mjr_vec_every-idx (pred vec) "Non-nil if PRED is non-nil for every index (i). Note difference from the built-in EVERY function" (let ((len (length vec))) (dotimes (i len (not nil)) (if (not (funcall pred i)) (return-from mjr_vec_every-idx nil))))) (defun mjr_vec_e? (vec n &optional eps) "Non-nil if the vec is the Nth element of the standard basis. This function uses MJR_CMP_= with EPS against vector elements." (if (>= (length vec) n) (mjr_vec_every-idx (lambda (i) (if (= i n) (mjr_cmp_= 1 (aref vec i) eps) (mjr_cmp_= 0 (aref vec i) eps))) vec))) (defun mjr_vec_print (vector &optional fmt-str) "Print a vector. If missing, the FMT-STR will be auto-sized (right justified ~S specifier). If a VECTOR is not a vector, then it will be printed out with ~S~& regardless of what was given for FMT-STR. Returns VECTOR so that this function may be inserted inside nested function calls." (if (vectorp vector) (let ((len (length vector))) (if (not fmt-str) (setq fmt-str (concatenate 'string "~" (format nil "~d" (+ 3 (mjr_util_max-print-width vector "~s"))) "<~S~>"))) (format 't "~%") (dotimes (i len) (format 't fmt-str (aref vector i))) (format 't "~%")) (format 't "~S~&" vector)) vector) (defun mjr_vec_code (vec &key (lang :lang-matlab)) "Print out the vector using the syntax of the selected programming language or computational environment." (if (vectorp vec) (let* ((len (length vec)) (len0 (1- len)) (str "") (bams (case lang (:lang-povray (list "<" "" "" "," ">" ",")) ((:lang-maxima :lang-matlab :lang-octave :lang-idl :lang-gap :lang-gp :lang-pari :lang-pari/gp) (list "[" "" "" "," "];" ",")) (:lang-hp48 (list "[" "" "" "," "]" ",")) (:lang-mathematica (list "{" "" "" "," "};" ",")) (:lang-python (list "(" "" "" "," ");" ",")) (:lang-maple (list "vector[" "" "" "," "]);" ",")) (:lang-ruby (list "Vector[" "" "" "," "]" ",")) (:lang-r (list "c(" "" "" "," ")" ",")) (:lang-lisp (list "#1a(" "" "" " " ")" " ")) ('t (list "" "" "" " " " " " "))))) (dotimes (i len str) (setq str (concatenate 'string str (format nil "~a~a~a" (cond ((= i 0) (nth 0 bams)) ((= i len0) (nth 1 bams)) ('t (nth 2 bams))) (mjr_numu_code (aref vec i) :lang lang) (cond ((= i 0) (nth 3 bams)) ((= i len0) (nth 4 bams)) ('t (nth 5 bams)))))))))) (defun mjr_vec_proj (u v) "Compute proj_u(v) == the projection of v along u." (mjr_vec_/ (mjr_vec_* (mjr_vec_dot u v) u) (mjr_vec_norm-two-squared u))) (defun mjr_vec_orthogonalize (vec-list &key (unitize nil) (method :cgs)) "Orthogonalize the set of vectors using the specified algorithm. Use :method to specify the algorithm: :cgs -- Classical Gram-Schmidt (Don't use this for floating point vectors as it is not stable....) Set :unitize to non-nil to unitize the basis (i.e. make them orthonormal)" (cond ((eq method :cgs) (loop with new-vec-list = (list (if unitize (mjr_vec_normalize (first vec-list)) (first vec-list))) for cv in (cdr vec-list) do (nconc new-vec-list (list (loop with nv = cv for j in new-vec-list do (setq nv (mjr_vec_- nv (mjr_vec_proj j cv))) finally (return (if unitize (mjr_vec_normalize nv) nv))))) finally (return new-vec-list))) ('t nil))) (defun mjr_vec_< (a b &key (order :lex)) "Vector orderings All of the orderings are suitable for use as monomial orderings for commutative algebra computations -- the names used are typical" (if (not (= (length a) (length b))) (error "mjr_vec_<: Vectors must be of the same length")) lex : order for bi across b when (not (= ai bi)) do (return (< ai bi)) finally (return nil))) revlex : Reverse lexicographic order for bi across b when (not (= ai bi)) do (return (> ai bi)) finally (return nil))) grlex : maximal order dominates , lex breaks ties (sb (reduce #'+ b))) (cond ((< sa sb) 't) ((= sa sb) (mjr_vec_< a b :order :lex)) ('t nil)))) grevlex : minimal order dominates , revlex breaks ties (sb (reduce #'+ b))) (cond ((> sa sb) 't) ((= sa sb) (mjr_vec_< a b :order :revlex)) ('t nil)))) ('t (error "mjr_vec_<: Unknown ordering!"))))
a9c8c90ddb2e0daa36e002ebf20775cd7742b0256b86bb78c21d714272aa1b04
racket/rhombus-prototype
provide.rkt
#lang racket/base (require (for-syntax racket/base syntax/parse/pre racket/provide-transform)) (provide for-spaces) (define-syntax for-spaces (make-provide-pre-transformer (lambda (stx space+phases) (syntax-parse stx [(_ (space ...) out ...) #`(combine-out (for-space space out ...) ...)]))))
null
https://raw.githubusercontent.com/racket/rhombus-prototype/4e66c1361bdde51c2df9332644800baead49e86f/rhombus/private/provide.rkt
racket
#lang racket/base (require (for-syntax racket/base syntax/parse/pre racket/provide-transform)) (provide for-spaces) (define-syntax for-spaces (make-provide-pre-transformer (lambda (stx space+phases) (syntax-parse stx [(_ (space ...) out ...) #`(combine-out (for-space space out ...) ...)]))))
bb5acbb1c8d49367a2962f83d62bb81ee4d358aefb3b351d9da910375abc2359
swift-nav/labsat
Parser.hs
# LANGUAGE NoImplicitPrelude # {-# LANGUAGE OverloadedStrings #-} module Test.Labsat.Parser ( tests ) where import Data.Attoparsec.ByteString import Data.ByteString import Labsat.Parser import Labsat.Types import Preamble import Test.Tasty import Test.Tasty.HUnit parser :: (Eq a, Show a) => Parser a -> ByteString -> Either String a -> Assertion parser p s r = parseOnly p s @?= r -------------------------------------------------------------------------------- -- HELP Parsers -------------------------------------------------------------------------------- helpOutput :: ByteString helpOutput = "Current commands are : \r\r\n\r\r\nHELP\r\r\nTYPE\r\r\nFIND\r\r\nMON\r\r\nPLAY\r\r\nREC\r\r\nATTN\r\r\nCONF\r\r\nMEDIA\r\r\nMUTE\r\r\n\r\r\n\r\r\nLABSAT_V3 >" helpResult :: HelpCommands helpResult = HelpCommands ["HELP","TYPE","FIND","MON","PLAY","REC","ATTN","CONF","MEDIA","MUTE"] testHelp :: TestTree testHelp = testGroup "Test help parser" [ testCase "Help without colors" $ parser parseHelp helpOutput $ Right helpResult ] -------------------------------------------------------------------------------- -- MEDIA Parsers -------------------------------------------------------------------------------- mediaListOutput :: ByteString mediaListOutput = "ABC \ESC[40G 00:00:00\r\r\nASDF\r\r\nFile_001 \ESC[40G 00:05:40\r\r\nFile_002 \ESC[40G 00:21:17\r\r\nLabSat 3 Wideband Demo SSD files\r\r\n\r\r\nLABSAT_V3 >" mediaListResult :: MediaList mediaListResult = MediaList [File "ABC" "00:00:00",Dir "ASDF",File "File_001" "00:05:40",File "File_002" "00:21:17",Dir "LabSat 3 Wideband Demo SSD files"] testMedia :: TestTree testMedia = testGroup "Test media parsers" [ testCase "Media list" $ parser parseMediaList mediaListOutput $ Right mediaListResult ] -------------------------------------------------------------------------------- PLAY Parsers -------------------------------------------------------------------------------- playFileOutput :: ByteString playFileOutput = "File_001\r\r\n\r\r\nLABSAT_V3 >" statusPlayingOutput :: ByteString statusPlayingOutput = "PLAY:/mnt/sata/File_001:DUR:00:00:20\r\r\n\r\r\nLABSAT_V3 >" statusPlayingResult :: PlayStatus statusPlayingResult = Playing "File_001" "00:00:20" statusIdleOutput :: ByteString statusIdleOutput = "PLAY:IDLE\r\r\n\r\r\nLABSAT_V3 >" testPlay :: TestTree testPlay = testGroup "Test play parsers" [ testCase "Play file" $ parser (parsePlay "File_001") playFileOutput $ Right "File_001" , testCase "Status playing" $ parser parsePlayStatus statusPlayingOutput $ Right statusPlayingResult , testCase "Status idle" $ parser parsePlayStatus statusIdleOutput $ Right PlayIdle ] -------------------------------------------------------------------------------- REC Parsers -------------------------------------------------------------------------------- statusRecordingOutput :: ByteString statusRecordingOutput = "REC:/mnt/sata/File_004:DUR:00:00:08\r\r\n\r\r\nLABSAT_V3 >" statusRecordingResult :: RecordStatus statusRecordingResult = Recording "File_004" "00:00:08" statusRecordIdleOutput :: ByteString statusRecordIdleOutput = "REC:IDLE\r\r\n\r\r\nLABSAT_V3 >" testRecord :: TestTree testRecord = testGroup "Test record parsers" [ testCase "Recordfile" $ parser parseRec playFileOutput $ Right "File_001" , testCase "Status playing" $ parser parseRecordStatus statusRecordingOutput $ Right statusRecordingResult , testCase "Status idle" $ parser parseRecordStatus statusRecordIdleOutput $ Right RecordIdle ] -------------------------------------------------------------------------------- TYPE -------------------------------------------------------------------------------- typeOutput :: ByteString typeOutput = "Labsat Wideband\r\nSerial 57082 \r\nFirmware 1.0.260\r\nFPGA 33\r\nIP 10.1.22.44\r\nBattery not connected\r\nTCXO-0x7b7f\r\n\r\r\n\r\r\nLABSAT_V3 >" typeResult :: Info typeResult = Info ["Labsat Wideband","Serial 57082 ","Firmware 1.0.260","FPGA 33","IP 10.1.22.44","Battery not connected","TCXO-0x7b7f"] testType :: TestTree testType = testGroup "Test type parser" [ testCase "Type command" $ parser parseInfo typeOutput $ Right typeResult ] -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- monSatOutput :: ByteString monSatOutput = "GPS 9\r\r\n05,42,07,52,08,43,09,52,16,35,23,47,27,43,28,42,30,49\r\r\n\r\r\nGLO 10\r\r\n01,50,02,52,03,36,08,37,10,36,11,50,12,50,13,32,20,31,21,40\r\r\n\r\r\nBDS 0\r\r\n\r\r\nGAL 4\r\r\n01,44,04,42,19,44,20,36\r\r\n\r\r\nLABSAT_V3 >" monSatResult :: [ConstellationCNO] monSatResult = [ConstellationCNO GPS "9" [SatelliteCNO "05" "42",SatelliteCNO "07" "52",SatelliteCNO "08" "43",SatelliteCNO "09" "52",SatelliteCNO "16" "35",SatelliteCNO "23" "47",SatelliteCNO "27" "43",SatelliteCNO "28" "42",SatelliteCNO "30" "49"],ConstellationCNO GLO "10" [SatelliteCNO "01" "50",SatelliteCNO "02" "52",SatelliteCNO "03" "36",SatelliteCNO "08" "37",SatelliteCNO "10" "36",SatelliteCNO "11" "50",SatelliteCNO "12" "50",SatelliteCNO "13" "32",SatelliteCNO "20" "31",SatelliteCNO "21" "40"],ConstellationCNO BDS "0" [],ConstellationCNO GAL "4" [SatelliteCNO "01" "44",SatelliteCNO "04" "42",SatelliteCNO "19" "44",SatelliteCNO "20" "36"]] monLocOutput :: ByteString monLocOutput = "123456.00,-5.800000,M,1234.12345,N,54321.54321,W\r\r\n\r\r\nLABSAT_V3 >" monLocResult :: Location monLocResult = Location {_time = 123456.0, _height = (-5.8,"M"), _lattitude = (1234.12345,"N"), _longitude = (54321.54321,"W")} testMon :: TestTree testMon = testGroup "Test MON parsers" [ testCase "Test MON:SAT" $ parser parseMonSat monSatOutput $ Right monSatResult , testCase "Test MON:LOC" $ parser parseMonLoc monLocOutput $ Right monLocResult ] -------------------------------------------------------------------------------- ATTN Parsers -------------------------------------------------------------------------------- attnOutput1 :: ByteString attnOutput1 = "OK:ATTN:CH1:0 \r\r\nOK:ATTN:CH2:0 \r\r\nOK:ATTN:CH3:0 \r\r\nOK\r\r\n\r\r\nLABSAT_V3 >" attnOutput2 :: ByteString attnOutput2 = "OK:ATTN:CH1:10 \r\r\nOK:ATTN:CH3:10 \r\r\nOK\r\r\n\r\r\nLABSAT_V3 >" attnResult1 :: AttnConf attnResult1 = AttnConf {_acAttnAll = Nothing, _acAttnCh1 = Just 0, _acAttnCh2 = Just 0, _acAttnCh3 = Just 0} attnResult2 :: AttnConf attnResult2 = AttnConf {_acAttnAll = Nothing, _acAttnCh1 = Just 10, _acAttnCh2 = Nothing, _acAttnCh3 = Just 10} testAttn :: TestTree testAttn = testGroup "Test ATTN parsers" [ testCase "Test ATTN:0" $ parser parseAttn attnOutput1 $ Right attnResult1 , testCase "Test ATTN:CH1:10:CH3:10" $ parser parseAttn attnOutput2 $ Right attnResult2 ] -------------------------------------------------------------------------------- CONF Parsers -------------------------------------------------------------------------------- canBaudOutput :: ByteString canBaudOutput = "baud value is 500000.000000 \r\r\nOK\r\r\n\r\r\nLABSAT_V3 >" canBaudResult :: Double canBaudResult = 500000.0 consFreqOutput :: ByteString consFreqOutput = "TELNET_CONF \r\r\n QUA-1, BW-10, Available ch(1) 1575420000, 1207140014, 1268520019 \r\r\nOK\r\r\n\r\r\nLABSAT_V3 >" consFreqResult :: ConstellationFreqConf consFreqResult = ConstellationFreqConf { _cfcQuantization = QUA1, _cfcBandwidth = BW_10, _cfcFrequencies = [1.57542e9,1.207140014e9,1.268520019e9]} testConf :: TestTree testConf = testGroup "Test CONF parsers" [ testCase "Test CONF:SETUP:CAN:CH1:BAUD:500000" $ parser parseCANBaud canBaudOutput $ Right canBaudResult , testCase "Test CONF:CONS:QUA:1:BW:10:FREQ:1575420000" $ parser parseConsFreq consFreqOutput $ Right consFreqResult ] tests :: TestTree tests = testGroup "LabSat parser tests" [ testHelp , testMedia , testPlay , testRecord , testType , testMon , testAttn , testConf ]
null
https://raw.githubusercontent.com/swift-nav/labsat/58ec344fffa6e06c27d30bc3f753103e312040ee/test/Test/Labsat/Parser.hs
haskell
# LANGUAGE OverloadedStrings # ------------------------------------------------------------------------------ HELP Parsers ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ MEDIA Parsers ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------
# LANGUAGE NoImplicitPrelude # module Test.Labsat.Parser ( tests ) where import Data.Attoparsec.ByteString import Data.ByteString import Labsat.Parser import Labsat.Types import Preamble import Test.Tasty import Test.Tasty.HUnit parser :: (Eq a, Show a) => Parser a -> ByteString -> Either String a -> Assertion parser p s r = parseOnly p s @?= r helpOutput :: ByteString helpOutput = "Current commands are : \r\r\n\r\r\nHELP\r\r\nTYPE\r\r\nFIND\r\r\nMON\r\r\nPLAY\r\r\nREC\r\r\nATTN\r\r\nCONF\r\r\nMEDIA\r\r\nMUTE\r\r\n\r\r\n\r\r\nLABSAT_V3 >" helpResult :: HelpCommands helpResult = HelpCommands ["HELP","TYPE","FIND","MON","PLAY","REC","ATTN","CONF","MEDIA","MUTE"] testHelp :: TestTree testHelp = testGroup "Test help parser" [ testCase "Help without colors" $ parser parseHelp helpOutput $ Right helpResult ] mediaListOutput :: ByteString mediaListOutput = "ABC \ESC[40G 00:00:00\r\r\nASDF\r\r\nFile_001 \ESC[40G 00:05:40\r\r\nFile_002 \ESC[40G 00:21:17\r\r\nLabSat 3 Wideband Demo SSD files\r\r\n\r\r\nLABSAT_V3 >" mediaListResult :: MediaList mediaListResult = MediaList [File "ABC" "00:00:00",Dir "ASDF",File "File_001" "00:05:40",File "File_002" "00:21:17",Dir "LabSat 3 Wideband Demo SSD files"] testMedia :: TestTree testMedia = testGroup "Test media parsers" [ testCase "Media list" $ parser parseMediaList mediaListOutput $ Right mediaListResult ] PLAY Parsers playFileOutput :: ByteString playFileOutput = "File_001\r\r\n\r\r\nLABSAT_V3 >" statusPlayingOutput :: ByteString statusPlayingOutput = "PLAY:/mnt/sata/File_001:DUR:00:00:20\r\r\n\r\r\nLABSAT_V3 >" statusPlayingResult :: PlayStatus statusPlayingResult = Playing "File_001" "00:00:20" statusIdleOutput :: ByteString statusIdleOutput = "PLAY:IDLE\r\r\n\r\r\nLABSAT_V3 >" testPlay :: TestTree testPlay = testGroup "Test play parsers" [ testCase "Play file" $ parser (parsePlay "File_001") playFileOutput $ Right "File_001" , testCase "Status playing" $ parser parsePlayStatus statusPlayingOutput $ Right statusPlayingResult , testCase "Status idle" $ parser parsePlayStatus statusIdleOutput $ Right PlayIdle ] REC Parsers statusRecordingOutput :: ByteString statusRecordingOutput = "REC:/mnt/sata/File_004:DUR:00:00:08\r\r\n\r\r\nLABSAT_V3 >" statusRecordingResult :: RecordStatus statusRecordingResult = Recording "File_004" "00:00:08" statusRecordIdleOutput :: ByteString statusRecordIdleOutput = "REC:IDLE\r\r\n\r\r\nLABSAT_V3 >" testRecord :: TestTree testRecord = testGroup "Test record parsers" [ testCase "Recordfile" $ parser parseRec playFileOutput $ Right "File_001" , testCase "Status playing" $ parser parseRecordStatus statusRecordingOutput $ Right statusRecordingResult , testCase "Status idle" $ parser parseRecordStatus statusRecordIdleOutput $ Right RecordIdle ] TYPE typeOutput :: ByteString typeOutput = "Labsat Wideband\r\nSerial 57082 \r\nFirmware 1.0.260\r\nFPGA 33\r\nIP 10.1.22.44\r\nBattery not connected\r\nTCXO-0x7b7f\r\n\r\r\n\r\r\nLABSAT_V3 >" typeResult :: Info typeResult = Info ["Labsat Wideband","Serial 57082 ","Firmware 1.0.260","FPGA 33","IP 10.1.22.44","Battery not connected","TCXO-0x7b7f"] testType :: TestTree testType = testGroup "Test type parser" [ testCase "Type command" $ parser parseInfo typeOutput $ Right typeResult ] monSatOutput :: ByteString monSatOutput = "GPS 9\r\r\n05,42,07,52,08,43,09,52,16,35,23,47,27,43,28,42,30,49\r\r\n\r\r\nGLO 10\r\r\n01,50,02,52,03,36,08,37,10,36,11,50,12,50,13,32,20,31,21,40\r\r\n\r\r\nBDS 0\r\r\n\r\r\nGAL 4\r\r\n01,44,04,42,19,44,20,36\r\r\n\r\r\nLABSAT_V3 >" monSatResult :: [ConstellationCNO] monSatResult = [ConstellationCNO GPS "9" [SatelliteCNO "05" "42",SatelliteCNO "07" "52",SatelliteCNO "08" "43",SatelliteCNO "09" "52",SatelliteCNO "16" "35",SatelliteCNO "23" "47",SatelliteCNO "27" "43",SatelliteCNO "28" "42",SatelliteCNO "30" "49"],ConstellationCNO GLO "10" [SatelliteCNO "01" "50",SatelliteCNO "02" "52",SatelliteCNO "03" "36",SatelliteCNO "08" "37",SatelliteCNO "10" "36",SatelliteCNO "11" "50",SatelliteCNO "12" "50",SatelliteCNO "13" "32",SatelliteCNO "20" "31",SatelliteCNO "21" "40"],ConstellationCNO BDS "0" [],ConstellationCNO GAL "4" [SatelliteCNO "01" "44",SatelliteCNO "04" "42",SatelliteCNO "19" "44",SatelliteCNO "20" "36"]] monLocOutput :: ByteString monLocOutput = "123456.00,-5.800000,M,1234.12345,N,54321.54321,W\r\r\n\r\r\nLABSAT_V3 >" monLocResult :: Location monLocResult = Location {_time = 123456.0, _height = (-5.8,"M"), _lattitude = (1234.12345,"N"), _longitude = (54321.54321,"W")} testMon :: TestTree testMon = testGroup "Test MON parsers" [ testCase "Test MON:SAT" $ parser parseMonSat monSatOutput $ Right monSatResult , testCase "Test MON:LOC" $ parser parseMonLoc monLocOutput $ Right monLocResult ] ATTN Parsers attnOutput1 :: ByteString attnOutput1 = "OK:ATTN:CH1:0 \r\r\nOK:ATTN:CH2:0 \r\r\nOK:ATTN:CH3:0 \r\r\nOK\r\r\n\r\r\nLABSAT_V3 >" attnOutput2 :: ByteString attnOutput2 = "OK:ATTN:CH1:10 \r\r\nOK:ATTN:CH3:10 \r\r\nOK\r\r\n\r\r\nLABSAT_V3 >" attnResult1 :: AttnConf attnResult1 = AttnConf {_acAttnAll = Nothing, _acAttnCh1 = Just 0, _acAttnCh2 = Just 0, _acAttnCh3 = Just 0} attnResult2 :: AttnConf attnResult2 = AttnConf {_acAttnAll = Nothing, _acAttnCh1 = Just 10, _acAttnCh2 = Nothing, _acAttnCh3 = Just 10} testAttn :: TestTree testAttn = testGroup "Test ATTN parsers" [ testCase "Test ATTN:0" $ parser parseAttn attnOutput1 $ Right attnResult1 , testCase "Test ATTN:CH1:10:CH3:10" $ parser parseAttn attnOutput2 $ Right attnResult2 ] CONF Parsers canBaudOutput :: ByteString canBaudOutput = "baud value is 500000.000000 \r\r\nOK\r\r\n\r\r\nLABSAT_V3 >" canBaudResult :: Double canBaudResult = 500000.0 consFreqOutput :: ByteString consFreqOutput = "TELNET_CONF \r\r\n QUA-1, BW-10, Available ch(1) 1575420000, 1207140014, 1268520019 \r\r\nOK\r\r\n\r\r\nLABSAT_V3 >" consFreqResult :: ConstellationFreqConf consFreqResult = ConstellationFreqConf { _cfcQuantization = QUA1, _cfcBandwidth = BW_10, _cfcFrequencies = [1.57542e9,1.207140014e9,1.268520019e9]} testConf :: TestTree testConf = testGroup "Test CONF parsers" [ testCase "Test CONF:SETUP:CAN:CH1:BAUD:500000" $ parser parseCANBaud canBaudOutput $ Right canBaudResult , testCase "Test CONF:CONS:QUA:1:BW:10:FREQ:1575420000" $ parser parseConsFreq consFreqOutput $ Right consFreqResult ] tests :: TestTree tests = testGroup "LabSat parser tests" [ testHelp , testMedia , testPlay , testRecord , testType , testMon , testAttn , testConf ]
ddde65c463c1e26a13fa6a635e50de1648317c8c036a90ffa2888cc23750e4e9
c-cube/stimsym
Builtins.mli
(* This file is free software. See file "license" for more details. *) (** {1 Builtin Functions} *) type t = Expr.t (** A builtin is just a constant expression *) exception Eval_does_not_apply (** Raised internally when an evaluation function does not apply to the arguments *) * a function definition . Takes [ self_cst , eval_fun , t ] and evaluates [ t ] into [ None ] ( fail ) or [ Some t ' ] into [None] (fail) or [Some t'] *) type fun_def = Expr.const -> Expr.prim_fun_args -> Expr.t -> Expr.t option val make : ?doc:Document.t -> ?printer:int * Expr.const_printer -> ?display:Expr.mime_printer -> ?fields:Expr.Properties.field list -> ?funs:fun_def list -> ?rules:(Expr.const -> t * t) list -> string -> t (** [make s] makes a new constant and sets some options/handlers on it *) val const_is_builtin : Expr.const -> bool val hold : t val full_form : t val blank : t val blank_seq : t val blank_null_seq : t val sequence : t val pattern : t val pattern_test : t val same_q : t val assign : t val assign_delayed : t val rule : t val rule_delayed : t val condition : t val replace_all : t val replace_repeated : t val alternatives : t val compound_expr : t val head : t val length : t (* number of immediate arguments *) val slot : t val function_ : t val true_ : t val false_ : t val if_ : t val match_ : t val match_l : t val matches : t val and_ : t val or_ : t val not_ : t val plus : t val times : t val div : t val mod_ : t val max : t val min : t val factorial : t val power : t val list : t val set : t val union : t val inter : t val random : t val floor : t val ceil : t val match_bind : t val match_bind1 : t val comprehension : t val let_ : t val fixpoint : t val clear : t val set_attributes : t val remove_attributes : t val get_attributes : t val clear_attributes : t val equal : t val not_equal : t val less : t val greater : t val less_equal : t val greater_equal : t val inequality : t val integer_q : t val rational_q : t val true_q : t val trace : t val print : t val null : t val doc : t val nest : t val range_seq : t val range : t val all_builtins : unit -> t list val complete_symbol : string -> t list (** Completion of the given identifier prefix using builtins *) (**/**) val log_: (string->unit) ref val log : string -> unit val logf : ('a, unit, string, unit) format4 -> 'a (**/**)
null
https://raw.githubusercontent.com/c-cube/stimsym/38c744b5f770b52980abbfe7636a0dc2b91bbeb7/src/core/Builtins.mli
ocaml
This file is free software. See file "license" for more details. * {1 Builtin Functions} * A builtin is just a constant expression * Raised internally when an evaluation function does not apply to the arguments * [make s] makes a new constant and sets some options/handlers on it number of immediate arguments * Completion of the given identifier prefix using builtins */* */*
type t = Expr.t exception Eval_does_not_apply * a function definition . Takes [ self_cst , eval_fun , t ] and evaluates [ t ] into [ None ] ( fail ) or [ Some t ' ] into [None] (fail) or [Some t'] *) type fun_def = Expr.const -> Expr.prim_fun_args -> Expr.t -> Expr.t option val make : ?doc:Document.t -> ?printer:int * Expr.const_printer -> ?display:Expr.mime_printer -> ?fields:Expr.Properties.field list -> ?funs:fun_def list -> ?rules:(Expr.const -> t * t) list -> string -> t val const_is_builtin : Expr.const -> bool val hold : t val full_form : t val blank : t val blank_seq : t val blank_null_seq : t val sequence : t val pattern : t val pattern_test : t val same_q : t val assign : t val assign_delayed : t val rule : t val rule_delayed : t val condition : t val replace_all : t val replace_repeated : t val alternatives : t val compound_expr : t val head : t val slot : t val function_ : t val true_ : t val false_ : t val if_ : t val match_ : t val match_l : t val matches : t val and_ : t val or_ : t val not_ : t val plus : t val times : t val div : t val mod_ : t val max : t val min : t val factorial : t val power : t val list : t val set : t val union : t val inter : t val random : t val floor : t val ceil : t val match_bind : t val match_bind1 : t val comprehension : t val let_ : t val fixpoint : t val clear : t val set_attributes : t val remove_attributes : t val get_attributes : t val clear_attributes : t val equal : t val not_equal : t val less : t val greater : t val less_equal : t val greater_equal : t val inequality : t val integer_q : t val rational_q : t val true_q : t val trace : t val print : t val null : t val doc : t val nest : t val range_seq : t val range : t val all_builtins : unit -> t list val complete_symbol : string -> t list val log_: (string->unit) ref val log : string -> unit val logf : ('a, unit, string, unit) format4 -> 'a
792894760ad766ad4f45dc82e8114a2d86b30fada4cc1a67409c93c5767a6aed
robindar/compil-petitrust
x86_64.mli
* { 0 Bibliothèque pour l'écriture de programmes X86 - 64 } Il s'agit là uniquement d'un fragment relativement petit de l'assembleur X86 - 64 . @author ( CNRS ) @author ( Université Paris Sud ) Il s'agit là uniquement d'un fragment relativement petit de l'assembleur X86-64. @author Jean-Christophe Filliâtre (CNRS) @author Kim Nguyen (Université Paris Sud) *) * { 1 Code } type 'a asm * type abstrait du code assembleur . [ ' a ] est utilisé comme type fantôme . Le paramètre ['a] est utilisé comme type fantôme. *) type text = [ `text ] asm (** du code assembleur se trouvant dans la zone de texte *) type data = [ `data ] asm (** du code assembleur se trouvant dans la zone de données *) type label = string (** les étiquettes d'addresses sont des chaînes de caractères *) val nop : [> ] asm * l'instruction vide . Peut se trouver dans du text ou du data val ( ++ ) : ([< `text|`data ] asm as 'a)-> 'a -> 'a * ( soit text avec text , soit data avec data ) data) *) val inline: string -> [> ] asm * [ inline s ] recopie la chaîne [ s ] telle quelle dans assembleur assembleur *) type program = { text : text; data : data; } * un programme est constitué d'une zone de texte et d'une zone de données val print_program : Format.formatter -> program -> unit (** [print_program fmt p] imprime le code du programme [p] dans le formatter [fmt] *) val print_in_file: file:string -> program -> unit (** {1 Registres } *) type size = [`B | `W | `L | `Q] type 'size register (** type abstrait des registres *) val rax: [`Q] register val rbx: [`Q] register val rcx: [`Q] register val rdx: [`Q] register val rsi: [`Q] register val rdi: [`Q] register val rbp: [`Q] register val rsp: [`Q] register val r8 : [`Q] register val r9 : [`Q] register val r10: [`Q] register val r11: [`Q] register val r12: [`Q] register val r13: [`Q] register val r14: [`Q] register val r15: [`Q] register * registres 64 bits val eax: [`L] register val ebx: [`L] register val ecx: [`L] register val edx: [`L] register val esi: [`L] register val edi: [`L] register val ebp: [`L] register val esp: [`L] register val r8d: [`L] register val r9d: [`L] register val r10d: [`L] register val r11d: [`L] register val r12d: [`L] register val r13d: [`L] register val r14d: [`L] register val r15d: [`L] register * registres 32 bits val ax: [`W] register val bx: [`W] register val cx: [`W] register val dx: [`W] register val si: [`W] register val di: [`W] register val bp: [`W] register val sp: [`W] register val r8w: [`W] register val r9w: [`W] register val r10w: [`W] register val r11w: [`W] register val r12w: [`W] register val r13w: [`W] register val r14w: [`W] register val r15w: [`W] register * registres 16 bits val al: [`B] register val bl: [`B] register val cl: [`B] register val dl: [`B] register val ah: [`B] register val bh: [`B] register val ch: [`B] register val dh: [`B] register val sil: [`B] register val dil: [`B] register val bpl: [`B] register val spl: [`B] register val r8b: [`B] register val r9b: [`B] register val r10b: [`B] register val r11b: [`B] register val r12b: [`B] register val r13b: [`B] register val r14b: [`B] register val r15b: [`B] register * registres 8 bits (** {1 Opérandes } *) type 'size operand (** Le type abstrait des opérandes *) val imm: int -> [>] operand (** opérande immédiate $i *) val imm32: int32 -> [>] operand (** opérande immédiate $i *) val reg: 'size register -> 'size operand (** registre *) val ind: ?ofs:int -> ?index:'size1 register -> ?scale:int -> 'size2 register -> [>] operand (** opérande indirecte ofs(register, index, scale) *) val lab: label -> [>] operand (** étiquette L *) val ilab: label -> [`Q] operand (** étiquette immédiate $L *) (** {1 Instructions } *) * { 2 } val movb: [`B] operand -> [`B] operand -> text val movw: [`W] operand -> [`W] operand -> text val movl: [`L] operand -> [`L] operand -> text val movq: [`Q] operand -> [`Q] operand -> text (** attention : toutes les combinaisons d'opérandes ne sont pas permises *) val movsbw: [`B] operand -> [`W] register -> text val movsbl: [`B] operand -> [`L] register -> text val movsbq: [`B] operand -> [`Q] register -> text val movswl: [`W] operand -> [`L] register -> text val movswq: [`W] operand -> [`Q] register -> text val movslq: [`L] operand -> [`Q] register -> text * 8->64 bit , avec extension de signe val movzbw: [`B] operand -> [`W] register -> text val movzbl: [`B] operand -> [`L] register -> text val movzbq: [`B] operand -> [`Q] register -> text val movzwl: [`W] operand -> [`L] register -> text val movzwq: [`W] operand -> [`Q] register -> text * 8->64 bit , avec extension par zéro val movabsq: int64 -> [`Q] register -> text * copie une valeur immédiate 64 bits dans un registre * { 2 Arithmétique } val leab: [`B] operand -> [`B] register -> text val leaw: [`W] operand -> [`W] register -> text val leal: [`L] operand -> [`L] register -> text val leaq: [`Q] operand -> [`Q] register -> text val incb: [`B] operand -> text val incw: [`W] operand -> text val incl: [`L] operand -> text val incq: [`Q] operand -> text val decb: [`B] operand -> text val decw: [`W] operand -> text val decl: [`L] operand -> text val decq: [`Q] operand -> text val negb: [`B] operand -> text val negw: [`W] operand -> text val negl: [`L] operand -> text val negq: [`Q] operand -> text val addb: [`B] operand -> [`B] operand -> text val addw: [`W] operand -> [`W] operand -> text val addl: [`L] operand -> [`L] operand -> text val addq: [`Q] operand -> [`Q] operand -> text val subb: [`B] operand -> [`B] operand -> text val subw: [`W] operand -> [`W] operand -> text val subl: [`L] operand -> [`L] operand -> text val subq: [`Q] operand -> [`Q] operand -> text val imulw: [`W] operand -> [`W] operand -> text val imull: [`L] operand -> [`L] operand -> text val imulq: [`Q] operand -> [`Q] operand -> text val idivq: [`Q] operand -> text val cqto: text * { 2 Opérations logiques } val notb: [`B] operand -> text val notw: [`W] operand -> text val notl: [`L] operand -> text val notq: [`Q] operand -> text val andb: [`B] operand -> [`B] operand -> text val andw: [`W] operand -> [`W] operand -> text val andl: [`L] operand -> [`L] operand -> text val andq: [`Q] operand -> [`Q] operand -> text val orb : [`B] operand -> [`B] operand -> text val orw : [`W] operand -> [`W] operand -> text val orl : [`L] operand -> [`L] operand -> text val orq : [`Q] operand -> [`Q] operand -> text val xorb: [`B] operand -> [`B] operand -> text val xorw: [`W] operand -> [`W] operand -> text val xorl: [`L] operand -> [`L] operand -> text val xorq: [`Q] operand -> [`Q] operand -> text (** Opérations de manipulation de bits. "et" bit à bit, "ou" bit à bit, "not" bit à bit *) (** {2 Décalages } *) val shlb: [`B] operand -> [`B] operand -> text val shlw: [`W] operand -> [`W] operand -> text val shll: [`L] operand -> [`L] operand -> text val shlq: [`Q] operand -> [`Q] operand -> text * note : shl est la même chose que sal val shrb: [`B] operand -> [`B] operand -> text val shrw: [`W] operand -> [`W] operand -> text val shrl: [`L] operand -> [`L] operand -> text val shrq: [`Q] operand -> [`Q] operand -> text val sarb: [`B] operand -> [`B] operand -> text val sarw: [`W] operand -> [`W] operand -> text val sarl: [`L] operand -> [`L] operand -> text val sarq: [`Q] operand -> [`Q] operand -> text (** {2 Sauts } *) val call: label -> text val call_star: [`Q] operand -> text val leave: text val ret: text (** appel de fonction et retour *) val jmp : label -> text * val jmp_star: [`Q] operand -> text (** saut à une adresse calculée *) = 0 = 0 < > 0 < > 0 < 0 > = 0 val jg : label -> text (* > signé *) val jge: label -> text (* >= signé *) val jl : label -> text (* < signé *) val jle: label -> text (* <= signé *) val ja : label -> text (* > non signé *) val jae: label -> text (* >= non signé *) val jb : label -> text (* < non signé *) val jbe: label -> text (* <= non signé *) (** sauts conditionnels *) * { 2 Conditions } val cmpb: [`B] operand -> [`B] operand -> text val cmpw: [`W] operand -> [`W] operand -> text val cmpl: [`L] operand -> [`L] operand -> text val cmpq: [`Q] operand -> [`Q] operand -> text val testb: [`B] operand -> [`B] operand -> text val testw: [`W] operand -> [`W] operand -> text val testl: [`L] operand -> [`L] operand -> text val testq: [`Q] operand -> [`Q] operand -> text = 0 < > 0 < 0 > = 0 val setg : [`B] operand -> text (* > signé *) val setge: [`B] operand -> text (* >= signé *) val setl : [`B] operand -> text (* < signé *) val setle: [`B] operand -> text (* <= signé *) val seta : [`B] operand -> text (* > non signé *) val setae: [`B] operand -> text (* >= non signé *) val setb : [`B] operand -> text (* < non signé *) val setbe: [`B] operand -> text (* <= non signé *) * opérande à 1 ou 0 selon que le test est vrai ou non * { 2 Manipulation de la pile } val pushq : [`Q] operand -> text * [ pushq r ] place [ r ] au sommet de la pile . : % rsp pointe sur l'adresse de la dernière case occupée Rappel : %rsp pointe sur l'adresse de la dernière case occupée *) val popq : [`Q] register -> text (** [popq r] place le mot en sommet de pile dans [r] et dépile *) (** {2 Divers } *) val label : label -> [> ] asm * un label . retrouver dans du text ou du data val globl : label -> [> ] asm (** déclaration .globl (pour main, typiquement) *) val comment : string -> [> ] asm * place . retrouver dans du text ou du data du text ou du data *) * { 2 Données } val string : string -> data * une constante chaîne de caractères ( terminée par 0 ) val dbyte : int list -> data val dword : int list -> data val dint : int list -> data val dquad : int list -> data * place une liste de valeurs sur 1/2/4/8 octets dans la zone data val address: label list -> data * place une liste d'adresses dans la zone data ( avec .quad ) val space: int -> data (** [space n] alloue [n] octets (valant 0) dans le segment de données *)
null
https://raw.githubusercontent.com/robindar/compil-petitrust/c28ae0df678860613f630b8e09bffabd7aa02c0e/x86_64.mli
ocaml
* du code assembleur se trouvant dans la zone de texte * du code assembleur se trouvant dans la zone de données * les étiquettes d'addresses sont des chaînes de caractères * [print_program fmt p] imprime le code du programme [p] dans le formatter [fmt] * {1 Registres } * type abstrait des registres * {1 Opérandes } * Le type abstrait des opérandes * opérande immédiate $i * opérande immédiate $i * registre * opérande indirecte ofs(register, index, scale) * étiquette L * étiquette immédiate $L * {1 Instructions } * attention : toutes les combinaisons d'opérandes ne sont pas permises * Opérations de manipulation de bits. "et" bit à bit, "ou" bit à bit, "not" bit à bit * {2 Décalages } * {2 Sauts } * appel de fonction et retour * saut à une adresse calculée > signé >= signé < signé <= signé > non signé >= non signé < non signé <= non signé * sauts conditionnels > signé >= signé < signé <= signé > non signé >= non signé < non signé <= non signé * [popq r] place le mot en sommet de pile dans [r] et dépile * {2 Divers } * déclaration .globl (pour main, typiquement) * [space n] alloue [n] octets (valant 0) dans le segment de données
* { 0 Bibliothèque pour l'écriture de programmes X86 - 64 } Il s'agit là uniquement d'un fragment relativement petit de l'assembleur X86 - 64 . @author ( CNRS ) @author ( Université Paris Sud ) Il s'agit là uniquement d'un fragment relativement petit de l'assembleur X86-64. @author Jean-Christophe Filliâtre (CNRS) @author Kim Nguyen (Université Paris Sud) *) * { 1 Code } type 'a asm * type abstrait du code assembleur . [ ' a ] est utilisé comme type fantôme . Le paramètre ['a] est utilisé comme type fantôme. *) type text = [ `text ] asm type data = [ `data ] asm type label = string val nop : [> ] asm * l'instruction vide . Peut se trouver dans du text ou du data val ( ++ ) : ([< `text|`data ] asm as 'a)-> 'a -> 'a * ( soit text avec text , soit data avec data ) data) *) val inline: string -> [> ] asm * [ inline s ] recopie la chaîne [ s ] telle quelle dans assembleur assembleur *) type program = { text : text; data : data; } * un programme est constitué d'une zone de texte et d'une zone de données val print_program : Format.formatter -> program -> unit val print_in_file: file:string -> program -> unit type size = [`B | `W | `L | `Q] type 'size register val rax: [`Q] register val rbx: [`Q] register val rcx: [`Q] register val rdx: [`Q] register val rsi: [`Q] register val rdi: [`Q] register val rbp: [`Q] register val rsp: [`Q] register val r8 : [`Q] register val r9 : [`Q] register val r10: [`Q] register val r11: [`Q] register val r12: [`Q] register val r13: [`Q] register val r14: [`Q] register val r15: [`Q] register * registres 64 bits val eax: [`L] register val ebx: [`L] register val ecx: [`L] register val edx: [`L] register val esi: [`L] register val edi: [`L] register val ebp: [`L] register val esp: [`L] register val r8d: [`L] register val r9d: [`L] register val r10d: [`L] register val r11d: [`L] register val r12d: [`L] register val r13d: [`L] register val r14d: [`L] register val r15d: [`L] register * registres 32 bits val ax: [`W] register val bx: [`W] register val cx: [`W] register val dx: [`W] register val si: [`W] register val di: [`W] register val bp: [`W] register val sp: [`W] register val r8w: [`W] register val r9w: [`W] register val r10w: [`W] register val r11w: [`W] register val r12w: [`W] register val r13w: [`W] register val r14w: [`W] register val r15w: [`W] register * registres 16 bits val al: [`B] register val bl: [`B] register val cl: [`B] register val dl: [`B] register val ah: [`B] register val bh: [`B] register val ch: [`B] register val dh: [`B] register val sil: [`B] register val dil: [`B] register val bpl: [`B] register val spl: [`B] register val r8b: [`B] register val r9b: [`B] register val r10b: [`B] register val r11b: [`B] register val r12b: [`B] register val r13b: [`B] register val r14b: [`B] register val r15b: [`B] register * registres 8 bits type 'size operand val imm: int -> [>] operand val imm32: int32 -> [>] operand val reg: 'size register -> 'size operand val ind: ?ofs:int -> ?index:'size1 register -> ?scale:int -> 'size2 register -> [>] operand val lab: label -> [>] operand val ilab: label -> [`Q] operand * { 2 } val movb: [`B] operand -> [`B] operand -> text val movw: [`W] operand -> [`W] operand -> text val movl: [`L] operand -> [`L] operand -> text val movq: [`Q] operand -> [`Q] operand -> text val movsbw: [`B] operand -> [`W] register -> text val movsbl: [`B] operand -> [`L] register -> text val movsbq: [`B] operand -> [`Q] register -> text val movswl: [`W] operand -> [`L] register -> text val movswq: [`W] operand -> [`Q] register -> text val movslq: [`L] operand -> [`Q] register -> text * 8->64 bit , avec extension de signe val movzbw: [`B] operand -> [`W] register -> text val movzbl: [`B] operand -> [`L] register -> text val movzbq: [`B] operand -> [`Q] register -> text val movzwl: [`W] operand -> [`L] register -> text val movzwq: [`W] operand -> [`Q] register -> text * 8->64 bit , avec extension par zéro val movabsq: int64 -> [`Q] register -> text * copie une valeur immédiate 64 bits dans un registre * { 2 Arithmétique } val leab: [`B] operand -> [`B] register -> text val leaw: [`W] operand -> [`W] register -> text val leal: [`L] operand -> [`L] register -> text val leaq: [`Q] operand -> [`Q] register -> text val incb: [`B] operand -> text val incw: [`W] operand -> text val incl: [`L] operand -> text val incq: [`Q] operand -> text val decb: [`B] operand -> text val decw: [`W] operand -> text val decl: [`L] operand -> text val decq: [`Q] operand -> text val negb: [`B] operand -> text val negw: [`W] operand -> text val negl: [`L] operand -> text val negq: [`Q] operand -> text val addb: [`B] operand -> [`B] operand -> text val addw: [`W] operand -> [`W] operand -> text val addl: [`L] operand -> [`L] operand -> text val addq: [`Q] operand -> [`Q] operand -> text val subb: [`B] operand -> [`B] operand -> text val subw: [`W] operand -> [`W] operand -> text val subl: [`L] operand -> [`L] operand -> text val subq: [`Q] operand -> [`Q] operand -> text val imulw: [`W] operand -> [`W] operand -> text val imull: [`L] operand -> [`L] operand -> text val imulq: [`Q] operand -> [`Q] operand -> text val idivq: [`Q] operand -> text val cqto: text * { 2 Opérations logiques } val notb: [`B] operand -> text val notw: [`W] operand -> text val notl: [`L] operand -> text val notq: [`Q] operand -> text val andb: [`B] operand -> [`B] operand -> text val andw: [`W] operand -> [`W] operand -> text val andl: [`L] operand -> [`L] operand -> text val andq: [`Q] operand -> [`Q] operand -> text val orb : [`B] operand -> [`B] operand -> text val orw : [`W] operand -> [`W] operand -> text val orl : [`L] operand -> [`L] operand -> text val orq : [`Q] operand -> [`Q] operand -> text val xorb: [`B] operand -> [`B] operand -> text val xorw: [`W] operand -> [`W] operand -> text val xorl: [`L] operand -> [`L] operand -> text val xorq: [`Q] operand -> [`Q] operand -> text val shlb: [`B] operand -> [`B] operand -> text val shlw: [`W] operand -> [`W] operand -> text val shll: [`L] operand -> [`L] operand -> text val shlq: [`Q] operand -> [`Q] operand -> text * note : shl est la même chose que sal val shrb: [`B] operand -> [`B] operand -> text val shrw: [`W] operand -> [`W] operand -> text val shrl: [`L] operand -> [`L] operand -> text val shrq: [`Q] operand -> [`Q] operand -> text val sarb: [`B] operand -> [`B] operand -> text val sarw: [`W] operand -> [`W] operand -> text val sarl: [`L] operand -> [`L] operand -> text val sarq: [`Q] operand -> [`Q] operand -> text val call: label -> text val call_star: [`Q] operand -> text val leave: text val ret: text val jmp : label -> text * val jmp_star: [`Q] operand -> text = 0 = 0 < > 0 < > 0 < 0 > = 0 * { 2 Conditions } val cmpb: [`B] operand -> [`B] operand -> text val cmpw: [`W] operand -> [`W] operand -> text val cmpl: [`L] operand -> [`L] operand -> text val cmpq: [`Q] operand -> [`Q] operand -> text val testb: [`B] operand -> [`B] operand -> text val testw: [`W] operand -> [`W] operand -> text val testl: [`L] operand -> [`L] operand -> text val testq: [`Q] operand -> [`Q] operand -> text = 0 < > 0 < 0 > = 0 * opérande à 1 ou 0 selon que le test est vrai ou non * { 2 Manipulation de la pile } val pushq : [`Q] operand -> text * [ pushq r ] place [ r ] au sommet de la pile . : % rsp pointe sur l'adresse de la dernière case occupée Rappel : %rsp pointe sur l'adresse de la dernière case occupée *) val popq : [`Q] register -> text val label : label -> [> ] asm * un label . retrouver dans du text ou du data val globl : label -> [> ] asm val comment : string -> [> ] asm * place . retrouver dans du text ou du data du text ou du data *) * { 2 Données } val string : string -> data * une constante chaîne de caractères ( terminée par 0 ) val dbyte : int list -> data val dword : int list -> data val dint : int list -> data val dquad : int list -> data * place une liste de valeurs sur 1/2/4/8 octets dans la zone data val address: label list -> data * place une liste d'adresses dans la zone data ( avec .quad ) val space: int -> data
7e241d11cef4ce2b47928b73d283f08a795d6440ea45dc2ebf33b8a085ba852b
dizengrong/erlang_game
npc_dict.erl
@author dzR < > @doc npc的字典数据模块 -module (npc_dict). -include("map.hrl"). -include("npc.hrl"). -export([init/1, next_npc_id/0]). -export([set_npc_rec/1, get_npc_rec/1]). -export([get_all_npc_id_list/0, set_all_npc_id_list/1]). init(_MapState) -> erlang:put(current_max_npc_uid, 1), set_all_npc_id_list([]), ok. %% @doc 获取当前一个可用的最大的npc id,并递增current_max_npc_uid next_npc_id() -> NpcId = erlang:get(current_max_npc_uid), erlang:put(current_max_npc_uid, 1 + NpcId), NpcId. %% @doc 操作#r_npc{}的接口 get_npc_rec(NpcId) -> erlang:get({npc, NpcId}). set_npc_rec(NpcRec) -> erlang:put({npc, NpcRec#r_npc.id}, NpcRec), ok. @doc 操作所有npc_id列表的接口 get_all_npc_id_list() -> erlang:get(npc_id_list). set_all_npc_id_list(NpcIdList) -> erlang:put(npc_id_list, NpcIdList), ok.
null
https://raw.githubusercontent.com/dizengrong/erlang_game/4598f97daa9ca5eecff292ac401dd8f903eea867/gerl/src/map_srv/npc_dict.erl
erlang
@doc 获取当前一个可用的最大的npc id,并递增current_max_npc_uid @doc 操作#r_npc{}的接口
@author dzR < > @doc npc的字典数据模块 -module (npc_dict). -include("map.hrl"). -include("npc.hrl"). -export([init/1, next_npc_id/0]). -export([set_npc_rec/1, get_npc_rec/1]). -export([get_all_npc_id_list/0, set_all_npc_id_list/1]). init(_MapState) -> erlang:put(current_max_npc_uid, 1), set_all_npc_id_list([]), ok. next_npc_id() -> NpcId = erlang:get(current_max_npc_uid), erlang:put(current_max_npc_uid, 1 + NpcId), NpcId. get_npc_rec(NpcId) -> erlang:get({npc, NpcId}). set_npc_rec(NpcRec) -> erlang:put({npc, NpcRec#r_npc.id}, NpcRec), ok. @doc 操作所有npc_id列表的接口 get_all_npc_id_list() -> erlang:get(npc_id_list). set_all_npc_id_list(NpcIdList) -> erlang:put(npc_id_list, NpcIdList), ok.
e5f2a7016a74b19d5531a78d9d7418c5dc6930308b356eea425a135050a50c64
bos/rwh
divby2m.hs
{-- snippet all --} ch20 / divby2m.hs divBy :: Integral a => a -> [a] -> Maybe [a] divBy numerator denominators = mapM (numerator `safeDiv`) denominators where safeDiv _ 0 = Nothing safeDiv x y = x `div` y {-- /snippet all --}
null
https://raw.githubusercontent.com/bos/rwh/7fd1e467d54aef832f5476ebf5f4f6a898a895d1/examples/ch20/divby2m.hs
haskell
- snippet all - - /snippet all -
ch20 / divby2m.hs divBy :: Integral a => a -> [a] -> Maybe [a] divBy numerator denominators = mapM (numerator `safeDiv`) denominators where safeDiv _ 0 = Nothing safeDiv x y = x `div` y
e273107c644f7f67e7f01da12505f5a9565e1c26b0450c07624219923a4c85ef
embecosm/cgen
guile.scm
; Guile-specific functions. Copyright ( C ) 2000 , 2004 , 2009 Red Hat , Inc. This file is part of CGEN . ; See file COPYING.CGEN for details. (define *guile-major-version* (string->number (major-version))) (define *guile-minor-version* (string->number (minor-version))) eval takes a module argument in 1.6 and later (if (or (> *guile-major-version* 1) (>= *guile-minor-version* 6)) (define (eval1 expr) (eval expr (current-module))) (define (eval1 expr) (eval expr)) ) symbol - bound ? is deprecated in 1.6 (if (or (> *guile-major-version* 1) (>= *guile-minor-version* 6)) (define (symbol-bound? table s) (if table (error "must pass #f for symbol-bound? first arg")) FIXME : Not sure this is 100 % correct . (module-defined? (current-module) s)) ) (if (symbol-bound? #f 'load-from-path) (begin (define (load file) (begin ;(load-from-path file) (primitive-load-path file) )) ) ) ; FIXME: to be deleted (define =? =) (define >=? >=) (if (not (symbol-bound? #f '%stat)) (begin (define %stat stat) ) ) (if (symbol-bound? #f 'debug-enable) (debug-enable 'backtrace) ) Guile 1.3 has reverse ! , 1.2 has list - reverse ! . CGEN uses reverse ! (if (and (not (symbol-bound? #f 'reverse!)) (symbol-bound? #f 'list-reverse!)) (define reverse! list-reverse!) ) (define (debug-write . objs) (map (lambda (o) ((if (string? o) display write) o (current-error-port))) objs) (newline (current-error-port))) ;; Guile 1.8 no longer has "." in %load-path so relative path loads ;; no longer work. (if (or (> *guile-major-version* 1) (>= *guile-minor-version* 8)) (set! %load-path (append %load-path (list "."))) ) ;;; Enabling and disabling debugging features of the host Scheme. ;;; For the initial load proces, turn everything on. We'll disable it ;;; before we start doing the heavy computation. (if (memq 'debug-extensions *features*) (begin (debug-enable 'backtrace) (debug-enable 'debug) (debug-enable 'backwards) (debug-set! depth 2000) (debug-set! maxdepth 2000) (debug-set! stack 100000) (debug-set! frames 10))) (read-enable 'positions) ;;; Call THUNK, with debugging enabled if FLAG is true, or disabled if ;;; FLAG is false. ;;; ( On systems other than , this need n't actually do anything at all , beyond calling THUNK , so long as your backtraces are still helpful . In , the debugging evaluator is slower , so we do n't ;;; want to use it unless the user asked for it.) (define (cgen-call-with-debugging flag thunk) (if (memq 'debug-extensions *features*) ((if flag debug-enable debug-disable) 'debug)) ;; Now, make that debugging / no-debugging setting actually take ;; effect. ;; has two separate evaluators , one that does the extra ;; bookkeeping for backtraces, and one which doesn't, but runs ;; faster. However, the evaluation process (in either evaluator) ;; ordinarily never consults the variable that says which evaluator ;; to use: whatever evaluator was running just keeps rolling along. ;; There are certain primitives, like some of the eval variants, ;; that do actually check. start-stack is one such primitive, but ;; we don't want to shadow whatever other stack id is there, so we ;; do all the real work in the ID argument, and do nothing in the EXP argument . What a kludge . (start-stack (begin (thunk) #t) #f)) ;;; Apply PROC to ARGS, marking that application as the bottom of the ;;; stack for error backtraces. ;;; ( On systems other than , this does n't really need to do ;;; anything other than apply PROC to ARGS, as long as something ;;; ensures that backtraces will work right.) (define (cgen-debugging-stack-start proc args) ;; Naming this procedure, rather than using an anonymous lambda, ;; allows us to pass less fragile cut info to save-stack. (define (handler . args) ;;(display args (current-error-port)) ;;(newline (current-error-port)) display - error takes 6 arguments . If ` quit ' is called from elsewhere , it may not have 6 ;; arguments. Not sure how best to handle this. (if (= (length args) 5) (begin (apply display-error #f (current-error-port) (cdr args)) ;; Grab a copy of the current stack, (save-stack handler 0) (backtrace))) (quit 1)) ;; Apply proc to args, and if any uncaught exception is thrown, call handler WITHOUT UNWINDING THE STACK ( that 's the ' lazy ' part ) . We ;; need the stack left alone so we can produce a backtrace. (lazy-catch #t (lambda () ;; I have no idea why the 'load-stack' stack mark is ;; not still present on the stack; we're still loading ;; cgen-APP.scm, aren't we? But stack-id returns #f ;; in handler if we don't do a start-stack here. (start-stack proc (apply proc args))) handler))
null
https://raw.githubusercontent.com/embecosm/cgen/3fa8809c015376cd0e80018a655d372df3678bc6/cgen/guile.scm
scheme
Guile-specific functions. See file COPYING.CGEN for details. (load-from-path file) FIXME: to be deleted Guile 1.8 no longer has "." in %load-path so relative path loads no longer work. Enabling and disabling debugging features of the host Scheme. For the initial load proces, turn everything on. We'll disable it before we start doing the heavy computation. Call THUNK, with debugging enabled if FLAG is true, or disabled if FLAG is false. want to use it unless the user asked for it.) Now, make that debugging / no-debugging setting actually take effect. bookkeeping for backtraces, and one which doesn't, but runs faster. However, the evaluation process (in either evaluator) ordinarily never consults the variable that says which evaluator to use: whatever evaluator was running just keeps rolling along. There are certain primitives, like some of the eval variants, that do actually check. start-stack is one such primitive, but we don't want to shadow whatever other stack id is there, so we do all the real work in the ID argument, and do nothing in the Apply PROC to ARGS, marking that application as the bottom of the stack for error backtraces. anything other than apply PROC to ARGS, as long as something ensures that backtraces will work right.) Naming this procedure, rather than using an anonymous lambda, allows us to pass less fragile cut info to save-stack. (display args (current-error-port)) (newline (current-error-port)) arguments. Not sure how best to handle this. Grab a copy of the current stack, Apply proc to args, and if any uncaught exception is thrown, call need the stack left alone so we can produce a backtrace. I have no idea why the 'load-stack' stack mark is not still present on the stack; we're still loading cgen-APP.scm, aren't we? But stack-id returns #f in handler if we don't do a start-stack here.
Copyright ( C ) 2000 , 2004 , 2009 Red Hat , Inc. This file is part of CGEN . (define *guile-major-version* (string->number (major-version))) (define *guile-minor-version* (string->number (minor-version))) eval takes a module argument in 1.6 and later (if (or (> *guile-major-version* 1) (>= *guile-minor-version* 6)) (define (eval1 expr) (eval expr (current-module))) (define (eval1 expr) (eval expr)) ) symbol - bound ? is deprecated in 1.6 (if (or (> *guile-major-version* 1) (>= *guile-minor-version* 6)) (define (symbol-bound? table s) (if table (error "must pass #f for symbol-bound? first arg")) FIXME : Not sure this is 100 % correct . (module-defined? (current-module) s)) ) (if (symbol-bound? #f 'load-from-path) (begin (define (load file) (begin (primitive-load-path file) )) ) ) (define =? =) (define >=? >=) (if (not (symbol-bound? #f '%stat)) (begin (define %stat stat) ) ) (if (symbol-bound? #f 'debug-enable) (debug-enable 'backtrace) ) Guile 1.3 has reverse ! , 1.2 has list - reverse ! . CGEN uses reverse ! (if (and (not (symbol-bound? #f 'reverse!)) (symbol-bound? #f 'list-reverse!)) (define reverse! list-reverse!) ) (define (debug-write . objs) (map (lambda (o) ((if (string? o) display write) o (current-error-port))) objs) (newline (current-error-port))) (if (or (> *guile-major-version* 1) (>= *guile-minor-version* 8)) (set! %load-path (append %load-path (list "."))) ) (if (memq 'debug-extensions *features*) (begin (debug-enable 'backtrace) (debug-enable 'debug) (debug-enable 'backwards) (debug-set! depth 2000) (debug-set! maxdepth 2000) (debug-set! stack 100000) (debug-set! frames 10))) (read-enable 'positions) ( On systems other than , this need n't actually do anything at all , beyond calling THUNK , so long as your backtraces are still helpful . In , the debugging evaluator is slower , so we do n't (define (cgen-call-with-debugging flag thunk) (if (memq 'debug-extensions *features*) ((if flag debug-enable debug-disable) 'debug)) has two separate evaluators , one that does the extra EXP argument . What a kludge . (start-stack (begin (thunk) #t) #f)) ( On systems other than , this does n't really need to do (define (cgen-debugging-stack-start proc args) (define (handler . args) display - error takes 6 arguments . If ` quit ' is called from elsewhere , it may not have 6 (if (= (length args) 5) (begin (apply display-error #f (current-error-port) (cdr args)) (save-stack handler 0) (backtrace))) (quit 1)) handler WITHOUT UNWINDING THE STACK ( that 's the ' lazy ' part ) . We (lazy-catch #t (lambda () (start-stack proc (apply proc args))) handler))
64373f01dd3761bcd1fd611f486c7f52f85e49e9f49fecca8fe7a7233c7980ee
tani/UFO
ufo.lisp
(in-package :cl-user) (defpackage ufo-test (:use :cl :ufo :prove)) (in-package :ufo-test) (when (cl-fad:directory-exists-p #p"~/.ufo") (cl-fad:delete-directory-and-files #p"~/.ufo/")) (plan nil) (ok (not (ufo:ufo "install" "gist"))) (ok (not (ufo:ufo "install" "ql-gists"))) (ok (not (ufo:ufo "remove" "clhs"))) (ok (not (ufo:ufo "update" "gist"))) (ok (not (ufo:ufo "install" "gh-pov"))) (ok (not (ufo:ufo "addon-install" (format nil "file://~a" (merge-pathnames #p"addon/extension/build.ros" (asdf:system-source-directory :ufo)))))) (ok (not (ufo:ufo "addon-remove" "build"))) (ok (not (ufo:ufo "help"))) (ok (ufo:ufo "unkown")) (ok (ufo:ufo "install" "ql")) (ok (ufo:ufo "install" "g")) (ok (ufo:ufo "install" "gh")) (ok (ufo:ufo "install" "gist")) (ok (ufo:ufo "install" "gh")) (ok (ufo:ufo "install" "gh://")) (ok (ufo:ufo "install" "gist")) (ok (ufo:ufo "install" "file")) (ok (ufo:ufo "update" "")) (ok (ufo:ufo "addon-install" (format nil "file://~a" (merge-pathnames #p"addon/extension/aaa" (asdf:system-source-directory :ufo))))) (finalize)
null
https://raw.githubusercontent.com/tani/UFO/d8f6876bcd6f09fcca679eb6fa56472ae76378cc/t/ufo.lisp
lisp
(in-package :cl-user) (defpackage ufo-test (:use :cl :ufo :prove)) (in-package :ufo-test) (when (cl-fad:directory-exists-p #p"~/.ufo") (cl-fad:delete-directory-and-files #p"~/.ufo/")) (plan nil) (ok (not (ufo:ufo "install" "gist"))) (ok (not (ufo:ufo "install" "ql-gists"))) (ok (not (ufo:ufo "remove" "clhs"))) (ok (not (ufo:ufo "update" "gist"))) (ok (not (ufo:ufo "install" "gh-pov"))) (ok (not (ufo:ufo "addon-install" (format nil "file://~a" (merge-pathnames #p"addon/extension/build.ros" (asdf:system-source-directory :ufo)))))) (ok (not (ufo:ufo "addon-remove" "build"))) (ok (not (ufo:ufo "help"))) (ok (ufo:ufo "unkown")) (ok (ufo:ufo "install" "ql")) (ok (ufo:ufo "install" "g")) (ok (ufo:ufo "install" "gh")) (ok (ufo:ufo "install" "gist")) (ok (ufo:ufo "install" "gh")) (ok (ufo:ufo "install" "gh://")) (ok (ufo:ufo "install" "gist")) (ok (ufo:ufo "install" "file")) (ok (ufo:ufo "update" "")) (ok (ufo:ufo "addon-install" (format nil "file://~a" (merge-pathnames #p"addon/extension/aaa" (asdf:system-source-directory :ufo))))) (finalize)
4cd0c2341308df1809973888a7f47318902c04ca496246cbdbe3578299591d43
marick/suchwow
readable.clj
(ns such.readable "Stringify nested structures such that all functions - and particular values of your choice - are displayed in a more readable way. [[value-string]] and [[fn-symbol]] are the key functions." (:refer-clojure :exclude [print]) (:require [such.symbols :as symbol] [such.types :as type] [clojure.string :as str] [clojure.repl :as repl] [com.rpl.specter :as specter])) What is stringified is controlled by two dynamically - bound variables . (def default-function-elaborations "Anonymous functions are named `fn` and functions are surrounded by `<>`" {:anonymous-name "fn" :surroundings "<>"}) (def ^:private ^:dynamic *function-elaborations* {:anonymous-name "fn" :surroundings "<>"}) (defn set-function-elaborations! "Control the way functions are prettified. Note: this does not override any value changed with `with-function-elaborations`. (set-function-elaborations! {:anonymous-name 'anon :surroundings \"\"}) " [{:keys [anonymous-name surroundings] :as all}] (alter-var-root #'*function-elaborations* (constantly all))) (defmacro with-function-elaborations "Change the function elaborations, execute the body, and revert the elaborations. (with-function-elaborations {:anonymous-name 'fun :surroundings \"{{}}\"} (fn-symbol (fn []))) => {{fun}} " [{:keys [anonymous-name surroundings] :as all} & body] `(binding [*function-elaborations* ~all] ~@body)) (def ^:private ^:dynamic *translations* "This atom contains the map from values->names that [[with-translations]] and [[value-strings]] use." (atom {})) (defn- translatable? [x] (contains? (deref *translations*) x)) (defn- translate [x] (get (deref *translations*) x)) (defn forget-translations! "There is a global store of translations from values to names, used by [[with-translations]] and [[value-strings]]. Empty it." [] (reset! *translations* {})) (defn instead-of "Arrange for [[value-string]] to show `value` as `show`. `show` is typically a symbol, but can be anything." [value show] (swap! *translations* assoc value show)) (defmacro with-translations "Describe a set of value->name translations, then execute the body (which presumably contains a call to [[value-string]]). (with-translations [5 'five {1 2} 'amap] (value-string {5 {1 2} :key [:value1 :value2 5]})) => \"{five amap, :key [:value1 :value2 five]}\" " [let-style & body] `(binding [*translations* (atom {})] (doseq [pair# (partition 2 ~let-style)] (apply instead-of pair#)) ~@body)) (defn rename "Produce a new function from `f`. It has the same behavior and metadata, except that [[fn-symbol]] and friends will use the given `name`. Note: `f` may actually be any object that allows metadata. That's irrelevant to `fn-symbol`, which accepts only functions, but it can be used to affect the output of [[value-string]]." [f name] (with-meta f (merge (meta f) {::name name}))) (defn- generate-name [f base-name anonymous-names] (if (contains? @anonymous-names f) (@anonymous-names f) (let [name (if (empty? @anonymous-names) base-name (str base-name "-" (+ 1 (count @anonymous-names))))] (swap! anonymous-names assoc f name) name))) (defn- super-demunge [f] (-> (str f) repl/demunge (str/split #"/") last (str/split #"@") first (str/split #"--[0-9]+$") first last clause required by 1.5.X (str/replace "-COLON-" ":"))) (def ^:private show-as-anonymous? #{"fn" "clojure.lang.MultiFn"}) (defn elaborate-fn-symbol "A more customizable version of [[fn-symbol]]. Takes `f`, which *must* be a function or multimethod. In all cases, the return value is a symbol where `f`'s name is embedded in the `surroundings`, a string. For example, if the surroundings are \"<!!>\", a result would look like `<!cons!>`. `f`'s name is found by these rules, checked in order: * `f` has had a name assigned with `rename`. * `f` is a key in `(deref anonymous-names)`. The value is its name. * The function had a name assigned by `defn`, `let`, or the seldom used \"named lambda\": `(fn name [...] ...)`. Note that multimethods do not have accessible names in current versions of Clojure. They are treated as anonymous functions. * The function is anonymous and there are no other anonymous names. The name is `anonymous-name`, which is also stored in the `anonymous-names` atom. * After the first anonymous name, the names are `<anonymous-name>-2` `<anonymous-name>-3` and so on. In the single-argument version, the global or default elaborations are used, and `anonymous-names` is empty. See [[set-function-elaborations!]]. " ([f {:keys [anonymous-name surroundings]} anonymous-names] (let [candidate (if (contains? (meta f) ::name) (get (meta f) ::name) (super-demunge f))] (symbol/from-concatenation [(subs surroundings 0 (/ (count surroundings) 2)) (if (show-as-anonymous? candidate) (generate-name f anonymous-name anonymous-names) candidate) (subs surroundings (/ (count surroundings) 2))]))) ([f] (elaborate-fn-symbol f *function-elaborations* (atom {})))) (defn fn-symbol "Transform `f` into a symbol with a more pleasing string representation. `f` *must* be a function or multimethod. (fn-symbol even?) => '<even?> (fn-symbol (fn [])) => '<fn> (fn-symbol (fn name [])) => '<name> (let [foo (fn [])] (fn-symbol foo)) => '<foo> See [[elaborate-fn-symbol]] for the gory details. " [f] (elaborate-fn-symbol f)) (defn fn-string "`str` applied to the result of [[fn-symbol]]." [f] (str (fn-symbol f))) (defn- better-aliases [x aliases] (specter/transform (specter/walker translatable?) translate x)) (defn- better-function-names [x anonymous-names] (specter/transform (specter/walker type/extended-fn?) #(elaborate-fn-symbol % *function-elaborations* anonymous-names) x)) (defn value "Like [[value-string]], but the final step of converting the value into a string is omitted. Note that this means functions are replaced by symbols." [x] (cond (translatable? x) (translate x) (type/extended-fn? x) (fn-symbol x) (coll? x) (let [anonymous-names (atom {})] (-> x (better-aliases (deref *translations*)) (better-function-names anonymous-names))) :else x)) (defn value-string "Except for special values, converts `x` into a string as with `pr-str`. Exceptions (which apply anywhere within collections): * If a value was given an alternate name in [[with-translations]] or [[instead-of]], that alternate is used. * Functions and multimethods are given better names as per [[fn-symbol]]. Examples: (value-string even?) => \"<even?>\" (value-string {1 {2 [even? odd?]}}) => \"{1 {2 [<even?> <odd?>]}}\" (instead-of even? 'not-odd) (value-string {1 {2 [even? odd?]}}) => \"{1 {2 [not-odd <odd?>]}}\" (def generator (fn [x] (fn [y] (+ x y)))) (def add2 (generator 2)) (def add3 (generator 3)) (value-string [add2 add3 add3 add2]) => \"[<fn> <fn-2> <fn-2> <fn>]\" (def add4 (rename (generator 4) 'add4)) (def add5 (rename (generator 4) 'add5)) (value-string [add4 add5 add5 add4]) => \"[<add4> <add5> <add5> <add4>]\" " [x] (pr-str (value x)))
null
https://raw.githubusercontent.com/marick/suchwow/111cd4aa21ee23552742701bfe52e593b65fb0f8/src/such/readable.clj
clojure
(ns such.readable "Stringify nested structures such that all functions - and particular values of your choice - are displayed in a more readable way. [[value-string]] and [[fn-symbol]] are the key functions." (:refer-clojure :exclude [print]) (:require [such.symbols :as symbol] [such.types :as type] [clojure.string :as str] [clojure.repl :as repl] [com.rpl.specter :as specter])) What is stringified is controlled by two dynamically - bound variables . (def default-function-elaborations "Anonymous functions are named `fn` and functions are surrounded by `<>`" {:anonymous-name "fn" :surroundings "<>"}) (def ^:private ^:dynamic *function-elaborations* {:anonymous-name "fn" :surroundings "<>"}) (defn set-function-elaborations! "Control the way functions are prettified. Note: this does not override any value changed with `with-function-elaborations`. (set-function-elaborations! {:anonymous-name 'anon :surroundings \"\"}) " [{:keys [anonymous-name surroundings] :as all}] (alter-var-root #'*function-elaborations* (constantly all))) (defmacro with-function-elaborations "Change the function elaborations, execute the body, and revert the elaborations. (with-function-elaborations {:anonymous-name 'fun :surroundings \"{{}}\"} (fn-symbol (fn []))) => {{fun}} " [{:keys [anonymous-name surroundings] :as all} & body] `(binding [*function-elaborations* ~all] ~@body)) (def ^:private ^:dynamic *translations* "This atom contains the map from values->names that [[with-translations]] and [[value-strings]] use." (atom {})) (defn- translatable? [x] (contains? (deref *translations*) x)) (defn- translate [x] (get (deref *translations*) x)) (defn forget-translations! "There is a global store of translations from values to names, used by [[with-translations]] and [[value-strings]]. Empty it." [] (reset! *translations* {})) (defn instead-of "Arrange for [[value-string]] to show `value` as `show`. `show` is typically a symbol, but can be anything." [value show] (swap! *translations* assoc value show)) (defmacro with-translations "Describe a set of value->name translations, then execute the body (which presumably contains a call to [[value-string]]). (with-translations [5 'five {1 2} 'amap] (value-string {5 {1 2} :key [:value1 :value2 5]})) => \"{five amap, :key [:value1 :value2 five]}\" " [let-style & body] `(binding [*translations* (atom {})] (doseq [pair# (partition 2 ~let-style)] (apply instead-of pair#)) ~@body)) (defn rename "Produce a new function from `f`. It has the same behavior and metadata, except that [[fn-symbol]] and friends will use the given `name`. Note: `f` may actually be any object that allows metadata. That's irrelevant to `fn-symbol`, which accepts only functions, but it can be used to affect the output of [[value-string]]." [f name] (with-meta f (merge (meta f) {::name name}))) (defn- generate-name [f base-name anonymous-names] (if (contains? @anonymous-names f) (@anonymous-names f) (let [name (if (empty? @anonymous-names) base-name (str base-name "-" (+ 1 (count @anonymous-names))))] (swap! anonymous-names assoc f name) name))) (defn- super-demunge [f] (-> (str f) repl/demunge (str/split #"/") last (str/split #"@") first (str/split #"--[0-9]+$") first last clause required by 1.5.X (str/replace "-COLON-" ":"))) (def ^:private show-as-anonymous? #{"fn" "clojure.lang.MultiFn"}) (defn elaborate-fn-symbol "A more customizable version of [[fn-symbol]]. Takes `f`, which *must* be a function or multimethod. In all cases, the return value is a symbol where `f`'s name is embedded in the `surroundings`, a string. For example, if the surroundings are \"<!!>\", a result would look like `<!cons!>`. `f`'s name is found by these rules, checked in order: * `f` has had a name assigned with `rename`. * `f` is a key in `(deref anonymous-names)`. The value is its name. * The function had a name assigned by `defn`, `let`, or the seldom used \"named lambda\": `(fn name [...] ...)`. Note that multimethods do not have accessible names in current versions of Clojure. They are treated as anonymous functions. * The function is anonymous and there are no other anonymous names. The name is `anonymous-name`, which is also stored in the `anonymous-names` atom. * After the first anonymous name, the names are `<anonymous-name>-2` `<anonymous-name>-3` and so on. In the single-argument version, the global or default elaborations are used, and `anonymous-names` is empty. See [[set-function-elaborations!]]. " ([f {:keys [anonymous-name surroundings]} anonymous-names] (let [candidate (if (contains? (meta f) ::name) (get (meta f) ::name) (super-demunge f))] (symbol/from-concatenation [(subs surroundings 0 (/ (count surroundings) 2)) (if (show-as-anonymous? candidate) (generate-name f anonymous-name anonymous-names) candidate) (subs surroundings (/ (count surroundings) 2))]))) ([f] (elaborate-fn-symbol f *function-elaborations* (atom {})))) (defn fn-symbol "Transform `f` into a symbol with a more pleasing string representation. `f` *must* be a function or multimethod. (fn-symbol even?) => '<even?> (fn-symbol (fn [])) => '<fn> (fn-symbol (fn name [])) => '<name> (let [foo (fn [])] (fn-symbol foo)) => '<foo> See [[elaborate-fn-symbol]] for the gory details. " [f] (elaborate-fn-symbol f)) (defn fn-string "`str` applied to the result of [[fn-symbol]]." [f] (str (fn-symbol f))) (defn- better-aliases [x aliases] (specter/transform (specter/walker translatable?) translate x)) (defn- better-function-names [x anonymous-names] (specter/transform (specter/walker type/extended-fn?) #(elaborate-fn-symbol % *function-elaborations* anonymous-names) x)) (defn value "Like [[value-string]], but the final step of converting the value into a string is omitted. Note that this means functions are replaced by symbols." [x] (cond (translatable? x) (translate x) (type/extended-fn? x) (fn-symbol x) (coll? x) (let [anonymous-names (atom {})] (-> x (better-aliases (deref *translations*)) (better-function-names anonymous-names))) :else x)) (defn value-string "Except for special values, converts `x` into a string as with `pr-str`. Exceptions (which apply anywhere within collections): * If a value was given an alternate name in [[with-translations]] or [[instead-of]], that alternate is used. * Functions and multimethods are given better names as per [[fn-symbol]]. Examples: (value-string even?) => \"<even?>\" (value-string {1 {2 [even? odd?]}}) => \"{1 {2 [<even?> <odd?>]}}\" (instead-of even? 'not-odd) (value-string {1 {2 [even? odd?]}}) => \"{1 {2 [not-odd <odd?>]}}\" (def generator (fn [x] (fn [y] (+ x y)))) (def add2 (generator 2)) (def add3 (generator 3)) (value-string [add2 add3 add3 add2]) => \"[<fn> <fn-2> <fn-2> <fn>]\" (def add4 (rename (generator 4) 'add4)) (def add5 (rename (generator 4) 'add5)) (value-string [add4 add5 add5 add4]) => \"[<add4> <add5> <add5> <add4>]\" " [x] (pr-str (value x)))
ebda6d5517e50b97ca8d3a061c1c1a730a5909023b4563a588eabdadbdc08a79
YoshikuniJujo/test_haskell
makeEnum.hs
# OPTIONS_GHC -Wall -fno - warn - tabs # module Main where import qualified VulkanExtDebugUtilsMessageEnum main :: IO () main = VulkanExtDebugUtilsMessageEnum.make
null
https://raw.githubusercontent.com/YoshikuniJujo/test_haskell/6694c28f444b99915e7e88dd3b5c38ed44d36466/themes/gui/vulkan/try-vulkan-middle-ext-debug-utils/tools/makeEnum.hs
haskell
# OPTIONS_GHC -Wall -fno - warn - tabs # module Main where import qualified VulkanExtDebugUtilsMessageEnum main :: IO () main = VulkanExtDebugUtilsMessageEnum.make
550ecb86b8b59dbca46f382d2c485e4aed1a0d3709388078c8be14a3375981bf
rwmjones/guestfs-tools
utils.ml
virt - sparsify * Copyright ( C ) 2011 - 2023 Red Hat Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation ; either version 2 of the License , or * ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License along * with this program ; if not , write to the Free Software Foundation , Inc. , * 51 Franklin Street , Fifth Floor , Boston , USA . * Copyright (C) 2011-2023 Red Hat Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *) Utilities / common functions used in virt - sparsify only . open Printf open Std_utils module G = Guestfs (* Return true if the filesystem is a read-only LV (RHBZ#1185561). *) let is_read_only_lv (g : G.guestfs) = let lvs = Array.to_list (g#lvs_full ()) in let ro_uuids = List.filter_map ( fun { G.lv_uuid; lv_attr } -> if lv_attr.[1] = 'r' then Some lv_uuid else None ) lvs in fun fs -> if g#is_lv fs then ( let uuid = g#lvuuid fs in List.exists (fun u -> compare_lvm2_uuids uuid u = 0) ro_uuids ) else false
null
https://raw.githubusercontent.com/rwmjones/guestfs-tools/57423d907270526ea664ff15601cce956353820e/sparsify/utils.ml
ocaml
Return true if the filesystem is a read-only LV (RHBZ#1185561).
virt - sparsify * Copyright ( C ) 2011 - 2023 Red Hat Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation ; either version 2 of the License , or * ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License along * with this program ; if not , write to the Free Software Foundation , Inc. , * 51 Franklin Street , Fifth Floor , Boston , USA . * Copyright (C) 2011-2023 Red Hat Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *) Utilities / common functions used in virt - sparsify only . open Printf open Std_utils module G = Guestfs let is_read_only_lv (g : G.guestfs) = let lvs = Array.to_list (g#lvs_full ()) in let ro_uuids = List.filter_map ( fun { G.lv_uuid; lv_attr } -> if lv_attr.[1] = 'r' then Some lv_uuid else None ) lvs in fun fs -> if g#is_lv fs then ( let uuid = g#lvuuid fs in List.exists (fun u -> compare_lvm2_uuids uuid u = 0) ro_uuids ) else false
092b54c49af9005485d7fa9350963a018e5812d98475a3d3ba3e73d18261803c
xively/clj-mqtt
suback_test.clj
(ns mqtt.packets.suback-test (:use clojure.test mqtt.test-helpers mqtt.decoder mqtt.encoder mqtt.packets.common mqtt.packets.suback) (:require [mqtt.decoding-utils :as du]) (:import [io.netty.buffer Unpooled] [io.netty.handler.codec EncoderException])) (deftest suback-validate-message-test (testing "nil when valid" (is (= nil (validate-message {:type :suback :message-id 1 :granted-qos [0]})))) (testing "it throws if no message-id" (is (thrown? EncoderException (validate-message {:type :suback :granted-qos [0]})))) (testing "it throws if message-id is 0" (is (thrown? EncoderException (validate-message {:type :suback :message-id 0 :granted-qos [0]}))))) (deftest suback-encoding-test (testing "when encoding a simple suback packet" (let [encoder (make-encoder) packet {:type :suback :message-id 5 :granted-qos [0]} out (Unpooled/buffer 5)] (.encode encoder nil packet out) (is (= (byte-buffer-to-bytes out) [;; fixed header (du/unsigned-byte 0x90) ;; remaining length 0x03 ;; message id 0x00 0x05 ;; granted qos(es) 0x00])))) (testing "when encoding a suback for two topics" (let [encoder (make-encoder) packet {:type :suback :message-id 6 :granted-qos [0 1]} out (Unpooled/buffer 5)] (.encode encoder nil packet out) (is (= (byte-buffer-to-bytes out) [;; fixed header (du/unsigned-byte 0x90) ;; remaining length 0x04 ;; message id 0x00 0x06 ;; granted qos(es) 0x00 0x01]))))) (deftest decoding-suback-packet-test (testing "when parsing a simple suback packet" (let [decoder (make-decoder) packet (bytes-to-byte-buffer ;; fixed header 0x90 ;; remaining length 0x03 ;; message id 0x00 0x05 ;; granted qos(es) 0x00) out (new java.util.ArrayList) _ (.decode decoder nil packet out) decoded (first out)] (testing "parses a packet" (is (not (nil? decoded))) (is (= :suback (:type decoded)))) (testing "should not be a duplicate" (is (= false (:duplicate decoded)))) (testing "parses the qos" (is (= 0 (:qos decoded)))) (testing "should not be retained" (is (= false (:retain decoded)))) (testing "it parses the message id" (is (= 5 (:message-id decoded)))) (testing "it parses the granted qos(es)" (is (= [0] (:granted-qos decoded)))))) (testing "when parsing suback packet for two topics" (let [decoder (make-decoder) packet (bytes-to-byte-buffer ;; fixed header 0x90 ;; remaining length 0x04 ;; message id 0x00 0x06 ;; granted qos(es) 0x00 0x01) out (new java.util.ArrayList) _ (.decode decoder nil packet out) decoded (first out)] (testing "parses a packet" (is (not (nil? decoded))) (is (= :suback (:type decoded)))) (testing "should not be a duplicate" (is (= false (:duplicate decoded)))) (testing "parses the qos" (is (= 0 (:qos decoded)))) (testing "should not be retained" (is (= false (:retain decoded)))) (testing "it parses the message id" (is (= 6 (:message-id decoded)))) (testing "it parses the granted qos(es)" (is (= [0 1] (:granted-qos decoded)))))))
null
https://raw.githubusercontent.com/xively/clj-mqtt/74964112505da717ea88279b62f239146450528c/test/mqtt/packets/suback_test.clj
clojure
fixed header remaining length message id granted qos(es) fixed header remaining length message id granted qos(es) fixed header remaining length message id granted qos(es) fixed header remaining length message id granted qos(es)
(ns mqtt.packets.suback-test (:use clojure.test mqtt.test-helpers mqtt.decoder mqtt.encoder mqtt.packets.common mqtt.packets.suback) (:require [mqtt.decoding-utils :as du]) (:import [io.netty.buffer Unpooled] [io.netty.handler.codec EncoderException])) (deftest suback-validate-message-test (testing "nil when valid" (is (= nil (validate-message {:type :suback :message-id 1 :granted-qos [0]})))) (testing "it throws if no message-id" (is (thrown? EncoderException (validate-message {:type :suback :granted-qos [0]})))) (testing "it throws if message-id is 0" (is (thrown? EncoderException (validate-message {:type :suback :message-id 0 :granted-qos [0]}))))) (deftest suback-encoding-test (testing "when encoding a simple suback packet" (let [encoder (make-encoder) packet {:type :suback :message-id 5 :granted-qos [0]} out (Unpooled/buffer 5)] (.encode encoder nil packet out) (is (= (byte-buffer-to-bytes out) (du/unsigned-byte 0x90) 0x03 0x00 0x05 0x00])))) (testing "when encoding a suback for two topics" (let [encoder (make-encoder) packet {:type :suback :message-id 6 :granted-qos [0 1]} out (Unpooled/buffer 5)] (.encode encoder nil packet out) (is (= (byte-buffer-to-bytes out) (du/unsigned-byte 0x90) 0x04 0x00 0x06 0x00 0x01]))))) (deftest decoding-suback-packet-test (testing "when parsing a simple suback packet" (let [decoder (make-decoder) packet (bytes-to-byte-buffer 0x90 0x03 0x00 0x05 0x00) out (new java.util.ArrayList) _ (.decode decoder nil packet out) decoded (first out)] (testing "parses a packet" (is (not (nil? decoded))) (is (= :suback (:type decoded)))) (testing "should not be a duplicate" (is (= false (:duplicate decoded)))) (testing "parses the qos" (is (= 0 (:qos decoded)))) (testing "should not be retained" (is (= false (:retain decoded)))) (testing "it parses the message id" (is (= 5 (:message-id decoded)))) (testing "it parses the granted qos(es)" (is (= [0] (:granted-qos decoded)))))) (testing "when parsing suback packet for two topics" (let [decoder (make-decoder) packet (bytes-to-byte-buffer 0x90 0x04 0x00 0x06 0x00 0x01) out (new java.util.ArrayList) _ (.decode decoder nil packet out) decoded (first out)] (testing "parses a packet" (is (not (nil? decoded))) (is (= :suback (:type decoded)))) (testing "should not be a duplicate" (is (= false (:duplicate decoded)))) (testing "parses the qos" (is (= 0 (:qos decoded)))) (testing "should not be retained" (is (= false (:retain decoded)))) (testing "it parses the message id" (is (= 6 (:message-id decoded)))) (testing "it parses the granted qos(es)" (is (= [0 1] (:granted-qos decoded)))))))
899b924fd0ec7c5d0237ac5950b673e9fc38d38dc48ff446bf2cf30338ac6dbf
skanev/playground
15.scm
SICP exercise 2.15 ; , another user , has also noticed the different intervals computed ; by different but algebraically equivalent expressions. She says that a formula to compute with intervals using 's system will produce tighter ; error bounds if it can be written in such a form that no variable that ; represents an uncertain number is repeated. Thus, she says, par2 is a ; "better" program for parallel resistances than par1. Is she right? Why? ; She is definitelly right. ; It is easy to see from the results of exercise 2.14 that the more we perform ; operations with uncertain quantities, the bigger error we get. It is ; important to note, that this applies mainly to multiplication and division. 2A is exactly the same as AA .
null
https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/sicp/02/15.scm
scheme
by different but algebraically equivalent expressions. She says that a error bounds if it can be written in such a form that no variable that represents an uncertain number is repeated. Thus, she says, par2 is a "better" program for parallel resistances than par1. Is she right? Why? She is definitelly right. operations with uncertain quantities, the bigger error we get. It is important to note, that this applies mainly to multiplication and division.
SICP exercise 2.15 , another user , has also noticed the different intervals computed formula to compute with intervals using 's system will produce tighter It is easy to see from the results of exercise 2.14 that the more we perform 2A is exactly the same as AA .
1edcb03dbd141aecae78a90d44daffcb23e2f00d7c724db3412bea0abf4293f4
Smoltbob/Caml-Est-Belle
letrec2.ml
let rec f x = print_int(x+1) in f(3.9)
null
https://raw.githubusercontent.com/Smoltbob/Caml-Est-Belle/3d6f53d4e8e01bbae57a0a402b7c0f02f4ed767c/tests/typechecking/invalid/letrec2.ml
ocaml
let rec f x = print_int(x+1) in f(3.9)
e1e958c49a6ac4cd1d6991505cb8e9bc6568a870f82681fc7fe221daf073fdb4
8thlight/hyperion
key_spec.clj
(ns hyperion.sql.key-spec (:require [speclj.core :refer :all ] [hyperion.sql.key :refer :all ] [clojure.data.codec.base64 :refer [encode decode]])) (describe "Hyperion SQL Key" (it "creates keys based on kind and id" (should= (compose-key "foo" 1) (compose-key "foo" 1)) (should-not= (compose-key "foo" 1) (compose-key "foo" 2)) (should-not= (compose-key "foo" 1) (compose-key "bar" 1))) (it "can parse a key" (let [key (compose-key "foo" 123)] (should= ["foo" 123] (decompose-key key)))) )
null
https://raw.githubusercontent.com/8thlight/hyperion/b1b8f60a5ef013da854e98319220b97920727865/sql/spec/hyperion/sql/key_spec.clj
clojure
(ns hyperion.sql.key-spec (:require [speclj.core :refer :all ] [hyperion.sql.key :refer :all ] [clojure.data.codec.base64 :refer [encode decode]])) (describe "Hyperion SQL Key" (it "creates keys based on kind and id" (should= (compose-key "foo" 1) (compose-key "foo" 1)) (should-not= (compose-key "foo" 1) (compose-key "foo" 2)) (should-not= (compose-key "foo" 1) (compose-key "bar" 1))) (it "can parse a key" (let [key (compose-key "foo" 123)] (should= ["foo" 123] (decompose-key key)))) )
2060e106b4c61a3686af40eac936dd3b890b64f8ff7853d3d4abf6525c335759
kovasb/gamma-driver
test.cljs
(ns gamma.webgl.test (:require [clojure.browser.repl :as repl] )) (enable-console-print!) (defonce conn (repl/connect ":9000/repl")) (comment (ns gamma.webgl.test1 (:require [goog.dom :as gdom] [goog.webgl :as ggl] [gamma.api :as g] [gamma.program :as p] [gamma.program :as p] [gamma.webgl.shader :as shader] [gamma.webgl.interpreter :as itr] [gamma.webgl.operations :as ops] [cljs.pprint :as pprint] [gamma.webgl.routines.symbolic :as r] [gamma.webgl.driver :as driver] )) (def pos-attribute (g/attribute "posAttr" :vec2)) (defn example-shader [] (assoc (shader/Shader. (p/program {:id :hello-triangle :vertex-shader {(g/gl-position) (g/vec4 pos-attribute 0 1)} :fragment-shader {(g/gl-frag-color) (g/vec4 1 0 0 1)}})) :tag :shader)) (defn get-context [id] (.getContext (.getElementById js/document id) "webgl")) (defn ->float32 [x] (js/Float32Array. (clj->js (flatten x)))) (let [ops (r/draw [:root] (example-shader)) driver (driver/driver {:gl (get-context "gl-canvas")} ops)] (driver/exec! driver {:hello-triangle {pos-attribute (->float32 [[-1 0] [0 1] [1 -1]])} :draw {:start 0 :count 3}})) (comment (def ops (r/draw [:root] (example-shader) )) (def driver (driver/driver {:gl (get-context "gl-canvas")} ops)) (:init? driver) (:loop driver) (:ops driver) (ops/rewrite (:ops driver)) ;; implement: :bind-attribute :bind-uniform :bind-arraybuffer :draw-arrays (clojure.walk/postwalk #(if (vector? %) (reverse %) %) [[1 2] [3 4] [5 6]] )) ;;;;; (def pos-varying (g/varying "posVarying" :vec2 :mediump)) (defn example-shader2 [] (p/program {:id :ex2 :precision {:float :mediump} :vertex-shader {(g/gl-position) (g/vec4 pos-attribute 0 1) pos-varying pos-attribute} :fragment-shader {(g/gl-frag-color) (let [v (g/sin (g/* (g/* 4.0 (g/swizzle pos-varying :x)) (g/* 4.0 (g/swizzle pos-varying :y))) )] (g/if (g/< 0 v) (g/vec4 0 0 v 1) (g/vec4 0 (g/abs v) 0 1)))}})) (defn example-shader2 [] (p/program {:id :ex2 :precision {:float :mediump} :vertex-shader {(g/gl-position) (g/vec4 pos-attribute 0 1) pos-varying pos-attribute} :fragment-shader {(g/gl-frag-color) (let [v (g/div (g/+ (g/cos (g/* 10 (g/swizzle pos-varying :x))) (g/cos (g/* 10 (g/swizzle pos-varying :y)))) 2)] (g/if (g/< 0 v) (g/vec4 0 0 v 1) (g/vec4 0 (g/abs v) 0 1)))}})) (comment ) (let [bl [-1 -1] tr [1 1] br [1 -1] tl [-1 1]] [bl br tl tr br tl]) (defn rect [left right bottom top] [[left bottom] [right bottom] [left top] [right top] [right bottom] [left top]]) (run (example-shader2) {:data {pos-attribute {:tag :data :data (js/Float32Array. (clj->js [-1 -1 1 -1 -1 1 1 1 1 -1 -1 1]))}} :draw {:start 0 :count 6}}) (run (example-shader) {:data {pos-attribute {:tag :data :data (js/Float32Array. (clj->js [-1 0 0 1 1 0]))}} :draw {:start 0 :count 3}}) (println (:glsl (:fragment-shader (example-shader2)))))
null
https://raw.githubusercontent.com/kovasb/gamma-driver/abe0e1dd01365404342f4e8e04263e48c4648b6e/test/gamma/webgl/test.cljs
clojure
implement:
(ns gamma.webgl.test (:require [clojure.browser.repl :as repl] )) (enable-console-print!) (defonce conn (repl/connect ":9000/repl")) (comment (ns gamma.webgl.test1 (:require [goog.dom :as gdom] [goog.webgl :as ggl] [gamma.api :as g] [gamma.program :as p] [gamma.program :as p] [gamma.webgl.shader :as shader] [gamma.webgl.interpreter :as itr] [gamma.webgl.operations :as ops] [cljs.pprint :as pprint] [gamma.webgl.routines.symbolic :as r] [gamma.webgl.driver :as driver] )) (def pos-attribute (g/attribute "posAttr" :vec2)) (defn example-shader [] (assoc (shader/Shader. (p/program {:id :hello-triangle :vertex-shader {(g/gl-position) (g/vec4 pos-attribute 0 1)} :fragment-shader {(g/gl-frag-color) (g/vec4 1 0 0 1)}})) :tag :shader)) (defn get-context [id] (.getContext (.getElementById js/document id) "webgl")) (defn ->float32 [x] (js/Float32Array. (clj->js (flatten x)))) (let [ops (r/draw [:root] (example-shader)) driver (driver/driver {:gl (get-context "gl-canvas")} ops)] (driver/exec! driver {:hello-triangle {pos-attribute (->float32 [[-1 0] [0 1] [1 -1]])} :draw {:start 0 :count 3}})) (comment (def ops (r/draw [:root] (example-shader) )) (def driver (driver/driver {:gl (get-context "gl-canvas")} ops)) (:init? driver) (:loop driver) (:ops driver) (ops/rewrite (:ops driver)) :bind-attribute :bind-uniform :bind-arraybuffer :draw-arrays (clojure.walk/postwalk #(if (vector? %) (reverse %) %) [[1 2] [3 4] [5 6]] )) (def pos-varying (g/varying "posVarying" :vec2 :mediump)) (defn example-shader2 [] (p/program {:id :ex2 :precision {:float :mediump} :vertex-shader {(g/gl-position) (g/vec4 pos-attribute 0 1) pos-varying pos-attribute} :fragment-shader {(g/gl-frag-color) (let [v (g/sin (g/* (g/* 4.0 (g/swizzle pos-varying :x)) (g/* 4.0 (g/swizzle pos-varying :y))) )] (g/if (g/< 0 v) (g/vec4 0 0 v 1) (g/vec4 0 (g/abs v) 0 1)))}})) (defn example-shader2 [] (p/program {:id :ex2 :precision {:float :mediump} :vertex-shader {(g/gl-position) (g/vec4 pos-attribute 0 1) pos-varying pos-attribute} :fragment-shader {(g/gl-frag-color) (let [v (g/div (g/+ (g/cos (g/* 10 (g/swizzle pos-varying :x))) (g/cos (g/* 10 (g/swizzle pos-varying :y)))) 2)] (g/if (g/< 0 v) (g/vec4 0 0 v 1) (g/vec4 0 (g/abs v) 0 1)))}})) (comment ) (let [bl [-1 -1] tr [1 1] br [1 -1] tl [-1 1]] [bl br tl tr br tl]) (defn rect [left right bottom top] [[left bottom] [right bottom] [left top] [right top] [right bottom] [left top]]) (run (example-shader2) {:data {pos-attribute {:tag :data :data (js/Float32Array. (clj->js [-1 -1 1 -1 -1 1 1 1 1 -1 -1 1]))}} :draw {:start 0 :count 6}}) (run (example-shader) {:data {pos-attribute {:tag :data :data (js/Float32Array. (clj->js [-1 0 0 1 1 0]))}} :draw {:start 0 :count 3}}) (println (:glsl (:fragment-shader (example-shader2)))))
a6d2f79adb80a75be729085101a47e8c594b605c8b1d099bf7983a6bc1de764c
greglook/cljstyle
type_test.clj
(ns cljstyle.format.type-test (:require [cljstyle.format.type :as type] [cljstyle.test-util] [clojure.test :refer [deftest testing is]])) (deftest protocol-definitions (testing "basics" (is (rule-reformatted? type/format-protocols {} "(defprotocol Foo)" "(defprotocol Foo)")) (is (rule-reformatted? type/format-protocols {} "(defprotocol Foo \"doc string goes here\")" "(defprotocol Foo \"doc string goes here\")")) (is (rule-reformatted? type/format-protocols {} "(defprotocol Foo \"doc string goes here\" (abc [foo]))" "(defprotocol Foo \"doc string goes here\" (abc [foo]))"))) (testing "method forms" (is (rule-reformatted? type/format-protocols {} "(defprotocol Foo (efg [foo] \"method doc\"))" "(defprotocol Foo (efg [foo] \"method doc\"))")) (is (rule-reformatted? type/format-protocols {} "(defprotocol Foo (bar [foo] [foo x]))" "(defprotocol Foo (bar [foo] [foo x]))")) (is (rule-reformatted? type/format-protocols {} "(defprotocol Foo (bar [foo] [foo x] \"multiline method doc\"))" "(defprotocol Foo (bar [foo] [foo x] \"multiline method doc\"))")) (is (rule-reformatted? type/format-protocols {} "(defprotocol Foo (bar [foo] \"method doc\") (baz [foo x y]))" "(defprotocol Foo (bar [foo] \"method doc\") (baz [foo x y]))"))) (testing "metadata" (is (rule-reformatted? type/format-protocols {} "(defprotocol ^:deprecated Foo (qrs [foo]))" "(defprotocol ^:deprecated Foo (qrs [foo]))"))) (testing "options" (is (rule-reformatted? type/format-protocols {} "(defprotocol Foo :extend-via-metadata true :baz 123 (qrs [foo]))" "(defprotocol Foo :extend-via-metadata true :baz 123 (qrs [foo]))")) (is (rule-reformatted? type/format-protocols {} "(defprotocol Foo ::methods (map f ms) (bar [foo x] \"doc\"))" "(defprotocol Foo ::methods (map f ms) (bar [foo x] \"doc\"))" "option value lists should not be treated like methods"))) (testing "comments" (is (rule-reformatted? type/format-protocols {} "(defprotocol Bar \"proto doc\" ;; an option comment :some-opt 123 ;; a method comment (frobble [bar x y]))" "(defprotocol Bar \"proto doc\" ;; an option comment :some-opt 123 ;; a method comment (frobble [bar x y]))"))) (testing "nesting" (is (rule-reformatted? type/format-protocols {} "(do (defprotocol Foo \"doc string goes here\" (abc [foo])))" "(do (defprotocol Foo \"doc string goes here\" (abc [foo])))")))) (deftest type-definitions (testing "basics" (is (rule-reformatted? type/format-types {} "(deftype Thing [])" "(deftype Thing\n[])")) (is (rule-reformatted? type/format-types {} "(defrecord Thing [field-one field-two another-field])" "(defrecord Thing [field-one field-two another-field])")) (is (rule-reformatted? type/format-types {} "(defrecord Foo\n[x]\nCloseable\n(close [_]\n(prn x)))" "(defrecord Foo\n[x]\n\nCloseable\n\n(close\n[_]\n(prn x)))"))) (testing "complex" (is (rule-reformatted? type/format-types {} "(deftype Thing [x y z] IFoo (oneline [this] :thing) (foo [this a b] (* (+ a x) z)) (bar [this c] (- c y)))" "(deftype Thing [x y z] IFoo (oneline [this] :thing) (foo [this a b] (* (+ a x) z)) (bar [this c] (- c y)))")) (is (rule-reformatted? type/format-types {} "(t/defrecord Foo\n [x]\nCloseable\n(close [_]\n(prn x)))" "(t/defrecord Foo\n [x]\n\nCloseable\n\n(close\n[_]\n(prn x)))")) (is (rule-reformatted? type/format-types {} "(defrecord Baz [x y]\n :load-ns true Object (toString [_] \"Baz\"))" "(defrecord Baz\n[x y]\n :load-ns true\n\nObject\n\n(toString [_] \"Baz\"))"))) (testing "comments" (is (rule-reformatted? type/format-types {} "(defrecord Apple [a b] ;; here are some interstitial comments ;; they should be left alone Object ;; a pre-method comment (toString [this] \"...\"))" "(defrecord Apple [a b] ;; here are some interstitial comments ;; they should be left alone Object ;; a pre-method comment (toString [this] \"...\"))"))) (testing "edge cases" (is (rule-reformatted? type/format-types {} "(defrecord MyComp [x y] component/Lifecycle (start [this] this) (stop [this] this))" "(defrecord MyComp [x y] component/Lifecycle (start [this] this) (stop [this] this))")))) (deftest reify-forms (is (rule-reformatted? type/format-reifies {} "(reify Closeable (close [_] (prn :closed)))" "(reify Closeable (close [_] (prn :closed)))")) (is (rule-reformatted? type/format-reifies {} "(reify Closeable (close [_] (prn :closed)))" "(reify Closeable (close [_] (prn :closed)))")) (is (rule-reformatted? type/format-reifies {} "(reify Key (getKey [this] key-data) Object (toString [this] \"key\"))" "(reify Key (getKey [this] key-data) Object (toString [this] \"key\"))")) (is (rule-reformatted? type/format-reifies {} "(reify ABC (close [_]))" "(reify ABC (close [_]))" "empty method body should be fine"))) (deftest proxy-forms (is (rule-reformatted? type/format-proxies {} "(proxy [Clazz] [] (method [x y] (+ x y)))" "(proxy [Clazz] [] (method [x y] (+ x y)))")) (is (rule-reformatted? type/format-proxies {} "(proxy [Clazz] [] (method [x y] (+ x y)))" "(proxy [Clazz] [] (method [x y] (+ x y)))")) (is (rule-reformatted? type/format-proxies {} "(proxy [Clazz IFaceA IFaceB] [arg1 arg2] (method [x y] (+ x y)))" "(proxy [Clazz IFaceA IFaceB] [arg1 arg2] (method [x y] (+ x y)))")) (is (rule-reformatted? type/format-proxies {} "(proxy [Clazz IFaceA IFaceB] [arg1 arg2] (method [x y] (+ x y)))" "(proxy [Clazz IFaceA IFaceB] [arg1 arg2] (method [x y] (+ x y)))")) (is (rule-reformatted? type/format-proxies {} "(proxy [Clazz IFaceA IFaceB] [arg1 arg2] (method [x y] (+ x y)))" "(proxy [Clazz IFaceA IFaceB] [arg1 arg2] (method [x y] (+ x y)))")) (is (rule-reformatted? type/format-proxies {} "(proxy [Clazz] [string] (add [x y] (+ x y)) (mul [x y] (* x y)))" "(proxy [Clazz] [string] (add [x y] (+ x y)) (mul [x y] (* x y)))")))
null
https://raw.githubusercontent.com/greglook/cljstyle/1f58e2e7af4c193aa77ad0695f6c2b9ac2c5c5ec/test/cljstyle/format/type_test.clj
clojure
an option comment a method comment an option comment a method comment here are some interstitial comments they should be left alone a pre-method comment here are some interstitial comments they should be left alone a pre-method comment
(ns cljstyle.format.type-test (:require [cljstyle.format.type :as type] [cljstyle.test-util] [clojure.test :refer [deftest testing is]])) (deftest protocol-definitions (testing "basics" (is (rule-reformatted? type/format-protocols {} "(defprotocol Foo)" "(defprotocol Foo)")) (is (rule-reformatted? type/format-protocols {} "(defprotocol Foo \"doc string goes here\")" "(defprotocol Foo \"doc string goes here\")")) (is (rule-reformatted? type/format-protocols {} "(defprotocol Foo \"doc string goes here\" (abc [foo]))" "(defprotocol Foo \"doc string goes here\" (abc [foo]))"))) (testing "method forms" (is (rule-reformatted? type/format-protocols {} "(defprotocol Foo (efg [foo] \"method doc\"))" "(defprotocol Foo (efg [foo] \"method doc\"))")) (is (rule-reformatted? type/format-protocols {} "(defprotocol Foo (bar [foo] [foo x]))" "(defprotocol Foo (bar [foo] [foo x]))")) (is (rule-reformatted? type/format-protocols {} "(defprotocol Foo (bar [foo] [foo x] \"multiline method doc\"))" "(defprotocol Foo (bar [foo] [foo x] \"multiline method doc\"))")) (is (rule-reformatted? type/format-protocols {} "(defprotocol Foo (bar [foo] \"method doc\") (baz [foo x y]))" "(defprotocol Foo (bar [foo] \"method doc\") (baz [foo x y]))"))) (testing "metadata" (is (rule-reformatted? type/format-protocols {} "(defprotocol ^:deprecated Foo (qrs [foo]))" "(defprotocol ^:deprecated Foo (qrs [foo]))"))) (testing "options" (is (rule-reformatted? type/format-protocols {} "(defprotocol Foo :extend-via-metadata true :baz 123 (qrs [foo]))" "(defprotocol Foo :extend-via-metadata true :baz 123 (qrs [foo]))")) (is (rule-reformatted? type/format-protocols {} "(defprotocol Foo ::methods (map f ms) (bar [foo x] \"doc\"))" "(defprotocol Foo ::methods (map f ms) (bar [foo x] \"doc\"))" "option value lists should not be treated like methods"))) (testing "comments" (is (rule-reformatted? type/format-protocols {} "(defprotocol Bar \"proto doc\" :some-opt 123 (frobble [bar x y]))" "(defprotocol Bar \"proto doc\" :some-opt 123 (frobble [bar x y]))"))) (testing "nesting" (is (rule-reformatted? type/format-protocols {} "(do (defprotocol Foo \"doc string goes here\" (abc [foo])))" "(do (defprotocol Foo \"doc string goes here\" (abc [foo])))")))) (deftest type-definitions (testing "basics" (is (rule-reformatted? type/format-types {} "(deftype Thing [])" "(deftype Thing\n[])")) (is (rule-reformatted? type/format-types {} "(defrecord Thing [field-one field-two another-field])" "(defrecord Thing [field-one field-two another-field])")) (is (rule-reformatted? type/format-types {} "(defrecord Foo\n[x]\nCloseable\n(close [_]\n(prn x)))" "(defrecord Foo\n[x]\n\nCloseable\n\n(close\n[_]\n(prn x)))"))) (testing "complex" (is (rule-reformatted? type/format-types {} "(deftype Thing [x y z] IFoo (oneline [this] :thing) (foo [this a b] (* (+ a x) z)) (bar [this c] (- c y)))" "(deftype Thing [x y z] IFoo (oneline [this] :thing) (foo [this a b] (* (+ a x) z)) (bar [this c] (- c y)))")) (is (rule-reformatted? type/format-types {} "(t/defrecord Foo\n [x]\nCloseable\n(close [_]\n(prn x)))" "(t/defrecord Foo\n [x]\n\nCloseable\n\n(close\n[_]\n(prn x)))")) (is (rule-reformatted? type/format-types {} "(defrecord Baz [x y]\n :load-ns true Object (toString [_] \"Baz\"))" "(defrecord Baz\n[x y]\n :load-ns true\n\nObject\n\n(toString [_] \"Baz\"))"))) (testing "comments" (is (rule-reformatted? type/format-types {} "(defrecord Apple [a b] Object (toString [this] \"...\"))" "(defrecord Apple [a b] Object (toString [this] \"...\"))"))) (testing "edge cases" (is (rule-reformatted? type/format-types {} "(defrecord MyComp [x y] component/Lifecycle (start [this] this) (stop [this] this))" "(defrecord MyComp [x y] component/Lifecycle (start [this] this) (stop [this] this))")))) (deftest reify-forms (is (rule-reformatted? type/format-reifies {} "(reify Closeable (close [_] (prn :closed)))" "(reify Closeable (close [_] (prn :closed)))")) (is (rule-reformatted? type/format-reifies {} "(reify Closeable (close [_] (prn :closed)))" "(reify Closeable (close [_] (prn :closed)))")) (is (rule-reformatted? type/format-reifies {} "(reify Key (getKey [this] key-data) Object (toString [this] \"key\"))" "(reify Key (getKey [this] key-data) Object (toString [this] \"key\"))")) (is (rule-reformatted? type/format-reifies {} "(reify ABC (close [_]))" "(reify ABC (close [_]))" "empty method body should be fine"))) (deftest proxy-forms (is (rule-reformatted? type/format-proxies {} "(proxy [Clazz] [] (method [x y] (+ x y)))" "(proxy [Clazz] [] (method [x y] (+ x y)))")) (is (rule-reformatted? type/format-proxies {} "(proxy [Clazz] [] (method [x y] (+ x y)))" "(proxy [Clazz] [] (method [x y] (+ x y)))")) (is (rule-reformatted? type/format-proxies {} "(proxy [Clazz IFaceA IFaceB] [arg1 arg2] (method [x y] (+ x y)))" "(proxy [Clazz IFaceA IFaceB] [arg1 arg2] (method [x y] (+ x y)))")) (is (rule-reformatted? type/format-proxies {} "(proxy [Clazz IFaceA IFaceB] [arg1 arg2] (method [x y] (+ x y)))" "(proxy [Clazz IFaceA IFaceB] [arg1 arg2] (method [x y] (+ x y)))")) (is (rule-reformatted? type/format-proxies {} "(proxy [Clazz IFaceA IFaceB] [arg1 arg2] (method [x y] (+ x y)))" "(proxy [Clazz IFaceA IFaceB] [arg1 arg2] (method [x y] (+ x y)))")) (is (rule-reformatted? type/format-proxies {} "(proxy [Clazz] [string] (add [x y] (+ x y)) (mul [x y] (* x y)))" "(proxy [Clazz] [string] (add [x y] (+ x y)) (mul [x y] (* x y)))")))
28da033afcaf6d06c14b8871b81e0140f0e51cd598f4e60559c0ddc053606e7c
ml4tp/tcoq
environ.mli
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) open Names open Term open Declarations open Univ (** Unsafe environments. We define here a datatype for environments. Since typing is not yet defined, it is not possible to check the informations added in environments, and that is why we speak here of ``unsafe'' environments. *) * Environments have the following components : - a context for variables - a context for variables vm values - a context for section variables and goal assumptions - a context for section variables and goal assumptions vm values - a context for global constants and axioms - a context for inductive definitions - a set of universe constraints - a flag telling if Set is , can be , or can not be set impredicative - a context for de Bruijn variables - a context for de Bruijn variables vm values - a context for section variables and goal assumptions - a context for section variables and goal assumptions vm values - a context for global constants and axioms - a context for inductive definitions - a set of universe constraints - a flag telling if Set is, can be, or cannot be set impredicative *) type env val pre_env : env -> Pre_env.env val env_of_pre_env : Pre_env.env -> env val oracle : env -> Conv_oracle.oracle val set_oracle : env -> Conv_oracle.oracle -> env type named_context_val val eq_named_context_val : named_context_val -> named_context_val -> bool val empty_env : env val universes : env -> UGraph.t val rel_context : env -> Context.Rel.t val named_context : env -> Context.Named.t val named_context_val : env -> named_context_val val opaque_tables : env -> Opaqueproof.opaquetab val set_opaque_tables : env -> Opaqueproof.opaquetab -> env val engagement : env -> engagement val typing_flags : env -> typing_flags val is_impredicative_set : env -> bool val type_in_type : env -> bool val deactivated_guard : env -> bool (** is the local context empty *) val empty_context : env -> bool * { 5 Context of de Bruijn variables ( [ rel_context ] ) } val nb_rel : env -> int val push_rel : Context.Rel.Declaration.t -> env -> env val push_rel_context : Context.Rel.t -> env -> env val push_rec_types : rec_declaration -> env -> env (** Looks up in the context of local vars referred by indice ([rel_context]) raises [Not_found] if the index points out of the context *) val lookup_rel : int -> env -> Context.Rel.Declaration.t val evaluable_rel : int -> env -> bool * { 6 Recurrence on [ rel_context ] } val fold_rel_context : (env -> Context.Rel.Declaration.t -> 'a -> 'a) -> env -> init:'a -> 'a * { 5 Context of variables ( section variables and goal assumptions ) } val named_context_of_val : named_context_val -> Context.Named.t val val_of_named_context : Context.Named.t -> named_context_val val empty_named_context_val : named_context_val (** [map_named_val f ctxt] apply [f] to the body and the type of each declarations. *** /!\ *** [f t] should be convertible with t *) val map_named_val : (constr -> constr) -> named_context_val -> named_context_val val push_named : Context.Named.Declaration.t -> env -> env val push_named_context : Context.Named.t -> env -> env val push_named_context_val : Context.Named.Declaration.t -> named_context_val -> named_context_val (** Looks up in the context of local vars referred by names ([named_context]) raises [Not_found] if the Id.t is not found *) val lookup_named : variable -> env -> Context.Named.Declaration.t val lookup_named_val : variable -> named_context_val -> Context.Named.Declaration.t val evaluable_named : variable -> env -> bool val named_type : variable -> env -> types val named_body : variable -> env -> constr option * { 6 Recurrence on [ named_context ] : older declarations processed first } val fold_named_context : (env -> Context.Named.Declaration.t -> 'a -> 'a) -> env -> init:'a -> 'a * Recurrence on [ named_context ] starting from younger val fold_named_context_reverse : ('a -> Context.Named.Declaration.t -> 'a) -> init:'a -> env -> 'a (** This forgets named and rel contexts *) val reset_context : env -> env (** This forgets rel context and sets a new named context *) val reset_with_named_context : named_context_val -> env -> env (** This removes the [n] last declarations from the rel context *) val pop_rel_context : int -> env -> env * { 5 Global constants } { 6 Add entries to global environment } {6 Add entries to global environment } *) val add_constant : constant -> constant_body -> env -> env val add_constant_key : constant -> constant_body -> Pre_env.link_info -> env -> env (** Looks up in the context of global constant names raises [Not_found] if the required path is not found *) val lookup_constant : constant -> env -> constant_body val evaluable_constant : constant -> env -> bool (** New-style polymorphism *) val polymorphic_constant : constant -> env -> bool val polymorphic_pconstant : pconstant -> env -> bool val type_in_type_constant : constant -> env -> bool (** Old-style polymorphism *) val template_polymorphic_constant : constant -> env -> bool val template_polymorphic_pconstant : pconstant -> env -> bool * { 6 ... } * [ constant_value env c ] raises [ NotEvaluableConst Opaque ] if [ c ] is opaque and [ ] if it has no body and [ NotEvaluableConst IsProj ] if [ c ] is a projection and [ Not_found ] if it does not exist in [ env ] [c] is opaque and [NotEvaluableConst NoBody] if it has no body and [NotEvaluableConst IsProj] if [c] is a projection and [Not_found] if it does not exist in [env] *) type const_evaluation_result = NoBody | Opaque | IsProj exception NotEvaluableConst of const_evaluation_result val constant_value : env -> constant puniverses -> constr constrained val constant_type : env -> constant puniverses -> constant_type constrained val constant_opt_value : env -> constant puniverses -> (constr * Univ.constraints) option val constant_value_and_type : env -> constant puniverses -> constr option * constant_type * Univ.constraints (** The universe context associated to the constant, empty if not polymorphic *) val constant_context : env -> constant -> Univ.universe_context (* These functions should be called under the invariant that [env] already contains the constraints corresponding to the constant application. *) val constant_value_in : env -> constant puniverses -> constr val constant_type_in : env -> constant puniverses -> constant_type val constant_opt_value_in : env -> constant puniverses -> constr option * { 6 Primitive projections } val lookup_projection : Names.projection -> env -> projection_body val is_projection : constant -> env -> bool * { 5 Inductive types } val add_mind_key : mutual_inductive -> Pre_env.mind_key -> env -> env val add_mind : mutual_inductive -> mutual_inductive_body -> env -> env (** Looks up in the context of global inductive names raises [Not_found] if the required path is not found *) val lookup_mind : mutual_inductive -> env -> mutual_inductive_body (** New-style polymorphism *) val polymorphic_ind : inductive -> env -> bool val polymorphic_pind : pinductive -> env -> bool val type_in_type_ind : inductive -> env -> bool (** Old-style polymorphism *) val template_polymorphic_ind : inductive -> env -> bool val template_polymorphic_pind : pinductive -> env -> bool * { 5 Modules } val add_modtype : module_type_body -> env -> env (** [shallow_add_module] does not add module components *) val shallow_add_module : module_body -> env -> env val lookup_module : module_path -> env -> module_body val lookup_modtype : module_path -> env -> module_type_body * { 5 Universe constraints } * Add universe constraints to the environment . @raises UniverseInconsistency @raises UniverseInconsistency *) val add_constraints : Univ.constraints -> env -> env (** Check constraints are satifiable in the environment. *) val check_constraints : Univ.constraints -> env -> bool val push_context : ?strict:bool -> Univ.universe_context -> env -> env val push_context_set : ?strict:bool -> Univ.universe_context_set -> env -> env val push_constraints_to_env : 'a Univ.constrained -> env -> env val set_engagement : engagement -> env -> env val set_typing_flags : typing_flags -> env -> env * { 6 Sets of referred section variables } [ global_vars_set env c ] returns the list of [ i d ] 's occurring either directly as [ Var i d ] in [ c ] or indirectly as a section variable dependent in a global reference occurring in [ c ] [global_vars_set env c] returns the list of [id]'s occurring either directly as [Var id] in [c] or indirectly as a section variable dependent in a global reference occurring in [c] *) val global_vars_set : env -> constr -> Id.Set.t (** the constr must be a global reference *) val vars_of_global : env -> constr -> Id.Set.t (** closure of the input id set w.r.t. dependency *) val really_needed : env -> Id.Set.t -> Id.Set.t (** like [really_needed] but computes a well ordered named context *) val keep_hyps : env -> Id.Set.t -> Context.section_context * { 5 Unsafe judgments . } We introduce here the pre - type of judgments , which is actually only a datatype to store a term with its type and the type of its type . We introduce here the pre-type of judgments, which is actually only a datatype to store a term with its type and the type of its type. *) type unsafe_judgment = { uj_val : constr; uj_type : types } val make_judge : constr -> types -> unsafe_judgment val j_val : unsafe_judgment -> constr val j_type : unsafe_judgment -> types type unsafe_type_judgment = { utj_val : constr; utj_type : sorts } (** {6 Compilation of global declaration } *) val compile_constant_body : env -> constant_universes option -> constant_def -> Cemitcodes.body_code option exception Hyp_not_found (** [apply_to_hyp sign id f] split [sign] into [tail::(id,_,_)::head] and return [tail::(f head (id,_,_) (rev tail))::head]. the value associated to id should not change *) val apply_to_hyp : named_context_val -> variable -> (Context.Named.t -> Context.Named.Declaration.t -> Context.Named.t -> Context.Named.Declaration.t) -> named_context_val val remove_hyps : Id.Set.t -> (Context.Named.Declaration.t -> Context.Named.Declaration.t) -> (Pre_env.lazy_val -> Pre_env.lazy_val) -> named_context_val -> named_context_val open Retroknowledge (** functions manipulating the retroknowledge @author spiwack *) val retroknowledge : (retroknowledge->'a) -> env -> 'a val registered : env -> field -> bool val register : env -> field -> Retroknowledge.entry -> env * Native compiler val no_link_info : Pre_env.link_info
null
https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/kernel/environ.mli
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** * Unsafe environments. We define here a datatype for environments. Since typing is not yet defined, it is not possible to check the informations added in environments, and that is why we speak here of ``unsafe'' environments. * is the local context empty * Looks up in the context of local vars referred by indice ([rel_context]) raises [Not_found] if the index points out of the context * [map_named_val f ctxt] apply [f] to the body and the type of each declarations. *** /!\ *** [f t] should be convertible with t * Looks up in the context of local vars referred by names ([named_context]) raises [Not_found] if the Id.t is not found * This forgets named and rel contexts * This forgets rel context and sets a new named context * This removes the [n] last declarations from the rel context * Looks up in the context of global constant names raises [Not_found] if the required path is not found * New-style polymorphism * Old-style polymorphism * The universe context associated to the constant, empty if not polymorphic These functions should be called under the invariant that [env] already contains the constraints corresponding to the constant application. * Looks up in the context of global inductive names raises [Not_found] if the required path is not found * New-style polymorphism * Old-style polymorphism * [shallow_add_module] does not add module components * Check constraints are satifiable in the environment. * the constr must be a global reference * closure of the input id set w.r.t. dependency * like [really_needed] but computes a well ordered named context * {6 Compilation of global declaration } * [apply_to_hyp sign id f] split [sign] into [tail::(id,_,_)::head] and return [tail::(f head (id,_,_) (rev tail))::head]. the value associated to id should not change * functions manipulating the retroknowledge @author spiwack
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Names open Term open Declarations open Univ * Environments have the following components : - a context for variables - a context for variables vm values - a context for section variables and goal assumptions - a context for section variables and goal assumptions vm values - a context for global constants and axioms - a context for inductive definitions - a set of universe constraints - a flag telling if Set is , can be , or can not be set impredicative - a context for de Bruijn variables - a context for de Bruijn variables vm values - a context for section variables and goal assumptions - a context for section variables and goal assumptions vm values - a context for global constants and axioms - a context for inductive definitions - a set of universe constraints - a flag telling if Set is, can be, or cannot be set impredicative *) type env val pre_env : env -> Pre_env.env val env_of_pre_env : Pre_env.env -> env val oracle : env -> Conv_oracle.oracle val set_oracle : env -> Conv_oracle.oracle -> env type named_context_val val eq_named_context_val : named_context_val -> named_context_val -> bool val empty_env : env val universes : env -> UGraph.t val rel_context : env -> Context.Rel.t val named_context : env -> Context.Named.t val named_context_val : env -> named_context_val val opaque_tables : env -> Opaqueproof.opaquetab val set_opaque_tables : env -> Opaqueproof.opaquetab -> env val engagement : env -> engagement val typing_flags : env -> typing_flags val is_impredicative_set : env -> bool val type_in_type : env -> bool val deactivated_guard : env -> bool val empty_context : env -> bool * { 5 Context of de Bruijn variables ( [ rel_context ] ) } val nb_rel : env -> int val push_rel : Context.Rel.Declaration.t -> env -> env val push_rel_context : Context.Rel.t -> env -> env val push_rec_types : rec_declaration -> env -> env val lookup_rel : int -> env -> Context.Rel.Declaration.t val evaluable_rel : int -> env -> bool * { 6 Recurrence on [ rel_context ] } val fold_rel_context : (env -> Context.Rel.Declaration.t -> 'a -> 'a) -> env -> init:'a -> 'a * { 5 Context of variables ( section variables and goal assumptions ) } val named_context_of_val : named_context_val -> Context.Named.t val val_of_named_context : Context.Named.t -> named_context_val val empty_named_context_val : named_context_val val map_named_val : (constr -> constr) -> named_context_val -> named_context_val val push_named : Context.Named.Declaration.t -> env -> env val push_named_context : Context.Named.t -> env -> env val push_named_context_val : Context.Named.Declaration.t -> named_context_val -> named_context_val val lookup_named : variable -> env -> Context.Named.Declaration.t val lookup_named_val : variable -> named_context_val -> Context.Named.Declaration.t val evaluable_named : variable -> env -> bool val named_type : variable -> env -> types val named_body : variable -> env -> constr option * { 6 Recurrence on [ named_context ] : older declarations processed first } val fold_named_context : (env -> Context.Named.Declaration.t -> 'a -> 'a) -> env -> init:'a -> 'a * Recurrence on [ named_context ] starting from younger val fold_named_context_reverse : ('a -> Context.Named.Declaration.t -> 'a) -> init:'a -> env -> 'a val reset_context : env -> env val reset_with_named_context : named_context_val -> env -> env val pop_rel_context : int -> env -> env * { 5 Global constants } { 6 Add entries to global environment } {6 Add entries to global environment } *) val add_constant : constant -> constant_body -> env -> env val add_constant_key : constant -> constant_body -> Pre_env.link_info -> env -> env val lookup_constant : constant -> env -> constant_body val evaluable_constant : constant -> env -> bool val polymorphic_constant : constant -> env -> bool val polymorphic_pconstant : pconstant -> env -> bool val type_in_type_constant : constant -> env -> bool val template_polymorphic_constant : constant -> env -> bool val template_polymorphic_pconstant : pconstant -> env -> bool * { 6 ... } * [ constant_value env c ] raises [ NotEvaluableConst Opaque ] if [ c ] is opaque and [ ] if it has no body and [ NotEvaluableConst IsProj ] if [ c ] is a projection and [ Not_found ] if it does not exist in [ env ] [c] is opaque and [NotEvaluableConst NoBody] if it has no body and [NotEvaluableConst IsProj] if [c] is a projection and [Not_found] if it does not exist in [env] *) type const_evaluation_result = NoBody | Opaque | IsProj exception NotEvaluableConst of const_evaluation_result val constant_value : env -> constant puniverses -> constr constrained val constant_type : env -> constant puniverses -> constant_type constrained val constant_opt_value : env -> constant puniverses -> (constr * Univ.constraints) option val constant_value_and_type : env -> constant puniverses -> constr option * constant_type * Univ.constraints val constant_context : env -> constant -> Univ.universe_context val constant_value_in : env -> constant puniverses -> constr val constant_type_in : env -> constant puniverses -> constant_type val constant_opt_value_in : env -> constant puniverses -> constr option * { 6 Primitive projections } val lookup_projection : Names.projection -> env -> projection_body val is_projection : constant -> env -> bool * { 5 Inductive types } val add_mind_key : mutual_inductive -> Pre_env.mind_key -> env -> env val add_mind : mutual_inductive -> mutual_inductive_body -> env -> env val lookup_mind : mutual_inductive -> env -> mutual_inductive_body val polymorphic_ind : inductive -> env -> bool val polymorphic_pind : pinductive -> env -> bool val type_in_type_ind : inductive -> env -> bool val template_polymorphic_ind : inductive -> env -> bool val template_polymorphic_pind : pinductive -> env -> bool * { 5 Modules } val add_modtype : module_type_body -> env -> env val shallow_add_module : module_body -> env -> env val lookup_module : module_path -> env -> module_body val lookup_modtype : module_path -> env -> module_type_body * { 5 Universe constraints } * Add universe constraints to the environment . @raises UniverseInconsistency @raises UniverseInconsistency *) val add_constraints : Univ.constraints -> env -> env val check_constraints : Univ.constraints -> env -> bool val push_context : ?strict:bool -> Univ.universe_context -> env -> env val push_context_set : ?strict:bool -> Univ.universe_context_set -> env -> env val push_constraints_to_env : 'a Univ.constrained -> env -> env val set_engagement : engagement -> env -> env val set_typing_flags : typing_flags -> env -> env * { 6 Sets of referred section variables } [ global_vars_set env c ] returns the list of [ i d ] 's occurring either directly as [ Var i d ] in [ c ] or indirectly as a section variable dependent in a global reference occurring in [ c ] [global_vars_set env c] returns the list of [id]'s occurring either directly as [Var id] in [c] or indirectly as a section variable dependent in a global reference occurring in [c] *) val global_vars_set : env -> constr -> Id.Set.t val vars_of_global : env -> constr -> Id.Set.t val really_needed : env -> Id.Set.t -> Id.Set.t val keep_hyps : env -> Id.Set.t -> Context.section_context * { 5 Unsafe judgments . } We introduce here the pre - type of judgments , which is actually only a datatype to store a term with its type and the type of its type . We introduce here the pre-type of judgments, which is actually only a datatype to store a term with its type and the type of its type. *) type unsafe_judgment = { uj_val : constr; uj_type : types } val make_judge : constr -> types -> unsafe_judgment val j_val : unsafe_judgment -> constr val j_type : unsafe_judgment -> types type unsafe_type_judgment = { utj_val : constr; utj_type : sorts } val compile_constant_body : env -> constant_universes option -> constant_def -> Cemitcodes.body_code option exception Hyp_not_found val apply_to_hyp : named_context_val -> variable -> (Context.Named.t -> Context.Named.Declaration.t -> Context.Named.t -> Context.Named.Declaration.t) -> named_context_val val remove_hyps : Id.Set.t -> (Context.Named.Declaration.t -> Context.Named.Declaration.t) -> (Pre_env.lazy_val -> Pre_env.lazy_val) -> named_context_val -> named_context_val open Retroknowledge val retroknowledge : (retroknowledge->'a) -> env -> 'a val registered : env -> field -> bool val register : env -> field -> Retroknowledge.entry -> env * Native compiler val no_link_info : Pre_env.link_info
20f35728ec14439c46d88b1c9daee875e898a14cb1baa7b86cb64a9282640456
laurocaetano/programming-in-haskell
2.hs
-- | Without looking at the definitions from the standard prelude, define the | higher - order functions all , any , takeWhile , and dropWhile . all' :: (a -> Bool) -> [a] -> Bool all' p = and . map p any' :: (a -> Bool) -> [a] -> Bool any' p = or . map p takeWhile' :: (a -> Bool) -> [a] -> [a] takeWhile' p [] = [] takeWhile' p (x:xs) | p x = x : takeWhile' p xs | otherwise = [] dropWhile' :: (a -> Bool) -> [a] -> [a] dropWhile' _ [] = [] dropWhile' p (x:xs) | p x = dropWhile' p xs | otherwise = x : xs
null
https://raw.githubusercontent.com/laurocaetano/programming-in-haskell/8b54f802c3949fab8bcb7460ab37229f0c52449a/ch-07/2.hs
haskell
| Without looking at the definitions from the standard prelude, define the
| higher - order functions all , any , takeWhile , and dropWhile . all' :: (a -> Bool) -> [a] -> Bool all' p = and . map p any' :: (a -> Bool) -> [a] -> Bool any' p = or . map p takeWhile' :: (a -> Bool) -> [a] -> [a] takeWhile' p [] = [] takeWhile' p (x:xs) | p x = x : takeWhile' p xs | otherwise = [] dropWhile' :: (a -> Bool) -> [a] -> [a] dropWhile' _ [] = [] dropWhile' p (x:xs) | p x = dropWhile' p xs | otherwise = x : xs
e2ab8d8a9d090e5ab01038d07a0cae1485c136d394431f8325ec08b1b5b716d7
bobbae/gosling-emacs
pascal.ml
(progn ;;; Pretty Brain Damaged at this point! (defun (electric-pascal-mode (use-abbrev-table "Pascal") (use-syntax-table "Pascal") (Do-Pascal-Bindings) (setq mode-string "philips' pascal")) (Make-Pascal-Abbrevs (use-abbrev-table "Pascal") (define-local-abbrev "and" "AND") (define-local-abbrev "array" "ARRAY") (define-local-abbrev "begin" "BEGIN") (define-local-abbrev "boolean" "BOOLEAN") (define-local-abbrev "logical" "BOOLEAN") (define-local-abbrev "cand" "CAND") (define-local-abbrev "case" "CASE") (define-local-abbrev "chr" "CHR") (define-local-abbrev "const" "CONST") (define-local-abbrev "cor" "COR") (define-local-abbrev "div" "DIV") (define-local-abbrev "do" "DO") (define-local-abbrev "downto" "DOWNTO") (define-local-abbrev "else" "ELSE") (define-local-abbrev "end" "END") (define-local-abbrev "exit" "EXIT") (define-local-abbrev "exports" "EXPORTS") (define-local-abbrev "false" "FALSE") (define-local-abbrev "file" "FILE") (define-local-abbrev "for" "FOR") (define-local-abbrev "forward" "FORWARD") (define-local-abbrev "from" "FROM") (define-local-abbrev "fun" "FUNCTION") (define-local-abbrev "function" "FUNCTION") (define-local-abbrev "get" "GET") (define-local-abbrev "goto" "GOTO") (define-local-abbrev "if" "IF") (define-local-abbrev "imports" "IMPORTS") (define-local-abbrev "in" "IN") (define-local-abbrev "input" "INPUT") (define-local-abbrev "integer" "INTEGER") (define-local-abbrev "label" "LABEL") (define-local-abbrev "long" "LONG") (define-local-abbrev "mod" "MOD") (define-local-abbrev "module" "MODULE") (define-local-abbrev "new" "NEW") (define-local-abbrev "nil" "NIL") (define-local-abbrev "null" "NIL") (define-local-abbrev "not" "NOT") (define-local-abbrev "of" "OF") (define-local-abbrev "or" "OR") (define-local-abbrev "ord" "ORD") (define-local-abbrev "otherwise" "OTHERWISE") (define-local-abbrev "output" "OUTPUT") (define-local-abbrev "packed" "PACKED") (define-local-abbrev "private" "PRIVATE") (define-local-abbrev "proc" "PROCEDURE") (define-local-abbrev "procedure" "PROCEDURE") (define-local-abbrev "program" "PROGRAM") (define-local-abbrev "put" "PUT") (define-local-abbrev "read" "READ") (define-local-abbrev "readln" "READLN") (define-local-abbrev "real" "REAL") (define-local-abbrev "record" "RECORD") (define-local-abbrev "repeat" "REPEAT") (define-local-abbrev "reset" "RESET") (define-local-abbrev "rewrite" "REWRITE") (define-local-abbrev "set" "SET") (define-local-abbrev "string" "STRING") (define-local-abbrev "text" "TEXT") (define-local-abbrev "then" "THEN") (define-local-abbrev "to" "TO") (define-local-abbrev "true" "TRUE") (define-local-abbrev "type" "TYPE") (define-local-abbrev "until" "UNTIL") (define-local-abbrev "var" "VAR") (define-local-abbrev "while" "WHILE") (define-local-abbrev "with" "WITH") (define-local-abbrev "write" "WRITE") (define-local-abbrev "writeln" "WRITELN") ) ;;; End of Make-Pascal-Abbrevs (Do-Pascal-Bindings (local-bind-to-key "Enter-Comment-Mode" '{') (local-bind-to-key "Leave-Comment-Mode" '}') (local-bind-to-key "Enter-Fuzzy-Comment" '*') (local-bind-to-key "End-Fuzzy-Comment" ')') (local-bind-to-key "Toggle-Comment-Mode" 39) ; Single Quote ) ;;; End of Do-Pascal-Bindings (Toggle-Comment-Mode (if (= abbrev-mode 0) (set "abbrev-mode" 1) (set "abbrev-mode" 0)) (insert-character (last-key-struck)) ) ;;; End of Toggle-Comment-Mode (Enter-Comment-Mode (set "abbrev-mode" 0) (insert-character (last-key-struck)) ) ;;; End of Enter-Comment-Mode (Leave-Comment-Mode (set "abbrev-mode" 1) (insert-character (last-key-struck)) ) ;;; End of Leave-Comment-Mode (Enter-Fuzzy-Comment last-key prev-char (setq last-key (last-key-struck)) (setq prev-char (preceding-char)) (if (& (= last-key 42) ; 42 = Asterisk (= prev-char 40)) ; 40 = open paren (progn (set "abbrev-mode" 0) (insert-string "*")) (insert-character last-key))) (End-Fuzzy-Comment last-key prev-char (setq last-key (last-key-struck)) (setq prev-char (preceding-char)) (if (& (= last-key 41) ; 41 = close paren (= prev-char 42)) ; 42 = Asterisk (set "abbrev-mode" 1)) (insert-character last-key)) (Pascal-Skeleton name type Prompt colno (setq Prompt ": Pascal-Skeleton ") (setq name (get-tty-string (concat Prompt "name: "))) (if (= name "") (error-occured "Aborted.")) (setq colno (current-column)) (setq type (get-tty-string (concat Prompt name " Result: "))) (if (= type "") (progn pos ; We have a procedure (insert-character 10)(to-col colno) (insert-string (concat "PROCEDURE " name )) (save-excursion (insert-string ";") (insert-character 10)(to-col colno) (insert-string "BEGIN") (insert-character 10)(to-col colno) (insert-string (concat "END; (* " name " *)")) (insert-character 10))) (progn ; We have a function (insert-character 10)(to-col colno) (insert-string (concat "FUNCTION " name)) (save-excursion (insert-string (concat ": " type ";")) (insert-character 10)(to-col colno) (insert-string "VAR") (insert-character 10)(to-col (+ colno 4)) (insert-string (concat "Answer: " type ";")) (insert-character 10)(to-col colno) (insert-string "BEGIN") (insert-character 10)(to-col (+ colno 4)) (insert-string (concat name " := Answer;")) (insert-character 10)(to-col colno) (insert-string (concat "END; (* " name " *)")) (insert-character 10)))) );;; End of Pascal-Skeleton ) ;;; End of Massive Defun (Make-Pascal-Abbrevs) (electric-pascal-mode) (use-syntax-table "Pascal") (modify-syntax-entry "w _") )
null
https://raw.githubusercontent.com/bobbae/gosling-emacs/8fdda532abbffb0c952251a0b5a4857e0f27495a/lib/maclib/pascal.ml
ocaml
(progn ;;; Pretty Brain Damaged at this point! (defun (electric-pascal-mode (use-abbrev-table "Pascal") (use-syntax-table "Pascal") (Do-Pascal-Bindings) (setq mode-string "philips' pascal")) (Make-Pascal-Abbrevs (use-abbrev-table "Pascal") (define-local-abbrev "and" "AND") (define-local-abbrev "array" "ARRAY") (define-local-abbrev "begin" "BEGIN") (define-local-abbrev "boolean" "BOOLEAN") (define-local-abbrev "logical" "BOOLEAN") (define-local-abbrev "cand" "CAND") (define-local-abbrev "case" "CASE") (define-local-abbrev "chr" "CHR") (define-local-abbrev "const" "CONST") (define-local-abbrev "cor" "COR") (define-local-abbrev "div" "DIV") (define-local-abbrev "do" "DO") (define-local-abbrev "downto" "DOWNTO") (define-local-abbrev "else" "ELSE") (define-local-abbrev "end" "END") (define-local-abbrev "exit" "EXIT") (define-local-abbrev "exports" "EXPORTS") (define-local-abbrev "false" "FALSE") (define-local-abbrev "file" "FILE") (define-local-abbrev "for" "FOR") (define-local-abbrev "forward" "FORWARD") (define-local-abbrev "from" "FROM") (define-local-abbrev "fun" "FUNCTION") (define-local-abbrev "function" "FUNCTION") (define-local-abbrev "get" "GET") (define-local-abbrev "goto" "GOTO") (define-local-abbrev "if" "IF") (define-local-abbrev "imports" "IMPORTS") (define-local-abbrev "in" "IN") (define-local-abbrev "input" "INPUT") (define-local-abbrev "integer" "INTEGER") (define-local-abbrev "label" "LABEL") (define-local-abbrev "long" "LONG") (define-local-abbrev "mod" "MOD") (define-local-abbrev "module" "MODULE") (define-local-abbrev "new" "NEW") (define-local-abbrev "nil" "NIL") (define-local-abbrev "null" "NIL") (define-local-abbrev "not" "NOT") (define-local-abbrev "of" "OF") (define-local-abbrev "or" "OR") (define-local-abbrev "ord" "ORD") (define-local-abbrev "otherwise" "OTHERWISE") (define-local-abbrev "output" "OUTPUT") (define-local-abbrev "packed" "PACKED") (define-local-abbrev "private" "PRIVATE") (define-local-abbrev "proc" "PROCEDURE") (define-local-abbrev "procedure" "PROCEDURE") (define-local-abbrev "program" "PROGRAM") (define-local-abbrev "put" "PUT") (define-local-abbrev "read" "READ") (define-local-abbrev "readln" "READLN") (define-local-abbrev "real" "REAL") (define-local-abbrev "record" "RECORD") (define-local-abbrev "repeat" "REPEAT") (define-local-abbrev "reset" "RESET") (define-local-abbrev "rewrite" "REWRITE") (define-local-abbrev "set" "SET") (define-local-abbrev "string" "STRING") (define-local-abbrev "text" "TEXT") (define-local-abbrev "then" "THEN") (define-local-abbrev "to" "TO") (define-local-abbrev "true" "TRUE") (define-local-abbrev "type" "TYPE") (define-local-abbrev "until" "UNTIL") (define-local-abbrev "var" "VAR") (define-local-abbrev "while" "WHILE") (define-local-abbrev "with" "WITH") (define-local-abbrev "write" "WRITE") (define-local-abbrev "writeln" "WRITELN") ) ;;; End of Make-Pascal-Abbrevs (Do-Pascal-Bindings (local-bind-to-key "Enter-Comment-Mode" '{') (local-bind-to-key "Leave-Comment-Mode" '}') (local-bind-to-key "Enter-Fuzzy-Comment" '*') (local-bind-to-key "End-Fuzzy-Comment" ')') (local-bind-to-key "Toggle-Comment-Mode" 39) ; Single Quote ) ;;; End of Do-Pascal-Bindings (Toggle-Comment-Mode (if (= abbrev-mode 0) (set "abbrev-mode" 1) (set "abbrev-mode" 0)) (insert-character (last-key-struck)) ) ;;; End of Toggle-Comment-Mode (Enter-Comment-Mode (set "abbrev-mode" 0) (insert-character (last-key-struck)) ) ;;; End of Enter-Comment-Mode (Leave-Comment-Mode (set "abbrev-mode" 1) (insert-character (last-key-struck)) ) ;;; End of Leave-Comment-Mode (Enter-Fuzzy-Comment last-key prev-char (setq last-key (last-key-struck)) (setq prev-char (preceding-char)) (if (& (= last-key 42) ; 42 = Asterisk (= prev-char 40)) ; 40 = open paren (progn (set "abbrev-mode" 0) (insert-string "*")) (insert-character last-key))) (End-Fuzzy-Comment last-key prev-char (setq last-key (last-key-struck)) (setq prev-char (preceding-char)) (if (& (= last-key 41) ; 41 = close paren (= prev-char 42)) ; 42 = Asterisk (set "abbrev-mode" 1)) (insert-character last-key)) (Pascal-Skeleton name type Prompt colno (setq Prompt ": Pascal-Skeleton ") (setq name (get-tty-string (concat Prompt "name: "))) (if (= name "") (error-occured "Aborted.")) (setq colno (current-column)) (setq type (get-tty-string (concat Prompt name " Result: "))) (if (= type "") (progn pos ; We have a procedure (insert-character 10)(to-col colno) (insert-string (concat "PROCEDURE " name )) (save-excursion (insert-string ";") (insert-character 10)(to-col colno) (insert-string "BEGIN") (insert-character 10)(to-col colno) (insert-string (concat "END; (* " name " *)")) (insert-character 10))) (progn ; We have a function (insert-character 10)(to-col colno) (insert-string (concat "FUNCTION " name)) (save-excursion (insert-string (concat ": " type ";")) (insert-character 10)(to-col colno) (insert-string "VAR") (insert-character 10)(to-col (+ colno 4)) (insert-string (concat "Answer: " type ";")) (insert-character 10)(to-col colno) (insert-string "BEGIN") (insert-character 10)(to-col (+ colno 4)) (insert-string (concat name " := Answer;")) (insert-character 10)(to-col colno) (insert-string (concat "END; (* " name " *)")) (insert-character 10)))) );;; End of Pascal-Skeleton ) ;;; End of Massive Defun (Make-Pascal-Abbrevs) (electric-pascal-mode) (use-syntax-table "Pascal") (modify-syntax-entry "w _") )
32caff3fa91106ef09aafa259549ad8e5c743f89271eb846ae2a11334448f746
AstRonin/sgi
sgi_n2o_fcgi_handler.erl
-module(sgi_n2o_fcgi_handler). -include_lib("n2o/include/wf.hrl"). -include_lib("stdlib/include/ms_transform.hrl"). %% API -export([init/0, send/0, send/1, do_send/3, stop/0]). -define(PROTO_CGI, <<"CGI/1.1">>). -define(PROTO_HTTP, <<"HTTP/1.1">>). -define(DEF_RESP_STATUS, 200). -define(DEF_TIMEOUT, 600000). -define(WS_URL_PARTS, (get(sgi_n2o_fcgi_ws_url_parts))). -type http() :: #http{}. -type htuple() :: {binary(), binary()}. -record(ws_url_parts, {scheme, userInfo, host, port, path, query}). -record(response_headers, {buff = [], ended = false}). %% =========================================================== %% API %% =========================================================== -spec init() -> ok | {error, term()}. init() -> ok. -spec stop() -> ok | {error, term()}. stop() -> ok. send() -> send(#http{}). -spec send(http()) -> {binary(), integer(), list()}. send(Http) -> wf:state(status, ?DEF_RESP_STATUS), make_ws_url_parts(Http), vhosts(), {_, Body} = bs(Http), CGIParams = get_params(Http), {RetH, Ret} = case sgi_cluster:is_use() of true -> sgi_cluster:send(sgi_n2o_fcgi_handler, do_send, [CGIParams, has_body(Http), Body]); _ -> do_send(CGIParams, has_body(Http), Body) end, set_header_to_cowboy(RetH, 0), terminate(), %% @todo Return headers from cgi because cowboy don't give access to resp_headers {Ret, wf:state(status), RetH}. { iolist_to_binary(Ret ) , wf : state(status ) , RetH } . do_send(CGIParams, HasBody, Body) -> {ok, Pid} = sgi_fcgi:start(), Timer = erlang:send_after(wf:config(sgi, response_timeout, ?DEF_TIMEOUT), self(), {sgi_fcgi_timeout, Pid}), Pid ! {overall, self(), CGIParams, HasBody, Body}, Ret = ret(), RetH = get_response_headers(), sgi:ct(Timer), sgi_fcgi:stop(Pid), {RetH, iolist_to_binary(Ret)}. %% =========================================================== %% Prepare Request %% =========================================================== -spec vhosts() -> ok. vhosts() -> Vs = wf:config(sgi, vhosts, []), vhosts(Vs). vhosts([H|T]) -> S = sgi:mv(server_name, H, ""), A = sgi:mv(alias, H, ""), case wf:to_list(host()) of Host when Host =:= S orelse Host =:= A -> wf:state(vhost, H), ok; _ -> vhosts(T) end; vhosts([]) -> wf:state(vhost, []), ok. -spec vhost(atom()) -> term(). vhost(Key) -> vhost(Key, ""). -spec vhost(atom(), []) -> term(). vhost(Key, Def) -> sgi:mv(Key, wf:state(vhost), Def). -spec get_params(http()) -> list(). get_params(Http) -> {{PeerIP, PeerPort}, _} = cowboy_req:peer(?REQ), Path = path(), QS = qs(), Root = vhost(root), DefScript = wf:to_binary(vhost(index, "index.php")), {FPath, FScript, FPathInfo} = final_path(Path, DefScript), @todo Waiting of %% HHttps = case HTTPS ? of <<"https">> -> [{<<"HTTPS">>, <<"'on'">>}]; _ -> [] end, HHttps = [], [{<<"GATEWAY_INTERFACE">>, ?PROTO_CGI}, {<<"QUERY_STRING">>, QS}, {<<"REMOTE_ADDR">>, wf:to_binary(inet:ntoa(PeerIP))}, {<<"REMOTE_PORT">>, wf:to_binary(PeerPort)}, {<<"REQUEST_METHOD">>, method(Http)}, {<<"REQUEST_URI">>, <<Path/binary, (case QS of <<>> -> <<>>; V -> <<"?", V/binary>> end)/binary>>}, {<<"DOCUMENT_ROOT">>, wf:to_binary(Root)}, {<<"SCRIPT_FILENAME">>, wf:to_binary([vhost(root), FPath, "/", FScript])}, {<<"SCRIPT_NAME">>, wf:to_binary(["/", FScript])}, %% {<<"SERVER_ADDR">>, <<"">>}, % I don't now how cowboy return self ip {<<"SERVER_NAME">>, wf:to_binary(vhost(server_name, wf:config(sgi, address, "")))}, {<<"SERVER_PORT">>, wf:to_binary(port())}, {<<"SERVER_PROTOCOL">>, ?PROTO_HTTP}, {<<"SERVER_SOFTWARE">>, <<"cowboy">>}] ++ path_info_headers(Root, FPathInfo) ++ HHttps ++ http_headers(Http) ++ post_headers(Http). -spec make_ws_url_parts(http()) -> ok. make_ws_url_parts(#http{url = undefined}) -> wf:state(sgi_n2o_fcgi_ws_url_parts, #ws_url_parts{}), ok; make_ws_url_parts(#http{url = Url}) -> case http_uri:parse(wf:to_list(Url), [{scheme_defaults, [ {http,80},{https,443},{ftp,21},{ssh,22},{sftp,22},{tftp,69},{ws,80},{wss,443}]}]) of {ok, {Scheme, UserInfo, Host, Port, Path, Query}} -> R = #ws_url_parts{scheme=Scheme,userInfo=UserInfo,host=Host,port=Port,path=Path,query=Query}, wf:state(sgi_n2o_fcgi_ws_url_parts, R), ok; {error, _Reason} -> wf:state(sgi_n2o_fcgi_ws_url_parts, #ws_url_parts{}), ok end. -spec external_headers(http()) -> list(). external_headers(#http{headers = Hs}) -> case Hs of undefined -> []; _ -> Hs end. -spec external_host_header() -> htuple() | undefined. external_host_header() -> case ?WS_URL_PARTS#ws_url_parts.host of undefined -> undefined; Host -> Port = case ?WS_URL_PARTS#ws_url_parts.port of P when P =:= 80 orelse P =:= 443 -> ""; P1 -> ":" ++ wf:to_list(P1) end, {<<"host">>, wf:to_binary([Host, Port])} end. -spec external_ajax_header() -> htuple() | undefined. external_ajax_header() -> case ?WS_URL_PARTS#ws_url_parts.host of undefined -> undefined; _ -> {<<"x-requested-with">>, <<"XMLHttpRequest">>} end. -spec post_headers(http()) -> [htuple()] | []. post_headers(Http) -> case has_body(Http) of true -> [{<<"CONTENT_TYPE">>, <<"application/x-www-form-urlencoded">>}, {<<"CONTENT_LENGTH">>, wf:to_binary(body_length())}]; _ -> [] end. -spec path_info_headers(string(), string()) -> [htuple()] | []. path_info_headers(Root, FPathInfo) -> case FPathInfo of [] -> []; _ -> [{<<"PATH_INFO">>, wf:to_binary(FPathInfo)}, {<<"PATH_TRANSLATED">>, wf:to_binary([Root, FPathInfo])}] end. -spec host() -> binary() | undefined. host() -> case ?WS_URL_PARTS#ws_url_parts.host of undefined -> case cowboy_req:host_info(?REQ) of {undefined, _} -> {H , _} = cowboy_req:host(?REQ), H; {H , _} -> H end; V -> V end. -spec method(http()) -> binary(). method(Http) -> case Http#http.method of undefined -> {M, _} = cowboy_req:method(?REQ), M; V -> to_upper(V) end. -spec has_body(http()) -> true | false. has_body(Http) -> case method(Http) of M when M =:= <<"POST">>; M =:= <<"PUT">>; M =:= <<"PATCH">> -> true; _ -> false end. -spec body_length() -> non_neg_integer(). body_length() -> case wf:state(sgi_n2o_fcgi_body_length) of L when is_integer(L) -> L; _ -> case cowboy_req:body_length(?REQ) of {undefined, _} -> 0; {CL, _} -> CL end end. -spec port() -> inet:port_number(). port() -> case ?WS_URL_PARTS#ws_url_parts.port of undefined -> {P, _} = cowboy_req:port(?REQ), P; V -> V end. -spec path() -> binary(). path() -> case ?WS_URL_PARTS#ws_url_parts.path of undefined -> get_cowboy_path(); V -> wf:to_binary(V) end. -spec qs() -> binary(). qs() -> case ?WS_URL_PARTS#ws_url_parts.query of undefined -> {Q, _} = cowboy_req:qs(?REQ), Q; V -> wf:to_binary(string:strip(V, left, $?)) end. -spec bs(http()) -> {ok, binary()} | {empty, <<>>}. bs(#http{body = undefined}) -> case cowboy_req:has_body(?REQ) of true -> case cowboy_req:body(?REQ) of {ok, CB, _} -> {ok, CB}; _ -> {empty, <<>>} end; _ -> {empty, <<>>} end; bs(#http{body = B}) when B =:= <<>> orelse B =:= "" -> {empty, <<>>}; bs(#http{body = B} = Http) -> case has_body(Http) of true -> wf:state(sgi_n2o_fcgi_body_length, byte_size(B)), {ok, B}; _ -> {empty, <<>>} end. -spec http_headers(http()) -> [htuple()]. http_headers(Params) -> {H, _} = cowboy_req:headers(?REQ), H1 = case external_host_header() of undefined -> H; V -> lists:keystore(<<"host">>, 1, H, V) end, H2 = case external_ajax_header() of undefined -> H1; V1 -> lists:keystore(<<"x-requested-with">>, 1, H1, V1) end, H3 = H2 ++ external_headers(Params), http_headers(H3, []). http_headers([H|T], New) -> K = element(1, H), K2 = "HTTP_" ++ string:to_upper(string:join(string:tokens(wf:to_list(K), "-"), "_")), http_headers(T, New ++ [{wf:to_binary(K2), element(2, H)}]); http_headers([], New) -> New. -spec get_cowboy_path() -> binary(). get_cowboy_path() -> case cowboy_req:path_info(?REQ) of {undefined, _} -> case cowboy_req:path(?REQ) of {undefined, _} -> <<"/">>; {P, _} -> P end; {P, _} -> <<"/", (binary_join(P, <<"/">>))/binary>> end. -spec final_path(binary(), string()) -> {string(), string(), string()}. final_path(CowboyPath, DefScript) -> {Path, Script, PathInfo} = case explode_path(CowboyPath) of {path, P} -> {P, DefScript, []}; {path_parts, P, S, I} -> {P, S, I} end, {FPath, FScript} = case rewrite(Path ++ "/" ++ Script) of {true, P1} -> case explode_path(P1) of {path, P2} -> {P2, Script}; {path_parts, P2, S2, _} -> {P2, S2} end; {false, _} -> {Path, Script} end, {FPath, FScript, PathInfo}. -spec explode_path(Path :: binary()) -> {path, NewPath} | {path_parts, NewPath, Script, PathInfo} when NewPath :: string(), Script :: string(), PathInfo :: string(). explode_path(P) -> Path = wf:to_list(P), case string:str(Path, ".") of 0 -> {path, string:strip(Path, right, $/)}; _ -> Tokens = string:tokens(Path, "/"), {P1, H, I} = parse_path(Tokens, []), {path_parts, P1, H, I} end. -spec parse_path(list(), list()) -> {NewPath, Script, PathInfo} when NewPath :: string(), Script :: string() | [], PathInfo :: string() | []. parse_path([], []) -> {[], [], []}; parse_path([H|T], P) -> case string:str(H, ".") of 0 -> parse_path(T, P ++ "/" ++ H); _ -> {P, H, parse_info(T)} end; parse_path([], P) -> {P, [], []}. -spec parse_info(list()) -> string(). parse_info(L) -> parse_info(L, []). parse_info([H|T], I) -> parse_info(T, I ++ "/" ++ H); parse_info([], I) -> I. -spec rewrite(string()) -> {true, string()} | {false, string()}. rewrite(Subject) -> rewrite(Subject, vhost(rewrite, [])). rewrite(Subject, [RewRule|H]) -> case element(1, RewRule) of S when S =:= Subject orelse S =:= "*" -> {true, element(2, RewRule)}; _ -> rewrite(Subject, H) end; rewrite(Subject, []) -> {false, Subject}. %% =========================================================== %% Response %% =========================================================== -spec ret() -> iolist(). ret() -> receive {sgi_fcgi_return, Out, _Err} -> stdout(Out); sgi_fcgi_return_end -> []; {sgi_fcgi_return_error, Err} -> wf:error(?MODULE, "Connection error ~p~n", [Err]), update_response_headers([{<<"retry-after">>, <<"3600">>}], true), set_header_to_cowboy([{<<"retry - after " > > , < < " 3600 " > > } ] ) , wf:state(status, 503), []; {sgi_fcgi_timeout, Pid} -> sgi_fcgi:stop(Pid), wf:error(?MODULE, "Connect timeout to FastCGI ~n", []), update_response_headers([{<<"retry-after">>, <<"3600">>}], true), set_header_to_cowboy([{<<"retry - after " > > , < < " 3600 " > > } ] ) , wf:state(status, 503), [] end. -spec stdout(list()) -> iolist(). stdout(Data) -> case get_response_headers_ended() of true -> [Data | ret()]; _ -> {ok, Hs, B} = decode_result(Data), case Hs of [] -> skip; _ -> update_response_headers(Hs) end, [B | ret()] end. update_response_headers(Hs) -> update_response_headers(Hs, false). update_response_headers(Hs, Status) -> RespH1 = case wf:state(sgi_n2o_fcgi_response_headers) of undefined -> #response_headers{}; RespH -> RespH end, Status1 = case RespH1#response_headers.ended of true -> true; _ -> Status end, RespH2 = RespH1#response_headers{buff = lists:append([Hs, RespH1#response_headers.buff]), ended = Status1}, wf:state(sgi_n2o_fcgi_response_headers, RespH2). get_response_headers() -> case wf:state(sgi_n2o_fcgi_response_headers) of undefined -> []; H -> lists:reverse(H#response_headers.buff) end. get_response_headers_ended() -> case wf:state(sgi_n2o_fcgi_response_headers) of undefined -> false; H -> H#response_headers.ended end. get_response_header(K) -> sgi:pv(K, get_response_headers(), <<>>). -spec decode_result(Data) -> {ok, Headers, Body} | {error, term()} when Data :: binary(), Headers :: list(), Body :: binary(). decode_result(<<>>) -> {ok, [], <<>>}; decode_result(Data) -> decode_result(Data, []). decode_result(Data, AccH) -> case erlang:decode_packet(httph_bin, Data, []) of {ok, http_eoh, Rest} -> update_response_headers([], true), {ok, AccH, Rest}; {ok, {http_header,_,<<"X-CGI-",_NameRest>>,_,_Value}, Rest} -> decode_result(Rest, AccH); {ok, {http_header,_Len,Field,_,Value}, Rest} -> decode_result(Rest, [{wf:to_binary(Field),Value} | AccH]); {ok, {http_error,Value}, Rest} -> case get_response_headers() of [] -> Rep = binary:replace(Value,<<"\r\n">>,<<"">>), Tokens = string:tokens(wf:to_list(Rep), " "), Status = wf:to_binary(string:join(lists:nthtail(1,Tokens), " ")), decode_result(Rest, [{<<"Status">>,Status} | AccH]); _ -> {ok, AccH, Data} end; {more, undefined} -> {ok, AccH, Data}; {more, _} -> {ok, [], Data}; {error, R} -> {error, R} end. set_header_to_cowboy(Hs, _Len) -> case Hs of undefined -> ok; _ -> %% @todo Use these default headers, if server will not to do that. Hs1 = lists : , , [ { < < " content - length " > > , wf : to_binary(Len ) } ] ) , Hs2 = lists : , Hs1 , [ { < < " Content - Type">>,<<"text / html ; charset = UTF-8 " > > } ] ) , case wf:state(status) > 500 of true -> skip; _ -> S = case lists:keyfind(<<"Status">>, 1, Hs) of false -> ?DEF_RESP_STATUS; {_, <<Code:3/binary, _/binary>>} -> wf:to_integer(Code) end, wf:state(status, S) end, set_header_to_cowboy(Hs) end. set_header_to_cowboy([H|T]) -> wf:header(to_lower(element(1,H)), element(2,H)), set_header_to_cowboy(T); set_header_to_cowboy([]) -> ok. %% =========================================================== %% %% =========================================================== -spec binary_join([binary()], binary()) -> binary(). binary_join([], _Sep) -> <<>>; binary_join([Part], _Sep) -> Part; binary_join([Head|Tail], Sep) -> lists:foldl(fun (Value, Acc) -> <<Acc/binary, Sep/binary, Value/binary>> end, Head, Tail). @todo If using lib of Cowboy , then ... -include_lib("cowlib / include / cow_inline.hrl " ) . to_lower ( < < > > , Acc ) - > Acc ; to_lower(<<C , Rest / bits > > , Acc ) - > %% case C of ? INLINE_LOWERCASE(to_lower , Rest , Acc ) %% end. -spec to_lower(binary() | string() | atom()) -> binary(). to_lower(Bit) -> wf:to_binary(string:to_lower(wf:to_list(Bit))). -spec to_upper(binary() | string() | atom()) -> binary(). to_upper(V) -> wf:to_binary(string:to_upper(wf:to_list(V))). terminate() -> wf:state(vhost, []), wf:state(sgi_n2o_fcgi_ws_url_parts, undefined), wf:state(sgi_n2o_fcgi_body_length, undefined), wf:state(sgi_n2o_fcgi_response_headers, #response_headers{}).
null
https://raw.githubusercontent.com/AstRonin/sgi/3854b62b6ce46ba71abd1e76e9cf5200dc0b1df3/src/sgi_n2o_fcgi_handler.erl
erlang
API =========================================================== API =========================================================== @todo Return headers from cgi because cowboy don't give access to resp_headers =========================================================== Prepare Request =========================================================== HHttps = case HTTPS ? of <<"https">> -> [{<<"HTTPS">>, <<"'on'">>}]; _ -> [] end, {<<"SERVER_ADDR">>, <<"">>}, % I don't now how cowboy return self ip =========================================================== Response =========================================================== @todo Use these default headers, if server will not to do that. =========================================================== =========================================================== case C of end.
-module(sgi_n2o_fcgi_handler). -include_lib("n2o/include/wf.hrl"). -include_lib("stdlib/include/ms_transform.hrl"). -export([init/0, send/0, send/1, do_send/3, stop/0]). -define(PROTO_CGI, <<"CGI/1.1">>). -define(PROTO_HTTP, <<"HTTP/1.1">>). -define(DEF_RESP_STATUS, 200). -define(DEF_TIMEOUT, 600000). -define(WS_URL_PARTS, (get(sgi_n2o_fcgi_ws_url_parts))). -type http() :: #http{}. -type htuple() :: {binary(), binary()}. -record(ws_url_parts, {scheme, userInfo, host, port, path, query}). -record(response_headers, {buff = [], ended = false}). -spec init() -> ok | {error, term()}. init() -> ok. -spec stop() -> ok | {error, term()}. stop() -> ok. send() -> send(#http{}). -spec send(http()) -> {binary(), integer(), list()}. send(Http) -> wf:state(status, ?DEF_RESP_STATUS), make_ws_url_parts(Http), vhosts(), {_, Body} = bs(Http), CGIParams = get_params(Http), {RetH, Ret} = case sgi_cluster:is_use() of true -> sgi_cluster:send(sgi_n2o_fcgi_handler, do_send, [CGIParams, has_body(Http), Body]); _ -> do_send(CGIParams, has_body(Http), Body) end, set_header_to_cowboy(RetH, 0), terminate(), {Ret, wf:state(status), RetH}. { iolist_to_binary(Ret ) , wf : state(status ) , RetH } . do_send(CGIParams, HasBody, Body) -> {ok, Pid} = sgi_fcgi:start(), Timer = erlang:send_after(wf:config(sgi, response_timeout, ?DEF_TIMEOUT), self(), {sgi_fcgi_timeout, Pid}), Pid ! {overall, self(), CGIParams, HasBody, Body}, Ret = ret(), RetH = get_response_headers(), sgi:ct(Timer), sgi_fcgi:stop(Pid), {RetH, iolist_to_binary(Ret)}. -spec vhosts() -> ok. vhosts() -> Vs = wf:config(sgi, vhosts, []), vhosts(Vs). vhosts([H|T]) -> S = sgi:mv(server_name, H, ""), A = sgi:mv(alias, H, ""), case wf:to_list(host()) of Host when Host =:= S orelse Host =:= A -> wf:state(vhost, H), ok; _ -> vhosts(T) end; vhosts([]) -> wf:state(vhost, []), ok. -spec vhost(atom()) -> term(). vhost(Key) -> vhost(Key, ""). -spec vhost(atom(), []) -> term(). vhost(Key, Def) -> sgi:mv(Key, wf:state(vhost), Def). -spec get_params(http()) -> list(). get_params(Http) -> {{PeerIP, PeerPort}, _} = cowboy_req:peer(?REQ), Path = path(), QS = qs(), Root = vhost(root), DefScript = wf:to_binary(vhost(index, "index.php")), {FPath, FScript, FPathInfo} = final_path(Path, DefScript), @todo Waiting of HHttps = [], [{<<"GATEWAY_INTERFACE">>, ?PROTO_CGI}, {<<"QUERY_STRING">>, QS}, {<<"REMOTE_ADDR">>, wf:to_binary(inet:ntoa(PeerIP))}, {<<"REMOTE_PORT">>, wf:to_binary(PeerPort)}, {<<"REQUEST_METHOD">>, method(Http)}, {<<"REQUEST_URI">>, <<Path/binary, (case QS of <<>> -> <<>>; V -> <<"?", V/binary>> end)/binary>>}, {<<"DOCUMENT_ROOT">>, wf:to_binary(Root)}, {<<"SCRIPT_FILENAME">>, wf:to_binary([vhost(root), FPath, "/", FScript])}, {<<"SCRIPT_NAME">>, wf:to_binary(["/", FScript])}, {<<"SERVER_NAME">>, wf:to_binary(vhost(server_name, wf:config(sgi, address, "")))}, {<<"SERVER_PORT">>, wf:to_binary(port())}, {<<"SERVER_PROTOCOL">>, ?PROTO_HTTP}, {<<"SERVER_SOFTWARE">>, <<"cowboy">>}] ++ path_info_headers(Root, FPathInfo) ++ HHttps ++ http_headers(Http) ++ post_headers(Http). -spec make_ws_url_parts(http()) -> ok. make_ws_url_parts(#http{url = undefined}) -> wf:state(sgi_n2o_fcgi_ws_url_parts, #ws_url_parts{}), ok; make_ws_url_parts(#http{url = Url}) -> case http_uri:parse(wf:to_list(Url), [{scheme_defaults, [ {http,80},{https,443},{ftp,21},{ssh,22},{sftp,22},{tftp,69},{ws,80},{wss,443}]}]) of {ok, {Scheme, UserInfo, Host, Port, Path, Query}} -> R = #ws_url_parts{scheme=Scheme,userInfo=UserInfo,host=Host,port=Port,path=Path,query=Query}, wf:state(sgi_n2o_fcgi_ws_url_parts, R), ok; {error, _Reason} -> wf:state(sgi_n2o_fcgi_ws_url_parts, #ws_url_parts{}), ok end. -spec external_headers(http()) -> list(). external_headers(#http{headers = Hs}) -> case Hs of undefined -> []; _ -> Hs end. -spec external_host_header() -> htuple() | undefined. external_host_header() -> case ?WS_URL_PARTS#ws_url_parts.host of undefined -> undefined; Host -> Port = case ?WS_URL_PARTS#ws_url_parts.port of P when P =:= 80 orelse P =:= 443 -> ""; P1 -> ":" ++ wf:to_list(P1) end, {<<"host">>, wf:to_binary([Host, Port])} end. -spec external_ajax_header() -> htuple() | undefined. external_ajax_header() -> case ?WS_URL_PARTS#ws_url_parts.host of undefined -> undefined; _ -> {<<"x-requested-with">>, <<"XMLHttpRequest">>} end. -spec post_headers(http()) -> [htuple()] | []. post_headers(Http) -> case has_body(Http) of true -> [{<<"CONTENT_TYPE">>, <<"application/x-www-form-urlencoded">>}, {<<"CONTENT_LENGTH">>, wf:to_binary(body_length())}]; _ -> [] end. -spec path_info_headers(string(), string()) -> [htuple()] | []. path_info_headers(Root, FPathInfo) -> case FPathInfo of [] -> []; _ -> [{<<"PATH_INFO">>, wf:to_binary(FPathInfo)}, {<<"PATH_TRANSLATED">>, wf:to_binary([Root, FPathInfo])}] end. -spec host() -> binary() | undefined. host() -> case ?WS_URL_PARTS#ws_url_parts.host of undefined -> case cowboy_req:host_info(?REQ) of {undefined, _} -> {H , _} = cowboy_req:host(?REQ), H; {H , _} -> H end; V -> V end. -spec method(http()) -> binary(). method(Http) -> case Http#http.method of undefined -> {M, _} = cowboy_req:method(?REQ), M; V -> to_upper(V) end. -spec has_body(http()) -> true | false. has_body(Http) -> case method(Http) of M when M =:= <<"POST">>; M =:= <<"PUT">>; M =:= <<"PATCH">> -> true; _ -> false end. -spec body_length() -> non_neg_integer(). body_length() -> case wf:state(sgi_n2o_fcgi_body_length) of L when is_integer(L) -> L; _ -> case cowboy_req:body_length(?REQ) of {undefined, _} -> 0; {CL, _} -> CL end end. -spec port() -> inet:port_number(). port() -> case ?WS_URL_PARTS#ws_url_parts.port of undefined -> {P, _} = cowboy_req:port(?REQ), P; V -> V end. -spec path() -> binary(). path() -> case ?WS_URL_PARTS#ws_url_parts.path of undefined -> get_cowboy_path(); V -> wf:to_binary(V) end. -spec qs() -> binary(). qs() -> case ?WS_URL_PARTS#ws_url_parts.query of undefined -> {Q, _} = cowboy_req:qs(?REQ), Q; V -> wf:to_binary(string:strip(V, left, $?)) end. -spec bs(http()) -> {ok, binary()} | {empty, <<>>}. bs(#http{body = undefined}) -> case cowboy_req:has_body(?REQ) of true -> case cowboy_req:body(?REQ) of {ok, CB, _} -> {ok, CB}; _ -> {empty, <<>>} end; _ -> {empty, <<>>} end; bs(#http{body = B}) when B =:= <<>> orelse B =:= "" -> {empty, <<>>}; bs(#http{body = B} = Http) -> case has_body(Http) of true -> wf:state(sgi_n2o_fcgi_body_length, byte_size(B)), {ok, B}; _ -> {empty, <<>>} end. -spec http_headers(http()) -> [htuple()]. http_headers(Params) -> {H, _} = cowboy_req:headers(?REQ), H1 = case external_host_header() of undefined -> H; V -> lists:keystore(<<"host">>, 1, H, V) end, H2 = case external_ajax_header() of undefined -> H1; V1 -> lists:keystore(<<"x-requested-with">>, 1, H1, V1) end, H3 = H2 ++ external_headers(Params), http_headers(H3, []). http_headers([H|T], New) -> K = element(1, H), K2 = "HTTP_" ++ string:to_upper(string:join(string:tokens(wf:to_list(K), "-"), "_")), http_headers(T, New ++ [{wf:to_binary(K2), element(2, H)}]); http_headers([], New) -> New. -spec get_cowboy_path() -> binary(). get_cowboy_path() -> case cowboy_req:path_info(?REQ) of {undefined, _} -> case cowboy_req:path(?REQ) of {undefined, _} -> <<"/">>; {P, _} -> P end; {P, _} -> <<"/", (binary_join(P, <<"/">>))/binary>> end. -spec final_path(binary(), string()) -> {string(), string(), string()}. final_path(CowboyPath, DefScript) -> {Path, Script, PathInfo} = case explode_path(CowboyPath) of {path, P} -> {P, DefScript, []}; {path_parts, P, S, I} -> {P, S, I} end, {FPath, FScript} = case rewrite(Path ++ "/" ++ Script) of {true, P1} -> case explode_path(P1) of {path, P2} -> {P2, Script}; {path_parts, P2, S2, _} -> {P2, S2} end; {false, _} -> {Path, Script} end, {FPath, FScript, PathInfo}. -spec explode_path(Path :: binary()) -> {path, NewPath} | {path_parts, NewPath, Script, PathInfo} when NewPath :: string(), Script :: string(), PathInfo :: string(). explode_path(P) -> Path = wf:to_list(P), case string:str(Path, ".") of 0 -> {path, string:strip(Path, right, $/)}; _ -> Tokens = string:tokens(Path, "/"), {P1, H, I} = parse_path(Tokens, []), {path_parts, P1, H, I} end. -spec parse_path(list(), list()) -> {NewPath, Script, PathInfo} when NewPath :: string(), Script :: string() | [], PathInfo :: string() | []. parse_path([], []) -> {[], [], []}; parse_path([H|T], P) -> case string:str(H, ".") of 0 -> parse_path(T, P ++ "/" ++ H); _ -> {P, H, parse_info(T)} end; parse_path([], P) -> {P, [], []}. -spec parse_info(list()) -> string(). parse_info(L) -> parse_info(L, []). parse_info([H|T], I) -> parse_info(T, I ++ "/" ++ H); parse_info([], I) -> I. -spec rewrite(string()) -> {true, string()} | {false, string()}. rewrite(Subject) -> rewrite(Subject, vhost(rewrite, [])). rewrite(Subject, [RewRule|H]) -> case element(1, RewRule) of S when S =:= Subject orelse S =:= "*" -> {true, element(2, RewRule)}; _ -> rewrite(Subject, H) end; rewrite(Subject, []) -> {false, Subject}. -spec ret() -> iolist(). ret() -> receive {sgi_fcgi_return, Out, _Err} -> stdout(Out); sgi_fcgi_return_end -> []; {sgi_fcgi_return_error, Err} -> wf:error(?MODULE, "Connection error ~p~n", [Err]), update_response_headers([{<<"retry-after">>, <<"3600">>}], true), set_header_to_cowboy([{<<"retry - after " > > , < < " 3600 " > > } ] ) , wf:state(status, 503), []; {sgi_fcgi_timeout, Pid} -> sgi_fcgi:stop(Pid), wf:error(?MODULE, "Connect timeout to FastCGI ~n", []), update_response_headers([{<<"retry-after">>, <<"3600">>}], true), set_header_to_cowboy([{<<"retry - after " > > , < < " 3600 " > > } ] ) , wf:state(status, 503), [] end. -spec stdout(list()) -> iolist(). stdout(Data) -> case get_response_headers_ended() of true -> [Data | ret()]; _ -> {ok, Hs, B} = decode_result(Data), case Hs of [] -> skip; _ -> update_response_headers(Hs) end, [B | ret()] end. update_response_headers(Hs) -> update_response_headers(Hs, false). update_response_headers(Hs, Status) -> RespH1 = case wf:state(sgi_n2o_fcgi_response_headers) of undefined -> #response_headers{}; RespH -> RespH end, Status1 = case RespH1#response_headers.ended of true -> true; _ -> Status end, RespH2 = RespH1#response_headers{buff = lists:append([Hs, RespH1#response_headers.buff]), ended = Status1}, wf:state(sgi_n2o_fcgi_response_headers, RespH2). get_response_headers() -> case wf:state(sgi_n2o_fcgi_response_headers) of undefined -> []; H -> lists:reverse(H#response_headers.buff) end. get_response_headers_ended() -> case wf:state(sgi_n2o_fcgi_response_headers) of undefined -> false; H -> H#response_headers.ended end. get_response_header(K) -> sgi:pv(K, get_response_headers(), <<>>). -spec decode_result(Data) -> {ok, Headers, Body} | {error, term()} when Data :: binary(), Headers :: list(), Body :: binary(). decode_result(<<>>) -> {ok, [], <<>>}; decode_result(Data) -> decode_result(Data, []). decode_result(Data, AccH) -> case erlang:decode_packet(httph_bin, Data, []) of {ok, http_eoh, Rest} -> update_response_headers([], true), {ok, AccH, Rest}; {ok, {http_header,_,<<"X-CGI-",_NameRest>>,_,_Value}, Rest} -> decode_result(Rest, AccH); {ok, {http_header,_Len,Field,_,Value}, Rest} -> decode_result(Rest, [{wf:to_binary(Field),Value} | AccH]); {ok, {http_error,Value}, Rest} -> case get_response_headers() of [] -> Rep = binary:replace(Value,<<"\r\n">>,<<"">>), Tokens = string:tokens(wf:to_list(Rep), " "), Status = wf:to_binary(string:join(lists:nthtail(1,Tokens), " ")), decode_result(Rest, [{<<"Status">>,Status} | AccH]); _ -> {ok, AccH, Data} end; {more, undefined} -> {ok, AccH, Data}; {more, _} -> {ok, [], Data}; {error, R} -> {error, R} end. set_header_to_cowboy(Hs, _Len) -> case Hs of undefined -> ok; _ -> Hs1 = lists : , , [ { < < " content - length " > > , wf : to_binary(Len ) } ] ) , Hs2 = lists : , Hs1 , [ { < < " Content - Type">>,<<"text / html ; charset = UTF-8 " > > } ] ) , case wf:state(status) > 500 of true -> skip; _ -> S = case lists:keyfind(<<"Status">>, 1, Hs) of false -> ?DEF_RESP_STATUS; {_, <<Code:3/binary, _/binary>>} -> wf:to_integer(Code) end, wf:state(status, S) end, set_header_to_cowboy(Hs) end. set_header_to_cowboy([H|T]) -> wf:header(to_lower(element(1,H)), element(2,H)), set_header_to_cowboy(T); set_header_to_cowboy([]) -> ok. -spec binary_join([binary()], binary()) -> binary(). binary_join([], _Sep) -> <<>>; binary_join([Part], _Sep) -> Part; binary_join([Head|Tail], Sep) -> lists:foldl(fun (Value, Acc) -> <<Acc/binary, Sep/binary, Value/binary>> end, Head, Tail). @todo If using lib of Cowboy , then ... -include_lib("cowlib / include / cow_inline.hrl " ) . to_lower ( < < > > , Acc ) - > Acc ; to_lower(<<C , Rest / bits > > , Acc ) - > ? INLINE_LOWERCASE(to_lower , Rest , Acc ) -spec to_lower(binary() | string() | atom()) -> binary(). to_lower(Bit) -> wf:to_binary(string:to_lower(wf:to_list(Bit))). -spec to_upper(binary() | string() | atom()) -> binary(). to_upper(V) -> wf:to_binary(string:to_upper(wf:to_list(V))). terminate() -> wf:state(vhost, []), wf:state(sgi_n2o_fcgi_ws_url_parts, undefined), wf:state(sgi_n2o_fcgi_body_length, undefined), wf:state(sgi_n2o_fcgi_response_headers, #response_headers{}).
40667a44573cf7c319a92bbcb33ee984c39a5a3292e957b43e23c33ac9577827
flyingmachine/datomic-junk
datomic_junk.clj
" Eid " is taken from ; -of-datomic/blob/master/src/datomic/samples/query.clj (ns com.flyingmachine.datomic-junk (:require [datomic.api :as d])) (defn max1 [query-result] (assert (< (count query-result) 2)) (assert (< (count (first query-result)) 2)) (ffirst query-result)) Get i d whether from number or datomic ent (defprotocol Eid (e [_])) (extend-protocol Eid java.lang.Long (e [n] n) datomic.Entity (e [ent] (:db/id ent))) (defn ent "Datomic entity from id, or nil if none exists" [id db] (if-let [exists (max1 (d/q '[:find ?eid :in $ ?eid :where [?eid]] db (e id)))] (d/entity db exists) nil)) (defn ents [db results] (map (fn [result] (-> result first (ent db))) results)) (defn ent? [x] (instance? datomic.query.EntityMap x)) ;; The following functions help when retrieving entities when you ;; don't need to specify their relationships to other entities and you only have one input , the db (defn add-head [head seqs] (map #(into [head] %) seqs)) (defn single-eid-where "Used to build where clauses for functions below" [eid [attr-or-condition & conditions]] (add-head eid (concat [(flatten [attr-or-condition])] conditions))) (defn parse-conditions [eid conditions] (let [[where & opts] (partition-by #(or (= :in %) (= :inputs %)) conditions)] (merge {:where (single-eid-where eid where) :in ['$]} (reduce merge {} (map #(hash-map (ffirst %) (second %)) (partition 2 opts)))))) (defn single-eid-query [find eid conditions] (let [parsed-conditions (parse-conditions eid conditions)] (apply d/q (merge {:find find} (dissoc parsed-conditions :inputs)) (:inputs parsed-conditions)))) (defn no-relation-where "Used to build where clauses for functions below" [eid [attr-or-condition & conditions]] (add-head eid (concat [(flatten [attr-or-condition])] conditions))) (defn no-relation-query-map [find variable conditions] {:find find :where (no-relation-where variable conditions) :in ['$]}) (defn no-relation-query [db find variable conditions] (d/q (no-relation-query-map find variable conditions) db)) (defn eid-by "Return eid of first entity matching conditions" [db & conditions] (ffirst (no-relation-query db ['?x] '?x conditions))) (defn one "Return first entity matching conditions" [db & conditions] (if-let [id (apply eid-by db conditions)] (d/entity db id))) (defn all "All entities matching condititions" [db & conditions] (ents db (no-relation-query db ['?x] '?x conditions))) (defn ent-count [db & conditions] (or (ffirst (no-relation-query db '[(count ?x)] '?x conditions)) 0)) ;; Transaction helpers (defn tempids [& keys] (into {} (map #(vector %1 (d/tempid :db.part/user %2)) keys (iterate dec -1)))) (defn retractions [eids] (map #(vector :db.fn/retractEntity %) eids)) (defn retract [conn & eids] (d/transact conn (retractions eids))) (def t d/transact)
null
https://raw.githubusercontent.com/flyingmachine/datomic-junk/c5688686cd1a9f4b181e9ffc2478b913f578f347/src/com/flyingmachine/datomic_junk.clj
clojure
-of-datomic/blob/master/src/datomic/samples/query.clj The following functions help when retrieving entities when you don't need to specify their relationships to other entities Transaction helpers
" Eid " is taken from (ns com.flyingmachine.datomic-junk (:require [datomic.api :as d])) (defn max1 [query-result] (assert (< (count query-result) 2)) (assert (< (count (first query-result)) 2)) (ffirst query-result)) Get i d whether from number or datomic ent (defprotocol Eid (e [_])) (extend-protocol Eid java.lang.Long (e [n] n) datomic.Entity (e [ent] (:db/id ent))) (defn ent "Datomic entity from id, or nil if none exists" [id db] (if-let [exists (max1 (d/q '[:find ?eid :in $ ?eid :where [?eid]] db (e id)))] (d/entity db exists) nil)) (defn ents [db results] (map (fn [result] (-> result first (ent db))) results)) (defn ent? [x] (instance? datomic.query.EntityMap x)) and you only have one input , the db (defn add-head [head seqs] (map #(into [head] %) seqs)) (defn single-eid-where "Used to build where clauses for functions below" [eid [attr-or-condition & conditions]] (add-head eid (concat [(flatten [attr-or-condition])] conditions))) (defn parse-conditions [eid conditions] (let [[where & opts] (partition-by #(or (= :in %) (= :inputs %)) conditions)] (merge {:where (single-eid-where eid where) :in ['$]} (reduce merge {} (map #(hash-map (ffirst %) (second %)) (partition 2 opts)))))) (defn single-eid-query [find eid conditions] (let [parsed-conditions (parse-conditions eid conditions)] (apply d/q (merge {:find find} (dissoc parsed-conditions :inputs)) (:inputs parsed-conditions)))) (defn no-relation-where "Used to build where clauses for functions below" [eid [attr-or-condition & conditions]] (add-head eid (concat [(flatten [attr-or-condition])] conditions))) (defn no-relation-query-map [find variable conditions] {:find find :where (no-relation-where variable conditions) :in ['$]}) (defn no-relation-query [db find variable conditions] (d/q (no-relation-query-map find variable conditions) db)) (defn eid-by "Return eid of first entity matching conditions" [db & conditions] (ffirst (no-relation-query db ['?x] '?x conditions))) (defn one "Return first entity matching conditions" [db & conditions] (if-let [id (apply eid-by db conditions)] (d/entity db id))) (defn all "All entities matching condititions" [db & conditions] (ents db (no-relation-query db ['?x] '?x conditions))) (defn ent-count [db & conditions] (or (ffirst (no-relation-query db '[(count ?x)] '?x conditions)) 0)) (defn tempids [& keys] (into {} (map #(vector %1 (d/tempid :db.part/user %2)) keys (iterate dec -1)))) (defn retractions [eids] (map #(vector :db.fn/retractEntity %) eids)) (defn retract [conn & eids] (d/transact conn (retractions eids))) (def t d/transact)
57cd3de29df8a284d5b40b75190328cfd9c0e73e1c0b14175c14e41c21924078
rtoy/ansi-cl-tests
nstring-capitalize.lsp
;-*- Mode: Lisp -*- Author : Created : Thu Oct 3 21:38:49 2002 ;;;; Contains: Tests for NSTRING-CAPITALIZE (in-package :cl-test) (deftest nstring-capitalize.1 (let* ((s (copy-seq "abCd")) (s2 (nstring-capitalize s))) (values (eqt s s2) s)) t "Abcd") (deftest nstring-capitalize.2 (let* ((s (copy-seq "0adA2Cdd3wXy")) (s2 (nstring-capitalize s))) (values (eqt s s2) s)) t "0ada2cdd3wxy") (deftest nstring-capitalize.3 (let* ((s (copy-seq "1a")) (s2 (nstring-capitalize s))) (values (eqt s s2) s)) t "1a") (deftest nstring-capitalize.4 (let* ((s (copy-seq "a1a")) (s2 (nstring-capitalize s))) (values (eqt s s2) s)) t "A1a") (deftest nstring-capitalize.7 (let ((s "ABCDEF")) (loop for i from 0 to 5 collect (nstring-capitalize (copy-seq s) :start i))) ("Abcdef" "ABcdef" "ABCdef" "ABCDef" "ABCDEf" "ABCDEF")) (deftest nstring-capitalize.8 (let ((s "ABCDEF")) (loop for i from 0 to 5 collect (nstring-capitalize (copy-seq s) :start i :end nil))) ("Abcdef" "ABcdef" "ABCdef" "ABCDef" "ABCDEf" "ABCDEF")) (deftest nstring-capitalize.9 (let ((s "ABCDEF")) (loop for i from 0 to 6 collect (nstring-capitalize (copy-seq s) :end i))) ("ABCDEF" "ABCDEF" "AbCDEF" "AbcDEF" "AbcdEF" "AbcdeF" "Abcdef")) (deftest nstring-capitalize.10 (let ((s "ABCDEF")) (loop for i from 0 to 5 collect (loop for j from i to 6 collect (nstring-capitalize (copy-seq s) :start i :end j)))) (("ABCDEF" "ABCDEF" "AbCDEF" "AbcDEF" "AbcdEF" "AbcdeF" "Abcdef") ("ABCDEF" "ABCDEF" "ABcDEF" "ABcdEF" "ABcdeF" "ABcdef") ("ABCDEF" "ABCDEF" "ABCdEF" "ABCdeF" "ABCdef") ("ABCDEF" "ABCDEF" "ABCDeF" "ABCDef") ("ABCDEF" "ABCDEF" "ABCDEf") ("ABCDEF" "ABCDEF"))) (deftest nstring-capitalize.11 (nstring-capitalize "") "") (deftest nstring-capitalize.12 :notes (:nil-vectors-are-strings) (nstring-capitalize (make-array '(0) :element-type nil)) "") (deftest nstring-capitalize.13 (loop for type in '(standard-char base-char character) for s = (make-array '(10) :element-type type :fill-pointer 5 :initial-contents "aB0cDefGHi") collect (list (copy-seq s) (copy-seq (nstring-capitalize s)) (copy-seq s) (progn (setf (fill-pointer s) 10) (copy-seq s)) )) (("aB0cD" "Ab0cd" "Ab0cd" "Ab0cdefGHi") ("aB0cD" "Ab0cd" "Ab0cd" "Ab0cdefGHi") ("aB0cD" "Ab0cd" "Ab0cd" "Ab0cdefGHi"))) (deftest nstring-capitalize.14 (loop for type in '(standard-char base-char character) for s0 = (make-array '(10) :element-type type :initial-contents "zZaB0cDefG") for s = (make-array '(5) :element-type type :displaced-to s0 :displaced-index-offset 2) collect (list (copy-seq s) (nstring-capitalize s) (copy-seq s) s0)) (("aB0cD" "Ab0cd" "Ab0cd" "zZAb0cdefG") ("aB0cD" "Ab0cd" "Ab0cd" "zZAb0cdefG") ("aB0cD" "Ab0cd" "Ab0cd" "zZAb0cdefG"))) (deftest nstring-capitalize.15 (loop for type in '(standard-char base-char character) for s = (make-array '(5) :element-type type :adjustable t :initial-contents "aB0cD") collect (list (copy-seq s) (nstring-capitalize s) (copy-seq s))) (("aB0cD" "Ab0cd" "Ab0cd") ("aB0cD" "Ab0cd" "Ab0cd") ("aB0cD" "Ab0cd" "Ab0cd"))) ;;; Order of evaluation tests (deftest nstring-capitalize.order.1 (let ((i 0) a b c (s (copy-seq "abcdef"))) (values (nstring-capitalize (progn (setf a (incf i)) s) :start (progn (setf b (incf i)) 1) :end (progn (setf c (incf i)) 4)) i a b c)) "aBcdef" 3 1 2 3) (deftest nstring-capitalize.order.2 (let ((i 0) a b c (s (copy-seq "abcdef"))) (values (nstring-capitalize (progn (setf a (incf i)) s) :end (progn (setf b (incf i)) 4) :start (progn (setf c (incf i)) 1)) i a b c)) "aBcdef" 3 1 2 3) ;;; Error cases (deftest nstring-capitalize.error.1 (signals-error (nstring-capitalize) program-error) t) (deftest nstring-capitalize.error.2 (signals-error (nstring-capitalize (copy-seq "abc") :bad t) program-error) t) (deftest nstring-capitalize.error.3 (signals-error (nstring-capitalize (copy-seq "abc") :start) program-error) t) (deftest nstring-capitalize.error.4 (signals-error (nstring-capitalize (copy-seq "abc") :bad t :allow-other-keys nil) program-error) t) (deftest nstring-capitalize.error.5 (signals-error (nstring-capitalize (copy-seq "abc") :end) program-error) t) (deftest nstring-capitalize.error.6 (signals-error (nstring-capitalize (copy-seq "abc") 1 2) program-error) t)
null
https://raw.githubusercontent.com/rtoy/ansi-cl-tests/9708f3977220c46def29f43bb237e97d62033c1d/nstring-capitalize.lsp
lisp
-*- Mode: Lisp -*- Contains: Tests for NSTRING-CAPITALIZE Order of evaluation tests Error cases
Author : Created : Thu Oct 3 21:38:49 2002 (in-package :cl-test) (deftest nstring-capitalize.1 (let* ((s (copy-seq "abCd")) (s2 (nstring-capitalize s))) (values (eqt s s2) s)) t "Abcd") (deftest nstring-capitalize.2 (let* ((s (copy-seq "0adA2Cdd3wXy")) (s2 (nstring-capitalize s))) (values (eqt s s2) s)) t "0ada2cdd3wxy") (deftest nstring-capitalize.3 (let* ((s (copy-seq "1a")) (s2 (nstring-capitalize s))) (values (eqt s s2) s)) t "1a") (deftest nstring-capitalize.4 (let* ((s (copy-seq "a1a")) (s2 (nstring-capitalize s))) (values (eqt s s2) s)) t "A1a") (deftest nstring-capitalize.7 (let ((s "ABCDEF")) (loop for i from 0 to 5 collect (nstring-capitalize (copy-seq s) :start i))) ("Abcdef" "ABcdef" "ABCdef" "ABCDef" "ABCDEf" "ABCDEF")) (deftest nstring-capitalize.8 (let ((s "ABCDEF")) (loop for i from 0 to 5 collect (nstring-capitalize (copy-seq s) :start i :end nil))) ("Abcdef" "ABcdef" "ABCdef" "ABCDef" "ABCDEf" "ABCDEF")) (deftest nstring-capitalize.9 (let ((s "ABCDEF")) (loop for i from 0 to 6 collect (nstring-capitalize (copy-seq s) :end i))) ("ABCDEF" "ABCDEF" "AbCDEF" "AbcDEF" "AbcdEF" "AbcdeF" "Abcdef")) (deftest nstring-capitalize.10 (let ((s "ABCDEF")) (loop for i from 0 to 5 collect (loop for j from i to 6 collect (nstring-capitalize (copy-seq s) :start i :end j)))) (("ABCDEF" "ABCDEF" "AbCDEF" "AbcDEF" "AbcdEF" "AbcdeF" "Abcdef") ("ABCDEF" "ABCDEF" "ABcDEF" "ABcdEF" "ABcdeF" "ABcdef") ("ABCDEF" "ABCDEF" "ABCdEF" "ABCdeF" "ABCdef") ("ABCDEF" "ABCDEF" "ABCDeF" "ABCDef") ("ABCDEF" "ABCDEF" "ABCDEf") ("ABCDEF" "ABCDEF"))) (deftest nstring-capitalize.11 (nstring-capitalize "") "") (deftest nstring-capitalize.12 :notes (:nil-vectors-are-strings) (nstring-capitalize (make-array '(0) :element-type nil)) "") (deftest nstring-capitalize.13 (loop for type in '(standard-char base-char character) for s = (make-array '(10) :element-type type :fill-pointer 5 :initial-contents "aB0cDefGHi") collect (list (copy-seq s) (copy-seq (nstring-capitalize s)) (copy-seq s) (progn (setf (fill-pointer s) 10) (copy-seq s)) )) (("aB0cD" "Ab0cd" "Ab0cd" "Ab0cdefGHi") ("aB0cD" "Ab0cd" "Ab0cd" "Ab0cdefGHi") ("aB0cD" "Ab0cd" "Ab0cd" "Ab0cdefGHi"))) (deftest nstring-capitalize.14 (loop for type in '(standard-char base-char character) for s0 = (make-array '(10) :element-type type :initial-contents "zZaB0cDefG") for s = (make-array '(5) :element-type type :displaced-to s0 :displaced-index-offset 2) collect (list (copy-seq s) (nstring-capitalize s) (copy-seq s) s0)) (("aB0cD" "Ab0cd" "Ab0cd" "zZAb0cdefG") ("aB0cD" "Ab0cd" "Ab0cd" "zZAb0cdefG") ("aB0cD" "Ab0cd" "Ab0cd" "zZAb0cdefG"))) (deftest nstring-capitalize.15 (loop for type in '(standard-char base-char character) for s = (make-array '(5) :element-type type :adjustable t :initial-contents "aB0cD") collect (list (copy-seq s) (nstring-capitalize s) (copy-seq s))) (("aB0cD" "Ab0cd" "Ab0cd") ("aB0cD" "Ab0cd" "Ab0cd") ("aB0cD" "Ab0cd" "Ab0cd"))) (deftest nstring-capitalize.order.1 (let ((i 0) a b c (s (copy-seq "abcdef"))) (values (nstring-capitalize (progn (setf a (incf i)) s) :start (progn (setf b (incf i)) 1) :end (progn (setf c (incf i)) 4)) i a b c)) "aBcdef" 3 1 2 3) (deftest nstring-capitalize.order.2 (let ((i 0) a b c (s (copy-seq "abcdef"))) (values (nstring-capitalize (progn (setf a (incf i)) s) :end (progn (setf b (incf i)) 4) :start (progn (setf c (incf i)) 1)) i a b c)) "aBcdef" 3 1 2 3) (deftest nstring-capitalize.error.1 (signals-error (nstring-capitalize) program-error) t) (deftest nstring-capitalize.error.2 (signals-error (nstring-capitalize (copy-seq "abc") :bad t) program-error) t) (deftest nstring-capitalize.error.3 (signals-error (nstring-capitalize (copy-seq "abc") :start) program-error) t) (deftest nstring-capitalize.error.4 (signals-error (nstring-capitalize (copy-seq "abc") :bad t :allow-other-keys nil) program-error) t) (deftest nstring-capitalize.error.5 (signals-error (nstring-capitalize (copy-seq "abc") :end) program-error) t) (deftest nstring-capitalize.error.6 (signals-error (nstring-capitalize (copy-seq "abc") 1 2) program-error) t)
9138c93f5d4e35823ec8509bbd7a8f2ad31a67731a853d71c8d86febd1e3f882
SahilKang/cl-avro
reinitialization.lisp
Copyright 2022 Google LLC ;;; ;;; This file is part of cl-avro. ;;; ;;; cl-avro 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-avro 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-avro. If not, see </>. (in-package #:cl-user) (defpackage #:cl-avro/test/reinitialization (:local-nicknames (#:avro #:cl-avro)) (:use #:cl #:1am)) (in-package #:cl-avro/test/reinitialization) (test direct (let ((schema (make-instance 'avro:fixed :name "foo" :size 1))) (is (= 1 (avro:size schema))) (is (eq schema (reinitialize-instance schema :name "foo" :size 2))) (is (= 2 (avro:size schema))))) (test inherited (let ((schema (make-instance 'avro:fixed :name "bar" :namespace "foo" :size 1))) (is (string= "foo.bar" (avro:fullname schema))) (is (eq schema (reinitialize-instance schema :name "bar" :size 1))) (is (string= "bar" (avro:fullname schema))))) (test invalid (let ((schema (make-instance 'avro:fixed :name "foo" :size 1))) (signals error (reinitialize-instance schema :name "foo"))))
null
https://raw.githubusercontent.com/SahilKang/cl-avro/34f227936a303f34a94e46480a7172a6171835fa/test/reinitialization.lisp
lisp
This file is part of cl-avro. cl-avro is free software: you can redistribute it and/or modify (at your option) any later version. cl-avro 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-avro. If not, see </>.
Copyright 2022 Google LLC it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License (in-package #:cl-user) (defpackage #:cl-avro/test/reinitialization (:local-nicknames (#:avro #:cl-avro)) (:use #:cl #:1am)) (in-package #:cl-avro/test/reinitialization) (test direct (let ((schema (make-instance 'avro:fixed :name "foo" :size 1))) (is (= 1 (avro:size schema))) (is (eq schema (reinitialize-instance schema :name "foo" :size 2))) (is (= 2 (avro:size schema))))) (test inherited (let ((schema (make-instance 'avro:fixed :name "bar" :namespace "foo" :size 1))) (is (string= "foo.bar" (avro:fullname schema))) (is (eq schema (reinitialize-instance schema :name "bar" :size 1))) (is (string= "bar" (avro:fullname schema))))) (test invalid (let ((schema (make-instance 'avro:fixed :name "foo" :size 1))) (signals error (reinitialize-instance schema :name "foo"))))
c9e807fa93b58288f02aeb27948ab1e654a3e8598197bf71a3f14de2209f48d7
leo-project/leofs
leo_gateway_web_tests.erl
%%==================================================================== %% Leo Gateway %% Copyright ( c ) 2012 - 2018 Rakuten , Inc. %% 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. %% %% ------------------------------------------------------------------- %% LeoFS Gateway - S3 domainogics Test %% @doc %% @end %%==================================================================== -module(leo_gateway_web_tests). -include("leo_gateway.hrl"). -include("leo_http.hrl"). -include_lib("leo_commons/include/leo_commons.hrl"). -include_lib("leo_logger/include/leo_logger.hrl"). -include_lib("leo_object_storage/include/leo_object_storage.hrl"). -include_lib("leo_s3_libs/include/leo_s3_bucket.hrl"). -include_lib("leo_redundant_manager/include/leo_redundant_manager.hrl"). -include_lib("eunit/include/eunit.hrl"). -define(TARGET_HOST, "localhost"). %%-------------------------------------------------------------------- %% TEST %%-------------------------------------------------------------------- -ifdef(EUNIT). s3_api_test_() -> {setup, fun setup_s3_api/0, fun teardown/1, fun gen_tests_1/1}. rest_api_test_() -> {setup, fun setup_rest_api/0, fun teardown/1, fun gen_tests_2/1}. gen_tests_1(Arg) -> lists:map(fun(Test) -> Test(Arg) end, [fun get_bucket_list_error_/1, fun get_bucket_list_empty_/1, fun get_bucket_list_normal1_/1, fun get_bucket_acl_normal1_/1, fun head_object_error_/1, fun head_object_notfound_/1, fun head_object_normal1_/1, fun get_object_error_/1, fun get_object_invalid_/1, fun get_object_notfound_/1, fun get_object_normal1_/1, fun get_object_cmeta_normal1_/1, fun get_object_acl_normal1_/1, fun range_object_normal1_/1, fun range_object_normal2_/1, fun range_object_normal3_/1, fun delete_object_error_/1, fun delete_object_notfound_/1, fun delete_object_normal1_/1, fun put_object_error_/1, fun put_object_error_metadata_too_large_/1, fun put_object_normal1_/1, fun put_object_aws_chunked_/1, fun put_object_aws_chunked_error_/1 ]). gen_tests_2(Arg) -> lists:map(fun(Test) -> Test(Arg) end, [fun head_object_error_/1, fun head_object_notfound_/1, fun head_object_normal1_/1, fun get_object_error_/1, fun get_object_notfound_/1, fun get_object_normal1_/1, fun delete_object_error_/1, fun delete_object_notfound_/1, fun delete_object_normal1_/1, fun put_object_error_/1, fun put_object_normal1_/1 ]). -define(SSL_CERT_DATA, "-----BEGIN CERTIFICATE-----\n" ++ "MIIDIDCCAgigAwIBAgIJAJLkNZzERPIUMA0GCSqGSIb3DQEBBQUAMBQxEjAQBgNV\n" ++ "BAMTCWxvY2FsaG9zdDAeFw0xMDAzMTgxOTM5MThaFw0yMDAzMTUxOTM5MThaMBQx\n" ++ "EjAQBgNVBAMTCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" ++ "ggEBAJeUCOZxbmtngF4S5lXckjSDLc+8C+XjMBYBPyy5eKdJY20AQ1s9/hhp3ulI\n" ++ "8pAvl+xVo4wQ+iBSvOzcy248Q+Xi6+zjceF7UNRgoYPgtJjKhdwcHV3mvFFrS/fp\n" ++ "9ggoAChaJQWDO1OCfUgTWXImhkw+vcDR11OVMAJ/h73dqzJPI9mfq44PTTHfYtgr\n" ++ "v4LAQAOlhXIAa2B+a6PlF6sqDqJaW5jLTcERjsBwnRhUGi7JevQzkejujX/vdA+N\n" ++ "jRBjKH/KLU5h3Q7wUchvIez0PXWVTCnZjpA9aR4m7YV05nKQfxtGd71czYDYk+j8\n" ++ "hd005jetT4ir7JkAWValBybJVksCAwEAAaN1MHMwHQYDVR0OBBYEFJl9s51SnjJt\n" ++ "V/wgKWqV5Q6jnv1ZMEQGA1UdIwQ9MDuAFJl9s51SnjJtV/wgKWqV5Q6jnv1ZoRik\n" ++ "FjAUMRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCS5DWcxETyFDAMBgNVHRMEBTADAQH/\n" ++ "MA0GCSqGSIb3DQEBBQUAA4IBAQB2ldLeLCc+lxK5i0EZquLamMBJwDIjGpT0JMP9\n" ++ "b4XQOK2JABIu54BQIZhwcjk3FDJz/uOW5vm8k1kYni8FCjNZAaRZzCUfiUYTbTKL\n" ++ "Rq9LuIAODyP2dnTqyKaQOOJHvrx9MRZ3XVecXPS0Tib4aO57vCaAbIkmhtYpTWmw\n" ++ "e3t8CAIDVtgvjR6Se0a1JA4LktR7hBu22tDImvCSJn1nVAaHpani6iPBPPdMuMsP\n" ++ "TBoeQfj8VpqBUjCStqJGa8ytjDFX73YaxV2mgrtGwPNme1x3YNRR11yTu7tksyMO\n" ++ "GrmgxNriqYRchBhNEf72AKF0LR1ByKwfbDB9rIsV00HtCgOp\n" ++ "-----END CERTIFICATE-----\n"). -define(SSL_KEY_DATA, "-----BEGIN RSA PRIVATE KEY-----\n" ++ "MIIEpAIBAAKCAQEAl5QI5nFua2eAXhLmVdySNIMtz7wL5eMwFgE/LLl4p0ljbQBD\n" ++ "Wz3+GGne6UjykC+X7FWjjBD6IFK87NzLbjxD5eLr7ONx4XtQ1GChg+C0mMqF3Bwd\n" ++ "Xea8UWtL9+n2CCgAKFolBYM7U4J9SBNZciaGTD69wNHXU5UwAn+Hvd2rMk8j2Z+r\n" ++ "jg9NMd9i2Cu/gsBAA6WFcgBrYH5ro+UXqyoOolpbmMtNwRGOwHCdGFQaLsl69DOR\n" ++ "6O6Nf+90D42NEGMof8otTmHdDvBRyG8h7PQ9dZVMKdmOkD1pHibthXTmcpB/G0Z3\n" ++ "vVzNgNiT6PyF3TTmN61PiKvsmQBZVqUHJslWSwIDAQABAoIBACI8Ky5xHDFh9RpK\n" ++ "Rn/KC7OUlTpADKflgizWJ0Cgu2F9L9mkn5HyFHvLHa+u7CootbWJOiEejH/UcBtH\n" ++ "WyMQtX0snYCpdkUpJv5wvMoebGu+AjHOn8tfm9T/2O6rhwgckLyMb6QpGbMo28b1\n" ++ "p9QiY17BJPZx7qJQJcHKsAvwDwSThlb7MFmWf42LYWlzybpeYQvwpd+UY4I0WXLu\n" ++ "/dqJIS9Npq+5Y5vbo2kAEAssb2hSCvhCfHmwFdKmBzlvgOn4qxgZ1iHQgfKI6Z3Y\n" ++ "J0573ZgOVTuacn+lewtdg5AaHFcl/zIYEr9SNqRoPNGbPliuv6k6N2EYcufWL5lR\n" ++ "sCmmmHECgYEAxm+7OpepGr++K3+O1e1MUhD7vSPkKJrCzNtUxbOi2NWj3FFUSPRU\n" ++ "adWhuxvUnZgTcgM1+KuQ0fB2VmxXe9IDcrSFS7PKFGtd2kMs/5mBw4UgDZkOQh+q\n" ++ "kDiBEV3HYYJWRq0w3NQ/9Iy1jxxdENHtGmG9aqamHxNtuO608wGW2S8CgYEAw4yG\n" ++ "ZyAic0Q/U9V2OHI0MLxLCzuQz17C2wRT1+hBywNZuil5YeTuIt2I46jro6mJmWI2\n" ++ "fH4S/geSZzg2RNOIZ28+aK79ab2jWBmMnvFCvaru+odAuser4N9pfAlHZvY0pT+S\n" ++ "1zYX3f44ygiio+oosabLC5nWI0zB2gG8pwaJlaUCgYEAgr7poRB+ZlaCCY0RYtjo\n" ++ "mYYBKD02vp5BzdKSB3V1zeLuBWM84pjB6b3Nw0fyDig+X7fH3uHEGN+USRs3hSj6\n" ++ "BqD01s1OT6fyfbYXNw5A1r+nP+5h26Wbr0zblcKxdQj4qbbBZC8hOJNhqTqqA0Qe\n" ++ "MmzF7jiBaiZV/Cyj4x1f9BcCgYEAhjL6SeuTuOctTqs/5pz5lDikh6DpUGcH8qaV\n" ++ "o6aRAHHcMhYkZzpk8yh1uUdD7516APmVyvn6rrsjjhLVq4ZAJjwB6HWvE9JBN0TR\n" ++ "bILF+sREHUqU8Zn2Ku0nxyfXCKIOnxlx/J/y4TaGYqBqfXNFWiXNUrjQbIlQv/xR\n" ++ "K48g/MECgYBZdQlYbMSDmfPCC5cxkdjrkmAl0EgV051PWAi4wR+hLxIMRjHBvAk7\n" ++ "IweobkFvT4TICulgroLkYcSa5eOZGxB/DHqcQCbWj3reFV0VpzmTDoFKG54sqBRl\n" ++ "vVntGt0pfA40fF17VoS7riAdHF53ippTtsovHEsg5tq5NrBl5uKm2g==\n" ++ "-----END RSA PRIVATE KEY-----\n"). setup(InitFun, TermFun) -> ok = leo_logger_api:new("./", ?LOG_LEVEL_INFO), ok = leo_logger_api:new(?LOG_GROUP_ID_ACCESS, ?LOG_ID_ACCESS, "./", ?LOG_FILENAME_ACCESS), io:format(user, "cwd:~p~n",[os:cmd("pwd")]), [] = os:cmd("epmd -daemon"), {ok, Hostname} = inet:gethostname(), NetKernelNode = list_to_atom("netkernel_0@" ++ Hostname), net_kernel:start([NetKernelNode, shortnames]), inets:start(), Args = " -pa ../deps/*/ebin " ++ " -kernel error_logger '{file, \"../kernel.log\"}' ", {ok, Node0} = slave:start_link(list_to_atom(Hostname), 'storage_0', Args), {ok, Node1} = slave:start_link(list_to_atom(Hostname), 'storage_1', Args), ok = leo_misc:init_env(), meck:new(leo_redundant_manager_api, [non_strict]), meck:expect(leo_redundant_manager_api, get_redundancies_by_key, fun(_Method, _Key) -> {ok, #redundancies{id = 0, nodes = [#redundant_node{node = Node0, available = true}, #redundant_node{node = Node1, available = true}], n = 2, r = 1, w = 1, d = 1}} end), meck:new(leo_s3_endpoint, [non_strict]), meck:expect(leo_s3_endpoint, get_endpoints, 0, {ok, [{endpoint, <<"localhost">>, 0}]}), meck:new(leo_s3_bucket, [non_strict]), meck:expect(leo_s3_bucket, get_latest_bucket, fun(_BucketName) -> {ok, #?BUCKET{name =_BucketName, acls = [#bucket_acl_info{user_id = ?GRANTEE_ALL_USER, permissions = [read, write]}]}} end), Date = erlang:list_to_binary(leo_http:rfc1123_date(leo_date:now())), meck:new(cowboy_clock, [non_strict]), meck:expect(cowboy_clock, rfc1123, 0, Date), meck:new(leo_watchdog_state, [non_strict]), meck:expect(leo_watchdog_state, find_not_safe_items, fun() -> not_found end), meck:new(leo_metrics_req, [non_strict]), meck:expect(leo_metrics_req, notify, fun(_) -> ok end), ok = rpc:call(Node1, meck, new, [leo_metrics_req, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_metrics_req, notify, fun(_) -> ok end]), code:add_path("../cherly/ebin"), ok = file:write_file("./server_cert.pem", ?SSL_CERT_DATA), ok = file:write_file("./server_key.pem", ?SSL_KEY_DATA), application:start(leo_cache), leo_cache_api:start(), leo_pod:start_link(?POD_LOH_WORKER, ?env_loh_put_worker_pool_size(), ?env_loh_put_worker_buffer_size(), leo_large_object_worker, [], fun(_) -> void end), InitFun(), [TermFun, Node0, Node1]. setup_s3_api() -> application:start(crypto), application:start(ranch), application:start(cowboy), {ok, Options} = leo_gateway_app:get_options(), InitFun = fun() -> leo_gateway_http_commons:start( Options#http_options{port = 12345, is_compatible_with_s3_content_type = true}) end, TermFun = fun() -> leo_gateway_s3_api:stop() end, setup(InitFun, TermFun). setup_rest_api() -> application:start(crypto), application:start(ranch), application:start(cowboy), {ok, Options} = leo_gateway_app:get_options(), InitFun = fun() -> leo_gateway_http_commons:start( Options#http_options{handler = leo_gateway_rest_api, port = 12345, is_compatible_with_s3_content_type = true}) end, TermFun = fun() -> leo_gateway_rest_api:stop() end, setup(InitFun, TermFun). teardown([TermFun, Node0, Node1]) -> inets:stop(), net_kernel:stop(), slave:stop(Node0), slave:stop(Node1), meck:unload(), TermFun(), cowboy:stop_listener(leo_gateway_s3_api), cowboy:stop_listener(leo_gateway_s3_api_ssl), application:stop(crypto), application:stop(ranch), application:stop(cowboy), leo_cache_api:stop(), leo_logger_api:stop(), timer:sleep(250), ok. get_bucket_list_error_([_TermFun, _Node0, Node1]) -> fun() -> timer:sleep(150), ok = rpc:call(Node1, meck, new, [leo_storage_handler_directory, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_directory, find_by_parent_dir, 1, {error, some_error}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, Body}} = httpc:request(get, {lists:append( ["http://", ?TARGET_HOST, ":12345/a/b?prefix=pre"]), [{"Date", Date}]}, [], [{full_result, false}]), %% req id is empty for now Xml = io_lib:format(?XML_ERROR, [?XML_ERROR_CODE_InternalError, ?XML_ERROR_MSG_InternalError, "a/b/", ""]), ?assertEqual(erlang:list_to_binary(Xml), erlang:list_to_binary(Body)), ?assertEqual(500, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_directory]) end, ok end. get_bucket_list_empty_([_TermFun, _Node0, Node1]) -> fun() -> timer:sleep(150), ok = rpc:call(Node1, meck, new, [leo_storage_handler_directory, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_directory, find_by_parent_dir, 4, {ok, []}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, Body}} = httpc:request(get, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b?prefix=pre&delimiter=/"]), [{"Date", Date}]}, [], [{full_result, false}]), ?assertEqual(200, SC), Xml = io_lib:format(?XML_OBJ_LIST, ["a", "pre", "1000", "", "false" "", ""]), ?assertEqual(erlang:list_to_binary(Xml), erlang:list_to_binary(Body)) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_directory]) end, ok end. get_bucket_list_normal1_([_TermFun, _Node0, Node1]) -> fun() -> timer:sleep(150), ok = rpc:call(Node1, meck, new, [leo_storage_handler_directory, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_directory, find_by_parent_dir, 4, {ok, [#?METADATA{ key = <<"localhost/a/b/pre/test.png">>, addr_id = 0, ksize = 8, dsize = 0, meta = <<>>, msize = 0, csize = 0, cnumber = 0, cindex = 0, offset = 0, clock = 63511805822, timestamp = 19740926, checksum = 0, ring_hash = 0, cluster_id = [], ver = 0, del = ?DEL_FALSE } %% {metadata, <<"localhost/a/b/pre/test.png">>, 0 , 8 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 63511805822 , 19740926 , 0 , 0 } ]}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC,Body}} = httpc:request(get, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b/?prefix=pre&delimiter=/"]), [{"Date", Date}]}, [], [{full_result, false}]), ?assertEqual(200, SC), {_XmlDoc, Rest} = xmerl_scan:string(Body), ?assertEqual([], Rest) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_directory]) end, ok end. get_bucket_acl_normal1_([_TermFun, _Node0,_Node1]) -> fun() -> timer:sleep(150), %% leo_s3_bucket is already created at setup meck:expect(leo_s3_bucket, get_acls, 1, {ok, [#bucket_acl_info{user_id = ?GRANTEE_ALL_USER, permissions = [read, write]}]}), meck:expect(leo_s3_bucket, find_bucket_by_name, 1, {ok, #?BUCKET{name = "bucket", access_key_id = <<"ackid">>, acls = [#bucket_acl_info{user_id = ?GRANTEE_ALL_USER, permissions = [read, write]}, #bucket_acl_info{user_id = ?GRANTEE_AUTHENTICATED_USER, permissions = [full_control]}] }}), meck:new(leo_s3_auth, [no_link, non_strict]), meck:expect(leo_s3_auth, authenticate, 3, {ok, ["hoge"], undefined}), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC,Body}} = httpc:request(get, {lists:append(["http://", ?TARGET_HOST, ":12345/bucket?acl"]), [{"Date", Date}, {"Authorization","AWS auth:hoge"}]}, [], [{full_result, false}]), ?assertEqual(200, SC), {_XmlDoc, Rest} = xmerl_scan:string(Body), ?assertEqual([], Rest) catch throw:Reason -> throw(Reason) after meck:unload(leo_s3_auth) end, ok end. head_object_notfound_([_TermFun, Node0, Node1]) -> fun() -> ok = rpc:call(Node0, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node0, meck, expect, [leo_storage_handler_object, head, 2, {error, not_found}]), ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, head, 2, {error, not_found}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, _Body}} = httpc:request(head, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b"]), [{"Date", Date}]}, [], [{full_result, false}]), ?assertEqual(404, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node0, meck, unload, [leo_storage_handler_object]), ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. head_object_error_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, head, 2, {error, foobar}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, _Body}} = httpc:request(head, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b"]), [{"Date", Date}]}, [], [{full_result, false}]), ?assertEqual(500, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. head_object_normal1_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, head, 2, {ok, #?METADATA{ key = <<"a/b/c/d.png">>, addr_id = 0, ksize = 4, dsize = 16384, meta = <<>>, msize = 0, csize = 0, cnumber = 0, cindex = 0, offset = 1, clock = 63511805822, timestamp = 19740926, checksum = 0, ring_hash = 0, cluster_id = [], ver = 0, del = ?DEL_FALSE } }]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {{_, SC, _}, Headers, _Body}} = httpc:request(head, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b/c/d.png"]), [{"Date", Date}, {"connection", "close"}]}, [], []), %% -project/leofs/issues/489#issuecomment-265389401 %% exists only content-length header ?assertEqual({"content-length", "16384"}, lists:keyfind("content-length", 1, Headers)), ?assertEqual(false, lists:keyfind("transfer-encoding", 1, Headers)), ?assertEqual(200, SC) %% ?assertEqual("16384", proplists:get_value("content-length", Headers)) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. get_object_error_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, get, 3, {error, foobar}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, Body}} = httpc:request(get, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b.png"]), [{"Date", Date}]}, [], [{full_result, false}]), %% req id is empty for now Xml = io_lib:format(?XML_ERROR, [?XML_ERROR_CODE_InternalError, ?XML_ERROR_MSG_InternalError, "a/b.png", ""]), ?assertEqual(erlang:list_to_binary(Xml), erlang:list_to_binary(Body)), ?assertEqual(500, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. get_object_invalid_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, get, 3, {error, foobar}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, _Body}} = httpc:request(head, {lists:append(["http://", ?TARGET_HOST, ":12345/"]), [{"Date", Date}, {"Host", ""}]}, [{version, "HTTP/1.0"}], [{full_result, false}]), ?assertEqual(400, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. get_object_notfound_([_TermFun, Node0, Node1]) -> fun() -> ok = rpc:call(Node0, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node0, meck, expect, [leo_storage_handler_object, get, 3, {error, not_found}]), ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, get, 3, {error, not_found}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, Body}} = httpc:request(get, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b/c.png"]), [{"Date", Date}]}, [], [{full_result, false}]), %% req id is empty for now Xml = io_lib:format(?XML_ERROR, [?XML_ERROR_CODE_NoSuchKey, ?XML_ERROR_MSG_NoSuchKey, "a/b/c.png", ""]), ?assertEqual(erlang:list_to_binary(Xml), erlang:list_to_binary(Body)), ?assertEqual(404, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node0, meck, unload, [leo_storage_handler_object]), ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. get_object_normal1_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, get, 3, {ok, #?METADATA{ key = <<"">>, addr_id = 0, ksize = 4, dsize = 4, meta = <<>>, msize = 0, csize = 0, cnumber = 0, cindex = 0, offset = 1, clock = calendar:datetime_to_gregorian_seconds(erlang:universaltime()), timestamp = 19740926, checksum = 0, ring_hash = 0, cluster_id = [], ver = 0, del = ?DEL_FALSE }, <<"body">>}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {{_, SC, _}, Headers, Body}} = httpc:request(get, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b.png"]), [{"Date", Date}, {"connection", "close"}]}, [], []), ?assertEqual(200, SC), ?assertEqual("body", Body), ContentType = proplists:get_value("content-type", Headers), ?assertEqual(true, ContentType =:= "application/octet-stream" orelse ContentType =:= "image/png"), ?assertEqual(undefined, proplists:get_value("X-From-Cache", Headers)) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. get_object_cmeta_normal1_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), CMetaBin = term_to_binary([{<<"x-amz-meta-test">>, <<"custom metadata">>},{<<"x-amz-meta-leofs-content-type">>,<<"image/svg">>}]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, get, 3, {ok, #?METADATA{ key = <<"">>, addr_id = 0, ksize = 4, dsize = 4, meta = CMetaBin, msize = byte_size(CMetaBin), csize = 0, cnumber = 0, cindex = 0, offset = 1, clock = calendar:datetime_to_gregorian_seconds(erlang:universaltime()), timestamp = 19740926, checksum = 0, ring_hash = 0, cluster_id = [], ver = 0, del = ?DEL_FALSE }, <<"body">>}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {{_, SC, _}, Headers, Body}} = httpc:request(get, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b.png"]), [{"Date", Date}, {"connection", "close"}]}, [], []), ?assertEqual(200, SC), ?assertEqual("body", Body), ?assertEqual("image/svg", proplists:get_value("content-type", Headers)), ?assertEqual(undefined, proplists:get_value("X-From-Cache", Headers)), ?assertEqual("custom metadata", proplists:get_value("x-amz-meta-test", Headers)) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. get_object_acl_normal1_([_TermFun, _Node0, Node1]) -> fun() -> meck:expect(leo_s3_bucket, get_acls, 1, {ok, [#bucket_acl_info{user_id = ?GRANTEE_ALL_USER, permissions = [read, write]}]}), meck:expect(leo_s3_bucket, find_bucket_by_name, 1, {ok, #?BUCKET{name = "bucket", access_key_id = <<"ackid">>, acls = [#bucket_acl_info{user_id = ?GRANTEE_ALL_USER, permissions = [read, write]}, #bucket_acl_info{user_id = ?GRANTEE_AUTHENTICATED_USER, permissions = [full_control]}] }}), meck:new(leo_s3_auth, [no_link, non_strict]), meck:expect(leo_s3_auth, authenticate, 3, {ok, ["hoge"], undefined}), ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, head, 2, {ok, #?METADATA{ key = <<"bucket/object">>, addr_id = 0, ksize = 4, dsize = 16384, meta = <<>>, msize = 0, csize = 0, cnumber = 0, cindex = 0, offset = 1, clock = 63511805822, timestamp = 19740926, checksum = 0, ring_hash = 0, cluster_id = [], ver = 0, del = ?DEL_FALSE } }]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC,Body}} = httpc:request(get, {lists:append(["http://", ?TARGET_HOST, ":12345/bucket/object?acl"]), [{"Date", Date}, {"Authorization","AWS auth:hoge"}]}, [], [{full_result, false}]), ?assertEqual(200, SC), {_XmlDoc, Rest} = xmerl_scan:string(Body), ?assertEqual([], Rest) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]), meck:unload(leo_s3_auth) end, ok end. range_object_normal1_([_TermFun, _Node0, Node1]) -> range_object_base([_TermFun, _Node0, Node1], "bytes=1-2"). range_object_normal2_([_TermFun, _Node0, Node1]) -> range_object_base([_TermFun, _Node0, Node1], "bytes=1-"). range_object_normal3_([_TermFun, _Node0, Node1]) -> range_object_base([_TermFun, _Node0, Node1], "bytes=-1"). range_object_base([_TermFun, _Node0, Node1], RangeValue) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, head, 2, {ok, #?METADATA{ key = <<"a/b.png">>, addr_id = 0, ksize = 4, dsize = 16384, meta = <<>>, msize = 0, csize = 0, cnumber = 0, cindex = 0, offset = 1, clock = 63505750315, timestamp = 19740926, checksum = 0, ring_hash = 0, cluster_id = [], ver = 0, del = ?DEL_FALSE } }]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, get, 5, {ok, #?METADATA{ key = <<"">>, addr_id = 0, ksize = 2, dsize = 2, meta = <<>>, msize = 0, csize = 0, cnumber = 0, cindex = 0, offset = 1, clock = calendar:datetime_to_gregorian_seconds(erlang:universaltime()), timestamp = 19740926, checksum = 0, ring_hash = 0, cluster_id = [], ver = 0, del = ?DEL_FALSE }, <<"od">>}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {{_, SC, _}, _Headers, Body}} = httpc:request(get, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b.png"]), [{"Date", Date},{"connection", "close"},{"range", RangeValue}]}, [], []), ?assertEqual(206, SC), ?assertEqual("od", Body) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. delete_object_notfound_([_TermFun, Node0, Node1]) -> fun() -> ok = rpc:call(Node0, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node0, meck, expect, [leo_storage_handler_object, delete, 2, {error, not_found}]), ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, delete, 2, {error, not_found}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, _Body}} = httpc:request(delete, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b.png"]), [{"Date", Date}, {"Authorization","auth"}]}, [], [{full_result, false}]), ?assertEqual(204, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node0, meck, unload, [leo_storage_handler_object]), ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. delete_object_error_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, delete, 2, {error, foobar}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, Body}} = httpc:request(delete, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b.png"]), [{"Date", Date}, {"Authorization","auth"}]}, [], [{full_result, false}]), %% req id is empty for now Xml = io_lib:format(?XML_ERROR, [?XML_ERROR_CODE_InternalError, ?XML_ERROR_MSG_InternalError, "a/b.png", ""]), ?assertEqual(erlang:list_to_binary(Xml), erlang:list_to_binary(Body)), ?assertEqual(500, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. delete_object_normal1_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, delete, 2, ok]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, _Body}} = httpc:request(delete, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b.png"]), [{"Date", Date}, {"Authorization","auth"}]}, [], [{full_result, false}]), ?assertEqual(204, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. -undef(EUNIT_DEBUG_VAL_DEPTH). -define(EUNIT_DEBUG_VAL_DEPTH, 1024). put_object_error_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, put, 2, {error, foobar}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, Body}} = httpc:request(put, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b.png"]), [{"Date", Date}, {"Authorization","auth"}], "image/png", "body"}, [], [{full_result, false}]), %% req id is empty for now Xml = io_lib:format(?XML_ERROR, [?XML_ERROR_CODE_InternalError, ?XML_ERROR_MSG_InternalError, "a/b.png", ""]), ?assertEqual(erlang:list_to_binary(Xml), erlang:list_to_binary(Body)), ?assertEqual(500, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. put_object_error_metadata_too_large_([_TermFun, _Node0, _Node1]) -> fun() -> try Date = leo_http:rfc1123_date(leo_date:now()), Dummy = lists:flatten(["test" || _ <- lists:seq(1, ?HTTP_METADATA_LIMIT * 2 div 4)]), Dummy = crypto : rand_bytes(?HTTP_METADATA_LIMIT * 2 ) , {ok, {SC, Body}} = httpc:request(put, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b.png"]), [{"Date", Date}, {"Authorization","auth"}, {"x-amz-meta-test", Dummy}], "image/png", "body"}, [], [{full_result, false}]), %% req id is empty for now Xml = io_lib:format(?XML_ERROR, [?XML_ERROR_CODE_MetadataTooLarge, ?XML_ERROR_MSG_MetadataTooLarge, "a/b.png", ""]), ?assertEqual(erlang:list_to_binary(Xml), erlang:list_to_binary(Body)), ?assertEqual(400, SC) catch throw:Reason -> throw(Reason) end, ok end. put_object_normal1_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, put, 2, {ok, 1}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, _Body}} = httpc:request(put, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b.png"]), [{"Date", Date}, {"Authorization","auth"}], "image/png", "body"}, [], [{full_result, false}]), ?assertEqual(200, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. -define(CHUNKSIZE, 4096). -define(AWSCHUNKEDSIZE, 65536). gen_chunks(PrevSign, SignHead, SignKey, 0, Acc) -> Bin = <<>>, {Chunk, _Signature} = compute_chunk(PrevSign, SignHead, SignKey, Bin), <<Acc/binary, Chunk/binary>>; gen_chunks(PrevSign, SignHead, SignKey, Remain, Acc) when Remain < ?CHUNKSIZE -> Bin = crypto:strong_rand_bytes(Remain), {Chunk, Signature} = compute_chunk(PrevSign, SignHead, SignKey, Bin), gen_chunks(Signature, SignHead, SignKey, 0, <<Acc/binary, Chunk/binary>>); gen_chunks(PrevSign, SignHead, SignKey, Remain, Acc) -> Bin = crypto:strong_rand_bytes(?CHUNKSIZE), {Chunk, Signature} = compute_chunk(PrevSign, SignHead, SignKey, Bin), gen_chunks(Signature, SignHead, SignKey, Remain - ?CHUNKSIZE, <<Acc/binary, Chunk/binary>>). compute_chunk(PrevSign, SignHead, SignKey, Bin) -> SizeHex = leo_hex:integer_to_hex(byte_size(Bin), 6), ChunkHashBin = leo_hex:binary_to_hexbin(crypto:hash(sha256, Bin)), BinToSign = <<"AWS4-HMAC-SHA256-PAYLOAD\n", SignHead/binary, PrevSign/binary, "\n", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\n", ChunkHashBin/binary>>, Signature = crypto:hmac(sha256, SignKey, BinToSign), Sign = leo_hex:binary_to_hexbin(Signature), SizeHexBin = list_to_binary(SizeHex), Chunk = <<SizeHexBin/binary, ";", "chunk-signature=", Sign/binary, "\r\n", Bin/binary, "\r\n">>, {Chunk, Sign}. put_object_aws_chunked_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, put, 2, {ok, 1}]), meck:new(leo_s3_auth, [no_link, non_strict]), Signature = <<"642797dcfdf817ac23b553420f52c160847d3747b2e86e5ac9d07cc5e7f60f63">>, SignHead = <<"20150706T051217Z\n20150706/us-east-1/s3/aws4_request\n">>, SignKey = <<"2040321d898be34c82d1db9e132124f11eb18a3d21569d1ed58b460b88954ac7">>, meck:expect(leo_s3_auth, authenticate, 3, {ok, <<"05236">>, {Signature, SignHead, SignKey}}), meck:expect(leo_s3_bucket, get_acls, 1, not_found), Chunks = gen_chunks(Signature, SignHead, SignKey, ?AWSCHUNKEDSIZE, <<>>), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, _Body}} = httpc:request(put, {lists:append(["http://", ?TARGET_HOST, ":12345/testjv4/testFile.large.one"]), [{"Date", Date}, {"authorization","AWS4-HMAC-SHA256 Credential=05236/20150706/us-east-1/s3/aws4_request, SignedHeaders=content-length, Signature=642797dcfdf817ac23b553420f52c160847d3747b2e86e5ac9d07cc5e7f60f63"}, {"x-amz-content-sha256", "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"}, {"x-amz-decoded-content-length", integer_to_list(?AWSCHUNKEDSIZE)} ], "image/png", Chunks}, [], [{full_result, false}]), ?assertEqual(200, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]), ok = meck:unload(leo_s3_auth) end, ok end. put_object_aws_chunked_error_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, put, 2, {ok, 1}]), meck:new(leo_s3_auth, [no_link, non_strict]), Signature = <<"642797dcfdf817ac23b553420f52c160847d3747b2e86e5ac9d07cc5e7f60f63">>, SignatureI = <<"incorrect">>, SignHead = <<"20150706T051217Z\n20150706/us-east-1/s3/aws4_request\n">>, SignKey = <<"2040321d898be34c82d1db9e132124f11eb18a3d21569d1ed58b460b88954ac7">>, meck:expect(leo_s3_auth, authenticate, 3, {ok, <<"05236">>, {Signature, SignHead, SignKey}}), meck:expect(leo_s3_bucket, get_latest_bucket, 1, not_found), Chunks = gen_chunks(SignatureI, SignHead, SignKey, ?AWSCHUNKEDSIZE, <<>>), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, _Body}} = httpc:request(put, {lists:append(["http://", ?TARGET_HOST, ":12345/testjv4/testFile.large.one"]), [{"Date", Date}, {"authorization","AWS4-HMAC-SHA256 Credential=05236/20150706/us-east-1/s3/aws4_request, SignedHeaders=content-length, Signature=642797dcfdf817ac23b553420f52c160847d3747b2e86e5ac9d07cc5e7f60f63"}, {"x-amz-content-sha256", "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"}, {"x-amz-decoded-content-length", integer_to_list(?AWSCHUNKEDSIZE)} ], "image/png", Chunks}, [], [{full_result, false}]), ?assertEqual(403, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]), ok = meck:unload(leo_s3_auth) end, ok end. proper_([_TermFun , _ Node0 , _ Node1 ] ) - > { timeout , 600 , ? _ assertEqual(true , leo_gateway_web_prop : test ( ) ) } . -endif.
null
https://raw.githubusercontent.com/leo-project/leofs/4ff701e0f4a4cf39a968dbe078b9c2412a22f995/apps/leo_gateway/test/leo_gateway_web_tests.erl
erlang
==================================================================== Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- LeoFS Gateway - S3 domainogics Test @doc @end ==================================================================== -------------------------------------------------------------------- TEST -------------------------------------------------------------------- req id is empty for now {metadata, <<"localhost/a/b/pre/test.png">>, leo_s3_bucket is already created at setup -project/leofs/issues/489#issuecomment-265389401 exists only content-length header ?assertEqual("16384", proplists:get_value("content-length", Headers)) req id is empty for now req id is empty for now req id is empty for now req id is empty for now req id is empty for now
Leo Gateway Copyright ( c ) 2012 - 2018 Rakuten , Inc. 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(leo_gateway_web_tests). -include("leo_gateway.hrl"). -include("leo_http.hrl"). -include_lib("leo_commons/include/leo_commons.hrl"). -include_lib("leo_logger/include/leo_logger.hrl"). -include_lib("leo_object_storage/include/leo_object_storage.hrl"). -include_lib("leo_s3_libs/include/leo_s3_bucket.hrl"). -include_lib("leo_redundant_manager/include/leo_redundant_manager.hrl"). -include_lib("eunit/include/eunit.hrl"). -define(TARGET_HOST, "localhost"). -ifdef(EUNIT). s3_api_test_() -> {setup, fun setup_s3_api/0, fun teardown/1, fun gen_tests_1/1}. rest_api_test_() -> {setup, fun setup_rest_api/0, fun teardown/1, fun gen_tests_2/1}. gen_tests_1(Arg) -> lists:map(fun(Test) -> Test(Arg) end, [fun get_bucket_list_error_/1, fun get_bucket_list_empty_/1, fun get_bucket_list_normal1_/1, fun get_bucket_acl_normal1_/1, fun head_object_error_/1, fun head_object_notfound_/1, fun head_object_normal1_/1, fun get_object_error_/1, fun get_object_invalid_/1, fun get_object_notfound_/1, fun get_object_normal1_/1, fun get_object_cmeta_normal1_/1, fun get_object_acl_normal1_/1, fun range_object_normal1_/1, fun range_object_normal2_/1, fun range_object_normal3_/1, fun delete_object_error_/1, fun delete_object_notfound_/1, fun delete_object_normal1_/1, fun put_object_error_/1, fun put_object_error_metadata_too_large_/1, fun put_object_normal1_/1, fun put_object_aws_chunked_/1, fun put_object_aws_chunked_error_/1 ]). gen_tests_2(Arg) -> lists:map(fun(Test) -> Test(Arg) end, [fun head_object_error_/1, fun head_object_notfound_/1, fun head_object_normal1_/1, fun get_object_error_/1, fun get_object_notfound_/1, fun get_object_normal1_/1, fun delete_object_error_/1, fun delete_object_notfound_/1, fun delete_object_normal1_/1, fun put_object_error_/1, fun put_object_normal1_/1 ]). -define(SSL_CERT_DATA, "-----BEGIN CERTIFICATE-----\n" ++ "MIIDIDCCAgigAwIBAgIJAJLkNZzERPIUMA0GCSqGSIb3DQEBBQUAMBQxEjAQBgNV\n" ++ "BAMTCWxvY2FsaG9zdDAeFw0xMDAzMTgxOTM5MThaFw0yMDAzMTUxOTM5MThaMBQx\n" ++ "EjAQBgNVBAMTCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" ++ "ggEBAJeUCOZxbmtngF4S5lXckjSDLc+8C+XjMBYBPyy5eKdJY20AQ1s9/hhp3ulI\n" ++ "8pAvl+xVo4wQ+iBSvOzcy248Q+Xi6+zjceF7UNRgoYPgtJjKhdwcHV3mvFFrS/fp\n" ++ "9ggoAChaJQWDO1OCfUgTWXImhkw+vcDR11OVMAJ/h73dqzJPI9mfq44PTTHfYtgr\n" ++ "v4LAQAOlhXIAa2B+a6PlF6sqDqJaW5jLTcERjsBwnRhUGi7JevQzkejujX/vdA+N\n" ++ "jRBjKH/KLU5h3Q7wUchvIez0PXWVTCnZjpA9aR4m7YV05nKQfxtGd71czYDYk+j8\n" ++ "hd005jetT4ir7JkAWValBybJVksCAwEAAaN1MHMwHQYDVR0OBBYEFJl9s51SnjJt\n" ++ "V/wgKWqV5Q6jnv1ZMEQGA1UdIwQ9MDuAFJl9s51SnjJtV/wgKWqV5Q6jnv1ZoRik\n" ++ "FjAUMRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCS5DWcxETyFDAMBgNVHRMEBTADAQH/\n" ++ "MA0GCSqGSIb3DQEBBQUAA4IBAQB2ldLeLCc+lxK5i0EZquLamMBJwDIjGpT0JMP9\n" ++ "b4XQOK2JABIu54BQIZhwcjk3FDJz/uOW5vm8k1kYni8FCjNZAaRZzCUfiUYTbTKL\n" ++ "Rq9LuIAODyP2dnTqyKaQOOJHvrx9MRZ3XVecXPS0Tib4aO57vCaAbIkmhtYpTWmw\n" ++ "e3t8CAIDVtgvjR6Se0a1JA4LktR7hBu22tDImvCSJn1nVAaHpani6iPBPPdMuMsP\n" ++ "TBoeQfj8VpqBUjCStqJGa8ytjDFX73YaxV2mgrtGwPNme1x3YNRR11yTu7tksyMO\n" ++ "GrmgxNriqYRchBhNEf72AKF0LR1ByKwfbDB9rIsV00HtCgOp\n" ++ "-----END CERTIFICATE-----\n"). -define(SSL_KEY_DATA, "-----BEGIN RSA PRIVATE KEY-----\n" ++ "MIIEpAIBAAKCAQEAl5QI5nFua2eAXhLmVdySNIMtz7wL5eMwFgE/LLl4p0ljbQBD\n" ++ "Wz3+GGne6UjykC+X7FWjjBD6IFK87NzLbjxD5eLr7ONx4XtQ1GChg+C0mMqF3Bwd\n" ++ "Xea8UWtL9+n2CCgAKFolBYM7U4J9SBNZciaGTD69wNHXU5UwAn+Hvd2rMk8j2Z+r\n" ++ "jg9NMd9i2Cu/gsBAA6WFcgBrYH5ro+UXqyoOolpbmMtNwRGOwHCdGFQaLsl69DOR\n" ++ "6O6Nf+90D42NEGMof8otTmHdDvBRyG8h7PQ9dZVMKdmOkD1pHibthXTmcpB/G0Z3\n" ++ "vVzNgNiT6PyF3TTmN61PiKvsmQBZVqUHJslWSwIDAQABAoIBACI8Ky5xHDFh9RpK\n" ++ "Rn/KC7OUlTpADKflgizWJ0Cgu2F9L9mkn5HyFHvLHa+u7CootbWJOiEejH/UcBtH\n" ++ "WyMQtX0snYCpdkUpJv5wvMoebGu+AjHOn8tfm9T/2O6rhwgckLyMb6QpGbMo28b1\n" ++ "p9QiY17BJPZx7qJQJcHKsAvwDwSThlb7MFmWf42LYWlzybpeYQvwpd+UY4I0WXLu\n" ++ "/dqJIS9Npq+5Y5vbo2kAEAssb2hSCvhCfHmwFdKmBzlvgOn4qxgZ1iHQgfKI6Z3Y\n" ++ "J0573ZgOVTuacn+lewtdg5AaHFcl/zIYEr9SNqRoPNGbPliuv6k6N2EYcufWL5lR\n" ++ "sCmmmHECgYEAxm+7OpepGr++K3+O1e1MUhD7vSPkKJrCzNtUxbOi2NWj3FFUSPRU\n" ++ "adWhuxvUnZgTcgM1+KuQ0fB2VmxXe9IDcrSFS7PKFGtd2kMs/5mBw4UgDZkOQh+q\n" ++ "kDiBEV3HYYJWRq0w3NQ/9Iy1jxxdENHtGmG9aqamHxNtuO608wGW2S8CgYEAw4yG\n" ++ "ZyAic0Q/U9V2OHI0MLxLCzuQz17C2wRT1+hBywNZuil5YeTuIt2I46jro6mJmWI2\n" ++ "fH4S/geSZzg2RNOIZ28+aK79ab2jWBmMnvFCvaru+odAuser4N9pfAlHZvY0pT+S\n" ++ "1zYX3f44ygiio+oosabLC5nWI0zB2gG8pwaJlaUCgYEAgr7poRB+ZlaCCY0RYtjo\n" ++ "mYYBKD02vp5BzdKSB3V1zeLuBWM84pjB6b3Nw0fyDig+X7fH3uHEGN+USRs3hSj6\n" ++ "BqD01s1OT6fyfbYXNw5A1r+nP+5h26Wbr0zblcKxdQj4qbbBZC8hOJNhqTqqA0Qe\n" ++ "MmzF7jiBaiZV/Cyj4x1f9BcCgYEAhjL6SeuTuOctTqs/5pz5lDikh6DpUGcH8qaV\n" ++ "o6aRAHHcMhYkZzpk8yh1uUdD7516APmVyvn6rrsjjhLVq4ZAJjwB6HWvE9JBN0TR\n" ++ "bILF+sREHUqU8Zn2Ku0nxyfXCKIOnxlx/J/y4TaGYqBqfXNFWiXNUrjQbIlQv/xR\n" ++ "K48g/MECgYBZdQlYbMSDmfPCC5cxkdjrkmAl0EgV051PWAi4wR+hLxIMRjHBvAk7\n" ++ "IweobkFvT4TICulgroLkYcSa5eOZGxB/DHqcQCbWj3reFV0VpzmTDoFKG54sqBRl\n" ++ "vVntGt0pfA40fF17VoS7riAdHF53ippTtsovHEsg5tq5NrBl5uKm2g==\n" ++ "-----END RSA PRIVATE KEY-----\n"). setup(InitFun, TermFun) -> ok = leo_logger_api:new("./", ?LOG_LEVEL_INFO), ok = leo_logger_api:new(?LOG_GROUP_ID_ACCESS, ?LOG_ID_ACCESS, "./", ?LOG_FILENAME_ACCESS), io:format(user, "cwd:~p~n",[os:cmd("pwd")]), [] = os:cmd("epmd -daemon"), {ok, Hostname} = inet:gethostname(), NetKernelNode = list_to_atom("netkernel_0@" ++ Hostname), net_kernel:start([NetKernelNode, shortnames]), inets:start(), Args = " -pa ../deps/*/ebin " ++ " -kernel error_logger '{file, \"../kernel.log\"}' ", {ok, Node0} = slave:start_link(list_to_atom(Hostname), 'storage_0', Args), {ok, Node1} = slave:start_link(list_to_atom(Hostname), 'storage_1', Args), ok = leo_misc:init_env(), meck:new(leo_redundant_manager_api, [non_strict]), meck:expect(leo_redundant_manager_api, get_redundancies_by_key, fun(_Method, _Key) -> {ok, #redundancies{id = 0, nodes = [#redundant_node{node = Node0, available = true}, #redundant_node{node = Node1, available = true}], n = 2, r = 1, w = 1, d = 1}} end), meck:new(leo_s3_endpoint, [non_strict]), meck:expect(leo_s3_endpoint, get_endpoints, 0, {ok, [{endpoint, <<"localhost">>, 0}]}), meck:new(leo_s3_bucket, [non_strict]), meck:expect(leo_s3_bucket, get_latest_bucket, fun(_BucketName) -> {ok, #?BUCKET{name =_BucketName, acls = [#bucket_acl_info{user_id = ?GRANTEE_ALL_USER, permissions = [read, write]}]}} end), Date = erlang:list_to_binary(leo_http:rfc1123_date(leo_date:now())), meck:new(cowboy_clock, [non_strict]), meck:expect(cowboy_clock, rfc1123, 0, Date), meck:new(leo_watchdog_state, [non_strict]), meck:expect(leo_watchdog_state, find_not_safe_items, fun() -> not_found end), meck:new(leo_metrics_req, [non_strict]), meck:expect(leo_metrics_req, notify, fun(_) -> ok end), ok = rpc:call(Node1, meck, new, [leo_metrics_req, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_metrics_req, notify, fun(_) -> ok end]), code:add_path("../cherly/ebin"), ok = file:write_file("./server_cert.pem", ?SSL_CERT_DATA), ok = file:write_file("./server_key.pem", ?SSL_KEY_DATA), application:start(leo_cache), leo_cache_api:start(), leo_pod:start_link(?POD_LOH_WORKER, ?env_loh_put_worker_pool_size(), ?env_loh_put_worker_buffer_size(), leo_large_object_worker, [], fun(_) -> void end), InitFun(), [TermFun, Node0, Node1]. setup_s3_api() -> application:start(crypto), application:start(ranch), application:start(cowboy), {ok, Options} = leo_gateway_app:get_options(), InitFun = fun() -> leo_gateway_http_commons:start( Options#http_options{port = 12345, is_compatible_with_s3_content_type = true}) end, TermFun = fun() -> leo_gateway_s3_api:stop() end, setup(InitFun, TermFun). setup_rest_api() -> application:start(crypto), application:start(ranch), application:start(cowboy), {ok, Options} = leo_gateway_app:get_options(), InitFun = fun() -> leo_gateway_http_commons:start( Options#http_options{handler = leo_gateway_rest_api, port = 12345, is_compatible_with_s3_content_type = true}) end, TermFun = fun() -> leo_gateway_rest_api:stop() end, setup(InitFun, TermFun). teardown([TermFun, Node0, Node1]) -> inets:stop(), net_kernel:stop(), slave:stop(Node0), slave:stop(Node1), meck:unload(), TermFun(), cowboy:stop_listener(leo_gateway_s3_api), cowboy:stop_listener(leo_gateway_s3_api_ssl), application:stop(crypto), application:stop(ranch), application:stop(cowboy), leo_cache_api:stop(), leo_logger_api:stop(), timer:sleep(250), ok. get_bucket_list_error_([_TermFun, _Node0, Node1]) -> fun() -> timer:sleep(150), ok = rpc:call(Node1, meck, new, [leo_storage_handler_directory, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_directory, find_by_parent_dir, 1, {error, some_error}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, Body}} = httpc:request(get, {lists:append( ["http://", ?TARGET_HOST, ":12345/a/b?prefix=pre"]), [{"Date", Date}]}, [], [{full_result, false}]), Xml = io_lib:format(?XML_ERROR, [?XML_ERROR_CODE_InternalError, ?XML_ERROR_MSG_InternalError, "a/b/", ""]), ?assertEqual(erlang:list_to_binary(Xml), erlang:list_to_binary(Body)), ?assertEqual(500, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_directory]) end, ok end. get_bucket_list_empty_([_TermFun, _Node0, Node1]) -> fun() -> timer:sleep(150), ok = rpc:call(Node1, meck, new, [leo_storage_handler_directory, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_directory, find_by_parent_dir, 4, {ok, []}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, Body}} = httpc:request(get, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b?prefix=pre&delimiter=/"]), [{"Date", Date}]}, [], [{full_result, false}]), ?assertEqual(200, SC), Xml = io_lib:format(?XML_OBJ_LIST, ["a", "pre", "1000", "", "false" "", ""]), ?assertEqual(erlang:list_to_binary(Xml), erlang:list_to_binary(Body)) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_directory]) end, ok end. get_bucket_list_normal1_([_TermFun, _Node0, Node1]) -> fun() -> timer:sleep(150), ok = rpc:call(Node1, meck, new, [leo_storage_handler_directory, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_directory, find_by_parent_dir, 4, {ok, [#?METADATA{ key = <<"localhost/a/b/pre/test.png">>, addr_id = 0, ksize = 8, dsize = 0, meta = <<>>, msize = 0, csize = 0, cnumber = 0, cindex = 0, offset = 0, clock = 63511805822, timestamp = 19740926, checksum = 0, ring_hash = 0, cluster_id = [], ver = 0, del = ?DEL_FALSE } 0 , 8 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 63511805822 , 19740926 , 0 , 0 } ]}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC,Body}} = httpc:request(get, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b/?prefix=pre&delimiter=/"]), [{"Date", Date}]}, [], [{full_result, false}]), ?assertEqual(200, SC), {_XmlDoc, Rest} = xmerl_scan:string(Body), ?assertEqual([], Rest) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_directory]) end, ok end. get_bucket_acl_normal1_([_TermFun, _Node0,_Node1]) -> fun() -> timer:sleep(150), meck:expect(leo_s3_bucket, get_acls, 1, {ok, [#bucket_acl_info{user_id = ?GRANTEE_ALL_USER, permissions = [read, write]}]}), meck:expect(leo_s3_bucket, find_bucket_by_name, 1, {ok, #?BUCKET{name = "bucket", access_key_id = <<"ackid">>, acls = [#bucket_acl_info{user_id = ?GRANTEE_ALL_USER, permissions = [read, write]}, #bucket_acl_info{user_id = ?GRANTEE_AUTHENTICATED_USER, permissions = [full_control]}] }}), meck:new(leo_s3_auth, [no_link, non_strict]), meck:expect(leo_s3_auth, authenticate, 3, {ok, ["hoge"], undefined}), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC,Body}} = httpc:request(get, {lists:append(["http://", ?TARGET_HOST, ":12345/bucket?acl"]), [{"Date", Date}, {"Authorization","AWS auth:hoge"}]}, [], [{full_result, false}]), ?assertEqual(200, SC), {_XmlDoc, Rest} = xmerl_scan:string(Body), ?assertEqual([], Rest) catch throw:Reason -> throw(Reason) after meck:unload(leo_s3_auth) end, ok end. head_object_notfound_([_TermFun, Node0, Node1]) -> fun() -> ok = rpc:call(Node0, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node0, meck, expect, [leo_storage_handler_object, head, 2, {error, not_found}]), ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, head, 2, {error, not_found}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, _Body}} = httpc:request(head, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b"]), [{"Date", Date}]}, [], [{full_result, false}]), ?assertEqual(404, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node0, meck, unload, [leo_storage_handler_object]), ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. head_object_error_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, head, 2, {error, foobar}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, _Body}} = httpc:request(head, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b"]), [{"Date", Date}]}, [], [{full_result, false}]), ?assertEqual(500, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. head_object_normal1_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, head, 2, {ok, #?METADATA{ key = <<"a/b/c/d.png">>, addr_id = 0, ksize = 4, dsize = 16384, meta = <<>>, msize = 0, csize = 0, cnumber = 0, cindex = 0, offset = 1, clock = 63511805822, timestamp = 19740926, checksum = 0, ring_hash = 0, cluster_id = [], ver = 0, del = ?DEL_FALSE } }]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {{_, SC, _}, Headers, _Body}} = httpc:request(head, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b/c/d.png"]), [{"Date", Date}, {"connection", "close"}]}, [], []), ?assertEqual({"content-length", "16384"}, lists:keyfind("content-length", 1, Headers)), ?assertEqual(false, lists:keyfind("transfer-encoding", 1, Headers)), ?assertEqual(200, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. get_object_error_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, get, 3, {error, foobar}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, Body}} = httpc:request(get, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b.png"]), [{"Date", Date}]}, [], [{full_result, false}]), Xml = io_lib:format(?XML_ERROR, [?XML_ERROR_CODE_InternalError, ?XML_ERROR_MSG_InternalError, "a/b.png", ""]), ?assertEqual(erlang:list_to_binary(Xml), erlang:list_to_binary(Body)), ?assertEqual(500, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. get_object_invalid_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, get, 3, {error, foobar}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, _Body}} = httpc:request(head, {lists:append(["http://", ?TARGET_HOST, ":12345/"]), [{"Date", Date}, {"Host", ""}]}, [{version, "HTTP/1.0"}], [{full_result, false}]), ?assertEqual(400, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. get_object_notfound_([_TermFun, Node0, Node1]) -> fun() -> ok = rpc:call(Node0, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node0, meck, expect, [leo_storage_handler_object, get, 3, {error, not_found}]), ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, get, 3, {error, not_found}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, Body}} = httpc:request(get, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b/c.png"]), [{"Date", Date}]}, [], [{full_result, false}]), Xml = io_lib:format(?XML_ERROR, [?XML_ERROR_CODE_NoSuchKey, ?XML_ERROR_MSG_NoSuchKey, "a/b/c.png", ""]), ?assertEqual(erlang:list_to_binary(Xml), erlang:list_to_binary(Body)), ?assertEqual(404, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node0, meck, unload, [leo_storage_handler_object]), ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. get_object_normal1_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, get, 3, {ok, #?METADATA{ key = <<"">>, addr_id = 0, ksize = 4, dsize = 4, meta = <<>>, msize = 0, csize = 0, cnumber = 0, cindex = 0, offset = 1, clock = calendar:datetime_to_gregorian_seconds(erlang:universaltime()), timestamp = 19740926, checksum = 0, ring_hash = 0, cluster_id = [], ver = 0, del = ?DEL_FALSE }, <<"body">>}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {{_, SC, _}, Headers, Body}} = httpc:request(get, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b.png"]), [{"Date", Date}, {"connection", "close"}]}, [], []), ?assertEqual(200, SC), ?assertEqual("body", Body), ContentType = proplists:get_value("content-type", Headers), ?assertEqual(true, ContentType =:= "application/octet-stream" orelse ContentType =:= "image/png"), ?assertEqual(undefined, proplists:get_value("X-From-Cache", Headers)) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. get_object_cmeta_normal1_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), CMetaBin = term_to_binary([{<<"x-amz-meta-test">>, <<"custom metadata">>},{<<"x-amz-meta-leofs-content-type">>,<<"image/svg">>}]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, get, 3, {ok, #?METADATA{ key = <<"">>, addr_id = 0, ksize = 4, dsize = 4, meta = CMetaBin, msize = byte_size(CMetaBin), csize = 0, cnumber = 0, cindex = 0, offset = 1, clock = calendar:datetime_to_gregorian_seconds(erlang:universaltime()), timestamp = 19740926, checksum = 0, ring_hash = 0, cluster_id = [], ver = 0, del = ?DEL_FALSE }, <<"body">>}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {{_, SC, _}, Headers, Body}} = httpc:request(get, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b.png"]), [{"Date", Date}, {"connection", "close"}]}, [], []), ?assertEqual(200, SC), ?assertEqual("body", Body), ?assertEqual("image/svg", proplists:get_value("content-type", Headers)), ?assertEqual(undefined, proplists:get_value("X-From-Cache", Headers)), ?assertEqual("custom metadata", proplists:get_value("x-amz-meta-test", Headers)) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. get_object_acl_normal1_([_TermFun, _Node0, Node1]) -> fun() -> meck:expect(leo_s3_bucket, get_acls, 1, {ok, [#bucket_acl_info{user_id = ?GRANTEE_ALL_USER, permissions = [read, write]}]}), meck:expect(leo_s3_bucket, find_bucket_by_name, 1, {ok, #?BUCKET{name = "bucket", access_key_id = <<"ackid">>, acls = [#bucket_acl_info{user_id = ?GRANTEE_ALL_USER, permissions = [read, write]}, #bucket_acl_info{user_id = ?GRANTEE_AUTHENTICATED_USER, permissions = [full_control]}] }}), meck:new(leo_s3_auth, [no_link, non_strict]), meck:expect(leo_s3_auth, authenticate, 3, {ok, ["hoge"], undefined}), ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, head, 2, {ok, #?METADATA{ key = <<"bucket/object">>, addr_id = 0, ksize = 4, dsize = 16384, meta = <<>>, msize = 0, csize = 0, cnumber = 0, cindex = 0, offset = 1, clock = 63511805822, timestamp = 19740926, checksum = 0, ring_hash = 0, cluster_id = [], ver = 0, del = ?DEL_FALSE } }]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC,Body}} = httpc:request(get, {lists:append(["http://", ?TARGET_HOST, ":12345/bucket/object?acl"]), [{"Date", Date}, {"Authorization","AWS auth:hoge"}]}, [], [{full_result, false}]), ?assertEqual(200, SC), {_XmlDoc, Rest} = xmerl_scan:string(Body), ?assertEqual([], Rest) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]), meck:unload(leo_s3_auth) end, ok end. range_object_normal1_([_TermFun, _Node0, Node1]) -> range_object_base([_TermFun, _Node0, Node1], "bytes=1-2"). range_object_normal2_([_TermFun, _Node0, Node1]) -> range_object_base([_TermFun, _Node0, Node1], "bytes=1-"). range_object_normal3_([_TermFun, _Node0, Node1]) -> range_object_base([_TermFun, _Node0, Node1], "bytes=-1"). range_object_base([_TermFun, _Node0, Node1], RangeValue) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, head, 2, {ok, #?METADATA{ key = <<"a/b.png">>, addr_id = 0, ksize = 4, dsize = 16384, meta = <<>>, msize = 0, csize = 0, cnumber = 0, cindex = 0, offset = 1, clock = 63505750315, timestamp = 19740926, checksum = 0, ring_hash = 0, cluster_id = [], ver = 0, del = ?DEL_FALSE } }]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, get, 5, {ok, #?METADATA{ key = <<"">>, addr_id = 0, ksize = 2, dsize = 2, meta = <<>>, msize = 0, csize = 0, cnumber = 0, cindex = 0, offset = 1, clock = calendar:datetime_to_gregorian_seconds(erlang:universaltime()), timestamp = 19740926, checksum = 0, ring_hash = 0, cluster_id = [], ver = 0, del = ?DEL_FALSE }, <<"od">>}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {{_, SC, _}, _Headers, Body}} = httpc:request(get, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b.png"]), [{"Date", Date},{"connection", "close"},{"range", RangeValue}]}, [], []), ?assertEqual(206, SC), ?assertEqual("od", Body) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. delete_object_notfound_([_TermFun, Node0, Node1]) -> fun() -> ok = rpc:call(Node0, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node0, meck, expect, [leo_storage_handler_object, delete, 2, {error, not_found}]), ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, delete, 2, {error, not_found}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, _Body}} = httpc:request(delete, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b.png"]), [{"Date", Date}, {"Authorization","auth"}]}, [], [{full_result, false}]), ?assertEqual(204, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node0, meck, unload, [leo_storage_handler_object]), ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. delete_object_error_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, delete, 2, {error, foobar}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, Body}} = httpc:request(delete, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b.png"]), [{"Date", Date}, {"Authorization","auth"}]}, [], [{full_result, false}]), Xml = io_lib:format(?XML_ERROR, [?XML_ERROR_CODE_InternalError, ?XML_ERROR_MSG_InternalError, "a/b.png", ""]), ?assertEqual(erlang:list_to_binary(Xml), erlang:list_to_binary(Body)), ?assertEqual(500, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. delete_object_normal1_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, delete, 2, ok]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, _Body}} = httpc:request(delete, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b.png"]), [{"Date", Date}, {"Authorization","auth"}]}, [], [{full_result, false}]), ?assertEqual(204, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. -undef(EUNIT_DEBUG_VAL_DEPTH). -define(EUNIT_DEBUG_VAL_DEPTH, 1024). put_object_error_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, put, 2, {error, foobar}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, Body}} = httpc:request(put, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b.png"]), [{"Date", Date}, {"Authorization","auth"}], "image/png", "body"}, [], [{full_result, false}]), Xml = io_lib:format(?XML_ERROR, [?XML_ERROR_CODE_InternalError, ?XML_ERROR_MSG_InternalError, "a/b.png", ""]), ?assertEqual(erlang:list_to_binary(Xml), erlang:list_to_binary(Body)), ?assertEqual(500, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. put_object_error_metadata_too_large_([_TermFun, _Node0, _Node1]) -> fun() -> try Date = leo_http:rfc1123_date(leo_date:now()), Dummy = lists:flatten(["test" || _ <- lists:seq(1, ?HTTP_METADATA_LIMIT * 2 div 4)]), Dummy = crypto : rand_bytes(?HTTP_METADATA_LIMIT * 2 ) , {ok, {SC, Body}} = httpc:request(put, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b.png"]), [{"Date", Date}, {"Authorization","auth"}, {"x-amz-meta-test", Dummy}], "image/png", "body"}, [], [{full_result, false}]), Xml = io_lib:format(?XML_ERROR, [?XML_ERROR_CODE_MetadataTooLarge, ?XML_ERROR_MSG_MetadataTooLarge, "a/b.png", ""]), ?assertEqual(erlang:list_to_binary(Xml), erlang:list_to_binary(Body)), ?assertEqual(400, SC) catch throw:Reason -> throw(Reason) end, ok end. put_object_normal1_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, put, 2, {ok, 1}]), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, _Body}} = httpc:request(put, {lists:append(["http://", ?TARGET_HOST, ":12345/a/b.png"]), [{"Date", Date}, {"Authorization","auth"}], "image/png", "body"}, [], [{full_result, false}]), ?assertEqual(200, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]) end, ok end. -define(CHUNKSIZE, 4096). -define(AWSCHUNKEDSIZE, 65536). gen_chunks(PrevSign, SignHead, SignKey, 0, Acc) -> Bin = <<>>, {Chunk, _Signature} = compute_chunk(PrevSign, SignHead, SignKey, Bin), <<Acc/binary, Chunk/binary>>; gen_chunks(PrevSign, SignHead, SignKey, Remain, Acc) when Remain < ?CHUNKSIZE -> Bin = crypto:strong_rand_bytes(Remain), {Chunk, Signature} = compute_chunk(PrevSign, SignHead, SignKey, Bin), gen_chunks(Signature, SignHead, SignKey, 0, <<Acc/binary, Chunk/binary>>); gen_chunks(PrevSign, SignHead, SignKey, Remain, Acc) -> Bin = crypto:strong_rand_bytes(?CHUNKSIZE), {Chunk, Signature} = compute_chunk(PrevSign, SignHead, SignKey, Bin), gen_chunks(Signature, SignHead, SignKey, Remain - ?CHUNKSIZE, <<Acc/binary, Chunk/binary>>). compute_chunk(PrevSign, SignHead, SignKey, Bin) -> SizeHex = leo_hex:integer_to_hex(byte_size(Bin), 6), ChunkHashBin = leo_hex:binary_to_hexbin(crypto:hash(sha256, Bin)), BinToSign = <<"AWS4-HMAC-SHA256-PAYLOAD\n", SignHead/binary, PrevSign/binary, "\n", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\n", ChunkHashBin/binary>>, Signature = crypto:hmac(sha256, SignKey, BinToSign), Sign = leo_hex:binary_to_hexbin(Signature), SizeHexBin = list_to_binary(SizeHex), Chunk = <<SizeHexBin/binary, ";", "chunk-signature=", Sign/binary, "\r\n", Bin/binary, "\r\n">>, {Chunk, Sign}. put_object_aws_chunked_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, put, 2, {ok, 1}]), meck:new(leo_s3_auth, [no_link, non_strict]), Signature = <<"642797dcfdf817ac23b553420f52c160847d3747b2e86e5ac9d07cc5e7f60f63">>, SignHead = <<"20150706T051217Z\n20150706/us-east-1/s3/aws4_request\n">>, SignKey = <<"2040321d898be34c82d1db9e132124f11eb18a3d21569d1ed58b460b88954ac7">>, meck:expect(leo_s3_auth, authenticate, 3, {ok, <<"05236">>, {Signature, SignHead, SignKey}}), meck:expect(leo_s3_bucket, get_acls, 1, not_found), Chunks = gen_chunks(Signature, SignHead, SignKey, ?AWSCHUNKEDSIZE, <<>>), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, _Body}} = httpc:request(put, {lists:append(["http://", ?TARGET_HOST, ":12345/testjv4/testFile.large.one"]), [{"Date", Date}, {"authorization","AWS4-HMAC-SHA256 Credential=05236/20150706/us-east-1/s3/aws4_request, SignedHeaders=content-length, Signature=642797dcfdf817ac23b553420f52c160847d3747b2e86e5ac9d07cc5e7f60f63"}, {"x-amz-content-sha256", "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"}, {"x-amz-decoded-content-length", integer_to_list(?AWSCHUNKEDSIZE)} ], "image/png", Chunks}, [], [{full_result, false}]), ?assertEqual(200, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]), ok = meck:unload(leo_s3_auth) end, ok end. put_object_aws_chunked_error_([_TermFun, _Node0, Node1]) -> fun() -> ok = rpc:call(Node1, meck, new, [leo_storage_handler_object, [no_link, non_strict]]), ok = rpc:call(Node1, meck, expect, [leo_storage_handler_object, put, 2, {ok, 1}]), meck:new(leo_s3_auth, [no_link, non_strict]), Signature = <<"642797dcfdf817ac23b553420f52c160847d3747b2e86e5ac9d07cc5e7f60f63">>, SignatureI = <<"incorrect">>, SignHead = <<"20150706T051217Z\n20150706/us-east-1/s3/aws4_request\n">>, SignKey = <<"2040321d898be34c82d1db9e132124f11eb18a3d21569d1ed58b460b88954ac7">>, meck:expect(leo_s3_auth, authenticate, 3, {ok, <<"05236">>, {Signature, SignHead, SignKey}}), meck:expect(leo_s3_bucket, get_latest_bucket, 1, not_found), Chunks = gen_chunks(SignatureI, SignHead, SignKey, ?AWSCHUNKEDSIZE, <<>>), try Date = leo_http:rfc1123_date(leo_date:now()), {ok, {SC, _Body}} = httpc:request(put, {lists:append(["http://", ?TARGET_HOST, ":12345/testjv4/testFile.large.one"]), [{"Date", Date}, {"authorization","AWS4-HMAC-SHA256 Credential=05236/20150706/us-east-1/s3/aws4_request, SignedHeaders=content-length, Signature=642797dcfdf817ac23b553420f52c160847d3747b2e86e5ac9d07cc5e7f60f63"}, {"x-amz-content-sha256", "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"}, {"x-amz-decoded-content-length", integer_to_list(?AWSCHUNKEDSIZE)} ], "image/png", Chunks}, [], [{full_result, false}]), ?assertEqual(403, SC) catch throw:Reason -> throw(Reason) after ok = rpc:call(Node1, meck, unload, [leo_storage_handler_object]), ok = meck:unload(leo_s3_auth) end, ok end. proper_([_TermFun , _ Node0 , _ Node1 ] ) - > { timeout , 600 , ? _ assertEqual(true , leo_gateway_web_prop : test ( ) ) } . -endif.
d7a3b0333080bc68f5ac62ba61bf70dc65ee8c88713aa899ac49520234588110
themattchan/advent-of-code
day14.hs
{-# LANGUAGE BangPatterns #-} import Utils input :: Int input = 681901 gen :: [Int] gen = 3 : 7 : go 0 1 2 where go !i !j !l = let ix = (gen !! i) jx = (gen !! j) x = ix + jx (x1, x2) = divMod x 10 f = if x1 == 0 then (x2 :) else ((x1 :) . (x2 :)) l' = l + if x1 == 0 then 1 else 2 i' = (i + 1 + ix) `mod` l' j' = (j + 1 + jx) `mod` l' in f (go i' j' l') tests = [ take 10 (drop 9 gen) == [5,1,5,8,9,1,6,7,7,9] , take 10 (drop 5 gen) == [0,1,2,4,5,1,5,8,9,1] , take 10 (drop 18 gen) == [9,2,5,1,0,7,1,0,8,5] , take 10 (drop 2018 gen) == [5,9,4,1,4,2,9,8,8,2] ] main = do putStrLn $ foldMap show $ take 10 (drop input gen)
null
https://raw.githubusercontent.com/themattchan/advent-of-code/0b08a4fbadf7e713d40044523af3debb7d0cb6b9/2018/day14/day14.hs
haskell
# LANGUAGE BangPatterns #
import Utils input :: Int input = 681901 gen :: [Int] gen = 3 : 7 : go 0 1 2 where go !i !j !l = let ix = (gen !! i) jx = (gen !! j) x = ix + jx (x1, x2) = divMod x 10 f = if x1 == 0 then (x2 :) else ((x1 :) . (x2 :)) l' = l + if x1 == 0 then 1 else 2 i' = (i + 1 + ix) `mod` l' j' = (j + 1 + jx) `mod` l' in f (go i' j' l') tests = [ take 10 (drop 9 gen) == [5,1,5,8,9,1,6,7,7,9] , take 10 (drop 5 gen) == [0,1,2,4,5,1,5,8,9,1] , take 10 (drop 18 gen) == [9,2,5,1,0,7,1,0,8,5] , take 10 (drop 2018 gen) == [5,9,4,1,4,2,9,8,8,2] ] main = do putStrLn $ foldMap show $ take 10 (drop input gen)
10df439ebc2829ea5b10f719a1ffb04a76d5ad6021d1e65b306156d7c87dd668
evosec/metabase-firebird-driver
firebird.clj
(ns metabase.driver.firebird (:require [clojure [set :as set] [string :as str]] [clojure.java.jdbc :as jdbc] [honeysql.core :as hsql] [honeysql.format :as hformat] [java-time :as t] [metabase.driver :as driver] [metabase.driver.common :as driver.common] ;; [metabase.driver.sql-jdbc.sync.describe-database :as sql-jdbc.sync.describe-database] [metabase.driver.sql-jdbc [common :as sql-jdbc.common] [connection :as sql-jdbc.conn] [sync :as sql-jdbc.sync]] [metabase.driver.sql-jdbc.sync.common :as sql-jdbc.sync.common] [metabase.driver.sql.query-processor :as sql.qp] [metabase.util [honeysql-extensions :as hx]] [metabase.util.ssh :as ssh]) (:import [java.sql DatabaseMetaData Time] [java.time LocalDate LocalDateTime LocalTime OffsetDateTime OffsetTime ZonedDateTime] [java.sql Connection DatabaseMetaData ResultSet])) (driver/register! :firebird, :parent :sql-jdbc) (defn- firebird->spec "Create a database specification for a FirebirdSQL database." [{:keys [host port db jdbc-flags] :or {host "localhost", port 3050, db "", jdbc-flags ""} :as opts}] (merge {:classname "org.firebirdsql.jdbc.FBDriver" :subprotocol "firebirdsql" :subname (str "//" host ":" port "/" db jdbc-flags)} (dissoc opts :host :port :db :jdbc-flags))) Obtain connection properties for connection to a Firebird database . (defmethod sql-jdbc.conn/connection-details->spec :firebird [_ details] (-> details (update :port (fn [port] (if (string? port) (Integer/parseInt port) port))) (set/rename-keys {:dbname :db}) firebird->spec (sql-jdbc.common/handle-additional-options details))) (defmethod driver/can-connect? :firebird [driver details] (let [connection (sql-jdbc.conn/connection-details->spec driver (ssh/include-ssh-tunnel! details))] (= 1 (first (vals (first (jdbc/query connection ["SELECT 1 FROM RDB$DATABASE"]))))))) ;; Use pattern matching because some parameters can have a length parameter, e.g. VARCHAR(255) (def ^:private database-type->base-type (sql-jdbc.sync/pattern-based-database-type->base-type [[#"INT64" :type/BigInteger] [#"DECIMAL" :type/Decimal] [#"FLOAT" :type/Float] [#"BLOB" :type/*] [#"INTEGER" :type/Integer] [#"NUMERIC" :type/Decimal] [#"DOUBLE" :type/Float] [#"SMALLINT" :type/Integer] [#"CHAR" :type/Text] [#"BIGINT" :type/BigInteger] [#"TIMESTAMP" :type/DateTime] [#"DATE" :type/Date] [#"TIME" :type/Time] [#"BLOB SUB_TYPE 0" :type/*] [#"BLOB SUB_TYPE 1" :type/Text] [#"DOUBLE PRECISION" :type/Float] [#"BOOLEAN" :type/Boolean]])) Map Firebird data types to base types (defmethod sql-jdbc.sync/database-type->base-type :firebird [_ database-type] (database-type->base-type database-type)) Use " FIRST " instead of " LIMIT " (defmethod sql.qp/apply-top-level-clause [:firebird :limit] [_ _ honeysql-form {value :limit}] (assoc honeysql-form :modifiers [(format "FIRST %d" value)])) ;; Use "SKIP" instead of "OFFSET" (defmethod sql.qp/apply-top-level-clause [:firebird :page] [_ _ honeysql-form {{:keys [items page]} :page}] (assoc honeysql-form :modifiers [(format "FIRST %d SKIP %d" items (* items (dec page)))])) When selecting constants Firebird does n't check privileges , we have to select all fields (defn simple-select-probe-query [driver schema table] {:pre [(string? table)]} (let [honeysql {:select [:*] :from [(sql.qp/->honeysql driver (hx/identifier :table schema table))] :where [:not= 1 1]} honeysql (sql.qp/apply-top-level-clause driver :limit honeysql {:limit 0})] (sql.qp/format-honeysql driver honeysql))) (defn- execute-select-probe-query [driver ^Connection conn [sql & params]] {:pre [(string? sql)]} (with-open [stmt (sql-jdbc.sync.common/prepare-statement driver conn sql params)] attempting to execute the SQL statement will throw an Exception if we do n't have permissions ; otherwise it will wheter or not it returns a ResultSet , but we can ignore that since we have enough info to proceed at ;; this point. (.execute stmt))) (defmethod sql-jdbc.sync/have-select-privilege? :sql-jdbc [driver conn table-schema table-name] ;; Query completes = we have SELECT privileges ;; Query throws some sort of no permissions exception = no SELECT privileges (let [sql-args (simple-select-probe-query driver table-schema table-name)] (try (execute-select-probe-query driver conn sql-args) true (catch Throwable _ false)))) (defmethod sql-jdbc.sync/active-tables :firebird [& args] (apply sql-jdbc.sync/post-filtered-active-tables args)) Convert unix time to a timestamp (defmethod sql.qp/unix-timestamp->honeysql [:firebird :seconds] [_ _ expr] (hsql/call :DATEADD (hsql/raw "SECOND") expr (hx/cast :TIMESTAMP (hx/literal "01-01-1970 00:00:00")))) ;; Helpers for Date extraction TODO : This can probably simplified a lot by using concentation instead of ;; replacing parts of the format recursively Specifies what Substring to replace for a given time unit (defn- get-unit-placeholder [unit] (case unit :SECOND :ss :MINUTE :mm :HOUR :hh :DAY :DD :MONTH :MM :YEAR :YYYY)) (defn- get-unit-name [unit] (case unit 0 :SECOND 1 :MINUTE 2 :HOUR 3 :DAY 4 :MONTH 5 :YEAR)) ;; Replace the specified part of the timestamp (defn- replace-timestamp-part [input unit expr] (hsql/call :replace input (hx/literal (get-unit-placeholder unit)) (hsql/call :extract unit expr))) (defn- format-step [expr input step wanted-unit] (if (> step wanted-unit) (format-step expr (replace-timestamp-part input (get-unit-name step) expr) (- step 1) wanted-unit) (replace-timestamp-part input (get-unit-name step) expr))) (defn- format-timestamp [expr format-template wanted-unit] (format-step expr (hx/literal format-template) 5 wanted-unit)) Firebird does n't have a date_trunc function , so use a workaround : First format the timestamp to a ;; string of the wanted resulution, then convert it back to a timestamp (defn- timestamp-trunc [expr format-str wanted-unit] (hx/cast :TIMESTAMP (format-timestamp expr format-str wanted-unit))) (defn- date-trunc [expr format-str wanted-unit] (hx/cast :DATE (format-timestamp expr format-str wanted-unit))) (defmethod sql.qp/date [:firebird :default] [_ _ expr] expr) Cast to TIMESTAMP if we need minutes or hours , since expr might be a DATE (defmethod sql.qp/date [:firebird :minute] [_ _ expr] (timestamp-trunc (hx/cast :TIMESTAMP expr) "YYYY-MM-DD hh:mm:00" 1)) (defmethod sql.qp/date [:firebird :minute-of-hour] [_ _ expr] (hsql/call :extract :MINUTE (hx/cast :TIMESTAMP expr))) (defmethod sql.qp/date [:firebird :hour] [_ _ expr] (timestamp-trunc (hx/cast :TIMESTAMP expr) "YYYY-MM-DD hh:00:00" 2)) (defmethod sql.qp/date [:firebird :hour-of-day] [_ _ expr] (hsql/call :extract :HOUR (hx/cast :TIMESTAMP expr))) ;; Cast to DATE to get rid of anything smaller than day (defmethod sql.qp/date [:firebird :day] [_ _ expr] (hx/cast :DATE expr)) Firebird DOW is 0 ( Sun ) - 6 ( Sat ) ; increment this to be consistent with Java , H2 , MySQL , and Mongo ( 1 - 7 ) (defmethod sql.qp/date [:firebird :day-of-week] [_ _ expr] (hx/+ (hsql/call :extract :WEEKDAY (hx/cast :DATE expr)) 1)) (defmethod sql.qp/date [:firebird :day-of-month] [_ _ expr] (hsql/call :extract :DAY expr)) Firebird YEARDAY starts from 0 ; increment this (defmethod sql.qp/date [:firebird :day-of-year] [_ _ expr] (hx/+ (hsql/call :extract :YEARDAY expr) 1)) ;; Cast to DATE because we do not want units smaller than days Use hsql / raw for DAY in dateadd because the keyword : WEEK gets surrounded with quotations (defmethod sql.qp/date [:firebird :week] [_ _ expr] (hsql/call :dateadd (hsql/raw "DAY") (hx/- 0 (hsql/call :extract :WEEKDAY (hx/cast :DATE expr))) (hx/cast :DATE expr))) (defmethod sql.qp/date [:firebird :week-of-year] [_ _ expr] (hsql/call :extract :WEEK expr)) (defmethod sql.qp/date [:firebird :month] [_ _ expr] (date-trunc expr "YYYY-MM-01" 4)) (defmethod sql.qp/date [:firebird :month-of-year] [_ _ expr] (hsql/call :extract :MONTH expr)) Use hsql / raw for MONTH in dateadd because the keyword : MONTH gets surrounded with quotations (defmethod sql.qp/date [:firebird :quarter] [_ _ expr] (hsql/call :dateadd (hsql/raw "MONTH") (hx/* (hx// (hx/- (hsql/call :extract :MONTH expr) 1) 3) 3) (date-trunc expr "YYYY-01-01" 5))) (defmethod sql.qp/date [:firebird :quarter-of-year] [_ _ expr] (hx/+ (hx// (hx/- (hsql/call :extract :MONTH expr) 1) 3) 1)) (defmethod sql.qp/date [:firebird :year] [_ _ expr] (hsql/call :extract :YEAR expr)) Firebird 2.x does n't support TRUE / FALSE , replacing them with 1 and 0 (defmethod sql.qp/->honeysql [:firebird Boolean] [_ bool] (if bool 1 0)) Firebird 2.x does n't support SUBSTRING arugments seperated by commas , but uses FROM and FOR keywords (defmethod sql.qp/->honeysql [:firebird :substring] [driver [_ arg start length]] (let [col-name (hformat/to-sql (sql.qp/->honeysql driver arg))] (if length (reify hformat/ToSql (to-sql [_] (str "substring(" col-name " FROM " start " FOR " length ")"))) (reify hformat/ToSql (to-sql [_] (str "substring(" col-name " FROM " start ")")))))) (defmethod sql.qp/add-interval-honeysql-form :firebird [driver hsql-form amount unit] (if (= unit :quarter) (recur driver hsql-form (hx/* amount 3) :month) (hsql/call :dateadd (hsql/raw (name unit)) amount hsql-form))) (defmethod sql.qp/current-datetime-honeysql-form :firebird [_] (hx/cast :timestamp (hx/literal :now))) (defmethod driver.common/current-db-time-date-formatters :firebird [_] (driver.common/create-db-time-formatters "yyyy-MM-dd HH:mm:ss.SSSS")) (defmethod driver.common/current-db-time-native-query :firebird [_] "SELECT CAST(CAST('Now' AS TIMESTAMP) AS VARCHAR(24)) FROM RDB$DATABASE") (defmethod driver/current-db-time :firebird [& args] (apply driver.common/current-db-time args)) (defmethod sql.qp/->honeysql [:firebird :stddev] [driver [_ field]] (hsql/call :stddev_samp (sql.qp/->honeysql driver field))) ;; MEGA HACK based on sqlite driver (defn- zero-time? [t] (= (t/local-time t) (t/local-time 0))) (defmethod sql.qp/->honeysql [:firebird LocalDate] [_ t] (hx/cast :DATE (t/format "yyyy-MM-dd" t))) (defmethod sql.qp/->honeysql [:firebird LocalDateTime] [driver t] (if (zero-time? t) (sql.qp/->honeysql driver (t/local-date t)) (hx/cast :TIMESTAMP (t/format "yyyy-MM-dd HH:mm:ss.SSSS" t)))) (defmethod sql.qp/->honeysql [:firebird LocalTime] [_ t] (hx/cast :TIME (t/format "HH:mm:ss.SSSS" t))) (defmethod sql.qp/->honeysql [:firebird OffsetDateTime] [driver t] (if (zero-time? t) (sql.qp/->honeysql driver (t/local-date t)) (hx/cast :TIMESTAMP (t/format "yyyy-MM-dd HH:mm:ss.SSSS" t)))) (defmethod sql.qp/->honeysql [:firebird OffsetTime] [_ t] (hx/cast :TIME (t/format "HH:mm:ss.SSSS" t))) (defmethod sql.qp/->honeysql [:firebird ZonedDateTime] [driver t] (if (zero-time? t) (sql.qp/->honeysql driver (t/local-date t)) (hx/cast :TIMESTAMP (t/format "yyyy-MM-dd HH:mm:ss.SSSS" t)))) (defmethod driver/supports? [:firebird :basic-aggregations] [_ _] true) (defmethod driver/supports? [:firebird :expression-aggregations] [_ _] true) (defmethod driver/supports? [:firebird :standard-deviation-aggregations] [_ _] true) (defmethod driver/supports? [:firebird :foreign-keys] [_ _] true) (defmethod driver/supports? [:firebird :nested-fields] [_ _] false) (defmethod driver/supports? [:firebird :set-timezone] [_ _] false) (defmethod driver/supports? [:firebird :nested-queries] [_ _] true) (defmethod driver/supports? [:firebird :binning] [_ _] false) (defmethod driver/supports? [:firebird :case-sensitivity-string-filter-options] [_ _] false)
null
https://raw.githubusercontent.com/evosec/metabase-firebird-driver/2e55040eb7b7d54da2aa9ac723e2b6fda3f22017/src/metabase/driver/firebird.clj
clojure
[metabase.driver.sql-jdbc.sync.describe-database :as sql-jdbc.sync.describe-database] Use pattern matching because some parameters can have a length parameter, e.g. VARCHAR(255) Use "SKIP" instead of "OFFSET" otherwise it will this point. Query completes = we have SELECT privileges Query throws some sort of no permissions exception = no SELECT privileges Helpers for Date extraction replacing parts of the format recursively Replace the specified part of the timestamp string of the wanted resulution, then convert it back to a timestamp Cast to DATE to get rid of anything smaller than day increment this to be consistent with Java , H2 , MySQL , and Mongo ( 1 - 7 ) increment this Cast to DATE because we do not want units smaller than days MEGA HACK based on sqlite driver
(ns metabase.driver.firebird (:require [clojure [set :as set] [string :as str]] [clojure.java.jdbc :as jdbc] [honeysql.core :as hsql] [honeysql.format :as hformat] [java-time :as t] [metabase.driver :as driver] [metabase.driver.common :as driver.common] [metabase.driver.sql-jdbc [common :as sql-jdbc.common] [connection :as sql-jdbc.conn] [sync :as sql-jdbc.sync]] [metabase.driver.sql-jdbc.sync.common :as sql-jdbc.sync.common] [metabase.driver.sql.query-processor :as sql.qp] [metabase.util [honeysql-extensions :as hx]] [metabase.util.ssh :as ssh]) (:import [java.sql DatabaseMetaData Time] [java.time LocalDate LocalDateTime LocalTime OffsetDateTime OffsetTime ZonedDateTime] [java.sql Connection DatabaseMetaData ResultSet])) (driver/register! :firebird, :parent :sql-jdbc) (defn- firebird->spec "Create a database specification for a FirebirdSQL database." [{:keys [host port db jdbc-flags] :or {host "localhost", port 3050, db "", jdbc-flags ""} :as opts}] (merge {:classname "org.firebirdsql.jdbc.FBDriver" :subprotocol "firebirdsql" :subname (str "//" host ":" port "/" db jdbc-flags)} (dissoc opts :host :port :db :jdbc-flags))) Obtain connection properties for connection to a Firebird database . (defmethod sql-jdbc.conn/connection-details->spec :firebird [_ details] (-> details (update :port (fn [port] (if (string? port) (Integer/parseInt port) port))) (set/rename-keys {:dbname :db}) firebird->spec (sql-jdbc.common/handle-additional-options details))) (defmethod driver/can-connect? :firebird [driver details] (let [connection (sql-jdbc.conn/connection-details->spec driver (ssh/include-ssh-tunnel! details))] (= 1 (first (vals (first (jdbc/query connection ["SELECT 1 FROM RDB$DATABASE"]))))))) (def ^:private database-type->base-type (sql-jdbc.sync/pattern-based-database-type->base-type [[#"INT64" :type/BigInteger] [#"DECIMAL" :type/Decimal] [#"FLOAT" :type/Float] [#"BLOB" :type/*] [#"INTEGER" :type/Integer] [#"NUMERIC" :type/Decimal] [#"DOUBLE" :type/Float] [#"SMALLINT" :type/Integer] [#"CHAR" :type/Text] [#"BIGINT" :type/BigInteger] [#"TIMESTAMP" :type/DateTime] [#"DATE" :type/Date] [#"TIME" :type/Time] [#"BLOB SUB_TYPE 0" :type/*] [#"BLOB SUB_TYPE 1" :type/Text] [#"DOUBLE PRECISION" :type/Float] [#"BOOLEAN" :type/Boolean]])) Map Firebird data types to base types (defmethod sql-jdbc.sync/database-type->base-type :firebird [_ database-type] (database-type->base-type database-type)) Use " FIRST " instead of " LIMIT " (defmethod sql.qp/apply-top-level-clause [:firebird :limit] [_ _ honeysql-form {value :limit}] (assoc honeysql-form :modifiers [(format "FIRST %d" value)])) (defmethod sql.qp/apply-top-level-clause [:firebird :page] [_ _ honeysql-form {{:keys [items page]} :page}] (assoc honeysql-form :modifiers [(format "FIRST %d SKIP %d" items (* items (dec page)))])) When selecting constants Firebird does n't check privileges , we have to select all fields (defn simple-select-probe-query [driver schema table] {:pre [(string? table)]} (let [honeysql {:select [:*] :from [(sql.qp/->honeysql driver (hx/identifier :table schema table))] :where [:not= 1 1]} honeysql (sql.qp/apply-top-level-clause driver :limit honeysql {:limit 0})] (sql.qp/format-honeysql driver honeysql))) (defn- execute-select-probe-query [driver ^Connection conn [sql & params]] {:pre [(string? sql)]} (with-open [stmt (sql-jdbc.sync.common/prepare-statement driver conn sql params)] wheter or not it returns a ResultSet , but we can ignore that since we have enough info to proceed at (.execute stmt))) (defmethod sql-jdbc.sync/have-select-privilege? :sql-jdbc [driver conn table-schema table-name] (let [sql-args (simple-select-probe-query driver table-schema table-name)] (try (execute-select-probe-query driver conn sql-args) true (catch Throwable _ false)))) (defmethod sql-jdbc.sync/active-tables :firebird [& args] (apply sql-jdbc.sync/post-filtered-active-tables args)) Convert unix time to a timestamp (defmethod sql.qp/unix-timestamp->honeysql [:firebird :seconds] [_ _ expr] (hsql/call :DATEADD (hsql/raw "SECOND") expr (hx/cast :TIMESTAMP (hx/literal "01-01-1970 00:00:00")))) TODO : This can probably simplified a lot by using concentation instead of Specifies what Substring to replace for a given time unit (defn- get-unit-placeholder [unit] (case unit :SECOND :ss :MINUTE :mm :HOUR :hh :DAY :DD :MONTH :MM :YEAR :YYYY)) (defn- get-unit-name [unit] (case unit 0 :SECOND 1 :MINUTE 2 :HOUR 3 :DAY 4 :MONTH 5 :YEAR)) (defn- replace-timestamp-part [input unit expr] (hsql/call :replace input (hx/literal (get-unit-placeholder unit)) (hsql/call :extract unit expr))) (defn- format-step [expr input step wanted-unit] (if (> step wanted-unit) (format-step expr (replace-timestamp-part input (get-unit-name step) expr) (- step 1) wanted-unit) (replace-timestamp-part input (get-unit-name step) expr))) (defn- format-timestamp [expr format-template wanted-unit] (format-step expr (hx/literal format-template) 5 wanted-unit)) Firebird does n't have a date_trunc function , so use a workaround : First format the timestamp to a (defn- timestamp-trunc [expr format-str wanted-unit] (hx/cast :TIMESTAMP (format-timestamp expr format-str wanted-unit))) (defn- date-trunc [expr format-str wanted-unit] (hx/cast :DATE (format-timestamp expr format-str wanted-unit))) (defmethod sql.qp/date [:firebird :default] [_ _ expr] expr) Cast to TIMESTAMP if we need minutes or hours , since expr might be a DATE (defmethod sql.qp/date [:firebird :minute] [_ _ expr] (timestamp-trunc (hx/cast :TIMESTAMP expr) "YYYY-MM-DD hh:mm:00" 1)) (defmethod sql.qp/date [:firebird :minute-of-hour] [_ _ expr] (hsql/call :extract :MINUTE (hx/cast :TIMESTAMP expr))) (defmethod sql.qp/date [:firebird :hour] [_ _ expr] (timestamp-trunc (hx/cast :TIMESTAMP expr) "YYYY-MM-DD hh:00:00" 2)) (defmethod sql.qp/date [:firebird :hour-of-day] [_ _ expr] (hsql/call :extract :HOUR (hx/cast :TIMESTAMP expr))) (defmethod sql.qp/date [:firebird :day] [_ _ expr] (hx/cast :DATE expr)) (defmethod sql.qp/date [:firebird :day-of-week] [_ _ expr] (hx/+ (hsql/call :extract :WEEKDAY (hx/cast :DATE expr)) 1)) (defmethod sql.qp/date [:firebird :day-of-month] [_ _ expr] (hsql/call :extract :DAY expr)) (defmethod sql.qp/date [:firebird :day-of-year] [_ _ expr] (hx/+ (hsql/call :extract :YEARDAY expr) 1)) Use hsql / raw for DAY in dateadd because the keyword : WEEK gets surrounded with quotations (defmethod sql.qp/date [:firebird :week] [_ _ expr] (hsql/call :dateadd (hsql/raw "DAY") (hx/- 0 (hsql/call :extract :WEEKDAY (hx/cast :DATE expr))) (hx/cast :DATE expr))) (defmethod sql.qp/date [:firebird :week-of-year] [_ _ expr] (hsql/call :extract :WEEK expr)) (defmethod sql.qp/date [:firebird :month] [_ _ expr] (date-trunc expr "YYYY-MM-01" 4)) (defmethod sql.qp/date [:firebird :month-of-year] [_ _ expr] (hsql/call :extract :MONTH expr)) Use hsql / raw for MONTH in dateadd because the keyword : MONTH gets surrounded with quotations (defmethod sql.qp/date [:firebird :quarter] [_ _ expr] (hsql/call :dateadd (hsql/raw "MONTH") (hx/* (hx// (hx/- (hsql/call :extract :MONTH expr) 1) 3) 3) (date-trunc expr "YYYY-01-01" 5))) (defmethod sql.qp/date [:firebird :quarter-of-year] [_ _ expr] (hx/+ (hx// (hx/- (hsql/call :extract :MONTH expr) 1) 3) 1)) (defmethod sql.qp/date [:firebird :year] [_ _ expr] (hsql/call :extract :YEAR expr)) Firebird 2.x does n't support TRUE / FALSE , replacing them with 1 and 0 (defmethod sql.qp/->honeysql [:firebird Boolean] [_ bool] (if bool 1 0)) Firebird 2.x does n't support SUBSTRING arugments seperated by commas , but uses FROM and FOR keywords (defmethod sql.qp/->honeysql [:firebird :substring] [driver [_ arg start length]] (let [col-name (hformat/to-sql (sql.qp/->honeysql driver arg))] (if length (reify hformat/ToSql (to-sql [_] (str "substring(" col-name " FROM " start " FOR " length ")"))) (reify hformat/ToSql (to-sql [_] (str "substring(" col-name " FROM " start ")")))))) (defmethod sql.qp/add-interval-honeysql-form :firebird [driver hsql-form amount unit] (if (= unit :quarter) (recur driver hsql-form (hx/* amount 3) :month) (hsql/call :dateadd (hsql/raw (name unit)) amount hsql-form))) (defmethod sql.qp/current-datetime-honeysql-form :firebird [_] (hx/cast :timestamp (hx/literal :now))) (defmethod driver.common/current-db-time-date-formatters :firebird [_] (driver.common/create-db-time-formatters "yyyy-MM-dd HH:mm:ss.SSSS")) (defmethod driver.common/current-db-time-native-query :firebird [_] "SELECT CAST(CAST('Now' AS TIMESTAMP) AS VARCHAR(24)) FROM RDB$DATABASE") (defmethod driver/current-db-time :firebird [& args] (apply driver.common/current-db-time args)) (defmethod sql.qp/->honeysql [:firebird :stddev] [driver [_ field]] (hsql/call :stddev_samp (sql.qp/->honeysql driver field))) (defn- zero-time? [t] (= (t/local-time t) (t/local-time 0))) (defmethod sql.qp/->honeysql [:firebird LocalDate] [_ t] (hx/cast :DATE (t/format "yyyy-MM-dd" t))) (defmethod sql.qp/->honeysql [:firebird LocalDateTime] [driver t] (if (zero-time? t) (sql.qp/->honeysql driver (t/local-date t)) (hx/cast :TIMESTAMP (t/format "yyyy-MM-dd HH:mm:ss.SSSS" t)))) (defmethod sql.qp/->honeysql [:firebird LocalTime] [_ t] (hx/cast :TIME (t/format "HH:mm:ss.SSSS" t))) (defmethod sql.qp/->honeysql [:firebird OffsetDateTime] [driver t] (if (zero-time? t) (sql.qp/->honeysql driver (t/local-date t)) (hx/cast :TIMESTAMP (t/format "yyyy-MM-dd HH:mm:ss.SSSS" t)))) (defmethod sql.qp/->honeysql [:firebird OffsetTime] [_ t] (hx/cast :TIME (t/format "HH:mm:ss.SSSS" t))) (defmethod sql.qp/->honeysql [:firebird ZonedDateTime] [driver t] (if (zero-time? t) (sql.qp/->honeysql driver (t/local-date t)) (hx/cast :TIMESTAMP (t/format "yyyy-MM-dd HH:mm:ss.SSSS" t)))) (defmethod driver/supports? [:firebird :basic-aggregations] [_ _] true) (defmethod driver/supports? [:firebird :expression-aggregations] [_ _] true) (defmethod driver/supports? [:firebird :standard-deviation-aggregations] [_ _] true) (defmethod driver/supports? [:firebird :foreign-keys] [_ _] true) (defmethod driver/supports? [:firebird :nested-fields] [_ _] false) (defmethod driver/supports? [:firebird :set-timezone] [_ _] false) (defmethod driver/supports? [:firebird :nested-queries] [_ _] true) (defmethod driver/supports? [:firebird :binning] [_ _] false) (defmethod driver/supports? [:firebird :case-sensitivity-string-filter-options] [_ _] false)
7ccc6b531f9d72cc4042a6db9f2afbfe0b3d96b4cb85a37cc073da029b194c92
gsakkas/rite
20060324-19:59:26-89f2326d390889b438f85e767726a3c5.seminal.ml
exception Unimplemented exception AlreadyDone (*** part a ***) type move = Home | Forward of float | Turn of float | For of int * (move)list (*** part b -- return move***) let makePoly sides len = let fSides = float_of_int sides in let turnAmount = (2.0 *. 3.1416) /. fSides in let rec makePolyHelp sidesLeft turn = match sidesLeft with 0 -> [] | 1 -> [Home](*::makePolyHelp 0 true*) | _ -> (Forward(len)::[Turn(turnAmount)]) (* ###################### ############# ######################################################## ############ ######### ############################################# ################################################ ###### *) in if sides < 3 then For(0, []) else ( let lst = makePolyHelp sides false in For(sides, lst) ) (*** part c ***) let interpLarge (movelist : move list) : (float*float) list = let rec loop movelist x y dir acc = match movelist with [] -> acc | Home::tl -> loop tl 0.0 0.0 dir ((0.0,0.0)::acc) | Forward f::tl -> let newX = x +. ( f *. (cos dir) ) in let newY = y +. ( f *. (sin dir) ) in loop tl newX newY dir ((newX,newY)::acc) | Turn f::tl -> let newDir = f +. dir in loop tl x y newDir acc | For (il, ml)::tl -> if il > 0 then let ild = il - 1 in let newMlTemp = For(ild, ml)::tl in let newMl = List.append ml newMlTemp in loop newMl x y dir acc else loop tl x y dir acc in List.rev (loop movelist 0.0 0.0 0.0 [(0.0,0.0)]) (*** part d ***) let interpSmall (movelist : move list) : (float*float) list = let interpSmallStep movelist x y dir : move list * float * float * float = match movelist with [] -> print_string "[]";print_newline ();raise AlreadyDone | Home::tl -> tl, 0.0, 0.0, 0.0 | Forward f::tl -> let newX = x +. ( f *. (cos dir) ) in let newY = y +. ( f *. (sin dir) ) in tl, newX, newY, dir | Turn f::tl -> let newDir = f +. dir in let radianCirc = 2.0 *. 3.1416 in let newDirNor = mod_float newDir radianCirc in tl, x, y, newDirNor | For (il, ml)::tl -> if il > 0 then ( let ild = il - 1 in let newMlTemp = For(ild, ml)::tl in let newMl = List.append ml newMlTemp in newMl, x, y, dir ) else tl, x, y, dir in let rec loop movelist x y dir acc = match movelist with [] -> acc | _ -> let ret = interpSmallStep movelist x y dir in match ret with newList, retX, retY, retDir -> if retX <> x || retY <> y then loop newList retX retY retDir ((retX, retY)::acc) else loop newList x y retDir acc in List.rev (loop movelist 0.0 0.0 0.0 [(0.0,0.0)]) (*** part e ***) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ###################################################################### ############################################################################# ########################################## *) (*** part f ***) let interpTrans movelist : float->float->float-> (float * float) list * float= # # # # # # # # # # # # # # # # # # # # # # # # # in let transMatch movelistMatch x y dir = match movelistMatch with [] -> -1.0, -1.0, -999.0, [] | Home::tl -> 0.0, 0.0, 0.0, tl | Forward f::tl -> let newX = x +. ( f *. (cos dir) ) in let newY = y +. ( f *. (sin dir) ) in newX, newY, dir, tl | Turn f::tl -> let newDir = f +. dir in x, y, newDir, tl | For (il, ml)::tl -> print_int il; print_string "___"; if il > 0 then ( let ild = il - 1 in let newMlTemp = For(ild, movelistMatch)::tl in let newMl = List.append ml newMlTemp in x, y, dir, newMl ) else x, y, dir, tl in let loop movelist = (fun x y dir -> let rec loopHelp movel x y dir acc = let res = transMatch movel x y dir in match res with -1.0, -1.0, -999.0, _ -> acc, dir | retX, retY, retDir, tl -> if retX <> x || retY <> y then ( let lst = [(retX,retY)] in let newAcc = List.append acc lst in loopHelp tl retX retY retDir newAcc ) else ( if retDir <> dir then loopHelp tl retX retY retDir tl else loopHelp tl retX retY dir tl ) in loopHelp movelist x y dir [] ) in loop movelist (*** possibly helpful testing code ***) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let example_logo_prog = let res = makePoly 5 1.0 in [res] # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ############################### ################################## ###################### *) let ansL = interpLarge example_logo_prog let ansS = interpSmall example_logo_prog let ansI = (0.0,0.0)::(fst ((interpTrans example_logo_prog) 0.0 0.0 0.0)) let rec pr lst = match lst with [] -> () | (x,y)::tl -> print_string("(" ^ (string_of_float x) ^ "," ^ (string_of_float y) ^ ")"); pr tl let _ = pr ansL; print_newline (); pr ansS; print_newline (); pr ansI; print_newline ();
null
https://raw.githubusercontent.com/gsakkas/rite/958a0ad2460e15734447bc07bd181f5d35956d3b/features/data/seminal/20060324-19%3A59%3A26-89f2326d390889b438f85e767726a3c5.seminal.ml
ocaml
** part a ** ** part b -- return move** ::makePolyHelp 0 true ###################### ############# ######################################################## ############ ######### ############################################# ################################################ ###### ** part c ** ** part d ** ** part e ** ** part f ** ** possibly helpful testing code **
exception Unimplemented exception AlreadyDone type move = Home | Forward of float | Turn of float | For of int * (move)list let makePoly sides len = let fSides = float_of_int sides in let turnAmount = (2.0 *. 3.1416) /. fSides in let rec makePolyHelp sidesLeft turn = match sidesLeft with 0 -> [] | _ -> (Forward(len)::[Turn(turnAmount)]) in if sides < 3 then For(0, []) else ( let lst = makePolyHelp sides false in For(sides, lst) ) let interpLarge (movelist : move list) : (float*float) list = let rec loop movelist x y dir acc = match movelist with [] -> acc | Home::tl -> loop tl 0.0 0.0 dir ((0.0,0.0)::acc) | Forward f::tl -> let newX = x +. ( f *. (cos dir) ) in let newY = y +. ( f *. (sin dir) ) in loop tl newX newY dir ((newX,newY)::acc) | Turn f::tl -> let newDir = f +. dir in loop tl x y newDir acc | For (il, ml)::tl -> if il > 0 then let ild = il - 1 in let newMlTemp = For(ild, ml)::tl in let newMl = List.append ml newMlTemp in loop newMl x y dir acc else loop tl x y dir acc in List.rev (loop movelist 0.0 0.0 0.0 [(0.0,0.0)]) let interpSmall (movelist : move list) : (float*float) list = let interpSmallStep movelist x y dir : move list * float * float * float = match movelist with [] -> print_string "[]";print_newline ();raise AlreadyDone | Home::tl -> tl, 0.0, 0.0, 0.0 | Forward f::tl -> let newX = x +. ( f *. (cos dir) ) in let newY = y +. ( f *. (sin dir) ) in tl, newX, newY, dir | Turn f::tl -> let newDir = f +. dir in let radianCirc = 2.0 *. 3.1416 in let newDirNor = mod_float newDir radianCirc in tl, x, y, newDirNor | For (il, ml)::tl -> if il > 0 then ( let ild = il - 1 in let newMlTemp = For(ild, ml)::tl in let newMl = List.append ml newMlTemp in newMl, x, y, dir ) else tl, x, y, dir in let rec loop movelist x y dir acc = match movelist with [] -> acc | _ -> let ret = interpSmallStep movelist x y dir in match ret with newList, retX, retY, retDir -> if retX <> x || retY <> y then loop newList retX retY retDir ((retX, retY)::acc) else loop newList x y retDir acc in List.rev (loop movelist 0.0 0.0 0.0 [(0.0,0.0)]) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ###################################################################### ############################################################################# ########################################## *) let interpTrans movelist : float->float->float-> (float * float) list * float= # # # # # # # # # # # # # # # # # # # # # # # # # in let transMatch movelistMatch x y dir = match movelistMatch with [] -> -1.0, -1.0, -999.0, [] | Home::tl -> 0.0, 0.0, 0.0, tl | Forward f::tl -> let newX = x +. ( f *. (cos dir) ) in let newY = y +. ( f *. (sin dir) ) in newX, newY, dir, tl | Turn f::tl -> let newDir = f +. dir in x, y, newDir, tl | For (il, ml)::tl -> print_int il; print_string "___"; if il > 0 then ( let ild = il - 1 in let newMlTemp = For(ild, movelistMatch)::tl in let newMl = List.append ml newMlTemp in x, y, dir, newMl ) else x, y, dir, tl in let loop movelist = (fun x y dir -> let rec loopHelp movel x y dir acc = let res = transMatch movel x y dir in match res with -1.0, -1.0, -999.0, _ -> acc, dir | retX, retY, retDir, tl -> if retX <> x || retY <> y then ( let lst = [(retX,retY)] in let newAcc = List.append acc lst in loopHelp tl retX retY retDir newAcc ) else ( if retDir <> dir then loopHelp tl retX retY retDir tl else loopHelp tl retX retY dir tl ) in loopHelp movelist x y dir [] ) in loop movelist # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let example_logo_prog = let res = makePoly 5 1.0 in [res] # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ############################### ################################## ###################### *) let ansL = interpLarge example_logo_prog let ansS = interpSmall example_logo_prog let ansI = (0.0,0.0)::(fst ((interpTrans example_logo_prog) 0.0 0.0 0.0)) let rec pr lst = match lst with [] -> () | (x,y)::tl -> print_string("(" ^ (string_of_float x) ^ "," ^ (string_of_float y) ^ ")"); pr tl let _ = pr ansL; print_newline (); pr ansS; print_newline (); pr ansI; print_newline ();
eb8b7312102625ea93df936742b7b9da4bd9c9bbca7ce5dd1759bd35ca09399d
pgj/mirage-kfreebsd
tcptimer.mli
* Copyright ( c ) 2012 < > * * 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) 2012 Balraj Singh <> * * 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. *) type t type tr = | Stoptimer | Continue of Sequence.t | ContinueSetPeriod of (int * Sequence.t) val t : period: int -> expire: (Sequence.t -> tr) -> t val start : t -> ?p:int -> Sequence.t -> unit Lwt.t
null
https://raw.githubusercontent.com/pgj/mirage-kfreebsd/0ff5b2cd7ab0975e3f2ee1bd89f8e5dbf028b102/packages/mirage-net/lib/tcp/tcptimer.mli
ocaml
* Copyright ( c ) 2012 < > * * 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) 2012 Balraj Singh <> * * 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. *) type t type tr = | Stoptimer | Continue of Sequence.t | ContinueSetPeriod of (int * Sequence.t) val t : period: int -> expire: (Sequence.t -> tr) -> t val start : t -> ?p:int -> Sequence.t -> unit Lwt.t
38d31342b574d7775fdf7b9571c45acb553c87d4dfe33ac27df17748276363cb
15Galan/asignatura-204
Dictionary.hs
------------------------------------------------------------------------------- -- Dictionaries implemented by using Binary Search Trees -- Data Structures . en Informática . UMA . , 2011 ------------------------------------------------------------------------------- module Dictionary ( Dictionary , empty , isEmpty , insert , valueOf , valueOf' , isDefinedAt , delete , keys , values ) where import Data.Function(on) import Data.List(intercalate) import Data.Maybe(isJust) import qualified BinarySearchTree as T data Rel a b = a :-> b key :: Rel a b -> a key (k :-> v) = k value :: Rel a b -> b value (k :-> v) = v withKey :: a -> Rel a b withKey k = k :-> undefined instance (Eq a) => Eq (Rel a b) where (==) = (==) `on` key instance (Ord a) => Ord (Rel a b) where compare = compare `on` key newtype Dictionary a b = M (T.BST (Rel a b)) empty :: Dictionary a b empty = M T.empty isEmpty :: Dictionary a b -> Bool isEmpty (M avl) = T.isEmpty avl insert :: (Ord a) => a -> b -> Dictionary a b -> Dictionary a b insert k v (M avl) = M (T.insert (k :-> v) avl) valueOf :: (Ord a) => a -> Dictionary a b -> Maybe b valueOf k (M avl) = case T.search (withKey k) avl of Nothing -> Nothing Just (k' :-> v') -> Just v' valueOf' :: (Ord a) => a -> Dictionary a b -> b valueOf' k (M avl) = case T.search (withKey k) avl of Just (k' :-> v') -> v' isDefinedAt :: (Ord a) => a -> Dictionary a b -> Bool isDefinedAt k map = isJust (valueOf k map) delete :: (Ord a) => a -> Dictionary a b -> Dictionary a b delete k (M avl) = M (T.delete (withKey k) avl) keys :: (Ord a) => Dictionary a b -> [a] keys (M avl) = map key (T.inOrder avl) values :: (Ord a) => Dictionary a b -> [b] values (M avl) = map value (T.inOrder avl) instance (Show a, Show b) => Show (Dictionary a b) where show (M avl) = "Dictionary(" ++ intercalate "," (aux (T.inOrder avl)) ++ ")" where aux [] = [] aux (x:->y : xys) = (show x++"->"++show y) : aux xys
null
https://raw.githubusercontent.com/15Galan/asignatura-204/894f33ff8e0f52a75d8f9ff15155c656f1a8f771/Ex%C3%A1menes/2012/Febrero/Haskell/Dictionary.hs
haskell
----------------------------------------------------------------------------- Dictionaries implemented by using Binary Search Trees -----------------------------------------------------------------------------
Data Structures . en Informática . UMA . , 2011 module Dictionary ( Dictionary , empty , isEmpty , insert , valueOf , valueOf' , isDefinedAt , delete , keys , values ) where import Data.Function(on) import Data.List(intercalate) import Data.Maybe(isJust) import qualified BinarySearchTree as T data Rel a b = a :-> b key :: Rel a b -> a key (k :-> v) = k value :: Rel a b -> b value (k :-> v) = v withKey :: a -> Rel a b withKey k = k :-> undefined instance (Eq a) => Eq (Rel a b) where (==) = (==) `on` key instance (Ord a) => Ord (Rel a b) where compare = compare `on` key newtype Dictionary a b = M (T.BST (Rel a b)) empty :: Dictionary a b empty = M T.empty isEmpty :: Dictionary a b -> Bool isEmpty (M avl) = T.isEmpty avl insert :: (Ord a) => a -> b -> Dictionary a b -> Dictionary a b insert k v (M avl) = M (T.insert (k :-> v) avl) valueOf :: (Ord a) => a -> Dictionary a b -> Maybe b valueOf k (M avl) = case T.search (withKey k) avl of Nothing -> Nothing Just (k' :-> v') -> Just v' valueOf' :: (Ord a) => a -> Dictionary a b -> b valueOf' k (M avl) = case T.search (withKey k) avl of Just (k' :-> v') -> v' isDefinedAt :: (Ord a) => a -> Dictionary a b -> Bool isDefinedAt k map = isJust (valueOf k map) delete :: (Ord a) => a -> Dictionary a b -> Dictionary a b delete k (M avl) = M (T.delete (withKey k) avl) keys :: (Ord a) => Dictionary a b -> [a] keys (M avl) = map key (T.inOrder avl) values :: (Ord a) => Dictionary a b -> [b] values (M avl) = map value (T.inOrder avl) instance (Show a, Show b) => Show (Dictionary a b) where show (M avl) = "Dictionary(" ++ intercalate "," (aux (T.inOrder avl)) ++ ")" where aux [] = [] aux (x:->y : xys) = (show x++"->"++show y) : aux xys
ae72761681fe7c0734ee47d4acd556c342b60e14af8a837720f8b93ccbc93a05
osstotalsoft/functional-guy
11.Quicksort.hs
quicksort [] = [] quicksort (x : xs) = quicksort smallerThanX ++ [x] ++ quicksort biggerThanX where smallerThanX = filter (<= x) xs biggerThanX = filter (> x) xs test = quicksort $ reverse [1 .. 10]
null
https://raw.githubusercontent.com/osstotalsoft/functional-guy/c02a8b22026c261a9722551f3641228dc02619ba/Chapter2.%20The%20foundation/Exercises/01.Recursion/11.Quicksort.hs
haskell
quicksort [] = [] quicksort (x : xs) = quicksort smallerThanX ++ [x] ++ quicksort biggerThanX where smallerThanX = filter (<= x) xs biggerThanX = filter (> x) xs test = quicksort $ reverse [1 .. 10]
415a62f4e81e2a357c8ade03c71af7138c11f9c57fd4bfc81c5379e5f5b6d736
ners/dosh
Zipper.hs
{-# OPTIONS_GHC -Wno-name-shadowing #-} module Data.Sequence.Zipper where import Control.Applicative ((<|>)) import Data.Sequence (Seq, ViewL (..), ViewR (..), (<|), (|>)) import Data.Sequence qualified as Seq import GHC.Exts (IsList (..)) import GHC.Generics (Generic) import Prelude data SeqZipper t = SeqZipper { before :: Seq t , after :: Seq t } deriving stock (Generic, Eq, Show) empty :: SeqZipper t empty = SeqZipper{before = Seq.empty, after = Seq.empty} singleton :: t -> SeqZipper t singleton x = SeqZipper{before = mempty, after = Seq.singleton x} instance Semigroup (SeqZipper t) where a <> b = SeqZipper{before = before a, after = after a <> before b <> after b} instance Monoid (SeqZipper t) where mempty = empty instance IsList (SeqZipper t) where type Item (SeqZipper t) = t fromList xs = SeqZipper{before = mempty, after = fromList xs} toList SeqZipper{..} = toList $ before <> after instance Foldable SeqZipper where foldr f z = foldr f z . toList instance Traversable SeqZipper where traverse :: Applicative f => (a -> f b) -> SeqZipper a -> f (SeqZipper b) traverse f SeqZipper{..} = do before <- traverse f before after <- traverse f after pure SeqZipper{..} instance Functor SeqZipper where fmap :: (a -> b) -> SeqZipper a -> SeqZipper b fmap f SeqZipper{..} = SeqZipper { before = fmap f before , after = fmap f after } seqFirst :: Seq a -> Maybe a seqFirst s = case Seq.viewl s of EmptyL -> Nothing (x :< _) -> Just x seqLast :: Seq a -> Maybe a seqLast s = case Seq.viewr s of EmptyR -> Nothing (_ :> x) -> Just x first :: SeqZipper t -> Maybe t first SeqZipper{..} = seqFirst before current :: SeqZipper t -> Maybe t current SeqZipper{..} = seqFirst after last :: SeqZipper t -> Maybe t last SeqZipper{..} = seqLast after <|> seqLast before forward :: SeqZipper t -> SeqZipper t forward sz@SeqZipper{..} = case Seq.viewl after of EmptyL -> sz (x :< after) -> sz{before = before |> x, after} back :: SeqZipper t -> SeqZipper t back sz@SeqZipper{..} = case Seq.viewr before of EmptyR -> sz (before :> x) -> sz{before, after = x <| after} home :: SeqZipper t -> SeqZipper t home sz@SeqZipper{..} = sz{before = mempty, after = before <> after} end :: SeqZipper t -> SeqZipper t end sz@SeqZipper{..} = sz{before = before <> after, after = mempty}
null
https://raw.githubusercontent.com/ners/dosh/ff0bcbf33ba38bfe3d981b90c815f7e827ee2d33/src/Data/Sequence/Zipper.hs
haskell
# OPTIONS_GHC -Wno-name-shadowing #
module Data.Sequence.Zipper where import Control.Applicative ((<|>)) import Data.Sequence (Seq, ViewL (..), ViewR (..), (<|), (|>)) import Data.Sequence qualified as Seq import GHC.Exts (IsList (..)) import GHC.Generics (Generic) import Prelude data SeqZipper t = SeqZipper { before :: Seq t , after :: Seq t } deriving stock (Generic, Eq, Show) empty :: SeqZipper t empty = SeqZipper{before = Seq.empty, after = Seq.empty} singleton :: t -> SeqZipper t singleton x = SeqZipper{before = mempty, after = Seq.singleton x} instance Semigroup (SeqZipper t) where a <> b = SeqZipper{before = before a, after = after a <> before b <> after b} instance Monoid (SeqZipper t) where mempty = empty instance IsList (SeqZipper t) where type Item (SeqZipper t) = t fromList xs = SeqZipper{before = mempty, after = fromList xs} toList SeqZipper{..} = toList $ before <> after instance Foldable SeqZipper where foldr f z = foldr f z . toList instance Traversable SeqZipper where traverse :: Applicative f => (a -> f b) -> SeqZipper a -> f (SeqZipper b) traverse f SeqZipper{..} = do before <- traverse f before after <- traverse f after pure SeqZipper{..} instance Functor SeqZipper where fmap :: (a -> b) -> SeqZipper a -> SeqZipper b fmap f SeqZipper{..} = SeqZipper { before = fmap f before , after = fmap f after } seqFirst :: Seq a -> Maybe a seqFirst s = case Seq.viewl s of EmptyL -> Nothing (x :< _) -> Just x seqLast :: Seq a -> Maybe a seqLast s = case Seq.viewr s of EmptyR -> Nothing (_ :> x) -> Just x first :: SeqZipper t -> Maybe t first SeqZipper{..} = seqFirst before current :: SeqZipper t -> Maybe t current SeqZipper{..} = seqFirst after last :: SeqZipper t -> Maybe t last SeqZipper{..} = seqLast after <|> seqLast before forward :: SeqZipper t -> SeqZipper t forward sz@SeqZipper{..} = case Seq.viewl after of EmptyL -> sz (x :< after) -> sz{before = before |> x, after} back :: SeqZipper t -> SeqZipper t back sz@SeqZipper{..} = case Seq.viewr before of EmptyR -> sz (before :> x) -> sz{before, after = x <| after} home :: SeqZipper t -> SeqZipper t home sz@SeqZipper{..} = sz{before = mempty, after = before <> after} end :: SeqZipper t -> SeqZipper t end sz@SeqZipper{..} = sz{before = before <> after, after = mempty}
403552ef531826d7b6bc39b1ba902e6696a4a278aa713aae157aa5aa1c996359
NorfairKing/haphviz
Internal.hs
-- | Internal types. -- -- You may want to keep off these. module Text.Dot.Types.Internal ( module Text.Dot.Types.Internal -- * Re-exports , Identity(..) , Monoid(..) ) where import Data.Text (Text) import Control.Monad.Identity (Identity (..)) -- | Internal name of a graph, used to reference graphs and subgraphs type GraphName = Text -- | Type of a graph, directed or undirected. -- -- This also specifies what edge declarations look like. data GraphType = UndirectedGraph | DirectedGraph deriving (Show, Eq) -- | Attribute name: just text type AttributeName = Text -- | Attribute value: just text type AttributeValue = Text -- | Attribute: a tuple of name and value. type Attribute = (AttributeName, AttributeValue) -- | A node identifier. -- -- This is either a user supplied name or a generated numerical identifier. data NodeId = UserId Text | Nameless Int deriving (Show, Eq) -- | Declaration type -- -- Used to declare common attributes for nodes or edges. data DecType = DecGraph | DecNode | DecEdge deriving (Show, Eq) -- | A Haphviz Graph data DotGraph = Graph GraphType GraphName Dot deriving (Show, Eq) -- | Rankdir Type -- -- Used to specify the default node layout direction data RankdirType = LR | RL | TB | BT deriving (Show, Eq) | Haphviz internal graph content AST data Dot = Node NodeId [Attribute] | Edge NodeId NodeId [Attribute] | Declaration DecType [Attribute] | Ranksame Dot | Subgraph Text Dot | RawDot Text | Label Text | Rankdir RankdirType | DotSeq Dot Dot | DotEmpty deriving (Show, Eq) -- | Dot is a semigroup, duh, that's the point. instance Semigroup Dot where -- Left identity (<>) DotEmpty d = d -- Right identity (<>) d DotEmpty = d Associativity (<>) d (DotSeq d1 d2) = DotSeq ((<>) d d1) d2 (<>) d1 d2 = DotSeq d1 d2 -- | Dot is a monoid, duh, that's the point. instance Monoid Dot where mempty = DotEmpty
null
https://raw.githubusercontent.com/NorfairKing/haphviz/90f1e8e0cbcd2a0745cfa66a46e878b473b3cf7e/src/Text/Dot/Types/Internal.hs
haskell
| Internal types. You may want to keep off these. * Re-exports | Internal name of a graph, used to reference graphs and subgraphs | Type of a graph, directed or undirected. This also specifies what edge declarations look like. | Attribute name: just text | Attribute value: just text | Attribute: a tuple of name and value. | A node identifier. This is either a user supplied name or a generated numerical identifier. | Declaration type Used to declare common attributes for nodes or edges. | A Haphviz Graph | Rankdir Type Used to specify the default node layout direction | Dot is a semigroup, duh, that's the point. Left identity Right identity | Dot is a monoid, duh, that's the point.
module Text.Dot.Types.Internal ( module Text.Dot.Types.Internal , Identity(..) , Monoid(..) ) where import Data.Text (Text) import Control.Monad.Identity (Identity (..)) type GraphName = Text data GraphType = UndirectedGraph | DirectedGraph deriving (Show, Eq) type AttributeName = Text type AttributeValue = Text type Attribute = (AttributeName, AttributeValue) data NodeId = UserId Text | Nameless Int deriving (Show, Eq) data DecType = DecGraph | DecNode | DecEdge deriving (Show, Eq) data DotGraph = Graph GraphType GraphName Dot deriving (Show, Eq) data RankdirType = LR | RL | TB | BT deriving (Show, Eq) | Haphviz internal graph content AST data Dot = Node NodeId [Attribute] | Edge NodeId NodeId [Attribute] | Declaration DecType [Attribute] | Ranksame Dot | Subgraph Text Dot | RawDot Text | Label Text | Rankdir RankdirType | DotSeq Dot Dot | DotEmpty deriving (Show, Eq) instance Semigroup Dot where (<>) DotEmpty d = d (<>) d DotEmpty = d Associativity (<>) d (DotSeq d1 d2) = DotSeq ((<>) d d1) d2 (<>) d1 d2 = DotSeq d1 d2 instance Monoid Dot where mempty = DotEmpty
1706f57b927d4274cfa3585d9a135b247b4109351af4b9c8d535b19893933120
rlepigre/pml
hval.ml
module Val = struct type t = v ex let equal : t -> t -> bool = fun v1 v2 -> eq_expr (Pos.none v1) (Pos.none v2) let hash t = Hashtbl.hash t end module HVal = Weak.Make(Val) let hval : v ex -> v ex = let tbl = HVal.create 1001 in try HVal.find tbl d with Not_found - > HVal.add tbl d ; d try HVal.find tbl d with Not_found -> HVal.add tbl d; d*)
null
https://raw.githubusercontent.com/rlepigre/pml/cdfdea0eecc6767b16edc6a7bef917bc9dd746ed/attic/hval.ml
ocaml
module Val = struct type t = v ex let equal : t -> t -> bool = fun v1 v2 -> eq_expr (Pos.none v1) (Pos.none v2) let hash t = Hashtbl.hash t end module HVal = Weak.Make(Val) let hval : v ex -> v ex = let tbl = HVal.create 1001 in try HVal.find tbl d with Not_found - > HVal.add tbl d ; d try HVal.find tbl d with Not_found -> HVal.add tbl d; d*)
0f97fcde6ccce77077258ad3a924bbe84bd477425c36af908315490edb76c531
input-output-hk/cardano-ledger
Chain.hs
# LANGUAGE DataKinds # {-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # module Cardano.Ledger.Chain ( -- | Chain Checks ChainChecksPParams (..), ChainPredicateFailure (..), pparamsToChainChecksPParams, chainChecks, ) where import Cardano.Ledger.BHeaderView (BHeaderView (..)) import Cardano.Ledger.BaseTypes (ProtVer (..), Version) import Cardano.Ledger.Core import Control.Monad (unless) import Control.Monad.Except (MonadError, throwError) import GHC.Generics (Generic) import Lens.Micro ((^.)) import NoThunks.Class (NoThunks (..)) import Numeric.Natural (Natural) data ChainChecksPParams = ChainChecksPParams { ccMaxBHSize :: Natural , ccMaxBBSize :: Natural , ccProtocolVersion :: ProtVer } deriving (Show, Eq, Generic, NoThunks) pparamsToChainChecksPParams :: EraPParams era => PParams era -> ChainChecksPParams pparamsToChainChecksPParams pp = ChainChecksPParams { ccMaxBHSize = pp ^. ppMaxBHSizeL , ccMaxBBSize = pp ^. ppMaxBBSizeL , ccProtocolVersion = pp ^. ppProtocolVersionL } data ChainPredicateFailure = HeaderSizeTooLargeCHAIN !Natural -- Header Size Header Size | BlockSizeTooLargeCHAIN !Natural -- Block Size | ObsoleteNodeCHAIN !Version -- protocol version used !Version -- max protocol version deriving (Generic, Show, Eq, Ord) instance NoThunks ChainPredicateFailure chainChecks :: MonadError ChainPredicateFailure m => Version -> ChainChecksPParams -> BHeaderView c -> m () chainChecks maxpv ccd bhv = do unless (m <= maxpv) $ throwError (ObsoleteNodeCHAIN m maxpv) unless (fromIntegral (bhviewHSize bhv) <= ccMaxBHSize ccd) $ throwError $ HeaderSizeTooLargeCHAIN (fromIntegral $ bhviewHSize bhv) (ccMaxBHSize ccd) unless (bhviewBSize bhv <= ccMaxBBSize ccd) $ throwError $ BlockSizeTooLargeCHAIN (bhviewBSize bhv) (ccMaxBBSize ccd) where ProtVer m _ = ccProtocolVersion ccd
null
https://raw.githubusercontent.com/input-output-hk/cardano-ledger/e0947b0c2e99ef929d20593be03e199560392f42/eras/shelley/impl/src/Cardano/Ledger/Chain.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE OverloadedStrings # | Chain Checks Header Size Block Size protocol version used max protocol version
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # module Cardano.Ledger.Chain ( ChainChecksPParams (..), ChainPredicateFailure (..), pparamsToChainChecksPParams, chainChecks, ) where import Cardano.Ledger.BHeaderView (BHeaderView (..)) import Cardano.Ledger.BaseTypes (ProtVer (..), Version) import Cardano.Ledger.Core import Control.Monad (unless) import Control.Monad.Except (MonadError, throwError) import GHC.Generics (Generic) import Lens.Micro ((^.)) import NoThunks.Class (NoThunks (..)) import Numeric.Natural (Natural) data ChainChecksPParams = ChainChecksPParams { ccMaxBHSize :: Natural , ccMaxBBSize :: Natural , ccProtocolVersion :: ProtVer } deriving (Show, Eq, Generic, NoThunks) pparamsToChainChecksPParams :: EraPParams era => PParams era -> ChainChecksPParams pparamsToChainChecksPParams pp = ChainChecksPParams { ccMaxBHSize = pp ^. ppMaxBHSizeL , ccMaxBBSize = pp ^. ppMaxBBSizeL , ccProtocolVersion = pp ^. ppProtocolVersionL } data ChainPredicateFailure = HeaderSizeTooLargeCHAIN Header Size | BlockSizeTooLargeCHAIN | ObsoleteNodeCHAIN deriving (Generic, Show, Eq, Ord) instance NoThunks ChainPredicateFailure chainChecks :: MonadError ChainPredicateFailure m => Version -> ChainChecksPParams -> BHeaderView c -> m () chainChecks maxpv ccd bhv = do unless (m <= maxpv) $ throwError (ObsoleteNodeCHAIN m maxpv) unless (fromIntegral (bhviewHSize bhv) <= ccMaxBHSize ccd) $ throwError $ HeaderSizeTooLargeCHAIN (fromIntegral $ bhviewHSize bhv) (ccMaxBHSize ccd) unless (bhviewBSize bhv <= ccMaxBBSize ccd) $ throwError $ BlockSizeTooLargeCHAIN (bhviewBSize bhv) (ccMaxBBSize ccd) where ProtVer m _ = ccProtocolVersion ccd
37b2989388da886a4c1d3c05c040ef85e6090459558360abae8daf19a41b3e02
plum-umd/fundamentals
light-fun.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname light-fun) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) A Light is one of : ;; - "Red" ;; - "Green" ;; - "Yellow" ;; light-function : Light -> ??? (define (light-function l) (cond [(string=? "Red" l) ...] [(string=? "Green" l) ...] [(string=? "Yellow" l) ...])) ;; next : Light -> Light ;; Next light after the given light (check-expect (next "Green") "Yellow") (check-expect (next "Red") "Green") (check-expect (next "Yellow") "Red") (define (next l) (cond [(string=? "Red" l) "Green"] [(string=? "Green" l) "Yellow"] [(string=? "Yellow" l) "Red"]))
null
https://raw.githubusercontent.com/plum-umd/fundamentals/eb01ac528d42855be53649991a17d19c025a97ad/2/www/lectures/4/light-fun.rkt
racket
about the language level of this file in a form that our tools can easily process. - "Red" - "Green" - "Yellow" light-function : Light -> ??? next : Light -> Light Next light after the given light
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname light-fun) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) A Light is one of : (define (light-function l) (cond [(string=? "Red" l) ...] [(string=? "Green" l) ...] [(string=? "Yellow" l) ...])) (check-expect (next "Green") "Yellow") (check-expect (next "Red") "Green") (check-expect (next "Yellow") "Red") (define (next l) (cond [(string=? "Red" l) "Green"] [(string=? "Green" l) "Yellow"] [(string=? "Yellow" l) "Red"]))
c999d5e0841e3befe9ce5aa548fbb31925c2e9d38b2dd36ff5ed0985b983179d
cxphoe/SICP-solutions
2.79.rkt
(load "2.77.rkt") (define (install-equ?-package) (put 'equ? '(scheme-number scheme-number) (lambda (x y) (= x y))) (put 'equ? '(rational rational) (lambda (x y) (= (* (numer x) (denom y)) (* (numer y) (denom x))))) (put 'equ? '(complex complex) (lambda (x y) (and (= (real-part x) (real-part y)) (= (imag-part x) (imag-part y))))) 'done) (define (equ? x y) (apply-generic 'equ? x y))
null
https://raw.githubusercontent.com/cxphoe/SICP-solutions/d35bb688db0320f6efb3b3bde1a14ce21da319bd/Chapter%202-Building%20Abstractions%20with%20Data/5.Systems%20with%20Generic%20Operations/2.79.rkt
racket
(load "2.77.rkt") (define (install-equ?-package) (put 'equ? '(scheme-number scheme-number) (lambda (x y) (= x y))) (put 'equ? '(rational rational) (lambda (x y) (= (* (numer x) (denom y)) (* (numer y) (denom x))))) (put 'equ? '(complex complex) (lambda (x y) (and (= (real-part x) (real-part y)) (= (imag-part x) (imag-part y))))) 'done) (define (equ? x y) (apply-generic 'equ? x y))
5d109dc99f24fae1b1646a83aa981f7c2953a5144953052c184bab8e14a08cd8
simingwang/emqx-plugin-kafkav5
logger_disk_log_h.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2017 - 2020 . All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %% %% %CopyrightEnd% %% -module(logger_disk_log_h). -include("logger.hrl"). -include("logger_internal.hrl"). -include("logger_h_common.hrl"). %%% API -export([filesync/1]). %% logger_h_common callbacks -export([init/2, check_config/4, reset_state/2, filesync/3, write/4, handle_info/3, terminate/3]). %% logger callbacks -export([log/2, adding_handler/1, removing_handler/1, changing_config/3, filter_config/1]). %%%=================================================================== %%% API %%%=================================================================== %%%----------------------------------------------------------------- %%% -spec filesync(Name) -> ok | {error,Reason} when Name :: atom(), Reason :: handler_busy | {badarg,term()}. filesync(Name) -> logger_h_common:filesync(?MODULE,Name). %%%=================================================================== %%% logger callbacks %%%=================================================================== %%%----------------------------------------------------------------- %%% Handler being added adding_handler(Config) -> logger_h_common:adding_handler(Config). %%%----------------------------------------------------------------- %%% Updating handler config changing_config(SetOrUpdate, OldConfig, NewConfig) -> logger_h_common:changing_config(SetOrUpdate, OldConfig, NewConfig). %%%----------------------------------------------------------------- %%% Handler being removed removing_handler(Config) -> logger_h_common:removing_handler(Config). %%%----------------------------------------------------------------- %%% Log a string or report -spec log(LogEvent, Config) -> ok when LogEvent :: logger:log_event(), Config :: logger:handler_config(). log(LogEvent, Config) -> logger_h_common:log(LogEvent, Config). %%%----------------------------------------------------------------- %%% Remove internal fields from configuration filter_config(Config) -> logger_h_common:filter_config(Config). %%%=================================================================== %%% logger_h_common callbacks %%%=================================================================== init(Name, #{file:=File,type:=Type,max_no_bytes:=MNB,max_no_files:=MNF}) -> case open_disk_log(Name, File, Type, MNB, MNF) of ok -> {ok,#{log_opts => #{file => File, type => Type, max_no_bytes => MNB, max_no_files => MNF}, prev_log_result => ok, prev_sync_result => ok, prev_disk_log_info => undefined}}; Error -> Error end. check_config(Name,set,undefined,HConfig0) -> HConfig=merge_default_logopts(Name,maps:merge(get_default_config(),HConfig0)), check_config(HConfig); check_config(_Name,SetOrUpdate,OldHConfig,NewHConfig0) -> WriteOnce = maps:with([type,file,max_no_files,max_no_bytes],OldHConfig), Default = case SetOrUpdate of set -> %% Do not reset write-once fields to defaults maps:merge(get_default_config(),WriteOnce); update -> OldHConfig end, NewHConfig = maps:merge(Default,NewHConfig0), %% Fail if write-once fields are changed case maps:with([type,file,max_no_files,max_no_bytes],NewHConfig) of WriteOnce -> check_config(NewHConfig); Other -> {Old,New} = logger_server:diff_maps(WriteOnce,Other), {error,{illegal_config_change,?MODULE,Old,New}} end. check_config(HConfig) -> case check_h_config(maps:to_list(HConfig)) of ok -> {ok,HConfig}; {error,{Key,Value}} -> {error,{invalid_config,?MODULE,#{Key=>Value}}} end. check_h_config([{file,File}|Config]) when is_list(File) -> check_h_config(Config); check_h_config([{max_no_files,undefined}|Config]) -> check_h_config(Config); check_h_config([{max_no_files,N}|Config]) when is_integer(N), N>0 -> check_h_config(Config); check_h_config([{max_no_bytes,infinity}|Config]) -> check_h_config(Config); check_h_config([{max_no_bytes,N}|Config]) when is_integer(N), N>0 -> check_h_config(Config); check_h_config([{type,Type}|Config]) when Type==wrap; Type==halt -> check_h_config(Config); check_h_config([Other | _]) -> {error,Other}; check_h_config([]) -> ok. get_default_config() -> #{}. merge_default_logopts(Name, HConfig) -> Type = maps:get(type, HConfig, wrap), {DefaultNoFiles,DefaultNoBytes} = case Type of halt -> {undefined,infinity}; _wrap -> {10,1048576} end, {ok,Dir} = file:get_cwd(), Defaults = #{file => filename:join(Dir,Name), max_no_files => DefaultNoFiles, max_no_bytes => DefaultNoBytes, type => Type}, maps:merge(Defaults, HConfig). filesync(Name,_Mode,State) -> Result = ?disk_log_sync(Name), maybe_notify_error(Name, filesync, Result, prev_sync_result, State). write(Name, Mode, Bin, State) -> Result = ?disk_log_write(Name, Mode, Bin), maybe_notify_error(Name, log, Result, prev_log_result, State). reset_state(_Name, State) -> State#{prev_log_result => ok, prev_sync_result => ok, prev_disk_log_info => undefined}. The disk log owner must handle status messages from disk_log . handle_info(Name, {disk_log, _Node, Log, Info={truncated,_NoLostItems}}, State) -> maybe_notify_status(Name, Log, Info, prev_disk_log_info, State); handle_info(Name, {disk_log, _Node, Log, Info = {blocked_log,_Items}}, State) -> maybe_notify_status(Name, Log, Info, prev_disk_log_info, State); handle_info(Name, {disk_log, _Node, Log, Info = full}, State) -> maybe_notify_status(Name, Log, Info, prev_disk_log_info, State); handle_info(Name, {disk_log, _Node, Log, Info = {error_status,_Status}}, State) -> maybe_notify_status(Name, Log, Info, prev_disk_log_info, State); handle_info(_, _, State) -> State. terminate(Name, _Reason, _State) -> _ = close_disk_log(Name, normal), ok. %%%----------------------------------------------------------------- Internal functions open_disk_log(Name, File, Type, MaxNoBytes, MaxNoFiles) -> case filelib:ensure_dir(File) of ok -> Size = if Type == halt -> MaxNoBytes; Type == wrap -> {MaxNoBytes,MaxNoFiles} end, Opts = [{name, Name}, {file, File}, {size, Size}, {type, Type}, {linkto, self()}, {repair, false}, {format, external}, {notify, true}, {quiet, true}, {mode, read_write}], case disk_log:open(Opts) of {ok,Name} -> ok; Error = {error,_Reason} -> Error end; Error -> Error end. close_disk_log(Name, _) -> _ = ?disk_log_sync(Name), _ = disk_log:close(Name), ok. disk_log_write(Name, sync, Bin) -> disk_log:blog(Name, Bin); disk_log_write(Name, async, Bin) -> disk_log:balog(Name, Bin). %%%----------------------------------------------------------------- %%% Print error messages, but don't repeat the same message maybe_notify_error(Name, Op, Result, Key, #{log_opts:=LogOpts}=State) -> {Result,error_notify_new({Name, Op, LogOpts, Result}, Result, Key, State)}. maybe_notify_status(Name, Log, Info, Key, State) -> error_notify_new({disk_log, Name, Log, Info}, Info, Key, State). error_notify_new(Term, What, Key, State) -> error_notify_new(What, maps:get(Key,State), Term), State#{Key => What}. error_notify_new(ok,_Prev,_Term) -> ok; error_notify_new(Same,Same,_Term) -> ok; error_notify_new(_New,_Prev,Term) -> logger_h_common:error_notify(Term).
null
https://raw.githubusercontent.com/simingwang/emqx-plugin-kafkav5/bbf919e56dbc8fd2d4c1c541084532f844a11cbc/_build/default/rel/emqx_plugin_kafka/lib/kernel-8.3/src/logger_disk_log_h.erl
erlang
%CopyrightBegin% you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. %CopyrightEnd% API logger_h_common callbacks logger callbacks =================================================================== API =================================================================== ----------------------------------------------------------------- =================================================================== logger callbacks =================================================================== ----------------------------------------------------------------- Handler being added ----------------------------------------------------------------- Updating handler config ----------------------------------------------------------------- Handler being removed ----------------------------------------------------------------- Log a string or report ----------------------------------------------------------------- Remove internal fields from configuration =================================================================== logger_h_common callbacks =================================================================== Do not reset write-once fields to defaults Fail if write-once fields are changed ----------------------------------------------------------------- ----------------------------------------------------------------- Print error messages, but don't repeat the same message
Copyright Ericsson AB 2017 - 2020 . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(logger_disk_log_h). -include("logger.hrl"). -include("logger_internal.hrl"). -include("logger_h_common.hrl"). -export([filesync/1]). -export([init/2, check_config/4, reset_state/2, filesync/3, write/4, handle_info/3, terminate/3]). -export([log/2, adding_handler/1, removing_handler/1, changing_config/3, filter_config/1]). -spec filesync(Name) -> ok | {error,Reason} when Name :: atom(), Reason :: handler_busy | {badarg,term()}. filesync(Name) -> logger_h_common:filesync(?MODULE,Name). adding_handler(Config) -> logger_h_common:adding_handler(Config). changing_config(SetOrUpdate, OldConfig, NewConfig) -> logger_h_common:changing_config(SetOrUpdate, OldConfig, NewConfig). removing_handler(Config) -> logger_h_common:removing_handler(Config). -spec log(LogEvent, Config) -> ok when LogEvent :: logger:log_event(), Config :: logger:handler_config(). log(LogEvent, Config) -> logger_h_common:log(LogEvent, Config). filter_config(Config) -> logger_h_common:filter_config(Config). init(Name, #{file:=File,type:=Type,max_no_bytes:=MNB,max_no_files:=MNF}) -> case open_disk_log(Name, File, Type, MNB, MNF) of ok -> {ok,#{log_opts => #{file => File, type => Type, max_no_bytes => MNB, max_no_files => MNF}, prev_log_result => ok, prev_sync_result => ok, prev_disk_log_info => undefined}}; Error -> Error end. check_config(Name,set,undefined,HConfig0) -> HConfig=merge_default_logopts(Name,maps:merge(get_default_config(),HConfig0)), check_config(HConfig); check_config(_Name,SetOrUpdate,OldHConfig,NewHConfig0) -> WriteOnce = maps:with([type,file,max_no_files,max_no_bytes],OldHConfig), Default = case SetOrUpdate of set -> maps:merge(get_default_config(),WriteOnce); update -> OldHConfig end, NewHConfig = maps:merge(Default,NewHConfig0), case maps:with([type,file,max_no_files,max_no_bytes],NewHConfig) of WriteOnce -> check_config(NewHConfig); Other -> {Old,New} = logger_server:diff_maps(WriteOnce,Other), {error,{illegal_config_change,?MODULE,Old,New}} end. check_config(HConfig) -> case check_h_config(maps:to_list(HConfig)) of ok -> {ok,HConfig}; {error,{Key,Value}} -> {error,{invalid_config,?MODULE,#{Key=>Value}}} end. check_h_config([{file,File}|Config]) when is_list(File) -> check_h_config(Config); check_h_config([{max_no_files,undefined}|Config]) -> check_h_config(Config); check_h_config([{max_no_files,N}|Config]) when is_integer(N), N>0 -> check_h_config(Config); check_h_config([{max_no_bytes,infinity}|Config]) -> check_h_config(Config); check_h_config([{max_no_bytes,N}|Config]) when is_integer(N), N>0 -> check_h_config(Config); check_h_config([{type,Type}|Config]) when Type==wrap; Type==halt -> check_h_config(Config); check_h_config([Other | _]) -> {error,Other}; check_h_config([]) -> ok. get_default_config() -> #{}. merge_default_logopts(Name, HConfig) -> Type = maps:get(type, HConfig, wrap), {DefaultNoFiles,DefaultNoBytes} = case Type of halt -> {undefined,infinity}; _wrap -> {10,1048576} end, {ok,Dir} = file:get_cwd(), Defaults = #{file => filename:join(Dir,Name), max_no_files => DefaultNoFiles, max_no_bytes => DefaultNoBytes, type => Type}, maps:merge(Defaults, HConfig). filesync(Name,_Mode,State) -> Result = ?disk_log_sync(Name), maybe_notify_error(Name, filesync, Result, prev_sync_result, State). write(Name, Mode, Bin, State) -> Result = ?disk_log_write(Name, Mode, Bin), maybe_notify_error(Name, log, Result, prev_log_result, State). reset_state(_Name, State) -> State#{prev_log_result => ok, prev_sync_result => ok, prev_disk_log_info => undefined}. The disk log owner must handle status messages from disk_log . handle_info(Name, {disk_log, _Node, Log, Info={truncated,_NoLostItems}}, State) -> maybe_notify_status(Name, Log, Info, prev_disk_log_info, State); handle_info(Name, {disk_log, _Node, Log, Info = {blocked_log,_Items}}, State) -> maybe_notify_status(Name, Log, Info, prev_disk_log_info, State); handle_info(Name, {disk_log, _Node, Log, Info = full}, State) -> maybe_notify_status(Name, Log, Info, prev_disk_log_info, State); handle_info(Name, {disk_log, _Node, Log, Info = {error_status,_Status}}, State) -> maybe_notify_status(Name, Log, Info, prev_disk_log_info, State); handle_info(_, _, State) -> State. terminate(Name, _Reason, _State) -> _ = close_disk_log(Name, normal), ok. Internal functions open_disk_log(Name, File, Type, MaxNoBytes, MaxNoFiles) -> case filelib:ensure_dir(File) of ok -> Size = if Type == halt -> MaxNoBytes; Type == wrap -> {MaxNoBytes,MaxNoFiles} end, Opts = [{name, Name}, {file, File}, {size, Size}, {type, Type}, {linkto, self()}, {repair, false}, {format, external}, {notify, true}, {quiet, true}, {mode, read_write}], case disk_log:open(Opts) of {ok,Name} -> ok; Error = {error,_Reason} -> Error end; Error -> Error end. close_disk_log(Name, _) -> _ = ?disk_log_sync(Name), _ = disk_log:close(Name), ok. disk_log_write(Name, sync, Bin) -> disk_log:blog(Name, Bin); disk_log_write(Name, async, Bin) -> disk_log:balog(Name, Bin). maybe_notify_error(Name, Op, Result, Key, #{log_opts:=LogOpts}=State) -> {Result,error_notify_new({Name, Op, LogOpts, Result}, Result, Key, State)}. maybe_notify_status(Name, Log, Info, Key, State) -> error_notify_new({disk_log, Name, Log, Info}, Info, Key, State). error_notify_new(Term, What, Key, State) -> error_notify_new(What, maps:get(Key,State), Term), State#{Key => What}. error_notify_new(ok,_Prev,_Term) -> ok; error_notify_new(Same,Same,_Term) -> ok; error_notify_new(_New,_Prev,Term) -> logger_h_common:error_notify(Term).
c98650fd5d26fff5200d9a9929f1b98ca6b9aae4f78a87a416ed750512556968
mhuebert/chia
jss.cljs
(ns chia.jss (:require ["jss" :as jss] ["reset-jss" :as reset-jss] ["jss-preset-default" :default jss-preset] [applied-science.js-interop :as j] [chia.view.util :as vu] [chia.util :as u])) (defonce JSS (delay (jss/create (jss-preset)))) (defonce global-reset! (delay (when (exists? js/window) (-> @JSS (j/call :createStyleSheet reset-jss) (doto (j/call :attach)))))) (defonce ^:private page-styles (delay (when (exists? js/window) (-> @JSS (j/call :createStyleSheet #js {} #js{:meta (str ::page-styles)}) (doto (j/call :attach)))))) (defonce classes! (memoize (fn [styles] (-> @page-styles (doto (j/call :addRules (clj->js styles))) (j/get :classes) (js->clj :keywordize-keys true) (select-keys (keys styles)))))) (defonce counter (volatile! 0)) (defonce class! (memoize (fn [styles] (some-> @page-styles (j/call :addRule (str "inline-" (vswap! counter inc)) (clj->js styles)) (j/get :selectorText) (subs 1))))) (defn to-string [styles] (-> @JSS (j/call :createStyleSheet (clj->js styles)) (str)))
null
https://raw.githubusercontent.com/mhuebert/chia/74ee3ee9f86efbdf81d8829ab4f0a44d619c73d3/jss/src/chia/jss.cljs
clojure
(ns chia.jss (:require ["jss" :as jss] ["reset-jss" :as reset-jss] ["jss-preset-default" :default jss-preset] [applied-science.js-interop :as j] [chia.view.util :as vu] [chia.util :as u])) (defonce JSS (delay (jss/create (jss-preset)))) (defonce global-reset! (delay (when (exists? js/window) (-> @JSS (j/call :createStyleSheet reset-jss) (doto (j/call :attach)))))) (defonce ^:private page-styles (delay (when (exists? js/window) (-> @JSS (j/call :createStyleSheet #js {} #js{:meta (str ::page-styles)}) (doto (j/call :attach)))))) (defonce classes! (memoize (fn [styles] (-> @page-styles (doto (j/call :addRules (clj->js styles))) (j/get :classes) (js->clj :keywordize-keys true) (select-keys (keys styles)))))) (defonce counter (volatile! 0)) (defonce class! (memoize (fn [styles] (some-> @page-styles (j/call :addRule (str "inline-" (vswap! counter inc)) (clj->js styles)) (j/get :selectorText) (subs 1))))) (defn to-string [styles] (-> @JSS (j/call :createStyleSheet (clj->js styles)) (str)))
37a1cffd7ecd8a62a0963d93ea42f57ee2e3a9626d6c36d8bc195fa1f7ba18d4
gahag/FSQL
Lang.hs
FSQL : / Lang.hs -- Language definition , lexer and standard parser functions - - Copyright ( C ) 2015 gahag - All rights reserved . - - This software may be modified and distributed under the terms - of the BSD license . See the LICENSE file for details . functions - - Copyright (C) 2015 gahag - All rights reserved. - - This software may be modified and distributed under the terms - of the BSD license. See the LICENSE file for details. -} module Parser.Lang ( fsql_dir, fsql_expr, fsql_joinType, fsql_recursive, fsql_selection, fsql_selections, reserved, whiteSpace ) where import Prelude hiding (Either(..)) import Data.Functor (($>)) import Text.Parsec ((<|>), (<?>), between, many1, optionMaybe, try, unexpected) import Text.Parsec.Char (anyChar, char, noneOf, oneOf) import Text.Parsec.Language (emptyDef) import Text.Parsec.Expr (Operator(Prefix, Infix), Assoc(AssocRight, AssocNone) , buildExpressionParser ) import qualified Text.Parsec.Token as Token (LanguageDef, TokenParser , commaSep1, lexeme, parens, whiteSpace , reserved, reservedOp, reservedOpNames , makeTokenParser ) import Expr.Untyped (Expr(..), Op(..), BinOp(..)) import Query (Selection(..), JoinType(..)) import Parser.Base (Parser, OperatorTable) fsql_selection :: Parser Selection fsql_selection = (reserved "name" $> Name) <|> (reserved "date" $> Date) <|> (reserved "size" $> Size) <?> "selection identifier (name|date|size)" fsql_selections :: Parser [Selection] fsql_selections = commaSep1 fsql_selection <?> "one or more selections" fsql_recursive :: Parser Bool fsql_recursive = (/= Nothing) <$> optionMaybe (reserved "recursive") <?> "keyword `recursive`" fsql_dir :: Parser FilePath fsql_dir = lexeme ( string (rawString "\"\\") -- Quoted. <|> rawString "\"\\ " -- Or not. ) <?> "directory path" fsql_joinType :: Parser JoinType fsql_joinType = (reserved "inner" $> Inner) <|> (reserved "outer" $> Outer) <|> (reserved "left" $> Left ) <|> (reserved "right" $> Right) <|> (reserved "full" $> Full ) <?> "join type (inner|outer|left|right|full)" fsql_ops :: OperatorTable Expr fsql_ops = [ [ Infix (reservedOp "==" $> BinOp (:==:)) AssocNone , Infix (reservedOp "!=" $> BinOp (:/=:)) AssocNone , Infix (reservedOp "<=" $> BinOp (:<=:)) AssocNone , Infix (reservedOp ">=" $> BinOp (:>=:)) AssocNone , Infix (reservedOp "<" $> BinOp (:<:)) AssocNone , Infix (reservedOp ">" $> BinOp (:>:)) AssocNone , Infix (reservedOp "=~" $> BinOp (:=~:)) AssocNone ] , [ Prefix (reservedOp "!" $> Op (:!:)) ] , [ Infix (reservedOp "&&" $> BinOp (:&&:)) AssocRight ] , [ Infix (reservedOp "||" $> BinOp (:||:)) AssocRight ] ] fsql_value :: Parser String fsql_value = lexeme ( string (rawString' "\"\\" (oneOf "\"\\") (noneOf "\"\\")) <|> rawString' "\"\\ !<>&|=()" -- avoid ambiguity with operators. (unexpected "escaped character") -- disallow backslashes. (unexpected "escaped character") ) <?> "literal value" fsql_expr :: Parser Expr fsql_expr = buildExpressionParser fsql_ops ( parens fsql_expr <|> (Sel <$> fsql_selection) <|> (Val <$> fsql_value) <?> "expression" ) -- fsql_langDef ------------------------------------------------------------------------ fsql_langDef :: Token.LanguageDef u fsql_langDef = emptyDef { Token.reservedOpNames = [ "<", ">", "<=", ">=", "==" , "!=", "=~", "&&", "||", "!" ] } fsql_lexer :: Token.TokenParser u fsql_lexer = Token.makeTokenParser fsql_langDef commaSep1 :: Parser a -> Parser [a] parens :: Parser a -> Parser a lexeme :: Parser a -> Parser a reserved :: String -> Parser () reservedOp :: String -> Parser () whiteSpace :: Parser () commaSep1 = Token.commaSep1 fsql_lexer parens = Token.parens fsql_lexer lexeme = Token.lexeme fsql_lexer reserved = Token.reserved fsql_lexer reservedOp = Token.reservedOp fsql_lexer whiteSpace = Token.whiteSpace fsql_lexer string :: Parser String -> Parser String string = between (char '"') (char '"' <?> "end of string") rawString :: String -- Characters that must be escaped. -> Parser String rawString s = many1 ( noneOf s <|> (char '\\' >> anyChar <?> "escaped char") ) rawString' :: String -- Characters that must be escaped Parser for escape characters . Parser for escape characters to be kept escaped . -> Parser String rawString' s e e' = concat <$> many1 ( (return <$> noneOf s) <|> try (char '\\' >> return <$> e <?> "escaped char") <|> try (char '\\' >> escape <$> e' <?> "escaped char") ) where escape c = ['\\', c] -- -------------------------------------------------------------------------------------
null
https://raw.githubusercontent.com/gahag/FSQL/5c68cb8af68e7e66876bc2b937b91ddb363b2db7/src/Parser/Lang.hs
haskell
Language definition , lexer and standard parser Quoted. Or not. avoid ambiguity with operators. disallow backslashes. fsql_langDef ------------------------------------------------------------------------ Characters that must be escaped. Characters that must be escaped -------------------------------------------------------------------------------------
functions - - Copyright ( C ) 2015 gahag - All rights reserved . - - This software may be modified and distributed under the terms - of the BSD license . See the LICENSE file for details . functions - - Copyright (C) 2015 gahag - All rights reserved. - - This software may be modified and distributed under the terms - of the BSD license. See the LICENSE file for details. -} module Parser.Lang ( fsql_dir, fsql_expr, fsql_joinType, fsql_recursive, fsql_selection, fsql_selections, reserved, whiteSpace ) where import Prelude hiding (Either(..)) import Data.Functor (($>)) import Text.Parsec ((<|>), (<?>), between, many1, optionMaybe, try, unexpected) import Text.Parsec.Char (anyChar, char, noneOf, oneOf) import Text.Parsec.Language (emptyDef) import Text.Parsec.Expr (Operator(Prefix, Infix), Assoc(AssocRight, AssocNone) , buildExpressionParser ) import qualified Text.Parsec.Token as Token (LanguageDef, TokenParser , commaSep1, lexeme, parens, whiteSpace , reserved, reservedOp, reservedOpNames , makeTokenParser ) import Expr.Untyped (Expr(..), Op(..), BinOp(..)) import Query (Selection(..), JoinType(..)) import Parser.Base (Parser, OperatorTable) fsql_selection :: Parser Selection fsql_selection = (reserved "name" $> Name) <|> (reserved "date" $> Date) <|> (reserved "size" $> Size) <?> "selection identifier (name|date|size)" fsql_selections :: Parser [Selection] fsql_selections = commaSep1 fsql_selection <?> "one or more selections" fsql_recursive :: Parser Bool fsql_recursive = (/= Nothing) <$> optionMaybe (reserved "recursive") <?> "keyword `recursive`" fsql_dir :: Parser FilePath fsql_dir = lexeme ( ) <?> "directory path" fsql_joinType :: Parser JoinType fsql_joinType = (reserved "inner" $> Inner) <|> (reserved "outer" $> Outer) <|> (reserved "left" $> Left ) <|> (reserved "right" $> Right) <|> (reserved "full" $> Full ) <?> "join type (inner|outer|left|right|full)" fsql_ops :: OperatorTable Expr fsql_ops = [ [ Infix (reservedOp "==" $> BinOp (:==:)) AssocNone , Infix (reservedOp "!=" $> BinOp (:/=:)) AssocNone , Infix (reservedOp "<=" $> BinOp (:<=:)) AssocNone , Infix (reservedOp ">=" $> BinOp (:>=:)) AssocNone , Infix (reservedOp "<" $> BinOp (:<:)) AssocNone , Infix (reservedOp ">" $> BinOp (:>:)) AssocNone , Infix (reservedOp "=~" $> BinOp (:=~:)) AssocNone ] , [ Prefix (reservedOp "!" $> Op (:!:)) ] , [ Infix (reservedOp "&&" $> BinOp (:&&:)) AssocRight ] , [ Infix (reservedOp "||" $> BinOp (:||:)) AssocRight ] ] fsql_value :: Parser String fsql_value = lexeme ( string (rawString' "\"\\" (oneOf "\"\\") (noneOf "\"\\")) (unexpected "escaped character") ) <?> "literal value" fsql_expr :: Parser Expr fsql_expr = buildExpressionParser fsql_ops ( parens fsql_expr <|> (Sel <$> fsql_selection) <|> (Val <$> fsql_value) <?> "expression" ) fsql_langDef :: Token.LanguageDef u fsql_langDef = emptyDef { Token.reservedOpNames = [ "<", ">", "<=", ">=", "==" , "!=", "=~", "&&", "||", "!" ] } fsql_lexer :: Token.TokenParser u fsql_lexer = Token.makeTokenParser fsql_langDef commaSep1 :: Parser a -> Parser [a] parens :: Parser a -> Parser a lexeme :: Parser a -> Parser a reserved :: String -> Parser () reservedOp :: String -> Parser () whiteSpace :: Parser () commaSep1 = Token.commaSep1 fsql_lexer parens = Token.parens fsql_lexer lexeme = Token.lexeme fsql_lexer reserved = Token.reserved fsql_lexer reservedOp = Token.reservedOp fsql_lexer whiteSpace = Token.whiteSpace fsql_lexer string :: Parser String -> Parser String string = between (char '"') (char '"' <?> "end of string") -> Parser String rawString s = many1 ( noneOf s <|> (char '\\' >> anyChar <?> "escaped char") ) Parser for escape characters . Parser for escape characters to be kept escaped . -> Parser String rawString' s e e' = concat <$> many1 ( (return <$> noneOf s) <|> try (char '\\' >> return <$> e <?> "escaped char") <|> try (char '\\' >> escape <$> e' <?> "escaped char") ) where escape c = ['\\', c]
89d52a6e8c7d1cf7f127e498aa0e51c950599495447989d777a3faa7ab86c294
snapframework/snap-core
Assertions.hs
# LANGUAGE CPP , OverloadedStrings # module Snap.Internal.Test.Assertions where ------------------------------------------------------------------------------ import Control.Monad (liftM) import Data.ByteString.Builder (toLazyByteString) import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as S import qualified Data.ByteString.Lazy.Char8 as L import Data.Maybe (fromJust) import Snap.Internal.Http.Types (Response (rspBody, rspStatus), getHeader, rspBodyToEnum) import qualified System.IO.Streams as Streams import Test.HUnit (Assertion, assertBool, assertEqual) import Text.Regex.Posix ((=~)) #if !MIN_VERSION_base(4,8,0) import Data.Monoid (mconcat) #endif ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- | Given a 'Response', return its body as a 'ByteString'. -- -- Example: -- -- @ -- ghci> 'getResponseBody' 'emptyResponse' -- \"\" -- @ -- getResponseBody :: Response -> IO ByteString getResponseBody rsp = do (os, grab) <- Streams.listOutputStream enum os liftM toBS grab where enum os = do os' <- rspBodyToEnum (rspBody rsp) os Streams.write Nothing os' toBS = S.concat . L.toChunks . toLazyByteString . mconcat ------------------------------------------------------------------------------ | Given a ' Response ' , assert that its HTTP status code is 200 ( success ) . -- -- Example: -- -- @ -- ghci> :set -XOverloadedStrings ghci > import qualified " Test . HUnit " as T -- ghci> let test = T.runTestTT . T.TestCase ghci > test $ ' assertSuccess ' ' Snap . Core.emptyResponse ' Cases : 1 Tried : 1 Errors : 0 Failures : 0 Counts { cases = 1 , tried = 1 , errors = 0 , failures = 0 } ghci > test $ ' assertSuccess ' ( ' Snap . Core.setResponseStatus ' 500 \"Internal Server Snap . Core.emptyResponse ' ) # # # Failure : Expected success ( 200 ) but got ( 500 ) expected : 200 but got : 500 Cases : 1 Tried : 1 Errors : 0 Failures : 1 Counts { cases = 1 , tried = 1 , errors = 0 , failures = 1 } -- @ assertSuccess :: Response -> Assertion assertSuccess rsp = assertEqual message 200 status where message = "Expected success (200) but got (" ++ (show status) ++ ")" status = rspStatus rsp ------------------------------------------------------------------------------ | Given a ' Response ' , assert that its HTTP status code is 404 ( Not Found ) . -- -- Example: -- -- @ -- ghci> :set -XOverloadedStrings ghci > ' assert404 ' $ ' Snap . Core.setResponseStatus ' 404 \"Not Found\ " ' Snap . Core.emptyResponse ' ghci > ' assert404 ' ' Snap . Core.emptyResponse ' * * * Exception : HUnitFailure \"Expected Not Found ( 404 ) but got ( 200)\\nexpected : 404\\n but got : 200\ " -- @ assert404 :: Response -> Assertion assert404 rsp = assertEqual message 404 status where message = "Expected Not Found (404) but got (" ++ (show status) ++ ")" status = rspStatus rsp ------------------------------------------------------------------------------ | Given a ' Response ' , assert that its HTTP status code is between 300 and 399 -- (a redirect), and that the Location header of the 'Response' points to the specified URI . -- -- Example: -- -- @ -- ghci> :set -XOverloadedStrings ghci > let r ' = ' Snap . Core.setResponseStatus ' 301 \"Moved Permanently\ " ' Snap . Core.emptyResponse ' ghci > let r = ' Snap . Core.setHeader ' \"Location\ " \"www.example.com\ " r ' -- ghci> 'assertRedirectTo' \"www.example.com\" r ghci > ' assertRedirectTo ' \"www.example.com\ " ' Snap . Core.emptyResponse ' * * * Exception : HUnitFailure \"Expected redirect but got status code ( 200)\ " -- @ assertRedirectTo :: ByteString -- ^ The Response should redirect to this URI -> Response -> Assertion assertRedirectTo uri rsp = do assertRedirect rsp assertEqual message uri rspUri where rspUri = fromJust $ getHeader "Location" rsp message = "Expected redirect to " ++ show uri ++ " but got redirected to " ++ show rspUri ++ " instead" ------------------------------------------------------------------------------ | Given a ' Response ' , assert that its HTTP status code is between 300 and 399 -- (a redirect). -- -- Example: -- -- @ -- ghci> :set -XOverloadedStrings ghci > ' assertRedirect ' $ ' Snap . Core.setResponseStatus ' 301 \"Moved Permanently\ " ' Snap . Core.emptyResponse ' ghci > ' assertRedirect ' ' Snap . Core.emptyResponse ' * * * Exception : HUnitFailure \"Expected redirect but got status code ( 200)\ " -- @ assertRedirect :: Response -> Assertion assertRedirect rsp = assertBool message (300 <= status && status <= 399) where message = "Expected redirect but got status code (" ++ show status ++ ")" status = rspStatus rsp ------------------------------------------------------------------------------ -- | Given a 'Response', assert that its body matches the given regular -- expression. -- -- Example: -- -- @ -- ghci> :set -XOverloadedStrings -- ghci> import qualified "System.IO.Streams" as Streams ghci > import qualified " Data . ByteString . Builder " as Builder -- ghci> :{ -- ghci| let r = 'Snap.Core.setResponseBody' -- ghci| (\out -> do -- ghci| Streams.write (Just $ Builder.byteString \"Hello, world!\") out -- ghci| return out) ghci| ' Snap . Core.emptyResponse ' -- ghci| :} -- ghci> 'assertBodyContains' \"^Hello\" r -- ghci> 'assertBodyContains' \"Bye\" r * * * Exception : HUnitFailure " Expected body to match regexp \\\"\\\"Bye\\\"\\\ " , but didn\'t " -- @ ^ Regexp that will match the body content -> Response -> Assertion assertBodyContains match rsp = do body <- getResponseBody rsp assertBool message (body =~ match) where message = "Expected body to match regexp \"" ++ show match ++ "\", but didn't"
null
https://raw.githubusercontent.com/snapframework/snap-core/04295679ccf8316fcf4944f2eb65d1b5266587ef/src/Snap/Internal/Test/Assertions.hs
haskell
---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- | Given a 'Response', return its body as a 'ByteString'. Example: @ ghci> 'getResponseBody' 'emptyResponse' \"\" @ ---------------------------------------------------------------------------- Example: @ ghci> :set -XOverloadedStrings ghci> let test = T.runTestTT . T.TestCase @ ---------------------------------------------------------------------------- Example: @ ghci> :set -XOverloadedStrings @ ---------------------------------------------------------------------------- (a redirect), and that the Location header of the 'Response' points to the Example: @ ghci> :set -XOverloadedStrings ghci> 'assertRedirectTo' \"www.example.com\" r @ ^ The Response should redirect to this ---------------------------------------------------------------------------- (a redirect). Example: @ ghci> :set -XOverloadedStrings @ ---------------------------------------------------------------------------- | Given a 'Response', assert that its body matches the given regular expression. Example: @ ghci> :set -XOverloadedStrings ghci> import qualified "System.IO.Streams" as Streams ghci> :{ ghci| let r = 'Snap.Core.setResponseBody' ghci| (\out -> do ghci| Streams.write (Just $ Builder.byteString \"Hello, world!\") out ghci| return out) ghci| :} ghci> 'assertBodyContains' \"^Hello\" r ghci> 'assertBodyContains' \"Bye\" r @
# LANGUAGE CPP , OverloadedStrings # module Snap.Internal.Test.Assertions where import Control.Monad (liftM) import Data.ByteString.Builder (toLazyByteString) import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as S import qualified Data.ByteString.Lazy.Char8 as L import Data.Maybe (fromJust) import Snap.Internal.Http.Types (Response (rspBody, rspStatus), getHeader, rspBodyToEnum) import qualified System.IO.Streams as Streams import Test.HUnit (Assertion, assertBool, assertEqual) import Text.Regex.Posix ((=~)) #if !MIN_VERSION_base(4,8,0) import Data.Monoid (mconcat) #endif getResponseBody :: Response -> IO ByteString getResponseBody rsp = do (os, grab) <- Streams.listOutputStream enum os liftM toBS grab where enum os = do os' <- rspBodyToEnum (rspBody rsp) os Streams.write Nothing os' toBS = S.concat . L.toChunks . toLazyByteString . mconcat | Given a ' Response ' , assert that its HTTP status code is 200 ( success ) . ghci > import qualified " Test . HUnit " as T ghci > test $ ' assertSuccess ' ' Snap . Core.emptyResponse ' Cases : 1 Tried : 1 Errors : 0 Failures : 0 Counts { cases = 1 , tried = 1 , errors = 0 , failures = 0 } ghci > test $ ' assertSuccess ' ( ' Snap . Core.setResponseStatus ' 500 \"Internal Server Snap . Core.emptyResponse ' ) # # # Failure : Expected success ( 200 ) but got ( 500 ) expected : 200 but got : 500 Cases : 1 Tried : 1 Errors : 0 Failures : 1 Counts { cases = 1 , tried = 1 , errors = 0 , failures = 1 } assertSuccess :: Response -> Assertion assertSuccess rsp = assertEqual message 200 status where message = "Expected success (200) but got (" ++ (show status) ++ ")" status = rspStatus rsp | Given a ' Response ' , assert that its HTTP status code is 404 ( Not Found ) . ghci > ' assert404 ' $ ' Snap . Core.setResponseStatus ' 404 \"Not Found\ " ' Snap . Core.emptyResponse ' ghci > ' assert404 ' ' Snap . Core.emptyResponse ' * * * Exception : HUnitFailure \"Expected Not Found ( 404 ) but got ( 200)\\nexpected : 404\\n but got : 200\ " assert404 :: Response -> Assertion assert404 rsp = assertEqual message 404 status where message = "Expected Not Found (404) but got (" ++ (show status) ++ ")" status = rspStatus rsp | Given a ' Response ' , assert that its HTTP status code is between 300 and 399 specified URI . ghci > let r ' = ' Snap . Core.setResponseStatus ' 301 \"Moved Permanently\ " ' Snap . Core.emptyResponse ' ghci > let r = ' Snap . Core.setHeader ' \"Location\ " \"www.example.com\ " r ' ghci > ' assertRedirectTo ' \"www.example.com\ " ' Snap . Core.emptyResponse ' * * * Exception : HUnitFailure \"Expected redirect but got status code ( 200)\ " URI -> Response -> Assertion assertRedirectTo uri rsp = do assertRedirect rsp assertEqual message uri rspUri where rspUri = fromJust $ getHeader "Location" rsp message = "Expected redirect to " ++ show uri ++ " but got redirected to " ++ show rspUri ++ " instead" | Given a ' Response ' , assert that its HTTP status code is between 300 and 399 ghci > ' assertRedirect ' $ ' Snap . Core.setResponseStatus ' 301 \"Moved Permanently\ " ' Snap . Core.emptyResponse ' ghci > ' assertRedirect ' ' Snap . Core.emptyResponse ' * * * Exception : HUnitFailure \"Expected redirect but got status code ( 200)\ " assertRedirect :: Response -> Assertion assertRedirect rsp = assertBool message (300 <= status && status <= 399) where message = "Expected redirect but got status code (" ++ show status ++ ")" status = rspStatus rsp ghci > import qualified " Data . ByteString . Builder " as Builder ghci| ' Snap . Core.emptyResponse ' * * * Exception : HUnitFailure " Expected body to match regexp \\\"\\\"Bye\\\"\\\ " , but didn\'t " ^ Regexp that will match the body content -> Response -> Assertion assertBodyContains match rsp = do body <- getResponseBody rsp assertBool message (body =~ match) where message = "Expected body to match regexp \"" ++ show match ++ "\", but didn't"
d5e12938c4776a243f13310171a5c74635bc55f2d6d57c91327d6040011f2165
matsen/pplacer
rppr_infer.ml
open Subcommand open Guppy_cmdobjs open Ppatteries open Convex let prune_notax sizemim st = let open Stree in let rec should_prune i = let sizem = IntMap.find i sizemim in ColorMap.cardinal sizem = 1 && ColorMap.mem Tax_id.NoTax sizem and aux = function | Leaf _ as l -> l | Node (i, subtrees) -> List.filter_map (fun t -> let j = top_id t in if should_prune j then None else Some (aux t)) subtrees |> node i in aux st let place_on_rp prefs ?placerun_cb rp gt = let td = Refpkg.get_taxonomy rp in Prefs.( prefs.informative_prior := true; prefs.keep_at_most := 20; prefs.keep_factor := 0.001; prefs.max_strikes := 20); let criterion = if Prefs.calc_pp prefs then Placement.post_prob else Placement.ml_ratio and results = RefList.empty () in let placerun_cb pr = Option.may ((|>) pr) placerun_cb; Placerun.get_pqueries pr |> List.iter (fun pq -> let classif = Pquery.place_list pq |> List.map Placement.classif |> Tax_taxonomy.list_mrca td in List.iter (Tuple3.curry identity classif (Pquery.best_place criterion pq) |- RefList.push results) (Pquery.namel pq)) and ref_name_set = Newick_gtree.leaf_label_map gt |> IntMap.values |> StringSet.of_enum in let query_align, ref_align = Pplacer_run.partition_queries ref_name_set (Refpkg.get_aln_fasta rp) in let rp' = Option.map_default (flip Refpkg.set_aln_fasta rp) rp ref_align |> Refpkg.set_ref_tree (Gtree.renumber gt |> fst) in Pplacer_run.run_placements prefs rp' (Array.to_list query_align) false "" placerun_cb; RefList.to_list results class cmd () = object (self) inherit subcommand () as super inherit refpkg_cmd ~required:true as super_refpkg inherit tabular_cmd () as super_tabular inherit placefile_cmd () as super_placefile (* required to get #write_placefile *) method private placefile_action _ = () val processes = flag "-j" (Formatted (2, "The number of processes to run pplacer with. default: %d")) val post_prob = flag "-p" (Plain (false, "Calculate posterior probabilities when doing placements.")) val placefile = flag "--placefile" (Needs_argument ("", "Save the placefile generated by running pplacer to the specified location.")) method specl = super_refpkg#specl @ super_tabular#specl @ [ int_flag processes; toggle_flag post_prob; string_flag placefile; ] method desc = "infers classifications of unclassified sequences in a reference package" method usage = "usage: infer [options] -c my.refpkg" method private prefs = let prefs = Prefs.defaults () in prefs.Prefs.refpkg_path := fv refpkg_path; Prefs.( prefs.children := fv processes; prefs.calc_pp := fv post_prob); prefs method private place_on_rp rp gt = place_on_rp self#prefs ?placerun_cb:(fvo placefile |> Option.map self#write_placefile) rp gt method action _ = let rp = self#get_rp in let gt = Refpkg.get_ref_tree rp and td = Refpkg.get_taxonomy rp and seqinfo = Refpkg.get_seqinfom rp in let leaf_labels = Newick_gtree.leaf_label_map gt in let colors = IntMap.map (Tax_seqinfo.tax_id_by_node_label seqinfo) leaf_labels and seq_nodes = IntMap.enum leaf_labels |> Enum.map swap |> StringMap.of_enum and st = Gtree.get_stree gt in let taxa_set colorm needle = IntMap.fold (fun i ti accum -> if ti = needle then IntSet.add i accum else accum) colorm IntSet.empty and sizemim, _ = build_sizemim_and_cutsetim (colors, st) in let dm = Edge_rdist.build_pairwise_dist gt and no_tax = taxa_set colors Tax_id.NoTax in let max_taxdist colorm ti = let ta = taxa_set colorm ti |> IntSet.elements |> Array.of_list in Uptri.init (Array.length ta) (fun i j -> Edge_rdist.find_pairwise_dist dm ta.(i) 0. ta.(j) 0.) |> Uptri.to_array |> Array.max and st' = prune_notax sizemim st in let gt' = Gtree.set_stree gt st' in let results = self#place_on_rp rp gt' in let colors' = List.fold_left (fun accum (tid, _, seq) -> IntMap.add (StringMap.find seq seq_nodes) tid accum) colors results and best_placements = List.fold_left (fun accum (_, p, seq) -> IntMap.add (StringMap.find seq seq_nodes) p accum) IntMap.empty results in let rankmap = IntMap.enum colors' |> build_rank_tax_map td some in let highest_rank, _ = IntMap.max_binding rankmap in IntSet.fold (fun i accum -> let p = IntMap.find i best_placements in dprintf ~l:2 "%s:\n" (Gtree.get_node_label gt i); let rec aux rank = if not (IntMap.mem rank rankmap) then aux (rank - 1) else (* ... *) let taxm = IntMap.find rank rankmap in if not (IntMap.mem i taxm) then aux (rank - 1) else (* ... *) let ti = IntMap.find i taxm in let others = taxa_set taxm ti |> flip IntSet.diff no_tax and max_pairwise = max_taxdist taxm ti in let max_placement = others |> IntSet.enum |> Enum.map (fun j -> Edge_rdist.find_pairwise_dist dm j 0. (Placement.location p) (Placement.distal_bl p)) |> Enum.reduce max |> (+.) (Placement.pendant_bl p) in dprintf ~l:2 " %s -> %s (%s): %b %g max %g max+pend\n" (Tax_taxonomy.get_rank_name td rank) (Tax_id.to_string ti) (Tax_taxonomy.get_tax_name td ti) (max_placement < max_pairwise) max_pairwise max_placement; if max_placement < max_pairwise then ti else if rank = 0 then begin dprintf "warning: no inferred taxid for %s\n" (Gtree.get_node_label gt i); Tax_id.NoTax end else aux (rank - 1) in let ti = aux highest_rank in [Gtree.get_node_label gt i; Tax_id.to_string ti; match ti with | Tax_id.NoTax -> "-" | _ -> Tax_taxonomy.get_tax_name td ti] :: accum) no_tax [] |> List.cons ["seq_name"; "new_taxid"; "new_name"] |> self#write_ll_tab end
null
https://raw.githubusercontent.com/matsen/pplacer/f40a363e962cca7131f1f2d372262e0081ff1190/pplacer_src/rppr_infer.ml
ocaml
required to get #write_placefile ... ...
open Subcommand open Guppy_cmdobjs open Ppatteries open Convex let prune_notax sizemim st = let open Stree in let rec should_prune i = let sizem = IntMap.find i sizemim in ColorMap.cardinal sizem = 1 && ColorMap.mem Tax_id.NoTax sizem and aux = function | Leaf _ as l -> l | Node (i, subtrees) -> List.filter_map (fun t -> let j = top_id t in if should_prune j then None else Some (aux t)) subtrees |> node i in aux st let place_on_rp prefs ?placerun_cb rp gt = let td = Refpkg.get_taxonomy rp in Prefs.( prefs.informative_prior := true; prefs.keep_at_most := 20; prefs.keep_factor := 0.001; prefs.max_strikes := 20); let criterion = if Prefs.calc_pp prefs then Placement.post_prob else Placement.ml_ratio and results = RefList.empty () in let placerun_cb pr = Option.may ((|>) pr) placerun_cb; Placerun.get_pqueries pr |> List.iter (fun pq -> let classif = Pquery.place_list pq |> List.map Placement.classif |> Tax_taxonomy.list_mrca td in List.iter (Tuple3.curry identity classif (Pquery.best_place criterion pq) |- RefList.push results) (Pquery.namel pq)) and ref_name_set = Newick_gtree.leaf_label_map gt |> IntMap.values |> StringSet.of_enum in let query_align, ref_align = Pplacer_run.partition_queries ref_name_set (Refpkg.get_aln_fasta rp) in let rp' = Option.map_default (flip Refpkg.set_aln_fasta rp) rp ref_align |> Refpkg.set_ref_tree (Gtree.renumber gt |> fst) in Pplacer_run.run_placements prefs rp' (Array.to_list query_align) false "" placerun_cb; RefList.to_list results class cmd () = object (self) inherit subcommand () as super inherit refpkg_cmd ~required:true as super_refpkg inherit tabular_cmd () as super_tabular inherit placefile_cmd () as super_placefile method private placefile_action _ = () val processes = flag "-j" (Formatted (2, "The number of processes to run pplacer with. default: %d")) val post_prob = flag "-p" (Plain (false, "Calculate posterior probabilities when doing placements.")) val placefile = flag "--placefile" (Needs_argument ("", "Save the placefile generated by running pplacer to the specified location.")) method specl = super_refpkg#specl @ super_tabular#specl @ [ int_flag processes; toggle_flag post_prob; string_flag placefile; ] method desc = "infers classifications of unclassified sequences in a reference package" method usage = "usage: infer [options] -c my.refpkg" method private prefs = let prefs = Prefs.defaults () in prefs.Prefs.refpkg_path := fv refpkg_path; Prefs.( prefs.children := fv processes; prefs.calc_pp := fv post_prob); prefs method private place_on_rp rp gt = place_on_rp self#prefs ?placerun_cb:(fvo placefile |> Option.map self#write_placefile) rp gt method action _ = let rp = self#get_rp in let gt = Refpkg.get_ref_tree rp and td = Refpkg.get_taxonomy rp and seqinfo = Refpkg.get_seqinfom rp in let leaf_labels = Newick_gtree.leaf_label_map gt in let colors = IntMap.map (Tax_seqinfo.tax_id_by_node_label seqinfo) leaf_labels and seq_nodes = IntMap.enum leaf_labels |> Enum.map swap |> StringMap.of_enum and st = Gtree.get_stree gt in let taxa_set colorm needle = IntMap.fold (fun i ti accum -> if ti = needle then IntSet.add i accum else accum) colorm IntSet.empty and sizemim, _ = build_sizemim_and_cutsetim (colors, st) in let dm = Edge_rdist.build_pairwise_dist gt and no_tax = taxa_set colors Tax_id.NoTax in let max_taxdist colorm ti = let ta = taxa_set colorm ti |> IntSet.elements |> Array.of_list in Uptri.init (Array.length ta) (fun i j -> Edge_rdist.find_pairwise_dist dm ta.(i) 0. ta.(j) 0.) |> Uptri.to_array |> Array.max and st' = prune_notax sizemim st in let gt' = Gtree.set_stree gt st' in let results = self#place_on_rp rp gt' in let colors' = List.fold_left (fun accum (tid, _, seq) -> IntMap.add (StringMap.find seq seq_nodes) tid accum) colors results and best_placements = List.fold_left (fun accum (_, p, seq) -> IntMap.add (StringMap.find seq seq_nodes) p accum) IntMap.empty results in let rankmap = IntMap.enum colors' |> build_rank_tax_map td some in let highest_rank, _ = IntMap.max_binding rankmap in IntSet.fold (fun i accum -> let p = IntMap.find i best_placements in dprintf ~l:2 "%s:\n" (Gtree.get_node_label gt i); let rec aux rank = let taxm = IntMap.find rank rankmap in let ti = IntMap.find i taxm in let others = taxa_set taxm ti |> flip IntSet.diff no_tax and max_pairwise = max_taxdist taxm ti in let max_placement = others |> IntSet.enum |> Enum.map (fun j -> Edge_rdist.find_pairwise_dist dm j 0. (Placement.location p) (Placement.distal_bl p)) |> Enum.reduce max |> (+.) (Placement.pendant_bl p) in dprintf ~l:2 " %s -> %s (%s): %b %g max %g max+pend\n" (Tax_taxonomy.get_rank_name td rank) (Tax_id.to_string ti) (Tax_taxonomy.get_tax_name td ti) (max_placement < max_pairwise) max_pairwise max_placement; if max_placement < max_pairwise then ti else if rank = 0 then begin dprintf "warning: no inferred taxid for %s\n" (Gtree.get_node_label gt i); Tax_id.NoTax end else aux (rank - 1) in let ti = aux highest_rank in [Gtree.get_node_label gt i; Tax_id.to_string ti; match ti with | Tax_id.NoTax -> "-" | _ -> Tax_taxonomy.get_tax_name td ti] :: accum) no_tax [] |> List.cons ["seq_name"; "new_taxid"; "new_name"] |> self#write_ll_tab end
cc3960ba3d5035ae01a35d64524b70fe972b664e35c0921f1997ea37bc285914
2600hz/kazoo
kapi_callflow.erl
%%%----------------------------------------------------------------------------- ( C ) 2013 - 2020 , 2600Hz %%% @doc @author 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 /. %%% %%% @end %%%----------------------------------------------------------------------------- -module(kapi_callflow). -include_lib("kazoo_stdlib/include/kz_types.hrl"). -include("kz_api_literals.hrl"). -export([api_definitions/0, api_definition/1]). -export([resume/1 ,resume_v/1 ,publish_resume/1 ]). -export([action_execute/1 ,action_execute_v/1 ,publish_action_execute/2 ]). -export([action_accepted/1 ,action_accepted_v/1 ,publish_action_accepted/2 ]). -export([action_result/1 ,action_result_v/1 ,publish_action_result/2 ]). -export([bind_q/2 ,unbind_q/2 ]). -export([declare_exchanges/0]). -type resume() :: kz_json:object(). -export_type([resume/0]). -ifdef(TEST). -export([action_routing_key/1 ]). -endif. %%------------------------------------------------------------------------------ %% @doc Get all API definitions of this module. %% @end %%------------------------------------------------------------------------------ -spec api_definitions() -> kapi_definition:apis(). api_definitions() -> [resume_definition() ,action_execute_definition() ,action_accepted_definition() ,action_result_definition() ]. %%------------------------------------------------------------------------------ %% @doc Get API definition of the given `Name'. %% @see api_definitions/0 %% @end %%------------------------------------------------------------------------------ -spec api_definition(kz_term:text()) -> kapi_definition:api(). api_definition(Name) when not is_binary(Name) -> api_definition(kz_term:to_binary(Name)); api_definition(<<"resume">>) -> resume_definition(); api_definition(<<"action_execute">>) -> action_execute_definition(); api_definition(<<"action_accepted">>) -> action_accepted_definition(); api_definition(<<"action_result">>) -> action_result_definition(). -spec resume_definition() -> kapi_definition:api(). resume_definition() -> EventName = <<"resume">>, Category = <<"callflow">>, Setters = [{fun kapi_definition:set_name/2, EventName} ,{fun kapi_definition:set_friendly_name/2, <<"Resume Callflow">>} ,{fun kapi_definition:set_description/2, <<"Resume a Callflow's flow">>} ,{fun kapi_definition:set_category/2, Category} ,{fun kapi_definition:set_build_fun/2, fun resume/1} ,{fun kapi_definition:set_validate_fun/2, fun resume_v/1} ,{fun kapi_definition:set_publish_fun/2, fun publish_resume/1} ,{fun kapi_definition:set_binding/2, <<"callflow.resume">>} ,{fun kapi_definition:set_required_headers/2, [<<"Call">> ,<<"Flow">> ]} ,{fun kapi_definition:set_optional_headers/2, []} ,{fun kapi_definition:set_values/2 ,kapi_definition:event_type_headers(Category, EventName) } ,{fun kapi_definition:set_types/2, []} ], kapi_definition:setters(Setters). -spec action_execute_definition() -> kapi_definition:api(). action_execute_definition() -> EventName = <<"action.execute">>, Category = <<"callflow">>, Setters = [{fun kapi_definition:set_name/2, EventName} ,{fun kapi_definition:set_friendly_name/2, <<"Remote execute a Callflow action">>} ,{fun kapi_definition:set_description/2, <<"Remote execute a Callflow action">>} ,{fun kapi_definition:set_category/2, Category} ,{fun kapi_definition:set_build_fun/2, fun action_execute/1} ,{fun kapi_definition:set_validate_fun/2, fun action_execute_v/1} ,{fun kapi_definition:set_publish_fun/2, fun publish_action_execute/2} ,{fun kapi_definition:set_binding/2, fun action_routing_key/1} ,{fun kapi_definition:set_required_headers/2, [<<"Call-ID">> ,<<"Call">> ]} ,{fun kapi_definition:set_optional_headers/2, [<<"Data">>]} ,{fun kapi_definition:set_values/2 ,kapi_definition:event_type_headers(Category, EventName) } ,{fun kapi_definition:set_types/2, []} ], kapi_definition:setters(Setters). -spec action_accepted_definition() -> kapi_definition:api(). action_accepted_definition() -> EventName = <<"action.accepted">>, Category = <<"callflow">>, Setters = [{fun kapi_definition:set_name/2, EventName} ,{fun kapi_definition:set_friendly_name/2, <<"Remote execute a Callflow action">>} ,{fun kapi_definition:set_description/2, <<"Remote execute a Callflow action">>} ,{fun kapi_definition:set_category/2, Category} ,{fun kapi_definition:set_build_fun/2, fun action_accepted/1} ,{fun kapi_definition:set_validate_fun/2, fun action_accepted_v/1} ,{fun kapi_definition:set_publish_fun/2, fun publish_action_accepted/2} ,{fun kapi_definition:set_required_headers/2, [?KEY_MSG_ID ,<<"Call-ID">> ]} ,{fun kapi_definition:set_optional_headers/2, []} ,{fun kapi_definition:set_values/2 ,kapi_definition:event_type_headers(Category, EventName) } ,{fun kapi_definition:set_types/2, []} ], kapi_definition:setters(Setters). -spec action_result_definition() -> kapi_definition:api(). action_result_definition() -> EventName = <<"action.result">>, Category = <<"callflow">>, Setters = [{fun kapi_definition:set_name/2, EventName} ,{fun kapi_definition:set_friendly_name/2, <<"Remote execute a Callflow action">>} ,{fun kapi_definition:set_description/2, <<"Remote execute a Callflow action">>} ,{fun kapi_definition:set_category/2, Category} ,{fun kapi_definition:set_build_fun/2, fun action_result/1} ,{fun kapi_definition:set_validate_fun/2, fun action_result_v/1} ,{fun kapi_definition:set_publish_fun/2, fun publish_action_result/2} ,{fun kapi_definition:set_required_headers/2, [?KEY_MSG_ID ,<<"Call-ID">> ,<<"Result">> ]} ,{fun kapi_definition:set_optional_headers/2, []} ,{fun kapi_definition:set_values/2 ,kapi_definition:event_type_headers(Category, EventName) } ,{fun kapi_definition:set_types/2, []} ], kapi_definition:setters(Setters). %%------------------------------------------------------------------------------ %% @doc Resume a Callflow's flow. Takes { @link kz_term : ( ) } , creates JSON string or error . %% @end %%------------------------------------------------------------------------------ -spec resume(kz_term:api_terms()) -> kz_api:api_formatter_return(). resume(Req) -> kapi_definition:build_message(Req, resume_definition()). -spec resume_v(kz_term:api_terms()) -> boolean(). resume_v(Req) -> kapi_definition:validate(Req, resume_definition()). -spec publish_resume(kz_term:api_terms()) -> 'ok'. publish_resume(JObj) -> Definition = resume_definition(), {'ok', Payload} = kz_api:prepare_api_payload(JObj ,kapi_definition:values(Definition) ,[{'formatter', kapi_definition:build_fun(Definition)} ,{'remove_recursive', 'false'} ] ), kz_amqp_util:kapps_publish(kapi_definition:binding(Definition), Payload). %%------------------------------------------------------------------------------ @doc Remote execution of a 's action . Takes { @link kz_term : ( ) } , creates JSON string or error . %% @end %%------------------------------------------------------------------------------ -spec action_execute(kz_term:api_terms()) -> kz_api:api_formatter_return(). action_execute(Req) -> kapi_definition:build_message(Req, action_execute_definition()). -spec action_execute_v(kz_term:api_terms()) -> boolean(). action_execute_v(Req) -> kapi_definition:validate(Req, action_execute_definition()). -spec publish_action_execute(kz_term:ne_binary(), kz_term:api_terms()) -> 'ok'. publish_action_execute(Action, API) -> Definition = action_execute_definition(), {'ok', Payload} = kz_api:prepare_api_payload(API ,kapi_definition:values(Definition) ,[{'formatter', kapi_definition:build_fun(Definition)} ,{'remove_recursive', 'false'} ] ), Options = [{mandatory, true}], kz_amqp_util:kapps_publish((kapi_definition:binding(action_execute_definition()))(Action) ,Payload ,?DEFAULT_CONTENT_TYPE ,Options ). -spec action_accepted(kz_term:api_terms()) -> kz_api:api_formatter_return(). action_accepted(Req) -> kapi_definition:build_message(Req, action_accepted_definition()). -spec action_accepted_v(kz_term:api_terms()) -> boolean(). action_accepted_v(Req) -> kapi_definition:validate(Req, action_accepted_definition()). -spec publish_action_accepted(kz_term:ne_binary(), kz_term:api_terms()) -> 'ok'. publish_action_accepted(ServerId, JObj) -> Definition = action_accepted_definition(), {'ok', Payload} = kz_api:prepare_api_payload(JObj ,kapi_definition:values(Definition) ,[{'formatter', kapi_definition:build_fun(Definition)} ,{'remove_recursive', 'false'} ] ), kz_amqp_util:targeted_publish(ServerId, Payload). -spec action_result(kz_term:api_terms()) -> kz_api:api_formatter_return(). action_result(Req) -> kapi_definition:build_message(Req, action_result_definition()). -spec action_result_v(kz_term:api_terms()) -> boolean(). action_result_v(Req) -> kapi_definition:validate(Req, action_result_definition()). -spec publish_action_result(kz_term:ne_binary(), kz_term:api_terms()) -> 'ok'. publish_action_result(ServerId, JObj) -> Definition = action_result_definition(), {'ok', Payload} = kz_api:prepare_api_payload(JObj ,kapi_definition:values(Definition) ,[{'formatter', kapi_definition:build_fun(Definition)} ,{'remove_recursive', 'false'} ] ), kz_amqp_util:targeted_publish(ServerId, Payload). %%------------------------------------------------------------------------------ %% @doc Binds used by this API. %% @end %%------------------------------------------------------------------------------ -spec bind_q(kz_term:ne_binary(), kz_term:proplist()) -> 'ok'. bind_q(Q, Props) -> RestrictTo = props:get_value('restrict_to', Props), bind_q(Q, RestrictTo, Props). -spec bind_q(kz_term:ne_binary(), kz_term:api_atoms(), kz_term:proplist()) -> 'ok'. bind_q(Q, 'undefined', _) -> kz_amqp_util:bind_q_to_kapps(Q, kapi_definition:binding(resume_definition())); bind_q(Q, ['resume'|Restrict], Props) -> kz_amqp_util:bind_q_to_kapps(Q, kapi_definition:binding(resume_definition())), bind_q(Q, Restrict, Props); bind_q(Q, ['actions'|Restrict], Props) -> Actions = props:get_value('actions', Props, []), _ = [kz_amqp_util:bind_q_to_kapps(Q ,(kapi_definition:binding(action_execute_definition()))(kz_term:to_binary(Action)) ) || Action <- Actions ], bind_q(Q, Restrict, Props); bind_q(Q, [_|Restrict], Props) -> bind_q(Q, Restrict, Props); bind_q(_, [], _) -> 'ok'. -spec unbind_q(kz_term:ne_binary(), kz_term:proplist()) -> 'ok'. unbind_q(Q, Props) -> RestrictTo = props:get_value('restrict_to', Props), unbind_q(Q, RestrictTo, Props). -spec unbind_q(kz_term:ne_binary(), kz_term:api_atoms(), kz_term:proplist()) -> 'ok'. unbind_q(Q, 'undefined', _) -> kz_amqp_util:unbind_q_from_kapps(Q, kapi_definition:binding(resume_definition())); unbind_q(Q, ['resume'|Restrict], Props) -> _ = kz_amqp_util:unbind_q_from_kapps(Q, kapi_definition:binding(resume_definition())), unbind_q(Q, Restrict, Props); unbind_q(Q, ['actions'|Restrict], Props) -> Actions = props:get_value('actions', Props, []), _ = [kz_amqp_util:unbind_q_from_kapps(Q ,(kapi_definition:binding(action_execute_definition()))(kz_term:to_binary(Action)) ) || Action <- Actions ], unbind_q(Q, Restrict, Props); unbind_q(Q, [_|Restrict], Props) -> unbind_q(Q, Restrict, Props); unbind_q(_, [], _) -> 'ok'. %%------------------------------------------------------------------------------ %% @doc Declare the exchanges used by this API. %% @end %%------------------------------------------------------------------------------ -spec declare_exchanges() -> 'ok'. declare_exchanges() -> kz_amqp_util:kapps_exchange(), kz_amqp_util:targeted_exchange(). -spec action_routing_key(kz_term:ne_binary()) -> kz_term:ne_binary(). action_routing_key(Action) -> <<"callflow.action.", Action/binary>>.
null
https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/core/kazoo_amqp/src/api/kapi_callflow.erl
erlang
----------------------------------------------------------------------------- @doc @end ----------------------------------------------------------------------------- ------------------------------------------------------------------------------ @doc Get all API definitions of this module. @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc Get API definition of the given `Name'. @see api_definitions/0 @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc Resume a Callflow's flow. @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc Binds used by this API. @end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @doc Declare the exchanges used by this API. @end ------------------------------------------------------------------------------
( C ) 2013 - 2020 , 2600Hz @author 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 /. -module(kapi_callflow). -include_lib("kazoo_stdlib/include/kz_types.hrl"). -include("kz_api_literals.hrl"). -export([api_definitions/0, api_definition/1]). -export([resume/1 ,resume_v/1 ,publish_resume/1 ]). -export([action_execute/1 ,action_execute_v/1 ,publish_action_execute/2 ]). -export([action_accepted/1 ,action_accepted_v/1 ,publish_action_accepted/2 ]). -export([action_result/1 ,action_result_v/1 ,publish_action_result/2 ]). -export([bind_q/2 ,unbind_q/2 ]). -export([declare_exchanges/0]). -type resume() :: kz_json:object(). -export_type([resume/0]). -ifdef(TEST). -export([action_routing_key/1 ]). -endif. -spec api_definitions() -> kapi_definition:apis(). api_definitions() -> [resume_definition() ,action_execute_definition() ,action_accepted_definition() ,action_result_definition() ]. -spec api_definition(kz_term:text()) -> kapi_definition:api(). api_definition(Name) when not is_binary(Name) -> api_definition(kz_term:to_binary(Name)); api_definition(<<"resume">>) -> resume_definition(); api_definition(<<"action_execute">>) -> action_execute_definition(); api_definition(<<"action_accepted">>) -> action_accepted_definition(); api_definition(<<"action_result">>) -> action_result_definition(). -spec resume_definition() -> kapi_definition:api(). resume_definition() -> EventName = <<"resume">>, Category = <<"callflow">>, Setters = [{fun kapi_definition:set_name/2, EventName} ,{fun kapi_definition:set_friendly_name/2, <<"Resume Callflow">>} ,{fun kapi_definition:set_description/2, <<"Resume a Callflow's flow">>} ,{fun kapi_definition:set_category/2, Category} ,{fun kapi_definition:set_build_fun/2, fun resume/1} ,{fun kapi_definition:set_validate_fun/2, fun resume_v/1} ,{fun kapi_definition:set_publish_fun/2, fun publish_resume/1} ,{fun kapi_definition:set_binding/2, <<"callflow.resume">>} ,{fun kapi_definition:set_required_headers/2, [<<"Call">> ,<<"Flow">> ]} ,{fun kapi_definition:set_optional_headers/2, []} ,{fun kapi_definition:set_values/2 ,kapi_definition:event_type_headers(Category, EventName) } ,{fun kapi_definition:set_types/2, []} ], kapi_definition:setters(Setters). -spec action_execute_definition() -> kapi_definition:api(). action_execute_definition() -> EventName = <<"action.execute">>, Category = <<"callflow">>, Setters = [{fun kapi_definition:set_name/2, EventName} ,{fun kapi_definition:set_friendly_name/2, <<"Remote execute a Callflow action">>} ,{fun kapi_definition:set_description/2, <<"Remote execute a Callflow action">>} ,{fun kapi_definition:set_category/2, Category} ,{fun kapi_definition:set_build_fun/2, fun action_execute/1} ,{fun kapi_definition:set_validate_fun/2, fun action_execute_v/1} ,{fun kapi_definition:set_publish_fun/2, fun publish_action_execute/2} ,{fun kapi_definition:set_binding/2, fun action_routing_key/1} ,{fun kapi_definition:set_required_headers/2, [<<"Call-ID">> ,<<"Call">> ]} ,{fun kapi_definition:set_optional_headers/2, [<<"Data">>]} ,{fun kapi_definition:set_values/2 ,kapi_definition:event_type_headers(Category, EventName) } ,{fun kapi_definition:set_types/2, []} ], kapi_definition:setters(Setters). -spec action_accepted_definition() -> kapi_definition:api(). action_accepted_definition() -> EventName = <<"action.accepted">>, Category = <<"callflow">>, Setters = [{fun kapi_definition:set_name/2, EventName} ,{fun kapi_definition:set_friendly_name/2, <<"Remote execute a Callflow action">>} ,{fun kapi_definition:set_description/2, <<"Remote execute a Callflow action">>} ,{fun kapi_definition:set_category/2, Category} ,{fun kapi_definition:set_build_fun/2, fun action_accepted/1} ,{fun kapi_definition:set_validate_fun/2, fun action_accepted_v/1} ,{fun kapi_definition:set_publish_fun/2, fun publish_action_accepted/2} ,{fun kapi_definition:set_required_headers/2, [?KEY_MSG_ID ,<<"Call-ID">> ]} ,{fun kapi_definition:set_optional_headers/2, []} ,{fun kapi_definition:set_values/2 ,kapi_definition:event_type_headers(Category, EventName) } ,{fun kapi_definition:set_types/2, []} ], kapi_definition:setters(Setters). -spec action_result_definition() -> kapi_definition:api(). action_result_definition() -> EventName = <<"action.result">>, Category = <<"callflow">>, Setters = [{fun kapi_definition:set_name/2, EventName} ,{fun kapi_definition:set_friendly_name/2, <<"Remote execute a Callflow action">>} ,{fun kapi_definition:set_description/2, <<"Remote execute a Callflow action">>} ,{fun kapi_definition:set_category/2, Category} ,{fun kapi_definition:set_build_fun/2, fun action_result/1} ,{fun kapi_definition:set_validate_fun/2, fun action_result_v/1} ,{fun kapi_definition:set_publish_fun/2, fun publish_action_result/2} ,{fun kapi_definition:set_required_headers/2, [?KEY_MSG_ID ,<<"Call-ID">> ,<<"Result">> ]} ,{fun kapi_definition:set_optional_headers/2, []} ,{fun kapi_definition:set_values/2 ,kapi_definition:event_type_headers(Category, EventName) } ,{fun kapi_definition:set_types/2, []} ], kapi_definition:setters(Setters). Takes { @link kz_term : ( ) } , creates JSON string or error . -spec resume(kz_term:api_terms()) -> kz_api:api_formatter_return(). resume(Req) -> kapi_definition:build_message(Req, resume_definition()). -spec resume_v(kz_term:api_terms()) -> boolean(). resume_v(Req) -> kapi_definition:validate(Req, resume_definition()). -spec publish_resume(kz_term:api_terms()) -> 'ok'. publish_resume(JObj) -> Definition = resume_definition(), {'ok', Payload} = kz_api:prepare_api_payload(JObj ,kapi_definition:values(Definition) ,[{'formatter', kapi_definition:build_fun(Definition)} ,{'remove_recursive', 'false'} ] ), kz_amqp_util:kapps_publish(kapi_definition:binding(Definition), Payload). @doc Remote execution of a 's action . Takes { @link kz_term : ( ) } , creates JSON string or error . -spec action_execute(kz_term:api_terms()) -> kz_api:api_formatter_return(). action_execute(Req) -> kapi_definition:build_message(Req, action_execute_definition()). -spec action_execute_v(kz_term:api_terms()) -> boolean(). action_execute_v(Req) -> kapi_definition:validate(Req, action_execute_definition()). -spec publish_action_execute(kz_term:ne_binary(), kz_term:api_terms()) -> 'ok'. publish_action_execute(Action, API) -> Definition = action_execute_definition(), {'ok', Payload} = kz_api:prepare_api_payload(API ,kapi_definition:values(Definition) ,[{'formatter', kapi_definition:build_fun(Definition)} ,{'remove_recursive', 'false'} ] ), Options = [{mandatory, true}], kz_amqp_util:kapps_publish((kapi_definition:binding(action_execute_definition()))(Action) ,Payload ,?DEFAULT_CONTENT_TYPE ,Options ). -spec action_accepted(kz_term:api_terms()) -> kz_api:api_formatter_return(). action_accepted(Req) -> kapi_definition:build_message(Req, action_accepted_definition()). -spec action_accepted_v(kz_term:api_terms()) -> boolean(). action_accepted_v(Req) -> kapi_definition:validate(Req, action_accepted_definition()). -spec publish_action_accepted(kz_term:ne_binary(), kz_term:api_terms()) -> 'ok'. publish_action_accepted(ServerId, JObj) -> Definition = action_accepted_definition(), {'ok', Payload} = kz_api:prepare_api_payload(JObj ,kapi_definition:values(Definition) ,[{'formatter', kapi_definition:build_fun(Definition)} ,{'remove_recursive', 'false'} ] ), kz_amqp_util:targeted_publish(ServerId, Payload). -spec action_result(kz_term:api_terms()) -> kz_api:api_formatter_return(). action_result(Req) -> kapi_definition:build_message(Req, action_result_definition()). -spec action_result_v(kz_term:api_terms()) -> boolean(). action_result_v(Req) -> kapi_definition:validate(Req, action_result_definition()). -spec publish_action_result(kz_term:ne_binary(), kz_term:api_terms()) -> 'ok'. publish_action_result(ServerId, JObj) -> Definition = action_result_definition(), {'ok', Payload} = kz_api:prepare_api_payload(JObj ,kapi_definition:values(Definition) ,[{'formatter', kapi_definition:build_fun(Definition)} ,{'remove_recursive', 'false'} ] ), kz_amqp_util:targeted_publish(ServerId, Payload). -spec bind_q(kz_term:ne_binary(), kz_term:proplist()) -> 'ok'. bind_q(Q, Props) -> RestrictTo = props:get_value('restrict_to', Props), bind_q(Q, RestrictTo, Props). -spec bind_q(kz_term:ne_binary(), kz_term:api_atoms(), kz_term:proplist()) -> 'ok'. bind_q(Q, 'undefined', _) -> kz_amqp_util:bind_q_to_kapps(Q, kapi_definition:binding(resume_definition())); bind_q(Q, ['resume'|Restrict], Props) -> kz_amqp_util:bind_q_to_kapps(Q, kapi_definition:binding(resume_definition())), bind_q(Q, Restrict, Props); bind_q(Q, ['actions'|Restrict], Props) -> Actions = props:get_value('actions', Props, []), _ = [kz_amqp_util:bind_q_to_kapps(Q ,(kapi_definition:binding(action_execute_definition()))(kz_term:to_binary(Action)) ) || Action <- Actions ], bind_q(Q, Restrict, Props); bind_q(Q, [_|Restrict], Props) -> bind_q(Q, Restrict, Props); bind_q(_, [], _) -> 'ok'. -spec unbind_q(kz_term:ne_binary(), kz_term:proplist()) -> 'ok'. unbind_q(Q, Props) -> RestrictTo = props:get_value('restrict_to', Props), unbind_q(Q, RestrictTo, Props). -spec unbind_q(kz_term:ne_binary(), kz_term:api_atoms(), kz_term:proplist()) -> 'ok'. unbind_q(Q, 'undefined', _) -> kz_amqp_util:unbind_q_from_kapps(Q, kapi_definition:binding(resume_definition())); unbind_q(Q, ['resume'|Restrict], Props) -> _ = kz_amqp_util:unbind_q_from_kapps(Q, kapi_definition:binding(resume_definition())), unbind_q(Q, Restrict, Props); unbind_q(Q, ['actions'|Restrict], Props) -> Actions = props:get_value('actions', Props, []), _ = [kz_amqp_util:unbind_q_from_kapps(Q ,(kapi_definition:binding(action_execute_definition()))(kz_term:to_binary(Action)) ) || Action <- Actions ], unbind_q(Q, Restrict, Props); unbind_q(Q, [_|Restrict], Props) -> unbind_q(Q, Restrict, Props); unbind_q(_, [], _) -> 'ok'. -spec declare_exchanges() -> 'ok'. declare_exchanges() -> kz_amqp_util:kapps_exchange(), kz_amqp_util:targeted_exchange(). -spec action_routing_key(kz_term:ne_binary()) -> kz_term:ne_binary(). action_routing_key(Action) -> <<"callflow.action.", Action/binary>>.
b7a1777c7dd758209ac0a5ca0faeae155cebe55d41985dfc685b6fe109f031e5
ssadler/zeno
VarInt.hs
module Data.VarInt where import Control.Monad import Data.Aeson import Data.Bits import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import Data.FixedBytes import Data.RLP import Data.Serialize import Data.Word import Text.Printf import qualified Haskoin as H newtype VarInt = VarInt { unVarInt :: Word64 } deriving (Eq, Ord, Num, ToJSON, FromJSON, PrintfArg, Enum, Real, Integral) deriving Serialize via H.VarInt deriving Show via Word64 newtype VarPrefixedList a = VarPrefixedList [a] instance Serialize a => Serialize (VarPrefixedList a) where put (VarPrefixedList xs) = do put $ VarInt $ fromIntegral $ length xs mapM_ put xs get = do VarInt n <- get VarPrefixedList <$> replicateM (fromIntegral n) get newtype VarPrefixedLazyByteString = VarPrefixedLazyByteString BSL.ByteString instance Serialize VarPrefixedLazyByteString where put (VarPrefixedLazyByteString bs) = do put $ VarInt $ fromIntegral $ BSL.length bs putLazyByteString bs get = do n <- fromIntegral . unVarInt <$> get VarPrefixedLazyByteString <$> getLazyByteString n newtype PackedInteger = PackedInteger Integer deriving (Eq, Ord, Bits, Integral, Real, Enum, Num, Show, RLPEncodable, ToJSON, FromJSON) instance Serialize PackedInteger where put = putPacked get = getPacked putPacked :: (Bits i, Integral i) => i -> Put putPacked i = do let bs = intToBytesBE i put (fromIntegral $ length bs :: VarInt) mapM_ put bs getPacked :: (Bits i, Integral i) => Get i getPacked = do len <- fromIntegral . unVarInt <$> get intFromBytesBE <$> replicateM len get
null
https://raw.githubusercontent.com/ssadler/zeno/9f715d7104a7b7b00dee9fe35275fb217532fdb6/src/Data/VarInt.hs
haskell
module Data.VarInt where import Control.Monad import Data.Aeson import Data.Bits import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import Data.FixedBytes import Data.RLP import Data.Serialize import Data.Word import Text.Printf import qualified Haskoin as H newtype VarInt = VarInt { unVarInt :: Word64 } deriving (Eq, Ord, Num, ToJSON, FromJSON, PrintfArg, Enum, Real, Integral) deriving Serialize via H.VarInt deriving Show via Word64 newtype VarPrefixedList a = VarPrefixedList [a] instance Serialize a => Serialize (VarPrefixedList a) where put (VarPrefixedList xs) = do put $ VarInt $ fromIntegral $ length xs mapM_ put xs get = do VarInt n <- get VarPrefixedList <$> replicateM (fromIntegral n) get newtype VarPrefixedLazyByteString = VarPrefixedLazyByteString BSL.ByteString instance Serialize VarPrefixedLazyByteString where put (VarPrefixedLazyByteString bs) = do put $ VarInt $ fromIntegral $ BSL.length bs putLazyByteString bs get = do n <- fromIntegral . unVarInt <$> get VarPrefixedLazyByteString <$> getLazyByteString n newtype PackedInteger = PackedInteger Integer deriving (Eq, Ord, Bits, Integral, Real, Enum, Num, Show, RLPEncodable, ToJSON, FromJSON) instance Serialize PackedInteger where put = putPacked get = getPacked putPacked :: (Bits i, Integral i) => i -> Put putPacked i = do let bs = intToBytesBE i put (fromIntegral $ length bs :: VarInt) mapM_ put bs getPacked :: (Bits i, Integral i) => Get i getPacked = do len <- fromIntegral . unVarInt <$> get intFromBytesBE <$> replicateM len get
948b22584cef5da284c1b9a8f5f86e1a4104753ae210e702389837aae9a6abb0
awslabs/s2n-bignum
instruction.ml
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved . * SPDX - License - Identifier : Apache-2.0 OR ISC * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 OR ISC *) (* ========================================================================= *) (* Simplified definition of x86 assembly instructions. *) (* ========================================================================= *) let wordsize_INDUCT,wordsize_RECURSION = define_type "wordsize = Quadword | Doubleword | Word | Byte";; (* ------------------------------------------------------------------------- *) (* The general-purpose registers *) (* ------------------------------------------------------------------------- *) let regsize_INDUCT,regsize_RECURSION = define_type "regsize = Full_64 | Lower_32 | Lower_16 | Upper_8 | Lower_8";; (*** There are some not actually addressable ones here ***) (*** But it keeps things uniform to use this pattern ***) let gpr_INDUCT,gpr_RECURSION = define_type "gpr = Gpr (4 word) regsize";; let rax = define `rax = Gpr (word 0) Full_64` and rcx = define `rcx = Gpr (word 1) Full_64` and rdx = define `rdx = Gpr (word 2) Full_64` and rbx = define `rbx = Gpr (word 3) Full_64` and rsp = define `rsp = Gpr (word 4) Full_64` and rbp = define `rbp = Gpr (word 5) Full_64` and rsi = define `rsi = Gpr (word 6) Full_64` and rdi = define `rdi = Gpr (word 7) Full_64` and r8 = define ` r8 = Gpr (word 8) Full_64` and r9 = define ` r9 = Gpr (word 9) Full_64` and r10 = define `r10 = Gpr (word 10) Full_64` and r11 = define `r11 = Gpr (word 11) Full_64` and r12 = define `r12 = Gpr (word 12) Full_64` and r13 = define `r13 = Gpr (word 13) Full_64` and r14 = define `r14 = Gpr (word 14) Full_64` and r15 = define `r15 = Gpr (word 15) Full_64`;; let eax = define ` eax = Gpr (word 0) Lower_32` and ecx = define ` ecx = Gpr (word 1) Lower_32` and edx = define ` edx = Gpr (word 2) Lower_32` and ebx = define ` ebx = Gpr (word 3) Lower_32` and esp = define ` esp = Gpr (word 4) Lower_32` and ebp = define ` ebp = Gpr (word 5) Lower_32` and esi = define ` esi = Gpr (word 6) Lower_32` and edi = define ` edi = Gpr (word 7) Lower_32` and r8d = define ` r8d = Gpr (word 8) Lower_32` and r9d = define ` r9d = Gpr (word 9) Lower_32` and r10d = define `r10d = Gpr (word 10) Lower_32` and r11d = define `r11d = Gpr (word 11) Lower_32` and r12d = define `r12d = Gpr (word 12) Lower_32` and r13d = define `r13d = Gpr (word 13) Lower_32` and r14d = define `r14d = Gpr (word 14) Lower_32` and r15d = define `r15d = Gpr (word 15) Lower_32` and ax = define `ax = Gpr (word 0) Lower_16` and cx = define `cx = Gpr (word 1) Lower_16` and dx = define `dx = Gpr (word 2) Lower_16` and bx = define `bx = Gpr (word 3) Lower_16` and sp = define `sp = Gpr (word 4) Lower_16` and bp = define `bp = Gpr (word 5) Lower_16` and si = define `si = Gpr (word 6) Lower_16` and di = define `di = Gpr (word 7) Lower_16`;; let ah = define `ah = Gpr (word 0) Upper_8` and al = define `al = Gpr (word 0) Lower_8` and ch = define `ch = Gpr (word 1) Upper_8` and cl = define `cl = Gpr (word 1) Lower_8` and dh = define `dh = Gpr (word 2) Upper_8` and dl = define `dl = Gpr (word 2) Lower_8` and bh = define `bh = Gpr (word 3) Upper_8` and bl = define `bl = Gpr (word 3) Lower_8` and spl = define `spl = Gpr (word 4) Lower_8` and bpl = define `bpl = Gpr (word 5) Lower_8` and sil = define `sil = Gpr (word 6) Lower_8` and dil = define `dil = Gpr (word 7) Lower_8`;; (* ------------------------------------------------------------------------- *) XMM / YMM / ZMM registers and opmask registers . (* ------------------------------------------------------------------------- *) let simdregsize_INDUCT,simdregsize_RECURSION = define_type "simdregsize = Full_512 | Lower_256 | Lower_128";; * * Again xmm / ymm are n't addressable for 16 .. 31 , but this is uniform * * let simdreg_INDUCT,simdreg_RECURSION = define_type "simdreg = Simdreg (5 word) simdregsize";; let xmm0 = define `xmm0 = Simdreg (word 0) Lower_128` and xmm1 = define `xmm1 = Simdreg (word 1) Lower_128` and xmm2 = define `xmm2 = Simdreg (word 2) Lower_128` and xmm3 = define `xmm3 = Simdreg (word 3) Lower_128` and xmm4 = define `xmm4 = Simdreg (word 4) Lower_128` and xmm5 = define `xmm5 = Simdreg (word 5) Lower_128` and xmm6 = define `xmm6 = Simdreg (word 6) Lower_128` and xmm7 = define `xmm7 = Simdreg (word 7) Lower_128` and xmm8 = define `xmm8 = Simdreg (word 8) Lower_128` and xmm9 = define `xmm9 = Simdreg (word 9) Lower_128` and xmm10 = define `xmm10 = Simdreg (word 10) Lower_128` and xmm11 = define `xmm11 = Simdreg (word 11) Lower_128` and xmm12 = define `xmm12 = Simdreg (word 12) Lower_128` and xmm13 = define `xmm13 = Simdreg (word 13) Lower_128` and xmm14 = define `xmm14 = Simdreg (word 14) Lower_128` and xmm15 = define `xmm15 = Simdreg (word 15) Lower_128`;; let ymm0 = define `ymm0 = Simdreg (word 0) Lower_256` and ymm1 = define `ymm1 = Simdreg (word 1) Lower_256` and ymm2 = define `ymm2 = Simdreg (word 2) Lower_256` and ymm3 = define `ymm3 = Simdreg (word 3) Lower_256` and ymm4 = define `ymm4 = Simdreg (word 4) Lower_256` and ymm5 = define `ymm5 = Simdreg (word 5) Lower_256` and ymm6 = define `ymm6 = Simdreg (word 6) Lower_256` and ymm7 = define `ymm7 = Simdreg (word 7) Lower_256` and ymm8 = define `ymm8 = Simdreg (word 8) Lower_256` and ymm9 = define `ymm9 = Simdreg (word 9) Lower_256` and ymm10 = define `ymm10 = Simdreg (word 10) Lower_256` and ymm11 = define `ymm11 = Simdreg (word 11) Lower_256` and ymm12 = define `ymm12 = Simdreg (word 12) Lower_256` and ymm13 = define `ymm13 = Simdreg (word 13) Lower_256` and ymm14 = define `ymm14 = Simdreg (word 14) Lower_256` and ymm15 = define `ymm15 = Simdreg (word 15) Lower_256`;; let zmm0 = define `zmm0 = Simdreg (word 0) Full_512` and zmm1 = define `zmm1 = Simdreg (word 1) Full_512` and zmm2 = define `zmm2 = Simdreg (word 2) Full_512` and zmm3 = define `zmm3 = Simdreg (word 3) Full_512` and zmm4 = define `zmm4 = Simdreg (word 4) Full_512` and zmm5 = define `zmm5 = Simdreg (word 5) Full_512` and zmm6 = define `zmm6 = Simdreg (word 6) Full_512` and zmm7 = define `zmm7 = Simdreg (word 7) Full_512` and zmm8 = define `zmm8 = Simdreg (word 8) Full_512` and zmm9 = define `zmm9 = Simdreg (word 9) Full_512` and zmm10 = define `zmm10 = Simdreg (word 10) Full_512` and zmm11 = define `zmm11 = Simdreg (word 11) Full_512` and zmm12 = define `zmm12 = Simdreg (word 12) Full_512` and zmm13 = define `zmm13 = Simdreg (word 13) Full_512` and zmm14 = define `zmm14 = Simdreg (word 14) Full_512` and zmm15 = define `zmm15 = Simdreg (word 15) Full_512` and zmm16 = define `zmm16 = Simdreg (word 16) Full_512` and zmm17 = define `zmm17 = Simdreg (word 17) Full_512` and zmm18 = define `zmm18 = Simdreg (word 18) Full_512` and zmm19 = define `zmm19 = Simdreg (word 19) Full_512` and zmm20 = define `zmm20 = Simdreg (word 20) Full_512` and zmm21 = define `zmm21 = Simdreg (word 21) Full_512` and zmm22 = define `zmm22 = Simdreg (word 22) Full_512` and zmm23 = define `zmm23 = Simdreg (word 23) Full_512` and zmm24 = define `zmm24 = Simdreg (word 24) Full_512` and zmm25 = define `zmm25 = Simdreg (word 25) Full_512` and zmm26 = define `zmm26 = Simdreg (word 26) Full_512` and zmm27 = define `zmm27 = Simdreg (word 27) Full_512` and zmm28 = define `zmm28 = Simdreg (word 28) Full_512` and zmm29 = define `zmm29 = Simdreg (word 29) Full_512` and zmm30 = define `zmm30 = Simdreg (word 30) Full_512` and zmm31 = define `zmm31 = Simdreg (word 31) Full_512`;; let opmaskreg_INDUCT,opmaskreg_RECURSION = define_type "opmaskreg = Opmaskreg (3 word)";; let kmask0 = define `kmask0 = Opmaskreg (word 0)`;; let kmask1 = define `kmask1 = Opmaskreg (word 1)`;; let kmask2 = define `kmask2 = Opmaskreg (word 2)`;; let kmask3 = define `kmask3 = Opmaskreg (word 3)`;; let kmask4 = define `kmask4 = Opmaskreg (word 4)`;; let kmask5 = define `kmask5 = Opmaskreg (word 5)`;; let kmask6 = define `kmask6 = Opmaskreg (word 6)`;; let kmask7 = define `kmask7 = Opmaskreg (word 7)`;; (* ------------------------------------------------------------------------- *) (* Condition codes for conditional operations. *) (* ------------------------------------------------------------------------- *) * * We leave out Condition_CXZ and Condition_ECXZ for now * * let condition_INDUCTION,condition_RECURSION = define_type "condition = Unconditional | Condition_B // JB, JNAE, JC | Condition_BE // JBE, JNA | Condition_L // JL, JNGE | Condition_LE // JLE, JNG | Condition_NB // JNB, JAE, JNC | Condition_NBE // JA, JNBE | Condition_NL // JGE, JNL | Condition_NLE // JG, JNLE | Condition_NO // JNO | Condition_NP // JNP, JPO | Condition_NS // JNS | Condition_NZ // JNE, JNZ | Condition_O // JO | Condition_P // JP, JPE | Condition_S // JS | Condition_Z // JE, JZ ";; (* ------------------------------------------------------------------------- *) The basic BSID is base + index<<scale + displacement . (* We also allow RIP-relative addressing, using a separate constructor. *) In all cases the displacement is a 64 - bit word ; the shorter ones actually (* in the various encodings can be sign-extended. *) (* ------------------------------------------------------------------------- *) let bsid_INDUCTION,bsid_RECURSION = define_type "bsid = Bsid (gpr option) (gpr option) (2 word) (64 word) | Riprel (64 word)";; (* ------------------------------------------------------------------------- *) (* Operands. *) (* ------------------------------------------------------------------------- *) let operand_INDUCTION,operand_RECURSION = define_type "operand = Register gpr | Simdregister simdreg | Imm8 (8 word) | Imm16 (16 word) | Imm32 (32 word) | Imm64 (64 word) | Memop wordsize bsid";; (* ------------------------------------------------------------------------- *) (* Instructions. *) (* ------------------------------------------------------------------------- *) * * We call " STC " " STCF " to avoid clashing with symmetric closure of relation * * * The " DIV " have numeric suffixes anyway to express implicit operands . * * *** The "DIV" have numeric suffixes anyway to express implicit operands. ***) let instruction_INDUCTION,instruction_RECURSION = define_type "instruction = ADC operand operand | ADCX operand operand | ADD operand operand | ADOX operand operand | AND operand operand | BSF operand operand | BSR operand operand | BSWAP operand | BT operand operand | BTC operand operand | BTR operand operand | BTS operand operand | CALL operand | CALL_ABSOLUTE (64 word) | CLC | CMC | CMOV condition operand operand | CMP operand operand | DEC operand | DIV2 (operand#operand) (operand#operand) operand | IMUL3 operand (operand#operand) | IMUL2 (operand#operand) operand | INC operand | JUMP condition operand | LEA operand bsid | LZCNT operand operand | MOV operand operand | MOVSX operand operand | MOVZX operand operand | MUL2 (operand#operand) operand | MULX4 (operand#operand) (operand#operand) | NEG operand | NOP | NOT operand | OR operand operand | POP operand | PUSH operand | RCL operand operand | RCR operand operand | RET | ROL operand operand | ROR operand operand | SAR operand operand | SBB operand operand | SET condition operand | SHL operand operand | SHR operand operand | SHLD operand operand operand | SHRD operand operand operand | STCF | SUB operand operand | TEST operand operand | TZCNT operand operand | XOR operand operand";; (* ------------------------------------------------------------------------- *) (* Some shorthands for addressing modes etc. *) (* ------------------------------------------------------------------------- *) override_interface("%",`Register`);; let base_displacement = define `%%(r,d) = Bsid (SOME r) NONE (word 0) (word d)` and base_scaled_index = define `%%%(r,s,i) = Bsid (SOME r) (SOME i) (word s) (word 0)` and base_scaled_index_displacement = define `%%%%(r,s,i,d) = Bsid (SOME r) (SOME i) (word s) (iword d)` and simple_immediate = define `## n = Imm32(word n)`;; let QWORD = define `QWORD = Memop Quadword`;; (* ------------------------------------------------------------------------- *) (* Instruction shorthands specific to my setup *) (* ------------------------------------------------------------------------- *) let IMUL = new_definition `IMUL dest src = IMUL3 dest (dest,src)`;; let IMUL1 = new_definition `IMUL1 = IMUL2 (%rdx,%rax)`;; * * Note : these are for the 64 - bit versions only . Otherwise % r - > % e etc . * * * * Also we call DIV - > DIV1 to avoid a clash with built - in constants * * (*** Should probably have some systematic short prefix for all these ***) let MUL = define `MUL = MUL2 (%rdx,%rax)`;; let MULX = define `MULX hidest lodest exsrc = MULX4 (hidest,lodest) (%rdx,exsrc)`;; let DIV1 = define `DIV1 = DIV2 (%rax,%rdx) (%rdx,%rax)`;; (* ------------------------------------------------------------------------- *) (* Standard opcodes for conditional combinations (not unique, i.e. there are *) (* often multiple ways of getting the same instruction). *) (* ------------------------------------------------------------------------- *) let CMOVB = define `CMOVB = CMOV Condition_B`;; let CMOVNAE = define `CMOVNAE = CMOV Condition_B`;; let CMOVC = define `CMOVC = CMOV Condition_B`;; let CMOVBE = define `CMOVBE = CMOV Condition_BE`;; let CMOVNA = define `CMOVNA = CMOV Condition_BE`;; let CMOVL = define `CMOVL = CMOV Condition_L`;; let CMOVNGE = define `CMOVNGE = CMOV Condition_L`;; let CMOVLE = define `CMOVLE = CMOV Condition_LE`;; let CMOVNG = define `CMOVNG = CMOV Condition_LE`;; let CMOVNB = define `CMOVNB = CMOV Condition_NB`;; let CMOVAE = define `CMOVAE = CMOV Condition_NB`;; let CMOVNC = define `CMOVNC = CMOV Condition_NB`;; let CMOVA = define `CMOVA = CMOV Condition_NBE`;; let CMOVNBE = define `CMOVNBE = CMOV Condition_NBE`;; let CMOVGE = define `CMOVGE = CMOV Condition_NL`;; let CMOVNL = define `CMOVNL = CMOV Condition_NL`;; let CMOVG = define `CMOVG = CMOV Condition_NLE`;; let CMOVNLE = define `CMOVNLE = CMOV Condition_NLE`;; let CMOVNO = define `CMOVNO = CMOV Condition_NO`;; let CMOVNP = define `CMOVNP = CMOV Condition_NP`;; let CMOVPO = define `CMOVPO = CMOV Condition_NP`;; let CMOVNS = define `CMOVNS = CMOV Condition_NS`;; let CMOVNE = define `CMOVNE = CMOV Condition_NZ`;; let CMOVNZ = define `CMOVNZ = CMOV Condition_NZ`;; let CMOVO = define `CMOVO = CMOV Condition_O`;; let CMOVP = define `CMOVP = CMOV Condition_P`;; let CMOVPE = define `CMOVPE = CMOV Condition_P`;; let CMOVS = define `CMOVS = CMOV Condition_S`;; let CMOVE = define `CMOVE = CMOV Condition_Z`;; let CMOVZ = define `CMOVZ = CMOV Condition_Z`;; let JMP = define `JMP = JUMP Unconditional`;; let JB = define `JB = JUMP Condition_B`;; let JNAE = define `JNAE = JUMP Condition_B`;; let JC = define `JC = JUMP Condition_B`;; let JBE = define `JBE = JUMP Condition_BE`;; let JNA = define `JNA = JUMP Condition_BE`;; let JL = define `JL = JUMP Condition_L`;; let JNGE = define `JNGE = JUMP Condition_L`;; let JLE = define `JLE = JUMP Condition_LE`;; let JNG = define `JNG = JUMP Condition_LE`;; let JNB = define `JNB = JUMP Condition_NB`;; let JAE = define `JAE = JUMP Condition_NB`;; let JNC = define `JNC = JUMP Condition_NB`;; let JA = define `JA = JUMP Condition_NBE`;; let JNBE = define `JNBE = JUMP Condition_NBE`;; let JGE = define `JGE = JUMP Condition_NL`;; let JNL = define `JNL = JUMP Condition_NL`;; let JG = define `JG = JUMP Condition_NLE`;; let JNLE = define `JNLE = JUMP Condition_NLE`;; let JNO = define `JNO = JUMP Condition_NO`;; let JNP = define `JNP = JUMP Condition_NP`;; let JPO = define `JPO = JUMP Condition_NP`;; let JNS = define `JNS = JUMP Condition_NS`;; let JNE = define `JNE = JUMP Condition_NZ`;; let JNZ = define `JNZ = JUMP Condition_NZ`;; let JO = define `JO = JUMP Condition_O`;; let JP = define `JP = JUMP Condition_P`;; let JPE = define `JPE = JUMP Condition_P`;; let JS = define `JS = JUMP Condition_S`;; let JE = define `JE = JUMP Condition_Z`;; let JZ = define `JZ = JUMP Condition_Z`;; let SETB = define `SETB = SET Condition_B`;; let SETNAE = define `SETNAE = SET Condition_B`;; let SETC = define `SETC = SET Condition_B`;; let SETBE = define `SETBE = SET Condition_BE`;; let SETNA = define `SETNA = SET Condition_BE`;; let SETL = define `SETL = SET Condition_L`;; let SETNGE = define `SETNGE = SET Condition_L`;; let SETLE = define `SETLE = SET Condition_LE`;; let SETNG = define `SETNG = SET Condition_LE`;; let SETNB = define `SETNB = SET Condition_NB`;; let SETAE = define `SETAE = SET Condition_NB`;; let SETNC = define `SETNC = SET Condition_NB`;; let SETA = define `SETA = SET Condition_NBE`;; let SETNBE = define `SETNBE = SET Condition_NBE`;; let SETGE = define `SETGE = SET Condition_NL`;; let SETNL = define `SETNL = SET Condition_NL`;; let SETG = define `SETG = SET Condition_NLE`;; let SETNLE = define `SETNLE = SET Condition_NLE`;; let SETNO = define `SETNO = SET Condition_NO`;; let SETNP = define `SETNP = SET Condition_NP`;; let SETPO = define `SETPO = SET Condition_NP`;; let SETNS = define `SETNS = SET Condition_NS`;; let SETNE = define `SETNE = SET Condition_NZ`;; let SETNZ = define `SETNZ = SET Condition_NZ`;; let SETO = define `SETO = SET Condition_O`;; let SETP = define `SETP = SET Condition_P`;; let SETPE = define `SETPE = SET Condition_P`;; let SETS = define `SETS = SET Condition_S`;; let SETE = define `SETE = SET Condition_Z`;; let SETZ = define `SETZ = SET Condition_Z`;; let X86_INSTRUCTION_ALIASES = [CMOVB; CMOVNAE; CMOVC; CMOVBE; CMOVNA; CMOVL; CMOVNGE; CMOVLE; CMOVNG; CMOVNB; CMOVAE; CMOVNC; CMOVA; CMOVNBE; CMOVGE; CMOVNL; CMOVG; CMOVNLE; CMOVNO; CMOVNP; CMOVPO; CMOVNS; CMOVNE; CMOVNZ; CMOVO; CMOVP; CMOVPE; CMOVS; CMOVE; CMOVZ; JMP; JB; JNAE; JC; JBE; JNA; JL; JNGE; JLE; JNG; JNB; JAE; JNC; JA; JNBE; JGE; JNL; JG; JNLE; JNO; JNP; JPO; JNS; JNE; JNZ; JO; JP; JPE; JS; JE; JZ; SETB; SETNAE; SETC; SETBE; SETNA; SETL; SETNGE; SETLE; SETNG; SETNB; SETAE; SETNC; SETA; SETNBE; SETGE; SETNL; SETG; SETNLE; SETNO; SETNP; SETPO; SETNS; SETNE; SETNZ; SETO; SETP; SETPE; SETS; SETE; SETZ; IMUL; IMUL1; MUL; MULX; DIV1];;
null
https://raw.githubusercontent.com/awslabs/s2n-bignum/01d5ee53066f8a4e820776505d21e4c1b9657637/x86/proofs/instruction.ml
ocaml
========================================================================= Simplified definition of x86 assembly instructions. ========================================================================= ------------------------------------------------------------------------- The general-purpose registers ------------------------------------------------------------------------- ** There are some not actually addressable ones here ** ** But it keeps things uniform to use this pattern ** ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- Condition codes for conditional operations. ------------------------------------------------------------------------- ------------------------------------------------------------------------- We also allow RIP-relative addressing, using a separate constructor. in the various encodings can be sign-extended. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Operands. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Instructions. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Some shorthands for addressing modes etc. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Instruction shorthands specific to my setup ------------------------------------------------------------------------- ** Should probably have some systematic short prefix for all these ** ------------------------------------------------------------------------- Standard opcodes for conditional combinations (not unique, i.e. there are often multiple ways of getting the same instruction). -------------------------------------------------------------------------
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved . * SPDX - License - Identifier : Apache-2.0 OR ISC * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 OR ISC *) let wordsize_INDUCT,wordsize_RECURSION = define_type "wordsize = Quadword | Doubleword | Word | Byte";; let regsize_INDUCT,regsize_RECURSION = define_type "regsize = Full_64 | Lower_32 | Lower_16 | Upper_8 | Lower_8";; let gpr_INDUCT,gpr_RECURSION = define_type "gpr = Gpr (4 word) regsize";; let rax = define `rax = Gpr (word 0) Full_64` and rcx = define `rcx = Gpr (word 1) Full_64` and rdx = define `rdx = Gpr (word 2) Full_64` and rbx = define `rbx = Gpr (word 3) Full_64` and rsp = define `rsp = Gpr (word 4) Full_64` and rbp = define `rbp = Gpr (word 5) Full_64` and rsi = define `rsi = Gpr (word 6) Full_64` and rdi = define `rdi = Gpr (word 7) Full_64` and r8 = define ` r8 = Gpr (word 8) Full_64` and r9 = define ` r9 = Gpr (word 9) Full_64` and r10 = define `r10 = Gpr (word 10) Full_64` and r11 = define `r11 = Gpr (word 11) Full_64` and r12 = define `r12 = Gpr (word 12) Full_64` and r13 = define `r13 = Gpr (word 13) Full_64` and r14 = define `r14 = Gpr (word 14) Full_64` and r15 = define `r15 = Gpr (word 15) Full_64`;; let eax = define ` eax = Gpr (word 0) Lower_32` and ecx = define ` ecx = Gpr (word 1) Lower_32` and edx = define ` edx = Gpr (word 2) Lower_32` and ebx = define ` ebx = Gpr (word 3) Lower_32` and esp = define ` esp = Gpr (word 4) Lower_32` and ebp = define ` ebp = Gpr (word 5) Lower_32` and esi = define ` esi = Gpr (word 6) Lower_32` and edi = define ` edi = Gpr (word 7) Lower_32` and r8d = define ` r8d = Gpr (word 8) Lower_32` and r9d = define ` r9d = Gpr (word 9) Lower_32` and r10d = define `r10d = Gpr (word 10) Lower_32` and r11d = define `r11d = Gpr (word 11) Lower_32` and r12d = define `r12d = Gpr (word 12) Lower_32` and r13d = define `r13d = Gpr (word 13) Lower_32` and r14d = define `r14d = Gpr (word 14) Lower_32` and r15d = define `r15d = Gpr (word 15) Lower_32` and ax = define `ax = Gpr (word 0) Lower_16` and cx = define `cx = Gpr (word 1) Lower_16` and dx = define `dx = Gpr (word 2) Lower_16` and bx = define `bx = Gpr (word 3) Lower_16` and sp = define `sp = Gpr (word 4) Lower_16` and bp = define `bp = Gpr (word 5) Lower_16` and si = define `si = Gpr (word 6) Lower_16` and di = define `di = Gpr (word 7) Lower_16`;; let ah = define `ah = Gpr (word 0) Upper_8` and al = define `al = Gpr (word 0) Lower_8` and ch = define `ch = Gpr (word 1) Upper_8` and cl = define `cl = Gpr (word 1) Lower_8` and dh = define `dh = Gpr (word 2) Upper_8` and dl = define `dl = Gpr (word 2) Lower_8` and bh = define `bh = Gpr (word 3) Upper_8` and bl = define `bl = Gpr (word 3) Lower_8` and spl = define `spl = Gpr (word 4) Lower_8` and bpl = define `bpl = Gpr (word 5) Lower_8` and sil = define `sil = Gpr (word 6) Lower_8` and dil = define `dil = Gpr (word 7) Lower_8`;; XMM / YMM / ZMM registers and opmask registers . let simdregsize_INDUCT,simdregsize_RECURSION = define_type "simdregsize = Full_512 | Lower_256 | Lower_128";; * * Again xmm / ymm are n't addressable for 16 .. 31 , but this is uniform * * let simdreg_INDUCT,simdreg_RECURSION = define_type "simdreg = Simdreg (5 word) simdregsize";; let xmm0 = define `xmm0 = Simdreg (word 0) Lower_128` and xmm1 = define `xmm1 = Simdreg (word 1) Lower_128` and xmm2 = define `xmm2 = Simdreg (word 2) Lower_128` and xmm3 = define `xmm3 = Simdreg (word 3) Lower_128` and xmm4 = define `xmm4 = Simdreg (word 4) Lower_128` and xmm5 = define `xmm5 = Simdreg (word 5) Lower_128` and xmm6 = define `xmm6 = Simdreg (word 6) Lower_128` and xmm7 = define `xmm7 = Simdreg (word 7) Lower_128` and xmm8 = define `xmm8 = Simdreg (word 8) Lower_128` and xmm9 = define `xmm9 = Simdreg (word 9) Lower_128` and xmm10 = define `xmm10 = Simdreg (word 10) Lower_128` and xmm11 = define `xmm11 = Simdreg (word 11) Lower_128` and xmm12 = define `xmm12 = Simdreg (word 12) Lower_128` and xmm13 = define `xmm13 = Simdreg (word 13) Lower_128` and xmm14 = define `xmm14 = Simdreg (word 14) Lower_128` and xmm15 = define `xmm15 = Simdreg (word 15) Lower_128`;; let ymm0 = define `ymm0 = Simdreg (word 0) Lower_256` and ymm1 = define `ymm1 = Simdreg (word 1) Lower_256` and ymm2 = define `ymm2 = Simdreg (word 2) Lower_256` and ymm3 = define `ymm3 = Simdreg (word 3) Lower_256` and ymm4 = define `ymm4 = Simdreg (word 4) Lower_256` and ymm5 = define `ymm5 = Simdreg (word 5) Lower_256` and ymm6 = define `ymm6 = Simdreg (word 6) Lower_256` and ymm7 = define `ymm7 = Simdreg (word 7) Lower_256` and ymm8 = define `ymm8 = Simdreg (word 8) Lower_256` and ymm9 = define `ymm9 = Simdreg (word 9) Lower_256` and ymm10 = define `ymm10 = Simdreg (word 10) Lower_256` and ymm11 = define `ymm11 = Simdreg (word 11) Lower_256` and ymm12 = define `ymm12 = Simdreg (word 12) Lower_256` and ymm13 = define `ymm13 = Simdreg (word 13) Lower_256` and ymm14 = define `ymm14 = Simdreg (word 14) Lower_256` and ymm15 = define `ymm15 = Simdreg (word 15) Lower_256`;; let zmm0 = define `zmm0 = Simdreg (word 0) Full_512` and zmm1 = define `zmm1 = Simdreg (word 1) Full_512` and zmm2 = define `zmm2 = Simdreg (word 2) Full_512` and zmm3 = define `zmm3 = Simdreg (word 3) Full_512` and zmm4 = define `zmm4 = Simdreg (word 4) Full_512` and zmm5 = define `zmm5 = Simdreg (word 5) Full_512` and zmm6 = define `zmm6 = Simdreg (word 6) Full_512` and zmm7 = define `zmm7 = Simdreg (word 7) Full_512` and zmm8 = define `zmm8 = Simdreg (word 8) Full_512` and zmm9 = define `zmm9 = Simdreg (word 9) Full_512` and zmm10 = define `zmm10 = Simdreg (word 10) Full_512` and zmm11 = define `zmm11 = Simdreg (word 11) Full_512` and zmm12 = define `zmm12 = Simdreg (word 12) Full_512` and zmm13 = define `zmm13 = Simdreg (word 13) Full_512` and zmm14 = define `zmm14 = Simdreg (word 14) Full_512` and zmm15 = define `zmm15 = Simdreg (word 15) Full_512` and zmm16 = define `zmm16 = Simdreg (word 16) Full_512` and zmm17 = define `zmm17 = Simdreg (word 17) Full_512` and zmm18 = define `zmm18 = Simdreg (word 18) Full_512` and zmm19 = define `zmm19 = Simdreg (word 19) Full_512` and zmm20 = define `zmm20 = Simdreg (word 20) Full_512` and zmm21 = define `zmm21 = Simdreg (word 21) Full_512` and zmm22 = define `zmm22 = Simdreg (word 22) Full_512` and zmm23 = define `zmm23 = Simdreg (word 23) Full_512` and zmm24 = define `zmm24 = Simdreg (word 24) Full_512` and zmm25 = define `zmm25 = Simdreg (word 25) Full_512` and zmm26 = define `zmm26 = Simdreg (word 26) Full_512` and zmm27 = define `zmm27 = Simdreg (word 27) Full_512` and zmm28 = define `zmm28 = Simdreg (word 28) Full_512` and zmm29 = define `zmm29 = Simdreg (word 29) Full_512` and zmm30 = define `zmm30 = Simdreg (word 30) Full_512` and zmm31 = define `zmm31 = Simdreg (word 31) Full_512`;; let opmaskreg_INDUCT,opmaskreg_RECURSION = define_type "opmaskreg = Opmaskreg (3 word)";; let kmask0 = define `kmask0 = Opmaskreg (word 0)`;; let kmask1 = define `kmask1 = Opmaskreg (word 1)`;; let kmask2 = define `kmask2 = Opmaskreg (word 2)`;; let kmask3 = define `kmask3 = Opmaskreg (word 3)`;; let kmask4 = define `kmask4 = Opmaskreg (word 4)`;; let kmask5 = define `kmask5 = Opmaskreg (word 5)`;; let kmask6 = define `kmask6 = Opmaskreg (word 6)`;; let kmask7 = define `kmask7 = Opmaskreg (word 7)`;; * * We leave out Condition_CXZ and Condition_ECXZ for now * * let condition_INDUCTION,condition_RECURSION = define_type "condition = Unconditional | Condition_B // JB, JNAE, JC | Condition_BE // JBE, JNA | Condition_L // JL, JNGE | Condition_LE // JLE, JNG | Condition_NB // JNB, JAE, JNC | Condition_NBE // JA, JNBE | Condition_NL // JGE, JNL | Condition_NLE // JG, JNLE | Condition_NO // JNO | Condition_NP // JNP, JPO | Condition_NS // JNS | Condition_NZ // JNE, JNZ | Condition_O // JO | Condition_P // JP, JPE | Condition_S // JS | Condition_Z // JE, JZ ";; The basic BSID is base + index<<scale + displacement . In all cases the displacement is a 64 - bit word ; the shorter ones actually let bsid_INDUCTION,bsid_RECURSION = define_type "bsid = Bsid (gpr option) (gpr option) (2 word) (64 word) | Riprel (64 word)";; let operand_INDUCTION,operand_RECURSION = define_type "operand = Register gpr | Simdregister simdreg | Imm8 (8 word) | Imm16 (16 word) | Imm32 (32 word) | Imm64 (64 word) | Memop wordsize bsid";; * * We call " STC " " STCF " to avoid clashing with symmetric closure of relation * * * The " DIV " have numeric suffixes anyway to express implicit operands . * * *** The "DIV" have numeric suffixes anyway to express implicit operands. ***) let instruction_INDUCTION,instruction_RECURSION = define_type "instruction = ADC operand operand | ADCX operand operand | ADD operand operand | ADOX operand operand | AND operand operand | BSF operand operand | BSR operand operand | BSWAP operand | BT operand operand | BTC operand operand | BTR operand operand | BTS operand operand | CALL operand | CALL_ABSOLUTE (64 word) | CLC | CMC | CMOV condition operand operand | CMP operand operand | DEC operand | DIV2 (operand#operand) (operand#operand) operand | IMUL3 operand (operand#operand) | IMUL2 (operand#operand) operand | INC operand | JUMP condition operand | LEA operand bsid | LZCNT operand operand | MOV operand operand | MOVSX operand operand | MOVZX operand operand | MUL2 (operand#operand) operand | MULX4 (operand#operand) (operand#operand) | NEG operand | NOP | NOT operand | OR operand operand | POP operand | PUSH operand | RCL operand operand | RCR operand operand | RET | ROL operand operand | ROR operand operand | SAR operand operand | SBB operand operand | SET condition operand | SHL operand operand | SHR operand operand | SHLD operand operand operand | SHRD operand operand operand | STCF | SUB operand operand | TEST operand operand | TZCNT operand operand | XOR operand operand";; override_interface("%",`Register`);; let base_displacement = define `%%(r,d) = Bsid (SOME r) NONE (word 0) (word d)` and base_scaled_index = define `%%%(r,s,i) = Bsid (SOME r) (SOME i) (word s) (word 0)` and base_scaled_index_displacement = define `%%%%(r,s,i,d) = Bsid (SOME r) (SOME i) (word s) (iword d)` and simple_immediate = define `## n = Imm32(word n)`;; let QWORD = define `QWORD = Memop Quadword`;; let IMUL = new_definition `IMUL dest src = IMUL3 dest (dest,src)`;; let IMUL1 = new_definition `IMUL1 = IMUL2 (%rdx,%rax)`;; * * Note : these are for the 64 - bit versions only . Otherwise % r - > % e etc . * * * * Also we call DIV - > DIV1 to avoid a clash with built - in constants * * let MUL = define `MUL = MUL2 (%rdx,%rax)`;; let MULX = define `MULX hidest lodest exsrc = MULX4 (hidest,lodest) (%rdx,exsrc)`;; let DIV1 = define `DIV1 = DIV2 (%rax,%rdx) (%rdx,%rax)`;; let CMOVB = define `CMOVB = CMOV Condition_B`;; let CMOVNAE = define `CMOVNAE = CMOV Condition_B`;; let CMOVC = define `CMOVC = CMOV Condition_B`;; let CMOVBE = define `CMOVBE = CMOV Condition_BE`;; let CMOVNA = define `CMOVNA = CMOV Condition_BE`;; let CMOVL = define `CMOVL = CMOV Condition_L`;; let CMOVNGE = define `CMOVNGE = CMOV Condition_L`;; let CMOVLE = define `CMOVLE = CMOV Condition_LE`;; let CMOVNG = define `CMOVNG = CMOV Condition_LE`;; let CMOVNB = define `CMOVNB = CMOV Condition_NB`;; let CMOVAE = define `CMOVAE = CMOV Condition_NB`;; let CMOVNC = define `CMOVNC = CMOV Condition_NB`;; let CMOVA = define `CMOVA = CMOV Condition_NBE`;; let CMOVNBE = define `CMOVNBE = CMOV Condition_NBE`;; let CMOVGE = define `CMOVGE = CMOV Condition_NL`;; let CMOVNL = define `CMOVNL = CMOV Condition_NL`;; let CMOVG = define `CMOVG = CMOV Condition_NLE`;; let CMOVNLE = define `CMOVNLE = CMOV Condition_NLE`;; let CMOVNO = define `CMOVNO = CMOV Condition_NO`;; let CMOVNP = define `CMOVNP = CMOV Condition_NP`;; let CMOVPO = define `CMOVPO = CMOV Condition_NP`;; let CMOVNS = define `CMOVNS = CMOV Condition_NS`;; let CMOVNE = define `CMOVNE = CMOV Condition_NZ`;; let CMOVNZ = define `CMOVNZ = CMOV Condition_NZ`;; let CMOVO = define `CMOVO = CMOV Condition_O`;; let CMOVP = define `CMOVP = CMOV Condition_P`;; let CMOVPE = define `CMOVPE = CMOV Condition_P`;; let CMOVS = define `CMOVS = CMOV Condition_S`;; let CMOVE = define `CMOVE = CMOV Condition_Z`;; let CMOVZ = define `CMOVZ = CMOV Condition_Z`;; let JMP = define `JMP = JUMP Unconditional`;; let JB = define `JB = JUMP Condition_B`;; let JNAE = define `JNAE = JUMP Condition_B`;; let JC = define `JC = JUMP Condition_B`;; let JBE = define `JBE = JUMP Condition_BE`;; let JNA = define `JNA = JUMP Condition_BE`;; let JL = define `JL = JUMP Condition_L`;; let JNGE = define `JNGE = JUMP Condition_L`;; let JLE = define `JLE = JUMP Condition_LE`;; let JNG = define `JNG = JUMP Condition_LE`;; let JNB = define `JNB = JUMP Condition_NB`;; let JAE = define `JAE = JUMP Condition_NB`;; let JNC = define `JNC = JUMP Condition_NB`;; let JA = define `JA = JUMP Condition_NBE`;; let JNBE = define `JNBE = JUMP Condition_NBE`;; let JGE = define `JGE = JUMP Condition_NL`;; let JNL = define `JNL = JUMP Condition_NL`;; let JG = define `JG = JUMP Condition_NLE`;; let JNLE = define `JNLE = JUMP Condition_NLE`;; let JNO = define `JNO = JUMP Condition_NO`;; let JNP = define `JNP = JUMP Condition_NP`;; let JPO = define `JPO = JUMP Condition_NP`;; let JNS = define `JNS = JUMP Condition_NS`;; let JNE = define `JNE = JUMP Condition_NZ`;; let JNZ = define `JNZ = JUMP Condition_NZ`;; let JO = define `JO = JUMP Condition_O`;; let JP = define `JP = JUMP Condition_P`;; let JPE = define `JPE = JUMP Condition_P`;; let JS = define `JS = JUMP Condition_S`;; let JE = define `JE = JUMP Condition_Z`;; let JZ = define `JZ = JUMP Condition_Z`;; let SETB = define `SETB = SET Condition_B`;; let SETNAE = define `SETNAE = SET Condition_B`;; let SETC = define `SETC = SET Condition_B`;; let SETBE = define `SETBE = SET Condition_BE`;; let SETNA = define `SETNA = SET Condition_BE`;; let SETL = define `SETL = SET Condition_L`;; let SETNGE = define `SETNGE = SET Condition_L`;; let SETLE = define `SETLE = SET Condition_LE`;; let SETNG = define `SETNG = SET Condition_LE`;; let SETNB = define `SETNB = SET Condition_NB`;; let SETAE = define `SETAE = SET Condition_NB`;; let SETNC = define `SETNC = SET Condition_NB`;; let SETA = define `SETA = SET Condition_NBE`;; let SETNBE = define `SETNBE = SET Condition_NBE`;; let SETGE = define `SETGE = SET Condition_NL`;; let SETNL = define `SETNL = SET Condition_NL`;; let SETG = define `SETG = SET Condition_NLE`;; let SETNLE = define `SETNLE = SET Condition_NLE`;; let SETNO = define `SETNO = SET Condition_NO`;; let SETNP = define `SETNP = SET Condition_NP`;; let SETPO = define `SETPO = SET Condition_NP`;; let SETNS = define `SETNS = SET Condition_NS`;; let SETNE = define `SETNE = SET Condition_NZ`;; let SETNZ = define `SETNZ = SET Condition_NZ`;; let SETO = define `SETO = SET Condition_O`;; let SETP = define `SETP = SET Condition_P`;; let SETPE = define `SETPE = SET Condition_P`;; let SETS = define `SETS = SET Condition_S`;; let SETE = define `SETE = SET Condition_Z`;; let SETZ = define `SETZ = SET Condition_Z`;; let X86_INSTRUCTION_ALIASES = [CMOVB; CMOVNAE; CMOVC; CMOVBE; CMOVNA; CMOVL; CMOVNGE; CMOVLE; CMOVNG; CMOVNB; CMOVAE; CMOVNC; CMOVA; CMOVNBE; CMOVGE; CMOVNL; CMOVG; CMOVNLE; CMOVNO; CMOVNP; CMOVPO; CMOVNS; CMOVNE; CMOVNZ; CMOVO; CMOVP; CMOVPE; CMOVS; CMOVE; CMOVZ; JMP; JB; JNAE; JC; JBE; JNA; JL; JNGE; JLE; JNG; JNB; JAE; JNC; JA; JNBE; JGE; JNL; JG; JNLE; JNO; JNP; JPO; JNS; JNE; JNZ; JO; JP; JPE; JS; JE; JZ; SETB; SETNAE; SETC; SETBE; SETNA; SETL; SETNGE; SETLE; SETNG; SETNB; SETAE; SETNC; SETA; SETNBE; SETGE; SETNL; SETG; SETNLE; SETNO; SETNP; SETPO; SETNS; SETNE; SETNZ; SETO; SETP; SETPE; SETS; SETE; SETZ; IMUL; IMUL1; MUL; MULX; DIV1];;
26bd01b223389885c351655b9ffe47972174962a41fb123d140a4e994967a234
biocad/math-grads
CyclesPathsAlignment.hs
-- | Module that is responsible for linking systems of conjugated cycles in graph -- with paths between them. -- module Math.Grads.Drawing.Internal.CyclesPathsAlignment ( alignCyclesAndPaths , bondsToAlignTo , bondsToAlignToExtreme ) where import Control.Arrow (first, second, (***)) import Data.Either (partitionEithers) import Data.List (find) import Data.Maybe (catMaybes, listToMaybe) import Linear.Matrix ((!*)) import Linear.Metric (dot, norm) import Linear.V2 (V2 (..)) import Linear.Vector (negated, (*^)) import Math.Grads.Algo.Paths (findBeginnings) import Math.Grads.Angem (alignmentFunc, rotation2D) import Math.Grads.Drawing.Internal.Coords (bondLength) import Math.Grads.Drawing.Internal.Utils (Coord, CoordList, cleanCoordList, tupleToList) import Math.Grads.Graph (EdgeList) type CoordsEnds e = (CoordList e, EdgeList e) | Given cycles and paths between them unites everything into one structure if possible . -- alignCyclesAndPaths :: Eq e => [CoordList e] -> [CoordList e] -> Maybe (CoordList e) alignCyclesAndPaths paths cycles = greedyAlignmentOfCyclesAndPaths (cyclesWithRestoredEnds ++ pathsWithRestoredEnds) where cyclesWithRestoredEnds = fmap linksForCycle cycles pathsWithRestoredEnds = fmap linksForPath paths linksForCycle :: CoordList e -> (CoordList e, EdgeList e) linksForCycle thisCycle = (thisCycle, findBondsToFind (fmap fst thisCycle)) linksForPath :: CoordList e -> (CoordList e, EdgeList e) linksForPath thisPath = (thisPath, helper' (fmap fst thisPath)) helper' :: EdgeList e -> EdgeList e helper' pathBondList = if length pathBondList == 1 then pathBondList else findBondsToFind pathBondList greedyAlignmentOfCyclesAndPaths :: Eq e => [(CoordList e, EdgeList e)] -> Maybe (CoordList e) greedyAlignmentOfCyclesAndPaths [] = Nothing greedyAlignmentOfCyclesAndPaths [x] = Just (fst x) greedyAlignmentOfCyclesAndPaths (thisPart : otherParts) = if not (null toAdd) then res else Nothing where theseCoords = fst thisPart bondsToFind = snd thisPart alignedNeighbors = fmap (detectAndAlignNeighbors bondsToFind theseCoords) otherParts (toAdd, leftParts) = first concat (partitionEithers alignedNeighbors) newTheseCoords = cleanCoordList (toAdd ++ theseCoords) [] edgeList = fmap fst newTheseCoords newBondsToFind = findBondsToFind edgeList res = greedyAlignmentOfCyclesAndPaths ((newTheseCoords, newBondsToFind) : leftParts) detectAndAlignNeighbors :: Eq e => EdgeList e -> CoordList e -> CoordsEnds e -> Either (CoordList e) (CoordsEnds e) detectAndAlignNeighbors bondsToFind theseCoords theseCoordsEnds = maybe (Right theseCoordsEnds) Left neighsOrLeft where neighsOrLeft = detectAndAlignNeighborsM bondsToFind theseCoords theseCoordsEnds detectAndAlignNeighborsM :: Eq e => EdgeList e -> CoordList e -> CoordsEnds e -> Maybe (CoordList e) detectAndAlignNeighborsM bondsToFind theseCoords (coords, ends) = do let found' = catMaybes (fmap (\x -> find (== x) bondsToFind) ends) found <- listToMaybe found' let findBondToAlign = find (\(a, _) -> a == found) alignCoords <- coordToList <$> findBondToAlign theseCoords toAlignCoords <- coordToList <$> findBondToAlign coords let alignFunc = alignmentFunc alignCoords toAlignCoords Just (fmap (second (alignFunc *** alignFunc)) coords) where coordToList :: Coord e -> [V2 Float] coordToList = tupleToList . snd findBondsToFind :: EdgeList e -> EdgeList e findBondsToFind bonds = catMaybes ((\ind -> find (\(a, b, _) -> a == ind || b == ind) bonds) <$> findBeginnings bonds) -- | Constructs edge that will be used to align to cycle containing given 'Coord's. -- bondsToAlignTo :: Coord e -> Coord e -> Int -> [(V2 Float, V2 Float)] bondsToAlignTo ((a, b, _), (pointA, pointB)) ((a', b', _), (pointA', pointB')) number = resultingVectors where coordA = pointB - pointA coordB = pointB' - pointA' ((vecA, vecB), linkingPoint) | a == a' = ((negated coordA, negated coordB), pointA) | a == b' = ((negated coordA, coordB), pointA) | b == a' = ((coordA, negated coordB), pointB) | otherwise = ((coordA, coordB), pointB) direction' = vecA + vecB direction = (bondLength / norm direction') *^ direction' toTopAngle = (180.0 - 180.0 * acos (dot vecA vecB / (norm vecA * norm vecB)) / pi) / 2.0 angle' = 180.0 / fromIntegral number startingAngle = (180.0 - (fromIntegral number - 1.0) * angle') / 2.0 dirA = dot (start (toTopAngle + startingAngle)) direction dirB = dot (start (-(toTopAngle + startingAngle))) direction startingPoint | dirA >= 0 && dirB >= 0 && dirA > dirB = start (toTopAngle + startingAngle) | dirA >= 0 && dirB >= 0 = start (-(toTopAngle + startingAngle)) | dirA >= 0 = start (toTopAngle + startingAngle) | otherwise = start (-(toTopAngle + startingAngle)) mult = if dot (start (toTopAngle + startingAngle)) direction > 0 then 1 else (-1) resultingVectors = (\x -> (linkingPoint, linkingPoint + x)) <$> getDirections startingPoint 1 angle' number mult start :: Float -> V2 Float start angle = rotation2D angle !* ((bondLength / norm vecA) *^ negated vecA) -- | If we have complicated situation where we need to calculate bonds to align to for vertex in cycle that has more then 2 neighbors then we pass direction in which we want to place neighbors and use bondsToAlignToExtreme function . -- Otherwise we use bondsToAlignTo function. -- bondsToAlignToExtreme :: (V2 Float, V2 Float) -> Int -> [(V2 Float, V2 Float)] bondsToAlignToExtreme (beg, end) number = resultingVectors where direction = end - beg startingPointComplicated = rotation2D (-40.0) !* ((bondLength / norm direction) *^ direction) resultingVectors = (\x -> (beg, beg + x)) <$> getDirections startingPointComplicated 1 47.0 number 1 getDirections :: V2 Float -> Int -> Float -> Int -> Float -> [V2 Float] getDirections prev counter angle number mult = if counter < number then prev : getDirections new (counter + 1) angle number mult else [prev] where new = rotation2D (mult * angle) !* prev
null
https://raw.githubusercontent.com/biocad/math-grads/df7bdc48f86f57f3d011991c64188489e8d73bc1/src/Math/Grads/Drawing/Internal/CyclesPathsAlignment.hs
haskell
| Module that is responsible for linking systems of conjugated cycles in graph with paths between them. | Constructs edge that will be used to align to cycle containing given 'Coord's. | If we have complicated situation where we need to calculate bonds to align to Otherwise we use bondsToAlignTo function.
module Math.Grads.Drawing.Internal.CyclesPathsAlignment ( alignCyclesAndPaths , bondsToAlignTo , bondsToAlignToExtreme ) where import Control.Arrow (first, second, (***)) import Data.Either (partitionEithers) import Data.List (find) import Data.Maybe (catMaybes, listToMaybe) import Linear.Matrix ((!*)) import Linear.Metric (dot, norm) import Linear.V2 (V2 (..)) import Linear.Vector (negated, (*^)) import Math.Grads.Algo.Paths (findBeginnings) import Math.Grads.Angem (alignmentFunc, rotation2D) import Math.Grads.Drawing.Internal.Coords (bondLength) import Math.Grads.Drawing.Internal.Utils (Coord, CoordList, cleanCoordList, tupleToList) import Math.Grads.Graph (EdgeList) type CoordsEnds e = (CoordList e, EdgeList e) | Given cycles and paths between them unites everything into one structure if possible . alignCyclesAndPaths :: Eq e => [CoordList e] -> [CoordList e] -> Maybe (CoordList e) alignCyclesAndPaths paths cycles = greedyAlignmentOfCyclesAndPaths (cyclesWithRestoredEnds ++ pathsWithRestoredEnds) where cyclesWithRestoredEnds = fmap linksForCycle cycles pathsWithRestoredEnds = fmap linksForPath paths linksForCycle :: CoordList e -> (CoordList e, EdgeList e) linksForCycle thisCycle = (thisCycle, findBondsToFind (fmap fst thisCycle)) linksForPath :: CoordList e -> (CoordList e, EdgeList e) linksForPath thisPath = (thisPath, helper' (fmap fst thisPath)) helper' :: EdgeList e -> EdgeList e helper' pathBondList = if length pathBondList == 1 then pathBondList else findBondsToFind pathBondList greedyAlignmentOfCyclesAndPaths :: Eq e => [(CoordList e, EdgeList e)] -> Maybe (CoordList e) greedyAlignmentOfCyclesAndPaths [] = Nothing greedyAlignmentOfCyclesAndPaths [x] = Just (fst x) greedyAlignmentOfCyclesAndPaths (thisPart : otherParts) = if not (null toAdd) then res else Nothing where theseCoords = fst thisPart bondsToFind = snd thisPart alignedNeighbors = fmap (detectAndAlignNeighbors bondsToFind theseCoords) otherParts (toAdd, leftParts) = first concat (partitionEithers alignedNeighbors) newTheseCoords = cleanCoordList (toAdd ++ theseCoords) [] edgeList = fmap fst newTheseCoords newBondsToFind = findBondsToFind edgeList res = greedyAlignmentOfCyclesAndPaths ((newTheseCoords, newBondsToFind) : leftParts) detectAndAlignNeighbors :: Eq e => EdgeList e -> CoordList e -> CoordsEnds e -> Either (CoordList e) (CoordsEnds e) detectAndAlignNeighbors bondsToFind theseCoords theseCoordsEnds = maybe (Right theseCoordsEnds) Left neighsOrLeft where neighsOrLeft = detectAndAlignNeighborsM bondsToFind theseCoords theseCoordsEnds detectAndAlignNeighborsM :: Eq e => EdgeList e -> CoordList e -> CoordsEnds e -> Maybe (CoordList e) detectAndAlignNeighborsM bondsToFind theseCoords (coords, ends) = do let found' = catMaybes (fmap (\x -> find (== x) bondsToFind) ends) found <- listToMaybe found' let findBondToAlign = find (\(a, _) -> a == found) alignCoords <- coordToList <$> findBondToAlign theseCoords toAlignCoords <- coordToList <$> findBondToAlign coords let alignFunc = alignmentFunc alignCoords toAlignCoords Just (fmap (second (alignFunc *** alignFunc)) coords) where coordToList :: Coord e -> [V2 Float] coordToList = tupleToList . snd findBondsToFind :: EdgeList e -> EdgeList e findBondsToFind bonds = catMaybes ((\ind -> find (\(a, b, _) -> a == ind || b == ind) bonds) <$> findBeginnings bonds) bondsToAlignTo :: Coord e -> Coord e -> Int -> [(V2 Float, V2 Float)] bondsToAlignTo ((a, b, _), (pointA, pointB)) ((a', b', _), (pointA', pointB')) number = resultingVectors where coordA = pointB - pointA coordB = pointB' - pointA' ((vecA, vecB), linkingPoint) | a == a' = ((negated coordA, negated coordB), pointA) | a == b' = ((negated coordA, coordB), pointA) | b == a' = ((coordA, negated coordB), pointB) | otherwise = ((coordA, coordB), pointB) direction' = vecA + vecB direction = (bondLength / norm direction') *^ direction' toTopAngle = (180.0 - 180.0 * acos (dot vecA vecB / (norm vecA * norm vecB)) / pi) / 2.0 angle' = 180.0 / fromIntegral number startingAngle = (180.0 - (fromIntegral number - 1.0) * angle') / 2.0 dirA = dot (start (toTopAngle + startingAngle)) direction dirB = dot (start (-(toTopAngle + startingAngle))) direction startingPoint | dirA >= 0 && dirB >= 0 && dirA > dirB = start (toTopAngle + startingAngle) | dirA >= 0 && dirB >= 0 = start (-(toTopAngle + startingAngle)) | dirA >= 0 = start (toTopAngle + startingAngle) | otherwise = start (-(toTopAngle + startingAngle)) mult = if dot (start (toTopAngle + startingAngle)) direction > 0 then 1 else (-1) resultingVectors = (\x -> (linkingPoint, linkingPoint + x)) <$> getDirections startingPoint 1 angle' number mult start :: Float -> V2 Float start angle = rotation2D angle !* ((bondLength / norm vecA) *^ negated vecA) for vertex in cycle that has more then 2 neighbors then we pass direction in which we want to place neighbors and use bondsToAlignToExtreme function . bondsToAlignToExtreme :: (V2 Float, V2 Float) -> Int -> [(V2 Float, V2 Float)] bondsToAlignToExtreme (beg, end) number = resultingVectors where direction = end - beg startingPointComplicated = rotation2D (-40.0) !* ((bondLength / norm direction) *^ direction) resultingVectors = (\x -> (beg, beg + x)) <$> getDirections startingPointComplicated 1 47.0 number 1 getDirections :: V2 Float -> Int -> Float -> Int -> Float -> [V2 Float] getDirections prev counter angle number mult = if counter < number then prev : getDirections new (counter + 1) angle number mult else [prev] where new = rotation2D (mult * angle) !* prev
8ac6dfc55b408ae9fed92eb2eece8dbd8144f02d561e331c2a543b6e47f95cde
caribou/caribou-core
field_map.clj
(ns caribou.migrations.field-map (:require [caribou.config :as config] [caribou.model :as model])) (defn migrate [] (model/update :model (model/models :field :id) {:fields [{:name "Map" :type "boolean"}]})) (defn rollback [])
null
https://raw.githubusercontent.com/caribou/caribou-core/6ebd9db4e14cddb1d6b4e152e771e016fa9c55f6/src/caribou/migrations/field_map.clj
clojure
(ns caribou.migrations.field-map (:require [caribou.config :as config] [caribou.model :as model])) (defn migrate [] (model/update :model (model/models :field :id) {:fields [{:name "Map" :type "boolean"}]})) (defn rollback [])
145ffc7ddb43f778b6aa0ed44b691d10496e09abe22dc11cf320e3d051a2b179
riverford/durable-ref
nippy.clj
(ns riverford.durable-ref.format.nippy (:require [clojure.java.io :as io] [taoensso.nippy :as nippy] [riverford.durable-ref.core :as dref]) (:import (java.io ByteArrayOutputStream))) (defmethod dref/serialize "nippy" [obj _ opts] (nippy/freeze obj (-> opts :format :nippy :write-opts))) (defmethod dref/deserialize "nippy" [in _ opts] (let [out (ByteArrayOutputStream.)] (with-open [in (io/input-stream in)] (io/copy in out)) (nippy/thaw (.toByteArray out) (-> opts :format :nippy :read-opts))))
null
https://raw.githubusercontent.com/riverford/durable-ref/f18402c07549079fd3a1c8d2595f893a055851de/src/riverford/durable_ref/format/nippy.clj
clojure
(ns riverford.durable-ref.format.nippy (:require [clojure.java.io :as io] [taoensso.nippy :as nippy] [riverford.durable-ref.core :as dref]) (:import (java.io ByteArrayOutputStream))) (defmethod dref/serialize "nippy" [obj _ opts] (nippy/freeze obj (-> opts :format :nippy :write-opts))) (defmethod dref/deserialize "nippy" [in _ opts] (let [out (ByteArrayOutputStream.)] (with-open [in (io/input-stream in)] (io/copy in out)) (nippy/thaw (.toByteArray out) (-> opts :format :nippy :read-opts))))
ae6ce36715941dde62efc8552963075125c760c7fd231c2f5862cc99ce23fcf6
broadinstitute/wfl
tsv.clj
(ns wfl.tsv "Read and write Terra's tab-separated value (.tsv) files." (:refer-clojure :exclude [read]) (:require [clojure.data.csv :as csv] [clojure.data.json :as json] [clojure.edn :as edn] [clojure.java.io :as io]) (:import [java.io Reader StringReader StringWriter Writer])) (defprotocol TsvField "One field of a row or line in a .tsv file." (-write [field ^Writer out] "Write FIELD to java.io.Writer OUT as a .tsv value.")) (extend-protocol TsvField clojure.lang.Named (^:private -write [field out] (.write out (name field))) java.lang.Object (^:private -write [field out] (.write out (json/write-str field :escape-slash false))) java.lang.String (^:private -write [field out] (.write out field))) BUG : Do not quote or escape \tab or \newline . ;; (defn ^:private write-fields "Write the sequence of .tsv FIELDS to WRITER." [fields ^Writer writer] (loop [fields fields separator ""] (when-first [field fields] (-write separator writer) (-write field writer) (recur (rest fields) "\t")))) (defn ^:private read-field "Guess what S is to avoid writing a full-blown scanner." [s] (case (first s) (\[ \{) (json/read-str s) (or (try (let [x (edn/read-string s)] (when (and (number? x) (= s (str x))) x)) (catch Throwable _ignored)) s))) ;; HACK: Post-process CSV to avoid writing a full-blown parser. ;; (defn read "Read a .tsv table, a sequence of sequences, from READER." [^Reader reader] (-> reader (csv/read-csv :separator \tab) (->> (map (partial map read-field))))) (defn read-str "Read a .tsv table, a sequence of sequences, from string S." [s] (read (StringReader. s))) (defn read-file "Return a lazy .tsv table from FILE." [file] (read (io/reader file))) (defn write "Write TABLE, a sequence of .tsv field sequences, to WRITER." [table ^Writer writer] (when-first [line table] (write-fields line writer) (.write writer "\n") (recur (rest table) writer))) (defn write-str "Return TABLE, a sequence of .tsv field sequences, in a string." [table] (let [writer (StringWriter.)] (write table writer) (str writer))) (defn write-file "Write TABLE, a sequence of .tsv field sequences, to FILE." [table file] (with-open [writer (io/writer file)] (write table writer))) (defn ^:private assert-mapulatable! "Throw when (mapulate TABLE) would lose information." [table] (letfn [(repeated? [[label n]] (when-not (== 1 n) label))] (let [repeats (keep repeated? (frequencies (first table)))] (when (seq repeats) (throw (ex-info "TABLE.tsv has repeated column labels." {:repeats repeats}))))) (let [counts (set (map count table))] (when-not (== 1 (count counts)) (throw (ex-info "TABLE.tsv has multiple column counts." {:counts counts}))))) (defn mapulate "Return a sequence of maps from TABLE, a sequence of sequences." [table] (assert-mapulatable! table) (let [[header & rows] table] (map (partial zipmap header) rows))) (defn ^:private assert-tabulatable! "Throw when (tabulate EDN) would lose information." [edn] (let [counts (set (map count edn))] (when-not (== 1 (count counts)) (throw (ex-info "TABLE.tsv has multiple column counts." {:counts counts}))))) (defn tabulate "Return a table, sequence of sequences, from EDN, a sequence of maps." [edn] (assert-tabulatable! edn) (let [header (keys (first edn))] (letfn [(extract [row] (map row header))] (cons header (map extract edn)))))
null
https://raw.githubusercontent.com/broadinstitute/wfl/a3b3fdff3d351270fcda3ec686f0be13d7c560a3/api/src/wfl/tsv.clj
clojure
HACK: Post-process CSV to avoid writing a full-blown parser.
(ns wfl.tsv "Read and write Terra's tab-separated value (.tsv) files." (:refer-clojure :exclude [read]) (:require [clojure.data.csv :as csv] [clojure.data.json :as json] [clojure.edn :as edn] [clojure.java.io :as io]) (:import [java.io Reader StringReader StringWriter Writer])) (defprotocol TsvField "One field of a row or line in a .tsv file." (-write [field ^Writer out] "Write FIELD to java.io.Writer OUT as a .tsv value.")) (extend-protocol TsvField clojure.lang.Named (^:private -write [field out] (.write out (name field))) java.lang.Object (^:private -write [field out] (.write out (json/write-str field :escape-slash false))) java.lang.String (^:private -write [field out] (.write out field))) BUG : Do not quote or escape \tab or \newline . (defn ^:private write-fields "Write the sequence of .tsv FIELDS to WRITER." [fields ^Writer writer] (loop [fields fields separator ""] (when-first [field fields] (-write separator writer) (-write field writer) (recur (rest fields) "\t")))) (defn ^:private read-field "Guess what S is to avoid writing a full-blown scanner." [s] (case (first s) (\[ \{) (json/read-str s) (or (try (let [x (edn/read-string s)] (when (and (number? x) (= s (str x))) x)) (catch Throwable _ignored)) s))) (defn read "Read a .tsv table, a sequence of sequences, from READER." [^Reader reader] (-> reader (csv/read-csv :separator \tab) (->> (map (partial map read-field))))) (defn read-str "Read a .tsv table, a sequence of sequences, from string S." [s] (read (StringReader. s))) (defn read-file "Return a lazy .tsv table from FILE." [file] (read (io/reader file))) (defn write "Write TABLE, a sequence of .tsv field sequences, to WRITER." [table ^Writer writer] (when-first [line table] (write-fields line writer) (.write writer "\n") (recur (rest table) writer))) (defn write-str "Return TABLE, a sequence of .tsv field sequences, in a string." [table] (let [writer (StringWriter.)] (write table writer) (str writer))) (defn write-file "Write TABLE, a sequence of .tsv field sequences, to FILE." [table file] (with-open [writer (io/writer file)] (write table writer))) (defn ^:private assert-mapulatable! "Throw when (mapulate TABLE) would lose information." [table] (letfn [(repeated? [[label n]] (when-not (== 1 n) label))] (let [repeats (keep repeated? (frequencies (first table)))] (when (seq repeats) (throw (ex-info "TABLE.tsv has repeated column labels." {:repeats repeats}))))) (let [counts (set (map count table))] (when-not (== 1 (count counts)) (throw (ex-info "TABLE.tsv has multiple column counts." {:counts counts}))))) (defn mapulate "Return a sequence of maps from TABLE, a sequence of sequences." [table] (assert-mapulatable! table) (let [[header & rows] table] (map (partial zipmap header) rows))) (defn ^:private assert-tabulatable! "Throw when (tabulate EDN) would lose information." [edn] (let [counts (set (map count edn))] (when-not (== 1 (count counts)) (throw (ex-info "TABLE.tsv has multiple column counts." {:counts counts}))))) (defn tabulate "Return a table, sequence of sequences, from EDN, a sequence of maps." [edn] (assert-tabulatable! edn) (let [header (keys (first edn))] (letfn [(extract [row] (map row header))] (cons header (map extract edn)))))
553f831f507e9032f424cf85eb02623f432d16ee9a4910625542fc1a5536cb00
bobzhang/ocaml-book
grammar.ml
# require " camlp4.gramlib " ; ; open Camlp4.PreCast module MGram = MakeGram(Lexer) let test = MGram.Entry.mk "test" let p = MGram.Entry.print let _ = begin MGram.Entry.clear test; EXTEND MGram GLOBAL: test; test: ["add" LEFTA [SELF; "+" ; SELF | SELF; "-" ; SELF] | "mult" RIGHTA [SELF; "*" ; SELF | SELF; "/" ; SELF] | "simple" NONA [ "("; SELF; ")" | INT ] ]; END; p Format.std_formatter test; end (** output test: [ "add" LEFTA [ SELF; "+"; SELF | SELF; "-"; SELF ] | "mult" RIGHTA [ SELF; "*"; SELF | SELF; "/"; SELF ] | "simple" NONA [ "("; SELF; ")" | INT ((_)) ] ] *) let _ = begin EXTEND MGram GLOBAL: test; test: [[ x = SELF ; "plus1plus" ; y = SELF ]]; END ; p Format.std_formatter test end (** output test: [ "add" LEFTA [ SELF; "plus1plus"; SELF | SELF; "+"; SELF | SELF; "-"; SELF ] | "mult" RIGHTA [ SELF; "*"; SELF | SELF; "/"; SELF ] | "simple" NONA [ "("; SELF; ")" | INT ((_)) ] ] *) let _ = begin EXTEND MGram test: LAST [[x = SELF ; "plus1plus" ; y = SELF ]]; END; p Format.std_formatter test end (** output test: [ "add" LEFTA [ SELF; "plus1plus"; SELF | SELF; "+"; SELF | SELF; "-"; SELF ] | "mult" RIGHTA [ SELF; "*"; SELF | SELF; "/"; SELF ] | "simple" NONA [ "("; SELF; ")" | INT ((_)) ] | LEFTA [ SELF; "plus1plus"; SELF ] ] *) let _ = begin EXTEND MGram test: LEVEL "mult" [[x = SELF ; "plus1plus" ; y = SELF ]]; END ; p Format.std_formatter test; end (** output test: [ "add" LEFTA [ SELF; "plus1plus"; SELF | SELF; "+"; SELF | SELF; "-"; SELF ] | "mult" RIGHTA [ SELF; "plus1plus"; SELF | SELF; "*"; SELF | SELF; "/"; SELF ] | "simple" NONA [ "("; SELF; ")" | INT ((_)) ] | LEFTA [ SELF; "plus1plus"; SELF ] ] *) let _ = begin EXTEND MGram test: BEFORE "mult" [[x = SELF ; "plus1plus" ; y = SELF ]]; END ; p Format.std_formatter test; end (** output test: [ "add" LEFTA [ SELF; "plus1plus"; SELF | SELF; "+"; SELF | SELF; "-"; SELF ] | LEFTA [ SELF; "plus1plus"; SELF ] | "mult" RIGHTA [ SELF; "plus1plus"; SELF | SELF; "*"; SELF | SELF; "/"; SELF ] | "simple" NONA [ "("; SELF; ")" | INT ((_)) ] | LEFTA [ SELF; "plus1plus"; SELF ] ] *)
null
https://raw.githubusercontent.com/bobzhang/ocaml-book/09a575b0d1fedfce565ecb9a0ae9cf0df37fdc75/camlp4/code/grammar.ml
ocaml
* output test: [ "add" LEFTA [ SELF; "+"; SELF | SELF; "-"; SELF ] | "mult" RIGHTA [ SELF; "*"; SELF | SELF; "/"; SELF ] | "simple" NONA [ "("; SELF; ")" | INT ((_)) ] ] * output test: [ "add" LEFTA [ SELF; "plus1plus"; SELF | SELF; "+"; SELF | SELF; "-"; SELF ] | "mult" RIGHTA [ SELF; "*"; SELF | SELF; "/"; SELF ] | "simple" NONA [ "("; SELF; ")" | INT ((_)) ] ] * output test: [ "add" LEFTA [ SELF; "plus1plus"; SELF | SELF; "+"; SELF | SELF; "-"; SELF ] | "mult" RIGHTA [ SELF; "*"; SELF | SELF; "/"; SELF ] | "simple" NONA [ "("; SELF; ")" | INT ((_)) ] | LEFTA [ SELF; "plus1plus"; SELF ] ] * output test: [ "add" LEFTA [ SELF; "plus1plus"; SELF | SELF; "+"; SELF | SELF; "-"; SELF ] | "mult" RIGHTA [ SELF; "plus1plus"; SELF | SELF; "*"; SELF | SELF; "/"; SELF ] | "simple" NONA [ "("; SELF; ")" | INT ((_)) ] | LEFTA [ SELF; "plus1plus"; SELF ] ] * output test: [ "add" LEFTA [ SELF; "plus1plus"; SELF | SELF; "+"; SELF | SELF; "-"; SELF ] | LEFTA [ SELF; "plus1plus"; SELF ] | "mult" RIGHTA [ SELF; "plus1plus"; SELF | SELF; "*"; SELF | SELF; "/"; SELF ] | "simple" NONA [ "("; SELF; ")" | INT ((_)) ] | LEFTA [ SELF; "plus1plus"; SELF ] ]
# require " camlp4.gramlib " ; ; open Camlp4.PreCast module MGram = MakeGram(Lexer) let test = MGram.Entry.mk "test" let p = MGram.Entry.print let _ = begin MGram.Entry.clear test; EXTEND MGram GLOBAL: test; test: ["add" LEFTA [SELF; "+" ; SELF | SELF; "-" ; SELF] | "mult" RIGHTA [SELF; "*" ; SELF | SELF; "/" ; SELF] | "simple" NONA [ "("; SELF; ")" | INT ] ]; END; p Format.std_formatter test; end let _ = begin EXTEND MGram GLOBAL: test; test: [[ x = SELF ; "plus1plus" ; y = SELF ]]; END ; p Format.std_formatter test end let _ = begin EXTEND MGram test: LAST [[x = SELF ; "plus1plus" ; y = SELF ]]; END; p Format.std_formatter test end let _ = begin EXTEND MGram test: LEVEL "mult" [[x = SELF ; "plus1plus" ; y = SELF ]]; END ; p Format.std_formatter test; end let _ = begin EXTEND MGram test: BEFORE "mult" [[x = SELF ; "plus1plus" ; y = SELF ]]; END ; p Format.std_formatter test; end
e9037f32db8e5cb0e564845181acc640e932c5a1e1cb0a883bc287677e201b96
nlamirault/climc
commands.lisp
-*- Mode : LISP ; Syntax : ANSI - Common - Lisp ; Base : 10 -*- ;;;; ************************************************************************* ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: commands.lisp Purpose : commands for the IM client . Programmer : < > ;;;; ;;;; climc users are granted the rights to distribute and use this software as governed by the terms of the MIT License : ;;;; -license.php ;;;; ;;;; ************************************************************************* (in-package :climc) ;; ----- ;; Menu ;; ----- (define-im-client-command (com-quit :name t :menu nil :keystroke (#\q :control)) () (clim:frame-exit *im-client*)) (define-im-client-command (com-xmpp-debug :name t :menu nil :keystroke (#\x :control)) () (when *xmpp-app* (bt:make-thread (lambda () (clim:run-frame-top-level *xmpp-app*)) :name "Climc Xmpp Debug"))) (define-im-client-command (com-add-contact :name t :menu nil :keystroke (#\a :control)) () (clim:frame-exit *im-client*)) ;; ---------- Selection ;; ---------- (define-im-client-command com-select-contact ((contact 'contact :gesture :select)) (let ((frame (clim:make-application-frame 'chat :height 200 :width 600 :calling-frame *im-client* :contact contact :doc-title (format nil "Chat with ~A" (email-of contact))))) (setf (gethash (email-of contact) (calls-of *im-client*)) frame) (clim:run-frame-top-level frame)))
null
https://raw.githubusercontent.com/nlamirault/climc/35a64a34d17c96708c14c08d1335352f1a4f96ee/src/commands.lisp
lisp
Syntax : ANSI - Common - Lisp ; Base : 10 -*- ************************************************************************* FILE IDENTIFICATION Name: commands.lisp climc users are granted the rights to distribute and use this software -license.php ************************************************************************* ----- Menu ----- ---------- ----------
Purpose : commands for the IM client . Programmer : < > as governed by the terms of the MIT License : (in-package :climc) (define-im-client-command (com-quit :name t :menu nil :keystroke (#\q :control)) () (clim:frame-exit *im-client*)) (define-im-client-command (com-xmpp-debug :name t :menu nil :keystroke (#\x :control)) () (when *xmpp-app* (bt:make-thread (lambda () (clim:run-frame-top-level *xmpp-app*)) :name "Climc Xmpp Debug"))) (define-im-client-command (com-add-contact :name t :menu nil :keystroke (#\a :control)) () (clim:frame-exit *im-client*)) Selection (define-im-client-command com-select-contact ((contact 'contact :gesture :select)) (let ((frame (clim:make-application-frame 'chat :height 200 :width 600 :calling-frame *im-client* :contact contact :doc-title (format nil "Chat with ~A" (email-of contact))))) (setf (gethash (email-of contact) (calls-of *im-client*)) frame) (clim:run-frame-top-level frame)))
4bc5c49cb8cce72926abb70c29b059045b07ede02095dcd3b63a9a1d4f60b18e
kappelmann/eidi2_repetitorium_tum
Doubly_Ended_List_Impl.ml
let todo _ = failwith "Something is not implemented" open Doubly_Ended_List Achten Sie bei der Implementierung auf eine möglichst effiziente Laufzeit (* module DoublyEndedListImpl ... *) (* few test cases *) open DoublyEndedListImpl let l = empty let rec push op l v = List.fold_left (fun l x -> op l x) l v let l = push push_front l [5;4;3;2;1] let l = push push_back l [6;7;8;9;10] let _ = print_string "If your implementation is correct, you should now see numbers from 1 to 10 and a happy smiley\n" let l = let rec pf l i = if i=10 then (print_string "\n"; l) else let (l,Some v) = pop_front l in print_int v; print_string ","; pf l (i+1) in pf l 0 let _ = let c = (pop_front l, pop_back l) in if c=((empty,None),(empty,None)) then print_string ":-)\n" else print_string "your pop_front does not work\n" let l = empty let rec push op l v = List.fold_left (fun l x -> op l x) l v let l = push push_front l [5;4;3;2;1] let l = push push_back l [6;7;8;9;10] let _ = print_string "If your implementation is correct, you should now see numbers from 10 to 1 and a happy smiley\n" let l = let rec pf l i = if i=10 then (print_string "\n"; l) else let (l,Some v) = pop_back l in print_int v; print_string ","; pf l (i+1) in pf l 0 let _ = let c = (pop_front l, pop_back l) in if c=((empty,None),(empty,None)) then print_string ":-)\n" else print_string "your pop does not work\n"
null
https://raw.githubusercontent.com/kappelmann/eidi2_repetitorium_tum/1d16bbc498487a85960e0d83152249eb13944611/2017/ocaml/data_structures/exercises/doubly_ended_list/Doubly_Ended_List_Impl.ml
ocaml
module DoublyEndedListImpl ... few test cases
let todo _ = failwith "Something is not implemented" open Doubly_Ended_List Achten Sie bei der Implementierung auf eine möglichst effiziente Laufzeit open DoublyEndedListImpl let l = empty let rec push op l v = List.fold_left (fun l x -> op l x) l v let l = push push_front l [5;4;3;2;1] let l = push push_back l [6;7;8;9;10] let _ = print_string "If your implementation is correct, you should now see numbers from 1 to 10 and a happy smiley\n" let l = let rec pf l i = if i=10 then (print_string "\n"; l) else let (l,Some v) = pop_front l in print_int v; print_string ","; pf l (i+1) in pf l 0 let _ = let c = (pop_front l, pop_back l) in if c=((empty,None),(empty,None)) then print_string ":-)\n" else print_string "your pop_front does not work\n" let l = empty let rec push op l v = List.fold_left (fun l x -> op l x) l v let l = push push_front l [5;4;3;2;1] let l = push push_back l [6;7;8;9;10] let _ = print_string "If your implementation is correct, you should now see numbers from 10 to 1 and a happy smiley\n" let l = let rec pf l i = if i=10 then (print_string "\n"; l) else let (l,Some v) = pop_back l in print_int v; print_string ","; pf l (i+1) in pf l 0 let _ = let c = (pop_front l, pop_back l) in if c=((empty,None),(empty,None)) then print_string ":-)\n" else print_string "your pop does not work\n"
f88160344005ea58862734397530142597fc6f4e6b157ff9b349c119f5205240
VisionsGlobalEmpowerment/webchange
teacher.cljc
(ns webchange.validation.specs.teacher (:require [clojure.spec.alpha :as s] [webchange.validation.predicates :as p])) (def email-regex #"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$") (def status? #{"active", "inactive"}) (def type? #{"admin", "teacher"}) (s/def ::first-name p/not-empty-string?) (s/def ::last-name p/not-empty-string?) (s/def ::email (s/and string? #(re-matches email-regex %))) (s/def ::status status?) (s/def ::type type?) (s/def ::id number?) (s/def ::create-teacher (s/keys :req-un [::first-name ::last-name ::email ::password ::type] :opt-un [])) (s/def ::edit-teacher (s/keys :req-un [::first-name ::last-name ::type] :opt-un [::password])) (s/def ::edit-teacher-status (s/keys :req-un [::status]))
null
https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/fac5273065559ac53becf059cfc84054d2e352df/src/cljc/webchange/validation/specs/teacher.cljc
clojure
(ns webchange.validation.specs.teacher (:require [clojure.spec.alpha :as s] [webchange.validation.predicates :as p])) (def email-regex #"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$") (def status? #{"active", "inactive"}) (def type? #{"admin", "teacher"}) (s/def ::first-name p/not-empty-string?) (s/def ::last-name p/not-empty-string?) (s/def ::email (s/and string? #(re-matches email-regex %))) (s/def ::status status?) (s/def ::type type?) (s/def ::id number?) (s/def ::create-teacher (s/keys :req-un [::first-name ::last-name ::email ::password ::type] :opt-un [])) (s/def ::edit-teacher (s/keys :req-un [::first-name ::last-name ::type] :opt-un [::password])) (s/def ::edit-teacher-status (s/keys :req-un [::status]))
db5f34ea127f6ecde5bb1ade6fd95f5b88fbd68562abea69297cb43ad7cf840d
rabbitmq/rabbitmq-sharding
rabbit_sharding_exchange_decorator.erl
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 ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved . %% -module(rabbit_sharding_exchange_decorator). -rabbit_boot_step({?MODULE, [{description, "sharding exchange decorator"}, {mfa, {rabbit_registry, register, [exchange_decorator, <<"sharding">>, ?MODULE]}}, {cleanup, {rabbit_registry, unregister, [exchange_decorator, <<"sharding">>]}}, {requires, rabbit_registry}, {enables, recovery}]}). -include_lib("rabbit_common/include/rabbit.hrl"). -behaviour(rabbit_exchange_decorator). -export([description/0, serialise_events/1]). -export([create/2, delete/3, policy_changed/2, add_binding/3, remove_bindings/3, route/2, active_for/1]). -import(rabbit_sharding_util, [shard/1]). %%---------------------------------------------------------------------------- description() -> [{description, <<"Shard exchange decorator">>}]. serialise_events(_X) -> false. create(transaction, _X) -> ok; create(none, X) -> maybe_start_sharding(X), ok. add_binding(_Tx, _X, _B) -> ok. remove_bindings(_Tx, _X, _Bs) -> ok. route(_, _) -> []. active_for(X) -> case shard(X) of true -> noroute; false -> none end. we have to remove the policy from ? SHARDING_TABLE delete(transaction, _X, _Bs) -> ok; delete(none, X, _Bs) -> maybe_stop_sharding(X), ok. we have to remove the old policy from ? SHARDING_TABLE %% and then add the new one. policy_changed(OldX, NewX) -> maybe_update_sharding(OldX, NewX), ok. %%---------------------------------------------------------------------------- maybe_update_sharding(OldX, NewX) -> case shard(NewX) of true -> rabbit_sharding_shard:maybe_update_shards(OldX, NewX); false -> rabbit_sharding_shard:stop_sharding(OldX) end. maybe_start_sharding(X)-> case shard(X) of true -> rabbit_sharding_shard:ensure_sharded_queues(X); false -> ok end. maybe_stop_sharding(X) -> case shard(X) of true -> rabbit_sharding_shard:stop_sharding(X); false -> ok end.
null
https://raw.githubusercontent.com/rabbitmq/rabbitmq-sharding/722f8165f156b03ffa2cb7890999b8c37446d3a6/src/rabbit_sharding_exchange_decorator.erl
erlang
---------------------------------------------------------------------------- and then add the new one. ----------------------------------------------------------------------------
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 ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved . -module(rabbit_sharding_exchange_decorator). -rabbit_boot_step({?MODULE, [{description, "sharding exchange decorator"}, {mfa, {rabbit_registry, register, [exchange_decorator, <<"sharding">>, ?MODULE]}}, {cleanup, {rabbit_registry, unregister, [exchange_decorator, <<"sharding">>]}}, {requires, rabbit_registry}, {enables, recovery}]}). -include_lib("rabbit_common/include/rabbit.hrl"). -behaviour(rabbit_exchange_decorator). -export([description/0, serialise_events/1]). -export([create/2, delete/3, policy_changed/2, add_binding/3, remove_bindings/3, route/2, active_for/1]). -import(rabbit_sharding_util, [shard/1]). description() -> [{description, <<"Shard exchange decorator">>}]. serialise_events(_X) -> false. create(transaction, _X) -> ok; create(none, X) -> maybe_start_sharding(X), ok. add_binding(_Tx, _X, _B) -> ok. remove_bindings(_Tx, _X, _Bs) -> ok. route(_, _) -> []. active_for(X) -> case shard(X) of true -> noroute; false -> none end. we have to remove the policy from ? SHARDING_TABLE delete(transaction, _X, _Bs) -> ok; delete(none, X, _Bs) -> maybe_stop_sharding(X), ok. we have to remove the old policy from ? SHARDING_TABLE policy_changed(OldX, NewX) -> maybe_update_sharding(OldX, NewX), ok. maybe_update_sharding(OldX, NewX) -> case shard(NewX) of true -> rabbit_sharding_shard:maybe_update_shards(OldX, NewX); false -> rabbit_sharding_shard:stop_sharding(OldX) end. maybe_start_sharding(X)-> case shard(X) of true -> rabbit_sharding_shard:ensure_sharded_queues(X); false -> ok end. maybe_stop_sharding(X) -> case shard(X) of true -> rabbit_sharding_shard:stop_sharding(X); false -> ok end.
fd45f75f2f3baadb162a30321b4ae86ac2eea6ee7f8967b7fb44691b06efdb15
RedPRL/asai
Flattened.ml
(** Styles *) type style = Marked.style (** A point with a style. *) type marked_point = {style : style option; position : Asai.Span.position} (** Flattened spans in a block. *) type block = marked_point list * A collection of flattened blocks from a file . ( The first component is the file path . ) type section = string * block list
null
https://raw.githubusercontent.com/RedPRL/asai/213c2d926bf51c81f209767fd3a1499151cad22e/src/file/Flattened.ml
ocaml
* Styles * A point with a style. * Flattened spans in a block.
type style = Marked.style type marked_point = {style : style option; position : Asai.Span.position} type block = marked_point list * A collection of flattened blocks from a file . ( The first component is the file path . ) type section = string * block list
c9a1e1446ea65422515df968f99f1794e2df8eb29bfa33f327c8daf554cfcca9
hyperfiddle/electric
analyzer1.cljc
(ns leo.analyzer1 (:require [missionary.core :as m] [dustin.trace28 :refer [let-bindings translate-binding]] [minitest :refer [tests]] [clojure.string :as str])) (defn analyze-let [ast {:keys [passives replayer-sym]}] (let [bindings (let-bindings ast) syms (distinct (map first bindings)) ;; shadowing new-bindings (mapcat (partial translate-binding passives replayer-sym) bindings)] (comment TODO body) {:syms syms :new-bindings new-bindings})) ;; change this form (defn analyze-for [[key-fn [sym form] body] {:keys []}] ) (defn analyze-ast ([ast] (analyze-ast ast {})) ([ast opts] (case (first ast) :let (analyze-let ast opts) :for (analyze-for ast opts)))) (tests (def !a (atom nil)) (def !b (atom nil)) (analyze-ast [:let ['>a `(m/watch !a) '>b `(m/watch !b) '>c [:fmap `+ '>a '>b]]]) := {:paths [{:type :user :symbol '>a :form `(m/watch !a)} {:type :user :symbol '>b :form `(m/watch !b)} {:type :user :symbol '>c :form [:fmap `+ '>a '>b]}]} (def !c (atom #{})) (analyze-ast [:for ['>a :id `(m/watch !c)] (:name '>a)]) := {:paths [{:type :user :form `(m/watch !c)} {:type :diff :target 0 :symbol '>a :key-fn :id} {:type :user :parent 1 :form '(:name >a)}]} (reset! !c #{{:id :a :name "alice"} {:id :b :name "bob"}}) {[0] #{} [1] [#{} #{}]} {[0] #{{:id :a :name "alice"} {:id :b :name "bob"}} [1] [#{:a :b} #{}] [1 :a] {:id :a :name "alice"} [1 :b] {:id :b :name "bob"} [2 :a] "alice" [2 :b] "bob"} )
null
https://raw.githubusercontent.com/hyperfiddle/electric/1c6c3891cbf13123fef8d33e6555d300f0dac134/scratch/leo/analyzer1.cljc
clojure
shadowing change this form
(ns leo.analyzer1 (:require [missionary.core :as m] [dustin.trace28 :refer [let-bindings translate-binding]] [minitest :refer [tests]] [clojure.string :as str])) (defn analyze-let [ast {:keys [passives replayer-sym]}] (let [bindings (let-bindings ast) new-bindings (mapcat (partial translate-binding passives replayer-sym) bindings)] (comment TODO body) {:syms syms (defn analyze-for [[key-fn [sym form] body] {:keys []}] ) (defn analyze-ast ([ast] (analyze-ast ast {})) ([ast opts] (case (first ast) :let (analyze-let ast opts) :for (analyze-for ast opts)))) (tests (def !a (atom nil)) (def !b (atom nil)) (analyze-ast [:let ['>a `(m/watch !a) '>b `(m/watch !b) '>c [:fmap `+ '>a '>b]]]) := {:paths [{:type :user :symbol '>a :form `(m/watch !a)} {:type :user :symbol '>b :form `(m/watch !b)} {:type :user :symbol '>c :form [:fmap `+ '>a '>b]}]} (def !c (atom #{})) (analyze-ast [:for ['>a :id `(m/watch !c)] (:name '>a)]) := {:paths [{:type :user :form `(m/watch !c)} {:type :diff :target 0 :symbol '>a :key-fn :id} {:type :user :parent 1 :form '(:name >a)}]} (reset! !c #{{:id :a :name "alice"} {:id :b :name "bob"}}) {[0] #{} [1] [#{} #{}]} {[0] #{{:id :a :name "alice"} {:id :b :name "bob"}} [1] [#{:a :b} #{}] [1 :a] {:id :a :name "alice"} [1 :b] {:id :b :name "bob"} [2 :a] "alice" [2 :b] "bob"} )
3637589a3ef01883b7308f085be5885556d0061611d419daeeb2fe3147c8d0d7
wireapp/wire-server
Client.hs
# LANGUAGE GeneralizedNewtypeDeriving # {-# LANGUAGE StrictData #-} -- This file is part of the Wire Server implementation. -- Copyright ( C ) 2022 Wire Swiss GmbH < > -- -- This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any -- later version. -- -- This program is distributed in the hope that it will be useful, but WITHOUT -- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more -- details. -- You should have received a copy of the GNU Affero General Public License along -- with this program. If not, see </>. module Wire.API.User.Client ( -- * ClientCapability ClientCapability (..), ClientCapabilityList (..), * ClientInfo ClientInfo (..), -- * UserClients UserClientMap (..), UserClientPrekeyMap (..), mkUserClientPrekeyMap, QualifiedUserClientMap (..), QualifiedUserClientPrekeyMap (..), mkQualifiedUserClientPrekeyMap, qualifiedUserClientPrekeyMapFromList, UserClientsFull (..), userClientsFullToUserClients, UserClients (..), mkUserClients, QualifiedUserClients (..), filterClients, filterClientsFull, -- * Client Client (..), PubClient (..), ClientType (..), ClientClass (..), MLSPublicKeys, -- * New/Update/Remove Client NewClient (..), newClient, UpdateClient (..), defUpdateClient, RmClient (..), -- * re-exports Location, location, latitude, longitude, Latitude (..), Longitude (..), ) where import qualified Cassandra as Cql import Control.Applicative import Control.Lens hiding (element, enum, set, (#), (.=)) import Data.Aeson (FromJSON (..), ToJSON (..)) import qualified Data.Aeson as A import qualified Data.Aeson.Key as Key import qualified Data.Aeson.KeyMap as KeyMap import Data.Bifunctor (second) import qualified Data.Code as Code import Data.Coerce import Data.Domain (Domain) import Data.Id import Data.Json.Util import qualified Data.Map.Strict as Map import Data.Misc (Latitude (..), Location, Longitude (..), PlainTextPassword (..), latitude, location, longitude) import Data.Qualified import Data.Schema import qualified Data.Set as Set import Data.Swagger hiding (Schema, ToSchema, schema) import qualified Data.Swagger as Swagger import qualified Data.Text.Encoding as Text.E import Data.UUID (toASCIIBytes) import Deriving.Swagger ( CustomSwagger, FieldLabelModifier, LowerCase, StripPrefix, ) import Imports import Wire.API.MLS.Credential import Wire.API.User.Auth (CookieLabel) import Wire.API.User.Client.Prekey as Prekey import Wire.Arbitrary (Arbitrary (arbitrary), GenericUniform (..), generateExample, mapOf', setOf') ---------------------------------------------------------------------- ClientCapability , ClientCapabilityList -- | Names of capabilities clients can claim to support in order to be treated differently by -- the backend. -- -- **The cost of capability keywords** -- -- Avoid this wherever possible. Adding capability keywords in the backend code makes testing -- exponentially more expensive (in principle, you should always test all combinations of -- supported capabilitiess. But even if you only test those known to occur in the wild, it will -- still make your life harder.) -- -- Consider dropping support for clients without ancient capabilitiess if you have "enough" clients -- that are younger. This will always be disruptive for a minority of users, but maybe this -- can be mitigated by giving those users clear feedback that they need to upgrade in order to get their expected UX back . -- -- **An alternative design** -- -- Consider replacing 'ClientCapability' with platform and version in formation (I played with @data Platform = Android | IOS | WebApp | TeamSettings | AccountPages@ and @Version@ from the ` semver ` package in -server/pull/1503 , -- but ended up deciding against it). This data could be passed in a similar way as the ' ClientCapabilityList ' is now ( similar end - point , different path , different body type ) , and the two approaches could be used in parallel indefinitely . -- -- Capability keywords reveal the minimum amount of information necessary to handle the client, -- making it harder to fingerprint and track clients; they are straight-forward and -- self-documenting (to an extent), and make it easier to release a capability on the backend and -- clients independently. -- Platform / version info is if you have many different capability keywords , even though it -- doesn't solve the problem of having to explore the entire capability space in your tests. -- They give you a better idea of the time line, and how to gently discontinue support for -- ancient capabilities. data ClientCapability | Clients have minimum support for LH , but not for explicit consent . Implicit consent -- is granted via the galley server config and cassandra table `galley.legalhold_whitelisted`. ClientSupportsLegalholdImplicitConsent deriving stock (Eq, Ord, Bounded, Enum, Show, Generic) deriving (Arbitrary) via (GenericUniform ClientCapability) deriving (ToJSON, FromJSON, Swagger.ToSchema) via Schema ClientCapability instance ToSchema ClientCapability where schema = enum @Text "ClientCapability" $ element "legalhold-implicit-consent" ClientSupportsLegalholdImplicitConsent instance Cql.Cql ClientCapability where ctype = Cql.Tagged Cql.IntColumn toCql ClientSupportsLegalholdImplicitConsent = Cql.CqlInt 1 fromCql (Cql.CqlInt i) = case i of 1 -> pure ClientSupportsLegalholdImplicitConsent n -> Left $ "Unexpected ClientCapability value: " ++ show n fromCql _ = Left "ClientCapability value: int expected" -- FUTUREWORK: add golden tests for this? newtype ClientCapabilityList = ClientCapabilityList {fromClientCapabilityList :: Set ClientCapability} deriving stock (Eq, Ord, Show, Generic) deriving newtype (Semigroup, Monoid) deriving (Arbitrary) via (GenericUniform ClientCapabilityList) deriving (ToJSON, FromJSON, Swagger.ToSchema) via (Schema ClientCapabilityList) instance ToSchema ClientCapabilityList where schema = object "ClientCapabilityList" $ ClientCapabilityList <$> fromClientCapabilityList .= fmap runIdentity capabilitiesFieldSchema capabilitiesFieldSchema :: FieldFunctor SwaggerDoc f => ObjectSchemaP SwaggerDoc (Set ClientCapability) (f (Set ClientCapability)) capabilitiesFieldSchema = Set.toList .= fieldWithDocModifierF "capabilities" mods (Set.fromList <$> array schema) where mods = description ?~ "Hints provided by the client for the backend so it can \ \behave in a backwards-compatible way." -------------------------------------------------------------------------------- -- UserClientMap newtype UserClientMap a = UserClientMap { userClientMap :: Map UserId (Map ClientId a) } deriving stock (Eq, Show, Functor, Foldable, Traversable) deriving newtype (Semigroup, Monoid) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema (UserClientMap a) instance ToSchema a => ToSchema (UserClientMap a) where schema = userClientMapSchema schema class WrapName doc where wrapName :: doc -> (Text -> Text) -> SwaggerDoc -> doc instance WrapName SwaggerDoc where wrapName _ _ = id instance WrapName NamedSwaggerDoc where wrapName d f = fmap (Swagger.NamedSchema (Just (f (maybe "" ("_" <>) (getName d))))) userClientMapSchema :: (WrapName doc, HasSchemaRef doc) => ValueSchema doc a -> ValueSchema doc (UserClientMap a) userClientMapSchema sch = over doc (wrapName (schemaDoc sch) ("UserClientMap" <>)) $ UserClientMap <$> userClientMap .= map_ (map_ sch) newtype UserClientPrekeyMap = UserClientPrekeyMap {getUserClientPrekeyMap :: UserClientMap (Maybe Prekey)} deriving stock (Eq, Show) deriving newtype (Arbitrary, Semigroup, Monoid) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema UserClientPrekeyMap mkUserClientPrekeyMap :: Map UserId (Map ClientId (Maybe Prekey)) -> UserClientPrekeyMap mkUserClientPrekeyMap = coerce instance ToSchema UserClientPrekeyMap where schema = UserClientPrekeyMap <$> getUserClientPrekeyMap .= addDoc sch where sch = named "UserClientPrekeyMap" $ userClientMapSchema (nullable (unnamed schema)) addDoc = Swagger.schema . Swagger.example ?~ toJSON ( Map.singleton (generateExample @UserId) ( Map.singleton (newClientId 4940483633899001999) (Just (Prekey (PrekeyId 1) "pQABAQECoQBYIOjl7hw0D8YRNq...")) ) ) instance Arbitrary a => Arbitrary (UserClientMap a) where arbitrary = UserClientMap <$> mapOf' arbitrary (mapOf' arbitrary arbitrary) newtype QualifiedUserClientMap a = QualifiedUserClientMap { qualifiedUserClientMap :: Map Domain (Map UserId (Map ClientId a)) } deriving stock (Eq, Show, Functor) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema (QualifiedUserClientMap a) instance Semigroup a => Semigroup (QualifiedUserClientMap a) where (QualifiedUserClientMap m1) <> (QualifiedUserClientMap m2) = QualifiedUserClientMap $ Map.unionWith (Map.unionWith (Map.unionWith (<>))) m1 m2 instance Semigroup (QualifiedUserClientMap a) => Monoid (QualifiedUserClientMap a) where mempty = QualifiedUserClientMap mempty instance Arbitrary a => Arbitrary (QualifiedUserClientMap a) where arbitrary = QualifiedUserClientMap <$> mapOf' arbitrary (mapOf' arbitrary (mapOf' arbitrary arbitrary)) instance ToSchema a => ToSchema (QualifiedUserClientMap a) where schema = qualifiedUserClientMapSchema schema qualifiedUserClientMapSchema :: ValueSchema NamedSwaggerDoc a -> ValueSchema NamedSwaggerDoc (QualifiedUserClientMap a) qualifiedUserClientMapSchema sch = addDoc . named nm $ QualifiedUserClientMap <$> qualifiedUserClientMap .= map_ (map_ (map_ sch)) where innerSchema = userClientMapSchema sch nm = "QualifiedUserClientMap" <> maybe "" ("_" <>) (getName (schemaDoc sch)) addDoc = Swagger.schema . Swagger.example ?~ toJSON ( Map.singleton ("domain1.example.com" :: Text) (schemaDoc innerSchema ^. Swagger.schema . Swagger.example) ) newtype QualifiedUserClientPrekeyMap = QualifiedUserClientPrekeyMap {getQualifiedUserClientPrekeyMap :: QualifiedUserClientMap (Maybe Prekey)} deriving stock (Eq, Show) deriving newtype (Arbitrary) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema QualifiedUserClientPrekeyMap deriving (Semigroup, Monoid) via (QualifiedUserClientMap (Alt Maybe Prekey)) instance ToSchema QualifiedUserClientPrekeyMap where schema = named "QualifiedUserClientPrekeyMap" $ mkQualifiedUserClientPrekeyMap <$> unmk .= map_ schema where unmk :: QualifiedUserClientPrekeyMap -> Map Domain UserClientPrekeyMap unmk = coerce mkQualifiedUserClientPrekeyMap :: Map Domain UserClientPrekeyMap -> QualifiedUserClientPrekeyMap mkQualifiedUserClientPrekeyMap = coerce qualifiedUserClientPrekeyMapFromList :: [Qualified UserClientPrekeyMap] -> QualifiedUserClientPrekeyMap qualifiedUserClientPrekeyMapFromList = mkQualifiedUserClientPrekeyMap . Map.fromList . map qToPair -------------------------------------------------------------------------------- ClientInfo -- | A client, together with extra information about it. data ClientInfo = ClientInfo { -- | The ID of this client. ciId :: ClientId, | Whether this client is MLS - capable . ciMLS :: Bool } deriving stock (Eq, Ord, Show) deriving (Swagger.ToSchema, FromJSON, ToJSON) via Schema ClientInfo instance ToSchema ClientInfo where schema = object "ClientInfo" $ ClientInfo <$> ciId .= field "id" schema <*> ciMLS .= field "mls" schema -------------------------------------------------------------------------------- UserClients newtype UserClientsFull = UserClientsFull { userClientsFull :: Map UserId (Set Client) } deriving stock (Eq, Show, Generic) deriving newtype (Semigroup, Monoid) instance ToJSON UserClientsFull where toJSON = toJSON . Map.foldrWithKey' fn Map.empty . userClientsFull where fn u c m = let k = Text.E.decodeLatin1 (toASCIIBytes (toUUID u)) in Map.insert k c m instance FromJSON UserClientsFull where parseJSON = A.withObject "UserClientsFull" (fmap UserClientsFull . foldrM fn Map.empty . KeyMap.toList) where fn (k, v) m = Map.insert <$> parseJSON (A.String $ Key.toText k) <*> parseJSON v <*> pure m instance Arbitrary UserClientsFull where arbitrary = UserClientsFull <$> mapOf' arbitrary (setOf' arbitrary) userClientsFullToUserClients :: UserClientsFull -> UserClients userClientsFullToUserClients (UserClientsFull mp) = UserClients $ Set.map clientId <$> mp newtype UserClients = UserClients { userClients :: Map UserId (Set ClientId) } deriving stock (Eq, Show, Generic) deriving newtype (Semigroup, Monoid) deriving (ToJSON, FromJSON, Swagger.ToSchema) via Schema UserClients mkUserClients :: [(UserId, [ClientId])] -> UserClients mkUserClients xs = UserClients $ Map.fromList (xs <&> second Set.fromList) instance ToSchema UserClients where schema = addDoc . named "UserClients" $ UserClients <$> userClients .= map_ (set schema) where addDoc sch = sch & Swagger.schema . Swagger.description ?~ "Map of user id to list of client ids." & Swagger.schema . Swagger.example ?~ toJSON ( Map.fromList [ (generateExample @UserId, [newClientId 1684636986166846496, newClientId 4940483633899001999]), (generateExample @UserId, [newClientId 6987438498444556166, newClientId 7940473633839002939]) ] ) instance Arbitrary UserClients where arbitrary = UserClients <$> mapOf' arbitrary (setOf' arbitrary) filterClients :: (Set ClientId -> Bool) -> UserClients -> UserClients filterClients p (UserClients c) = UserClients $ Map.filter p c filterClientsFull :: (Set Client -> Bool) -> UserClientsFull -> UserClientsFull filterClientsFull p (UserClientsFull c) = UserClientsFull $ Map.filter p c newtype QualifiedUserClients = QualifiedUserClients { qualifiedUserClients :: Map Domain (Map UserId (Set ClientId)) } deriving stock (Eq, Show, Generic) deriving (FromJSON, ToJSON, Swagger.ToSchema) via (Schema QualifiedUserClients) instance Semigroup QualifiedUserClients where (QualifiedUserClients m1) <> (QualifiedUserClients m2) = QualifiedUserClients $ Map.unionWith (Map.unionWith (<>)) m1 m2 instance Monoid QualifiedUserClients where mempty = QualifiedUserClients mempty instance Arbitrary QualifiedUserClients where arbitrary = QualifiedUserClients <$> mapOf' arbitrary (mapOf' arbitrary (setOf' arbitrary)) instance ToSchema QualifiedUserClients where schema = addDoc . named "QualifiedUserClients" $ QualifiedUserClients <$> qualifiedUserClients .= map_ (map_ (set schema)) where addDoc sch = sch & Swagger.schema . Swagger.description ?~ "Map of Domain to UserClients" & Swagger.schema . Swagger.example ?~ toJSON ( Map.singleton ("domain1.example.com" :: Text) (view (Swagger.schema . Swagger.example) (schema @UserClients)) ) -------------------------------------------------------------------------------- -- Client data Client = Client { clientId :: ClientId, clientType :: ClientType, clientTime :: UTCTimeMillis, clientClass :: Maybe ClientClass, clientLabel :: Maybe Text, clientCookie :: Maybe CookieLabel, clientLocation :: Maybe Location, clientModel :: Maybe Text, clientCapabilities :: ClientCapabilityList, clientMLSPublicKeys :: MLSPublicKeys } deriving stock (Eq, Show, Generic, Ord) deriving (Arbitrary) via (GenericUniform Client) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema Client type MLSPublicKeys = Map SignatureSchemeTag ByteString mlsPublicKeysSchema :: ValueSchema NamedSwaggerDoc MLSPublicKeys mlsPublicKeysSchema = mapSchema & doc %~ ( (description ?~ "Mapping from signature scheme (tags) to public key data") . (example ?~ toJSON (Map.fromList $ map (,exampleValue) keys)) ) & named "MLSPublicKeys" where keys :: [SignatureSchemeTag] keys = [minBound .. maxBound] exampleValue :: A.Value exampleValue = fromMaybe (toJSON ("base64==" :: Text)) (base64Schema ^. doc . example) mapSchema :: ValueSchema SwaggerDoc MLSPublicKeys mapSchema = map_ base64Schema instance ToSchema Client where schema = object "Client" $ Client <$> clientId .= field "id" schema <*> clientType .= field "type" schema <*> clientTime .= field "time" schema <*> clientClass .= maybe_ (optField "class" schema) <*> clientLabel .= maybe_ (optField "label" schema) <*> clientCookie .= maybe_ (optField "cookie" schema) <*> clientLocation .= maybe_ (optField "location" schema) <*> clientModel .= maybe_ (optField "model" schema) <*> clientCapabilities .= (fromMaybe mempty <$> optField "capabilities" schema) <*> clientMLSPublicKeys .= mlsPublicKeysFieldSchema mlsPublicKeysFieldSchema :: ObjectSchema SwaggerDoc MLSPublicKeys mlsPublicKeysFieldSchema = fromMaybe mempty <$> optField "mls_public_keys" mlsPublicKeysSchema -------------------------------------------------------------------------------- PubClient data PubClient = PubClient { pubClientId :: ClientId, pubClientClass :: Maybe ClientClass } deriving stock (Eq, Show, Generic, Ord) deriving (Arbitrary) via (GenericUniform PubClient) deriving (Swagger.ToSchema) via (CustomSwagger '[FieldLabelModifier (StripPrefix "pubClient", LowerCase)] PubClient) instance ToJSON PubClient where toJSON c = A.object $ "id" A..= pubClientId c # "class" A..= pubClientClass c # [] instance FromJSON PubClient where parseJSON = A.withObject "PubClient" $ \o -> PubClient <$> o A..: "id" <*> o A..:? "class" -------------------------------------------------------------------------------- -- Client Type/Class -- [Note: LegalHold] -- -- Short feature description: -- LegalHold is an enterprise feature, enabled on a per-team basis, and within a -- team on a per-user basis -- -- A LegalHoldClient is a client outside that user's control (but under the -- control of that team's business) -- -- Users need to click "accept" before a LegalHoldClient is added to their -- account. -- -- Any user interacting with a user which has a LegalHoldClient will upon -- first interaction receive a warning, have the option of cancelling the -- interaction, and on an ongoing basis see a visual indication in all -- conversations where such a device is active. data ClientType = TemporaryClientType | PermanentClientType see Note [ LegalHold ] deriving stock (Eq, Ord, Show, Generic) deriving (Arbitrary) via (GenericUniform ClientType) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema ClientType instance ToSchema ClientType where schema = enum @Text "ClientType" $ element "temporary" TemporaryClientType <> element "permanent" PermanentClientType <> element "legalhold" LegalHoldClientType data ClientClass = PhoneClient | TabletClient | DesktopClient see Note [ LegalHold ] deriving stock (Eq, Ord, Show, Generic) deriving (Arbitrary) via (GenericUniform ClientClass) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema ClientClass instance ToSchema ClientClass where schema = enum @Text "ClientClass" $ element "phone" PhoneClient <> element "tablet" TabletClient <> element "desktop" DesktopClient <> element "legalhold" LegalHoldClient -------------------------------------------------------------------------------- NewClient data NewClient = NewClient { newClientPrekeys :: [Prekey], newClientLastKey :: LastPrekey, newClientType :: ClientType, newClientLabel :: Maybe Text, newClientClass :: Maybe ClientClass, newClientCookie :: Maybe CookieLabel, newClientPassword :: Maybe PlainTextPassword, newClientModel :: Maybe Text, newClientCapabilities :: Maybe (Set ClientCapability), newClientMLSPublicKeys :: MLSPublicKeys, newClientVerificationCode :: Maybe Code.Value } deriving stock (Eq, Show, Generic) deriving (Arbitrary) via (GenericUniform NewClient) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema NewClient instance ToSchema NewClient where schema = object "NewClient" $ NewClient <$> newClientPrekeys .= fieldWithDocModifier "prekeys" (description ?~ "Prekeys for other clients to establish OTR sessions.") (array schema) <*> newClientLastKey .= fieldWithDocModifier "lastkey" ( description ?~ "The last resort prekey for other clients to establish OTR sessions. \ \This key must have the ID 0xFFFF and is never deleted." ) schema <*> newClientType .= fieldWithDocModifier "type" ( description ?~ "The type of client to register. A user may have no more than \ \7 (seven) permanent clients and 1 (one) temporary client. When the \ \limit of permanent clients is reached, an error is returned. \ \When a temporary client already exists, it is replaced." ) schema <*> newClientLabel .= maybe_ (optField "label" schema) <*> newClientClass .= maybe_ ( optFieldWithDocModifier "class" ( description ?~ "The device class this client belongs to. \ \Either 'phone', 'tablet', or 'desktop'." ) schema ) <*> newClientCookie .= maybe_ ( optFieldWithDocModifier "cookie" (description ?~ "The cookie label, i.e. the label used when logging in.") schema ) <*> newClientPassword .= maybe_ ( optFieldWithDocModifier "password" ( description ?~ "The password of the authenticated user for verification. \ \Note: Required for registration of the 2nd, 3rd, ... client." ) schema ) <*> newClientModel .= maybe_ (optField "model" schema) <*> newClientCapabilities .= maybe_ capabilitiesFieldSchema <*> newClientMLSPublicKeys .= mlsPublicKeysFieldSchema <*> newClientVerificationCode .= maybe_ (optField "verification_code" schema) newClient :: ClientType -> LastPrekey -> NewClient newClient t k = NewClient { newClientPrekeys = [], newClientLastKey = k, newClientType = t, newClientLabel = Nothing, newClientClass = if t == LegalHoldClientType then Just LegalHoldClient else Nothing, newClientCookie = Nothing, newClientPassword = Nothing, newClientModel = Nothing, newClientCapabilities = Nothing, newClientMLSPublicKeys = mempty, newClientVerificationCode = Nothing } -------------------------------------------------------------------------------- UpdateClient data UpdateClient = UpdateClient { updateClientPrekeys :: [Prekey], updateClientLastKey :: Maybe LastPrekey, updateClientLabel :: Maybe Text, | see for ' ClientCapability ' updateClientCapabilities :: Maybe (Set ClientCapability), updateClientMLSPublicKeys :: MLSPublicKeys } deriving stock (Eq, Show, Generic) deriving (Arbitrary) via (GenericUniform UpdateClient) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema UpdateClient defUpdateClient :: UpdateClient defUpdateClient = UpdateClient { updateClientPrekeys = [], updateClientLastKey = Nothing, updateClientLabel = Nothing, updateClientCapabilities = Nothing, updateClientMLSPublicKeys = mempty } instance ToSchema UpdateClient where schema = object "UpdateClient" $ UpdateClient <$> updateClientPrekeys .= ( fromMaybe [] <$> optFieldWithDocModifier "prekeys" (description ?~ "New prekeys for other clients to establish OTR sessions.") (array schema) ) <*> updateClientLastKey .= maybe_ ( optFieldWithDocModifier "lastkey" (description ?~ "New last-resort prekey.") schema ) <*> updateClientLabel .= maybe_ ( optFieldWithDocModifier "label" (description ?~ "A new name for this client.") schema ) <*> updateClientCapabilities .= maybe_ capabilitiesFieldSchema <*> updateClientMLSPublicKeys .= mlsPublicKeysFieldSchema -------------------------------------------------------------------------------- -- RmClient newtype RmClient = RmClient { rmPassword :: Maybe PlainTextPassword } deriving stock (Eq, Show, Generic) deriving newtype (Arbitrary) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema RmClient instance ToSchema RmClient where schema = object "DeleteClient" $ RmClient <$> rmPassword .= optFieldWithDocModifier "password" ( description ?~ "The password of the authenticated user for verification. \ \The password is not required for deleting temporary clients." ) (maybeWithDefault A.Null schema)
null
https://raw.githubusercontent.com/wireapp/wire-server/6c4b00ec111e853871564687862a19658d04ea4f/libs/wire-api/src/Wire/API/User/Client.hs
haskell
# LANGUAGE StrictData # This file is part of the Wire Server implementation. This program is free software: you can redistribute it and/or modify it under later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. with this program. If not, see </>. * ClientCapability * UserClients * Client * New/Update/Remove Client * re-exports -------------------------------------------------------------------- | Names of capabilities clients can claim to support in order to be treated differently by the backend. **The cost of capability keywords** Avoid this wherever possible. Adding capability keywords in the backend code makes testing exponentially more expensive (in principle, you should always test all combinations of supported capabilitiess. But even if you only test those known to occur in the wild, it will still make your life harder.) Consider dropping support for clients without ancient capabilitiess if you have "enough" clients that are younger. This will always be disruptive for a minority of users, but maybe this can be mitigated by giving those users clear feedback that they need to upgrade in order to **An alternative design** Consider replacing 'ClientCapability' with platform and version in formation (I but ended up deciding against it). This data could be passed in a similar way as the Capability keywords reveal the minimum amount of information necessary to handle the client, making it harder to fingerprint and track clients; they are straight-forward and self-documenting (to an extent), and make it easier to release a capability on the backend and clients independently. doesn't solve the problem of having to explore the entire capability space in your tests. They give you a better idea of the time line, and how to gently discontinue support for ancient capabilities. is granted via the galley server config and cassandra table `galley.legalhold_whitelisted`. FUTUREWORK: add golden tests for this? ------------------------------------------------------------------------------ UserClientMap ------------------------------------------------------------------------------ | A client, together with extra information about it. | The ID of this client. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Client ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Client Type/Class [Note: LegalHold] Short feature description: LegalHold is an enterprise feature, enabled on a per-team basis, and within a team on a per-user basis A LegalHoldClient is a client outside that user's control (but under the control of that team's business) Users need to click "accept" before a LegalHoldClient is added to their account. Any user interacting with a user which has a LegalHoldClient will upon first interaction receive a warning, have the option of cancelling the interaction, and on an ongoing basis see a visual indication in all conversations where such a device is active. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ RmClient
# LANGUAGE GeneralizedNewtypeDeriving # Copyright ( C ) 2022 Wire Swiss GmbH < > the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any You should have received a copy of the GNU Affero General Public License along module Wire.API.User.Client ClientCapability (..), ClientCapabilityList (..), * ClientInfo ClientInfo (..), UserClientMap (..), UserClientPrekeyMap (..), mkUserClientPrekeyMap, QualifiedUserClientMap (..), QualifiedUserClientPrekeyMap (..), mkQualifiedUserClientPrekeyMap, qualifiedUserClientPrekeyMapFromList, UserClientsFull (..), userClientsFullToUserClients, UserClients (..), mkUserClients, QualifiedUserClients (..), filterClients, filterClientsFull, Client (..), PubClient (..), ClientType (..), ClientClass (..), MLSPublicKeys, NewClient (..), newClient, UpdateClient (..), defUpdateClient, RmClient (..), Location, location, latitude, longitude, Latitude (..), Longitude (..), ) where import qualified Cassandra as Cql import Control.Applicative import Control.Lens hiding (element, enum, set, (#), (.=)) import Data.Aeson (FromJSON (..), ToJSON (..)) import qualified Data.Aeson as A import qualified Data.Aeson.Key as Key import qualified Data.Aeson.KeyMap as KeyMap import Data.Bifunctor (second) import qualified Data.Code as Code import Data.Coerce import Data.Domain (Domain) import Data.Id import Data.Json.Util import qualified Data.Map.Strict as Map import Data.Misc (Latitude (..), Location, Longitude (..), PlainTextPassword (..), latitude, location, longitude) import Data.Qualified import Data.Schema import qualified Data.Set as Set import Data.Swagger hiding (Schema, ToSchema, schema) import qualified Data.Swagger as Swagger import qualified Data.Text.Encoding as Text.E import Data.UUID (toASCIIBytes) import Deriving.Swagger ( CustomSwagger, FieldLabelModifier, LowerCase, StripPrefix, ) import Imports import Wire.API.MLS.Credential import Wire.API.User.Auth (CookieLabel) import Wire.API.User.Client.Prekey as Prekey import Wire.Arbitrary (Arbitrary (arbitrary), GenericUniform (..), generateExample, mapOf', setOf') ClientCapability , ClientCapabilityList get their expected UX back . played with @data Platform = Android | IOS | WebApp | TeamSettings | AccountPages@ and @Version@ from the ` semver ` package in -server/pull/1503 , ' ClientCapabilityList ' is now ( similar end - point , different path , different body type ) , and the two approaches could be used in parallel indefinitely . Platform / version info is if you have many different capability keywords , even though it data ClientCapability | Clients have minimum support for LH , but not for explicit consent . Implicit consent ClientSupportsLegalholdImplicitConsent deriving stock (Eq, Ord, Bounded, Enum, Show, Generic) deriving (Arbitrary) via (GenericUniform ClientCapability) deriving (ToJSON, FromJSON, Swagger.ToSchema) via Schema ClientCapability instance ToSchema ClientCapability where schema = enum @Text "ClientCapability" $ element "legalhold-implicit-consent" ClientSupportsLegalholdImplicitConsent instance Cql.Cql ClientCapability where ctype = Cql.Tagged Cql.IntColumn toCql ClientSupportsLegalholdImplicitConsent = Cql.CqlInt 1 fromCql (Cql.CqlInt i) = case i of 1 -> pure ClientSupportsLegalholdImplicitConsent n -> Left $ "Unexpected ClientCapability value: " ++ show n fromCql _ = Left "ClientCapability value: int expected" newtype ClientCapabilityList = ClientCapabilityList {fromClientCapabilityList :: Set ClientCapability} deriving stock (Eq, Ord, Show, Generic) deriving newtype (Semigroup, Monoid) deriving (Arbitrary) via (GenericUniform ClientCapabilityList) deriving (ToJSON, FromJSON, Swagger.ToSchema) via (Schema ClientCapabilityList) instance ToSchema ClientCapabilityList where schema = object "ClientCapabilityList" $ ClientCapabilityList <$> fromClientCapabilityList .= fmap runIdentity capabilitiesFieldSchema capabilitiesFieldSchema :: FieldFunctor SwaggerDoc f => ObjectSchemaP SwaggerDoc (Set ClientCapability) (f (Set ClientCapability)) capabilitiesFieldSchema = Set.toList .= fieldWithDocModifierF "capabilities" mods (Set.fromList <$> array schema) where mods = description ?~ "Hints provided by the client for the backend so it can \ \behave in a backwards-compatible way." newtype UserClientMap a = UserClientMap { userClientMap :: Map UserId (Map ClientId a) } deriving stock (Eq, Show, Functor, Foldable, Traversable) deriving newtype (Semigroup, Monoid) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema (UserClientMap a) instance ToSchema a => ToSchema (UserClientMap a) where schema = userClientMapSchema schema class WrapName doc where wrapName :: doc -> (Text -> Text) -> SwaggerDoc -> doc instance WrapName SwaggerDoc where wrapName _ _ = id instance WrapName NamedSwaggerDoc where wrapName d f = fmap (Swagger.NamedSchema (Just (f (maybe "" ("_" <>) (getName d))))) userClientMapSchema :: (WrapName doc, HasSchemaRef doc) => ValueSchema doc a -> ValueSchema doc (UserClientMap a) userClientMapSchema sch = over doc (wrapName (schemaDoc sch) ("UserClientMap" <>)) $ UserClientMap <$> userClientMap .= map_ (map_ sch) newtype UserClientPrekeyMap = UserClientPrekeyMap {getUserClientPrekeyMap :: UserClientMap (Maybe Prekey)} deriving stock (Eq, Show) deriving newtype (Arbitrary, Semigroup, Monoid) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema UserClientPrekeyMap mkUserClientPrekeyMap :: Map UserId (Map ClientId (Maybe Prekey)) -> UserClientPrekeyMap mkUserClientPrekeyMap = coerce instance ToSchema UserClientPrekeyMap where schema = UserClientPrekeyMap <$> getUserClientPrekeyMap .= addDoc sch where sch = named "UserClientPrekeyMap" $ userClientMapSchema (nullable (unnamed schema)) addDoc = Swagger.schema . Swagger.example ?~ toJSON ( Map.singleton (generateExample @UserId) ( Map.singleton (newClientId 4940483633899001999) (Just (Prekey (PrekeyId 1) "pQABAQECoQBYIOjl7hw0D8YRNq...")) ) ) instance Arbitrary a => Arbitrary (UserClientMap a) where arbitrary = UserClientMap <$> mapOf' arbitrary (mapOf' arbitrary arbitrary) newtype QualifiedUserClientMap a = QualifiedUserClientMap { qualifiedUserClientMap :: Map Domain (Map UserId (Map ClientId a)) } deriving stock (Eq, Show, Functor) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema (QualifiedUserClientMap a) instance Semigroup a => Semigroup (QualifiedUserClientMap a) where (QualifiedUserClientMap m1) <> (QualifiedUserClientMap m2) = QualifiedUserClientMap $ Map.unionWith (Map.unionWith (Map.unionWith (<>))) m1 m2 instance Semigroup (QualifiedUserClientMap a) => Monoid (QualifiedUserClientMap a) where mempty = QualifiedUserClientMap mempty instance Arbitrary a => Arbitrary (QualifiedUserClientMap a) where arbitrary = QualifiedUserClientMap <$> mapOf' arbitrary (mapOf' arbitrary (mapOf' arbitrary arbitrary)) instance ToSchema a => ToSchema (QualifiedUserClientMap a) where schema = qualifiedUserClientMapSchema schema qualifiedUserClientMapSchema :: ValueSchema NamedSwaggerDoc a -> ValueSchema NamedSwaggerDoc (QualifiedUserClientMap a) qualifiedUserClientMapSchema sch = addDoc . named nm $ QualifiedUserClientMap <$> qualifiedUserClientMap .= map_ (map_ (map_ sch)) where innerSchema = userClientMapSchema sch nm = "QualifiedUserClientMap" <> maybe "" ("_" <>) (getName (schemaDoc sch)) addDoc = Swagger.schema . Swagger.example ?~ toJSON ( Map.singleton ("domain1.example.com" :: Text) (schemaDoc innerSchema ^. Swagger.schema . Swagger.example) ) newtype QualifiedUserClientPrekeyMap = QualifiedUserClientPrekeyMap {getQualifiedUserClientPrekeyMap :: QualifiedUserClientMap (Maybe Prekey)} deriving stock (Eq, Show) deriving newtype (Arbitrary) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema QualifiedUserClientPrekeyMap deriving (Semigroup, Monoid) via (QualifiedUserClientMap (Alt Maybe Prekey)) instance ToSchema QualifiedUserClientPrekeyMap where schema = named "QualifiedUserClientPrekeyMap" $ mkQualifiedUserClientPrekeyMap <$> unmk .= map_ schema where unmk :: QualifiedUserClientPrekeyMap -> Map Domain UserClientPrekeyMap unmk = coerce mkQualifiedUserClientPrekeyMap :: Map Domain UserClientPrekeyMap -> QualifiedUserClientPrekeyMap mkQualifiedUserClientPrekeyMap = coerce qualifiedUserClientPrekeyMapFromList :: [Qualified UserClientPrekeyMap] -> QualifiedUserClientPrekeyMap qualifiedUserClientPrekeyMapFromList = mkQualifiedUserClientPrekeyMap . Map.fromList . map qToPair ClientInfo data ClientInfo = ClientInfo ciId :: ClientId, | Whether this client is MLS - capable . ciMLS :: Bool } deriving stock (Eq, Ord, Show) deriving (Swagger.ToSchema, FromJSON, ToJSON) via Schema ClientInfo instance ToSchema ClientInfo where schema = object "ClientInfo" $ ClientInfo <$> ciId .= field "id" schema <*> ciMLS .= field "mls" schema UserClients newtype UserClientsFull = UserClientsFull { userClientsFull :: Map UserId (Set Client) } deriving stock (Eq, Show, Generic) deriving newtype (Semigroup, Monoid) instance ToJSON UserClientsFull where toJSON = toJSON . Map.foldrWithKey' fn Map.empty . userClientsFull where fn u c m = let k = Text.E.decodeLatin1 (toASCIIBytes (toUUID u)) in Map.insert k c m instance FromJSON UserClientsFull where parseJSON = A.withObject "UserClientsFull" (fmap UserClientsFull . foldrM fn Map.empty . KeyMap.toList) where fn (k, v) m = Map.insert <$> parseJSON (A.String $ Key.toText k) <*> parseJSON v <*> pure m instance Arbitrary UserClientsFull where arbitrary = UserClientsFull <$> mapOf' arbitrary (setOf' arbitrary) userClientsFullToUserClients :: UserClientsFull -> UserClients userClientsFullToUserClients (UserClientsFull mp) = UserClients $ Set.map clientId <$> mp newtype UserClients = UserClients { userClients :: Map UserId (Set ClientId) } deriving stock (Eq, Show, Generic) deriving newtype (Semigroup, Monoid) deriving (ToJSON, FromJSON, Swagger.ToSchema) via Schema UserClients mkUserClients :: [(UserId, [ClientId])] -> UserClients mkUserClients xs = UserClients $ Map.fromList (xs <&> second Set.fromList) instance ToSchema UserClients where schema = addDoc . named "UserClients" $ UserClients <$> userClients .= map_ (set schema) where addDoc sch = sch & Swagger.schema . Swagger.description ?~ "Map of user id to list of client ids." & Swagger.schema . Swagger.example ?~ toJSON ( Map.fromList [ (generateExample @UserId, [newClientId 1684636986166846496, newClientId 4940483633899001999]), (generateExample @UserId, [newClientId 6987438498444556166, newClientId 7940473633839002939]) ] ) instance Arbitrary UserClients where arbitrary = UserClients <$> mapOf' arbitrary (setOf' arbitrary) filterClients :: (Set ClientId -> Bool) -> UserClients -> UserClients filterClients p (UserClients c) = UserClients $ Map.filter p c filterClientsFull :: (Set Client -> Bool) -> UserClientsFull -> UserClientsFull filterClientsFull p (UserClientsFull c) = UserClientsFull $ Map.filter p c newtype QualifiedUserClients = QualifiedUserClients { qualifiedUserClients :: Map Domain (Map UserId (Set ClientId)) } deriving stock (Eq, Show, Generic) deriving (FromJSON, ToJSON, Swagger.ToSchema) via (Schema QualifiedUserClients) instance Semigroup QualifiedUserClients where (QualifiedUserClients m1) <> (QualifiedUserClients m2) = QualifiedUserClients $ Map.unionWith (Map.unionWith (<>)) m1 m2 instance Monoid QualifiedUserClients where mempty = QualifiedUserClients mempty instance Arbitrary QualifiedUserClients where arbitrary = QualifiedUserClients <$> mapOf' arbitrary (mapOf' arbitrary (setOf' arbitrary)) instance ToSchema QualifiedUserClients where schema = addDoc . named "QualifiedUserClients" $ QualifiedUserClients <$> qualifiedUserClients .= map_ (map_ (set schema)) where addDoc sch = sch & Swagger.schema . Swagger.description ?~ "Map of Domain to UserClients" & Swagger.schema . Swagger.example ?~ toJSON ( Map.singleton ("domain1.example.com" :: Text) (view (Swagger.schema . Swagger.example) (schema @UserClients)) ) data Client = Client { clientId :: ClientId, clientType :: ClientType, clientTime :: UTCTimeMillis, clientClass :: Maybe ClientClass, clientLabel :: Maybe Text, clientCookie :: Maybe CookieLabel, clientLocation :: Maybe Location, clientModel :: Maybe Text, clientCapabilities :: ClientCapabilityList, clientMLSPublicKeys :: MLSPublicKeys } deriving stock (Eq, Show, Generic, Ord) deriving (Arbitrary) via (GenericUniform Client) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema Client type MLSPublicKeys = Map SignatureSchemeTag ByteString mlsPublicKeysSchema :: ValueSchema NamedSwaggerDoc MLSPublicKeys mlsPublicKeysSchema = mapSchema & doc %~ ( (description ?~ "Mapping from signature scheme (tags) to public key data") . (example ?~ toJSON (Map.fromList $ map (,exampleValue) keys)) ) & named "MLSPublicKeys" where keys :: [SignatureSchemeTag] keys = [minBound .. maxBound] exampleValue :: A.Value exampleValue = fromMaybe (toJSON ("base64==" :: Text)) (base64Schema ^. doc . example) mapSchema :: ValueSchema SwaggerDoc MLSPublicKeys mapSchema = map_ base64Schema instance ToSchema Client where schema = object "Client" $ Client <$> clientId .= field "id" schema <*> clientType .= field "type" schema <*> clientTime .= field "time" schema <*> clientClass .= maybe_ (optField "class" schema) <*> clientLabel .= maybe_ (optField "label" schema) <*> clientCookie .= maybe_ (optField "cookie" schema) <*> clientLocation .= maybe_ (optField "location" schema) <*> clientModel .= maybe_ (optField "model" schema) <*> clientCapabilities .= (fromMaybe mempty <$> optField "capabilities" schema) <*> clientMLSPublicKeys .= mlsPublicKeysFieldSchema mlsPublicKeysFieldSchema :: ObjectSchema SwaggerDoc MLSPublicKeys mlsPublicKeysFieldSchema = fromMaybe mempty <$> optField "mls_public_keys" mlsPublicKeysSchema PubClient data PubClient = PubClient { pubClientId :: ClientId, pubClientClass :: Maybe ClientClass } deriving stock (Eq, Show, Generic, Ord) deriving (Arbitrary) via (GenericUniform PubClient) deriving (Swagger.ToSchema) via (CustomSwagger '[FieldLabelModifier (StripPrefix "pubClient", LowerCase)] PubClient) instance ToJSON PubClient where toJSON c = A.object $ "id" A..= pubClientId c # "class" A..= pubClientClass c # [] instance FromJSON PubClient where parseJSON = A.withObject "PubClient" $ \o -> PubClient <$> o A..: "id" <*> o A..:? "class" data ClientType = TemporaryClientType | PermanentClientType see Note [ LegalHold ] deriving stock (Eq, Ord, Show, Generic) deriving (Arbitrary) via (GenericUniform ClientType) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema ClientType instance ToSchema ClientType where schema = enum @Text "ClientType" $ element "temporary" TemporaryClientType <> element "permanent" PermanentClientType <> element "legalhold" LegalHoldClientType data ClientClass = PhoneClient | TabletClient | DesktopClient see Note [ LegalHold ] deriving stock (Eq, Ord, Show, Generic) deriving (Arbitrary) via (GenericUniform ClientClass) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema ClientClass instance ToSchema ClientClass where schema = enum @Text "ClientClass" $ element "phone" PhoneClient <> element "tablet" TabletClient <> element "desktop" DesktopClient <> element "legalhold" LegalHoldClient NewClient data NewClient = NewClient { newClientPrekeys :: [Prekey], newClientLastKey :: LastPrekey, newClientType :: ClientType, newClientLabel :: Maybe Text, newClientClass :: Maybe ClientClass, newClientCookie :: Maybe CookieLabel, newClientPassword :: Maybe PlainTextPassword, newClientModel :: Maybe Text, newClientCapabilities :: Maybe (Set ClientCapability), newClientMLSPublicKeys :: MLSPublicKeys, newClientVerificationCode :: Maybe Code.Value } deriving stock (Eq, Show, Generic) deriving (Arbitrary) via (GenericUniform NewClient) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema NewClient instance ToSchema NewClient where schema = object "NewClient" $ NewClient <$> newClientPrekeys .= fieldWithDocModifier "prekeys" (description ?~ "Prekeys for other clients to establish OTR sessions.") (array schema) <*> newClientLastKey .= fieldWithDocModifier "lastkey" ( description ?~ "The last resort prekey for other clients to establish OTR sessions. \ \This key must have the ID 0xFFFF and is never deleted." ) schema <*> newClientType .= fieldWithDocModifier "type" ( description ?~ "The type of client to register. A user may have no more than \ \7 (seven) permanent clients and 1 (one) temporary client. When the \ \limit of permanent clients is reached, an error is returned. \ \When a temporary client already exists, it is replaced." ) schema <*> newClientLabel .= maybe_ (optField "label" schema) <*> newClientClass .= maybe_ ( optFieldWithDocModifier "class" ( description ?~ "The device class this client belongs to. \ \Either 'phone', 'tablet', or 'desktop'." ) schema ) <*> newClientCookie .= maybe_ ( optFieldWithDocModifier "cookie" (description ?~ "The cookie label, i.e. the label used when logging in.") schema ) <*> newClientPassword .= maybe_ ( optFieldWithDocModifier "password" ( description ?~ "The password of the authenticated user for verification. \ \Note: Required for registration of the 2nd, 3rd, ... client." ) schema ) <*> newClientModel .= maybe_ (optField "model" schema) <*> newClientCapabilities .= maybe_ capabilitiesFieldSchema <*> newClientMLSPublicKeys .= mlsPublicKeysFieldSchema <*> newClientVerificationCode .= maybe_ (optField "verification_code" schema) newClient :: ClientType -> LastPrekey -> NewClient newClient t k = NewClient { newClientPrekeys = [], newClientLastKey = k, newClientType = t, newClientLabel = Nothing, newClientClass = if t == LegalHoldClientType then Just LegalHoldClient else Nothing, newClientCookie = Nothing, newClientPassword = Nothing, newClientModel = Nothing, newClientCapabilities = Nothing, newClientMLSPublicKeys = mempty, newClientVerificationCode = Nothing } UpdateClient data UpdateClient = UpdateClient { updateClientPrekeys :: [Prekey], updateClientLastKey :: Maybe LastPrekey, updateClientLabel :: Maybe Text, | see for ' ClientCapability ' updateClientCapabilities :: Maybe (Set ClientCapability), updateClientMLSPublicKeys :: MLSPublicKeys } deriving stock (Eq, Show, Generic) deriving (Arbitrary) via (GenericUniform UpdateClient) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema UpdateClient defUpdateClient :: UpdateClient defUpdateClient = UpdateClient { updateClientPrekeys = [], updateClientLastKey = Nothing, updateClientLabel = Nothing, updateClientCapabilities = Nothing, updateClientMLSPublicKeys = mempty } instance ToSchema UpdateClient where schema = object "UpdateClient" $ UpdateClient <$> updateClientPrekeys .= ( fromMaybe [] <$> optFieldWithDocModifier "prekeys" (description ?~ "New prekeys for other clients to establish OTR sessions.") (array schema) ) <*> updateClientLastKey .= maybe_ ( optFieldWithDocModifier "lastkey" (description ?~ "New last-resort prekey.") schema ) <*> updateClientLabel .= maybe_ ( optFieldWithDocModifier "label" (description ?~ "A new name for this client.") schema ) <*> updateClientCapabilities .= maybe_ capabilitiesFieldSchema <*> updateClientMLSPublicKeys .= mlsPublicKeysFieldSchema newtype RmClient = RmClient { rmPassword :: Maybe PlainTextPassword } deriving stock (Eq, Show, Generic) deriving newtype (Arbitrary) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema RmClient instance ToSchema RmClient where schema = object "DeleteClient" $ RmClient <$> rmPassword .= optFieldWithDocModifier "password" ( description ?~ "The password of the authenticated user for verification. \ \The password is not required for deleting temporary clients." ) (maybeWithDefault A.Null schema)
de2a17faef92c932e7770ac05bd832149cff6ec0bdd05b210a77156e6824cf3f
CSCfi/rems
test_end_to_end.clj
(ns ^:integration rems.api.test-end-to-end "Go from zero to an approved application via the API. Check that all side-effects happen." (:require [clojure.test :refer :all] [rems.api.testing :refer :all] [rems.application.approver-bot :as approver-bot] [rems.application.bona-fide-bot :as bona-fide-bot] [rems.application.rejecter-bot :as rejecter-bot] [rems.db.api-key :as api-key] [rems.db.applications :as applications] [rems.db.entitlements :as entitlements] [rems.db.test-data-helpers :as test-helpers] [rems.email.core :as email] [rems.event-notification :as event-notification] [rems.json :as json] [stub-http.core :as stub])) (use-fixtures :each api-fixture) (defn extract-id [resp] (assert-success resp) (let [id (:id resp)] (assert (number? id) (pr-str resp)) id)) (deftest test-end-to-end (testing "clear poller backlog" (email/try-send-emails!) (entitlements/process-outbox!) (event-notification/process-outbox!)) (with-open [entitlements-server (stub/start! {"/add" {:status 200} "/remove" {:status 200}}) event-server (stub/start! {"/event" {:status 200}})] TODO should test emails with a mock smtp server (let [email-atom (atom [])] (with-redefs [rems.config/env (assoc rems.config/env :smtp-host "localhost" :smtp-port 25 :languages [:en] :mail-from "" :oidc-extra-attributes [{:attribute "ssn"}] :entitlements-target {:add (str (:uri entitlements-server) "/add") :remove (str (:uri entitlements-server) "/remove")} :event-notification-targets [{:url (str (:uri event-server) "/event") :event-types [:application.event/created :application.event/submitted :application.event/approved]}]) postal.core/send-message (fn [_host message] (swap! email-atom conj message))] (let [api-key "42" owner-id "owner" handler-id "e2e-handler" handler-attributes {:userid handler-id :name "E2E Handler" :email "" :ssn "111111-2222"} applicant-id "e2e-applicant" applicant-attributes {:userid applicant-id :name "E2E Applicant" :email "" :ssn "012345-0123"}] (testing "create owner & api key" (test-helpers/create-user! {:userid owner-id} :owner) (api-key/add-api-key! api-key)) (testing "create organization" (api-call :post "/api/organizations/create" {:organization/id "e2e" :organization/name {:fi "Päästä loppuun -testi" :en "End-to-end"} :organization/short-name {:fi "E2E" :en "E2E"} :organization/owners [] :organization/review-emails []} api-key owner-id)) (testing "create users" (api-call :post "/api/users/create" handler-attributes api-key owner-id) (api-call :post "/api/users/create" applicant-attributes api-key owner-id)) (let [resource-ext-id "e2e-resource" resource-id (testing "create resource" (extract-id (api-call :post "/api/resources/create" {:resid resource-ext-id :organization {:organization/id "e2e"} :licenses []} api-key owner-id))) resource-ext-id2 "e2e-resource 2" resource-id2 (testing "create resource 2" (extract-id (api-call :post "/api/resources/create" {:resid resource-ext-id2 :organization {:organization/id "e2e"} :licenses []} api-key owner-id))) wf-form-id (testing "create workflow form" (extract-id (api-call :post "/api/forms/create" {:organization {:organization/id "e2e"} :form/internal-name "e2e wf" :form/external-title {:en "en e2e wf" :fi "fi e2e wf" :sv "sv e2e wf"} :form/fields [{:field/id "description" :field/type :description :field/title {:en "text field" :fi "tekstikenttä" :sv "textfält"} :field/optional false}]} api-key owner-id))) form-id (testing "create form" (extract-id (api-call :post "/api/forms/create" {:organization {:organization/id "e2e"} :form/internal-name "e2e" :form/external-title {:en "en e2e" :fi "fi e2e" :sv "en e2e"} :form/fields [{:field/type :text :field/title {:en "text field" :fi "tekstikenttä" :sv "tekstfält"} :field/optional false}]} api-key owner-id))) form-id2 (testing "create form 2" (extract-id (api-call :post "/api/forms/create" {:organization {:organization/id "e2e"} :form/internal-name "e2e 2" :form/external-title {:en "en e2e 2" :fi "fi e2e 2" :sv "en e2e 2"} :form/fields [{:field/id "e2e_fld_2" :field/type :text :field/title {:en "text field 2" :fi "tekstikenttä 2" :sv "textfält 2"} :field/optional true}]} api-key owner-id))) license-id (testing "create license" (extract-id (api-call :post "/api/licenses/create" {:licensetype "link" :organization {:organization/id "e2e"} :localizations {:en {:title "e2e license" :textcontent ""}}} api-key owner-id))) workflow-id (testing "create workflow" (extract-id (api-call :post "/api/workflows/create" {:organization {:organization/id "e2e"} :title "e2e workflow" :type :workflow/default :forms [{:form/id wf-form-id} {:form/id form-id}] :handlers [handler-id]} api-key owner-id))) catalogue-item-id (testing "create catalogue item" (extract-id (api-call :post "/api/catalogue-items/create" {:resid resource-id :form form-id :wfid workflow-id :organization {:organization/id "e2e"} :localizations {:en {:title "e2e catalogue item"}}} api-key owner-id))) catalogue-item-id2 (testing "create catalogue item 2" (extract-id (api-call :post "/api/catalogue-items/create" {:resid resource-id2 :form form-id2 :wfid workflow-id :organization {:organization/id "e2e"} :localizations {:en {:title "e2e catalogue item 2"}}} api-key owner-id))) application-id (testing "create application" (:application-id (assert-success (api-call :post "/api/applications/create" {:catalogue-item-ids [catalogue-item-id catalogue-item-id2]} api-key applicant-id))))] (testing "fetch application as applicant" (assert (number? application-id)) (let [application (api-call :get (str "/api/applications/" application-id) nil api-key applicant-id)] (is (= applicant-id (get-in application [:application/applicant :userid]))) (is (= [resource-ext-id resource-ext-id2] (mapv :resource/ext-id (:application/resources application)))) (is (= [wf-form-id form-id form-id2] (mapv :form/id (:application/forms application)))))) (testing "check that application is visible" (let [applications (api-call :get "/api/my-applications" nil api-key applicant-id)] (is (= [application-id] (mapv :application/id applications))))) (testing "fill in application" (assert-success (api-call :post "/api/applications/save-draft" {:application-id application-id :field-values [{:form wf-form-id :field "description" :value "e2e description"} {:form form-id :field "fld1" :value "e2e test contents"} {:form form-id2 :field "e2e_fld_2" :value "e2e test contents 2"}]} api-key applicant-id))) (testing "accept terms of use" (assert-success (api-call :post "/api/applications/accept-licenses" {:application-id application-id :accepted-licenses [license-id]} api-key applicant-id))) (testing "submit application" (assert-success (api-call :post "/api/applications/submit" {:application-id application-id} api-key applicant-id))) ;; we could start the pollers normally and wait for them to process the events here for better coverage (email/try-send-emails!) (testing "email for new application" (let [mail (last @email-atom)] (is (= "" (:to mail))) (is (.contains (:subject mail) "new application")) (is (.startsWith (:body mail) "Dear E2E Handler,"))) (reset! email-atom [])) (testing "no entitlement yet" (let [entitlements (api-call :get "/api/entitlements" nil api-key owner-id) applications (set (map :application-id entitlements))] (is (not (contains? applications application-id))))) (testing "fetch application as handler" (let [applications (api-call :get "/api/applications/todo" nil api-key handler-id) todos (set (map (juxt :application/id :application/todo) applications))] (is (contains? todos [application-id "new-application"]))) (let [application (api-call :get (str "/api/applications/" application-id) nil api-key handler-id)] (is (= ["e2e description" "e2e test contents" "e2e test contents 2"] (for [form (:application/forms application) field (:form/fields form)] (:field/value field)))) (is (= [license-id] (get-in application [:application/accepted-licenses (keyword applicant-id)])) application) (testing ": can see extra attributes for applicant" (is (= {:userid "e2e-applicant" :name "E2E Applicant" :email "" :ssn "012345-0123"} (:application/applicant application)))))) (testing "approve application" (assert-success (api-call :post "/api/applications/approve" {:application-id application-id :comment "e2e approved"} api-key handler-id))) (email/try-send-emails!) (entitlements/process-outbox!) (testing "email for approved application" (let [mail (last @email-atom)] (is (= "" (:to mail))) (is (.contains (:subject mail) "approved")) (is (.startsWith (:body mail) "Dear E2E Applicant,"))) (reset! email-atom [])) (testing "entitlement" (testing "visible via API" (let [[entitlement entitlement2 & others] (api-call :get (str "/api/entitlements?user=" applicant-id) nil api-key owner-id)] (is (empty? others)) (is (= resource-ext-id (:resource entitlement))) (is (= resource-ext-id2 (:resource entitlement2))) (is (not (:end entitlement))) (is (not (:end entitlement2))))) (testing "POSTed to callback" (let [[req req2 & others] (stub/recorded-requests entitlements-server)] (is (empty? others)) (is (= "/add" (:path req))) (is (= "/add" (:path req2))) (is (= #{{:application application-id :mail "" :resource resource-ext-id :user applicant-id :end nil} {:application application-id :mail "" :resource resource-ext-id2 :user applicant-id :end nil}} (set (concat (json/parse-string (get-in req [:body "postData"])) (json/parse-string (get-in req2 [:body "postData"]))))))))) (testing "close application" (assert-success (api-call :post "/api/applications/close" {:application-id application-id :comment "e2e closed"} api-key handler-id))) (email/try-send-emails!) (entitlements/process-outbox!) (testing "ended entitlement" (testing "visible via API" (let [[entitlement entitlement2 & others] (api-call :get (str "/api/entitlements?expired=true&user=" applicant-id) nil api-key owner-id)] (is (empty? others)) (is (= resource-ext-id (:resource entitlement))) (is (:end entitlement) entitlement) (is (= resource-ext-id2 (:resource entitlement2))) (is (:end entitlement2) entitlement2))) (testing "POSTed to callback" (let [[_old _old2 req req2 & others] (stub/recorded-requests entitlements-server) [body] (json/parse-string (get-in req [:body "postData"])) [body2] (json/parse-string (get-in req2 [:body "postData"]))] (is (empty? others)) (is (= "/remove" (:path req))) (is (= "/remove" (:path req2))) (is (= application-id (:application body) (:application body2))) (is (= applicant-id (:user body) (:user body2))) (is (= "" (:mail body) (:mail body2))) (is (:end body)) (is (:end body2)) (is (= #{resource-ext-id resource-ext-id2} (set [(:resource body) (:resource body2)])))))) (testing "fetch application as applicant" (let [application (api-call :get (str "/api/applications/" application-id) nil api-key applicant-id)] (is (= "application.state/closed" (:application/state application))) (testing "can't see handler extra attributes" (is (= {:userid "e2e-handler" :name "E2E Handler" :email ""} (:event/actor-attributes (last (:application/events application)))))))) (event-notification/process-outbox!) (testing "event notifications" (let [requests (stub/recorded-requests event-server) events (for [r requests] (-> r :body (get "content") json/parse-string (select-keys [:application/id :event/type :event/actor :application/resources :application/forms :event/application]) (update :event/application select-keys [:application/id :application/state])))] (is (every? (comp #{"PUT"} :method) requests)) (is (= [{:application/id application-id :event/type "application.event/created" :event/actor applicant-id :application/resources [{:resource/ext-id resource-ext-id :catalogue-item/id catalogue-item-id} {:resource/ext-id resource-ext-id2 :catalogue-item/id catalogue-item-id2}] :application/forms [{:form/id wf-form-id} {:form/id form-id} {:form/id form-id2}] :event/application {:application/id application-id :application/state "application.state/draft"}} {:application/id application-id :event/type "application.event/submitted" :event/actor applicant-id :event/application {:application/id application-id :application/state "application.state/submitted"}} {:application/id application-id :event/type "application.event/approved" :event/actor handler-id :event/application {:application/id application-id :application/state "application.state/approved"}}] events)))))))))) (deftest test-approver-rejecter-bots (let [api-key "42" owner-id "owner" handler-id "e2e-handler" handler-attributes {:userid handler-id :name "E2E Handler" :email ""} applicant-id "e2e-applicant" applicant-attributes {:userid applicant-id :name "E2E Applicant" :email ""} approver-attributes {:userid approver-bot/bot-userid :email nil :name "approver"} rejecter-attributes {:userid rejecter-bot/bot-userid :email nil :name "rejecter"}] (testing "create owner & api key" (test-helpers/create-user! {:userid owner-id} :owner) (api-key/add-api-key! api-key)) (testing "create users" (api-call :post "/api/users/create" handler-attributes api-key owner-id) (api-call :post "/api/users/create" applicant-attributes api-key owner-id) (api-call :post "/api/users/create" approver-attributes api-key owner-id) (api-call :post "/api/users/create" rejecter-attributes api-key owner-id)) (let [resource-ext-id "e2e-resource" resource-id (testing "create resource" (extract-id (api-call :post "/api/resources/create" {:resid resource-ext-id :organization {:organization/id "e2e"} :licenses []} api-key owner-id))) form-id (testing "create form" (extract-id (api-call :post "/api/forms/create" {:organization {:organization/id "e2e"} :form/internal-name "e2e" :form/external-title {:en "en e2e" :fi "fi e2e" :sv "en e2e"} :form/fields [{:field/type :text :field/title {:en "text field" :fi "tekstikenttä" :sv "textfält"} :field/optional true}]} api-key owner-id))) workflow-id (testing "create workflow" (extract-id (api-call :post "/api/workflows/create" {:organization {:organization/id "e2e"} :title "e2e workflow" :type :workflow/default :handlers [handler-id approver-bot/bot-userid rejecter-bot/bot-userid]} api-key owner-id))) catalogue-item-id (testing "create catalogue item" (extract-id (api-call :post "/api/catalogue-items/create" {:organization {:organization/id "e2e"} :resid resource-id :form form-id :wfid workflow-id :localizations {:en {:title "e2e catalogue item"}}} api-key owner-id)))] (testing "autoapproved application:" (let [application-id (testing "create application" (:application-id (assert-success (api-call :post "/api/applications/create" {:catalogue-item-ids [catalogue-item-id]} api-key applicant-id))))] (testing "submit application" (assert-success (api-call :post "/api/applications/submit" {:application-id application-id} api-key applicant-id))) (testing "application approved" (let [application (api-call :get (str "/api/applications/" application-id) nil api-key applicant-id)] (is (= "application.state/approved" (:application/state application))))) (testing "entitlement visible via API" (let [[entitlement & others] (api-call :get (str "/api/entitlements?user=" applicant-id) nil api-key owner-id)] (is (empty? others)) (is (= resource-ext-id (:resource entitlement))) (is (not (:end entitlement))))) (testing "revoke" (assert-success (api-call :post "/api/applications/revoke" {:application-id application-id :comment "revoke"} api-key handler-id))) (testing "entitlement ended" (let [[entitlement & others] (api-call :get (str "/api/entitlements?expired=true&user=" applicant-id) nil api-key owner-id)] (is (empty? others)) (is (= resource-ext-id (:resource entitlement))) (is (:end entitlement)))) (testing "user blacklisted" (let [[entry & _] (api-call :get (str "/api/blacklist?user=" applicant-id "&resource=" resource-ext-id) nil api-key handler-id)] (is (= {:resource/ext-id resource-ext-id} (:blacklist/resource entry))) (is (= applicant-id (:userid (:blacklist/user entry)))))))) (testing "second application" (let [application-id (testing "create application" (:application-id (assert-success (api-call :post "/api/applications/create" {:catalogue-item-ids [catalogue-item-id]} api-key applicant-id))))] (testing "submit application" (assert-success (api-call :post "/api/applications/submit" {:application-id application-id} api-key applicant-id))) (testing "application rejected" (let [application (api-call :get (str "/api/applications/" application-id) nil api-key applicant-id)] (is (= "application.state/rejected" (:application/state application))))) (testing "blacklist visible to handler in application" (let [application (api-call :get (str "/api/applications/" application-id) nil api-key handler-id)] (is (= [{:blacklist/user applicant-attributes :blacklist/resource {:resource/ext-id resource-ext-id}}] (:application/blacklist application)))))))))) (deftest test-blacklisting (let [api-key "42" owner-id "owner" handler-id "e2e-handler" handler-attributes {:userid handler-id :name "E2E Handler" :email ""} applicant-id "e2e-applicant" applicant-attributes {:userid applicant-id :name "E2E Applicant" :email ""} rejecter-attributes {:userid rejecter-bot/bot-userid :email nil :name "rejecter"}] (testing "create owner & api key" (test-helpers/create-user! {:userid owner-id} :owner) (api-key/add-api-key! api-key)) (testing "create users" (api-call :post "/api/users/create" handler-attributes api-key owner-id) (api-call :post "/api/users/create" applicant-attributes api-key owner-id) (api-call :post "/api/users/create" rejecter-attributes api-key owner-id)) (let [resource-ext-id "e2e-resource" resource-id (testing "create resource" (extract-id (api-call :post "/api/resources/create" {:resid resource-ext-id :organization {:organization/id "e2e"} :licenses []} api-key owner-id))) form-id (testing "create form" (extract-id (api-call :post "/api/forms/create" {:organization {:organization/id "e2e"} :form/internal-name "e2e" :form/external-title {:en "en e2e" :fi "fi e2e" :sv "en e2e"} :form/fields [{:field/type :text :field/title {:en "text field" :fi "tekstikenttä" :sv "textfält"} :field/optional true}]} api-key owner-id))) workflow-id (testing "create workflow" (extract-id (api-call :post "/api/workflows/create" {:organization {:organization/id "e2e"} :title "e2e workflow" :type :workflow/default :handlers [handler-id rejecter-bot/bot-userid]} api-key owner-id))) catalogue-item-id (testing "create catalogue item" (extract-id (api-call :post "/api/catalogue-items/create" {:organization {:organization/id "e2e"} :resid resource-id :form form-id :wfid workflow-id :localizations {:en {:title "e2e catalogue item"}}} api-key owner-id))) app-1 (testing "create first application" (:application-id (assert-success (api-call :post "/api/applications/create" {:catalogue-item-ids [catalogue-item-id]} api-key applicant-id)))) app-2 (testing "create second application" (:application-id (assert-success (api-call :post "/api/applications/create" {:catalogue-item-ids [catalogue-item-id]} api-key applicant-id))))] (testing "submit first application" (assert-success (api-call :post "/api/applications/submit" {:application-id app-1} api-key applicant-id))) (testing "second application" (testing "submit" (assert-success (api-call :post "/api/applications/submit" {:application-id app-2} api-key applicant-id))) (testing "approve" (assert-success (api-call :post "/api/applications/approve" {:application-id app-2} api-key handler-id))) (testing "revoke" (assert-success (api-call :post "/api/applications/revoke" {:application-id app-2 :comment "revoke"} api-key handler-id)))) (testing "user blacklisted" (let [[entry & _] (api-call :get (str "/api/blacklist?user=" applicant-id "&resource=" resource-ext-id) nil api-key handler-id)] (is (= {:resource/ext-id resource-ext-id} (:blacklist/resource entry))) (is (= applicant-id (:userid (:blacklist/user entry)))))) (testing "first application rejected" (let [application (api-call :get (str "/api/applications/" app-1) nil api-key applicant-id)] (is (= "application.state/rejected" (:application/state application))))) (testing "new applications gets automatically rejected" (let [app-3 (:application-id (assert-success (api-call :post "/api/applications/create" {:catalogue-item-ids [catalogue-item-id]} api-key applicant-id)))] (assert-success (api-call :post "/api/applications/submit" {:application-id app-3} api-key applicant-id)) (let [application (api-call :get (str "/api/applications/" app-3) nil api-key applicant-id)] (is (= "application.state/rejected" (:application/state application)))))) (testing "remove blacklist entry" (assert-success (api-call :post "/api/blacklist/remove" {:blacklist/user {:userid applicant-id} :blacklist/resource {:resource/ext-id resource-ext-id} :comment "good"} api-key handler-id))) (let [app-3 (testing "create third application" (:application-id (assert-success (api-call :post "/api/applications/create" {:catalogue-item-ids [catalogue-item-id]} api-key applicant-id))))] (testing "submit third application" (assert-success (api-call :post "/api/applications/submit" {:application-id app-3} api-key applicant-id)) (testing "and it doesn't get rejected" (is (= "application.state/submitted" (:application/state (api-call :get (str "/api/applications/" app-3) nil api-key applicant-id)))))) (testing "blacklist user again" (assert-success (api-call :post "/api/blacklist/add" {:blacklist/user {:userid applicant-id} :blacklist/resource {:resource/ext-id resource-ext-id} :comment "bad"} api-key handler-id))) (testing "third application gets rejected" (testing "and it doesn't get rejected" (is (= "application.state/rejected" (:application/state (api-call :get (str "/api/applications/" app-3) nil api-key applicant-id)))))))))) (deftest test-bona-fide-bot (let [api-key "42" owner-id "owner" applicant-id "bona-fide-applicant" applicant-attributes {:userid applicant-id :name "Bona Fide Applicant" :email ""} referer-id "bona-fide-referer" referer-attributes {:userid referer-id :name "Bona Fide Referer" :email "" :researcher-status-by "so"} bot-attributes {:userid bona-fide-bot/bot-userid :email nil :name "bona fide bot"}] (testing "create owner & api key" (test-helpers/create-user! {:userid owner-id} :owner) (api-key/add-api-key! api-key)) (testing "create users" (api-call :post "/api/users/create" applicant-attributes api-key owner-id) (api-call :post "/api/users/create" referer-attributes api-key owner-id) (api-call :post "/api/users/create" bot-attributes api-key owner-id)) (let [resource-id (extract-id (api-call :post "/api/resources/create" {:organization {:organization/id "default"} :resid "bona fide" :licenses []} api-key owner-id)) form-id (extract-id (api-call :post "/api/forms/create" {:organization {:organization/id "default"} :form/internal-name "e2e" :form/external-title {:en "en e2e" :fi "fi e2e" :sv "en e2e"} :form/fields [{:field/type :email :field/id "referer email" :field/title {:en "referer" :fi "referer" :sv "referer"} :field/optional false}]} api-key owner-id)) workflow-id (extract-id (api-call :post "/api/workflows/create" {:organization {:organization/id "default"} :title "bona fide workflow" :type :workflow/default :handlers [bona-fide-bot/bot-userid]} api-key owner-id)) catalogue-item-id (extract-id (api-call :post "/api/catalogue-items/create" {:organization {:organization/id "default"} :resid resource-id :form form-id :wfid workflow-id :localizations {:en {:title "bona fide catalogue item"}}} api-key owner-id)) app-id (testing "create application" (:application-id (assert-success (api-call :post "/api/applications/create" {:catalogue-item-ids [catalogue-item-id]} api-key applicant-id))))] (testing "fill & submit application" (assert-success (api-call :post "/api/applications/save-draft" {:application-id app-id :field-values [{:form form-id :field "referer email" :value ""}]} api-key applicant-id)) (assert-success (api-call :post "/api/applications/submit" {:application-id app-id} api-key applicant-id))) (let [event (-> (applications/get-application-internal app-id) :application/events last) token (:invitation/token event)] (testing "check that bot has requested decision" (is (= {:event/type :application.event/decider-invited :application/id app-id :application/decider {:name "Referer" :email ""} :event/actor bona-fide-bot/bot-userid} (select-keys event [:event/type :application/id :application/decider :event/actor]))) (is (string? token))) (testing "post decision as referer" (assert-success (api-call :post (str "/api/applications/accept-invitation?invitation-token=" token) nil api-key referer-id)) (assert-success (api-call :post "/api/applications/decide" {:application-id app-id :decision :approved} api-key referer-id))) (testing "check that application was approved" (let [application (api-call :get (str "/api/applications/" app-id) nil api-key applicant-id)] (is (= "application.state/approved" (:application/state application)))))))))
null
https://raw.githubusercontent.com/CSCfi/rems/1530afdce724dd6a68b2912bc281dacec39f6cf2/test/clj/rems/api/test_end_to_end.clj
clojure
we could start the pollers normally and wait for them to process the events here for better coverage
(ns ^:integration rems.api.test-end-to-end "Go from zero to an approved application via the API. Check that all side-effects happen." (:require [clojure.test :refer :all] [rems.api.testing :refer :all] [rems.application.approver-bot :as approver-bot] [rems.application.bona-fide-bot :as bona-fide-bot] [rems.application.rejecter-bot :as rejecter-bot] [rems.db.api-key :as api-key] [rems.db.applications :as applications] [rems.db.entitlements :as entitlements] [rems.db.test-data-helpers :as test-helpers] [rems.email.core :as email] [rems.event-notification :as event-notification] [rems.json :as json] [stub-http.core :as stub])) (use-fixtures :each api-fixture) (defn extract-id [resp] (assert-success resp) (let [id (:id resp)] (assert (number? id) (pr-str resp)) id)) (deftest test-end-to-end (testing "clear poller backlog" (email/try-send-emails!) (entitlements/process-outbox!) (event-notification/process-outbox!)) (with-open [entitlements-server (stub/start! {"/add" {:status 200} "/remove" {:status 200}}) event-server (stub/start! {"/event" {:status 200}})] TODO should test emails with a mock smtp server (let [email-atom (atom [])] (with-redefs [rems.config/env (assoc rems.config/env :smtp-host "localhost" :smtp-port 25 :languages [:en] :mail-from "" :oidc-extra-attributes [{:attribute "ssn"}] :entitlements-target {:add (str (:uri entitlements-server) "/add") :remove (str (:uri entitlements-server) "/remove")} :event-notification-targets [{:url (str (:uri event-server) "/event") :event-types [:application.event/created :application.event/submitted :application.event/approved]}]) postal.core/send-message (fn [_host message] (swap! email-atom conj message))] (let [api-key "42" owner-id "owner" handler-id "e2e-handler" handler-attributes {:userid handler-id :name "E2E Handler" :email "" :ssn "111111-2222"} applicant-id "e2e-applicant" applicant-attributes {:userid applicant-id :name "E2E Applicant" :email "" :ssn "012345-0123"}] (testing "create owner & api key" (test-helpers/create-user! {:userid owner-id} :owner) (api-key/add-api-key! api-key)) (testing "create organization" (api-call :post "/api/organizations/create" {:organization/id "e2e" :organization/name {:fi "Päästä loppuun -testi" :en "End-to-end"} :organization/short-name {:fi "E2E" :en "E2E"} :organization/owners [] :organization/review-emails []} api-key owner-id)) (testing "create users" (api-call :post "/api/users/create" handler-attributes api-key owner-id) (api-call :post "/api/users/create" applicant-attributes api-key owner-id)) (let [resource-ext-id "e2e-resource" resource-id (testing "create resource" (extract-id (api-call :post "/api/resources/create" {:resid resource-ext-id :organization {:organization/id "e2e"} :licenses []} api-key owner-id))) resource-ext-id2 "e2e-resource 2" resource-id2 (testing "create resource 2" (extract-id (api-call :post "/api/resources/create" {:resid resource-ext-id2 :organization {:organization/id "e2e"} :licenses []} api-key owner-id))) wf-form-id (testing "create workflow form" (extract-id (api-call :post "/api/forms/create" {:organization {:organization/id "e2e"} :form/internal-name "e2e wf" :form/external-title {:en "en e2e wf" :fi "fi e2e wf" :sv "sv e2e wf"} :form/fields [{:field/id "description" :field/type :description :field/title {:en "text field" :fi "tekstikenttä" :sv "textfält"} :field/optional false}]} api-key owner-id))) form-id (testing "create form" (extract-id (api-call :post "/api/forms/create" {:organization {:organization/id "e2e"} :form/internal-name "e2e" :form/external-title {:en "en e2e" :fi "fi e2e" :sv "en e2e"} :form/fields [{:field/type :text :field/title {:en "text field" :fi "tekstikenttä" :sv "tekstfält"} :field/optional false}]} api-key owner-id))) form-id2 (testing "create form 2" (extract-id (api-call :post "/api/forms/create" {:organization {:organization/id "e2e"} :form/internal-name "e2e 2" :form/external-title {:en "en e2e 2" :fi "fi e2e 2" :sv "en e2e 2"} :form/fields [{:field/id "e2e_fld_2" :field/type :text :field/title {:en "text field 2" :fi "tekstikenttä 2" :sv "textfält 2"} :field/optional true}]} api-key owner-id))) license-id (testing "create license" (extract-id (api-call :post "/api/licenses/create" {:licensetype "link" :organization {:organization/id "e2e"} :localizations {:en {:title "e2e license" :textcontent ""}}} api-key owner-id))) workflow-id (testing "create workflow" (extract-id (api-call :post "/api/workflows/create" {:organization {:organization/id "e2e"} :title "e2e workflow" :type :workflow/default :forms [{:form/id wf-form-id} {:form/id form-id}] :handlers [handler-id]} api-key owner-id))) catalogue-item-id (testing "create catalogue item" (extract-id (api-call :post "/api/catalogue-items/create" {:resid resource-id :form form-id :wfid workflow-id :organization {:organization/id "e2e"} :localizations {:en {:title "e2e catalogue item"}}} api-key owner-id))) catalogue-item-id2 (testing "create catalogue item 2" (extract-id (api-call :post "/api/catalogue-items/create" {:resid resource-id2 :form form-id2 :wfid workflow-id :organization {:organization/id "e2e"} :localizations {:en {:title "e2e catalogue item 2"}}} api-key owner-id))) application-id (testing "create application" (:application-id (assert-success (api-call :post "/api/applications/create" {:catalogue-item-ids [catalogue-item-id catalogue-item-id2]} api-key applicant-id))))] (testing "fetch application as applicant" (assert (number? application-id)) (let [application (api-call :get (str "/api/applications/" application-id) nil api-key applicant-id)] (is (= applicant-id (get-in application [:application/applicant :userid]))) (is (= [resource-ext-id resource-ext-id2] (mapv :resource/ext-id (:application/resources application)))) (is (= [wf-form-id form-id form-id2] (mapv :form/id (:application/forms application)))))) (testing "check that application is visible" (let [applications (api-call :get "/api/my-applications" nil api-key applicant-id)] (is (= [application-id] (mapv :application/id applications))))) (testing "fill in application" (assert-success (api-call :post "/api/applications/save-draft" {:application-id application-id :field-values [{:form wf-form-id :field "description" :value "e2e description"} {:form form-id :field "fld1" :value "e2e test contents"} {:form form-id2 :field "e2e_fld_2" :value "e2e test contents 2"}]} api-key applicant-id))) (testing "accept terms of use" (assert-success (api-call :post "/api/applications/accept-licenses" {:application-id application-id :accepted-licenses [license-id]} api-key applicant-id))) (testing "submit application" (assert-success (api-call :post "/api/applications/submit" {:application-id application-id} api-key applicant-id))) (email/try-send-emails!) (testing "email for new application" (let [mail (last @email-atom)] (is (= "" (:to mail))) (is (.contains (:subject mail) "new application")) (is (.startsWith (:body mail) "Dear E2E Handler,"))) (reset! email-atom [])) (testing "no entitlement yet" (let [entitlements (api-call :get "/api/entitlements" nil api-key owner-id) applications (set (map :application-id entitlements))] (is (not (contains? applications application-id))))) (testing "fetch application as handler" (let [applications (api-call :get "/api/applications/todo" nil api-key handler-id) todos (set (map (juxt :application/id :application/todo) applications))] (is (contains? todos [application-id "new-application"]))) (let [application (api-call :get (str "/api/applications/" application-id) nil api-key handler-id)] (is (= ["e2e description" "e2e test contents" "e2e test contents 2"] (for [form (:application/forms application) field (:form/fields form)] (:field/value field)))) (is (= [license-id] (get-in application [:application/accepted-licenses (keyword applicant-id)])) application) (testing ": can see extra attributes for applicant" (is (= {:userid "e2e-applicant" :name "E2E Applicant" :email "" :ssn "012345-0123"} (:application/applicant application)))))) (testing "approve application" (assert-success (api-call :post "/api/applications/approve" {:application-id application-id :comment "e2e approved"} api-key handler-id))) (email/try-send-emails!) (entitlements/process-outbox!) (testing "email for approved application" (let [mail (last @email-atom)] (is (= "" (:to mail))) (is (.contains (:subject mail) "approved")) (is (.startsWith (:body mail) "Dear E2E Applicant,"))) (reset! email-atom [])) (testing "entitlement" (testing "visible via API" (let [[entitlement entitlement2 & others] (api-call :get (str "/api/entitlements?user=" applicant-id) nil api-key owner-id)] (is (empty? others)) (is (= resource-ext-id (:resource entitlement))) (is (= resource-ext-id2 (:resource entitlement2))) (is (not (:end entitlement))) (is (not (:end entitlement2))))) (testing "POSTed to callback" (let [[req req2 & others] (stub/recorded-requests entitlements-server)] (is (empty? others)) (is (= "/add" (:path req))) (is (= "/add" (:path req2))) (is (= #{{:application application-id :mail "" :resource resource-ext-id :user applicant-id :end nil} {:application application-id :mail "" :resource resource-ext-id2 :user applicant-id :end nil}} (set (concat (json/parse-string (get-in req [:body "postData"])) (json/parse-string (get-in req2 [:body "postData"]))))))))) (testing "close application" (assert-success (api-call :post "/api/applications/close" {:application-id application-id :comment "e2e closed"} api-key handler-id))) (email/try-send-emails!) (entitlements/process-outbox!) (testing "ended entitlement" (testing "visible via API" (let [[entitlement entitlement2 & others] (api-call :get (str "/api/entitlements?expired=true&user=" applicant-id) nil api-key owner-id)] (is (empty? others)) (is (= resource-ext-id (:resource entitlement))) (is (:end entitlement) entitlement) (is (= resource-ext-id2 (:resource entitlement2))) (is (:end entitlement2) entitlement2))) (testing "POSTed to callback" (let [[_old _old2 req req2 & others] (stub/recorded-requests entitlements-server) [body] (json/parse-string (get-in req [:body "postData"])) [body2] (json/parse-string (get-in req2 [:body "postData"]))] (is (empty? others)) (is (= "/remove" (:path req))) (is (= "/remove" (:path req2))) (is (= application-id (:application body) (:application body2))) (is (= applicant-id (:user body) (:user body2))) (is (= "" (:mail body) (:mail body2))) (is (:end body)) (is (:end body2)) (is (= #{resource-ext-id resource-ext-id2} (set [(:resource body) (:resource body2)])))))) (testing "fetch application as applicant" (let [application (api-call :get (str "/api/applications/" application-id) nil api-key applicant-id)] (is (= "application.state/closed" (:application/state application))) (testing "can't see handler extra attributes" (is (= {:userid "e2e-handler" :name "E2E Handler" :email ""} (:event/actor-attributes (last (:application/events application)))))))) (event-notification/process-outbox!) (testing "event notifications" (let [requests (stub/recorded-requests event-server) events (for [r requests] (-> r :body (get "content") json/parse-string (select-keys [:application/id :event/type :event/actor :application/resources :application/forms :event/application]) (update :event/application select-keys [:application/id :application/state])))] (is (every? (comp #{"PUT"} :method) requests)) (is (= [{:application/id application-id :event/type "application.event/created" :event/actor applicant-id :application/resources [{:resource/ext-id resource-ext-id :catalogue-item/id catalogue-item-id} {:resource/ext-id resource-ext-id2 :catalogue-item/id catalogue-item-id2}] :application/forms [{:form/id wf-form-id} {:form/id form-id} {:form/id form-id2}] :event/application {:application/id application-id :application/state "application.state/draft"}} {:application/id application-id :event/type "application.event/submitted" :event/actor applicant-id :event/application {:application/id application-id :application/state "application.state/submitted"}} {:application/id application-id :event/type "application.event/approved" :event/actor handler-id :event/application {:application/id application-id :application/state "application.state/approved"}}] events)))))))))) (deftest test-approver-rejecter-bots (let [api-key "42" owner-id "owner" handler-id "e2e-handler" handler-attributes {:userid handler-id :name "E2E Handler" :email ""} applicant-id "e2e-applicant" applicant-attributes {:userid applicant-id :name "E2E Applicant" :email ""} approver-attributes {:userid approver-bot/bot-userid :email nil :name "approver"} rejecter-attributes {:userid rejecter-bot/bot-userid :email nil :name "rejecter"}] (testing "create owner & api key" (test-helpers/create-user! {:userid owner-id} :owner) (api-key/add-api-key! api-key)) (testing "create users" (api-call :post "/api/users/create" handler-attributes api-key owner-id) (api-call :post "/api/users/create" applicant-attributes api-key owner-id) (api-call :post "/api/users/create" approver-attributes api-key owner-id) (api-call :post "/api/users/create" rejecter-attributes api-key owner-id)) (let [resource-ext-id "e2e-resource" resource-id (testing "create resource" (extract-id (api-call :post "/api/resources/create" {:resid resource-ext-id :organization {:organization/id "e2e"} :licenses []} api-key owner-id))) form-id (testing "create form" (extract-id (api-call :post "/api/forms/create" {:organization {:organization/id "e2e"} :form/internal-name "e2e" :form/external-title {:en "en e2e" :fi "fi e2e" :sv "en e2e"} :form/fields [{:field/type :text :field/title {:en "text field" :fi "tekstikenttä" :sv "textfält"} :field/optional true}]} api-key owner-id))) workflow-id (testing "create workflow" (extract-id (api-call :post "/api/workflows/create" {:organization {:organization/id "e2e"} :title "e2e workflow" :type :workflow/default :handlers [handler-id approver-bot/bot-userid rejecter-bot/bot-userid]} api-key owner-id))) catalogue-item-id (testing "create catalogue item" (extract-id (api-call :post "/api/catalogue-items/create" {:organization {:organization/id "e2e"} :resid resource-id :form form-id :wfid workflow-id :localizations {:en {:title "e2e catalogue item"}}} api-key owner-id)))] (testing "autoapproved application:" (let [application-id (testing "create application" (:application-id (assert-success (api-call :post "/api/applications/create" {:catalogue-item-ids [catalogue-item-id]} api-key applicant-id))))] (testing "submit application" (assert-success (api-call :post "/api/applications/submit" {:application-id application-id} api-key applicant-id))) (testing "application approved" (let [application (api-call :get (str "/api/applications/" application-id) nil api-key applicant-id)] (is (= "application.state/approved" (:application/state application))))) (testing "entitlement visible via API" (let [[entitlement & others] (api-call :get (str "/api/entitlements?user=" applicant-id) nil api-key owner-id)] (is (empty? others)) (is (= resource-ext-id (:resource entitlement))) (is (not (:end entitlement))))) (testing "revoke" (assert-success (api-call :post "/api/applications/revoke" {:application-id application-id :comment "revoke"} api-key handler-id))) (testing "entitlement ended" (let [[entitlement & others] (api-call :get (str "/api/entitlements?expired=true&user=" applicant-id) nil api-key owner-id)] (is (empty? others)) (is (= resource-ext-id (:resource entitlement))) (is (:end entitlement)))) (testing "user blacklisted" (let [[entry & _] (api-call :get (str "/api/blacklist?user=" applicant-id "&resource=" resource-ext-id) nil api-key handler-id)] (is (= {:resource/ext-id resource-ext-id} (:blacklist/resource entry))) (is (= applicant-id (:userid (:blacklist/user entry)))))))) (testing "second application" (let [application-id (testing "create application" (:application-id (assert-success (api-call :post "/api/applications/create" {:catalogue-item-ids [catalogue-item-id]} api-key applicant-id))))] (testing "submit application" (assert-success (api-call :post "/api/applications/submit" {:application-id application-id} api-key applicant-id))) (testing "application rejected" (let [application (api-call :get (str "/api/applications/" application-id) nil api-key applicant-id)] (is (= "application.state/rejected" (:application/state application))))) (testing "blacklist visible to handler in application" (let [application (api-call :get (str "/api/applications/" application-id) nil api-key handler-id)] (is (= [{:blacklist/user applicant-attributes :blacklist/resource {:resource/ext-id resource-ext-id}}] (:application/blacklist application)))))))))) (deftest test-blacklisting (let [api-key "42" owner-id "owner" handler-id "e2e-handler" handler-attributes {:userid handler-id :name "E2E Handler" :email ""} applicant-id "e2e-applicant" applicant-attributes {:userid applicant-id :name "E2E Applicant" :email ""} rejecter-attributes {:userid rejecter-bot/bot-userid :email nil :name "rejecter"}] (testing "create owner & api key" (test-helpers/create-user! {:userid owner-id} :owner) (api-key/add-api-key! api-key)) (testing "create users" (api-call :post "/api/users/create" handler-attributes api-key owner-id) (api-call :post "/api/users/create" applicant-attributes api-key owner-id) (api-call :post "/api/users/create" rejecter-attributes api-key owner-id)) (let [resource-ext-id "e2e-resource" resource-id (testing "create resource" (extract-id (api-call :post "/api/resources/create" {:resid resource-ext-id :organization {:organization/id "e2e"} :licenses []} api-key owner-id))) form-id (testing "create form" (extract-id (api-call :post "/api/forms/create" {:organization {:organization/id "e2e"} :form/internal-name "e2e" :form/external-title {:en "en e2e" :fi "fi e2e" :sv "en e2e"} :form/fields [{:field/type :text :field/title {:en "text field" :fi "tekstikenttä" :sv "textfält"} :field/optional true}]} api-key owner-id))) workflow-id (testing "create workflow" (extract-id (api-call :post "/api/workflows/create" {:organization {:organization/id "e2e"} :title "e2e workflow" :type :workflow/default :handlers [handler-id rejecter-bot/bot-userid]} api-key owner-id))) catalogue-item-id (testing "create catalogue item" (extract-id (api-call :post "/api/catalogue-items/create" {:organization {:organization/id "e2e"} :resid resource-id :form form-id :wfid workflow-id :localizations {:en {:title "e2e catalogue item"}}} api-key owner-id))) app-1 (testing "create first application" (:application-id (assert-success (api-call :post "/api/applications/create" {:catalogue-item-ids [catalogue-item-id]} api-key applicant-id)))) app-2 (testing "create second application" (:application-id (assert-success (api-call :post "/api/applications/create" {:catalogue-item-ids [catalogue-item-id]} api-key applicant-id))))] (testing "submit first application" (assert-success (api-call :post "/api/applications/submit" {:application-id app-1} api-key applicant-id))) (testing "second application" (testing "submit" (assert-success (api-call :post "/api/applications/submit" {:application-id app-2} api-key applicant-id))) (testing "approve" (assert-success (api-call :post "/api/applications/approve" {:application-id app-2} api-key handler-id))) (testing "revoke" (assert-success (api-call :post "/api/applications/revoke" {:application-id app-2 :comment "revoke"} api-key handler-id)))) (testing "user blacklisted" (let [[entry & _] (api-call :get (str "/api/blacklist?user=" applicant-id "&resource=" resource-ext-id) nil api-key handler-id)] (is (= {:resource/ext-id resource-ext-id} (:blacklist/resource entry))) (is (= applicant-id (:userid (:blacklist/user entry)))))) (testing "first application rejected" (let [application (api-call :get (str "/api/applications/" app-1) nil api-key applicant-id)] (is (= "application.state/rejected" (:application/state application))))) (testing "new applications gets automatically rejected" (let [app-3 (:application-id (assert-success (api-call :post "/api/applications/create" {:catalogue-item-ids [catalogue-item-id]} api-key applicant-id)))] (assert-success (api-call :post "/api/applications/submit" {:application-id app-3} api-key applicant-id)) (let [application (api-call :get (str "/api/applications/" app-3) nil api-key applicant-id)] (is (= "application.state/rejected" (:application/state application)))))) (testing "remove blacklist entry" (assert-success (api-call :post "/api/blacklist/remove" {:blacklist/user {:userid applicant-id} :blacklist/resource {:resource/ext-id resource-ext-id} :comment "good"} api-key handler-id))) (let [app-3 (testing "create third application" (:application-id (assert-success (api-call :post "/api/applications/create" {:catalogue-item-ids [catalogue-item-id]} api-key applicant-id))))] (testing "submit third application" (assert-success (api-call :post "/api/applications/submit" {:application-id app-3} api-key applicant-id)) (testing "and it doesn't get rejected" (is (= "application.state/submitted" (:application/state (api-call :get (str "/api/applications/" app-3) nil api-key applicant-id)))))) (testing "blacklist user again" (assert-success (api-call :post "/api/blacklist/add" {:blacklist/user {:userid applicant-id} :blacklist/resource {:resource/ext-id resource-ext-id} :comment "bad"} api-key handler-id))) (testing "third application gets rejected" (testing "and it doesn't get rejected" (is (= "application.state/rejected" (:application/state (api-call :get (str "/api/applications/" app-3) nil api-key applicant-id)))))))))) (deftest test-bona-fide-bot (let [api-key "42" owner-id "owner" applicant-id "bona-fide-applicant" applicant-attributes {:userid applicant-id :name "Bona Fide Applicant" :email ""} referer-id "bona-fide-referer" referer-attributes {:userid referer-id :name "Bona Fide Referer" :email "" :researcher-status-by "so"} bot-attributes {:userid bona-fide-bot/bot-userid :email nil :name "bona fide bot"}] (testing "create owner & api key" (test-helpers/create-user! {:userid owner-id} :owner) (api-key/add-api-key! api-key)) (testing "create users" (api-call :post "/api/users/create" applicant-attributes api-key owner-id) (api-call :post "/api/users/create" referer-attributes api-key owner-id) (api-call :post "/api/users/create" bot-attributes api-key owner-id)) (let [resource-id (extract-id (api-call :post "/api/resources/create" {:organization {:organization/id "default"} :resid "bona fide" :licenses []} api-key owner-id)) form-id (extract-id (api-call :post "/api/forms/create" {:organization {:organization/id "default"} :form/internal-name "e2e" :form/external-title {:en "en e2e" :fi "fi e2e" :sv "en e2e"} :form/fields [{:field/type :email :field/id "referer email" :field/title {:en "referer" :fi "referer" :sv "referer"} :field/optional false}]} api-key owner-id)) workflow-id (extract-id (api-call :post "/api/workflows/create" {:organization {:organization/id "default"} :title "bona fide workflow" :type :workflow/default :handlers [bona-fide-bot/bot-userid]} api-key owner-id)) catalogue-item-id (extract-id (api-call :post "/api/catalogue-items/create" {:organization {:organization/id "default"} :resid resource-id :form form-id :wfid workflow-id :localizations {:en {:title "bona fide catalogue item"}}} api-key owner-id)) app-id (testing "create application" (:application-id (assert-success (api-call :post "/api/applications/create" {:catalogue-item-ids [catalogue-item-id]} api-key applicant-id))))] (testing "fill & submit application" (assert-success (api-call :post "/api/applications/save-draft" {:application-id app-id :field-values [{:form form-id :field "referer email" :value ""}]} api-key applicant-id)) (assert-success (api-call :post "/api/applications/submit" {:application-id app-id} api-key applicant-id))) (let [event (-> (applications/get-application-internal app-id) :application/events last) token (:invitation/token event)] (testing "check that bot has requested decision" (is (= {:event/type :application.event/decider-invited :application/id app-id :application/decider {:name "Referer" :email ""} :event/actor bona-fide-bot/bot-userid} (select-keys event [:event/type :application/id :application/decider :event/actor]))) (is (string? token))) (testing "post decision as referer" (assert-success (api-call :post (str "/api/applications/accept-invitation?invitation-token=" token) nil api-key referer-id)) (assert-success (api-call :post "/api/applications/decide" {:application-id app-id :decision :approved} api-key referer-id))) (testing "check that application was approved" (let [application (api-call :get (str "/api/applications/" app-id) nil api-key applicant-id)] (is (= "application.state/approved" (:application/state application)))))))))
0ecf7c87a3f8218c9d0177a3c9653f61cfa8e261cc9b5d69930e44b587f6a569
hopv/homusat
ACG.ml
(* Abstract Configuration Graph *) (*** Rough sketch of the construction process ***) 0 . Set ( F_{1 } , { q_{0 } } ) as the root 1 . For each node ( F \phi_{1 } ... \phi_{\ell } , P ) , where an equation of the form F X_{1 } ... X_{\ell } = _ { \alpha } \psi_{F } is in the HES , 1.0 . Add bindings of the form X_{k } < ~ \phi_{k } 1.1 . Add ( \psi_{F } , P ) as a child node ( if there is already a node of the form ( \psi_{F } , P ' ) , then update it to ( \psi_{F } , P \cup P ' ) 2 . For each node ( X \phi_{1 } ... \phi_{\ell } , P ) , where X is a rhs variable , add ( ' \phi_{1 } ... \phi_{\ell } , P ) as a child node for each ' such that X < ~ \phi ' 3 . For each node ( op \phi_{1 } ... \phi_{\ell } , P ) , where op is an operator , calculate the set of possible states } for each k and add ( \phi_{k } , } ) as a child node 4 . Argument formulas that are applied simultaneously and thus share a common context are treated inseparately 0. Set (F_{1}, {q_{0}}) as the root 1. For each node (F \phi_{1} ... \phi_{\ell}, P), where an equation of the form F X_{1} ... X_{\ell} =_{\alpha} \psi_{F} is in the HES, 1.0. Add bindings of the form X_{k} <~ \phi_{k} 1.1. Add (\psi_{F}, P) as a child node (if there is already a node of the form (\psi_{F}, P'), then update it to (\psi_{F}, P \cup P') 2. For each node (X \phi_{1} ... \phi_{\ell}, P), where X is a rhs variable, add (\phi' \phi_{1} ... \phi_{\ell}, P) as a child node for each \phi' such that X <~ \phi' 3. For each node (op \phi_{1} ... \phi_{\ell}, P), where op is an operator, calculate the set of possible states P_{k} for each k and add (\phi_{k}, P_{k}) as a child node 4. Argument formulas that are applied simultaneously and thus share a common context are treated inseparately *) module LHS = Id.IdMap module RHS = Id.IdMap module IdSet = Id.IdSet module States = LTS.States module Delta = LTS.Delta type formula = | Or of Enc.elt list | And of Enc.elt list | Box of Id.t * Enc.elt | Diamond of Id.t * Enc.elt | App of Id.t * ((Enc.elt list) list) module FmlSet = Set.Make (struct type t = Enc.elt let compare : t -> t -> int = compare end) module FmlSet2 = Set.Make (struct type t = formula let compare : t -> t -> int = compare end) module FmlsSet = Set.Make (struct type t = Enc.elt list let compare : t -> t -> int = compare end) module FmlMap = X.Map.Make (struct type t = Enc.elt let compare : t -> t -> int = compare end) module FmlMap2 = X.Map.Make (struct type t = formula let compare : t -> t -> int = compare end) module FmlsMap = X.Map.Make (struct type t = Enc.elt list let compare : t -> t -> int = compare end) ACG : ( nodes , flows , rev_flows ) (* Might be better to define as a record type { nodes; flows; rev_flows } *) type t = States.t FmlMap2.t * FmlSet.t RHS.t * Id.t list list FmlsMap.t let convert = fun fml -> match Enc.decode fml with | Enc.Or (xs) -> Or (xs) | Enc.And (xs) -> And (xs) | Enc.Box (a, x) -> Box (a, x) | Enc.Diamond (a, x) -> Diamond (a, x) | Enc.App (x, ys) -> if ys = [] then App (x, []) else App (x, [ys]) let push = fun fml qs queue -> let ps = FmlMap2.find_default States.empty fml queue in let qs = States.union ps qs in FmlMap2.add fml qs queue let initial_node = fun funcs lts -> let (_, x, _, _, _) = List.hd funcs in let (_, _, _, q0) = lts in (App (x, []), States.singleton q0) (* The set of states reachable through a modal operator *) let next_states = fun delta qs a -> let f = fun delta a q acc -> let qs = Delta.find_default States.empty (q, a) delta in States.union qs acc in States.fold (f delta a) qs States.empty (* Append zss as additional arguments to the formula fml *) let append_args = fun fml zss -> match Enc.decode fml with | Enc.App (x, ys) -> if ys = [] then App (x, zss) else App (x, ys :: zss) | _ -> (* assert (zss = []); *) convert fml Push ( phi : : , qs ) for each phi such that x < ~ phi let push_flows = fun x yss qs flows queue -> let f = fun yss qs z queue -> let z = append_args z yss in push z qs queue in let zs = RHS.find_default FmlSet.empty x flows in FmlSet.fold (f yss qs) zs queue (* Update an old node *) let update_node = fun fmap delta queue nodes flows rev_flows xnodes fml qs -> let qs' = FmlMap2.find fml nodes in let qs_diff = States.diff qs qs' in if States.is_empty qs_diff then (* Already up-to-date *) (queue, nodes, flows, rev_flows, xnodes) else let nodes = FmlMap2.add fml (States.union qs_diff qs') nodes in match fml with | Or (xs) | And (xs) -> let f = fun qs queue x -> push (convert x) qs queue in let queue = List.fold_left (f qs_diff) queue xs in (queue, nodes, flows, rev_flows, xnodes) | Box (a, x) | Diamond (a, x) -> let qs_next = next_states delta qs_diff a in let queue = push (convert x) qs_next queue in (queue, nodes, flows, rev_flows, xnodes) | App (x, yss) -> if LHS.mem x fmap then let (_, body) = LHS.find x fmap in let queue = push body qs_diff queue in (queue, nodes, flows, rev_flows, xnodes) else (* x is a rhs variable *) let queue = push_flows x yss qs_diff flows queue in (queue, nodes, flows, rev_flows, xnodes) (* Push (y :: zss, qs) for each node of the form (x zss, qs) *) let push_xnodes = fun x y nodes xnodes queue -> let f = fun y nodes z queue -> match z with | App (x, zss) -> let y = append_args y zss in let qs = FmlMap2.find z nodes in push y qs queue | _ -> assert false in let zs = RHS.find_default FmlSet2.empty x xnodes in FmlSet2.fold (f y nodes) zs queue let split_xs = fun xs ys -> let rec f = fun xs ys acc -> match (xs, ys) with | (_, []) -> (List.rev acc, xs) | ([], _) -> assert false | (x :: xs, y :: ys) -> f xs ys (x :: acc) in f xs ys [] (* Add bindings of the form x <~ y *) let rec update_flows = fun xs yss queue nodes flows rev_flows xnodes -> let f = fun nodes xnodes (queue, flows) x y -> let zs = RHS.find_default FmlSet.empty x flows in let zs = FmlSet.add y zs in let flows = RHS.add x zs flows in let queue = push_xnodes x y nodes xnodes queue in (queue, flows) in match yss with | [] -> (queue, flows, rev_flows) | ys :: yss -> let (xs, next_xs) = split_xs xs ys in let f = f nodes xnodes in let (queue, flows) = List.fold_left2 f (queue, flows) xs ys in let xss = FmlsMap.find_default [] ys rev_flows in let rev_flows = FmlsMap.add ys (xs :: xss) rev_flows in update_flows next_xs yss queue nodes flows rev_flows xnodes The formula fml is of the form App ( x , ) let update_xnodes = fun x fml xnodes -> let zs = RHS.find_default FmlSet2.empty x xnodes in let zs = FmlSet2.add fml zs in RHS.add x zs xnodes (* Expand a new node *) let expand_node = fun fmap delta queue nodes flows rev_flows xnodes fml qs -> let nodes = FmlMap2.add fml qs nodes in match fml with | Or (xs) | And (xs) -> let f = fun qs queue x -> push (convert x) qs queue in let queue = List.fold_left (f qs) queue xs in (queue, nodes, flows, rev_flows, xnodes) | Box (a, x) | Diamond (a, x) -> let qs_next = next_states delta qs a in let queue = push (convert x) qs_next queue in (queue, nodes, flows, rev_flows, xnodes) | App (x, yss) -> if LHS.mem x fmap then let (args, body) = LHS.find x fmap in let (queue, flows, rev_flows) = update_flows args yss queue nodes flows rev_flows xnodes in let queue = push body qs queue in (queue, nodes, flows, rev_flows, xnodes) else (* x is a rhs variable *) let queue = push_flows x yss qs flows queue in let xnodes = update_xnodes x fml xnodes in (queue, nodes, flows, rev_flows, xnodes) (* Main loop *) let rec expand = fun fmap delta queue nodes flows rev_flows xnodes -> Profile.check_time_out "model checking" !Flags.time_out; if FmlMap2.is_empty queue then (nodes, flows, rev_flows) else let (fml, qs) = FmlMap2.min_binding queue in let queue = FmlMap2.remove fml queue in let (queue, nodes, flows, rev_flows, xnodes) = if FmlMap2.mem fml nodes then update_node fmap delta queue nodes flows rev_flows xnodes fml qs else expand_node fmap delta queue nodes flows rev_flows xnodes fml qs in expand fmap delta queue nodes flows rev_flows xnodes let initial_set = fun funcs lts -> let nodes = FmlMap2.empty in let flows = RHS.empty in let rev_flows = FmlsMap.empty in let xnodes = RHS.empty in let (fml, qs) = initial_node funcs lts in let queue = FmlMap2.singleton fml qs in (queue, nodes, flows, rev_flows, xnodes) let generate_fmap = fun funcs -> let f = fun acc func -> let (_, x, _, args, fml) = func in let args = X.List.map fst args in let fml = convert fml in LHS.add x (args, fml) acc in List.fold_left f LHS.empty funcs let construct = fun funcs lts -> let fmap = generate_fmap funcs in let (_, _, delta, _) = lts in let (queue, nodes, flows, rev_flows, xnodes) = initial_set funcs lts in expand fmap delta queue nodes flows rev_flows xnodes
null
https://raw.githubusercontent.com/hopv/homusat/cc05711a3f9d45b253b83ad09a2d0288115cc4f4/ACG.ml
ocaml
Abstract Configuration Graph ** Rough sketch of the construction process ** Might be better to define as a record type { nodes; flows; rev_flows } The set of states reachable through a modal operator Append zss as additional arguments to the formula fml assert (zss = []); Update an old node Already up-to-date x is a rhs variable Push (y :: zss, qs) for each node of the form (x zss, qs) Add bindings of the form x <~ y Expand a new node x is a rhs variable Main loop
0 . Set ( F_{1 } , { q_{0 } } ) as the root 1 . For each node ( F \phi_{1 } ... \phi_{\ell } , P ) , where an equation of the form F X_{1 } ... X_{\ell } = _ { \alpha } \psi_{F } is in the HES , 1.0 . Add bindings of the form X_{k } < ~ \phi_{k } 1.1 . Add ( \psi_{F } , P ) as a child node ( if there is already a node of the form ( \psi_{F } , P ' ) , then update it to ( \psi_{F } , P \cup P ' ) 2 . For each node ( X \phi_{1 } ... \phi_{\ell } , P ) , where X is a rhs variable , add ( ' \phi_{1 } ... \phi_{\ell } , P ) as a child node for each ' such that X < ~ \phi ' 3 . For each node ( op \phi_{1 } ... \phi_{\ell } , P ) , where op is an operator , calculate the set of possible states } for each k and add ( \phi_{k } , } ) as a child node 4 . Argument formulas that are applied simultaneously and thus share a common context are treated inseparately 0. Set (F_{1}, {q_{0}}) as the root 1. For each node (F \phi_{1} ... \phi_{\ell}, P), where an equation of the form F X_{1} ... X_{\ell} =_{\alpha} \psi_{F} is in the HES, 1.0. Add bindings of the form X_{k} <~ \phi_{k} 1.1. Add (\psi_{F}, P) as a child node (if there is already a node of the form (\psi_{F}, P'), then update it to (\psi_{F}, P \cup P') 2. For each node (X \phi_{1} ... \phi_{\ell}, P), where X is a rhs variable, add (\phi' \phi_{1} ... \phi_{\ell}, P) as a child node for each \phi' such that X <~ \phi' 3. For each node (op \phi_{1} ... \phi_{\ell}, P), where op is an operator, calculate the set of possible states P_{k} for each k and add (\phi_{k}, P_{k}) as a child node 4. Argument formulas that are applied simultaneously and thus share a common context are treated inseparately *) module LHS = Id.IdMap module RHS = Id.IdMap module IdSet = Id.IdSet module States = LTS.States module Delta = LTS.Delta type formula = | Or of Enc.elt list | And of Enc.elt list | Box of Id.t * Enc.elt | Diamond of Id.t * Enc.elt | App of Id.t * ((Enc.elt list) list) module FmlSet = Set.Make (struct type t = Enc.elt let compare : t -> t -> int = compare end) module FmlSet2 = Set.Make (struct type t = formula let compare : t -> t -> int = compare end) module FmlsSet = Set.Make (struct type t = Enc.elt list let compare : t -> t -> int = compare end) module FmlMap = X.Map.Make (struct type t = Enc.elt let compare : t -> t -> int = compare end) module FmlMap2 = X.Map.Make (struct type t = formula let compare : t -> t -> int = compare end) module FmlsMap = X.Map.Make (struct type t = Enc.elt list let compare : t -> t -> int = compare end) ACG : ( nodes , flows , rev_flows ) type t = States.t FmlMap2.t * FmlSet.t RHS.t * Id.t list list FmlsMap.t let convert = fun fml -> match Enc.decode fml with | Enc.Or (xs) -> Or (xs) | Enc.And (xs) -> And (xs) | Enc.Box (a, x) -> Box (a, x) | Enc.Diamond (a, x) -> Diamond (a, x) | Enc.App (x, ys) -> if ys = [] then App (x, []) else App (x, [ys]) let push = fun fml qs queue -> let ps = FmlMap2.find_default States.empty fml queue in let qs = States.union ps qs in FmlMap2.add fml qs queue let initial_node = fun funcs lts -> let (_, x, _, _, _) = List.hd funcs in let (_, _, _, q0) = lts in (App (x, []), States.singleton q0) let next_states = fun delta qs a -> let f = fun delta a q acc -> let qs = Delta.find_default States.empty (q, a) delta in States.union qs acc in States.fold (f delta a) qs States.empty let append_args = fun fml zss -> match Enc.decode fml with | Enc.App (x, ys) -> if ys = [] then App (x, zss) else App (x, ys :: zss) Push ( phi : : , qs ) for each phi such that x < ~ phi let push_flows = fun x yss qs flows queue -> let f = fun yss qs z queue -> let z = append_args z yss in push z qs queue in let zs = RHS.find_default FmlSet.empty x flows in FmlSet.fold (f yss qs) zs queue let update_node = fun fmap delta queue nodes flows rev_flows xnodes fml qs -> let qs' = FmlMap2.find fml nodes in let qs_diff = States.diff qs qs' in (queue, nodes, flows, rev_flows, xnodes) else let nodes = FmlMap2.add fml (States.union qs_diff qs') nodes in match fml with | Or (xs) | And (xs) -> let f = fun qs queue x -> push (convert x) qs queue in let queue = List.fold_left (f qs_diff) queue xs in (queue, nodes, flows, rev_flows, xnodes) | Box (a, x) | Diamond (a, x) -> let qs_next = next_states delta qs_diff a in let queue = push (convert x) qs_next queue in (queue, nodes, flows, rev_flows, xnodes) | App (x, yss) -> if LHS.mem x fmap then let (_, body) = LHS.find x fmap in let queue = push body qs_diff queue in (queue, nodes, flows, rev_flows, xnodes) let queue = push_flows x yss qs_diff flows queue in (queue, nodes, flows, rev_flows, xnodes) let push_xnodes = fun x y nodes xnodes queue -> let f = fun y nodes z queue -> match z with | App (x, zss) -> let y = append_args y zss in let qs = FmlMap2.find z nodes in push y qs queue | _ -> assert false in let zs = RHS.find_default FmlSet2.empty x xnodes in FmlSet2.fold (f y nodes) zs queue let split_xs = fun xs ys -> let rec f = fun xs ys acc -> match (xs, ys) with | (_, []) -> (List.rev acc, xs) | ([], _) -> assert false | (x :: xs, y :: ys) -> f xs ys (x :: acc) in f xs ys [] let rec update_flows = fun xs yss queue nodes flows rev_flows xnodes -> let f = fun nodes xnodes (queue, flows) x y -> let zs = RHS.find_default FmlSet.empty x flows in let zs = FmlSet.add y zs in let flows = RHS.add x zs flows in let queue = push_xnodes x y nodes xnodes queue in (queue, flows) in match yss with | [] -> (queue, flows, rev_flows) | ys :: yss -> let (xs, next_xs) = split_xs xs ys in let f = f nodes xnodes in let (queue, flows) = List.fold_left2 f (queue, flows) xs ys in let xss = FmlsMap.find_default [] ys rev_flows in let rev_flows = FmlsMap.add ys (xs :: xss) rev_flows in update_flows next_xs yss queue nodes flows rev_flows xnodes The formula fml is of the form App ( x , ) let update_xnodes = fun x fml xnodes -> let zs = RHS.find_default FmlSet2.empty x xnodes in let zs = FmlSet2.add fml zs in RHS.add x zs xnodes let expand_node = fun fmap delta queue nodes flows rev_flows xnodes fml qs -> let nodes = FmlMap2.add fml qs nodes in match fml with | Or (xs) | And (xs) -> let f = fun qs queue x -> push (convert x) qs queue in let queue = List.fold_left (f qs) queue xs in (queue, nodes, flows, rev_flows, xnodes) | Box (a, x) | Diamond (a, x) -> let qs_next = next_states delta qs a in let queue = push (convert x) qs_next queue in (queue, nodes, flows, rev_flows, xnodes) | App (x, yss) -> if LHS.mem x fmap then let (args, body) = LHS.find x fmap in let (queue, flows, rev_flows) = update_flows args yss queue nodes flows rev_flows xnodes in let queue = push body qs queue in (queue, nodes, flows, rev_flows, xnodes) let queue = push_flows x yss qs flows queue in let xnodes = update_xnodes x fml xnodes in (queue, nodes, flows, rev_flows, xnodes) let rec expand = fun fmap delta queue nodes flows rev_flows xnodes -> Profile.check_time_out "model checking" !Flags.time_out; if FmlMap2.is_empty queue then (nodes, flows, rev_flows) else let (fml, qs) = FmlMap2.min_binding queue in let queue = FmlMap2.remove fml queue in let (queue, nodes, flows, rev_flows, xnodes) = if FmlMap2.mem fml nodes then update_node fmap delta queue nodes flows rev_flows xnodes fml qs else expand_node fmap delta queue nodes flows rev_flows xnodes fml qs in expand fmap delta queue nodes flows rev_flows xnodes let initial_set = fun funcs lts -> let nodes = FmlMap2.empty in let flows = RHS.empty in let rev_flows = FmlsMap.empty in let xnodes = RHS.empty in let (fml, qs) = initial_node funcs lts in let queue = FmlMap2.singleton fml qs in (queue, nodes, flows, rev_flows, xnodes) let generate_fmap = fun funcs -> let f = fun acc func -> let (_, x, _, args, fml) = func in let args = X.List.map fst args in let fml = convert fml in LHS.add x (args, fml) acc in List.fold_left f LHS.empty funcs let construct = fun funcs lts -> let fmap = generate_fmap funcs in let (_, _, delta, _) = lts in let (queue, nodes, flows, rev_flows, xnodes) = initial_set funcs lts in expand fmap delta queue nodes flows rev_flows xnodes
2c90eea7c06296574ea1447905433da445498d1b43aa09574246c457cca8aaaf
spawngrid/cowboy_session
cowboy_session_server.erl
-module(cowboy_session_server). -behaviour(gen_server). %% API -export([start_link/3, command/2, handler_state/1, session_id/1, session_id/2, touch/1, stop/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, { handler, handler_state, session }). %%%=================================================================== %%% API %%%=================================================================== command(Server, Command) -> gen_server:call(Server, {command, Command}). handler_state(Server) -> gen_server:call(Server, handler_state). session_id(Server) -> gen_server:call(Server, session_id). session_id(Server, Session) -> gen_server:cast(Server, {session_id, Session}). touch(Server) -> gen_server:cast(Server, touch). stop(Server) -> gen_server:cast(Server, stop). %%-------------------------------------------------------------------- %% @doc %% Starts the server %% ( ) - > { ok , Pid } | ignore | { error , Error } %% @end %%-------------------------------------------------------------------- start_link(Handler, Session, SessionName) -> gen_server:start_link(?MODULE, [Handler, Session, SessionName], []). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %%-------------------------------------------------------------------- @private %% @doc %% Initializes the server %% ) - > { ok , State } | { ok , State , Timeout } | %% ignore | %% {stop, Reason} %% @end %%-------------------------------------------------------------------- init([Handler, Session, SessionName]) -> gproc:add_local_name({cowboy_session, SessionName}), HandlerState = Handler:init(Session, SessionName), {ok, #state{ session = Session, handler_state = HandlerState, handler = Handler }}. %%-------------------------------------------------------------------- @private %% @doc %% Handling call messages %% , From , State ) - > %% {reply, Reply, State} | { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_call(session_id, _From, #state{ session = Session } = State) -> {reply, Session, State}; handle_call(handler_state, _From, #state{ handler_state = HandlerState } = State) -> {reply, HandlerState, State}; handle_call({command, Command}, _From, #state{ handler = Handler, handler_state = HandlerState, session = Session } = State) -> {Reply, HandlerState1} = Handler:handle(Command, Session, HandlerState), {reply, Reply, State#state{ handler_state = HandlerState1 }}. %%-------------------------------------------------------------------- @private %% @doc %% Handling cast messages %% @spec handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_cast({session_id, NewSession}, #state{} = State) -> {noreply, State#state{ session = NewSession }}; handle_cast(touch, #state{ handler = Handler, handler_state = HandlerState, session = Session } = State) -> HandlerState1 = Handler:touch(Session, HandlerState), {noreply, State#state{ handler_state = HandlerState1 }}; handle_cast(stop, #state{ handler = Handler, handler_state = HandlerState, session = Session } = State) -> Handler:stop(Session, HandlerState), {stop, normal, State}. %%-------------------------------------------------------------------- @private %% @doc %% Handling all non call/cast messages %% , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_info(_Info, State) -> {noreply, State}. %%-------------------------------------------------------------------- @private %% @doc %% This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any %% necessary cleaning up. When it returns, the gen_server terminates with . The return value is ignored . %% , State ) - > void ( ) %% @end %%-------------------------------------------------------------------- terminate(_Reason, _State) -> ok. %%-------------------------------------------------------------------- @private %% @doc %% Convert process state when code is changed %% , State , Extra ) - > { ok , NewState } %% @end %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== Internal functions %%%===================================================================
null
https://raw.githubusercontent.com/spawngrid/cowboy_session/515c17c42b414ce516468c3c3236c2f16ca16482/src/cowboy_session_server.erl
erlang
API gen_server callbacks =================================================================== API =================================================================== -------------------------------------------------------------------- @doc Starts the server @end -------------------------------------------------------------------- =================================================================== gen_server callbacks =================================================================== -------------------------------------------------------------------- @doc Initializes the server ignore | {stop, Reason} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Handling call messages {reply, Reply, State} | {stop, Reason, Reply, State} | {stop, Reason, State} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Handling cast messages {stop, Reason, State} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Handling all non call/cast messages {stop, Reason, State} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc This function is called by a gen_server when it is about to terminate. It should be the opposite of Module:init/1 and do any necessary cleaning up. When it returns, the gen_server terminates @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Convert process state when code is changed @end -------------------------------------------------------------------- =================================================================== ===================================================================
-module(cowboy_session_server). -behaviour(gen_server). -export([start_link/3, command/2, handler_state/1, session_id/1, session_id/2, touch/1, stop/1]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, { handler, handler_state, session }). command(Server, Command) -> gen_server:call(Server, {command, Command}). handler_state(Server) -> gen_server:call(Server, handler_state). session_id(Server) -> gen_server:call(Server, session_id). session_id(Server, Session) -> gen_server:cast(Server, {session_id, Session}). touch(Server) -> gen_server:cast(Server, touch). stop(Server) -> gen_server:cast(Server, stop). ( ) - > { ok , Pid } | ignore | { error , Error } start_link(Handler, Session, SessionName) -> gen_server:start_link(?MODULE, [Handler, Session, SessionName], []). @private ) - > { ok , State } | { ok , State , Timeout } | init([Handler, Session, SessionName]) -> gproc:add_local_name({cowboy_session, SessionName}), HandlerState = Handler:init(Session, SessionName), {ok, #state{ session = Session, handler_state = HandlerState, handler = Handler }}. @private , From , State ) - > { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | handle_call(session_id, _From, #state{ session = Session } = State) -> {reply, Session, State}; handle_call(handler_state, _From, #state{ handler_state = HandlerState } = State) -> {reply, HandlerState, State}; handle_call({command, Command}, _From, #state{ handler = Handler, handler_state = HandlerState, session = Session } = State) -> {Reply, HandlerState1} = Handler:handle(Command, Session, HandlerState), {reply, Reply, State#state{ handler_state = HandlerState1 }}. @private @spec handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_cast({session_id, NewSession}, #state{} = State) -> {noreply, State#state{ session = NewSession }}; handle_cast(touch, #state{ handler = Handler, handler_state = HandlerState, session = Session } = State) -> HandlerState1 = Handler:touch(Session, HandlerState), {noreply, State#state{ handler_state = HandlerState1 }}; handle_cast(stop, #state{ handler = Handler, handler_state = HandlerState, session = Session } = State) -> Handler:stop(Session, HandlerState), {stop, normal, State}. @private , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_info(_Info, State) -> {noreply, State}. @private with . The return value is ignored . , State ) - > void ( ) terminate(_Reason, _State) -> ok. @private , State , Extra ) - > { ok , NewState } code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions
4069bf1e5bd01778edc6373eaebcfb5d26de20644ecc4b0ce2559bb77e3dd0ac
hopv/MoCHi
set_.ml
open Util open Combinator (** Sets (aka lists modulo permutation and contraction) *) type 'a t = 'a list let subset ?(cmp = (=)) l1 l2 = List.for_all (fun x -> List.mem ~cmp:cmp x l2) l1 let equiv ?(cmp = (=)) l1 l2 = subset ~cmp:cmp l1 l2 && subset ~cmp:cmp l2 l1 let intersects ?(cmp = (=)) l1 l2 = List.exists (fun x -> List.mem ~cmp:cmp x l2) l1 let disjoint ?(cmp = (=)) l1 l2 = List.for_all (fun x -> not (List.mem ~cmp:cmp x l2)) l1 (*let rec diff xs ys = match xs, ys with | [], [] | [], _ | _, [] -> xs | x' :: xs', ys -> if List.mem x' ys then diff xs' ys else x' :: diff xs' ys*) let diff ?(cmp = (=)) l1 l2 = List.filter (fun x -> not (List.mem ~cmp:cmp x l2)) l1 let inter ?(cmp = (=)) l1 l2 = List.filter (fun x -> List.mem ~cmp:cmp x l2) l1 let union ?(eq = (=)) l1 l2 = List.unique ~eq (l1 @ l2) let rec power = function | [] -> [[]] | x :: s' -> s' |> power |> List.concat_map (fun s -> [s; x :: s]) let subsets_of_size n s = let rec aux n s1s2s = if n = 0 then s1s2s else List.concat_map (fun (s1, s2) -> (** @invariant Set_.equiv (s1 @ s2) s *) List.maplr (fun s11 x s12 -> s11 @ s12, x :: s2) s1) (aux (n - 1) s1s2s) in List.map snd (aux n [s, []]) let rec equiv_classes rel s = match s with | [] -> [] | x :: s' -> let aux s1 s2 = List.partition (fun y -> List.exists (rel y) s1) s2 |> Pair.map_fst ((@) s1) in let ls, rs = fix (uncurry2 aux) (comp2 List.eq_length fst fst) ([x], s') in ls :: equiv_classes rel rs let rec representatives eqrel = function | [] -> [] | x :: s' -> x :: representatives eqrel (List.filter (eqrel x >> not) s') let minimal p s = let rec aux s1 s2 = match s1 with | [] -> s2 | x :: s1' ->if p (s1' @ s2) then aux s1' s2 else aux s1' (x :: s2) in aux s [] let rec cover = function | [] -> [] | s :: ss' -> if List.exists (flip subset s) ss' then cover ss' else s :: cover ss' let rec reachable ids next = let rec loop ids nids = let ids' = ids @ nids in let nids' = diff (List.unique (List.concat_map next nids)) ids' in if nids' = [] then ids' else loop ids' nids' in loop [] ids
null
https://raw.githubusercontent.com/hopv/MoCHi/b0ac0d626d64b1e3c779d8e98cb232121cc3196a/fpat/set_.ml
ocaml
* Sets (aka lists modulo permutation and contraction) let rec diff xs ys = match xs, ys with | [], [] | [], _ | _, [] -> xs | x' :: xs', ys -> if List.mem x' ys then diff xs' ys else x' :: diff xs' ys * @invariant Set_.equiv (s1 @ s2) s
open Util open Combinator type 'a t = 'a list let subset ?(cmp = (=)) l1 l2 = List.for_all (fun x -> List.mem ~cmp:cmp x l2) l1 let equiv ?(cmp = (=)) l1 l2 = subset ~cmp:cmp l1 l2 && subset ~cmp:cmp l2 l1 let intersects ?(cmp = (=)) l1 l2 = List.exists (fun x -> List.mem ~cmp:cmp x l2) l1 let disjoint ?(cmp = (=)) l1 l2 = List.for_all (fun x -> not (List.mem ~cmp:cmp x l2)) l1 let diff ?(cmp = (=)) l1 l2 = List.filter (fun x -> not (List.mem ~cmp:cmp x l2)) l1 let inter ?(cmp = (=)) l1 l2 = List.filter (fun x -> List.mem ~cmp:cmp x l2) l1 let union ?(eq = (=)) l1 l2 = List.unique ~eq (l1 @ l2) let rec power = function | [] -> [[]] | x :: s' -> s' |> power |> List.concat_map (fun s -> [s; x :: s]) let subsets_of_size n s = let rec aux n s1s2s = if n = 0 then s1s2s else List.concat_map (fun (s1, s2) -> List.maplr (fun s11 x s12 -> s11 @ s12, x :: s2) s1) (aux (n - 1) s1s2s) in List.map snd (aux n [s, []]) let rec equiv_classes rel s = match s with | [] -> [] | x :: s' -> let aux s1 s2 = List.partition (fun y -> List.exists (rel y) s1) s2 |> Pair.map_fst ((@) s1) in let ls, rs = fix (uncurry2 aux) (comp2 List.eq_length fst fst) ([x], s') in ls :: equiv_classes rel rs let rec representatives eqrel = function | [] -> [] | x :: s' -> x :: representatives eqrel (List.filter (eqrel x >> not) s') let minimal p s = let rec aux s1 s2 = match s1 with | [] -> s2 | x :: s1' ->if p (s1' @ s2) then aux s1' s2 else aux s1' (x :: s2) in aux s [] let rec cover = function | [] -> [] | s :: ss' -> if List.exists (flip subset s) ss' then cover ss' else s :: cover ss' let rec reachable ids next = let rec loop ids nids = let ids' = ids @ nids in let nids' = diff (List.unique (List.concat_map next nids)) ids' in if nids' = [] then ids' else loop ids' nids' in loop [] ids
5356c89342cba2a08496ae06ab66e0b603bda9dda29519d98bd1ba87292d0dff
bgamari/xmonad-config
Property.hs
{-# LANGUAGE OverloadedStrings #-} module Property ( -- * Properties PropertyName , getProperty , setProperty -- * Utilities , safeCall , safeCall_ ) where import DBus import DBus.Client (Client, call) import Data.String (IsString(..)) import Control.Error import Control.Monad (void) newtype PropertyName = PropertyName String deriving (Show) instance IsString PropertyName where fromString = PropertyName getProperty :: Client -> BusName -> ObjectPath -> InterfaceName -> PropertyName -> ExceptT String IO Variant getProperty client dest path iface (PropertyName prop) = do ret <- safeCall client c fromVariant ret ?? "Invalid return type" where c = (methodCall path "org.freedesktop.DBus.Properties" "Get") { methodCallDestination = Just dest , methodCallBody = [ toVariant iface, toVariant prop ] } setProperty :: Client -> BusName -> ObjectPath -> InterfaceName -> PropertyName -> Variant -> ExceptT String IO () setProperty client dest path iface (PropertyName prop) value = do void $ safeCall_ client c where c = (methodCall path "org.freedesktop.DBus.Properties" "Set") { methodCallDestination = Just dest , methodCallBody = [ toVariant iface, toVariant prop, toVariant value ] } safeCall_ :: Client -> MethodCall -> ExceptT String IO () safeCall_ client mcall = do void $ fmapLT show $ tryIO $ call client mcall safeCall :: Client -> MethodCall -> ExceptT String IO Variant safeCall client mcall = do ret <- fmapLT show $ tryIO $ call client mcall either (throwE . show) (tryHead "Empty response" . methodReturnBody) ret
null
https://raw.githubusercontent.com/bgamari/xmonad-config/14b93954ef89531161d5a02f94246c3a502fb18d/xmonad-ben/lib/Property.hs
haskell
# LANGUAGE OverloadedStrings # * Properties * Utilities
PropertyName , getProperty , setProperty , safeCall , safeCall_ ) where import DBus import DBus.Client (Client, call) import Data.String (IsString(..)) import Control.Error import Control.Monad (void) newtype PropertyName = PropertyName String deriving (Show) instance IsString PropertyName where fromString = PropertyName getProperty :: Client -> BusName -> ObjectPath -> InterfaceName -> PropertyName -> ExceptT String IO Variant getProperty client dest path iface (PropertyName prop) = do ret <- safeCall client c fromVariant ret ?? "Invalid return type" where c = (methodCall path "org.freedesktop.DBus.Properties" "Get") { methodCallDestination = Just dest , methodCallBody = [ toVariant iface, toVariant prop ] } setProperty :: Client -> BusName -> ObjectPath -> InterfaceName -> PropertyName -> Variant -> ExceptT String IO () setProperty client dest path iface (PropertyName prop) value = do void $ safeCall_ client c where c = (methodCall path "org.freedesktop.DBus.Properties" "Set") { methodCallDestination = Just dest , methodCallBody = [ toVariant iface, toVariant prop, toVariant value ] } safeCall_ :: Client -> MethodCall -> ExceptT String IO () safeCall_ client mcall = do void $ fmapLT show $ tryIO $ call client mcall safeCall :: Client -> MethodCall -> ExceptT String IO Variant safeCall client mcall = do ret <- fmapLT show $ tryIO $ call client mcall either (throwE . show) (tryHead "Empty response" . methodReturnBody) ret
f9e26dec0135d491098a1c2c14b70c796e258b74232524103dc8e9804d9fa3d9
theosotr/buildfs
syntax.mli
* Copyright ( c ) 2018 - 2020 * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation , version 3 . * * This program is distributed in the hope that it will be useful , but * WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * General Public License for more details . * * You should have received a copy of the GNU General Public License * along with this program . If not , see < / > . * Copyright (c) 2018-2020 Thodoris Sotiropoulos * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see </>. *) type eff = | Cons | Expunge | Prod type fd_var = | CWD | Fd of string type path = | Unknown of string | Path of string type expr = | P of path | V of fd_var | At of (fd_var * path) type statement = | Let of (fd_var * expr) | Del of expr | Consume of expr | Produce of expr | Input of (string * string) | Output of (string * string) | DependsOn of (string * string) | Newproc of string | Begin_task of string | End_task of string | Nop * The statements of used to model all the system calls . type syscall_desc = {syscall: string; (** The name of the system call. *) args: string; (** The string corresponding to the arguments of the system call. *) ret: string; (** The return value of the system call. *) err: string option; (** The error type and message of a failed system call. *) line: int; (** The line where the system call appears in traces. *) } (** A record that stores all the information of a certain system call trace. *) type trace = (string * (statement * syscall_desc)) * The type representing a statement in BuildFS . Every entry consists of a string value corresponding to PID , the BuildFS statement and the system call description . Every entry consists of a string value corresponding to PID, the BuildFS statement and the system call description. *) type 'a stream = | Stream of 'a * (unit -> 'a stream) | Empty (** A polymorphic type representing a stream. *) val main_block : string (** String representing the main execution block. *) val is_main : string -> bool (** Checks whether the given block is the main block. *) val dummy_statement : statement -> int -> trace (** Generates a dummy statement for the given statement*) val string_of_syscall : syscall_desc -> string (** This function converts a system call description into a string without including the number of the line where the system call appears. *) val string_of_syscall_desc : syscall_desc -> string (** This function converts a system call description into a string. *) val string_of_trace : (statement * syscall_desc) -> string * This function converts an BuildFS statement along with its system call description into a string . its system call description into a string. *) val next_trace : trace stream -> trace stream (** This function expects a stream of traces and returns the next stream (if any). *) val peek_trace : trace stream -> trace option (** This function expects a stream of traces and and returns the current trace (if any). *)
null
https://raw.githubusercontent.com/theosotr/buildfs/3cd287da0d1184934c1bcd28d301f2545196f44b/src/analysis/syntax.mli
ocaml
* The name of the system call. * The string corresponding to the arguments of the system call. * The return value of the system call. * The error type and message of a failed system call. * The line where the system call appears in traces. * A record that stores all the information of a certain system call trace. * A polymorphic type representing a stream. * String representing the main execution block. * Checks whether the given block is the main block. * Generates a dummy statement for the given statement * This function converts a system call description into a string without including the number of the line where the system call appears. * This function converts a system call description into a string. * This function expects a stream of traces and returns the next stream (if any). * This function expects a stream of traces and and returns the current trace (if any).
* Copyright ( c ) 2018 - 2020 * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation , version 3 . * * This program is distributed in the hope that it will be useful , but * WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * General Public License for more details . * * You should have received a copy of the GNU General Public License * along with this program . If not , see < / > . * Copyright (c) 2018-2020 Thodoris Sotiropoulos * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see </>. *) type eff = | Cons | Expunge | Prod type fd_var = | CWD | Fd of string type path = | Unknown of string | Path of string type expr = | P of path | V of fd_var | At of (fd_var * path) type statement = | Let of (fd_var * expr) | Del of expr | Consume of expr | Produce of expr | Input of (string * string) | Output of (string * string) | DependsOn of (string * string) | Newproc of string | Begin_task of string | End_task of string | Nop * The statements of used to model all the system calls . type syscall_desc = } type trace = (string * (statement * syscall_desc)) * The type representing a statement in BuildFS . Every entry consists of a string value corresponding to PID , the BuildFS statement and the system call description . Every entry consists of a string value corresponding to PID, the BuildFS statement and the system call description. *) type 'a stream = | Stream of 'a * (unit -> 'a stream) | Empty val main_block : string val is_main : string -> bool val dummy_statement : statement -> int -> trace val string_of_syscall : syscall_desc -> string val string_of_syscall_desc : syscall_desc -> string val string_of_trace : (statement * syscall_desc) -> string * This function converts an BuildFS statement along with its system call description into a string . its system call description into a string. *) val next_trace : trace stream -> trace stream val peek_trace : trace stream -> trace option
9971750a712313bbacaf687f6a811fe0aeaebb73e95e6a43a6e6a15453fe61c1
dbuenzli/hyperbib
home_html.mli
--------------------------------------------------------------------------- Copyright ( c ) 2021 University of Bern . All rights reserved . Distributed under the ISC license , see terms at the end of the file . --------------------------------------------------------------------------- Copyright (c) 2021 University of Bern. All rights reserved. Distributed under the ISC license, see terms at the end of the file. ---------------------------------------------------------------------------*) (** The home page. *) open Hyperbib.Std val page : Page.Gen.t -> Page.t --------------------------------------------------------------------------- Copyright ( c ) 2021 University of Bern Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 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) 2021 University of Bern Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
null
https://raw.githubusercontent.com/dbuenzli/hyperbib/04a09ae1036c68a45114c080206364fecb64b7f6/src/html/home_html.mli
ocaml
* The home page.
--------------------------------------------------------------------------- Copyright ( c ) 2021 University of Bern . All rights reserved . Distributed under the ISC license , see terms at the end of the file . --------------------------------------------------------------------------- Copyright (c) 2021 University of Bern. All rights reserved. Distributed under the ISC license, see terms at the end of the file. ---------------------------------------------------------------------------*) open Hyperbib.Std val page : Page.Gen.t -> Page.t --------------------------------------------------------------------------- Copyright ( c ) 2021 University of Bern Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 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) 2021 University of Bern Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
3957e67a98f6192290b8677d7475825a6323dcd6e8aef63e352c10517c09dc10
abarbu/haskell-torch
T11_VAE.hs
# LANGUAGE AllowAmbiguousTypes , CPP , ConstraintKinds , DataKinds , , DeriveGeneric , FlexibleContexts , FlexibleInstances # # LANGUAGE FunctionalDependencies , GADTs , OverloadedLabels , OverloadedStrings , PartialTypeSignatures , PolyKinds , QuasiQuotes # # LANGUAGE RankNTypes , RecordWildCards , ScopedTypeVariables , TemplateHaskell , TypeApplications , TypeFamilies , TypeFamilyDependencies # # LANGUAGE TypeInType , TypeOperators , UndecidableInstances # {-# OPTIONS_GHC -fconstraint-solver-iterations=10 -fdefer-typed-holes #-} # OPTIONS_GHC -fplugin - opt GHC.TypeLits . Normalise -fplugin GHC.TypeLits . KnownNat . Solver # {-# OPTIONS_GHC -Wno-partial-type-signatures #-} module Torch.Tutorial.Intro.T11_VAE where import Control.Monad import Control.Monad.Extra import Data.Default import Data.IORef import Data.String.InterpolateIO import System.Directory as D import Torch import Torch.Tensor as T import Torch.Datasets type ImageSize = 784 type HDim = 400 type ZDim = 20 type BatchSz = 128 encode :: _ => _ -> Tensor TFloat ki '[batch, ImageSize] -> IO (Tensor TFloat ki '[batch, ZDim], Tensor TFloat ki '[batch, ZDim]) encode (w1,w2,w3,_,_) x = do h <- linear (inF_ @ImageSize) (outF_ @HDim) w1 x a <- linear (inF_ @HDim) (outF_ @ZDim) w2 h b <- linear (inF_ @HDim) (outF_ @ZDim) w3 h pure (a,b) decode :: _ => _ -> Tensor TFloat ki '[batch, ZDim] -> IO (Tensor TFloat ki '[batch, ImageSize]) decode (_,_,_,w4,w5) x = do h <- relu =<< linear (inF_ @ZDim) (outF_ @HDim) w4 x sigmoid =<< linear (inF_ @HDim) (outF_ @ImageSize) w5 h reparameterize :: _ => Tensor TFloat ki '[batch, ZDim] -> Tensor TFloat ki '[batch, ZDim] -> IO (Tensor TFloat ki '[batch, ZDim]) reparameterize mu logVar = do std <- T.exp =<< logVar ./@ 2 eps <- randn pure mu ..+ (like std eps .* std) forward ws x = do (mu, logVar) <- encode ws x z <- reparameterize mu logVar x' <- decode ws z pure (x', mu, logVar) ex = do let epochs = 200 :: Int -- whenM (D.doesDirectoryExist "generated-images") $ D.removeDirectoryRecursive "generated-images" D.createDirectory "generated-images" net <- gradP params <- toParameters net optimizer <- newIORef (adam (def { adamLearningRate = 1e-3 }) params) -- (tr, _) <- mnist "datasets/image/" (Right trs) <- fetchDataset tr let trainStream = batchTensors (batchSize_ @BatchSz) $ shuffle 5000 trs -- withGrad $ mapM_ (\epoch -> forEachDataN (\d n -> do images <- reshape =<< dataObject d (images', mu, logVar) <- forward net images -- Compute reconstruction loss and kl divergence For KL divergence , see Appendix B in VAE paper -- or reconstructionLoss <- binaryCrossEntropyLoss images def (SizeAverage False) images' TODO This could be a lot cleaner klDivergence <- ((-0.5) @*. ) =<< T.sum =<< (1 @+. logVar ..- (T.pow mu =<< toScalar 2) ..- T.exp logVar) Backprop and optimize loss <- reconstructionLoss .+ klDivergence zeroGradients_ params backward1 loss False False step_ optimizer when (n `rem` 100 == 0) $ putStrLn =<< [c|Epoch #{epoch+1}/#{epochs} Reconstruction loss #{reconstructionLoss} KL divergence #{klDivergence}|] putStrLn =<< [c|Step #{n+1} #{epoch+1}/#{epochs} Reconstruction loss #{reconstructionLoss} KL divergence #{klDivergence}|] when (n `rem` 100 == 0) $ withoutGrad $ do -- Sample an image from tha latent space z <- sized (size_ @'[BatchSz, ZDim]) <$> randn sampledImages <- decode net z writeGreyTensorToFile ("generated-images/sampled-"<>show' epoch<>"@"<>show' n<>".jpg") =<< makeGreyGrid (size_ @8) (padding_ @2) 0 =<< reshape @'[BatchSz, 1, 28, 28] sampledImages -- Reconstruct images from the dataset (images', _, _) <- forward net images is <- reshape @'[BatchSz, 1, 28, 28] images is' <- reshape @'[BatchSz, 1, 28, 28] images' writeGreyTensorToFile ("generated-images/reconstructed-"<>show' epoch<>"@"<>show' n<>".jpg") =<< makeGreyGrid (size_ @8) (padding_ @2) 0 =<< cat2 @0 is is' pure () pure ()) trainStream) [0..epochs-1] pure ()
null
https://raw.githubusercontent.com/abarbu/haskell-torch/e0afcaf81b78e9211ba120dcd247f9a6112b57ab/haskell-torch-examples/src/Torch/Tutorial/Intro/T11_VAE.hs
haskell
# OPTIONS_GHC -fconstraint-solver-iterations=10 -fdefer-typed-holes # # OPTIONS_GHC -Wno-partial-type-signatures # Compute reconstruction loss and kl divergence or Sample an image from tha latent space Reconstruct images from the dataset
# LANGUAGE AllowAmbiguousTypes , CPP , ConstraintKinds , DataKinds , , DeriveGeneric , FlexibleContexts , FlexibleInstances # # LANGUAGE FunctionalDependencies , GADTs , OverloadedLabels , OverloadedStrings , PartialTypeSignatures , PolyKinds , QuasiQuotes # # LANGUAGE RankNTypes , RecordWildCards , ScopedTypeVariables , TemplateHaskell , TypeApplications , TypeFamilies , TypeFamilyDependencies # # LANGUAGE TypeInType , TypeOperators , UndecidableInstances # # OPTIONS_GHC -fplugin - opt GHC.TypeLits . Normalise -fplugin GHC.TypeLits . KnownNat . Solver # module Torch.Tutorial.Intro.T11_VAE where import Control.Monad import Control.Monad.Extra import Data.Default import Data.IORef import Data.String.InterpolateIO import System.Directory as D import Torch import Torch.Tensor as T import Torch.Datasets type ImageSize = 784 type HDim = 400 type ZDim = 20 type BatchSz = 128 encode :: _ => _ -> Tensor TFloat ki '[batch, ImageSize] -> IO (Tensor TFloat ki '[batch, ZDim], Tensor TFloat ki '[batch, ZDim]) encode (w1,w2,w3,_,_) x = do h <- linear (inF_ @ImageSize) (outF_ @HDim) w1 x a <- linear (inF_ @HDim) (outF_ @ZDim) w2 h b <- linear (inF_ @HDim) (outF_ @ZDim) w3 h pure (a,b) decode :: _ => _ -> Tensor TFloat ki '[batch, ZDim] -> IO (Tensor TFloat ki '[batch, ImageSize]) decode (_,_,_,w4,w5) x = do h <- relu =<< linear (inF_ @ZDim) (outF_ @HDim) w4 x sigmoid =<< linear (inF_ @HDim) (outF_ @ImageSize) w5 h reparameterize :: _ => Tensor TFloat ki '[batch, ZDim] -> Tensor TFloat ki '[batch, ZDim] -> IO (Tensor TFloat ki '[batch, ZDim]) reparameterize mu logVar = do std <- T.exp =<< logVar ./@ 2 eps <- randn pure mu ..+ (like std eps .* std) forward ws x = do (mu, logVar) <- encode ws x z <- reparameterize mu logVar x' <- decode ws z pure (x', mu, logVar) ex = do let epochs = 200 :: Int whenM (D.doesDirectoryExist "generated-images") $ D.removeDirectoryRecursive "generated-images" D.createDirectory "generated-images" net <- gradP params <- toParameters net optimizer <- newIORef (adam (def { adamLearningRate = 1e-3 }) params) (tr, _) <- mnist "datasets/image/" (Right trs) <- fetchDataset tr let trainStream = batchTensors (batchSize_ @BatchSz) $ shuffle 5000 trs withGrad $ mapM_ (\epoch -> forEachDataN (\d n -> do images <- reshape =<< dataObject d (images', mu, logVar) <- forward net images For KL divergence , see Appendix B in VAE paper reconstructionLoss <- binaryCrossEntropyLoss images def (SizeAverage False) images' TODO This could be a lot cleaner klDivergence <- ((-0.5) @*. ) =<< T.sum =<< (1 @+. logVar ..- (T.pow mu =<< toScalar 2) ..- T.exp logVar) Backprop and optimize loss <- reconstructionLoss .+ klDivergence zeroGradients_ params backward1 loss False False step_ optimizer when (n `rem` 100 == 0) $ putStrLn =<< [c|Epoch #{epoch+1}/#{epochs} Reconstruction loss #{reconstructionLoss} KL divergence #{klDivergence}|] putStrLn =<< [c|Step #{n+1} #{epoch+1}/#{epochs} Reconstruction loss #{reconstructionLoss} KL divergence #{klDivergence}|] when (n `rem` 100 == 0) $ withoutGrad $ do z <- sized (size_ @'[BatchSz, ZDim]) <$> randn sampledImages <- decode net z writeGreyTensorToFile ("generated-images/sampled-"<>show' epoch<>"@"<>show' n<>".jpg") =<< makeGreyGrid (size_ @8) (padding_ @2) 0 =<< reshape @'[BatchSz, 1, 28, 28] sampledImages (images', _, _) <- forward net images is <- reshape @'[BatchSz, 1, 28, 28] images is' <- reshape @'[BatchSz, 1, 28, 28] images' writeGreyTensorToFile ("generated-images/reconstructed-"<>show' epoch<>"@"<>show' n<>".jpg") =<< makeGreyGrid (size_ @8) (padding_ @2) 0 =<< cat2 @0 is is' pure () pure ()) trainStream) [0..epochs-1] pure ()
5f513a6be54091abece849eb4c7d0192ed28989282716f8c6d8564839b8dd6f6
marick/lein-midje
project.clj
(defproject {{name}} "0.0.1-SNAPSHOT" :description "Cool new project to do things and stuff" :dependencies [[org.clojure/clojure "1.7.0"]] :profiles {:dev {:dependencies [[midje "1.7.0"]]} You can add dependencies that apply to ` ` below . ;; An example would be changing the logging destination for test runs. :midje {}}) Note that itself is in the ` dev ` profile to support ;; running autotest in the repl.
null
https://raw.githubusercontent.com/marick/lein-midje/71a98ad1da2b94ed7050cc6b99be798ef3b3837e/src/leiningen/new/midje/project.clj
clojure
An example would be changing the logging destination for test runs. running autotest in the repl.
(defproject {{name}} "0.0.1-SNAPSHOT" :description "Cool new project to do things and stuff" :dependencies [[org.clojure/clojure "1.7.0"]] :profiles {:dev {:dependencies [[midje "1.7.0"]]} You can add dependencies that apply to ` ` below . :midje {}}) Note that itself is in the ` dev ` profile to support
2186da18ad7b690d123ec47741a23503379930dbc7002ec52b40311dd2cb03c4
alura-cursos/clojure-introducao
aula5.clj
(ns curso.aula5) (def estoque {"Mochila" 10 "Camiseta" 5}) (println estoque) (def estoque {"Mochila" 10, "Camiseta" 5}) (def estoque {"Mochila" 10 "Camiseta" 5}) (println estoque) (println "Temos" (count estoque) "elementos") (println "Chaves são:" (keys estoque)) (println "Valores são:" (vals estoque)) ; keyword : mochila (def estoque {:mochila 10 :camiseta 5}) (println (assoc estoque :cadeira 3)) (println estoque) (println (assoc estoque :mochila 1)) (println estoque) (println (update estoque :mochila inc)) (defn tira-um [valor] (println "tirando um de" valor) (- valor 1)) (println estoque) (println (update estoque :mochila tira-um)) (println estoque) (println (update estoque :mochila #(- % 3))) (println (dissoc estoque :mochila)) (def pedido {:mochila {:quantidade 2, :preco 80} :camiseta {:quantidade 3, :preco 40}}) (println "\n\n\n\n") (println pedido) (def pedido (assoc pedido :chaveiro {:quantidade 1, :preco 10})) (println pedido) mapa (println (get pedido :mochila)) (println (get pedido :cadeira)) (println (get pedido :cadeira {})) ; get com valor default (println (:mochila pedido)) (println (:cadeira pedido)) (println (:cadeira pedido {})) (println (:quantidade (:mochila pedido))) (println (update-in pedido [:mochila :quantidade] inc)) ; THREADING FIRST (println pedido) (println (-> pedido :mochila :quantidade)) (-> pedido :mochila ,,, :quantidade ,,, println ,,,)
null
https://raw.githubusercontent.com/alura-cursos/clojure-introducao/9b37f6cca3c33dd2382a3b44c87896d33e0246ae/src/curso/aula5.clj
clojure
keyword get com valor default THREADING FIRST
(ns curso.aula5) (def estoque {"Mochila" 10 "Camiseta" 5}) (println estoque) (def estoque {"Mochila" 10, "Camiseta" 5}) (def estoque {"Mochila" 10 "Camiseta" 5}) (println estoque) (println "Temos" (count estoque) "elementos") (println "Chaves são:" (keys estoque)) (println "Valores são:" (vals estoque)) : mochila (def estoque {:mochila 10 :camiseta 5}) (println (assoc estoque :cadeira 3)) (println estoque) (println (assoc estoque :mochila 1)) (println estoque) (println (update estoque :mochila inc)) (defn tira-um [valor] (println "tirando um de" valor) (- valor 1)) (println estoque) (println (update estoque :mochila tira-um)) (println estoque) (println (update estoque :mochila #(- % 3))) (println (dissoc estoque :mochila)) (def pedido {:mochila {:quantidade 2, :preco 80} :camiseta {:quantidade 3, :preco 40}}) (println "\n\n\n\n") (println pedido) (def pedido (assoc pedido :chaveiro {:quantidade 1, :preco 10})) (println pedido) mapa (println (get pedido :mochila)) (println (get pedido :cadeira)) (println (:mochila pedido)) (println (:cadeira pedido)) (println (:cadeira pedido {})) (println (:quantidade (:mochila pedido))) (println (update-in pedido [:mochila :quantidade] inc)) (println pedido) (println (-> pedido :mochila :quantidade)) (-> pedido :mochila ,,, :quantidade ,,, println ,,,)
20a42e68baa26b329e130b9c020b4735f151170772d96353f0308e7b1e4ecc48
project-oak/hafnium-verification
Propset.mli
* Copyright ( c ) 2009 - 2013 , Monoidics ltd . * Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) 2009-2013, Monoidics ltd. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd (** Functions for Sets of Propositions with and without sharing *) * { 2 Sets of Propositions } [@@@warning "-32"] * Sets of propositions . The invariant is maintaned that Prop.prop_rename_primed_footprint_vars is called on any prop added to the set . called on any prop added to the set. *) type t val compare : t -> t -> int (** Compare propsets *) val singleton : Tenv.t -> Prop.normal Prop.t -> t * set . val mem : Prop.normal Prop.t -> t -> bool (** Set membership. *) val union : t -> t -> t (** Set union. *) val inter : t -> t -> t (** Set intersection *) val add : Tenv.t -> Prop.normal Prop.t -> t -> t * Add [ prop ] to propset . val diff : t -> t -> t (** Set difference. *) val empty : t (** The empty set of propositions. *) val size : t -> int (** Size of the set *) val from_proplist : Tenv.t -> Prop.normal Prop.t list -> t val to_proplist : t -> Prop.normal Prop.t list val map : Tenv.t -> (Prop.normal Prop.t -> Prop.normal Prop.t) -> t -> t * Apply function to all the elements of the propset . val map_option : Tenv.t -> (Prop.normal Prop.t -> Prop.normal Prop.t option) -> t -> t * Apply function to all the elements of the propset , removing those where it returns [ None ] . val fold : ('a -> Prop.normal Prop.t -> 'a) -> 'a -> t -> 'a (** [fold f pset a] computes [(f pN ... (f p2 (f p1 a))...)], where [p1 ... pN] are the elements of pset, in increasing order. *) val iter : (Prop.normal Prop.t -> unit) -> t -> unit (** [iter f pset] computes (f p1;f p2;..;f pN) where [p1 ... pN] are the elements of pset, in increasing order. *) val partition : (Prop.normal Prop.t -> bool) -> t -> t * t val subseteq : t -> t -> bool val is_empty : t -> bool (** Set emptiness check. *) val filter : (Prop.normal Prop.t -> bool) -> t -> t [@@@warning "+32"] * { 2 Pretty print } val d : Prop.normal Prop.t -> t -> unit * dump a propset coming form the given initial prop
null
https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/infer/src/biabduction/Propset.mli
ocaml
* Functions for Sets of Propositions with and without sharing * Compare propsets * Set membership. * Set union. * Set intersection * Set difference. * The empty set of propositions. * Size of the set * [fold f pset a] computes [(f pN ... (f p2 (f p1 a))...)], where [p1 ... pN] are the elements of pset, in increasing order. * [iter f pset] computes (f p1;f p2;..;f pN) where [p1 ... pN] are the elements of pset, in increasing order. * Set emptiness check.
* Copyright ( c ) 2009 - 2013 , Monoidics ltd . * Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) 2009-2013, Monoidics ltd. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd * { 2 Sets of Propositions } [@@@warning "-32"] * Sets of propositions . The invariant is maintaned that Prop.prop_rename_primed_footprint_vars is called on any prop added to the set . called on any prop added to the set. *) type t val compare : t -> t -> int val singleton : Tenv.t -> Prop.normal Prop.t -> t * set . val mem : Prop.normal Prop.t -> t -> bool val union : t -> t -> t val inter : t -> t -> t val add : Tenv.t -> Prop.normal Prop.t -> t -> t * Add [ prop ] to propset . val diff : t -> t -> t val empty : t val size : t -> int val from_proplist : Tenv.t -> Prop.normal Prop.t list -> t val to_proplist : t -> Prop.normal Prop.t list val map : Tenv.t -> (Prop.normal Prop.t -> Prop.normal Prop.t) -> t -> t * Apply function to all the elements of the propset . val map_option : Tenv.t -> (Prop.normal Prop.t -> Prop.normal Prop.t option) -> t -> t * Apply function to all the elements of the propset , removing those where it returns [ None ] . val fold : ('a -> Prop.normal Prop.t -> 'a) -> 'a -> t -> 'a val iter : (Prop.normal Prop.t -> unit) -> t -> unit val partition : (Prop.normal Prop.t -> bool) -> t -> t * t val subseteq : t -> t -> bool val is_empty : t -> bool val filter : (Prop.normal Prop.t -> bool) -> t -> t [@@@warning "+32"] * { 2 Pretty print } val d : Prop.normal Prop.t -> t -> unit * dump a propset coming form the given initial prop
047c0138d24ad29f2f822e563bce50a74b1dc13495de94137d43bf71c0b3e511
monadbobo/ocaml-core
constrained_float.ml
open Std_internal module type S = sig type t = private float include Sexpable with type t := t include Binable with type t := t include Comparable_binable with type t := t include Hashable_binable with type t := t include Robustly_comparable with type t := t include Stringable with type t := t include Floatable with type t := t end
null
https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/core/lib/constrained_float.ml
ocaml
open Std_internal module type S = sig type t = private float include Sexpable with type t := t include Binable with type t := t include Comparable_binable with type t := t include Hashable_binable with type t := t include Robustly_comparable with type t := t include Stringable with type t := t include Floatable with type t := t end
8204a5975ddf092be8b47dd2f29a874223fd7d45b129e2aa07839e5063a4d31e
cnr/cgroup-rts-threads
Types.hs
-- | Parsers and types related to cgroups and mounts module System.CGroup.Types ( -- * CPU quotas CPUQuota (..), -- * raw cgroups as viewed in \/proc\/$PID\/cgroup RawCGroup (..), parseCGroups, * mounts as viewed in \/proc\/$PID\/mountinfo Mount (..), parseMountInfo, -- * Parser type Parser, parseFile, ) where import Control.Exception (throwIO) import Data.Char (isSpace) import Data.Ratio import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.IO as TIO import Data.Void (Void) import Path import Text.Megaparsec import Text.Megaparsec.Char import qualified Text.Megaparsec.Char.Lexer as L ---------- CPU quotas -- | A CPU quota is the ratio of CPU time our process can use relative to the -- scheduler period -- -- For example: -- -- @ -- | ratio | description | -- | ---------------- | ----------- | | 100000 / 100000 | ( 1 ) | | 200000 / 100000 | ( 2 ) | | 50000 / 100000 | ( 3 ) | | / 100000 | ( 4 ) | -- @ -- ( 1 ): we can use up to a single CPU core -- ( 2 ): we can use up to two CPU cores -- ( 3 ): the scheduler will give us a single CPU core for up to 50 % of the time -- ( 4 ): we can use all available CPU resources ( there is no quota ) data CPUQuota = CPUQuota (Ratio Int) | NoQuota deriving (Eq, Ord, Show) ---------- Raw cgroups -- | A cgroup, as viewed within \/proc\/[pid]\/cgroup -- -- see cgroups(7): \/proc\/[pid]\/cgroup section data RawCGroup = RawCGroup { rawCGroupId :: Text , rawCGroupControllers :: [Text] , rawCGroupPath :: Path Abs Dir } deriving (Show) -- | Parse an entire \/proc\/[pid]\/cgroup file into a list of cgroups parseCGroups :: Parser [RawCGroup] parseCGroups = some parseSingleCGroup <* eof | Parse a single cgroup line within \/proc\/[pid]\/cgroup -- -- hierarchyID:list,of,controllers:path -- -- In cgroups version 1, a comma-separated list of controllers exists within each group -- In cgroups version 2 , the " controllers " section is always an empty string -- -- see cgroups(7): \/proc\/[pid]\/cgroup section parseSingleCGroup :: Parser RawCGroup parseSingleCGroup = RawCGroup <$> takeUntil1P ':' -- hierarchy ID number <*> (splitOnIgnoreEmpty "," <$> takeUntilP ':') -- comma-separated list of controllers <*> (parseIntoAbsDir =<< takeUntil1P '\n') -- path -- return the prefix of the input until reaching the supplied character. -- the character is also consumed as part of this parser. -- -- this parser succeeds even when the character does not exist in the input takeUntilP :: Char -> Parser Text takeUntilP c = takeWhileP Nothing (/= c) <* optional (char c) -- like 'takeUntilP', but expects a non-empty prefix before the character takeUntil1P :: Char -> Parser Text takeUntil1P c = takeWhile1P Nothing (/= c) <* optional (char c) Data . Text.splitOn , but returns empty list on empty haystack , rather than [ " " ] -- -- >>> Data.Text.splitOn "foo" "" -- [""] -- -- >>> splitOnIgnoreEmpty "foo" "" -- [] splitOnIgnoreEmpty :: Text -> Text -> [Text] splitOnIgnoreEmpty _ "" = [] splitOnIgnoreEmpty s str = Text.splitOn s str ---------- Mounts -- | A mount, as viewed within \/proc\/[pid]\/mountinfo -- -- see proc(5): \/proc\/[pid]\/mountinfo section data Mount = Mount { mountId :: Text , mountParentId :: Text , mountStDev :: Text , mountRoot :: Text , mountPoint :: Text , mountOptions :: Text , mountTags :: [Text] , mountFilesystemType :: Text , mountSource :: Text , mountSuperOptions :: [Text] } deriving (Show) -- | Parse an entire \/proc\/[pid]\/mountinfo file into a list of mounts parseMountInfo :: Parser [Mount] parseMountInfo = some parseSingleMount <* eof -- | Parse a single mount line within \/proc\/[pid]\/mountinfo -- Fields are space - separated -- -- see proc(5): \/proc\/[pid]\/mountinfo section parseSingleMount :: Parser Mount parseSingleMount = Mount <$> field -- id <*> field -- parent id <*> field -- st_dev <*> field -- mount root <*> field -- mount point <*> field -- mount options <*> field `manyTill` separator -- optional mount tags, terminated by "-" <*> field -- filesystem type <*> field -- mount source <*> (splitOnIgnoreEmpty "," <$> field) -- super options <* optional (char '\n') a field in the mountinfo file , terminated by whitespace field :: Parser Text field = lexeme $ takeWhile1P Nothing (not . isSpace) -- separator after optional mount tags ("-") separator :: Parser Char separator = lexeme $ char '-' lexeme :: Parser a -> Parser a lexeme = L.lexeme (skipMany (char ' ')) parseIntoAbsDir :: Text -> Parser (Path Abs Dir) parseIntoAbsDir = either (fail . show) pure . parseAbsDir . Text.unpack | type Parser = Parsec Void Text -- | Parse a file parseFile :: Parser a -> Path b File -> IO a parseFile parser file = either throwIO pure . parse parser (toFilePath file) =<< TIO.readFile (toFilePath file)
null
https://raw.githubusercontent.com/cnr/cgroup-rts-threads/02ad7228948339705faeb789702fcbfb3c823ab1/src/System/CGroup/Types.hs
haskell
| Parsers and types related to cgroups and mounts * CPU quotas * raw cgroups as viewed in \/proc\/$PID\/cgroup * Parser type -------- CPU quotas | A CPU quota is the ratio of CPU time our process can use relative to the scheduler period For example: @ | ratio | description | | ---------------- | ----------- | @ -------- Raw cgroups | A cgroup, as viewed within \/proc\/[pid]\/cgroup see cgroups(7): \/proc\/[pid]\/cgroup section | Parse an entire \/proc\/[pid]\/cgroup file into a list of cgroups hierarchyID:list,of,controllers:path In cgroups version 1, a comma-separated list of controllers exists within each group see cgroups(7): \/proc\/[pid]\/cgroup section hierarchy ID number comma-separated list of controllers path return the prefix of the input until reaching the supplied character. the character is also consumed as part of this parser. this parser succeeds even when the character does not exist in the input like 'takeUntilP', but expects a non-empty prefix before the character >>> Data.Text.splitOn "foo" "" [""] >>> splitOnIgnoreEmpty "foo" "" [] -------- Mounts | A mount, as viewed within \/proc\/[pid]\/mountinfo see proc(5): \/proc\/[pid]\/mountinfo section | Parse an entire \/proc\/[pid]\/mountinfo file into a list of mounts | Parse a single mount line within \/proc\/[pid]\/mountinfo see proc(5): \/proc\/[pid]\/mountinfo section id parent id st_dev mount root mount point mount options optional mount tags, terminated by "-" filesystem type mount source super options separator after optional mount tags ("-") | Parse a file
module System.CGroup.Types ( CPUQuota (..), RawCGroup (..), parseCGroups, * mounts as viewed in \/proc\/$PID\/mountinfo Mount (..), parseMountInfo, Parser, parseFile, ) where import Control.Exception (throwIO) import Data.Char (isSpace) import Data.Ratio import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.IO as TIO import Data.Void (Void) import Path import Text.Megaparsec import Text.Megaparsec.Char import qualified Text.Megaparsec.Char.Lexer as L | 100000 / 100000 | ( 1 ) | | 200000 / 100000 | ( 2 ) | | 50000 / 100000 | ( 3 ) | | / 100000 | ( 4 ) | ( 1 ): we can use up to a single CPU core ( 2 ): we can use up to two CPU cores ( 3 ): the scheduler will give us a single CPU core for up to 50 % of the time ( 4 ): we can use all available CPU resources ( there is no quota ) data CPUQuota = CPUQuota (Ratio Int) | NoQuota deriving (Eq, Ord, Show) data RawCGroup = RawCGroup { rawCGroupId :: Text , rawCGroupControllers :: [Text] , rawCGroupPath :: Path Abs Dir } deriving (Show) parseCGroups :: Parser [RawCGroup] parseCGroups = some parseSingleCGroup <* eof | Parse a single cgroup line within \/proc\/[pid]\/cgroup In cgroups version 2 , the " controllers " section is always an empty string parseSingleCGroup :: Parser RawCGroup parseSingleCGroup = RawCGroup takeUntilP :: Char -> Parser Text takeUntilP c = takeWhileP Nothing (/= c) <* optional (char c) takeUntil1P :: Char -> Parser Text takeUntil1P c = takeWhile1P Nothing (/= c) <* optional (char c) Data . Text.splitOn , but returns empty list on empty haystack , rather than [ " " ] splitOnIgnoreEmpty :: Text -> Text -> [Text] splitOnIgnoreEmpty _ "" = [] splitOnIgnoreEmpty s str = Text.splitOn s str data Mount = Mount { mountId :: Text , mountParentId :: Text , mountStDev :: Text , mountRoot :: Text , mountPoint :: Text , mountOptions :: Text , mountTags :: [Text] , mountFilesystemType :: Text , mountSource :: Text , mountSuperOptions :: [Text] } deriving (Show) parseMountInfo :: Parser [Mount] parseMountInfo = some parseSingleMount <* eof Fields are space - separated parseSingleMount :: Parser Mount parseSingleMount = Mount <* optional (char '\n') a field in the mountinfo file , terminated by whitespace field :: Parser Text field = lexeme $ takeWhile1P Nothing (not . isSpace) separator :: Parser Char separator = lexeme $ char '-' lexeme :: Parser a -> Parser a lexeme = L.lexeme (skipMany (char ' ')) parseIntoAbsDir :: Text -> Parser (Path Abs Dir) parseIntoAbsDir = either (fail . show) pure . parseAbsDir . Text.unpack | type Parser = Parsec Void Text parseFile :: Parser a -> Path b File -> IO a parseFile parser file = either throwIO pure . parse parser (toFilePath file) =<< TIO.readFile (toFilePath file)
3d232477dc0879471926060be408a17b846d2a378221ef55fe3ee0297be3ad54
RedPRL/asai
Syntax.ml
open Asai type tm = tm_ Span.located and tm_ = | Var of string | Lam of string * tm | Ap of tm * tm | Pair of tm * tm | Fst of tm | Snd of tm | Lit of int | Suc of tm | NatRec of tm * tm * tm and tp = | Fun of tp * tp | Tuple of tp * tp | Nat let rec pp_tp fmt = function | Fun (a, b) -> Format.fprintf fmt "(→ %a %a)" pp_tp a pp_tp b | Tuple (a, b) -> Format.fprintf fmt "(× %a %a)" pp_tp a pp_tp b | Nat -> Format.fprintf fmt "ℕ"
null
https://raw.githubusercontent.com/RedPRL/asai/5b06a62676987923a76729ddc4765505aa2cabf8/examples/stlc/Syntax.ml
ocaml
open Asai type tm = tm_ Span.located and tm_ = | Var of string | Lam of string * tm | Ap of tm * tm | Pair of tm * tm | Fst of tm | Snd of tm | Lit of int | Suc of tm | NatRec of tm * tm * tm and tp = | Fun of tp * tp | Tuple of tp * tp | Nat let rec pp_tp fmt = function | Fun (a, b) -> Format.fprintf fmt "(→ %a %a)" pp_tp a pp_tp b | Tuple (a, b) -> Format.fprintf fmt "(× %a %a)" pp_tp a pp_tp b | Nat -> Format.fprintf fmt "ℕ"
14953b414097f4ea3b6b68e521a3b21997747385eae715a4ad84ac677f359595
gonzojive/elephant
query-utils.lisp
-*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Base : 10 -*- ;;; query-utils.lisp -- sets , predicates , etc . ;;; Copyright ( c ) 2009 ;;; <ieslick common-lisp net> ;;; ;;; part of ;;; Elephant : an object - oriented database for Common Lisp ;;; ;;; Elephant users are granted the rights to distribute and use this software as governed by the terms of the Lisp Lesser GNU Public License ;;; (), also known as the LLGPL. ;;; (in-package :elephant) ;;; ================================= ;;; Simple query sets ;;; ================================= (defclass simple-set () ((recs :initarg :recs :accessor set-recs :initform nil) (seq :initarg :seq :accessor set-sequence :initform (make-array 1000 :adjustable nil :fill-pointer 0)))) (defmethod print-object ((set simple-set) stream) (format stream "#<SIMPLE-SET:~A ~A>" (length (set-sequence set)) (set-recs set))) (defun dump-simple-set (set) (map-simple-set #'print set) set) (defun make-simple-set (recs) (make-instance 'simple-set :recs recs)) (defparameter *min-simple-set-extension* 1000) (defun add-row (set values) (assert (valid-row set values)) (vector-push-extend values (set-sequence set) *min-simple-set-extension*)) (defun valid-row (set values) (every #'(lambda (i rec) (if (atom rec) (or (integerp i) (subtypep (type-of i) rec)) t)) values (set-recs set))) (defun sort-set (set rec &optional (pred #'lisp-compare<)) (let ((offset (position rec (set-recs set) :test #'equal))) (assert offset) (setf (set-sequence set) (sort (set-sequence set) pred :key (lambda (values) (nth offset values)))))) (defun intersect-sets (output-recs set1 vrec1 set2 vrec2) "The simple is when we are intersecting on two columns. We back up the join pointer when we have dual sets of duplicate elements." (let* ((seq1 (set-sequence set1)) (v1 (position vrec1 (set-recs set1) :test #'equal)) (seq2 (set-sequence set2)) (v2 (position vrec2 (set-recs set2) :test #'equal)) (imax (length (set-sequence set1))) (jmax (length (set-sequence set2))) (out (make-array (min imax jmax) :fill-pointer 0)) (output-map (output-map output-recs (set-recs set1) (set-recs set2))) (left (nth v1 (aref seq1 0))) (right (nth v2 (aref seq2 0))) (next-left nil) (next-right nil) (i 1) (j 1) (bp 0)) (declare (fixnum i j imax jmax v1 v2 bp) (list left right next-left next-right)) ( ( array t * ) seq1 seq2 out ) ) (unless v1 (error "Dependency ~A not found in ~A with spec ~A" vrec1 set1 (set-recs set1))) (unless v2 (error "Dependency ~A not found in ~A with spec ~A" vrec2 set2 (set-recs set2))) (labels ((maybe-return () (when (and (= imax i) (= jmax j)) (return-from intersect-sets (make-instance 'simple-set :recs output-recs :seq out)))) (increment-left () (setq right right-next) (unless (= imax i) (incf i)) (setq right-next (nth v1 (aref seq1 i)))) (increment-right () (setq left left-next) (unless (= jmax j) (incf j)) (setq left-next (nth v2 (aref seq2 j)))) (track-left-dups () (if (lisp-compare-equal left next-left) (when (not dups-left) (setf dups-left t)) (when dups-left (setf dups-left nil)))) (track-right-dups () (unless dups-right (when (lisp-compare-equal right next-right) (setf dups-right t) (setf bp (1- j))))) (step-on-equal () (cond ((and (not dups-right) (not dups-left)) (increment-right)) (dups-right (increment-right)) ((and (not dups-right) dups-left) (increment-left)))) (step-on-right-greater () (cond (dups-left (increment-right)) ((and dups-right (not dups-left)) (increment-right)) ((and (not dups-right) dups-left) (increment-left)) ((and dups-right dups-left) (step-on-left-greater () (cond ((and (not dups-right) (not dups-left)) (increment-right)) ((and dups-right (not dups-left)) (increment-right)) ((and (not dups-right) dups-left) (increment-left)) ((and dups-right dups-left) (loop (when (or (= i imax) (= j jmax)) (track-right-dups) (track-left-dups) ;; NOTE: Optimize away comparisons when dealing with dups? (cond ((lisp-compare-equal left right) (vector-push (merge-set-rows output-map row1 row2) out) (step-on-equal)) ((lisp-compare< left right) (step-on-right-greater)) (t (step-on-left-greater)))) (defun filter-set (fn set rec) (let ((offset (position rec (set-recs set) :test #'equal)) (out (make-array (length (set-sequence set)) :fill-pointer 0))) (loop for entry across (set-sequence set) do (when (funcall fn (nth offset entry)) (vector-push-extend entry out))) (make-instance 'simple-set :recs (set-recs set) :seq out))) (defun map-simple-set (fn set) (loop for entry across (set-sequence set) do (funcall fn entry))) (defun merge-set-rows (map row1 row2) (loop for entry in map collect (if (car entry) (nth (cdr entry) row2) (nth (cdr entry) row1)))) (defun output-map (out-recs in-recs1 in-recs2) (loop for rec in out-recs collect (let ((pos1 (position rec in-recs1 :test #'equal)) (pos2 (position rec in-recs2 :test #'equal))) (cond (pos1 (cons nil pos1)) (pos2 (cons t pos2)) (t (error "Cannot find output rec ~A in input recs~%~A, ~A" rec in-recs1 in-recs2)))))) (defun make-simple-recs (class slots) (cons class (mapcar (lambda (s) (list s class)) slots))) (defun get-simple-values (instance slots) (if slots (cons (oid instance) (mapcar (lambda (s) (persistent-slot-reader *store-controller* instance s t)) slots)) (cons (oid instance) nil))) (defmacro with-simple-set ((constructor recs) &body body) "Optimization (support insertion of index value w/o slot access" (with-gensyms (r iset) `(let* ((,r ,recs) (,iset (make-simple-set ,r))) (labels ((,constructor (values) (add-row ,iset values))) ,@body ,iset)))) ;;; ================================= ;;; Query sets ;;; ================================= ( defparameter * default - instance - set - size * 100 ) ( defparameter * growth - increment * 1000 ) ;; ;;; An instance set around an array w/ (instance/oid slot-val1 slot-val2 ...) ;; (defstruct instance-set class slots row-size array) ;; (defun make-iset (class slots) ;; (make-instance-set ;; :class class ;; :slots slots ;; :row-size (1+ (length slots)) ;; :array (make-array (* (1+ (length slots)) ;; *default-instance-set-size*) ;; :adjustable t :fill-pointer t))) ;; (defun add-row (set instance values) ;; (let ((array (instance-set-array set))) ;; (vector-push-extend instance array *growth-increment*) ( dolist ( value values ) ;; (vector-push-extend value array *growth-increment*)))) ;; (defun get-row (set nth) ;; (with-slots (row-size array) set ;; (let ((offset (get-row-pointer set nth))) ;; (loop for i from offset below (+ offset row-size) collect ;; (aref array i))))) ;; (defun map-instance-set (fn set) ;; (let ((array (instance-set-array set)) ;; (rlen (instance-set-row-length set))) ;; (loop for i from 0 below (/ (length array) rlen) do ;; (let ((offset (* i rlen))) ;; (apply fn ( loop for j from 1 below rlen collect ;; (aref array (+ offset j)))))))) ;; (defun get-row-pointer (set offset) ;; (* offset (instance-set-row-size set))) ;; (defmacro with-instance-set ((constvar class slots) &rest body) ;; (with-gensyms (c s iset) ;; `(let* ((,c ,class) ;; (,s ,slots) ;; (,iset (make-iset ,c ,s))) ;; (labels ((,constvar (instance) ;; (add-row ,iset instance (slot-values instance slots)))) ;; ,@body ;; ,iset)))) ;; (defmacro with-index-set ((constvar class slots index-slot) &body body) ( with - gensyms ( c s ) ;; `(let* ((,c ,class) ;; (,s ,slots) ( , islot - p , index - slot ) ( , iset ( make - instance - set , c , s ) ) ) ;; (labels ((,constvar (instance value) ( if , islot - p ;; (add-row ,iset instance (cons value (slot-values instance ,slots))) ;; (add-row ,iset instance (slot-values instance ,slots))))) ;; ,@body ;; ,iset)))) ;; (defun slot-values (instance slots) ;; (flet ((curried (slot) ;; (slot-value instance slot))) ;; (mapcar #'curried slots))) ;;; ================================================ ;;; Predicate namespace ;;; ================================================ (defparameter *comparison-functions* `((< >= ,#'< :lt) (<= > ,#'<= :lt) (> <= ,#'> :gt) (>= < ,#'>= :gt) (= != ,#'= :eq) (!= = ,#'(lambda (x y) (not (= x y))) :neq) (string< string>= ,#'string< :lt) (string<= string> ,#'string<= :lt) (string> string<= ,#'string> :gt) (string>= string< ,#'string>= :gt) (string= string!= ,#'equal :eq) (string!= string= ,(lambda (x y) (not (equal x y))) :neq) (lt gte lisp-compare< :lt) (lte gt lisp-compare<= :lt) (gt lte ,#'(lambda (x y) (not (lisp-compare<= x y))) :gt) (gte lt ,#'(lambda (x y) (not (lisp-compare< x y))) :gt) (eq neq ,#'eq :eq) (neq eq ,#'(lambda (x y) (not (eq x y))) :neq) (equal nequal lisp-compare-equal :eq) (nequal equal ,#'(lambda (x y) (not (lisp-compare-equal x y))) :neq) (class nil ,#'(lambda (i cname) (eq (type-of i) cname)) nil) (subclass nil ,#'(lambda (i cname) (subtypep (type-of i) cname)) nil))) (defun predicate-function (pred-name expr) (aif (assoc pred-name *comparison-functions*) (third it) (aif (symbol-function pred-name) pred-name (error "Unknown predicate function ~A in constraint expression ~A" pred-name expr)))) (defun invert-predicate (pred-name expr) (aif (find pred-name *comparison-functions* :key #'second) (predicate-function (second it) expr) (error "Cannot invert predicate name ~A from constraint ~A" pred-name expr))) (defun predicate-range-type (pred) "Is this a less-than, greater-than, equality or non-equality value domain?" (awhen (find pred *comparison-functions* :key #'third) (fourth it))) ;;; ;;; Actual utilities ;;; (defun pairs (list) "Take each set of two elements in the list and make a list one half the size containing a pair of each two items" (labels ((pairing (list accum num) (cond ((null list) (nreverse accum)) ((and (consp list) (null (cdr list))) (nreverse (cons (list (car list) nil) accum))) (t (pairing (cddr list) (cons (list (car list) (cadr list)) accum) (- num 2)))))) (pairing list nil (length list))))
null
https://raw.githubusercontent.com/gonzojive/elephant/b29a012ab75ccea2fc7fc4f1e9d5e821f0bd60bf/src/elephant/query-utils.lisp
lisp
Syntax : ANSI - Common - Lisp ; Base : 10 -*- <ieslick common-lisp net> part of Elephant users are granted the rights to distribute and use this software (), also known as the LLGPL. ================================= Simple query sets ================================= NOTE: Optimize away comparisons when dealing with dups? ================================= Query sets ================================= ;;; An instance set around an array w/ (instance/oid slot-val1 slot-val2 ...) (defstruct instance-set class slots row-size array) (defun make-iset (class slots) (make-instance-set :class class :slots slots :row-size (1+ (length slots)) :array (make-array (* (1+ (length slots)) *default-instance-set-size*) :adjustable t :fill-pointer t))) (defun add-row (set instance values) (let ((array (instance-set-array set))) (vector-push-extend instance array *growth-increment*) (vector-push-extend value array *growth-increment*)))) (defun get-row (set nth) (with-slots (row-size array) set (let ((offset (get-row-pointer set nth))) (loop for i from offset below (+ offset row-size) collect (aref array i))))) (defun map-instance-set (fn set) (let ((array (instance-set-array set)) (rlen (instance-set-row-length set))) (loop for i from 0 below (/ (length array) rlen) do (let ((offset (* i rlen))) (apply fn (aref array (+ offset j)))))))) (defun get-row-pointer (set offset) (* offset (instance-set-row-size set))) (defmacro with-instance-set ((constvar class slots) &rest body) (with-gensyms (c s iset) `(let* ((,c ,class) (,s ,slots) (,iset (make-iset ,c ,s))) (labels ((,constvar (instance) (add-row ,iset instance (slot-values instance slots)))) ,@body ,iset)))) (defmacro with-index-set ((constvar class slots index-slot) &body body) `(let* ((,c ,class) (,s ,slots) (labels ((,constvar (instance value) (add-row ,iset instance (cons value (slot-values instance ,slots))) (add-row ,iset instance (slot-values instance ,slots))))) ,@body ,iset)))) (defun slot-values (instance slots) (flet ((curried (slot) (slot-value instance slot))) (mapcar #'curried slots))) ================================================ Predicate namespace ================================================ Actual utilities
query-utils.lisp -- sets , predicates , etc . Copyright ( c ) 2009 Elephant : an object - oriented database for Common Lisp as governed by the terms of the Lisp Lesser GNU Public License (in-package :elephant) (defclass simple-set () ((recs :initarg :recs :accessor set-recs :initform nil) (seq :initarg :seq :accessor set-sequence :initform (make-array 1000 :adjustable nil :fill-pointer 0)))) (defmethod print-object ((set simple-set) stream) (format stream "#<SIMPLE-SET:~A ~A>" (length (set-sequence set)) (set-recs set))) (defun dump-simple-set (set) (map-simple-set #'print set) set) (defun make-simple-set (recs) (make-instance 'simple-set :recs recs)) (defparameter *min-simple-set-extension* 1000) (defun add-row (set values) (assert (valid-row set values)) (vector-push-extend values (set-sequence set) *min-simple-set-extension*)) (defun valid-row (set values) (every #'(lambda (i rec) (if (atom rec) (or (integerp i) (subtypep (type-of i) rec)) t)) values (set-recs set))) (defun sort-set (set rec &optional (pred #'lisp-compare<)) (let ((offset (position rec (set-recs set) :test #'equal))) (assert offset) (setf (set-sequence set) (sort (set-sequence set) pred :key (lambda (values) (nth offset values)))))) (defun intersect-sets (output-recs set1 vrec1 set2 vrec2) "The simple is when we are intersecting on two columns. We back up the join pointer when we have dual sets of duplicate elements." (let* ((seq1 (set-sequence set1)) (v1 (position vrec1 (set-recs set1) :test #'equal)) (seq2 (set-sequence set2)) (v2 (position vrec2 (set-recs set2) :test #'equal)) (imax (length (set-sequence set1))) (jmax (length (set-sequence set2))) (out (make-array (min imax jmax) :fill-pointer 0)) (output-map (output-map output-recs (set-recs set1) (set-recs set2))) (left (nth v1 (aref seq1 0))) (right (nth v2 (aref seq2 0))) (next-left nil) (next-right nil) (i 1) (j 1) (bp 0)) (declare (fixnum i j imax jmax v1 v2 bp) (list left right next-left next-right)) ( ( array t * ) seq1 seq2 out ) ) (unless v1 (error "Dependency ~A not found in ~A with spec ~A" vrec1 set1 (set-recs set1))) (unless v2 (error "Dependency ~A not found in ~A with spec ~A" vrec2 set2 (set-recs set2))) (labels ((maybe-return () (when (and (= imax i) (= jmax j)) (return-from intersect-sets (make-instance 'simple-set :recs output-recs :seq out)))) (increment-left () (setq right right-next) (unless (= imax i) (incf i)) (setq right-next (nth v1 (aref seq1 i)))) (increment-right () (setq left left-next) (unless (= jmax j) (incf j)) (setq left-next (nth v2 (aref seq2 j)))) (track-left-dups () (if (lisp-compare-equal left next-left) (when (not dups-left) (setf dups-left t)) (when dups-left (setf dups-left nil)))) (track-right-dups () (unless dups-right (when (lisp-compare-equal right next-right) (setf dups-right t) (setf bp (1- j))))) (step-on-equal () (cond ((and (not dups-right) (not dups-left)) (increment-right)) (dups-right (increment-right)) ((and (not dups-right) dups-left) (increment-left)))) (step-on-right-greater () (cond (dups-left (increment-right)) ((and dups-right (not dups-left)) (increment-right)) ((and (not dups-right) dups-left) (increment-left)) ((and dups-right dups-left) (step-on-left-greater () (cond ((and (not dups-right) (not dups-left)) (increment-right)) ((and dups-right (not dups-left)) (increment-right)) ((and (not dups-right) dups-left) (increment-left)) ((and dups-right dups-left) (loop (when (or (= i imax) (= j jmax)) (track-right-dups) (track-left-dups) (cond ((lisp-compare-equal left right) (vector-push (merge-set-rows output-map row1 row2) out) (step-on-equal)) ((lisp-compare< left right) (step-on-right-greater)) (t (step-on-left-greater)))) (defun filter-set (fn set rec) (let ((offset (position rec (set-recs set) :test #'equal)) (out (make-array (length (set-sequence set)) :fill-pointer 0))) (loop for entry across (set-sequence set) do (when (funcall fn (nth offset entry)) (vector-push-extend entry out))) (make-instance 'simple-set :recs (set-recs set) :seq out))) (defun map-simple-set (fn set) (loop for entry across (set-sequence set) do (funcall fn entry))) (defun merge-set-rows (map row1 row2) (loop for entry in map collect (if (car entry) (nth (cdr entry) row2) (nth (cdr entry) row1)))) (defun output-map (out-recs in-recs1 in-recs2) (loop for rec in out-recs collect (let ((pos1 (position rec in-recs1 :test #'equal)) (pos2 (position rec in-recs2 :test #'equal))) (cond (pos1 (cons nil pos1)) (pos2 (cons t pos2)) (t (error "Cannot find output rec ~A in input recs~%~A, ~A" rec in-recs1 in-recs2)))))) (defun make-simple-recs (class slots) (cons class (mapcar (lambda (s) (list s class)) slots))) (defun get-simple-values (instance slots) (if slots (cons (oid instance) (mapcar (lambda (s) (persistent-slot-reader *store-controller* instance s t)) slots)) (cons (oid instance) nil))) (defmacro with-simple-set ((constructor recs) &body body) "Optimization (support insertion of index value w/o slot access" (with-gensyms (r iset) `(let* ((,r ,recs) (,iset (make-simple-set ,r))) (labels ((,constructor (values) (add-row ,iset values))) ,@body ,iset)))) ( defparameter * default - instance - set - size * 100 ) ( defparameter * growth - increment * 1000 ) ( dolist ( value values ) ( loop for j from 1 below rlen collect ( with - gensyms ( c s ) ( , islot - p , index - slot ) ( , iset ( make - instance - set , c , s ) ) ) ( if , islot - p (defparameter *comparison-functions* `((< >= ,#'< :lt) (<= > ,#'<= :lt) (> <= ,#'> :gt) (>= < ,#'>= :gt) (= != ,#'= :eq) (!= = ,#'(lambda (x y) (not (= x y))) :neq) (string< string>= ,#'string< :lt) (string<= string> ,#'string<= :lt) (string> string<= ,#'string> :gt) (string>= string< ,#'string>= :gt) (string= string!= ,#'equal :eq) (string!= string= ,(lambda (x y) (not (equal x y))) :neq) (lt gte lisp-compare< :lt) (lte gt lisp-compare<= :lt) (gt lte ,#'(lambda (x y) (not (lisp-compare<= x y))) :gt) (gte lt ,#'(lambda (x y) (not (lisp-compare< x y))) :gt) (eq neq ,#'eq :eq) (neq eq ,#'(lambda (x y) (not (eq x y))) :neq) (equal nequal lisp-compare-equal :eq) (nequal equal ,#'(lambda (x y) (not (lisp-compare-equal x y))) :neq) (class nil ,#'(lambda (i cname) (eq (type-of i) cname)) nil) (subclass nil ,#'(lambda (i cname) (subtypep (type-of i) cname)) nil))) (defun predicate-function (pred-name expr) (aif (assoc pred-name *comparison-functions*) (third it) (aif (symbol-function pred-name) pred-name (error "Unknown predicate function ~A in constraint expression ~A" pred-name expr)))) (defun invert-predicate (pred-name expr) (aif (find pred-name *comparison-functions* :key #'second) (predicate-function (second it) expr) (error "Cannot invert predicate name ~A from constraint ~A" pred-name expr))) (defun predicate-range-type (pred) "Is this a less-than, greater-than, equality or non-equality value domain?" (awhen (find pred *comparison-functions* :key #'third) (fourth it))) (defun pairs (list) "Take each set of two elements in the list and make a list one half the size containing a pair of each two items" (labels ((pairing (list accum num) (cond ((null list) (nreverse accum)) ((and (consp list) (null (cdr list))) (nreverse (cons (list (car list) nil) accum))) (t (pairing (cddr list) (cons (list (car list) (cadr list)) accum) (- num 2)))))) (pairing list nil (length list))))
54405c5bcbe461b41394d41b8f3eec15173192578df3db7c66d38675f9858c80
zotonic/template_compiler
template_compiler_operators.erl
@author < > 2010 - 2022 %% @doc Operators for expression evaluation in templates Copyright 2010 - 2022 %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. -module(template_compiler_operators). -author("Marc Worrell <>"). -export([ 'not'/3, 'xor'/4, 'and'/4, 'or'/4, concat/4, subtract/4, add/4, sub/4, divide/4, multiply/4, modulo/4, negate/3, ge/4, le/4, gt/4, lt/4, eq/4, ne/4, seq/4, sne/4 ]). 'not'(false, _Runtime, _Context) -> true; 'not'(true, _Runtime, _Context) -> false; 'not'(undefined, _Runtime, _Context) -> true; 'not'(A, Runtime, Context) -> not Runtime:to_bool(A, Context). 'xor'(A, A, _Runtime, _Context) -> false; 'xor'(A, B, Runtime, Context) -> A1 = Runtime:to_simple_value(A, Context), B1 = Runtime:to_simple_value(B, Context), Runtime:to_bool(A1, Context) xor Runtime:to_bool(B1, Context). % 'and' and 'or' are used by the expression compiler. 'and'(A, B, Runtime, Context) -> A1 = Runtime:to_simple_value(A, Context), B1 = Runtime:to_simple_value(B, Context), Runtime:to_bool(A1, Context) andalso Runtime:to_bool(B1, Context). 'or'(A, B, Runtime, Context) -> A1 = Runtime:to_simple_value(A, Context), B1 = Runtime:to_simple_value(B, Context), Runtime:to_bool(A1, Context) orelse Runtime:to_bool(B1, Context). concat(A, undefined, _Runtime, _Context) when is_binary(A) -> A; concat(undefined, B, _Runtime, _Context) when is_binary(B) -> B; concat({trans, _} = Tr, B, Runtime, Context) -> concat(Runtime:to_simple_value(Tr, Context), B, Runtime, Context); concat(A, {trans, _} = Tr, Runtime, Context) -> concat(A, Runtime:to_simple_value(Tr, Context), Runtime, Context); concat(A, undefined, Runtime, Context) -> to_maybe_list(A, Runtime, Context); concat(undefined, B, Runtime, Context) -> to_maybe_list(B, Runtime, Context); concat(A, B, _Runtime, _Context) when is_list(A), is_list(B) -> A++B; concat(A, B, _Runtime, _Context) when is_binary(A), is_binary(B) -> <<A/binary, B/binary>>; concat(A, B, Runtime, Context) when is_binary(A); is_binary(B) -> concat( to_maybe_binary(A, Runtime, Context), to_maybe_binary(B, Runtime, Context), Runtime, Context); concat(A, B, Runtime, Context) -> concat( to_maybe_list(A, Runtime, Context), to_maybe_list(B, Runtime, Context), Runtime, Context). subtract(A, undefined, _Runtime, _Context) -> A; subtract(undefined, _, _Runtime, _Context) -> undefined; subtract(A, B, _Runtime, _Context) when is_list(A), is_list(B) -> A--B; subtract(A, B, Runtime, Context) -> subtract( to_maybe_list(A, Runtime, Context), to_maybe_list(B, Runtime, Context), Runtime, Context). add(A, B, Runtime, Context) -> case to_numbers(A, B, Runtime, Context) of {undefined, _} -> undefined; {_, undefined} -> undefined; {A1, B1} -> A1 + B1 end. sub(A, B, Runtime, Context) -> case to_numbers(A, B, Runtime, Context) of {undefined, _} -> undefined; {_, undefined} -> undefined; {A1, B1} -> A1 - B1 end. divide(A, B, Runtime, Context) -> case to_numbers(A, B, Runtime, Context) of {undefined, _} -> undefined; {_, undefined} -> undefined; {_, 0} -> undefined; {_, 0.0} -> undefined; {A1, B1} -> A1 / B1 end. multiply(A, B, Runtime, Context) -> case to_numbers(A, B, Runtime, Context) of {undefined, _} -> undefined; {_, undefined} -> undefined; {A1, B1} -> A1 * B1 end. modulo(A, B, Runtime, Context) -> case to_numbers(A, B, Runtime, Context) of {undefined, _} -> undefined; {_, undefined} -> undefined; {_, 0} -> undefined; {_, 0.0} -> undefined; {A1, B1} -> A1 rem B1 end. negate(undefined, _Runtime, _Context) -> undefined; negate(A, _Runtime, _Context) when is_number(A) -> 0 - A; negate(A, Runtime, Context) -> negate(to_maybe_integer(A, Runtime, Context), Runtime, Context). ge(Input, Value, Runtime, Context) -> case to_values(Input, Value, Runtime, Context) of {undefined, _} -> undefined; {_, undefined} -> undefined; {A, B} -> A >= B end. le(Input, Value, Runtime, Context) -> case to_values(Input, Value, Runtime, Context) of {undefined, _} -> undefined; {_, undefined} -> undefined; {A, B} -> A =< B end. gt(Input, Value, Runtime, Context) -> case to_values(Input, Value, Runtime, Context) of {undefined, _} -> undefined; {_, undefined} -> undefined; {A, B} -> A > B end. lt(Input, Value, Runtime, Context) -> case to_values(Input, Value, Runtime, Context) of {undefined, _} -> undefined; {_, undefined} -> undefined; {A, B} -> A < B end. eq(A, A, _Runtime, _Context) -> true; eq(Input, Value, Runtime, Context) -> {A, B} = to_values(Input, Value, Runtime, Context), A == B. ne(A, A, _Runtime, _Context) -> false; ne(Input, Value, Runtime, Context) -> {A, B} = to_values(Input, Value, Runtime, Context), A /= B. seq(A, A, _Runtime, _Context) -> true; seq(Input, Value, Runtime, Context) -> A1 = Runtime:to_simple_value(Input, Context), B1 = Runtime:to_simple_value(Value, Context), A1 == B1. sne(A, A, _Runtime, _Context) -> false; sne(Input, Value, Runtime, Context) -> A1 = Runtime:to_simple_value(Input, Context), B1 = Runtime:to_simple_value(Value, Context), A1 /= B1. @doc Convert the two parameters to compatible values to_values(undefined, B, _Runtime, _Context) -> {undefined, B}; to_values(A, undefined, _Runtime, _Context) -> {A, undefined}; to_values({trans, _} = Tr, B, Runtime, Context) -> to_values(Runtime:to_simple_value(Tr, Context), B, Runtime, Context); to_values(A, {trans, _} = Tr, Runtime, Context) -> to_values(A, Runtime:to_simple_value(Tr, Context), Runtime, Context); to_values(A, B, _Runtime, _Context) when is_number(A), is_number(B) -> {A,B}; to_values(A, B, Runtime, Context) when is_boolean(A); is_boolean(B) -> {z_convert:to_bool(Runtime:to_simple_value(A, Context)), z_convert:to_bool(Runtime:to_simple_value(B, Context))}; to_values(A, B, Runtime, Context) when is_integer(A); is_integer(B) -> {to_maybe_integer(A, Runtime, Context), to_maybe_integer(B, Runtime, Context)}; to_values(A, B, Runtime, Context) when is_float(A); is_float(B) -> {to_maybe_float(A, Runtime, Context), to_maybe_float(B, Runtime, Context)}; to_values(A, B, _Runtime, _Context) when is_binary(A), is_binary(B) -> {A,B}; to_values(A, B, _Runtime, _Context) when is_list(A), is_list(B) -> {A,B}; to_values(A, B, Runtime, Context) when is_binary(A); is_binary(B) -> {to_maybe_binary(A, Runtime, Context), to_maybe_binary(B, Runtime, Context)}; to_values(A, B, Runtime, Context) when is_tuple(A), is_tuple(B) -> {Runtime:to_simple_value(A, Context), Runtime:to_simple_value(B, Context)}; to_values(A, B, Runtime, Context) when is_binary(A); is_binary(B) -> {to_maybe_binary(A, Runtime, Context), to_maybe_binary(B, Runtime, Context)}; to_values(A, B, Runtime, Context) -> {to_maybe_list(A, Runtime, Context), to_maybe_list(B, Runtime, Context)}. @doc Convert the two parameters to compatible numerical values to_numbers(undefined, B, _Runtime, _Context) -> {undefined, B}; to_numbers(A, undefined, _Runtime, _Context) -> {A, undefined}; to_numbers(A, B, _Runtime, _Context) when is_number(A), is_number(B) -> {A,B}; to_numbers(A, B, Runtime, Context) when is_float(A); is_float(B) -> {to_maybe_float(A, Runtime, Context), to_maybe_float(B, Runtime, Context)}; to_numbers(A, B, Runtime, Context) -> {to_maybe_integer(A, Runtime, Context), to_maybe_integer(B, Runtime, Context)}. to_maybe_integer(A, _Runtime, _Context) when is_number(A) -> A; to_maybe_integer(A, Runtime, Context) -> try A1 = Runtime:to_simple_value(A, Context), z_convert:to_integer(A1) catch _:_ -> undefined end. to_maybe_float(A, _Runtime, _Context) when is_float(A) -> A; to_maybe_float(A, Runtime, Context) -> try A1 = Runtime:to_simple_value(A, Context), z_convert:to_float(A1) catch _:_ -> undefined end. to_maybe_binary(A, _Runtime, _Context) when is_binary(A) -> A; to_maybe_binary(A, Runtime, Context) -> try A1 = Runtime:to_simple_value(A, Context), z_convert:to_binary(A1) catch _:_ -> undefined end. to_maybe_list(A, _Runtime, _Context) when is_list(A) -> A; to_maybe_list(A, Runtime, Context) -> try A1 = Runtime:to_simple_value(A, Context), z_convert:to_list(A1) catch _:_ -> undefined end.
null
https://raw.githubusercontent.com/zotonic/template_compiler/a92e9bdac8beba1e4ef68f5151ad528b3f0713fb/src/template_compiler_operators.erl
erlang
@doc Operators for expression evaluation in templates you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 'and' and 'or' are used by the expression compiler.
@author < > 2010 - 2022 Copyright 2010 - 2022 Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(template_compiler_operators). -author("Marc Worrell <>"). -export([ 'not'/3, 'xor'/4, 'and'/4, 'or'/4, concat/4, subtract/4, add/4, sub/4, divide/4, multiply/4, modulo/4, negate/3, ge/4, le/4, gt/4, lt/4, eq/4, ne/4, seq/4, sne/4 ]). 'not'(false, _Runtime, _Context) -> true; 'not'(true, _Runtime, _Context) -> false; 'not'(undefined, _Runtime, _Context) -> true; 'not'(A, Runtime, Context) -> not Runtime:to_bool(A, Context). 'xor'(A, A, _Runtime, _Context) -> false; 'xor'(A, B, Runtime, Context) -> A1 = Runtime:to_simple_value(A, Context), B1 = Runtime:to_simple_value(B, Context), Runtime:to_bool(A1, Context) xor Runtime:to_bool(B1, Context). 'and'(A, B, Runtime, Context) -> A1 = Runtime:to_simple_value(A, Context), B1 = Runtime:to_simple_value(B, Context), Runtime:to_bool(A1, Context) andalso Runtime:to_bool(B1, Context). 'or'(A, B, Runtime, Context) -> A1 = Runtime:to_simple_value(A, Context), B1 = Runtime:to_simple_value(B, Context), Runtime:to_bool(A1, Context) orelse Runtime:to_bool(B1, Context). concat(A, undefined, _Runtime, _Context) when is_binary(A) -> A; concat(undefined, B, _Runtime, _Context) when is_binary(B) -> B; concat({trans, _} = Tr, B, Runtime, Context) -> concat(Runtime:to_simple_value(Tr, Context), B, Runtime, Context); concat(A, {trans, _} = Tr, Runtime, Context) -> concat(A, Runtime:to_simple_value(Tr, Context), Runtime, Context); concat(A, undefined, Runtime, Context) -> to_maybe_list(A, Runtime, Context); concat(undefined, B, Runtime, Context) -> to_maybe_list(B, Runtime, Context); concat(A, B, _Runtime, _Context) when is_list(A), is_list(B) -> A++B; concat(A, B, _Runtime, _Context) when is_binary(A), is_binary(B) -> <<A/binary, B/binary>>; concat(A, B, Runtime, Context) when is_binary(A); is_binary(B) -> concat( to_maybe_binary(A, Runtime, Context), to_maybe_binary(B, Runtime, Context), Runtime, Context); concat(A, B, Runtime, Context) -> concat( to_maybe_list(A, Runtime, Context), to_maybe_list(B, Runtime, Context), Runtime, Context). subtract(A, undefined, _Runtime, _Context) -> A; subtract(undefined, _, _Runtime, _Context) -> undefined; subtract(A, B, _Runtime, _Context) when is_list(A), is_list(B) -> A--B; subtract(A, B, Runtime, Context) -> subtract( to_maybe_list(A, Runtime, Context), to_maybe_list(B, Runtime, Context), Runtime, Context). add(A, B, Runtime, Context) -> case to_numbers(A, B, Runtime, Context) of {undefined, _} -> undefined; {_, undefined} -> undefined; {A1, B1} -> A1 + B1 end. sub(A, B, Runtime, Context) -> case to_numbers(A, B, Runtime, Context) of {undefined, _} -> undefined; {_, undefined} -> undefined; {A1, B1} -> A1 - B1 end. divide(A, B, Runtime, Context) -> case to_numbers(A, B, Runtime, Context) of {undefined, _} -> undefined; {_, undefined} -> undefined; {_, 0} -> undefined; {_, 0.0} -> undefined; {A1, B1} -> A1 / B1 end. multiply(A, B, Runtime, Context) -> case to_numbers(A, B, Runtime, Context) of {undefined, _} -> undefined; {_, undefined} -> undefined; {A1, B1} -> A1 * B1 end. modulo(A, B, Runtime, Context) -> case to_numbers(A, B, Runtime, Context) of {undefined, _} -> undefined; {_, undefined} -> undefined; {_, 0} -> undefined; {_, 0.0} -> undefined; {A1, B1} -> A1 rem B1 end. negate(undefined, _Runtime, _Context) -> undefined; negate(A, _Runtime, _Context) when is_number(A) -> 0 - A; negate(A, Runtime, Context) -> negate(to_maybe_integer(A, Runtime, Context), Runtime, Context). ge(Input, Value, Runtime, Context) -> case to_values(Input, Value, Runtime, Context) of {undefined, _} -> undefined; {_, undefined} -> undefined; {A, B} -> A >= B end. le(Input, Value, Runtime, Context) -> case to_values(Input, Value, Runtime, Context) of {undefined, _} -> undefined; {_, undefined} -> undefined; {A, B} -> A =< B end. gt(Input, Value, Runtime, Context) -> case to_values(Input, Value, Runtime, Context) of {undefined, _} -> undefined; {_, undefined} -> undefined; {A, B} -> A > B end. lt(Input, Value, Runtime, Context) -> case to_values(Input, Value, Runtime, Context) of {undefined, _} -> undefined; {_, undefined} -> undefined; {A, B} -> A < B end. eq(A, A, _Runtime, _Context) -> true; eq(Input, Value, Runtime, Context) -> {A, B} = to_values(Input, Value, Runtime, Context), A == B. ne(A, A, _Runtime, _Context) -> false; ne(Input, Value, Runtime, Context) -> {A, B} = to_values(Input, Value, Runtime, Context), A /= B. seq(A, A, _Runtime, _Context) -> true; seq(Input, Value, Runtime, Context) -> A1 = Runtime:to_simple_value(Input, Context), B1 = Runtime:to_simple_value(Value, Context), A1 == B1. sne(A, A, _Runtime, _Context) -> false; sne(Input, Value, Runtime, Context) -> A1 = Runtime:to_simple_value(Input, Context), B1 = Runtime:to_simple_value(Value, Context), A1 /= B1. @doc Convert the two parameters to compatible values to_values(undefined, B, _Runtime, _Context) -> {undefined, B}; to_values(A, undefined, _Runtime, _Context) -> {A, undefined}; to_values({trans, _} = Tr, B, Runtime, Context) -> to_values(Runtime:to_simple_value(Tr, Context), B, Runtime, Context); to_values(A, {trans, _} = Tr, Runtime, Context) -> to_values(A, Runtime:to_simple_value(Tr, Context), Runtime, Context); to_values(A, B, _Runtime, _Context) when is_number(A), is_number(B) -> {A,B}; to_values(A, B, Runtime, Context) when is_boolean(A); is_boolean(B) -> {z_convert:to_bool(Runtime:to_simple_value(A, Context)), z_convert:to_bool(Runtime:to_simple_value(B, Context))}; to_values(A, B, Runtime, Context) when is_integer(A); is_integer(B) -> {to_maybe_integer(A, Runtime, Context), to_maybe_integer(B, Runtime, Context)}; to_values(A, B, Runtime, Context) when is_float(A); is_float(B) -> {to_maybe_float(A, Runtime, Context), to_maybe_float(B, Runtime, Context)}; to_values(A, B, _Runtime, _Context) when is_binary(A), is_binary(B) -> {A,B}; to_values(A, B, _Runtime, _Context) when is_list(A), is_list(B) -> {A,B}; to_values(A, B, Runtime, Context) when is_binary(A); is_binary(B) -> {to_maybe_binary(A, Runtime, Context), to_maybe_binary(B, Runtime, Context)}; to_values(A, B, Runtime, Context) when is_tuple(A), is_tuple(B) -> {Runtime:to_simple_value(A, Context), Runtime:to_simple_value(B, Context)}; to_values(A, B, Runtime, Context) when is_binary(A); is_binary(B) -> {to_maybe_binary(A, Runtime, Context), to_maybe_binary(B, Runtime, Context)}; to_values(A, B, Runtime, Context) -> {to_maybe_list(A, Runtime, Context), to_maybe_list(B, Runtime, Context)}. @doc Convert the two parameters to compatible numerical values to_numbers(undefined, B, _Runtime, _Context) -> {undefined, B}; to_numbers(A, undefined, _Runtime, _Context) -> {A, undefined}; to_numbers(A, B, _Runtime, _Context) when is_number(A), is_number(B) -> {A,B}; to_numbers(A, B, Runtime, Context) when is_float(A); is_float(B) -> {to_maybe_float(A, Runtime, Context), to_maybe_float(B, Runtime, Context)}; to_numbers(A, B, Runtime, Context) -> {to_maybe_integer(A, Runtime, Context), to_maybe_integer(B, Runtime, Context)}. to_maybe_integer(A, _Runtime, _Context) when is_number(A) -> A; to_maybe_integer(A, Runtime, Context) -> try A1 = Runtime:to_simple_value(A, Context), z_convert:to_integer(A1) catch _:_ -> undefined end. to_maybe_float(A, _Runtime, _Context) when is_float(A) -> A; to_maybe_float(A, Runtime, Context) -> try A1 = Runtime:to_simple_value(A, Context), z_convert:to_float(A1) catch _:_ -> undefined end. to_maybe_binary(A, _Runtime, _Context) when is_binary(A) -> A; to_maybe_binary(A, Runtime, Context) -> try A1 = Runtime:to_simple_value(A, Context), z_convert:to_binary(A1) catch _:_ -> undefined end. to_maybe_list(A, _Runtime, _Context) when is_list(A) -> A; to_maybe_list(A, Runtime, Context) -> try A1 = Runtime:to_simple_value(A, Context), z_convert:to_list(A1) catch _:_ -> undefined end.
5d42174bc354e89d00a269ee14fa0dd9a2141570df1527b2d73c7cd49495fac2
mirage/decompress
lzo.mli
type bigstring = (char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t type error = [ `Malformed of string | `Invalid_argument of string | `Invalid_dictionary ] val pp_error : Format.formatter -> error -> unit val uncompress : bigstring -> bigstring -> (bigstring, [> error ]) result * [ uncompress input output ] returns a { i sub - layout } of [ output ] which is the inflated contents of [ input ] . Otherwise , it returns : { ul { - [ ` Malformed ] if the [ input ] is not recognized as a LZO contents . } { - [ ` Invalid_argument ] if [ output ] is not large enough to contain inflated contents . } { - [ ` Invalid_dictionary ] if an { i op - code } of [ input ] refers to an unbound location . } } inflated contents of [input]. Otherwise, it returns: {ul {- [`Malformed] if the [input] is not recognized as a LZO contents.} {- [`Invalid_argument] if [output] is not large enough to contain inflated contents.} {- [`Invalid_dictionary] if an {i op-code} of [input] refers to an unbound location.}} *) val uncompress_with_buffer : ?chunk:int -> bigstring -> (string, [> error ]) result * [ uncompress ? chunk input ] returns a fresh - allocated [ string ] which is the inflated contents of [ input ] . An internal { ! Buffer.t } is used and it can be initialized with [ chunk ] ( default to [ 0x1000 ] ) . Otherwise , it returns same errors as [ uncompress ] . inflated contents of [input]. An internal {!Buffer.t} is used and it can be initialized with [chunk] (default to [0x1000]). Otherwise, it returns same errors as [uncompress]. *) type wrkmem (** Type of an internal {i hash-table} used by {!compress}. *) val make_wrkmem : unit -> wrkmem * [ make_wrkmem ( ) ] returns a fresh - allocated { ! } . val compress : bigstring -> bigstring -> wrkmem -> int * [ compress input output ] deflates [ input ] and produces a LZO contents into [ output ] . It uses [ wrkmem ] to do the deflation . It returns the number of bytes wrotes into [ output ] such as : { [ let len = compress input output wrkmem in Bigarray.Array1.sub output 0 len ] } is the deflated contents of [ input ] . @raise Invalid_argument if [ output ] is not large enough to contain the deflated contents . into [output]. It uses [wrkmem] to do the deflation. It returns the number of bytes wrotes into [output] such as: {[ let len = compress input output wrkmem in Bigarray.Array1.sub output 0 len ]} is the deflated contents of [input]. @raise Invalid_argument if [output] is not large enough to contain the deflated contents. *)
null
https://raw.githubusercontent.com/mirage/decompress/e7e4804047e796b1da6e5181857b49f9ac1c9d1c/lib/lzo.mli
ocaml
* Type of an internal {i hash-table} used by {!compress}.
type bigstring = (char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t type error = [ `Malformed of string | `Invalid_argument of string | `Invalid_dictionary ] val pp_error : Format.formatter -> error -> unit val uncompress : bigstring -> bigstring -> (bigstring, [> error ]) result * [ uncompress input output ] returns a { i sub - layout } of [ output ] which is the inflated contents of [ input ] . Otherwise , it returns : { ul { - [ ` Malformed ] if the [ input ] is not recognized as a LZO contents . } { - [ ` Invalid_argument ] if [ output ] is not large enough to contain inflated contents . } { - [ ` Invalid_dictionary ] if an { i op - code } of [ input ] refers to an unbound location . } } inflated contents of [input]. Otherwise, it returns: {ul {- [`Malformed] if the [input] is not recognized as a LZO contents.} {- [`Invalid_argument] if [output] is not large enough to contain inflated contents.} {- [`Invalid_dictionary] if an {i op-code} of [input] refers to an unbound location.}} *) val uncompress_with_buffer : ?chunk:int -> bigstring -> (string, [> error ]) result * [ uncompress ? chunk input ] returns a fresh - allocated [ string ] which is the inflated contents of [ input ] . An internal { ! Buffer.t } is used and it can be initialized with [ chunk ] ( default to [ 0x1000 ] ) . Otherwise , it returns same errors as [ uncompress ] . inflated contents of [input]. An internal {!Buffer.t} is used and it can be initialized with [chunk] (default to [0x1000]). Otherwise, it returns same errors as [uncompress]. *) type wrkmem val make_wrkmem : unit -> wrkmem * [ make_wrkmem ( ) ] returns a fresh - allocated { ! } . val compress : bigstring -> bigstring -> wrkmem -> int * [ compress input output ] deflates [ input ] and produces a LZO contents into [ output ] . It uses [ wrkmem ] to do the deflation . It returns the number of bytes wrotes into [ output ] such as : { [ let len = compress input output wrkmem in Bigarray.Array1.sub output 0 len ] } is the deflated contents of [ input ] . @raise Invalid_argument if [ output ] is not large enough to contain the deflated contents . into [output]. It uses [wrkmem] to do the deflation. It returns the number of bytes wrotes into [output] such as: {[ let len = compress input output wrkmem in Bigarray.Array1.sub output 0 len ]} is the deflated contents of [input]. @raise Invalid_argument if [output] is not large enough to contain the deflated contents. *)
868112c4e8c429963104d45ef234b3abeded1b8d255d6c9aed56e61ab9bf6353
digitallyinduced/ihp
ApplicationGenerator.hs
module IHP.IDE.CodeGen.ApplicationGenerator (buildPlan) where import IHP.Prelude import IHP.IDE.CodeGen.Types buildPlan :: Text -> IO (Either Text [GeneratorAction]) buildPlan applicationName = if (null applicationName) then do pure $ Left "Application name cannot be empty" else do let applicationName' = ucfirst applicationName pure $ Right $ generateGenericApplication applicationName' generateGenericApplication :: Text -> [GeneratorAction] generateGenericApplication applicationName = let typesHs = "module " <> applicationName <> ".Types where\n\n" <> "import IHP.Prelude\n" <> "import IHP.ModelSupport\n" <> "import Generated.Types\n\n" <> "data " <> applicationName <> "Application = " <> applicationName <> "Application deriving (Eq, Show)\n\n" <> "\n" <> "data StaticController = WelcomeAction deriving (Eq, Show, Data)" <> "\n" routesHs = "module " <> applicationName <> ".Routes where\n" <> "import IHP.RouterPrelude\n" <> "import Generated.Types\n" <> "import " <> applicationName <> ".Types\n\n" <> "-- Generator Marker\n" <> "instance AutoRoute StaticController" frontControllerHs = "module " <> applicationName <> ".FrontController where\n\n" <> "import IHP.RouterPrelude\n" <> "import " <> applicationName <> ".Controller.Prelude\n" <> "import " <> applicationName <> ".View.Layout (defaultLayout)\n\n" <> "-- Controller Imports\n" <> "import " <> applicationName <> ".Controller.Static\n\n" <> "instance FrontController " <> applicationName <> "Application where\n" <> " controllers = \n" <> " [ startPage WelcomeAction\n" <> " -- Generator Marker\n" <> " ]\n\n" <> "instance InitControllerContext " <> applicationName <> "Application where\n" <> " initContext = do\n" <> " setLayout defaultLayout\n" <> " initAutoRefresh\n" controllerPreludeHs = "module " <> applicationName <> ".Controller.Prelude\n" <> "( module " <> applicationName <> ".Types\n" <> ", module Application.Helper.Controller\n" <> ", module IHP.ControllerPrelude\n" <> ", module Generated.Types\n" <> ")\n" <> "where\n\n" <> "import " <> applicationName <> ".Types\n" <> "import Application.Helper.Controller\n" <> "import IHP.ControllerPrelude\n" <> "import Generated.Types\n" <> "import " <> applicationName <> ".Routes\n" viewLayoutHs = "module " <> applicationName <> ".View.Layout (defaultLayout, Html) where\n" <> "\n" <> "import IHP.ViewPrelude\n" <> "import IHP.Environment\n" <> "import qualified Text.Blaze.Html5 as H\n" <> "import qualified Text.Blaze.Html5.Attributes as A\n" <> "import Generated.Types\n" <> "import IHP.Controller.RequestContext\n" <> "import " <> applicationName <> ".Types\n" <> "import " <> applicationName <> ".Routes\n" <> "import Application.Helper.View\n" <> "\n" <> "defaultLayout :: Html -> Html\n" <> "defaultLayout inner = H.docTypeHtml ! A.lang \"en\" $ [hsx|\n" <> "<head>\n" <> " {metaTags}\n" <> "\n" <> " {stylesheets}\n" <> " {scripts}\n" <> "\n" <> " <title>{pageTitleOrDefault \"App\"}</title>\n" <> "</head>\n" <> "<body>\n" <> " <div class=\"container mt-4\">\n" <> " {renderFlashMessages}\n" <> " {inner}\n" <> " </div>\n" <> "</body>\n" <> "|]\n" <> "\n" <> "-- The 'assetPath' function used below appends a `?v=SOME_VERSION` to the static assets in production\n" <> "-- This is useful to avoid users having old CSS and JS files in their browser cache once a new version is deployed\n" <> "-- See for more details\n" <> "\n" <> "stylesheets :: Html\n" <> "stylesheets = [hsx|\n" <> " <link rel=\"stylesheet\" href={assetPath \"/vendor/bootstrap-5.2.1/bootstrap.min.css\"}/>\n" <> " <link rel=\"stylesheet\" href={assetPath \"/vendor/flatpickr.min.css\"}/>\n" <> " <link rel=\"stylesheet\" href={assetPath \"/app.css\"}/>\n" <> " |]\n" <> "\n" <> "scripts :: Html\n" <> "scripts = [hsx|\n" <> " {when isDevelopment devScripts}\n" <> " <script src={assetPath \"/vendor/jquery-3.6.0.slim.min.js\"}></script>\n" <> " <script src={assetPath \"/vendor/timeago.js\"}></script>\n" <> " <script src={assetPath \"/vendor/popper.min.js\"}></script>\n" <> " <script src={assetPath \"/vendor/bootstrap-5.2.1/bootstrap.min.js\"}></script>\n" <> " <script src={assetPath \"/vendor/flatpickr.js\"}></script>\n" <> " <script src={assetPath \"/vendor/morphdom-umd.min.js\"}></script>\n" <> " <script src={assetPath \"/vendor/turbolinks.js\"}></script>\n" <> " <script src={assetPath \"/vendor/turbolinksInstantClick.js\"}></script>\n" <> " <script src={assetPath \"/vendor/turbolinksMorphdom.js\"}></script>\n" <> " <script src={assetPath \"/helpers.js\"}></script>\n" <> " <script src={assetPath \"/ihp-auto-refresh.js\"}></script>\n" <> " <script src={assetPath \"/app.js\"}></script>\n" <> " |]\n" <> "\n" <> "devScripts :: Html\n" <> "devScripts = [hsx|\n" <> " <script id=\"livereload-script\" src={assetPath \"/livereload.js\"} data-ws={liveReloadWebsocketUrl}></script>\n" <> " |]\n" <> "\n" <> "metaTags :: Html\n" <> "metaTags = [hsx|\n" <> " <meta charset=\"utf-8\"/>\n" <> " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"/>\n" <> " <meta property=\"og:title\" content=\"App\"/>\n" <> " <meta property=\"og:type\" content=\"website\"/>\n" <> " <meta property=\"og:url\" content=\"TODO\"/>\n" <> " <meta property=\"og:description\" content=\"TODO\"/>\n" <> " {autoRefreshMeta}\n" <> "|]\n" viewPreludeHs = "module " <> applicationName <> ".View.Prelude\n" <> "( module IHP.ViewPrelude\n" <> ", module " <> applicationName <> ".View.Layout\n" <> ", module Generated.Types\n" <> ", module " <> applicationName <> ".Types\n" <> ", module Application.Helper.View\n" <> ") where\n" <> "\n" <> "import IHP.ViewPrelude\n" <> "import " <> applicationName <> ".View.Layout\n" <> "import Generated.Types\n" <> "import " <> applicationName <> ".Types\n" <> "import " <> applicationName <> ".Routes ()\n" <> "import Application.Helper.View\n" welcomeControllerStaticHs = "module " <> applicationName <> ".Controller.Static where\n" <> "import " <> applicationName <>".Controller.Prelude\n" <> "import " <> applicationName <>".View.Static.Welcome\n" <> "\n" <> "instance Controller StaticController where\n" <> " action WelcomeAction = render WelcomeView\n" welcomeViewStaticHs = "module " <> applicationName <> ".View.Static.Welcome where\n" <>"import " <> applicationName <> ".View.Prelude\n" <>"\n" <>"data WelcomeView = WelcomeView\n" <>"\n" <>"instance View WelcomeView where\n" <>" html WelcomeView = [hsx|\n" <>" <div style=\"background-color: #657b83; padding: 2rem; color:hsla(196, 13%, 96%, 1); border-radius: 4px\">\n" <>" <div style=\"max-width: 800px; margin-left: auto; margin-right: auto\">\n" <>" <h1 style=\"margin-bottom: 2rem; font-size: 2rem; font-weight: 300; border-bottom: 1px solid white; padding-bottom: 0.25rem; border-color: hsla(196, 13%, 60%, 1)\">\n" <>" IHP\n" <>" </h1>\n" <>"\n" <>" <h2 style=\"margin-top: 0; margin-bottom: 0rem; font-weight: 900; font-size: 3rem\">\n" <>" It's working!\n" <>" </h2>\n" <>"\n" <>" <p style=\"margin-top: 1rem; font-size: 1.75rem; font-weight: 600; color:hsla(196, 13%, 80%, 1)\">\n" <>" Your new application is up and running.\n" <>" </p>\n" <>"\n" <>" <p>\n" <>" <a\n" <>" href=\"\"\n" <>" style=\"margin-top: 2rem; background-color: #268bd2; padding: 1rem; border-radius: 3px; color: hsla(205, 69%, 98%, 1); text-decoration: none; font-weight: bold; display: inline-block; box-shadow: 0 4px 6px hsla(205, 69%, 0%, 0.08); transition: box-shadow 0.2s; transition: transform 0.2s;\"\n" <>" target=\"_blank\"\n" <>" >Join our community on Slack!</a>\n" <>" </p>\n" <>"\n" <>" <a href=\"-first-project.html\" style=\"margin-top: 2rem; background-color: #268bd2; padding: 1rem; border-radius: 3px; color: hsla(205, 69%, 98%, 1); text-decoration: none; font-weight: bold; display: inline-block; box-shadow: 0 4px 6px hsla(205, 69%, 0%, 0.08); transition: box-shadow 0.2s; transition: transform 0.2s;\" target=\"_blank\">\n" <>" Learn the Next Steps in the Documentation\n" <>" </a>\n" <>" </div>\n" <>" </div>\n" <>"\n" <>" <div style=\"max-width: 800px; margin-left: auto; margin-right: auto; margin-top: 4rem\">\n" <>" <img src=\"/ihp-welcome-icon.svg\" alt=\"/ihp-welcome-icon\" style=\"width:100%;\">\n" <>" <p style=\"color: hsla(196, 13%, 50%, 1); margin-top: 4rem\">\n" <>" You can modify this start page by making changes to \"./Web/View/Static/Welcome.hs\".\n" <>" </p>\n" <>" </div> \n" <>"|]" in [ EnsureDirectory { directory = applicationName } , EnsureDirectory { directory = applicationName <> "/Controller" } , EnsureDirectory { directory = applicationName <> "/View" } , EnsureDirectory { directory = applicationName <> "/View/Static" } , AddImport { filePath = "Main.hs", fileContent = "import " <> applicationName <> ".FrontController" } , AddImport { filePath = "Main.hs", fileContent = "import " <> applicationName <> ".Types" } , AddMountToFrontController { filePath = "Main.hs", applicationName = applicationName } , CreateFile { filePath = applicationName <> "/Types.hs", fileContent = typesHs } , CreateFile { filePath = applicationName <> "/Routes.hs", fileContent = routesHs } , CreateFile { filePath = applicationName <> "/FrontController.hs", fileContent = frontControllerHs } , CreateFile { filePath = applicationName <> "/Controller/Prelude.hs", fileContent = controllerPreludeHs } , CreateFile { filePath = applicationName <> "/View/Layout.hs", fileContent = viewLayoutHs } , CreateFile { filePath = applicationName <> "/View/Prelude.hs", fileContent = viewPreludeHs } , CreateFile { filePath = applicationName <> "/Controller/Static.hs", fileContent = welcomeControllerStaticHs } , CreateFile { filePath = applicationName <> "/View/Static/Welcome.hs", fileContent = welcomeViewStaticHs } ]
null
https://raw.githubusercontent.com/digitallyinduced/ihp/ca4691970a130a1589506c66fe8257ac8670e905/IHP/IDE/CodeGen/ApplicationGenerator.hs
haskell
module IHP.IDE.CodeGen.ApplicationGenerator (buildPlan) where import IHP.Prelude import IHP.IDE.CodeGen.Types buildPlan :: Text -> IO (Either Text [GeneratorAction]) buildPlan applicationName = if (null applicationName) then do pure $ Left "Application name cannot be empty" else do let applicationName' = ucfirst applicationName pure $ Right $ generateGenericApplication applicationName' generateGenericApplication :: Text -> [GeneratorAction] generateGenericApplication applicationName = let typesHs = "module " <> applicationName <> ".Types where\n\n" <> "import IHP.Prelude\n" <> "import IHP.ModelSupport\n" <> "import Generated.Types\n\n" <> "data " <> applicationName <> "Application = " <> applicationName <> "Application deriving (Eq, Show)\n\n" <> "\n" <> "data StaticController = WelcomeAction deriving (Eq, Show, Data)" <> "\n" routesHs = "module " <> applicationName <> ".Routes where\n" <> "import IHP.RouterPrelude\n" <> "import Generated.Types\n" <> "import " <> applicationName <> ".Types\n\n" <> "-- Generator Marker\n" <> "instance AutoRoute StaticController" frontControllerHs = "module " <> applicationName <> ".FrontController where\n\n" <> "import IHP.RouterPrelude\n" <> "import " <> applicationName <> ".Controller.Prelude\n" <> "import " <> applicationName <> ".View.Layout (defaultLayout)\n\n" <> "-- Controller Imports\n" <> "import " <> applicationName <> ".Controller.Static\n\n" <> "instance FrontController " <> applicationName <> "Application where\n" <> " controllers = \n" <> " [ startPage WelcomeAction\n" <> " -- Generator Marker\n" <> " ]\n\n" <> "instance InitControllerContext " <> applicationName <> "Application where\n" <> " initContext = do\n" <> " setLayout defaultLayout\n" <> " initAutoRefresh\n" controllerPreludeHs = "module " <> applicationName <> ".Controller.Prelude\n" <> "( module " <> applicationName <> ".Types\n" <> ", module Application.Helper.Controller\n" <> ", module IHP.ControllerPrelude\n" <> ", module Generated.Types\n" <> ")\n" <> "where\n\n" <> "import " <> applicationName <> ".Types\n" <> "import Application.Helper.Controller\n" <> "import IHP.ControllerPrelude\n" <> "import Generated.Types\n" <> "import " <> applicationName <> ".Routes\n" viewLayoutHs = "module " <> applicationName <> ".View.Layout (defaultLayout, Html) where\n" <> "\n" <> "import IHP.ViewPrelude\n" <> "import IHP.Environment\n" <> "import qualified Text.Blaze.Html5 as H\n" <> "import qualified Text.Blaze.Html5.Attributes as A\n" <> "import Generated.Types\n" <> "import IHP.Controller.RequestContext\n" <> "import " <> applicationName <> ".Types\n" <> "import " <> applicationName <> ".Routes\n" <> "import Application.Helper.View\n" <> "\n" <> "defaultLayout :: Html -> Html\n" <> "defaultLayout inner = H.docTypeHtml ! A.lang \"en\" $ [hsx|\n" <> "<head>\n" <> " {metaTags}\n" <> "\n" <> " {stylesheets}\n" <> " {scripts}\n" <> "\n" <> " <title>{pageTitleOrDefault \"App\"}</title>\n" <> "</head>\n" <> "<body>\n" <> " <div class=\"container mt-4\">\n" <> " {renderFlashMessages}\n" <> " {inner}\n" <> " </div>\n" <> "</body>\n" <> "|]\n" <> "\n" <> "-- The 'assetPath' function used below appends a `?v=SOME_VERSION` to the static assets in production\n" <> "-- This is useful to avoid users having old CSS and JS files in their browser cache once a new version is deployed\n" <> "-- See for more details\n" <> "\n" <> "stylesheets :: Html\n" <> "stylesheets = [hsx|\n" <> " <link rel=\"stylesheet\" href={assetPath \"/vendor/bootstrap-5.2.1/bootstrap.min.css\"}/>\n" <> " <link rel=\"stylesheet\" href={assetPath \"/vendor/flatpickr.min.css\"}/>\n" <> " <link rel=\"stylesheet\" href={assetPath \"/app.css\"}/>\n" <> " |]\n" <> "\n" <> "scripts :: Html\n" <> "scripts = [hsx|\n" <> " {when isDevelopment devScripts}\n" <> " <script src={assetPath \"/vendor/jquery-3.6.0.slim.min.js\"}></script>\n" <> " <script src={assetPath \"/vendor/timeago.js\"}></script>\n" <> " <script src={assetPath \"/vendor/popper.min.js\"}></script>\n" <> " <script src={assetPath \"/vendor/bootstrap-5.2.1/bootstrap.min.js\"}></script>\n" <> " <script src={assetPath \"/vendor/flatpickr.js\"}></script>\n" <> " <script src={assetPath \"/vendor/morphdom-umd.min.js\"}></script>\n" <> " <script src={assetPath \"/vendor/turbolinks.js\"}></script>\n" <> " <script src={assetPath \"/vendor/turbolinksInstantClick.js\"}></script>\n" <> " <script src={assetPath \"/vendor/turbolinksMorphdom.js\"}></script>\n" <> " <script src={assetPath \"/helpers.js\"}></script>\n" <> " <script src={assetPath \"/ihp-auto-refresh.js\"}></script>\n" <> " <script src={assetPath \"/app.js\"}></script>\n" <> " |]\n" <> "\n" <> "devScripts :: Html\n" <> "devScripts = [hsx|\n" <> " <script id=\"livereload-script\" src={assetPath \"/livereload.js\"} data-ws={liveReloadWebsocketUrl}></script>\n" <> " |]\n" <> "\n" <> "metaTags :: Html\n" <> "metaTags = [hsx|\n" <> " <meta charset=\"utf-8\"/>\n" <> " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"/>\n" <> " <meta property=\"og:title\" content=\"App\"/>\n" <> " <meta property=\"og:type\" content=\"website\"/>\n" <> " <meta property=\"og:url\" content=\"TODO\"/>\n" <> " <meta property=\"og:description\" content=\"TODO\"/>\n" <> " {autoRefreshMeta}\n" <> "|]\n" viewPreludeHs = "module " <> applicationName <> ".View.Prelude\n" <> "( module IHP.ViewPrelude\n" <> ", module " <> applicationName <> ".View.Layout\n" <> ", module Generated.Types\n" <> ", module " <> applicationName <> ".Types\n" <> ", module Application.Helper.View\n" <> ") where\n" <> "\n" <> "import IHP.ViewPrelude\n" <> "import " <> applicationName <> ".View.Layout\n" <> "import Generated.Types\n" <> "import " <> applicationName <> ".Types\n" <> "import " <> applicationName <> ".Routes ()\n" <> "import Application.Helper.View\n" welcomeControllerStaticHs = "module " <> applicationName <> ".Controller.Static where\n" <> "import " <> applicationName <>".Controller.Prelude\n" <> "import " <> applicationName <>".View.Static.Welcome\n" <> "\n" <> "instance Controller StaticController where\n" <> " action WelcomeAction = render WelcomeView\n" welcomeViewStaticHs = "module " <> applicationName <> ".View.Static.Welcome where\n" <>"import " <> applicationName <> ".View.Prelude\n" <>"\n" <>"data WelcomeView = WelcomeView\n" <>"\n" <>"instance View WelcomeView where\n" <>" html WelcomeView = [hsx|\n" <>" <div style=\"background-color: #657b83; padding: 2rem; color:hsla(196, 13%, 96%, 1); border-radius: 4px\">\n" <>" <div style=\"max-width: 800px; margin-left: auto; margin-right: auto\">\n" <>" <h1 style=\"margin-bottom: 2rem; font-size: 2rem; font-weight: 300; border-bottom: 1px solid white; padding-bottom: 0.25rem; border-color: hsla(196, 13%, 60%, 1)\">\n" <>" IHP\n" <>" </h1>\n" <>"\n" <>" <h2 style=\"margin-top: 0; margin-bottom: 0rem; font-weight: 900; font-size: 3rem\">\n" <>" It's working!\n" <>" </h2>\n" <>"\n" <>" <p style=\"margin-top: 1rem; font-size: 1.75rem; font-weight: 600; color:hsla(196, 13%, 80%, 1)\">\n" <>" Your new application is up and running.\n" <>" </p>\n" <>"\n" <>" <p>\n" <>" <a\n" <>" href=\"\"\n" <>" style=\"margin-top: 2rem; background-color: #268bd2; padding: 1rem; border-radius: 3px; color: hsla(205, 69%, 98%, 1); text-decoration: none; font-weight: bold; display: inline-block; box-shadow: 0 4px 6px hsla(205, 69%, 0%, 0.08); transition: box-shadow 0.2s; transition: transform 0.2s;\"\n" <>" target=\"_blank\"\n" <>" >Join our community on Slack!</a>\n" <>" </p>\n" <>"\n" <>" <a href=\"-first-project.html\" style=\"margin-top: 2rem; background-color: #268bd2; padding: 1rem; border-radius: 3px; color: hsla(205, 69%, 98%, 1); text-decoration: none; font-weight: bold; display: inline-block; box-shadow: 0 4px 6px hsla(205, 69%, 0%, 0.08); transition: box-shadow 0.2s; transition: transform 0.2s;\" target=\"_blank\">\n" <>" Learn the Next Steps in the Documentation\n" <>" </a>\n" <>" </div>\n" <>" </div>\n" <>"\n" <>" <div style=\"max-width: 800px; margin-left: auto; margin-right: auto; margin-top: 4rem\">\n" <>" <img src=\"/ihp-welcome-icon.svg\" alt=\"/ihp-welcome-icon\" style=\"width:100%;\">\n" <>" <p style=\"color: hsla(196, 13%, 50%, 1); margin-top: 4rem\">\n" <>" You can modify this start page by making changes to \"./Web/View/Static/Welcome.hs\".\n" <>" </p>\n" <>" </div> \n" <>"|]" in [ EnsureDirectory { directory = applicationName } , EnsureDirectory { directory = applicationName <> "/Controller" } , EnsureDirectory { directory = applicationName <> "/View" } , EnsureDirectory { directory = applicationName <> "/View/Static" } , AddImport { filePath = "Main.hs", fileContent = "import " <> applicationName <> ".FrontController" } , AddImport { filePath = "Main.hs", fileContent = "import " <> applicationName <> ".Types" } , AddMountToFrontController { filePath = "Main.hs", applicationName = applicationName } , CreateFile { filePath = applicationName <> "/Types.hs", fileContent = typesHs } , CreateFile { filePath = applicationName <> "/Routes.hs", fileContent = routesHs } , CreateFile { filePath = applicationName <> "/FrontController.hs", fileContent = frontControllerHs } , CreateFile { filePath = applicationName <> "/Controller/Prelude.hs", fileContent = controllerPreludeHs } , CreateFile { filePath = applicationName <> "/View/Layout.hs", fileContent = viewLayoutHs } , CreateFile { filePath = applicationName <> "/View/Prelude.hs", fileContent = viewPreludeHs } , CreateFile { filePath = applicationName <> "/Controller/Static.hs", fileContent = welcomeControllerStaticHs } , CreateFile { filePath = applicationName <> "/View/Static/Welcome.hs", fileContent = welcomeViewStaticHs } ]
ecaa37c483dbb53988f2655ec770051bd7a1873373c5c9b3f23800ffe5d7ce3a
Deducteam/Logipedia
holstt.ml
module BasicHol = struct Defining basic hol structures : terms , types , proofs (* Inspired from HOL Light fusion files *) type tyOp = string type const = string type hol_type = Tyvar of string | Tyapp of tyOp * hol_type list let dummy_type = Tyvar("dummy") type term = Var of string * hol_type | Const of const * hol_type | Comb of term * term | Abs of term * term let dummy_term = Var("dummy",dummy_type) type hyp = term list type proof = Axiom_proof of term | Thm of string | Rule of string * term list * proof list | Refl_proof of term | Sym_proof of proof | Trans_proof of proof * proof | Mk_comb_proof of proof * proof | Abs_proof of term * proof | Beta_conv_proof of term | Assume_proof of term | Eq_mp_proof of proof * proof | Deduct_antisym_rule_proof of proof * proof | Prove_hyp_proof of proof * proof | Subst_proof of ((hol_type * hol_type) list * (term * term) list) * proof | New_basic_definition_proof of string * string * term | New_basic_type_definition_proof_left of string * (string * string) * proof | New_basic_type_definition_proof_right of string * (string * string) * proof let dummy_proof = Axiom_proof(dummy_term) type thm = Sequent of (string * hyp * term * proof) (* Handling names, namespaces, and basic names coming from sttfa *) let mk_name namespace name = let mk_namespace md = List.fold_left (fun s x -> s^x^".") "" md in (mk_namespace namespace)^name let arrow_name () = mk_name [] "->" let bool_name () = mk_name [] "bool" let equal_name () = mk_name [] "=" let impl_name () = mk_name [] "==>" let forall_name () = mk_name [] "!" Building hol types let mk_tyOp name = name let arrow_tyOp () = mk_tyOp (arrow_name ()) let bool_tyOp () = mk_tyOp (bool_name ()) let mk_varType name = Tyvar(name) let mk_list l = l let ty_of_tyOp (tyop: tyOp) (tys:hol_type list) : hol_type = Tyapp (tyop,tys) let mk_arrow_type tyl tyr : hol_type = ty_of_tyOp (arrow_tyOp ()) [tyl;tyr] let mk_bool_type () : hol_type = ty_of_tyOp (bool_tyOp ()) [] let mk_equal_type ty : hol_type = mk_arrow_type ty (mk_arrow_type ty (mk_bool_type ())) let mk_impl_type () = mk_arrow_type (mk_bool_type ()) (mk_arrow_type (mk_bool_type ()) (mk_bool_type())) let mk_forall_type ty = mk_arrow_type (mk_arrow_type ty (mk_bool_type ())) (mk_bool_type ()) Building hol terms let mk_var name ty : term = Var (name,ty) let mk_var_term v = v let mk_app_term f t : term = Comb (f,t) let mk_abs_term v t : term = Abs (v,t) let term_of_const cst ty : term = Const (cst,ty) let const_of_name name = name let mk_equal_term left right ty = let ty = mk_equal_type ty in let cst = term_of_const (const_of_name (equal_name ())) ty in mk_app_term (mk_app_term cst left) right Building hol proofs let mk_refl term = Refl_proof(term) let mk_appThm pil pir = Mk_comb_proof(pil,pir) let mk_absThm var pi = Abs_proof(var,pi) let mk_sym pi = Sym_proof(pi) let mk_betaConv term = Beta_conv_proof(term) let mk_trans pil pir = Trans_proof(pil,pir) let mk_subst tylist tlist pi = Subst_proof((tylist,tlist),pi) let mk_eqMp pil pir = Eq_mp_proof(pir,pil) let mk_proveHyp pil pir = Prove_hyp_proof(pil,pir) let mk_assume term = Assume_proof(term) let mk_deductAntiSym pil pir = Deduct_antisym_rule_proof(pil,pir) let true_name () = mk_name [] "T" let and_name () = mk_name [] "/\\\\" let mk_true_type () = mk_bool_type () let mk_and_type () = mk_arrow_type (mk_bool_type ()) (mk_arrow_type (mk_bool_type ()) (mk_bool_type())) let mk_true_term () = term_of_const (const_of_name (true_name ())) (mk_true_type ()) let mk_and () = term_of_const (const_of_name (and_name ())) (mk_and_type ()) let mk_and_term left right = mk_app_term (mk_app_term (mk_and ()) left) right let mk_impl () = term_of_const (const_of_name (impl_name ())) (mk_impl_type ()) let mk_impl_term left right = mk_app_term (mk_app_term (mk_impl ()) left) right let mk_forall ty = term_of_const (const_of_name (forall_name ())) (mk_forall_type ty) let mk_forall_term f ty = mk_app_term (mk_forall ty) f let mk_axiom_true () = (*Sequent("TRUTH",[],mk_true_term (),*) Thm("TRUTH") (* Define conjunction *) let mk_axiom_and_ () = Thm("AND_DEF") proof of tl'=tr ' with et tr ->B tr ' and thm a proof of tl = tr let beta_equal thm tl tr = let left = mk_sym (mk_betaConv tl) in let right = mk_betaConv tr in let trans = mk_trans left thm in mk_trans trans right (* Apply a beta-conversion to the right-hand side/left-hand side of a binary op *) let beta_right pi = Rule("CONV_RULE (RAND_CONV BETA_CONV)",[],[pi]) let beta_left pi = Rule("CONV_RULE (LAND_CONV BETA_CONV)",[],[pi]) (* Beta-reduce right-hand side of the definition of and *) let mk_axiom_and () = beta_right (beta_right (mk_axiom_and_ ())) (* Same for implication *) let mk_axiom_impl_ () = Thm("IMP_DEF") let mk_axiom_impl () = beta_right (beta_right (mk_axiom_impl_ ())) (* Same for forall *) let mk_axiom_forall_ () = Thm("FORALL_DEF") let mk_axiom_forall () = beta_right (beta_right (mk_axiom_forall_ ())) (* Natural deduction rules *) let mk_rule_intro_forall name ty pi = Rule("GEN",[mk_var name ty],[pi]) let mk_rule_elim_forall comment t pi = Rule(comment^"SPEC",[t],[pi]) let proj_left pi = Rule("CONJUNCT1",[],[pi]) let proj_right pi = Rule("CONJUNCT2",[],[pi]) let mk_rule_intro_impl t pi = Rule("DISCH",[t],[pi]) let mk_rule_elim_impl piimp pi = Rule("MP",[],[piimp;pi]) let mk_impl_equal eqp eqq = Mk_comb_proof(Mk_comb_proof(Refl_proof(mk_impl ()),eqp),eqq) let mk_forall_equal eq ty = Mk_comb_proof(Refl_proof(mk_forall ty),eq) (* Prove beta-delta-conversion between terms *) let conv_proof comment t pi = Rule(comment^"CONV_CONV_rule",[t],[pi]) end module PrintHol = struct include BasicHol Print HOL objects , recognizable by HOL Light parser let oc = ref Format.std_formatter let set_oc f = oc := f let rec print_list s d1 d2 print_object out = function [] -> () | [obj] -> Format.fprintf out "%s%a%s" d1 print_object obj d2 | hd::q -> Format.fprintf out "%s%a%s%s%a" d1 print_object hd d2 s (print_list s d1 d2 print_object) q (* Print HOL types *) let rec print_type_rec out = function Tyvar name -> Format.fprintf out "%s" name | Tyapp (tyop,[]) -> Format.fprintf out "%s" tyop | Tyapp (tyop,tylist) when tyop = "->" -> Format.fprintf out "%a -> %a" print_type_atomic (List.hd tylist) print_type_atomic (List.hd (List.tl tylist)) | Tyapp (tyop,tylist) -> Format.fprintf out "%s %a" tyop (print_list " " "" "" print_type_atomic) tylist and print_type_atomic out t = match t with Tyapp(tyop,_) when tyop = "->" -> Format.fprintf out "(%a)" print_type_rec t | _ -> print_type_rec out t let print_type out t = Format.fprintf out "`:%a`" print_type_rec t (* Print HOL terms *) let print_var out = function | Var(name,ty) -> Format.fprintf out "%s : %a" name print_type_rec ty | _ -> failwith "Not a variable\n" let rec print_term_rec b out = function Var(name,ty) when b -> Format.fprintf out "%a" (print_term_atomic b) (Var(name,ty)) | Var(name,_) -> Format.fprintf out "%s" name | Const(cst,_) -> Format.fprintf out "%s" cst | Comb(f,t) -> begin match f,t with Const("!",_),Abs(v,t) -> Format.fprintf out "! %a. %a" print_var v (print_term_atomic b) t | Comb(Const(s,_),t1),_ when (s = "==>" || s = "/\\" || s = "=") -> Format.fprintf out "%a %s %a" (print_term_atomic b) t1 s (print_term_atomic b) t | _ -> Format.fprintf out "%a %a" (print_term_atomic b) f (print_term_atomic b) t end | Abs(v,t) -> Format.fprintf out "\\ %a. %a" print_var v (print_term_atomic b) t and print_term_atomic b out t = match t with Comb _ | Abs _ -> Format.fprintf out "(%a)" (print_term_rec b) t | Var _ when b -> Format.fprintf out "(%a)" print_var t | _ -> print_term_rec b out t let print_term b out t = Format.fprintf out "`%a`" (print_term_rec b) t Print HOL proofs Observation : no " proof " object in HOL Light ! Here : using proof squeleton to build HOL Light theorems let rec print_proof_rec out = let print_term_proof = print_term true in function Axiom_proof(t) -> Format.fprintf out "@[new_axiom %a@]@," print_term_proof t | Thm(th) -> Format.fprintf out "@[%s@]@," th | Rule (rule,tlist,pilist) -> Format.fprintf out "@[<hov>%s %a @,@[<hov>%a@]@,@]@," rule (print_list " " "" "" print_term_proof) tlist (print_list " " "(" ")" print_proof_rec) pilist | Refl_proof(t) -> Format.fprintf out "@[<hov>REFL %a@]@," print_term_proof t | Sym_proof(pi) -> Format.fprintf out "@[<hov>SYM (%a)@]@," print_proof_rec pi | Trans_proof(pi1,pi2) -> Format.fprintf out "@;@[<hov>TRANS @[<hov>(%a)@]@, @[<hov>(%a)@]@,@]@," print_proof_rec pi1 print_proof_rec pi2 | Mk_comb_proof(pi1,pi2) -> Format.fprintf out "@\n@[<hov>MK_COMB (@[%a@]@,,@[%a@]@,)@]@," print_proof_rec pi1 print_proof_rec pi2 | Abs_proof(t,pi) -> Format.fprintf out "@[<hov>ABS %a @[(%a)@]@,@]@," print_term_proof t print_proof_rec pi | Beta_conv_proof(t) -> Format.fprintf out "@[<hov>BETA_CONV %a@]@," print_term_proof t | Assume_proof(t) -> Format.fprintf out "@[<hov>ASSUME %a@]@," print_term_proof t | Eq_mp_proof(pi1,pi2) -> Format.fprintf out "@[<hov>EQ_MP @[<hov>(%a)@]@, @[<hov>(%a)@]@,@]@," print_proof_rec pi1 print_proof_rec pi2 | Deduct_antisym_rule_proof(pi1,pi2) -> Format.fprintf out "@[<hov>DEDUCT_ANTISYM_RULE @[<hov>(%a)@]@, @[<hov>(%a)@]@,@]@," print_proof_rec pi1 print_proof_rec pi2 | Prove_hyp_proof(pi1,pi2) -> Format.fprintf out "@[<hov>PROVE_HYP @[<hov>(%a)@]@, @[<hov>(%a)@]@,@]@," print_proof_rec pi1 print_proof_rec pi2 | Subst_proof(lists,pi) -> let tylist,tlist = lists in let print_couple_rev print_object out pair = let (x,y)=pair in Format.fprintf out "(%a,%a)" print_object y print_object x in Format.fprintf out "@[<hov>PINST [%a] [%a] @[<hov>(%a)@]@,@]@," (print_list ";" "" "" (print_couple_rev print_type)) tylist (print_list ";" "" "" (print_couple_rev print_term_proof)) tlist print_proof_rec pi (* Basic definitions must stand by themselves *) | New_basic_definition_proof(thm_name,name,t) -> Format.fprintf out "@[<hov>new_basic_definition %a@]@,;;\n\n" print_term_proof t; Format.fprintf out "let _ = (new_defs := (\"%s\",%s)::!new_defs)" name thm_name | New_basic_type_definition_proof_left(s,(s1,s2),pi) -> Format.fprintf out "@[<hov>fst (new_basic_type_definition (%s) (%s,%s) (%a))@]@," s s1 s2 print_proof_rec pi | New_basic_type_definition_proof_right(s,(s1,s2),pi) -> Format.fprintf out "@[<hov>snd (new_basic_type_definition (%s) (%s,%s) (%a))@]@," s s1 s2 print_proof_rec pi (* Print statement of theorems (not useful to build them, but useful to visualize them)*) let print_thm_debug out = function Sequent(name,hyps,t,_) -> Format.fprintf out "(*%s : %a |- %a*)\n" name (print_list ";" "" "" (print_term false)) hyps (print_term false) t (* Define whole theorem *) let print_thm out = function Sequent(name,_,_,pi) -> Format.fprintf out "let %s =@\n@[<v 1>@,%a@];;\n\n" name print_proof_rec pi let print_parameter name ty out = Format.fprintf out "new_constant(\"%s\",%a);;\n\n" name print_type ty end module HolSTT = struct include PrintHol (** Keeping tracks of previous definitions/theorems/etc *) let defined_csts = Hashtbl.create 100 let declared_axioms = Hashtbl.create 100 let defined_thms = Hashtbl.create 300 let declared_types = Hashtbl.create 100 let reset () = Hashtbl.reset defined_thms; Hashtbl.reset defined_csts; Hashtbl.reset declared_axioms (** Find type variables in a type*) module VarsT = Set.Make(String) let rec free_vartypes vars = function | Tyvar(v) -> VarsT.add v vars | Tyapp(_,l) -> List.fold_left (fun setvars -> fun ty -> VarsT.union setvars (free_vartypes vars ty)) vars l (* Handle hypotheses as implications, notably for axioms which accept none *) let mk_hyp ts : hyp = mk_list ts let mk_imps (hyps:hyp) (t:term) = List.fold_right (fun x -> fun y -> mk_app_term (mk_app_term (term_of_const (impl_name ()) (mk_impl_type ())) x) y) hyps t (** Printing axioms *) let mk_axiom name hyps term = let imp_term = mk_imps hyps term in Hashtbl.add declared_axioms name (List.length hyps); Sequent(name,[],imp_term,Axiom_proof(imp_term)) (** Printing a comment, useful for debugging *) let mk_comment comment = Format.fprintf !oc "------> comment : %s\n" comment (** Printing types *) let mk_type name arity = Format.fprintf !oc "new_type(\"%s\",%i);;\n\n" name arity; Hashtbl.add declared_types name arity (** Printing deifnitions *) let mk_def thm_name name eqt (ty:hol_type) = let thm_def = Sequent(name,[],eqt,New_basic_definition_proof(thm_name,name,eqt)) in Hashtbl.add defined_csts name (thm_def,ty); thm_def (** Finding the definition theorem associated with a constant *) let thm_of_const_name name = if Hashtbl.mem defined_csts name then (fst @@ Hashtbl.find defined_csts name) else failwith (Format.sprintf "Const %s not found" name) (** Printing theorems *) let mk_thm name term hyp pi = let thm = Sequent(name,hyp,term,pi) in Hashtbl.add defined_thms name thm; print_thm_debug !oc thm; print_thm !oc thm (** Printing parameters *) let mk_parameter name ty = print_parameter name ty !oc (** Finding theorem using its name *) let thm_of_lemma name = if Hashtbl.mem defined_thms name then Hashtbl.find defined_thms name else failwith (Format.sprintf "Theorem %s not found" name) end
null
https://raw.githubusercontent.com/Deducteam/Logipedia/09797a35ae36ab671e40e615fcdc09a7bba69134/src/sttfa/holstt.ml
ocaml
Inspired from HOL Light fusion files Handling names, namespaces, and basic names coming from sttfa Sequent("TRUTH",[],mk_true_term (), Define conjunction Apply a beta-conversion to the right-hand side/left-hand side of a binary op Beta-reduce right-hand side of the definition of and Same for implication Same for forall Natural deduction rules Prove beta-delta-conversion between terms Print HOL types Print HOL terms Basic definitions must stand by themselves Print statement of theorems (not useful to build them, but useful to visualize them) Define whole theorem * Keeping tracks of previous definitions/theorems/etc * Find type variables in a type Handle hypotheses as implications, notably for axioms which accept none * Printing axioms * Printing a comment, useful for debugging * Printing types * Printing deifnitions * Finding the definition theorem associated with a constant * Printing theorems * Printing parameters * Finding theorem using its name
module BasicHol = struct Defining basic hol structures : terms , types , proofs type tyOp = string type const = string type hol_type = Tyvar of string | Tyapp of tyOp * hol_type list let dummy_type = Tyvar("dummy") type term = Var of string * hol_type | Const of const * hol_type | Comb of term * term | Abs of term * term let dummy_term = Var("dummy",dummy_type) type hyp = term list type proof = Axiom_proof of term | Thm of string | Rule of string * term list * proof list | Refl_proof of term | Sym_proof of proof | Trans_proof of proof * proof | Mk_comb_proof of proof * proof | Abs_proof of term * proof | Beta_conv_proof of term | Assume_proof of term | Eq_mp_proof of proof * proof | Deduct_antisym_rule_proof of proof * proof | Prove_hyp_proof of proof * proof | Subst_proof of ((hol_type * hol_type) list * (term * term) list) * proof | New_basic_definition_proof of string * string * term | New_basic_type_definition_proof_left of string * (string * string) * proof | New_basic_type_definition_proof_right of string * (string * string) * proof let dummy_proof = Axiom_proof(dummy_term) type thm = Sequent of (string * hyp * term * proof) let mk_name namespace name = let mk_namespace md = List.fold_left (fun s x -> s^x^".") "" md in (mk_namespace namespace)^name let arrow_name () = mk_name [] "->" let bool_name () = mk_name [] "bool" let equal_name () = mk_name [] "=" let impl_name () = mk_name [] "==>" let forall_name () = mk_name [] "!" Building hol types let mk_tyOp name = name let arrow_tyOp () = mk_tyOp (arrow_name ()) let bool_tyOp () = mk_tyOp (bool_name ()) let mk_varType name = Tyvar(name) let mk_list l = l let ty_of_tyOp (tyop: tyOp) (tys:hol_type list) : hol_type = Tyapp (tyop,tys) let mk_arrow_type tyl tyr : hol_type = ty_of_tyOp (arrow_tyOp ()) [tyl;tyr] let mk_bool_type () : hol_type = ty_of_tyOp (bool_tyOp ()) [] let mk_equal_type ty : hol_type = mk_arrow_type ty (mk_arrow_type ty (mk_bool_type ())) let mk_impl_type () = mk_arrow_type (mk_bool_type ()) (mk_arrow_type (mk_bool_type ()) (mk_bool_type())) let mk_forall_type ty = mk_arrow_type (mk_arrow_type ty (mk_bool_type ())) (mk_bool_type ()) Building hol terms let mk_var name ty : term = Var (name,ty) let mk_var_term v = v let mk_app_term f t : term = Comb (f,t) let mk_abs_term v t : term = Abs (v,t) let term_of_const cst ty : term = Const (cst,ty) let const_of_name name = name let mk_equal_term left right ty = let ty = mk_equal_type ty in let cst = term_of_const (const_of_name (equal_name ())) ty in mk_app_term (mk_app_term cst left) right Building hol proofs let mk_refl term = Refl_proof(term) let mk_appThm pil pir = Mk_comb_proof(pil,pir) let mk_absThm var pi = Abs_proof(var,pi) let mk_sym pi = Sym_proof(pi) let mk_betaConv term = Beta_conv_proof(term) let mk_trans pil pir = Trans_proof(pil,pir) let mk_subst tylist tlist pi = Subst_proof((tylist,tlist),pi) let mk_eqMp pil pir = Eq_mp_proof(pir,pil) let mk_proveHyp pil pir = Prove_hyp_proof(pil,pir) let mk_assume term = Assume_proof(term) let mk_deductAntiSym pil pir = Deduct_antisym_rule_proof(pil,pir) let true_name () = mk_name [] "T" let and_name () = mk_name [] "/\\\\" let mk_true_type () = mk_bool_type () let mk_and_type () = mk_arrow_type (mk_bool_type ()) (mk_arrow_type (mk_bool_type ()) (mk_bool_type())) let mk_true_term () = term_of_const (const_of_name (true_name ())) (mk_true_type ()) let mk_and () = term_of_const (const_of_name (and_name ())) (mk_and_type ()) let mk_and_term left right = mk_app_term (mk_app_term (mk_and ()) left) right let mk_impl () = term_of_const (const_of_name (impl_name ())) (mk_impl_type ()) let mk_impl_term left right = mk_app_term (mk_app_term (mk_impl ()) left) right let mk_forall ty = term_of_const (const_of_name (forall_name ())) (mk_forall_type ty) let mk_forall_term f ty = mk_app_term (mk_forall ty) f let mk_axiom_and_ () = Thm("AND_DEF") proof of tl'=tr ' with et tr ->B tr ' and thm a proof of tl = tr let beta_equal thm tl tr = let left = mk_sym (mk_betaConv tl) in let right = mk_betaConv tr in let trans = mk_trans left thm in mk_trans trans right let beta_right pi = Rule("CONV_RULE (RAND_CONV BETA_CONV)",[],[pi]) let beta_left pi = Rule("CONV_RULE (LAND_CONV BETA_CONV)",[],[pi]) let mk_axiom_and () = beta_right (beta_right (mk_axiom_and_ ())) let mk_axiom_impl_ () = Thm("IMP_DEF") let mk_axiom_impl () = beta_right (beta_right (mk_axiom_impl_ ())) let mk_axiom_forall_ () = Thm("FORALL_DEF") let mk_axiom_forall () = beta_right (beta_right (mk_axiom_forall_ ())) let mk_rule_intro_forall name ty pi = Rule("GEN",[mk_var name ty],[pi]) let mk_rule_elim_forall comment t pi = Rule(comment^"SPEC",[t],[pi]) let proj_left pi = Rule("CONJUNCT1",[],[pi]) let proj_right pi = Rule("CONJUNCT2",[],[pi]) let mk_rule_intro_impl t pi = Rule("DISCH",[t],[pi]) let mk_rule_elim_impl piimp pi = Rule("MP",[],[piimp;pi]) let mk_impl_equal eqp eqq = Mk_comb_proof(Mk_comb_proof(Refl_proof(mk_impl ()),eqp),eqq) let mk_forall_equal eq ty = Mk_comb_proof(Refl_proof(mk_forall ty),eq) let conv_proof comment t pi = Rule(comment^"CONV_CONV_rule",[t],[pi]) end module PrintHol = struct include BasicHol Print HOL objects , recognizable by HOL Light parser let oc = ref Format.std_formatter let set_oc f = oc := f let rec print_list s d1 d2 print_object out = function [] -> () | [obj] -> Format.fprintf out "%s%a%s" d1 print_object obj d2 | hd::q -> Format.fprintf out "%s%a%s%s%a" d1 print_object hd d2 s (print_list s d1 d2 print_object) q let rec print_type_rec out = function Tyvar name -> Format.fprintf out "%s" name | Tyapp (tyop,[]) -> Format.fprintf out "%s" tyop | Tyapp (tyop,tylist) when tyop = "->" -> Format.fprintf out "%a -> %a" print_type_atomic (List.hd tylist) print_type_atomic (List.hd (List.tl tylist)) | Tyapp (tyop,tylist) -> Format.fprintf out "%s %a" tyop (print_list " " "" "" print_type_atomic) tylist and print_type_atomic out t = match t with Tyapp(tyop,_) when tyop = "->" -> Format.fprintf out "(%a)" print_type_rec t | _ -> print_type_rec out t let print_type out t = Format.fprintf out "`:%a`" print_type_rec t let print_var out = function | Var(name,ty) -> Format.fprintf out "%s : %a" name print_type_rec ty | _ -> failwith "Not a variable\n" let rec print_term_rec b out = function Var(name,ty) when b -> Format.fprintf out "%a" (print_term_atomic b) (Var(name,ty)) | Var(name,_) -> Format.fprintf out "%s" name | Const(cst,_) -> Format.fprintf out "%s" cst | Comb(f,t) -> begin match f,t with Const("!",_),Abs(v,t) -> Format.fprintf out "! %a. %a" print_var v (print_term_atomic b) t | Comb(Const(s,_),t1),_ when (s = "==>" || s = "/\\" || s = "=") -> Format.fprintf out "%a %s %a" (print_term_atomic b) t1 s (print_term_atomic b) t | _ -> Format.fprintf out "%a %a" (print_term_atomic b) f (print_term_atomic b) t end | Abs(v,t) -> Format.fprintf out "\\ %a. %a" print_var v (print_term_atomic b) t and print_term_atomic b out t = match t with Comb _ | Abs _ -> Format.fprintf out "(%a)" (print_term_rec b) t | Var _ when b -> Format.fprintf out "(%a)" print_var t | _ -> print_term_rec b out t let print_term b out t = Format.fprintf out "`%a`" (print_term_rec b) t Print HOL proofs Observation : no " proof " object in HOL Light ! Here : using proof squeleton to build HOL Light theorems let rec print_proof_rec out = let print_term_proof = print_term true in function Axiom_proof(t) -> Format.fprintf out "@[new_axiom %a@]@," print_term_proof t | Thm(th) -> Format.fprintf out "@[%s@]@," th | Rule (rule,tlist,pilist) -> Format.fprintf out "@[<hov>%s %a @,@[<hov>%a@]@,@]@," rule (print_list " " "" "" print_term_proof) tlist (print_list " " "(" ")" print_proof_rec) pilist | Refl_proof(t) -> Format.fprintf out "@[<hov>REFL %a@]@," print_term_proof t | Sym_proof(pi) -> Format.fprintf out "@[<hov>SYM (%a)@]@," print_proof_rec pi | Trans_proof(pi1,pi2) -> Format.fprintf out "@;@[<hov>TRANS @[<hov>(%a)@]@, @[<hov>(%a)@]@,@]@," print_proof_rec pi1 print_proof_rec pi2 | Mk_comb_proof(pi1,pi2) -> Format.fprintf out "@\n@[<hov>MK_COMB (@[%a@]@,,@[%a@]@,)@]@," print_proof_rec pi1 print_proof_rec pi2 | Abs_proof(t,pi) -> Format.fprintf out "@[<hov>ABS %a @[(%a)@]@,@]@," print_term_proof t print_proof_rec pi | Beta_conv_proof(t) -> Format.fprintf out "@[<hov>BETA_CONV %a@]@," print_term_proof t | Assume_proof(t) -> Format.fprintf out "@[<hov>ASSUME %a@]@," print_term_proof t | Eq_mp_proof(pi1,pi2) -> Format.fprintf out "@[<hov>EQ_MP @[<hov>(%a)@]@, @[<hov>(%a)@]@,@]@," print_proof_rec pi1 print_proof_rec pi2 | Deduct_antisym_rule_proof(pi1,pi2) -> Format.fprintf out "@[<hov>DEDUCT_ANTISYM_RULE @[<hov>(%a)@]@, @[<hov>(%a)@]@,@]@," print_proof_rec pi1 print_proof_rec pi2 | Prove_hyp_proof(pi1,pi2) -> Format.fprintf out "@[<hov>PROVE_HYP @[<hov>(%a)@]@, @[<hov>(%a)@]@,@]@," print_proof_rec pi1 print_proof_rec pi2 | Subst_proof(lists,pi) -> let tylist,tlist = lists in let print_couple_rev print_object out pair = let (x,y)=pair in Format.fprintf out "(%a,%a)" print_object y print_object x in Format.fprintf out "@[<hov>PINST [%a] [%a] @[<hov>(%a)@]@,@]@," (print_list ";" "" "" (print_couple_rev print_type)) tylist (print_list ";" "" "" (print_couple_rev print_term_proof)) tlist print_proof_rec pi | New_basic_definition_proof(thm_name,name,t) -> Format.fprintf out "@[<hov>new_basic_definition %a@]@,;;\n\n" print_term_proof t; Format.fprintf out "let _ = (new_defs := (\"%s\",%s)::!new_defs)" name thm_name | New_basic_type_definition_proof_left(s,(s1,s2),pi) -> Format.fprintf out "@[<hov>fst (new_basic_type_definition (%s) (%s,%s) (%a))@]@," s s1 s2 print_proof_rec pi | New_basic_type_definition_proof_right(s,(s1,s2),pi) -> Format.fprintf out "@[<hov>snd (new_basic_type_definition (%s) (%s,%s) (%a))@]@," s s1 s2 print_proof_rec pi let print_thm_debug out = function Sequent(name,hyps,t,_) -> Format.fprintf out "(*%s : %a |- %a*)\n" name (print_list ";" "" "" (print_term false)) hyps (print_term false) t let print_thm out = function Sequent(name,_,_,pi) -> Format.fprintf out "let %s =@\n@[<v 1>@,%a@];;\n\n" name print_proof_rec pi let print_parameter name ty out = Format.fprintf out "new_constant(\"%s\",%a);;\n\n" name print_type ty end module HolSTT = struct include PrintHol let defined_csts = Hashtbl.create 100 let declared_axioms = Hashtbl.create 100 let defined_thms = Hashtbl.create 300 let declared_types = Hashtbl.create 100 let reset () = Hashtbl.reset defined_thms; Hashtbl.reset defined_csts; Hashtbl.reset declared_axioms module VarsT = Set.Make(String) let rec free_vartypes vars = function | Tyvar(v) -> VarsT.add v vars | Tyapp(_,l) -> List.fold_left (fun setvars -> fun ty -> VarsT.union setvars (free_vartypes vars ty)) vars l let mk_hyp ts : hyp = mk_list ts let mk_imps (hyps:hyp) (t:term) = List.fold_right (fun x -> fun y -> mk_app_term (mk_app_term (term_of_const (impl_name ()) (mk_impl_type ())) x) y) hyps t let mk_axiom name hyps term = let imp_term = mk_imps hyps term in Hashtbl.add declared_axioms name (List.length hyps); Sequent(name,[],imp_term,Axiom_proof(imp_term)) let mk_comment comment = Format.fprintf !oc "------> comment : %s\n" comment let mk_type name arity = Format.fprintf !oc "new_type(\"%s\",%i);;\n\n" name arity; Hashtbl.add declared_types name arity let mk_def thm_name name eqt (ty:hol_type) = let thm_def = Sequent(name,[],eqt,New_basic_definition_proof(thm_name,name,eqt)) in Hashtbl.add defined_csts name (thm_def,ty); thm_def let thm_of_const_name name = if Hashtbl.mem defined_csts name then (fst @@ Hashtbl.find defined_csts name) else failwith (Format.sprintf "Const %s not found" name) let mk_thm name term hyp pi = let thm = Sequent(name,hyp,term,pi) in Hashtbl.add defined_thms name thm; print_thm_debug !oc thm; print_thm !oc thm let mk_parameter name ty = print_parameter name ty !oc let thm_of_lemma name = if Hashtbl.mem defined_thms name then Hashtbl.find defined_thms name else failwith (Format.sprintf "Theorem %s not found" name) end
d6a651e1d0e882237aca29ef8cfcad10215003e01dcc8242e8393a5e89c442aa
ashinn/alschemist
base.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Images - 3D arrays of width*height*color-channel (define-record-type Image (%make-image array color-space) image? (array image-array) (color-space image-color-space)) (define (image-width image) (let ((domain (array-domain (image-array image)))) (- (interval-upper-bound domain 1) (interval-lower-bound domain 1)))) (define (image-height image) (let ((domain (array-domain (image-array image)))) (- (interval-upper-bound domain 0) (interval-lower-bound domain 0)))) (define (make-image width height . o) (let* ((storage-class (if (pair? o) (car o) u8-storage-class)) (array (make-specialized-array (make-interval (vector width height 3)) storage-class))) ;; (%make-image array 'sRGB))) (define (array->image array . o) (assert (and (specialized-array? array) (= 3 (array-dimension array)) (zero? (interval-lower-bound (array-domain array) 2)) (<= 3 (interval-upper-bound (array-domain array) 2) 4))) (%make-image array 'sRGB)) (define (image-channels image) (let ((channels (array-tile (image-array image) (vector (image-width image) (image-height image) 1))) (domain (make-interval (vector (image-width image) (image-height image))))) (values (specialized-array-reshape (array-ref channels 0 0 0) domain) (specialized-array-reshape (array-ref channels 0 0 1) domain) (specialized-array-reshape (array-ref channels 0 0 2) domain)))) (define (image-alpha image) (let ((array (image-array image)) (width (image-width image)) (height (image-height image))) (and (= 4 (interval-upper-bound (array-domain array) 2)) (let ((channels (array-tile array (vector width height 1)))) (specialized-array-reshape (array-ref channels 0 0 3) (make-interval (vector width height))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Pixmaps - 2D arrays of single-value pixels (define-record-type Pixel-Format (%make-pixel-format storage-class bits masks shifts palette rgb-encoder rgba-encoder rgb-decoder rgba-decoder) pixel-format? (storage-class pixel-format-storage-class) (bits pixel-format-bits) (masks pixel-format-masks) (shifts pixel-format-shifts) (palette pixel-format-palette) (rgb-encoder pixel-format-rgb-encoder) (rgba-encoder pixel-format-rgba-encoder) (rgb-decoder pixel-format-rgb-decoder) (rgba-decoder pixel-format-rgba-decoder)) (define (make-rgb-decoder masks shifts) (let ((mask0 (vector-ref masks 0)) (shift0 (- (vector-ref shifts 0))) (mask1 (vector-ref masks 1)) (shift1 (- (vector-ref shifts 1))) (mask2 (vector-ref masks 2)) (shift2 (- (vector-ref shifts 2)))) (lambda (pixel) (values (bitwise-and mask0 (arithmetic-shift pixel shift0)) (bitwise-and mask1 (arithmetic-shift pixel shift1)) (bitwise-and mask2 (arithmetic-shift pixel shift2)))))) (define (make-rgba-decoder masks shifts) (let ((mask0 (vector-ref masks 0)) (shift0 (- (vector-ref shifts 0))) (mask1 (vector-ref masks 1)) (shift1 (- (vector-ref shifts 1))) (mask2 (vector-ref masks 2)) (shift2 (- (vector-ref shifts 2))) (mask3 (vector-ref masks 3)) (shift3 (- (vector-ref shifts 3)))) (lambda (pixel) (values (bitwise-and mask0 (arithmetic-shift pixel shift0)) (bitwise-and mask1 (arithmetic-shift pixel shift1)) (bitwise-and mask2 (arithmetic-shift pixel shift2)) (bitwise-and mask3 (arithmetic-shift pixel shift3)))))) (define (make-rgb-encoder masks shifts) (let ((shift0 (vector-ref shifts 0)) (shift1 (vector-ref shifts 1)) (shift2 (vector-ref shifts 2))) (lambda (red green blue) (bitwise-ior (arithmetic-shift red shift0) (arithmetic-shift green shift1) (arithmetic-shift blue shift2))))) (define (make-rgba-encoder masks shifts) (let ((shift0 (vector-ref shifts 0)) (shift1 (vector-ref shifts 1)) (shift2 (vector-ref shifts 2)) (shift3 (vector-ref shifts 3))) (lambda (red green blue alpha) (bitwise-ior (arithmetic-shift red shift0) (arithmetic-shift green shift1) (arithmetic-shift blue shift2) (arithmetic-shift alpha shift3))))) (define (make-rgba-pixel-format storage-class bits . o) (let ((masks (if (pair? o) (car o) (vector-map (lambda (x) (- (expt 2 x) 1)) (make-vector 4 (quotient bits 4))))) (shifts (if (and (pair? o) (pair? (cdr o))) (cadr o) (list->vector (fold (lambda (i acc) (cons (- bits (* i (quotient bits 4))) acc)) '() (iota 4 1)))))) (%make-pixel-format storage-class bits masks shifts #f (make-rgb-encoder masks shifts) (make-rgba-encoder masks shifts) (make-rgb-decoder masks shifts) (make-rgba-decoder masks shifts)))) (define rgba8888-format (make-rgba-pixel-format u32-storage-class 32)) (define (make-rgb-decoder/palette palette) (lambda (pixel) ((pixel-format-rgb-decoder rgba8888-format) (u32vector-ref palette pixel)))) (define (make-rgba-decoder/palette palette) (lambda (pixel) ((pixel-format-rgba-decoder rgba8888-format) (u32vector-ref palette pixel)))) (define (make-rgb-encoder/palette palette decoder) ;; TODO: ultra-slow - implement a nearest neighbor lookup in a color cube (lambda (r g b) (let lp ((i (- (u32vector-length palette) 1)) (nearest #f) (nearest-distance 1e100)) (if (negative? i) nearest (let-values (((r2 g2 b2) (decoder (u32vector-ref palette i)))) (let ((dist (+ (square (- r r2)) (square (- g g2)) (square (- b b2))))) (if (< dist nearest-distance) (lp (- i 1) i dist) (lp (- i 1) nearest nearest-distance)))))))) (define (make-rgba-encoder/palette palette decoder) (let ((encode (make-rgb-encoder/palette palette decoder))) (lambda (r g b a) (encode r g b)))) (define (make-palette-pixel-format storage-class bits palette) (let ((decoder (make-rgb-decoder/palette palette))) (%make-pixel-format storage-class bits #f #f palette (make-rgb-encoder/palette palette decoder) (make-rgba-encoder/palette palette decoder) decoder (make-rgba-decoder/palette palette)))) (define-record-type Pixmap (%make-pixmap array pixel-format) pixmap? (array pixmap-array) (pixel-format pixmap-pixel-format)) (define (make-pixmap width height . o) (let* ((pixel-format (if (pair? o) (car o) rgba8888-format)) (array (make-specialized-array (make-interval (vector width height)) (pixel-format-storage-class pixel-format)))) (%make-pixmap array pixel-format))) (define (pixmap-width pixmap) (let ((domain (array-domain (pixmap-array pixmap)))) (- (interval-upper-bound domain 1) (interval-lower-bound domain 1)))) (define (pixmap-height pixmap) (let ((domain (array-domain (pixmap-array pixmap)))) (- (interval-upper-bound domain 0) (interval-lower-bound domain 0)))) (define (array->pixmap array . o) (assert (and (specialized-array? array) (= 2 (array-dimension array)))) (let ((pixel-format (if (pair? o) (car o) rgba8888-format))) (%make-pixmap array pixel-format))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Conversions ;; Reshaping allows us to flatten the R, G, B components as adjacent ;; values in the same dimension, but for a pixmap we want to join them ;; into a single value. (define (image->pixmap image . o) (let* ((pixel-format (if (pair? o) (car o) rgba8888-format)) (src (image-array image)) (width (image-width image)) (height (image-height image)) (w0 (interval-lower-bound (array-domain src) 1)) (h0 (interval-lower-bound (array-domain src) 0)) (dst (make-specialized-array (make-interval (vector height width)) (pixel-format-storage-class pixel-format))) (getter (array-getter src)) (rgb->pixel (pixel-format-rgb-encoder pixel-format)) (setter (array-setter dst))) (do ((i 0 (+ i 1))) ((= i height) (%make-pixmap dst pixel-format)) (do ((j 0 (+ j 1))) ((= j width)) (let ((r (getter (- i h0) (- j w0) 0)) (g (getter (- i h0) (- j w0) 1)) (b (getter (- i h0) (- j w0) 2))) (setter (rgb->pixel r g b) i j)))))) (define (pixmap->image pixmap . o) (let* ((storage-class (if (pair? o) (car o) u32-storage-class)) (src (pixmap-array pixmap)) (w0 (interval-lower-bound (array-domain src) 1)) (h0 (interval-lower-bound (array-domain src) 0)) (width (pixmap-width pixmap)) (height (pixmap-height pixmap)) (dst (make-specialized-array (make-interval (vector height width 3)) storage-class)) (getter (array-getter src)) (pixel->rgb (pixel-format-rgb-decoder (pixmap-pixel-format pixmap))) (setter (array-setter dst))) (do ((i 0 (+ i 1))) ((= i height) (%make-image dst 'sRGB)) (do ((j 0 (+ j 1))) ((= j width)) (let-values (((r g b) (pixel->rgb (getter (- i h0) (- j w0))))) (setter r i j 0) (setter g i j 1) (setter b i j 2))))))
null
https://raw.githubusercontent.com/ashinn/alschemist/cffef6903ae5885493088b76b057225ae69e257f/chibi/image/base.scm
scheme
Images - 3D arrays of width*height*color-channel Pixmaps - 2D arrays of single-value pixels TODO: ultra-slow - implement a nearest neighbor lookup in a color cube Conversions Reshaping allows us to flatten the R, G, B components as adjacent values in the same dimension, but for a pixmap we want to join them into a single value.
(define-record-type Image (%make-image array color-space) image? (array image-array) (color-space image-color-space)) (define (image-width image) (let ((domain (array-domain (image-array image)))) (- (interval-upper-bound domain 1) (interval-lower-bound domain 1)))) (define (image-height image) (let ((domain (array-domain (image-array image)))) (- (interval-upper-bound domain 0) (interval-lower-bound domain 0)))) (define (make-image width height . o) (let* ((storage-class (if (pair? o) (car o) u8-storage-class)) (array (make-specialized-array (make-interval (vector width height 3)) storage-class))) (%make-image array 'sRGB))) (define (array->image array . o) (assert (and (specialized-array? array) (= 3 (array-dimension array)) (zero? (interval-lower-bound (array-domain array) 2)) (<= 3 (interval-upper-bound (array-domain array) 2) 4))) (%make-image array 'sRGB)) (define (image-channels image) (let ((channels (array-tile (image-array image) (vector (image-width image) (image-height image) 1))) (domain (make-interval (vector (image-width image) (image-height image))))) (values (specialized-array-reshape (array-ref channels 0 0 0) domain) (specialized-array-reshape (array-ref channels 0 0 1) domain) (specialized-array-reshape (array-ref channels 0 0 2) domain)))) (define (image-alpha image) (let ((array (image-array image)) (width (image-width image)) (height (image-height image))) (and (= 4 (interval-upper-bound (array-domain array) 2)) (let ((channels (array-tile array (vector width height 1)))) (specialized-array-reshape (array-ref channels 0 0 3) (make-interval (vector width height))))))) (define-record-type Pixel-Format (%make-pixel-format storage-class bits masks shifts palette rgb-encoder rgba-encoder rgb-decoder rgba-decoder) pixel-format? (storage-class pixel-format-storage-class) (bits pixel-format-bits) (masks pixel-format-masks) (shifts pixel-format-shifts) (palette pixel-format-palette) (rgb-encoder pixel-format-rgb-encoder) (rgba-encoder pixel-format-rgba-encoder) (rgb-decoder pixel-format-rgb-decoder) (rgba-decoder pixel-format-rgba-decoder)) (define (make-rgb-decoder masks shifts) (let ((mask0 (vector-ref masks 0)) (shift0 (- (vector-ref shifts 0))) (mask1 (vector-ref masks 1)) (shift1 (- (vector-ref shifts 1))) (mask2 (vector-ref masks 2)) (shift2 (- (vector-ref shifts 2)))) (lambda (pixel) (values (bitwise-and mask0 (arithmetic-shift pixel shift0)) (bitwise-and mask1 (arithmetic-shift pixel shift1)) (bitwise-and mask2 (arithmetic-shift pixel shift2)))))) (define (make-rgba-decoder masks shifts) (let ((mask0 (vector-ref masks 0)) (shift0 (- (vector-ref shifts 0))) (mask1 (vector-ref masks 1)) (shift1 (- (vector-ref shifts 1))) (mask2 (vector-ref masks 2)) (shift2 (- (vector-ref shifts 2))) (mask3 (vector-ref masks 3)) (shift3 (- (vector-ref shifts 3)))) (lambda (pixel) (values (bitwise-and mask0 (arithmetic-shift pixel shift0)) (bitwise-and mask1 (arithmetic-shift pixel shift1)) (bitwise-and mask2 (arithmetic-shift pixel shift2)) (bitwise-and mask3 (arithmetic-shift pixel shift3)))))) (define (make-rgb-encoder masks shifts) (let ((shift0 (vector-ref shifts 0)) (shift1 (vector-ref shifts 1)) (shift2 (vector-ref shifts 2))) (lambda (red green blue) (bitwise-ior (arithmetic-shift red shift0) (arithmetic-shift green shift1) (arithmetic-shift blue shift2))))) (define (make-rgba-encoder masks shifts) (let ((shift0 (vector-ref shifts 0)) (shift1 (vector-ref shifts 1)) (shift2 (vector-ref shifts 2)) (shift3 (vector-ref shifts 3))) (lambda (red green blue alpha) (bitwise-ior (arithmetic-shift red shift0) (arithmetic-shift green shift1) (arithmetic-shift blue shift2) (arithmetic-shift alpha shift3))))) (define (make-rgba-pixel-format storage-class bits . o) (let ((masks (if (pair? o) (car o) (vector-map (lambda (x) (- (expt 2 x) 1)) (make-vector 4 (quotient bits 4))))) (shifts (if (and (pair? o) (pair? (cdr o))) (cadr o) (list->vector (fold (lambda (i acc) (cons (- bits (* i (quotient bits 4))) acc)) '() (iota 4 1)))))) (%make-pixel-format storage-class bits masks shifts #f (make-rgb-encoder masks shifts) (make-rgba-encoder masks shifts) (make-rgb-decoder masks shifts) (make-rgba-decoder masks shifts)))) (define rgba8888-format (make-rgba-pixel-format u32-storage-class 32)) (define (make-rgb-decoder/palette palette) (lambda (pixel) ((pixel-format-rgb-decoder rgba8888-format) (u32vector-ref palette pixel)))) (define (make-rgba-decoder/palette palette) (lambda (pixel) ((pixel-format-rgba-decoder rgba8888-format) (u32vector-ref palette pixel)))) (define (make-rgb-encoder/palette palette decoder) (lambda (r g b) (let lp ((i (- (u32vector-length palette) 1)) (nearest #f) (nearest-distance 1e100)) (if (negative? i) nearest (let-values (((r2 g2 b2) (decoder (u32vector-ref palette i)))) (let ((dist (+ (square (- r r2)) (square (- g g2)) (square (- b b2))))) (if (< dist nearest-distance) (lp (- i 1) i dist) (lp (- i 1) nearest nearest-distance)))))))) (define (make-rgba-encoder/palette palette decoder) (let ((encode (make-rgb-encoder/palette palette decoder))) (lambda (r g b a) (encode r g b)))) (define (make-palette-pixel-format storage-class bits palette) (let ((decoder (make-rgb-decoder/palette palette))) (%make-pixel-format storage-class bits #f #f palette (make-rgb-encoder/palette palette decoder) (make-rgba-encoder/palette palette decoder) decoder (make-rgba-decoder/palette palette)))) (define-record-type Pixmap (%make-pixmap array pixel-format) pixmap? (array pixmap-array) (pixel-format pixmap-pixel-format)) (define (make-pixmap width height . o) (let* ((pixel-format (if (pair? o) (car o) rgba8888-format)) (array (make-specialized-array (make-interval (vector width height)) (pixel-format-storage-class pixel-format)))) (%make-pixmap array pixel-format))) (define (pixmap-width pixmap) (let ((domain (array-domain (pixmap-array pixmap)))) (- (interval-upper-bound domain 1) (interval-lower-bound domain 1)))) (define (pixmap-height pixmap) (let ((domain (array-domain (pixmap-array pixmap)))) (- (interval-upper-bound domain 0) (interval-lower-bound domain 0)))) (define (array->pixmap array . o) (assert (and (specialized-array? array) (= 2 (array-dimension array)))) (let ((pixel-format (if (pair? o) (car o) rgba8888-format))) (%make-pixmap array pixel-format))) (define (image->pixmap image . o) (let* ((pixel-format (if (pair? o) (car o) rgba8888-format)) (src (image-array image)) (width (image-width image)) (height (image-height image)) (w0 (interval-lower-bound (array-domain src) 1)) (h0 (interval-lower-bound (array-domain src) 0)) (dst (make-specialized-array (make-interval (vector height width)) (pixel-format-storage-class pixel-format))) (getter (array-getter src)) (rgb->pixel (pixel-format-rgb-encoder pixel-format)) (setter (array-setter dst))) (do ((i 0 (+ i 1))) ((= i height) (%make-pixmap dst pixel-format)) (do ((j 0 (+ j 1))) ((= j width)) (let ((r (getter (- i h0) (- j w0) 0)) (g (getter (- i h0) (- j w0) 1)) (b (getter (- i h0) (- j w0) 2))) (setter (rgb->pixel r g b) i j)))))) (define (pixmap->image pixmap . o) (let* ((storage-class (if (pair? o) (car o) u32-storage-class)) (src (pixmap-array pixmap)) (w0 (interval-lower-bound (array-domain src) 1)) (h0 (interval-lower-bound (array-domain src) 0)) (width (pixmap-width pixmap)) (height (pixmap-height pixmap)) (dst (make-specialized-array (make-interval (vector height width 3)) storage-class)) (getter (array-getter src)) (pixel->rgb (pixel-format-rgb-decoder (pixmap-pixel-format pixmap))) (setter (array-setter dst))) (do ((i 0 (+ i 1))) ((= i height) (%make-image dst 'sRGB)) (do ((j 0 (+ j 1))) ((= j width)) (let-values (((r g b) (pixel->rgb (getter (- i h0) (- j w0))))) (setter r i j 0) (setter g i j 1) (setter b i j 2))))))