_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
2f71fcafbfd607b967b8fca7fcd24a3671e887bffe7792b7bfc562ffd3de3f8e
janestreet/universe
sexp_conv.mli
(** Utility Module for S-expression Conversions *) (** Dummy definitions for "optional" options, lists, and for opaque types *) type sexp_bool = bool [@@deprecated "[since 2019-03] use [@sexp.bool] instead"] type 'a sexp_option = 'a option [@@deprecated "[since 2019-03] use [@sexp.option] instead"] type 'a sexp_list = 'a list [@@deprecated "[since 2019-03] use [@sexp.list] instead"] type 'a sexp_array = 'a array [@@deprecated "[since 2019-03] use [@sexp.array] instead"] type 'a sexp_opaque = 'a [@@deprecated "[since 2019-03] use [@sexp.opaque] instead"] * { 6 Conversion of OCaml - values to S - expressions } val default_string_of_float : (float -> string) ref (** [default_string_of_float] reference to the default function used to convert floats to strings. Initially set to [fun n -> sprintf "%.20G" n]. *) val write_old_option_format : bool ref * [ write_old_option_format ] reference for the default option format used to write option values . If set to [ true ] , the old - style option format will be used , the new - style one otherwise . Initially set to [ true ] . used to write option values. If set to [true], the old-style option format will be used, the new-style one otherwise. Initially set to [true]. *) val read_old_option_format : bool ref (** [read_old_option_format] reference for the default option format used to read option values. [Of_sexp_error] will be raised with old-style option values if this reference is set to [false]. Reading new-style option values is always supported. Using a global reference instead of changing the converter calling conventions is the only way to avoid breaking old code with the standard macros. Initially set to [true]. *) * We re - export a tail recursive map function , because some modules override the standard library functions ( e.g. [ StdLabels ] ) which wrecks havoc with the extension . override the standard library functions (e.g. [StdLabels]) which wrecks havoc with the camlp4 extension. *) val list_map : ('a -> 'b) -> 'a list -> 'b list val sexp_of_unit : unit -> Sexp.t (** [sexp_of_unit ()] converts a value of type [unit] to an S-expression. *) val sexp_of_bool : bool -> Sexp.t (** [sexp_of_bool b] converts the value [x] of type [bool] to an S-expression. *) val sexp_of_string : string -> Sexp.t (** [sexp_of_bool str] converts the value [str] of type [string] to an S-expression. *) val sexp_of_bytes : bytes -> Sexp.t (** [sexp_of_bool str] converts the value [str] of type [bytes] to an S-expression. *) val sexp_of_char : char -> Sexp.t (** [sexp_of_char c] converts the value [c] of type [char] to an S-expression. *) val sexp_of_int : int -> Sexp.t (** [sexp_of_int n] converts the value [n] of type [int] to an S-expression. *) val sexp_of_float : float -> Sexp.t (** [sexp_of_float n] converts the value [n] of type [float] to an S-expression. *) val sexp_of_int32 : int32 -> Sexp.t (** [sexp_of_int32 n] converts the value [n] of type [int32] to an S-expression. *) val sexp_of_int64 : int64 -> Sexp.t * [ sexp_of_int64 n ] converts the value [ n ] of type [ int64 ] to an S - expression . S-expression. *) val sexp_of_nativeint : nativeint -> Sexp.t (** [sexp_of_nativeint n] converts the value [n] of type [nativeint] to an S-expression. *) val sexp_of_ref : ('a -> Sexp.t) -> 'a ref -> Sexp.t * [ sexp_of_ref conv r ] converts the value [ r ] of type [ ' a ref ] to an S - expression . Uses [ conv ] to convert values of type [ ' a ] to an S - expression . an S-expression. Uses [conv] to convert values of type ['a] to an S-expression. *) val sexp_of_lazy_t : ('a -> Sexp.t) -> 'a lazy_t -> Sexp.t (** [sexp_of_lazy_t conv l] converts the value [l] of type ['a lazy_t] to an S-expression. Uses [conv] to convert values of type ['a] to an S-expression. *) val sexp_of_option : ('a -> Sexp.t) -> 'a option -> Sexp.t (** [sexp_of_option conv opt] converts the value [opt] of type ['a option] to an S-expression. Uses [conv] to convert values of type ['a] to an S-expression. *) val sexp_of_pair : ('a -> Sexp.t) -> ('b -> Sexp.t) -> 'a * 'b -> Sexp.t * [ sexp_of_pair conv1 conv2 pair ] converts a pair to an S - expression . It uses its first argument to convert the first element of the pair , and its second argument to convert the second element of the pair . It uses its first argument to convert the first element of the pair, and its second argument to convert the second element of the pair. *) val sexp_of_triple : ('a -> Sexp.t) -> ('b -> Sexp.t) -> ('c -> Sexp.t) -> 'a * 'b * 'c -> Sexp.t * [ sexp_of_triple conv1 conv2 conv3 triple ] converts a triple to an S - expression using [ conv1 ] , [ conv2 ] , and [ ] to convert its elements . an S-expression using [conv1], [conv2], and [conv3] to convert its elements. *) val sexp_of_list : ('a -> Sexp.t) -> 'a list -> Sexp.t * [ sexp_of_list conv lst ] converts the value [ lst ] of type [ ' a list ] to an S - expression . Uses [ conv ] to convert values of type [ ' a ] to an S - expression . list] to an S-expression. Uses [conv] to convert values of type ['a] to an S-expression. *) val sexp_of_array : ('a -> Sexp.t) -> 'a array -> Sexp.t (** [sexp_of_array conv ar] converts the value [ar] of type ['a array] to an S-expression. Uses [conv] to convert values of type ['a] to an S-expression. *) val sexp_of_hashtbl : ('a -> Sexp.t) -> ('b -> Sexp.t) -> ('a, 'b) Hashtbl.t -> Sexp.t * [ ] converts the value [ htbl ] of type [ ( ' a , ' b ) ] to an S - expression . Uses [ conv_key ] to convert the hashtable keys of type [ ' a ] , and [ conv_value ] to convert hashtable values of type [ ' b ] to S - expressions . of type [('a, 'b) Hashtbl.t] to an S-expression. Uses [conv_key] to convert the hashtable keys of type ['a], and [conv_value] to convert hashtable values of type ['b] to S-expressions. *) val sexp_of_opaque : 'a -> Sexp.t (** [sexp_of_opaque x] converts the value [x] of opaque type to an S-expression. This means the user need not provide converters, but the result cannot be interpreted. *) val sexp_of_fun : ('a -> 'b) -> Sexp.t (** [sexp_of_fun f] converts the value [f] of function type to a dummy S-expression. Functions cannot be serialized as S-expressions, but at least a placeholder can be generated for pretty-printing. *) * { 6 Conversion of S - expressions to OCaml - values } exception Of_sexp_error of exn * Sexp.t (** [Of_sexp_error (exn, sexp)] the exception raised when an S-expression could not be successfully converted to an OCaml-value. *) val record_check_extra_fields : bool ref (** [record_check_extra_fields] checks for extra (= unknown) fields in record S-expressions. *) val of_sexp_error : string -> Sexp.t -> 'a (** [of_sexp_error reason sexp] @raise Of_sexp_error (Failure reason, sexp). *) val of_sexp_error_exn : exn -> Sexp.t -> 'a * [ of_sexp_error exc sexp ] @raise Of_sexp_error ( exc , sexp ) . val unit_of_sexp : Sexp.t -> unit * [ unit_of_sexp sexp ] converts S - expression [ sexp ] to a value of type [ unit ] . [unit]. *) val bool_of_sexp : Sexp.t -> bool (** [bool_of_sexp sexp] converts S-expression [sexp] to a value of type [bool]. *) val string_of_sexp : Sexp.t -> string * [ sexp ] converts S - expression [ sexp ] to a value of type [ string ] . [string]. *) val bytes_of_sexp : Sexp.t -> bytes * [ sexp ] converts S - expression [ sexp ] to a value of type [ bytes ] . [bytes]. *) val char_of_sexp : Sexp.t -> char (** [char_of_sexp sexp] converts S-expression [sexp] to a value of type [char]. *) val int_of_sexp : Sexp.t -> int (** [int_of_sexp sexp] converts S-expression [sexp] to a value of type [int]. *) val float_of_sexp : Sexp.t -> float (** [float_of_sexp sexp] converts S-expression [sexp] to a value of type [float]. *) val int32_of_sexp : Sexp.t -> int32 (** [int32_of_sexp sexp] converts S-expression [sexp] to a value of type [int32]. *) val int64_of_sexp : Sexp.t -> int64 * [ int64_of_sexp sexp ] converts S - expression [ sexp ] to a value of type [ int64 ] . [int64]. *) val nativeint_of_sexp : Sexp.t -> nativeint (** [nativeint_of_sexp sexp] converts S-expression [sexp] to a value of type [nativeint]. *) val ref_of_sexp : (Sexp.t -> 'a) -> Sexp.t -> 'a ref (** [ref_of_sexp conv sexp] converts S-expression [sexp] to a value of type ['a ref] using conversion function [conv], which converts an S-expression to a value of type ['a]. *) val lazy_t_of_sexp : (Sexp.t -> 'a) -> Sexp.t -> 'a lazy_t (** [lazy_t_of_sexp conv sexp] converts S-expression [sexp] to a value of type ['a lazy_t] using conversion function [conv], which converts an S-expression to a value of type ['a]. *) val option_of_sexp : (Sexp.t -> 'a) -> Sexp.t -> 'a option (** [option_of_sexp conv sexp] converts S-expression [sexp] to a value of type ['a option] using conversion function [conv], which converts an S-expression to a value of type ['a]. *) val pair_of_sexp : (Sexp.t -> 'a) -> (Sexp.t -> 'b) -> Sexp.t -> 'a * 'b * [ pair_of_sexp conv1 conv2 sexp ] converts S - expression [ sexp ] to a pair of type [ ' a * ' b ] using conversion functions [ conv1 ] and [ conv2 ] , which convert S - expressions to values of type [ ' a ] and [ ' b ] respectively . of type ['a * 'b] using conversion functions [conv1] and [conv2], which convert S-expressions to values of type ['a] and ['b] respectively. *) val triple_of_sexp : (Sexp.t -> 'a) -> (Sexp.t -> 'b) -> (Sexp.t -> 'c) -> Sexp.t -> 'a * 'b * 'c * [ triple_of_sexp conv1 conv2 sexp ] converts S - expression [ sexp ] to a triple of type [ ' a * ' b * ' c ] using conversion functions [ conv1 ] , [ conv2 ] , and [ ] , which convert S - expressions to values of type [ ' a ] , [ ' b ] , and [ ' c ] respectively . to a triple of type ['a * 'b * 'c] using conversion functions [conv1], [conv2], and [conv3], which convert S-expressions to values of type ['a], ['b], and ['c] respectively. *) val list_of_sexp : (Sexp.t -> 'a) -> Sexp.t -> 'a list (** [list_of_sexp conv sexp] converts S-expression [sexp] to a value of type ['a list] using conversion function [conv], which converts an S-expression to a value of type ['a]. *) val array_of_sexp : (Sexp.t -> 'a) -> Sexp.t -> 'a array (** [array_of_sexp conv sexp] converts S-expression [sexp] to a value of type ['a array] using conversion function [conv], which converts an S-expression to a value of type ['a]. *) val hashtbl_of_sexp : (Sexp.t -> 'a) -> (Sexp.t -> 'b) -> Sexp.t -> ('a, 'b) Hashtbl.t * [ hashtbl_of_sexp conv_key conv_value sexp ] converts S - expression [ sexp ] to a value of type [ ( ' a , ' b ) ] using conversion function [ conv_key ] , which converts an S - expression to hashtable key of type [ ' a ] , and function [ conv_value ] , which converts an S - expression to hashtable value of type [ ' b ] . [sexp] to a value of type [('a, 'b) Hashtbl.t] using conversion function [conv_key], which converts an S-expression to hashtable key of type ['a], and function [conv_value], which converts an S-expression to hashtable value of type ['b]. *) val opaque_of_sexp : Sexp.t -> 'a (** [opaque_of_sexp sexp] @raise Of_sexp_error when attempting to convert an S-expression to an opaque value. *) val fun_of_sexp : Sexp.t -> 'a (** [fun_of_sexp sexp] @raise Of_sexp_error when attempting to convert an S-expression to a function. *) (** Exception converters *) val sexp_of_exn : exn -> Sexp.t (** [sexp_of_exn exc] converts exception [exc] to an S-expression. If no suitable converter is found, the standard converter in [Printexc] will be used to generate an atomic S-expression. *) val sexp_of_exn_opt : exn -> Sexp.t option (** [sexp_of_exn_opt exc] converts exception [exc] to [Some sexp]. If no suitable converter is found, [None] is returned instead. *) module Exn_converter : sig val add_auto : ?finalise : bool -> exn -> (exn -> Sexp.t) -> unit [@@deprecated "[since 2016-07] use Conv.Exn_converter.add"] val add : ?finalise : bool -> extension_constructor -> (exn -> Sexp.t) -> unit * [ add ? finalise constructor sexp_of_exn ] registers exception S - expression converter [ sexp_of_exn ] for exceptions with the given [ constructor ] . NOTE : If [ finalise ] is [ true ] , then the exception will be automatically registered for removal with the GC ( default ) . Finalisation will not work with exceptions that have been allocated outside the heap , which is the case for some standard ones e.g. [ ] . @param finalise default = [ true ] converter [sexp_of_exn] for exceptions with the given [constructor]. NOTE: If [finalise] is [true], then the exception will be automatically registered for removal with the GC (default). Finalisation will not work with exceptions that have been allocated outside the heap, which is the case for some standard ones e.g. [Sys_error]. @param finalise default = [true] *) module For_unit_tests_only : sig val size : unit -> int end end (**/**) (*_ For the syntax extension *) external ignore : _ -> unit = "%ignore" external ( = ) : 'a -> 'a -> bool = "%equal"
null
https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/sexplib0/src/sexp_conv.mli
ocaml
* Utility Module for S-expression Conversions * Dummy definitions for "optional" options, lists, and for opaque types * [default_string_of_float] reference to the default function used to convert floats to strings. Initially set to [fun n -> sprintf "%.20G" n]. * [read_old_option_format] reference for the default option format used to read option values. [Of_sexp_error] will be raised with old-style option values if this reference is set to [false]. Reading new-style option values is always supported. Using a global reference instead of changing the converter calling conventions is the only way to avoid breaking old code with the standard macros. Initially set to [true]. * [sexp_of_unit ()] converts a value of type [unit] to an S-expression. * [sexp_of_bool b] converts the value [x] of type [bool] to an S-expression. * [sexp_of_bool str] converts the value [str] of type [string] to an S-expression. * [sexp_of_bool str] converts the value [str] of type [bytes] to an S-expression. * [sexp_of_char c] converts the value [c] of type [char] to an S-expression. * [sexp_of_int n] converts the value [n] of type [int] to an S-expression. * [sexp_of_float n] converts the value [n] of type [float] to an S-expression. * [sexp_of_int32 n] converts the value [n] of type [int32] to an S-expression. * [sexp_of_nativeint n] converts the value [n] of type [nativeint] to an S-expression. * [sexp_of_lazy_t conv l] converts the value [l] of type ['a lazy_t] to an S-expression. Uses [conv] to convert values of type ['a] to an S-expression. * [sexp_of_option conv opt] converts the value [opt] of type ['a option] to an S-expression. Uses [conv] to convert values of type ['a] to an S-expression. * [sexp_of_array conv ar] converts the value [ar] of type ['a array] to an S-expression. Uses [conv] to convert values of type ['a] to an S-expression. * [sexp_of_opaque x] converts the value [x] of opaque type to an S-expression. This means the user need not provide converters, but the result cannot be interpreted. * [sexp_of_fun f] converts the value [f] of function type to a dummy S-expression. Functions cannot be serialized as S-expressions, but at least a placeholder can be generated for pretty-printing. * [Of_sexp_error (exn, sexp)] the exception raised when an S-expression could not be successfully converted to an OCaml-value. * [record_check_extra_fields] checks for extra (= unknown) fields in record S-expressions. * [of_sexp_error reason sexp] @raise Of_sexp_error (Failure reason, sexp). * [bool_of_sexp sexp] converts S-expression [sexp] to a value of type [bool]. * [char_of_sexp sexp] converts S-expression [sexp] to a value of type [char]. * [int_of_sexp sexp] converts S-expression [sexp] to a value of type [int]. * [float_of_sexp sexp] converts S-expression [sexp] to a value of type [float]. * [int32_of_sexp sexp] converts S-expression [sexp] to a value of type [int32]. * [nativeint_of_sexp sexp] converts S-expression [sexp] to a value of type [nativeint]. * [ref_of_sexp conv sexp] converts S-expression [sexp] to a value of type ['a ref] using conversion function [conv], which converts an S-expression to a value of type ['a]. * [lazy_t_of_sexp conv sexp] converts S-expression [sexp] to a value of type ['a lazy_t] using conversion function [conv], which converts an S-expression to a value of type ['a]. * [option_of_sexp conv sexp] converts S-expression [sexp] to a value of type ['a option] using conversion function [conv], which converts an S-expression to a value of type ['a]. * [list_of_sexp conv sexp] converts S-expression [sexp] to a value of type ['a list] using conversion function [conv], which converts an S-expression to a value of type ['a]. * [array_of_sexp conv sexp] converts S-expression [sexp] to a value of type ['a array] using conversion function [conv], which converts an S-expression to a value of type ['a]. * [opaque_of_sexp sexp] @raise Of_sexp_error when attempting to convert an S-expression to an opaque value. * [fun_of_sexp sexp] @raise Of_sexp_error when attempting to convert an S-expression to a function. * Exception converters * [sexp_of_exn exc] converts exception [exc] to an S-expression. If no suitable converter is found, the standard converter in [Printexc] will be used to generate an atomic S-expression. * [sexp_of_exn_opt exc] converts exception [exc] to [Some sexp]. If no suitable converter is found, [None] is returned instead. */* _ For the syntax extension
type sexp_bool = bool [@@deprecated "[since 2019-03] use [@sexp.bool] instead"] type 'a sexp_option = 'a option [@@deprecated "[since 2019-03] use [@sexp.option] instead"] type 'a sexp_list = 'a list [@@deprecated "[since 2019-03] use [@sexp.list] instead"] type 'a sexp_array = 'a array [@@deprecated "[since 2019-03] use [@sexp.array] instead"] type 'a sexp_opaque = 'a [@@deprecated "[since 2019-03] use [@sexp.opaque] instead"] * { 6 Conversion of OCaml - values to S - expressions } val default_string_of_float : (float -> string) ref val write_old_option_format : bool ref * [ write_old_option_format ] reference for the default option format used to write option values . If set to [ true ] , the old - style option format will be used , the new - style one otherwise . Initially set to [ true ] . used to write option values. If set to [true], the old-style option format will be used, the new-style one otherwise. Initially set to [true]. *) val read_old_option_format : bool ref * We re - export a tail recursive map function , because some modules override the standard library functions ( e.g. [ StdLabels ] ) which wrecks havoc with the extension . override the standard library functions (e.g. [StdLabels]) which wrecks havoc with the camlp4 extension. *) val list_map : ('a -> 'b) -> 'a list -> 'b list val sexp_of_unit : unit -> Sexp.t val sexp_of_bool : bool -> Sexp.t val sexp_of_string : string -> Sexp.t val sexp_of_bytes : bytes -> Sexp.t val sexp_of_char : char -> Sexp.t val sexp_of_int : int -> Sexp.t val sexp_of_float : float -> Sexp.t val sexp_of_int32 : int32 -> Sexp.t val sexp_of_int64 : int64 -> Sexp.t * [ sexp_of_int64 n ] converts the value [ n ] of type [ int64 ] to an S - expression . S-expression. *) val sexp_of_nativeint : nativeint -> Sexp.t val sexp_of_ref : ('a -> Sexp.t) -> 'a ref -> Sexp.t * [ sexp_of_ref conv r ] converts the value [ r ] of type [ ' a ref ] to an S - expression . Uses [ conv ] to convert values of type [ ' a ] to an S - expression . an S-expression. Uses [conv] to convert values of type ['a] to an S-expression. *) val sexp_of_lazy_t : ('a -> Sexp.t) -> 'a lazy_t -> Sexp.t val sexp_of_option : ('a -> Sexp.t) -> 'a option -> Sexp.t val sexp_of_pair : ('a -> Sexp.t) -> ('b -> Sexp.t) -> 'a * 'b -> Sexp.t * [ sexp_of_pair conv1 conv2 pair ] converts a pair to an S - expression . It uses its first argument to convert the first element of the pair , and its second argument to convert the second element of the pair . It uses its first argument to convert the first element of the pair, and its second argument to convert the second element of the pair. *) val sexp_of_triple : ('a -> Sexp.t) -> ('b -> Sexp.t) -> ('c -> Sexp.t) -> 'a * 'b * 'c -> Sexp.t * [ sexp_of_triple conv1 conv2 conv3 triple ] converts a triple to an S - expression using [ conv1 ] , [ conv2 ] , and [ ] to convert its elements . an S-expression using [conv1], [conv2], and [conv3] to convert its elements. *) val sexp_of_list : ('a -> Sexp.t) -> 'a list -> Sexp.t * [ sexp_of_list conv lst ] converts the value [ lst ] of type [ ' a list ] to an S - expression . Uses [ conv ] to convert values of type [ ' a ] to an S - expression . list] to an S-expression. Uses [conv] to convert values of type ['a] to an S-expression. *) val sexp_of_array : ('a -> Sexp.t) -> 'a array -> Sexp.t val sexp_of_hashtbl : ('a -> Sexp.t) -> ('b -> Sexp.t) -> ('a, 'b) Hashtbl.t -> Sexp.t * [ ] converts the value [ htbl ] of type [ ( ' a , ' b ) ] to an S - expression . Uses [ conv_key ] to convert the hashtable keys of type [ ' a ] , and [ conv_value ] to convert hashtable values of type [ ' b ] to S - expressions . of type [('a, 'b) Hashtbl.t] to an S-expression. Uses [conv_key] to convert the hashtable keys of type ['a], and [conv_value] to convert hashtable values of type ['b] to S-expressions. *) val sexp_of_opaque : 'a -> Sexp.t val sexp_of_fun : ('a -> 'b) -> Sexp.t * { 6 Conversion of S - expressions to OCaml - values } exception Of_sexp_error of exn * Sexp.t val record_check_extra_fields : bool ref val of_sexp_error : string -> Sexp.t -> 'a val of_sexp_error_exn : exn -> Sexp.t -> 'a * [ of_sexp_error exc sexp ] @raise Of_sexp_error ( exc , sexp ) . val unit_of_sexp : Sexp.t -> unit * [ unit_of_sexp sexp ] converts S - expression [ sexp ] to a value of type [ unit ] . [unit]. *) val bool_of_sexp : Sexp.t -> bool val string_of_sexp : Sexp.t -> string * [ sexp ] converts S - expression [ sexp ] to a value of type [ string ] . [string]. *) val bytes_of_sexp : Sexp.t -> bytes * [ sexp ] converts S - expression [ sexp ] to a value of type [ bytes ] . [bytes]. *) val char_of_sexp : Sexp.t -> char val int_of_sexp : Sexp.t -> int val float_of_sexp : Sexp.t -> float val int32_of_sexp : Sexp.t -> int32 val int64_of_sexp : Sexp.t -> int64 * [ int64_of_sexp sexp ] converts S - expression [ sexp ] to a value of type [ int64 ] . [int64]. *) val nativeint_of_sexp : Sexp.t -> nativeint val ref_of_sexp : (Sexp.t -> 'a) -> Sexp.t -> 'a ref val lazy_t_of_sexp : (Sexp.t -> 'a) -> Sexp.t -> 'a lazy_t val option_of_sexp : (Sexp.t -> 'a) -> Sexp.t -> 'a option val pair_of_sexp : (Sexp.t -> 'a) -> (Sexp.t -> 'b) -> Sexp.t -> 'a * 'b * [ pair_of_sexp conv1 conv2 sexp ] converts S - expression [ sexp ] to a pair of type [ ' a * ' b ] using conversion functions [ conv1 ] and [ conv2 ] , which convert S - expressions to values of type [ ' a ] and [ ' b ] respectively . of type ['a * 'b] using conversion functions [conv1] and [conv2], which convert S-expressions to values of type ['a] and ['b] respectively. *) val triple_of_sexp : (Sexp.t -> 'a) -> (Sexp.t -> 'b) -> (Sexp.t -> 'c) -> Sexp.t -> 'a * 'b * 'c * [ triple_of_sexp conv1 conv2 sexp ] converts S - expression [ sexp ] to a triple of type [ ' a * ' b * ' c ] using conversion functions [ conv1 ] , [ conv2 ] , and [ ] , which convert S - expressions to values of type [ ' a ] , [ ' b ] , and [ ' c ] respectively . to a triple of type ['a * 'b * 'c] using conversion functions [conv1], [conv2], and [conv3], which convert S-expressions to values of type ['a], ['b], and ['c] respectively. *) val list_of_sexp : (Sexp.t -> 'a) -> Sexp.t -> 'a list val array_of_sexp : (Sexp.t -> 'a) -> Sexp.t -> 'a array val hashtbl_of_sexp : (Sexp.t -> 'a) -> (Sexp.t -> 'b) -> Sexp.t -> ('a, 'b) Hashtbl.t * [ hashtbl_of_sexp conv_key conv_value sexp ] converts S - expression [ sexp ] to a value of type [ ( ' a , ' b ) ] using conversion function [ conv_key ] , which converts an S - expression to hashtable key of type [ ' a ] , and function [ conv_value ] , which converts an S - expression to hashtable value of type [ ' b ] . [sexp] to a value of type [('a, 'b) Hashtbl.t] using conversion function [conv_key], which converts an S-expression to hashtable key of type ['a], and function [conv_value], which converts an S-expression to hashtable value of type ['b]. *) val opaque_of_sexp : Sexp.t -> 'a val fun_of_sexp : Sexp.t -> 'a val sexp_of_exn : exn -> Sexp.t val sexp_of_exn_opt : exn -> Sexp.t option module Exn_converter : sig val add_auto : ?finalise : bool -> exn -> (exn -> Sexp.t) -> unit [@@deprecated "[since 2016-07] use Conv.Exn_converter.add"] val add : ?finalise : bool -> extension_constructor -> (exn -> Sexp.t) -> unit * [ add ? finalise constructor sexp_of_exn ] registers exception S - expression converter [ sexp_of_exn ] for exceptions with the given [ constructor ] . NOTE : If [ finalise ] is [ true ] , then the exception will be automatically registered for removal with the GC ( default ) . Finalisation will not work with exceptions that have been allocated outside the heap , which is the case for some standard ones e.g. [ ] . @param finalise default = [ true ] converter [sexp_of_exn] for exceptions with the given [constructor]. NOTE: If [finalise] is [true], then the exception will be automatically registered for removal with the GC (default). Finalisation will not work with exceptions that have been allocated outside the heap, which is the case for some standard ones e.g. [Sys_error]. @param finalise default = [true] *) module For_unit_tests_only : sig val size : unit -> int end end external ignore : _ -> unit = "%ignore" external ( = ) : 'a -> 'a -> bool = "%equal"
cfd0a1afba3cdb671b034fa89ec768c21df531c86a4a271866f335e459cf3f19
gtk2hs/gtk2hs
CNames.hs
C->Haskell Compiler : C name analysis -- Author : Created : 16 October 99 -- Version $ Revision : 1.2 $ from $ Date : 2005/07/29 01:26:56 $ -- Copyright ( c ) 1999 -- -- This file 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 file 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. -- --- DESCRIPTION --------------------------------------------------------------- -- -- Name analysis of C header files. -- --- DOCU ---------------------------------------------------------------------- -- language : 98 -- -- * Member names are not looked up, because this requires type information -- about the expressions before the `.' or `->'. -- --- TODO ---------------------------------------------------------------------- -- -- * `defObjOrErr': currently, repeated declarations are completely ignored; -- eventually, the consistency of the declarations should be checked -- module CNames (nameAnalysis) where import Control.Monad (when, mapM_) import Position (Position, posOf) import Idents (Ident, identToLexeme) import C2HSState (CST, nop) import CAST import CAttrs (AttrC, CObj(..), CTag(..), CDef(..)) import CBuiltin (builtinTypeNames) import CTrav (CT, getCHeaderCT, runCT, enter, enterObjs, leave, leaveObjs, ifCTExc, raiseErrorCTExc, defObj, findTypeObj, findValueObj, defTag, refersToDef, isTypedef) -- monad and wrapper -- ----------------- -- local instance of the C traversal monad -- type NA a = CT () a -- name analysis of C header files (EXPORTED) -- nameAnalysis :: AttrC -> CST s AttrC nameAnalysis ac = do (ac', _) <- runCT naCHeader ac () return ac' -- name analyis traversal -- ---------------------- -- traverse a complete header file -- -- * in case of an error, back off the current declaration -- naCHeader :: NA () naCHeader = do -- establish definitions for builtins -- mapM_ (uncurry defObjOrErr) builtinTypeNames -- -- analyse the header -- CHeader decls _ <- getCHeaderCT mapM_ (\decl -> naCExtDecl decl `ifCTExc` nop) decls -- Processing of toplevel declarations -- -- * We turn function definitions into prototypes, as we are not interested in -- function bodies. -- naCExtDecl :: CExtDecl -> NA () naCExtDecl (CDeclExt decl ) = naCDecl decl naCExtDecl (CFDefExt (CFunDef specs declr _ _ at)) = naCDecl $ CDecl specs [(Just declr, Nothing, Nothing)] at naCExtDecl (CAsmExt at ) = return () naCDecl :: CDecl -> NA () naCDecl decl@(CDecl specs decls _) = do mapM_ naCDeclSpec specs mapM_ naTriple decls where naTriple (odeclr, oinit, oexpr) = do let obj = if isTypedef decl then TypeCO decl else ObjCO decl mapMaybeM_ (naCDeclr obj) odeclr mapMaybeM_ naCInit oinit mapMaybeM_ naCExpr oexpr naCDeclSpec :: CDeclSpec -> NA () naCDeclSpec (CTypeSpec tspec) = naCTypeSpec tspec naCDeclSpec _ = nop naCTypeSpec :: CTypeSpec -> NA () naCTypeSpec (CSUType su _) = naCStructUnion (StructUnionCT su) su naCTypeSpec (CEnumType enum _) = naCEnum (EnumCT enum) enum naCTypeSpec (CTypeDef ide _) = do (obj, _) <- findTypeObj ide False ide `refersToDef` ObjCD obj naCTypeSpec _ = nop naCStructUnion :: CTag -> CStructUnion -> NA () naCStructUnion tag (CStruct _ oide decls _) = do mapMaybeM_ (`defTagOrErr` tag) oide enterObjs -- enter local struct range for objects mapM_ naCDecl decls leaveObjs -- leave range naCEnum :: CTag -> CEnum -> NA () naCEnum tag enum@(CEnum oide enumrs _) = do mapMaybeM_ (`defTagOrErr` tag) oide mapM_ naEnumr enumrs where naEnumr (ide, oexpr) = do ide `defObjOrErr` EnumCO ide enum mapMaybeM_ naCExpr oexpr naCDeclr :: CObj -> CDeclr -> NA () naCDeclr obj (CVarDeclr oide _) = mapMaybeM_ (`defObjOrErr` obj) oide naCDeclr obj (CPtrDeclr _ declr _ ) = naCDeclr obj declr naCDeclr obj (CArrDeclr declr _ oexpr _ ) = do naCDeclr obj declr mapMaybeM_ naCExpr oexpr naCDeclr obj (CFunDeclr declr decls _ _ ) = do naCDeclr obj declr enterObjs -- enter range of function arguments mapM_ naCDecl decls leaveObjs -- end of function arguments naCInit :: CInit -> NA () naCInit (CInitExpr expr _) = naCExpr expr naCInit (CInitList inits _) = mapM_ (naCInit . snd) inits naCExpr :: CExpr -> NA () naCExpr (CComma exprs _) = mapM_ naCExpr exprs naCExpr (CAssign _ expr1 expr2 _) = naCExpr expr1 >> naCExpr expr2 naCExpr (CCond expr1 expr2 expr3 _) = naCExpr expr1 >> mapMaybeM_ naCExpr expr2 >> naCExpr expr3 naCExpr (CBinary _ expr1 expr2 _) = naCExpr expr1 >> naCExpr expr2 naCExpr (CCast decl expr _) = naCDecl decl >> naCExpr expr naCExpr (CUnary _ expr _) = naCExpr expr naCExpr (CSizeofExpr expr _) = naCExpr expr naCExpr (CSizeofType decl _) = naCDecl decl naCExpr (CAlignofExpr expr _) = naCExpr expr naCExpr (CAlignofType decl _) = naCDecl decl naCExpr (CIndex expr1 expr2 _) = naCExpr expr1 >> naCExpr expr2 naCExpr (CCall expr exprs _) = naCExpr expr >> mapM_ naCExpr exprs naCExpr (CMember expr ide _ _) = naCExpr expr naCExpr (CVar ide _) = do (obj, _) <- findValueObj ide False ide `refersToDef` ObjCD obj naCExpr (CConst _ _) = nop naCExpr (CCompoundLit _ inits _) = mapM_ (naCInit . snd) inits -- auxilliary functions -- -------------------- -- raise an error and exception if the identifier is defined twice -- defTagOrErr :: Ident -> CTag -> NA () ide `defTagOrErr` tag = do otag <- ide `defTag` tag case otag of Nothing -> nop Just tag' -> declaredTwiceErr ide (posOf tag') -- associate an object with a referring identifier -- -- * currently, repeated declarations are completely ignored; eventually, the -- consistency of the declarations should be checked -- defObjOrErr :: Ident -> CObj -> NA () ide `defObjOrErr` obj = ide `defObj` obj >> nop -- maps some monad operation into a `Maybe', discarding the result -- mapMaybeM_ :: Monad m => (a -> m b) -> Maybe a -> m () mapMaybeM_ m Nothing = return () mapMaybeM_ m (Just a) = m a >> return () -- error messages -- -------------- declaredTwiceErr :: Ident -> Position -> NA a declaredTwiceErr ide otherPos = raiseErrorCTExc (posOf ide) ["Identifier declared twice!", "The identifier `" ++ identToLexeme ide ++ "' was already declared at " ++ show otherPos ++ "."]
null
https://raw.githubusercontent.com/gtk2hs/gtk2hs/0f90caa1dae319a0f4bbab76ed1a84f17c730adf/tools/c2hs/c/CNames.hs
haskell
This file is free software; you can redistribute it and/or modify (at your option) any later version. This file 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. - DESCRIPTION --------------------------------------------------------------- Name analysis of C header files. - DOCU ---------------------------------------------------------------------- * Member names are not looked up, because this requires type information about the expressions before the `.' or `->'. - TODO ---------------------------------------------------------------------- * `defObjOrErr': currently, repeated declarations are completely ignored; eventually, the consistency of the declarations should be checked monad and wrapper ----------------- local instance of the C traversal monad name analysis of C header files (EXPORTED) name analyis traversal ---------------------- traverse a complete header file * in case of an error, back off the current declaration establish definitions for builtins analyse the header Processing of toplevel declarations * We turn function definitions into prototypes, as we are not interested in function bodies. enter local struct range for objects leave range enter range of function arguments end of function arguments auxilliary functions -------------------- raise an error and exception if the identifier is defined twice associate an object with a referring identifier * currently, repeated declarations are completely ignored; eventually, the consistency of the declarations should be checked maps some monad operation into a `Maybe', discarding the result error messages --------------
C->Haskell Compiler : C name analysis Author : Created : 16 October 99 Version $ Revision : 1.2 $ from $ Date : 2005/07/29 01:26:56 $ Copyright ( c ) 1999 it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or language : 98 module CNames (nameAnalysis) where import Control.Monad (when, mapM_) import Position (Position, posOf) import Idents (Ident, identToLexeme) import C2HSState (CST, nop) import CAST import CAttrs (AttrC, CObj(..), CTag(..), CDef(..)) import CBuiltin (builtinTypeNames) import CTrav (CT, getCHeaderCT, runCT, enter, enterObjs, leave, leaveObjs, ifCTExc, raiseErrorCTExc, defObj, findTypeObj, findValueObj, defTag, refersToDef, isTypedef) type NA a = CT () a nameAnalysis :: AttrC -> CST s AttrC nameAnalysis ac = do (ac', _) <- runCT naCHeader ac () return ac' naCHeader :: NA () naCHeader = do mapM_ (uncurry defObjOrErr) builtinTypeNames CHeader decls _ <- getCHeaderCT mapM_ (\decl -> naCExtDecl decl `ifCTExc` nop) decls naCExtDecl :: CExtDecl -> NA () naCExtDecl (CDeclExt decl ) = naCDecl decl naCExtDecl (CFDefExt (CFunDef specs declr _ _ at)) = naCDecl $ CDecl specs [(Just declr, Nothing, Nothing)] at naCExtDecl (CAsmExt at ) = return () naCDecl :: CDecl -> NA () naCDecl decl@(CDecl specs decls _) = do mapM_ naCDeclSpec specs mapM_ naTriple decls where naTriple (odeclr, oinit, oexpr) = do let obj = if isTypedef decl then TypeCO decl else ObjCO decl mapMaybeM_ (naCDeclr obj) odeclr mapMaybeM_ naCInit oinit mapMaybeM_ naCExpr oexpr naCDeclSpec :: CDeclSpec -> NA () naCDeclSpec (CTypeSpec tspec) = naCTypeSpec tspec naCDeclSpec _ = nop naCTypeSpec :: CTypeSpec -> NA () naCTypeSpec (CSUType su _) = naCStructUnion (StructUnionCT su) su naCTypeSpec (CEnumType enum _) = naCEnum (EnumCT enum) enum naCTypeSpec (CTypeDef ide _) = do (obj, _) <- findTypeObj ide False ide `refersToDef` ObjCD obj naCTypeSpec _ = nop naCStructUnion :: CTag -> CStructUnion -> NA () naCStructUnion tag (CStruct _ oide decls _) = do mapMaybeM_ (`defTagOrErr` tag) oide mapM_ naCDecl decls naCEnum :: CTag -> CEnum -> NA () naCEnum tag enum@(CEnum oide enumrs _) = do mapMaybeM_ (`defTagOrErr` tag) oide mapM_ naEnumr enumrs where naEnumr (ide, oexpr) = do ide `defObjOrErr` EnumCO ide enum mapMaybeM_ naCExpr oexpr naCDeclr :: CObj -> CDeclr -> NA () naCDeclr obj (CVarDeclr oide _) = mapMaybeM_ (`defObjOrErr` obj) oide naCDeclr obj (CPtrDeclr _ declr _ ) = naCDeclr obj declr naCDeclr obj (CArrDeclr declr _ oexpr _ ) = do naCDeclr obj declr mapMaybeM_ naCExpr oexpr naCDeclr obj (CFunDeclr declr decls _ _ ) = do naCDeclr obj declr mapM_ naCDecl decls naCInit :: CInit -> NA () naCInit (CInitExpr expr _) = naCExpr expr naCInit (CInitList inits _) = mapM_ (naCInit . snd) inits naCExpr :: CExpr -> NA () naCExpr (CComma exprs _) = mapM_ naCExpr exprs naCExpr (CAssign _ expr1 expr2 _) = naCExpr expr1 >> naCExpr expr2 naCExpr (CCond expr1 expr2 expr3 _) = naCExpr expr1 >> mapMaybeM_ naCExpr expr2 >> naCExpr expr3 naCExpr (CBinary _ expr1 expr2 _) = naCExpr expr1 >> naCExpr expr2 naCExpr (CCast decl expr _) = naCDecl decl >> naCExpr expr naCExpr (CUnary _ expr _) = naCExpr expr naCExpr (CSizeofExpr expr _) = naCExpr expr naCExpr (CSizeofType decl _) = naCDecl decl naCExpr (CAlignofExpr expr _) = naCExpr expr naCExpr (CAlignofType decl _) = naCDecl decl naCExpr (CIndex expr1 expr2 _) = naCExpr expr1 >> naCExpr expr2 naCExpr (CCall expr exprs _) = naCExpr expr >> mapM_ naCExpr exprs naCExpr (CMember expr ide _ _) = naCExpr expr naCExpr (CVar ide _) = do (obj, _) <- findValueObj ide False ide `refersToDef` ObjCD obj naCExpr (CConst _ _) = nop naCExpr (CCompoundLit _ inits _) = mapM_ (naCInit . snd) inits defTagOrErr :: Ident -> CTag -> NA () ide `defTagOrErr` tag = do otag <- ide `defTag` tag case otag of Nothing -> nop Just tag' -> declaredTwiceErr ide (posOf tag') defObjOrErr :: Ident -> CObj -> NA () ide `defObjOrErr` obj = ide `defObj` obj >> nop mapMaybeM_ :: Monad m => (a -> m b) -> Maybe a -> m () mapMaybeM_ m Nothing = return () mapMaybeM_ m (Just a) = m a >> return () declaredTwiceErr :: Ident -> Position -> NA a declaredTwiceErr ide otherPos = raiseErrorCTExc (posOf ide) ["Identifier declared twice!", "The identifier `" ++ identToLexeme ide ++ "' was already declared at " ++ show otherPos ++ "."]
a1d3e29ce8db52ff9232befc61331b46f7200eb33d7049134d3a235385e3448f
ashwinbhaskar/kafka-util
spec.clj
(ns kafka-util.spec (:require [clojure.spec.alpha :as s] [kafka-util.utils :as u])) (s/def ::broker (s/and string? u/not-nil? not-empty)) (s/def ::port pos-int?) (s/def ::security-protocol #{"SSL" "PLAINTEXT" "SASL_PLAINTEXT" "SASL_SSL"}) (s/def ::key-deserializer #{:string :long}) (s/def ::decode-value-as-json boolean?) (s/def ::consumer-settings (s/keys :req-un [::broker ::port ::security-protocol ::key-deserializer] :opt-un [::decode-value-as-json]))
null
https://raw.githubusercontent.com/ashwinbhaskar/kafka-util/9284c43856911749a22a036508b3538fe869b60f/src/kafka_util/spec.clj
clojure
(ns kafka-util.spec (:require [clojure.spec.alpha :as s] [kafka-util.utils :as u])) (s/def ::broker (s/and string? u/not-nil? not-empty)) (s/def ::port pos-int?) (s/def ::security-protocol #{"SSL" "PLAINTEXT" "SASL_PLAINTEXT" "SASL_SSL"}) (s/def ::key-deserializer #{:string :long}) (s/def ::decode-value-as-json boolean?) (s/def ::consumer-settings (s/keys :req-un [::broker ::port ::security-protocol ::key-deserializer] :opt-un [::decode-value-as-json]))
f967637727e5980618ebd61edf2e1054719aa32f1097b7dbc767491dc738cece
broadinstitute/firecloud-ui
create_notebook.cljs
(ns broadfcui.page.workspace.notebooks.create-notebook (:require [dmohs.react :as react] [broadfcui.common.components :as comps] [broadfcui.common.input :as input] [broadfcui.common.style :as style] [broadfcui.components.blocker :refer [blocker]] [broadfcui.components.foundation-tooltip :refer [FoundationTooltip]] [broadfcui.components.modals :as modals] [broadfcui.page.workspace.notebooks.utils :as notebook-utils] [broadfcui.utils :as utils] )) (def base-notebook {:cells [{:cell_type "code" :execution_count nil :metadata {} :outputs [] :source []}] :nbformat 4 :nbformat_minor 2} ) (def python2-notebook (merge base-notebook {:metadata {:kernelspec {:display_name "Python 2" :language "python", :name "python2"}}})) (def python3-notebook (merge base-notebook {:metadata {:kernelspec {:display_name "Python 3" :language "python", :name "python3"}}})) (def hail01-notebook (merge base-notebook {:metadata {:kernelspec {:display_name "PySpark 2" :language "python", :name "pyspark2"}}})) (def hail02-notebook (merge base-notebook {:metadata {:kernelspec {:display_name "PySpark 3" :language "python", :name "pyspark3"}}})) (def r-notebook (merge base-notebook {:metadata {:kernelspec {:display_name "R" :language "R" :name "ir"} :language_info {:codemirror_mode "r" :file_extension ".r" :mimetype "text/x-r-source" :name "R" :pygments_lexer "r" :version "3.3.3"}}})) (def kernel-map {"Python 2" python2-notebook "Python 3" python3-notebook "R" r-notebook "Hail 0.1" hail01-notebook TODO Hail 0.2 not supported in yet " Hail 0.2 " hail02 - notebook }) (react/defc NotebookCreator {:render (fn [{:keys [props state this]}] (let [{:keys [creating? server-response validation-errors]} @state {:keys [server-error]} server-response {:keys [dismiss]} props] [modals/OKCancelForm {:header "Create New Notebook" :dismiss dismiss :ok-button {:text "Create" :onClick #(this :-create-notebook)} :content (react/create-element [:div {:style {:marginTop 0 :width 500}} (when creating? (blocker "Creating notebook...")) [:div {:style {:width "48%" :marginRight "4%" :marginBottom "1%"}} [FoundationTooltip {:text (notebook-utils/create-inline-form-label "Name") :tooltip "The name of the notebook. Does not need to include .ipynb. This can be changed later."}]] [input/TextField {:data-test-id "notebook-name-input" :ref "newNotebookName" :autoFocus true :style {:width "100%"} :defaultValue "" :predicates [(input/nonempty "Notebook name") (input/alphanumeric_-space "Notebook name")]}] [:div {:style {:width "48%" :marginRight "4%" :marginBottom "1%"}} [FoundationTooltip {:text (notebook-utils/create-inline-form-label "Kernel") :tooltip "The notebook kernel. This can be changed later."}]] (style/create-identity-select {:data-test-id "kernel-select" :ref "newNotebookKernel" :style {:width "100%"} :defaultValue "Python 3"} (keys kernel-map)) (style/create-validation-error-message validation-errors) [comps/ErrorViewer {:error server-error}]])}])) :-create-notebook (fn [{:keys [props state this refs]}] (let [{:keys [pet-token notebooks refresh-notebooks dismiss]} props bucket-name (get-in props [:workspace :workspace :bucketName]) [new-notebook-name & fails] (input/get-and-validate refs "newNotebookName") new-notebook-kernel (.-value (@refs "newNotebookKernel"))] (if fails (swap! state assoc :validation-errors fails) ; fail if a notebook already exists with the same name (if (some (comp (partial = new-notebook-name) notebook-utils/notebook-name) notebooks) (swap! state assoc :validation-errors [(str "Notebook with name \"" new-notebook-name "\" already exists")]) (do (swap! state assoc :creating? true) (notebook-utils/create-notebook bucket-name pet-token new-notebook-name (get kernel-map new-notebook-kernel) (fn [{:keys [success? raw-response]}] (swap! state assoc :creating? false) (if success? (do (refresh-notebooks) (dismiss)) (swap! state assoc :server-response {:server-error (notebook-utils/parse-gcs-error raw-response)})))))))))})
null
https://raw.githubusercontent.com/broadinstitute/firecloud-ui/8eb077bc137ead105db5665a8fa47a7523145633/src/cljs/main/broadfcui/page/workspace/notebooks/create_notebook.cljs
clojure
fail if a notebook already exists with the same name
(ns broadfcui.page.workspace.notebooks.create-notebook (:require [dmohs.react :as react] [broadfcui.common.components :as comps] [broadfcui.common.input :as input] [broadfcui.common.style :as style] [broadfcui.components.blocker :refer [blocker]] [broadfcui.components.foundation-tooltip :refer [FoundationTooltip]] [broadfcui.components.modals :as modals] [broadfcui.page.workspace.notebooks.utils :as notebook-utils] [broadfcui.utils :as utils] )) (def base-notebook {:cells [{:cell_type "code" :execution_count nil :metadata {} :outputs [] :source []}] :nbformat 4 :nbformat_minor 2} ) (def python2-notebook (merge base-notebook {:metadata {:kernelspec {:display_name "Python 2" :language "python", :name "python2"}}})) (def python3-notebook (merge base-notebook {:metadata {:kernelspec {:display_name "Python 3" :language "python", :name "python3"}}})) (def hail01-notebook (merge base-notebook {:metadata {:kernelspec {:display_name "PySpark 2" :language "python", :name "pyspark2"}}})) (def hail02-notebook (merge base-notebook {:metadata {:kernelspec {:display_name "PySpark 3" :language "python", :name "pyspark3"}}})) (def r-notebook (merge base-notebook {:metadata {:kernelspec {:display_name "R" :language "R" :name "ir"} :language_info {:codemirror_mode "r" :file_extension ".r" :mimetype "text/x-r-source" :name "R" :pygments_lexer "r" :version "3.3.3"}}})) (def kernel-map {"Python 2" python2-notebook "Python 3" python3-notebook "R" r-notebook "Hail 0.1" hail01-notebook TODO Hail 0.2 not supported in yet " Hail 0.2 " hail02 - notebook }) (react/defc NotebookCreator {:render (fn [{:keys [props state this]}] (let [{:keys [creating? server-response validation-errors]} @state {:keys [server-error]} server-response {:keys [dismiss]} props] [modals/OKCancelForm {:header "Create New Notebook" :dismiss dismiss :ok-button {:text "Create" :onClick #(this :-create-notebook)} :content (react/create-element [:div {:style {:marginTop 0 :width 500}} (when creating? (blocker "Creating notebook...")) [:div {:style {:width "48%" :marginRight "4%" :marginBottom "1%"}} [FoundationTooltip {:text (notebook-utils/create-inline-form-label "Name") :tooltip "The name of the notebook. Does not need to include .ipynb. This can be changed later."}]] [input/TextField {:data-test-id "notebook-name-input" :ref "newNotebookName" :autoFocus true :style {:width "100%"} :defaultValue "" :predicates [(input/nonempty "Notebook name") (input/alphanumeric_-space "Notebook name")]}] [:div {:style {:width "48%" :marginRight "4%" :marginBottom "1%"}} [FoundationTooltip {:text (notebook-utils/create-inline-form-label "Kernel") :tooltip "The notebook kernel. This can be changed later."}]] (style/create-identity-select {:data-test-id "kernel-select" :ref "newNotebookKernel" :style {:width "100%"} :defaultValue "Python 3"} (keys kernel-map)) (style/create-validation-error-message validation-errors) [comps/ErrorViewer {:error server-error}]])}])) :-create-notebook (fn [{:keys [props state this refs]}] (let [{:keys [pet-token notebooks refresh-notebooks dismiss]} props bucket-name (get-in props [:workspace :workspace :bucketName]) [new-notebook-name & fails] (input/get-and-validate refs "newNotebookName") new-notebook-kernel (.-value (@refs "newNotebookKernel"))] (if fails (swap! state assoc :validation-errors fails) (if (some (comp (partial = new-notebook-name) notebook-utils/notebook-name) notebooks) (swap! state assoc :validation-errors [(str "Notebook with name \"" new-notebook-name "\" already exists")]) (do (swap! state assoc :creating? true) (notebook-utils/create-notebook bucket-name pet-token new-notebook-name (get kernel-map new-notebook-kernel) (fn [{:keys [success? raw-response]}] (swap! state assoc :creating? false) (if success? (do (refresh-notebooks) (dismiss)) (swap! state assoc :server-response {:server-error (notebook-utils/parse-gcs-error raw-response)})))))))))})
0901a600a234f57f0a3bcdcc168e7909a5a491cf184d1a973e2038ce588defd4
pbogdan/nvs
Main.hs
module Main where import Protolude import Nvs.Cli main :: IO () main = defaultMain
null
https://raw.githubusercontent.com/pbogdan/nvs/d9705b34a4385e64700c4f4f54171b65bc73b1ee/app/Main.hs
haskell
module Main where import Protolude import Nvs.Cli main :: IO () main = defaultMain
46bd9e45ded5f180195e86d85047cba1dcd5c8e602c5a6193636cf8b5236e26f
marigold-dev/deku
external_vm_client.mli
open Deku_crypto open Deku_stdlib open External_vm_protocol exception Vm_lifecycle_error of string exception Vm_execution_error of string val get_initial_state : unit -> State.t val set_initial_state : State.t -> unit val start_vm_ipc : named_pipe_path:string -> unit type ledger_api = < take_tickets : Deku_ledger.Address.t -> (Deku_ledger.Ticket_id.t * N.t) list ; deposit : Deku_ledger.Address.t -> Deku_ledger.Ticket_id.t * N.t -> unit > val apply_vm_operation_exn : state:State.t -> ledger_api:< ledger_api ; .. > -> level:Deku_concepts.Level.t -> source:Key_hash.t -> tickets:(Deku_ledger.Ticket_id.t * N.t) list -> (BLAKE2b.t * string) option -> State.t val close_vm_ipc : unit -> unit
null
https://raw.githubusercontent.com/marigold-dev/deku/6d11a7de26dbbdec54439503e81def45ed19b45e/deku-p/src/core/external_vm/external_vm_client.mli
ocaml
open Deku_crypto open Deku_stdlib open External_vm_protocol exception Vm_lifecycle_error of string exception Vm_execution_error of string val get_initial_state : unit -> State.t val set_initial_state : State.t -> unit val start_vm_ipc : named_pipe_path:string -> unit type ledger_api = < take_tickets : Deku_ledger.Address.t -> (Deku_ledger.Ticket_id.t * N.t) list ; deposit : Deku_ledger.Address.t -> Deku_ledger.Ticket_id.t * N.t -> unit > val apply_vm_operation_exn : state:State.t -> ledger_api:< ledger_api ; .. > -> level:Deku_concepts.Level.t -> source:Key_hash.t -> tickets:(Deku_ledger.Ticket_id.t * N.t) list -> (BLAKE2b.t * string) option -> State.t val close_vm_ipc : unit -> unit
c02646e2d763da851c2b8e71d328d1e01ce76901c957e18e4025187e5b557928
dgiot/dgiot
emqx_broker_bench.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2021 - 2022 EMQ Technologies Co. , Ltd. All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%-------------------------------------------------------------------- -module(emqx_broker_bench). -ifdef(EMQX_BENCHMARK). -export([run/1, run1/0, run1/4]). -define(T(Expr), timer:tc(fun() -> Expr end)). run1() -> run1(80, 1000, 80, 10000). run1(Subs, SubOps, Pubs, PubOps) -> run(#{subscribers => Subs, publishers => Pubs, sub_ops => SubOps, pub_ops => PubOps, sub_ptn => <<"device/{{id}}/+/{{num}}/#">>, pub_ptn => <<"device/{{id}}/foo/{{num}}/bar/1/2/3/4/5">> }). %% setting fields: %% - subscribers: spawn this number of subscriber workers %% - publishers: spawn this number of publisher workers %% - sub_ops: the number of subscribes (route insert) each subscriber runs %% - pub_ops: the number of publish (route lookups) each publisher runs %% - sub_ptn: subscribe topic pattern like a/+/b/+/c/# %% or a/+/{{id}}/{{num}}/# to generate pattern with {{id}} %% replaced by worker id and {{num}} replaced by topic number. %% - pub_ptn: topic pattern used to benchmark publish (match) performance %% e.g. a/x/{{id}}/{{num}}/foo/bar run(#{subscribers := Subs, publishers := Pubs, sub_ops := SubOps, pub_ops := PubOps } = Settings) -> SubsPids = start_callers(Subs, fun start_subscriber/1, Settings), PubsPids = start_callers(Pubs, fun start_publisher/1, Settings), _ = collect_results(SubsPids, subscriber_ready), io:format(user, "subscribe ...~n", []), {T1, SubsTime} = ?T(begin lists:foreach(fun(Pid) -> Pid ! start_subscribe end, SubsPids), collect_results(SubsPids, subscribe_time) end), io:format(user, "InsertTotalTime: ~s~n", [ns(T1)]), io:format(user, "InsertTimeAverage: ~s~n", [ns(SubsTime / Subs)]), io:format(user, "InsertRps: ~p~n", [rps(Subs * SubOps, T1)]), io:format(user, "lookup ...~n", []), {T2, PubsTime} = ?T(begin lists:foreach(fun(Pid) -> Pid ! start_lookup end, PubsPids), collect_results(PubsPids, lookup_time) end), io:format(user, "LookupTotalTime: ~s~n", [ns(T2)]), io:format(user, "LookupTimeAverage: ~s~n", [ns(PubsTime / Pubs)]), io:format(user, "LookupRps: ~p~n", [rps(Pubs * PubOps, T2)]), io:format(user, "mnesia table(s) RAM: ~p~n", [ram_bytes()]), io:format(user, "unsubscribe ...~n", []), {T3, ok} = ?T(begin lists:foreach(fun(Pid) -> Pid ! stop end, SubsPids), wait_until_empty() end), io:format(user, "TimeToUnsubscribeAll: ~s~n", [ns(T3)]). wait_until_empty() -> case emqx_trie:empty() of true -> ok; false -> timer:sleep(5), wait_until_empty() end. rps(N, NanoSec) -> N * 1_000_000 / NanoSec. ns(T) when T > 1_000_000 -> io_lib:format("~p(s)", [T / 1_000_000]); ns(T) when T > 1_000 -> io_lib:format("~p(ms)", [T / 1_000]); ns(T) -> io_lib:format("~p(ns)", [T]). ram_bytes() -> Wordsize = erlang:system_info(wordsize), mnesia:table_info(emqx_trie, memory) * Wordsize + case lists:member(emqx_trie_node, ets:all()) of true -> before 4.3 mnesia:table_info(emqx_trie_node, memory) * Wordsize; false -> 0 end. start_callers(N, F, Settings) -> start_callers(N, F, Settings, []). start_callers(0, _F, _Settings, Acc) -> lists:reverse(Acc); start_callers(N, F, Settings, Acc) -> start_callers(N - 1, F, Settings, [F(Settings#{id => N}) | Acc]). collect_results(Pids, Tag) -> collect_results(Pids, Tag, 0). collect_results([], _Tag, R) -> R; collect_results([Pid | Pids], Tag, R) -> receive {Pid, Tag, N} -> collect_results(Pids, Tag, N + R) end. start_subscriber(#{id := Id, sub_ops := N, sub_ptn := SubPtn}) -> Parent = self(), proc_lib:spawn_link( fun() -> SubTopics = make_topics(SubPtn, Id, N), Parent ! {self(), subscriber_ready, 0}, receive start_subscribe -> ok end, {Ts, _} = ?T(subscribe(SubTopics)), _ = erlang:send(Parent, {self(), subscribe_time, Ts/ N}), %% subscribers should not exit before publish test is done receive stop -> ok end end). start_publisher(#{id := Id, pub_ops := N, pub_ptn := PubPtn, subscribers := Subs}) -> Parent = self(), proc_lib:spawn_link( fun() -> L = lists:seq(1, N), [Topic] = make_topics(PubPtn, (Id rem Subs) + 1, 1), receive start_lookup -> ok end, {Tm, ok} = ?T(lists:foreach(fun(_) -> match(Topic) end, L)), _ = erlang:send(Parent, {self(), lookup_time, Tm / N}), ok end). match(Topic) -> [_] = emqx_router:match_routes(Topic). subscribe([]) -> ok; subscribe([Topic | Rest]) -> ok = emqx_broker:subscribe(Topic), subscribe(Rest). make_topics(Ptn0, Id, Limit) -> Ptn = emqx_topic:words(Ptn0), F = fun(N) -> render(Id, N, Ptn) end, lists:map(F, lists:seq(1, Limit)). render(ID, N, Ptn) -> render(ID, N, Ptn, []). render(_ID, _N, [], Acc) -> emqx_topic:join(lists:reverse(Acc)); render(ID, N, [<<"{{id}}">> | T], Acc) -> render(ID, N, T, [integer_to_binary(ID) | Acc]); render(ID, N, [<<"{{num}}">> | T], Acc) -> render(ID, N, T, [integer_to_binary(N) | Acc]); render(ID, N, [H | T], Acc) -> render(ID, N, T, [H | Acc]). -endif.
null
https://raw.githubusercontent.com/dgiot/dgiot/c601555e45f38d02aafc308b18a9e28c543b6f2c/src/emqx_broker_bench.erl
erlang
-------------------------------------------------------------------- you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -------------------------------------------------------------------- setting fields: - subscribers: spawn this number of subscriber workers - publishers: spawn this number of publisher workers - sub_ops: the number of subscribes (route insert) each subscriber runs - pub_ops: the number of publish (route lookups) each publisher runs - sub_ptn: subscribe topic pattern like a/+/b/+/c/# or a/+/{{id}}/{{num}}/# to generate pattern with {{id}} replaced by worker id and {{num}} replaced by topic number. - pub_ptn: topic pattern used to benchmark publish (match) performance e.g. a/x/{{id}}/{{num}}/foo/bar subscribers should not exit before publish test is done
Copyright ( c ) 2021 - 2022 EMQ Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(emqx_broker_bench). -ifdef(EMQX_BENCHMARK). -export([run/1, run1/0, run1/4]). -define(T(Expr), timer:tc(fun() -> Expr end)). run1() -> run1(80, 1000, 80, 10000). run1(Subs, SubOps, Pubs, PubOps) -> run(#{subscribers => Subs, publishers => Pubs, sub_ops => SubOps, pub_ops => PubOps, sub_ptn => <<"device/{{id}}/+/{{num}}/#">>, pub_ptn => <<"device/{{id}}/foo/{{num}}/bar/1/2/3/4/5">> }). run(#{subscribers := Subs, publishers := Pubs, sub_ops := SubOps, pub_ops := PubOps } = Settings) -> SubsPids = start_callers(Subs, fun start_subscriber/1, Settings), PubsPids = start_callers(Pubs, fun start_publisher/1, Settings), _ = collect_results(SubsPids, subscriber_ready), io:format(user, "subscribe ...~n", []), {T1, SubsTime} = ?T(begin lists:foreach(fun(Pid) -> Pid ! start_subscribe end, SubsPids), collect_results(SubsPids, subscribe_time) end), io:format(user, "InsertTotalTime: ~s~n", [ns(T1)]), io:format(user, "InsertTimeAverage: ~s~n", [ns(SubsTime / Subs)]), io:format(user, "InsertRps: ~p~n", [rps(Subs * SubOps, T1)]), io:format(user, "lookup ...~n", []), {T2, PubsTime} = ?T(begin lists:foreach(fun(Pid) -> Pid ! start_lookup end, PubsPids), collect_results(PubsPids, lookup_time) end), io:format(user, "LookupTotalTime: ~s~n", [ns(T2)]), io:format(user, "LookupTimeAverage: ~s~n", [ns(PubsTime / Pubs)]), io:format(user, "LookupRps: ~p~n", [rps(Pubs * PubOps, T2)]), io:format(user, "mnesia table(s) RAM: ~p~n", [ram_bytes()]), io:format(user, "unsubscribe ...~n", []), {T3, ok} = ?T(begin lists:foreach(fun(Pid) -> Pid ! stop end, SubsPids), wait_until_empty() end), io:format(user, "TimeToUnsubscribeAll: ~s~n", [ns(T3)]). wait_until_empty() -> case emqx_trie:empty() of true -> ok; false -> timer:sleep(5), wait_until_empty() end. rps(N, NanoSec) -> N * 1_000_000 / NanoSec. ns(T) when T > 1_000_000 -> io_lib:format("~p(s)", [T / 1_000_000]); ns(T) when T > 1_000 -> io_lib:format("~p(ms)", [T / 1_000]); ns(T) -> io_lib:format("~p(ns)", [T]). ram_bytes() -> Wordsize = erlang:system_info(wordsize), mnesia:table_info(emqx_trie, memory) * Wordsize + case lists:member(emqx_trie_node, ets:all()) of true -> before 4.3 mnesia:table_info(emqx_trie_node, memory) * Wordsize; false -> 0 end. start_callers(N, F, Settings) -> start_callers(N, F, Settings, []). start_callers(0, _F, _Settings, Acc) -> lists:reverse(Acc); start_callers(N, F, Settings, Acc) -> start_callers(N - 1, F, Settings, [F(Settings#{id => N}) | Acc]). collect_results(Pids, Tag) -> collect_results(Pids, Tag, 0). collect_results([], _Tag, R) -> R; collect_results([Pid | Pids], Tag, R) -> receive {Pid, Tag, N} -> collect_results(Pids, Tag, N + R) end. start_subscriber(#{id := Id, sub_ops := N, sub_ptn := SubPtn}) -> Parent = self(), proc_lib:spawn_link( fun() -> SubTopics = make_topics(SubPtn, Id, N), Parent ! {self(), subscriber_ready, 0}, receive start_subscribe -> ok end, {Ts, _} = ?T(subscribe(SubTopics)), _ = erlang:send(Parent, {self(), subscribe_time, Ts/ N}), receive stop -> ok end end). start_publisher(#{id := Id, pub_ops := N, pub_ptn := PubPtn, subscribers := Subs}) -> Parent = self(), proc_lib:spawn_link( fun() -> L = lists:seq(1, N), [Topic] = make_topics(PubPtn, (Id rem Subs) + 1, 1), receive start_lookup -> ok end, {Tm, ok} = ?T(lists:foreach(fun(_) -> match(Topic) end, L)), _ = erlang:send(Parent, {self(), lookup_time, Tm / N}), ok end). match(Topic) -> [_] = emqx_router:match_routes(Topic). subscribe([]) -> ok; subscribe([Topic | Rest]) -> ok = emqx_broker:subscribe(Topic), subscribe(Rest). make_topics(Ptn0, Id, Limit) -> Ptn = emqx_topic:words(Ptn0), F = fun(N) -> render(Id, N, Ptn) end, lists:map(F, lists:seq(1, Limit)). render(ID, N, Ptn) -> render(ID, N, Ptn, []). render(_ID, _N, [], Acc) -> emqx_topic:join(lists:reverse(Acc)); render(ID, N, [<<"{{id}}">> | T], Acc) -> render(ID, N, T, [integer_to_binary(ID) | Acc]); render(ID, N, [<<"{{num}}">> | T], Acc) -> render(ID, N, T, [integer_to_binary(N) | Acc]); render(ID, N, [H | T], Acc) -> render(ID, N, T, [H | Acc]). -endif.
1ce5088e381d3f4b2978f165d3f5159ccedbbcf8c54845589d3ec0eaa7e37351
fadbadml-dev/FADBADml
exampleBADFAD1.ml
(**************************************************************************) (* *) (* FADBADml *) (* *) OCaml port by and Based on FADBAD++ , written by and (* *) Copyright 2019 - 2020 (* *) This file is distributed under the terms of the CeCILL - C license . (* *) (**************************************************************************) module Op = Fadbad.OpFloat module F = Fadbad.F(Op) module BF = Fadbad.B(F) let func x y = let open BF in let z = sqrt x in (y * z) + (sin z) let () = let x = BF.make 1. in let y = BF.make 2. in let () = F.diff (BF.value x) 0 2 in let () = F.diff (BF.value y) 1 2 in let f = func x y in let () = BF.diff f 0 1 in let () = BF.compute f in let f_val = BF.get f in let dfdx = BF.d x 0 in let dfdy = BF.d y 0 in let dfdxdx = F.d (BF.deriv x 0) 0 in let dfdxdy = F.d (BF.deriv x 0) 1 in let dfdydx = F.d (BF.deriv y 0) 0 in let dfdydy = F.d (BF.deriv y 0) 1 in let () = print_endline ("x = 1") in let () = print_endline ("y = 2") in let () = print_endline ("f(x,y) = y * (sqrt x) + (sin (sqrt x))") in let () = print_newline () in let () = print_endline ("f(x,y) = " ^ (string_of_float f_val)) in let () = print_endline ("df/dx(x,y) = " ^ (string_of_float dfdx)) in let () = print_endline ("df/dy(x,y) = " ^ (string_of_float dfdy)) in let () = print_endline ("df/dxdx(x,y) = " ^ (string_of_float dfdxdx)) in let () = print_endline ("df/dxdy(x,y) = " ^ (string_of_float dfdxdy)) in let () = print_endline ("df/dydx(x,y) = " ^ (string_of_float dfdydx)) in let () = print_endline ("df/dydy(x,y) = " ^ (string_of_float dfdydy)) in ()
null
https://raw.githubusercontent.com/fadbadml-dev/FADBADml/bd5668433b8ad297aa70e91a032953d55923b533/example/exampleBADFAD1.ml
ocaml
************************************************************************ FADBADml ************************************************************************
OCaml port by and Based on FADBAD++ , written by and Copyright 2019 - 2020 This file is distributed under the terms of the CeCILL - C license . module Op = Fadbad.OpFloat module F = Fadbad.F(Op) module BF = Fadbad.B(F) let func x y = let open BF in let z = sqrt x in (y * z) + (sin z) let () = let x = BF.make 1. in let y = BF.make 2. in let () = F.diff (BF.value x) 0 2 in let () = F.diff (BF.value y) 1 2 in let f = func x y in let () = BF.diff f 0 1 in let () = BF.compute f in let f_val = BF.get f in let dfdx = BF.d x 0 in let dfdy = BF.d y 0 in let dfdxdx = F.d (BF.deriv x 0) 0 in let dfdxdy = F.d (BF.deriv x 0) 1 in let dfdydx = F.d (BF.deriv y 0) 0 in let dfdydy = F.d (BF.deriv y 0) 1 in let () = print_endline ("x = 1") in let () = print_endline ("y = 2") in let () = print_endline ("f(x,y) = y * (sqrt x) + (sin (sqrt x))") in let () = print_newline () in let () = print_endline ("f(x,y) = " ^ (string_of_float f_val)) in let () = print_endline ("df/dx(x,y) = " ^ (string_of_float dfdx)) in let () = print_endline ("df/dy(x,y) = " ^ (string_of_float dfdy)) in let () = print_endline ("df/dxdx(x,y) = " ^ (string_of_float dfdxdx)) in let () = print_endline ("df/dxdy(x,y) = " ^ (string_of_float dfdxdy)) in let () = print_endline ("df/dydx(x,y) = " ^ (string_of_float dfdydx)) in let () = print_endline ("df/dydy(x,y) = " ^ (string_of_float dfdydy)) in ()
3b9bbbb1cc7803065a32abff4e2165e6eaf37d5b213227621b232a31e1e35969
quicklisp/quicklisp-client
network.lisp
;;; ;;; Low-level networking implementations ;;; (in-package #:ql-network) (definterface host-address (host) (:implementation t host) (:implementation sbcl (ql-sbcl:host-ent-address (ql-sbcl:get-host-by-name host)))) (definterface open-connection (host port) (:documentation "Open and return a network connection to HOST on the given PORT.") (:implementation t (declare (ignore host port)) (error "Sorry, quicklisp in implementation ~S is not supported yet." (lisp-implementation-type))) (:implementation allegro (ql-allegro:make-socket :remote-host host :remote-port port)) (:implementation abcl (let ((socket (ql-abcl:make-socket host port))) (ql-abcl:get-socket-stream socket :element-type '(unsigned-byte 8)))) (:implementation ccl (ql-ccl:make-socket :remote-host host :remote-port port)) (:implementation clasp (let* ((endpoint (ql-clasp:host-ent-address (ql-clasp:get-host-by-name host))) (socket (make-instance 'ql-clasp:inet-socket :protocol :tcp :type :stream))) (ql-clasp:socket-connect socket endpoint port) (ql-clasp:socket-make-stream socket :element-type '(unsigned-byte 8) :input t :output t :buffering :full))) (:implementation clisp (ql-clisp:socket-connect port host :element-type '(unsigned-byte 8))) (:implementation cmucl (let ((fd (ql-cmucl:connect-to-inet-socket host port))) (ql-cmucl:make-fd-stream fd :element-type '(unsigned-byte 8) :binary-stream-p t :input t :output t))) (:implementation scl (let ((fd (ql-scl:connect-to-inet-socket host port))) (ql-scl:make-fd-stream fd :element-type '(unsigned-byte 8) :input t :output t))) (:implementation ecl (let* ((endpoint (ql-ecl:host-ent-address (ql-ecl:get-host-by-name host))) (socket (make-instance 'ql-ecl:inet-socket :protocol :tcp :type :stream))) (ql-ecl:socket-connect socket endpoint port) (ql-ecl:socket-make-stream socket :element-type '(unsigned-byte 8) :input t :output t :buffering :full))) (:implementation mezzano (ql-mezzano:tcp-stream-connect host port :element-type '(unsigned-byte 8))) (:implementation mkcl (let* ((endpoint (ql-mkcl:host-ent-address (ql-mkcl:get-host-by-name host))) (socket (make-instance 'ql-mkcl:inet-socket :protocol :tcp :type :stream))) (ql-mkcl:socket-connect socket endpoint port) (ql-mkcl:socket-make-stream socket :element-type '(unsigned-byte 8) :input t :output t :buffering :full))) (:implementation lispworks (ql-lispworks:open-tcp-stream host port :direction :io :errorp t :read-timeout nil :element-type '(unsigned-byte 8) :timeout 5)) (:implementation sbcl (let* ((endpoint (ql-sbcl:host-ent-address (ql-sbcl:get-host-by-name host))) (socket (make-instance 'ql-sbcl:inet-socket :protocol :tcp :type :stream))) (ql-sbcl:socket-connect socket endpoint port) (ql-sbcl:socket-make-stream socket :element-type '(unsigned-byte 8) :input t :output t :buffering :full))) (:implementation genera (ql-genera:open-tcp-stream host port nil :direction :io :characters nil))) (definterface read-octets (buffer connection) (:documentation "Read from CONNECTION into BUFFER. Returns the number of octets read.") (:implementation t (read-sequence buffer connection)) (:implementation allegro (ql-allegro:read-vector buffer connection)) (:implementation clisp (ql-clisp:read-byte-sequence buffer connection :no-hang nil :interactive t))) (definterface write-octets (buffer connection) (:documentation "Write the contents of BUFFER to CONNECTION.") (:implementation t (write-sequence buffer connection) (finish-output connection))) (definterface close-connection (connection) (:implementation t (ignore-errors (close connection)))) (definterface call-with-connection (host port fun) (:documentation "Establish a network connection to HOST on PORT and call FUN with that connection as the only argument. Unconditionally closes the connection afterwareds via CLOSE-CONNECTION in an unwind-protect. See also WITH-CONNECTION.") (:implementation t (let ((connection nil)) (unwind-protect (progn (setf connection (open-connection host port)) (funcall fun connection)) (when connection (close-connection connection)))))) (defmacro with-connection ((connection host port) &body body) `(call-with-connection ,host ,port (lambda (,connection) ,@body)))
null
https://raw.githubusercontent.com/quicklisp/quicklisp-client/e5c4345296387b630c0002ecf5e6b37ac13beb32/quicklisp/network.lisp
lisp
Low-level networking implementations
(in-package #:ql-network) (definterface host-address (host) (:implementation t host) (:implementation sbcl (ql-sbcl:host-ent-address (ql-sbcl:get-host-by-name host)))) (definterface open-connection (host port) (:documentation "Open and return a network connection to HOST on the given PORT.") (:implementation t (declare (ignore host port)) (error "Sorry, quicklisp in implementation ~S is not supported yet." (lisp-implementation-type))) (:implementation allegro (ql-allegro:make-socket :remote-host host :remote-port port)) (:implementation abcl (let ((socket (ql-abcl:make-socket host port))) (ql-abcl:get-socket-stream socket :element-type '(unsigned-byte 8)))) (:implementation ccl (ql-ccl:make-socket :remote-host host :remote-port port)) (:implementation clasp (let* ((endpoint (ql-clasp:host-ent-address (ql-clasp:get-host-by-name host))) (socket (make-instance 'ql-clasp:inet-socket :protocol :tcp :type :stream))) (ql-clasp:socket-connect socket endpoint port) (ql-clasp:socket-make-stream socket :element-type '(unsigned-byte 8) :input t :output t :buffering :full))) (:implementation clisp (ql-clisp:socket-connect port host :element-type '(unsigned-byte 8))) (:implementation cmucl (let ((fd (ql-cmucl:connect-to-inet-socket host port))) (ql-cmucl:make-fd-stream fd :element-type '(unsigned-byte 8) :binary-stream-p t :input t :output t))) (:implementation scl (let ((fd (ql-scl:connect-to-inet-socket host port))) (ql-scl:make-fd-stream fd :element-type '(unsigned-byte 8) :input t :output t))) (:implementation ecl (let* ((endpoint (ql-ecl:host-ent-address (ql-ecl:get-host-by-name host))) (socket (make-instance 'ql-ecl:inet-socket :protocol :tcp :type :stream))) (ql-ecl:socket-connect socket endpoint port) (ql-ecl:socket-make-stream socket :element-type '(unsigned-byte 8) :input t :output t :buffering :full))) (:implementation mezzano (ql-mezzano:tcp-stream-connect host port :element-type '(unsigned-byte 8))) (:implementation mkcl (let* ((endpoint (ql-mkcl:host-ent-address (ql-mkcl:get-host-by-name host))) (socket (make-instance 'ql-mkcl:inet-socket :protocol :tcp :type :stream))) (ql-mkcl:socket-connect socket endpoint port) (ql-mkcl:socket-make-stream socket :element-type '(unsigned-byte 8) :input t :output t :buffering :full))) (:implementation lispworks (ql-lispworks:open-tcp-stream host port :direction :io :errorp t :read-timeout nil :element-type '(unsigned-byte 8) :timeout 5)) (:implementation sbcl (let* ((endpoint (ql-sbcl:host-ent-address (ql-sbcl:get-host-by-name host))) (socket (make-instance 'ql-sbcl:inet-socket :protocol :tcp :type :stream))) (ql-sbcl:socket-connect socket endpoint port) (ql-sbcl:socket-make-stream socket :element-type '(unsigned-byte 8) :input t :output t :buffering :full))) (:implementation genera (ql-genera:open-tcp-stream host port nil :direction :io :characters nil))) (definterface read-octets (buffer connection) (:documentation "Read from CONNECTION into BUFFER. Returns the number of octets read.") (:implementation t (read-sequence buffer connection)) (:implementation allegro (ql-allegro:read-vector buffer connection)) (:implementation clisp (ql-clisp:read-byte-sequence buffer connection :no-hang nil :interactive t))) (definterface write-octets (buffer connection) (:documentation "Write the contents of BUFFER to CONNECTION.") (:implementation t (write-sequence buffer connection) (finish-output connection))) (definterface close-connection (connection) (:implementation t (ignore-errors (close connection)))) (definterface call-with-connection (host port fun) (:documentation "Establish a network connection to HOST on PORT and call FUN with that connection as the only argument. Unconditionally closes the connection afterwareds via CLOSE-CONNECTION in an unwind-protect. See also WITH-CONNECTION.") (:implementation t (let ((connection nil)) (unwind-protect (progn (setf connection (open-connection host port)) (funcall fun connection)) (when connection (close-connection connection)))))) (defmacro with-connection ((connection host port) &body body) `(call-with-connection ,host ,port (lambda (,connection) ,@body)))
d1bbdd6f499947ac67aabdd95ada2aa09aafc9822d58ef6e58a7eb42acc99492
pallet/pallet-aws
ami_test.clj
(ns pallet.compute.ec2.ami-test (:require [clojure.test :refer :all] [pallet.compute.ec2.ami :refer [parse]])) (deftest parse-test (is (= {:os-family :amzn-linux :os-version "2013.09.0" :user {:username "ec2-user"}} (parse {:owner-id "137112412989" :name "amzn-ami-pv-2013.09.0.x86_64-ebs" :description "Amazon Linux AMI x86_64 PV EBS"})))) (deftest os-parser-test (testing "amzn linux" (is (= {:os-family :amzn-linux :os-version "0.9.7-beta" :user {:username "ec2-user"}} (parse {:owner-id "137112412989" :description "Amazon Linux AMI.*" :name "137112412989/amzn-ami-0.9.7-beta.i386-ebs"}))) (is (= {:os-family :amzn-linux :os-version "0.9.7-beta" :user {:username "ec2-user"}} (parse {:owner-id "137112412989" :description "Amazon Linux AMI.*" :name "137112412989/amzn-ami-0.9.7-beta.x86_64-ebs"}))) (is (= {:os-family :amzn-linux :os-version "0.9.7-beta" :user {:username "ec2-user"}} (parse {:owner-id "137112412989" :description "Amazon Linux AMI.*" :name "amzn-ami-us-east-1/amzn-ami-0.9.7-beta.x86_64.manifest.xml"}))) (is (= {:os-family :amzn-linux :os-version "0.9.7-beta" :user {:username "ec2-user"}} (parse {:owner-id "137112412989" :description "Amazon Linux AMI.*" :name "amzn-ami-us-east-1/amzn-ami-0.9.7-beta.i386.manifest.xml"})))) (testing "amazon centos" (is (= {:os-family :centos :os-version "5.4"} (parse {:owner-id "137112412989" :description "Amazon Centos" :name "amazon/EC2 CentOS 5.4 HVM AMI"})))) (testing "canonical" (is (= {:os-family :ubuntu :os-version "12.04" :user {:username "ubuntu"}} (parse {:owner-id "099720109477" :name "ubuntu/images-milestone/ubuntu-precise-12.04-beta1-i386-server-20120229.1"})))) (testing "rightscale" (is (= {:os-family :centos :os-version "5.4"} (parse {:owner-id "411009282317" :name "rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml"})))) (testing "rightimage" (is (= {:os-family :ubuntu :os-version "9.10"} (parse {:owner-id "411009282317" :name "411009282317/RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha"}))) (is (= {:os-family :windows :os-version "2008"} (parse {:owner-id "411009282317" :name "411009282317/RightImage_Windows_2008_x64_v5.5.5"})))))
null
https://raw.githubusercontent.com/pallet/pallet-aws/6f650ca93c853f8a574ad36875f4d164e46e8e8d/test/pallet/compute/ec2/ami_test.clj
clojure
(ns pallet.compute.ec2.ami-test (:require [clojure.test :refer :all] [pallet.compute.ec2.ami :refer [parse]])) (deftest parse-test (is (= {:os-family :amzn-linux :os-version "2013.09.0" :user {:username "ec2-user"}} (parse {:owner-id "137112412989" :name "amzn-ami-pv-2013.09.0.x86_64-ebs" :description "Amazon Linux AMI x86_64 PV EBS"})))) (deftest os-parser-test (testing "amzn linux" (is (= {:os-family :amzn-linux :os-version "0.9.7-beta" :user {:username "ec2-user"}} (parse {:owner-id "137112412989" :description "Amazon Linux AMI.*" :name "137112412989/amzn-ami-0.9.7-beta.i386-ebs"}))) (is (= {:os-family :amzn-linux :os-version "0.9.7-beta" :user {:username "ec2-user"}} (parse {:owner-id "137112412989" :description "Amazon Linux AMI.*" :name "137112412989/amzn-ami-0.9.7-beta.x86_64-ebs"}))) (is (= {:os-family :amzn-linux :os-version "0.9.7-beta" :user {:username "ec2-user"}} (parse {:owner-id "137112412989" :description "Amazon Linux AMI.*" :name "amzn-ami-us-east-1/amzn-ami-0.9.7-beta.x86_64.manifest.xml"}))) (is (= {:os-family :amzn-linux :os-version "0.9.7-beta" :user {:username "ec2-user"}} (parse {:owner-id "137112412989" :description "Amazon Linux AMI.*" :name "amzn-ami-us-east-1/amzn-ami-0.9.7-beta.i386.manifest.xml"})))) (testing "amazon centos" (is (= {:os-family :centos :os-version "5.4"} (parse {:owner-id "137112412989" :description "Amazon Centos" :name "amazon/EC2 CentOS 5.4 HVM AMI"})))) (testing "canonical" (is (= {:os-family :ubuntu :os-version "12.04" :user {:username "ubuntu"}} (parse {:owner-id "099720109477" :name "ubuntu/images-milestone/ubuntu-precise-12.04-beta1-i386-server-20120229.1"})))) (testing "rightscale" (is (= {:os-family :centos :os-version "5.4"} (parse {:owner-id "411009282317" :name "rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml"})))) (testing "rightimage" (is (= {:os-family :ubuntu :os-version "9.10"} (parse {:owner-id "411009282317" :name "411009282317/RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha"}))) (is (= {:os-family :windows :os-version "2008"} (parse {:owner-id "411009282317" :name "411009282317/RightImage_Windows_2008_x64_v5.5.5"})))))
50ff888251a3b352b85d12fd0cfc49c314e0b0fb26e4af60ac68d61da5cca5b3
sbcl/sbcl
simd-fndb.lisp
This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the ;;;; public domain. The software is in the public domain and is ;;;; provided with absolutely no warranty. See the COPYING and CREDITS ;;;; files for more information. (in-package "SB-VM") (deftype 128-element () #+x86-64 '(simd-pack (unsigned-byte 32)) #+arm64 'complex-double-float) (defknown vector-ref-128 (t index) 128-element (flushable)) (defknown (setf vector-ref-128) (128-element t index) (values) ()) (defknown (simd-nreverse8 simd-nreverse32) (vector (simple-array * (*)) fixnum fixnum) vector (sb-c::fixed-args)) (defknown (simd-reverse8 simd-reverse32) ((simple-array * (*)) (simple-array * (*)) fixnum fixnum) (simple-array * (*)) (sb-c::fixed-args)) (defknown (simd-cmp-8-8 simd-cmp-8-32 simd-cmp-32-32 simd-base-string-equal simd-base-character-string-equal) ((simple-array * (*)) (simple-array * (*)) fixnum) (boolean) (sb-c::no-verify-arg-count))
null
https://raw.githubusercontent.com/sbcl/sbcl/64245708810072990d9f054820e85bd8c618257f/src/code/simd-fndb.lisp
lisp
more information. public domain. The software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information.
This software is part of the SBCL system . See the README file for This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the (in-package "SB-VM") (deftype 128-element () #+x86-64 '(simd-pack (unsigned-byte 32)) #+arm64 'complex-double-float) (defknown vector-ref-128 (t index) 128-element (flushable)) (defknown (setf vector-ref-128) (128-element t index) (values) ()) (defknown (simd-nreverse8 simd-nreverse32) (vector (simple-array * (*)) fixnum fixnum) vector (sb-c::fixed-args)) (defknown (simd-reverse8 simd-reverse32) ((simple-array * (*)) (simple-array * (*)) fixnum fixnum) (simple-array * (*)) (sb-c::fixed-args)) (defknown (simd-cmp-8-8 simd-cmp-8-32 simd-cmp-32-32 simd-base-string-equal simd-base-character-string-equal) ((simple-array * (*)) (simple-array * (*)) fixnum) (boolean) (sb-c::no-verify-arg-count))
09ab4c5919686c52a527c5afbad31acf9d9ebd8d1d8df4ad6324745324bf6c23
kframework/semantic-approaches
State.hs
# LANGUAGE NamedFieldPuns # module Language.ImpPP.State {- ( ImpPPEnv(..) , initialEnv , lookupEnv , insertEnv , pushEnv , popEnv , writeOut ) -} where TODO : lens tomfoolery , but does that make this ? import Prelude hiding ( lookup ) import Data.Map.Strict ( Map, lookup, insert, empty, fromList, union) import Language.ImpPP.Syntax.Abstract ( Id ) data ImpPPEnv = ImpPPEnv { varEnv :: Map Id Integer , envStack :: [Map Id Integer] , input :: [Integer] , output :: [Integer] } deriving( Eq ) instance Show ImpPPEnv where show ImpPPEnv{varEnv, envStack, input, output} = "< state: "++show varEnv++ ", input: "++show input++ ", output: "++show output++" >" initialEnv :: ImpPPEnv initialEnv = ImpPPEnv empty [] [] [] initialEnvWithInput :: [Integer] -> ImpPPEnv initialEnvWithInput input = ImpPPEnv empty [] input [] lookupEnv :: Id -> ImpPPEnv -> Maybe Integer lookupEnv var = lookup var . varEnv insertEnv :: Id -> Integer -> ImpPPEnv -> ImpPPEnv insertEnv var val env = env { varEnv = insert var val $ varEnv env } pushEnv :: ImpPPEnv -> ImpPPEnv pushEnv env = env { envStack = varEnv env : envStack env } zeroEnv :: [Id] -> ImpPPEnv -> ImpPPEnv zeroEnv ids env = env { varEnv = union newEnv (varEnv env) } where newEnv = fromList $ zip ids [0,0..] popEnv :: ImpPPEnv -> ImpPPEnv popEnv env = env { varEnv = vars, envStack = envs } where (vars:envs) = envStack env -- non-total should be unreachable updateIn :: [Integer] -> ImpPPEnv -> ImpPPEnv updateIn ins env = env {input = ins} writeOut :: Integer -> ImpPPEnv -> ImpPPEnv writeOut n env = env { output = n : output env }
null
https://raw.githubusercontent.com/kframework/semantic-approaches/6f64eac09e005fe4eae7141e3c0e0f5711da0647/haskell/semantic-styles/src/Language/ImpPP/State.hs
haskell
( ImpPPEnv(..) , initialEnv , lookupEnv , insertEnv , pushEnv , popEnv , writeOut ) non-total should be unreachable
# LANGUAGE NamedFieldPuns # module Language.ImpPP.State where TODO : lens tomfoolery , but does that make this ? import Prelude hiding ( lookup ) import Data.Map.Strict ( Map, lookup, insert, empty, fromList, union) import Language.ImpPP.Syntax.Abstract ( Id ) data ImpPPEnv = ImpPPEnv { varEnv :: Map Id Integer , envStack :: [Map Id Integer] , input :: [Integer] , output :: [Integer] } deriving( Eq ) instance Show ImpPPEnv where show ImpPPEnv{varEnv, envStack, input, output} = "< state: "++show varEnv++ ", input: "++show input++ ", output: "++show output++" >" initialEnv :: ImpPPEnv initialEnv = ImpPPEnv empty [] [] [] initialEnvWithInput :: [Integer] -> ImpPPEnv initialEnvWithInput input = ImpPPEnv empty [] input [] lookupEnv :: Id -> ImpPPEnv -> Maybe Integer lookupEnv var = lookup var . varEnv insertEnv :: Id -> Integer -> ImpPPEnv -> ImpPPEnv insertEnv var val env = env { varEnv = insert var val $ varEnv env } pushEnv :: ImpPPEnv -> ImpPPEnv pushEnv env = env { envStack = varEnv env : envStack env } zeroEnv :: [Id] -> ImpPPEnv -> ImpPPEnv zeroEnv ids env = env { varEnv = union newEnv (varEnv env) } where newEnv = fromList $ zip ids [0,0..] popEnv :: ImpPPEnv -> ImpPPEnv popEnv env = env { varEnv = vars, envStack = envs } updateIn :: [Integer] -> ImpPPEnv -> ImpPPEnv updateIn ins env = env {input = ins} writeOut :: Integer -> ImpPPEnv -> ImpPPEnv writeOut n env = env { output = n : output env }
554a17f55ef71975003f9b1f413e90dea8af452c5549dee5d7fb3e78c52847b4
haskell/cabal
Lens.hs
module Distribution.Types.ForeignLib.Lens ( ForeignLib, module Distribution.Types.ForeignLib.Lens, ) where import Distribution.Compat.Lens import Distribution.Compat.Prelude import Prelude () import Distribution.Types.BuildInfo (BuildInfo) import Distribution.Types.ForeignLib (ForeignLib, LibVersionInfo) import Distribution.Types.ForeignLibOption (ForeignLibOption) import Distribution.Types.ForeignLibType (ForeignLibType) import Distribution.Types.UnqualComponentName (UnqualComponentName) import Distribution.Version (Version) import qualified Distribution.Types.ForeignLib as T foreignLibName :: Lens' ForeignLib UnqualComponentName foreignLibName f s = fmap (\x -> s { T.foreignLibName = x }) (f (T.foreignLibName s)) # INLINE foreignLibName # foreignLibType :: Lens' ForeignLib ForeignLibType foreignLibType f s = fmap (\x -> s { T.foreignLibType = x }) (f (T.foreignLibType s)) # INLINE foreignLibType # foreignLibOptions :: Lens' ForeignLib [ForeignLibOption] foreignLibOptions f s = fmap (\x -> s { T.foreignLibOptions = x }) (f (T.foreignLibOptions s)) # INLINE foreignLibOptions # foreignLibBuildInfo :: Lens' ForeignLib BuildInfo foreignLibBuildInfo f s = fmap (\x -> s { T.foreignLibBuildInfo = x }) (f (T.foreignLibBuildInfo s)) # INLINE foreignLibBuildInfo # foreignLibVersionInfo :: Lens' ForeignLib (Maybe LibVersionInfo) foreignLibVersionInfo f s = fmap (\x -> s { T.foreignLibVersionInfo = x }) (f (T.foreignLibVersionInfo s)) # INLINE foreignLibVersionInfo # foreignLibVersionLinux :: Lens' ForeignLib (Maybe Version) foreignLibVersionLinux f s = fmap (\x -> s { T.foreignLibVersionLinux = x }) (f (T.foreignLibVersionLinux s)) # INLINE foreignLibVersionLinux # foreignLibModDefFile :: Lens' ForeignLib [FilePath] foreignLibModDefFile f s = fmap (\x -> s { T.foreignLibModDefFile = x }) (f (T.foreignLibModDefFile s)) # INLINE foreignLibModDefFile #
null
https://raw.githubusercontent.com/haskell/cabal/0abbe37187f708e0a5daac8d388167f72ca0db7e/Cabal-syntax/src/Distribution/Types/ForeignLib/Lens.hs
haskell
module Distribution.Types.ForeignLib.Lens ( ForeignLib, module Distribution.Types.ForeignLib.Lens, ) where import Distribution.Compat.Lens import Distribution.Compat.Prelude import Prelude () import Distribution.Types.BuildInfo (BuildInfo) import Distribution.Types.ForeignLib (ForeignLib, LibVersionInfo) import Distribution.Types.ForeignLibOption (ForeignLibOption) import Distribution.Types.ForeignLibType (ForeignLibType) import Distribution.Types.UnqualComponentName (UnqualComponentName) import Distribution.Version (Version) import qualified Distribution.Types.ForeignLib as T foreignLibName :: Lens' ForeignLib UnqualComponentName foreignLibName f s = fmap (\x -> s { T.foreignLibName = x }) (f (T.foreignLibName s)) # INLINE foreignLibName # foreignLibType :: Lens' ForeignLib ForeignLibType foreignLibType f s = fmap (\x -> s { T.foreignLibType = x }) (f (T.foreignLibType s)) # INLINE foreignLibType # foreignLibOptions :: Lens' ForeignLib [ForeignLibOption] foreignLibOptions f s = fmap (\x -> s { T.foreignLibOptions = x }) (f (T.foreignLibOptions s)) # INLINE foreignLibOptions # foreignLibBuildInfo :: Lens' ForeignLib BuildInfo foreignLibBuildInfo f s = fmap (\x -> s { T.foreignLibBuildInfo = x }) (f (T.foreignLibBuildInfo s)) # INLINE foreignLibBuildInfo # foreignLibVersionInfo :: Lens' ForeignLib (Maybe LibVersionInfo) foreignLibVersionInfo f s = fmap (\x -> s { T.foreignLibVersionInfo = x }) (f (T.foreignLibVersionInfo s)) # INLINE foreignLibVersionInfo # foreignLibVersionLinux :: Lens' ForeignLib (Maybe Version) foreignLibVersionLinux f s = fmap (\x -> s { T.foreignLibVersionLinux = x }) (f (T.foreignLibVersionLinux s)) # INLINE foreignLibVersionLinux # foreignLibModDefFile :: Lens' ForeignLib [FilePath] foreignLibModDefFile f s = fmap (\x -> s { T.foreignLibModDefFile = x }) (f (T.foreignLibModDefFile s)) # INLINE foreignLibModDefFile #
9ff1b8ebd59f31e1b818e3a2999422f8d8cfab8cfcc4d5d915f90fbd2b7339ea
rd--/hsc3
hpf.help.hs
-- hpf let f = fSinOsc kr (xLine kr 0.7 300 20 RemoveSynth) 0 * 3600 + 4000 in hpf (saw ar 200 * 0.1) f hpf ; cutoff at one hertz hpf (whiteNoiseId 'α' ar) 1 * 0.1 ---- ; drawings Sound.Sc3.Plot.FFT.plot_ugen_fft1 0.05 (hpf (whiteNoiseId 'α' ar) 12000)
null
https://raw.githubusercontent.com/rd--/hsc3/024d45b6b5166e5cd3f0142fbf65aeb6ef642d46/Help/Ugen/hpf.help.hs
haskell
hpf -- ; drawings
let f = fSinOsc kr (xLine kr 0.7 300 20 RemoveSynth) 0 * 3600 + 4000 in hpf (saw ar 200 * 0.1) f hpf ; cutoff at one hertz hpf (whiteNoiseId 'α' ar) 1 * 0.1 Sound.Sc3.Plot.FFT.plot_ugen_fft1 0.05 (hpf (whiteNoiseId 'α' ar) 12000)
a3b985854b537b3d12eac58f2b03ae8c40818df6e8f35d597381dbfe1ff0d37b
shamazmazum/easy-audio
package.lisp
(defpackage easy-audio.ape-examples (:use #:cl #:easy-audio.wav #:easy-audio.ape #:easy-audio.core) (:nicknames #:ape-examples) (:export #:ape2wav))
null
https://raw.githubusercontent.com/shamazmazum/easy-audio/4944f4ac12ffbe96f2d6bb7b116deae8203080e8/ape/examples/package.lisp
lisp
(defpackage easy-audio.ape-examples (:use #:cl #:easy-audio.wav #:easy-audio.ape #:easy-audio.core) (:nicknames #:ape-examples) (:export #:ape2wav))
d36039bdc0717ecd1d8d5dc58e561444589ed5f72960e9ce9d0c6240050193a2
atlas-engineer/nyxt
status.lisp
SPDX - FileCopyrightText : Atlas Engineer LLC SPDX - License - Identifier : BSD-3 - Clause (in-package :nyxt) (export-always 'mode-status) (defgeneric mode-status (status mode) (:method ((status status-buffer) (mode mode)) (if (glyph-mode-presentation-p status) (glyph mode) (princ-to-string mode))) (:documentation "Return a MODE `mode' string description for the STATUS `status-buffer'. Upon returning NIL, the mode is not displayed.")) (defun sort-modes-for-status (modes) "Return visible modes in MODES, with `nyxt/keyscheme-mode:keyscheme-mode' placed first." (multiple-value-bind (keyscheme-mode other-modes) (sera:partition #'nyxt/keyscheme-mode::keyscheme-mode-p (sera:filter #'visible-in-status-p modes)) (append keyscheme-mode other-modes))) (export-always 'format-status-modes) (defmethod format-status-modes ((status status-buffer)) "Render the enabled modes. Any `nyxt/keyscheme-mode:keyscheme-mode' is placed first. This leverages `mode-status' which can be specialized for individual modes." (let ((buffer (current-buffer (window status)))) (if (modable-buffer-p buffer) (let ((sorted-modes (sort-modes-for-status (modes buffer)))) (spinneret:with-html-string (when (nosave-buffer-p buffer) (:span "⚠ nosave")) (:nbutton :buffer status :text "✚" :title (str:concat "Enabled modes: " (modes-string buffer)) (nyxt:toggle-modes)) (loop for mode in sorted-modes collect (let ((mode mode)) (alex:when-let ((formatted-mode (mode-status status mode))) (if (html-string-p formatted-mode) (:raw formatted-mode) (:nbutton :buffer status :text formatted-mode :title (format nil "Describe ~a" mode) (describe-class :class (name mode))))))))) ""))) (defun modes-string (buffer) (when (modable-buffer-p buffer) (format nil "~{~a~^ ~}" (mapcar #'princ-to-string (modes buffer))))) (export-always 'format-status-buttons) (defmethod format-status-buttons ((status status-buffer)) "Render interactive buttons." (spinneret:with-html-string ;; TODO: Firefox-like additional click actions? See ;; -US/kb/mouse-shortcuts-perform-common-tasks (:nbutton :buffer status :text "←" :title "Backwards" (nyxt/history-mode:history-backwards)) (:nbutton :buffer status :text "↺" :title "Reload" (nyxt:reload-current-buffer)) (:nbutton :buffer status :text "→" :title "Forwards" (nyxt/history-mode:history-forwards) ) (:nbutton :buffer status :text "≡" :title "Execute" (nyxt:execute-command)) (:nbutton :buffer status :text "★" :title "Bookmark this page" (funcall (read-from-string "nyxt/bookmark-mode:bookmark-current-url"))))) (export-always 'format-status-load-status) (defmethod format-status-load-status ((status status-buffer)) (let ((buffer (current-buffer (window status)))) (spinneret:with-html-string (:div :class (if (and (web-buffer-p buffer) (eq (slot-value buffer 'status) :loading)) "loader" ""))))) (export-always 'format-status-url) (defmethod format-status-url ((status status-buffer)) "Formats the currently open URL for the STATUS buffer. MODIFY AT YOUR OWN RISK! The current implementation goes a great way to make the display safe, in particular to prevent IDN-spoofing by showing the Unicode domains as punicode (the Unicode aesthetic domain is shown in parentheses after the URL.)" ;; However this function changes, it should always: ;; - Prevent IDN/Unicode-spoofing. ;; - Clearly show subdomains (except maybe "trivial" ones) to prevent ;; subdomain takeover attacks. ;; - Retain a clear display of which protocol/scheme is used to discourage ;; e.g. trusting HTTP websites. (let* ((buffer (current-buffer (window status))) (content (multiple-value-bind (aesthetic safe) (render-url (url buffer)) (uiop:strcat (if safe (format nil "~a (~a)" safe aesthetic) aesthetic) (when (title buffer) (str:concat " — " (title buffer))) (when (find (url buffer) (remove buffer (buffer-list)) :test #'url-equal :key #'url) (format nil " (buffer ~a)" (id buffer))))))) (spinneret:with-html-string (:nbutton :buffer status :text content :title content (nyxt:set-url))))) (export-always 'format-status-tabs) (defmethod format-status-tabs ((status status-buffer)) (spinneret:with-html-string (alex:when-let ((internal-buffers (remove-if-not #'internal-url-p (sort-by-time (buffer-list)) :key #'url))) (:nbutton :class (when (internal-url-p (url (current-buffer))) "plain") :buffer status :type "tab" :text (if (sera:single internal-buffers) (prini-to-string (parse-nyxt-url (url (first internal-buffers)))) "internal") (prompt :prompt "Switch to buffer with internal page" :sources (make-instance 'buffer-source :constructor internal-buffers)))) (loop for domain in (remove-duplicates (sera:filter-map #'quri:uri-domain (remove-if #'internal-url-p (mapcar #'url (sort-by-time (buffer-list))))) :test #'equal) collect (let ((domain domain)) (:nbutton :class (when (equal (quri:uri-domain (url (current-buffer))) domain) "plain") :buffer status :type "tab" :text domain (nyxt::switch-buffer-or-query-domain domain)))))) (export-always 'format-status) (defmethod format-status ((status status-buffer)) (let* ((buffer (current-buffer (window status)))) (spinneret:with-html-string (:div :id "container" (:div :id "controls" :class "arrow-right" (:raw (format-status-buttons status))) (:div :id "url" :class "arrow-right" (:raw (format-status-load-status status) (format-status-url status))) (:div :id "tabs" (:raw (format-status-tabs status))) (:div :id "modes" :class "arrow-left" :title (modes-string buffer) (:raw (format-status-modes status))))))) (defvar *setf-handlers* (sera:dict) "A hash-table mapping (CLASS SLOT) pairs to hash-tables mapping OBJECT to HANDLER. OBJECT may be any value. HANDLER is a function of argument the CLASS instance. See `define-setf-handler'.") (export-always 'define-setf-handler) TODO : SLOT or WRITER ? "When (setf (SLOT-WRITER CLASS-INSTANCE) VALUE) is called, all handlers corresponding to (CLASS SLOT) are evaluated with CLASS-INSTANCE as argument. There is a unique HANDLER per BOUND-OBJECT. When BOUND-OBJECT is garbage-collected, the corresponding handler is automatically removed." (alex:with-gensyms (key) (alex:once-only (bound-object) `(progn (let ((,key (list (find-class ',class-name) ',slot))) (handler-bind ((warning (if (gethash ,key *setf-handlers*) #'muffle-warning ; To avoid warning on redefinition. #'identity))) (setf (gethash ,bound-object (alex:ensure-gethash ,key *setf-handlers* (tg:make-weak-hash-table :test 'equal :weakness :key))) ,handler) (defmethod (setf ,slot) :after (value (,class-name ,class-name)) (declare (ignorable value)) (dolist (handler (alex:hash-table-values (gethash ,key *setf-handlers*))) (funcall* handler ,class-name))))))))) (defmethod customize-instance :after ((status-buffer status-buffer) &key) "Add setf-handlers calling `print-status' on: - `buffer' `modes', - `document-buffer' `url', - `document-buffer' `title', - `window' `active-buffer'. See also `define-setf-handler'." ;; We need to watch both the buffer `modes' slot and the status of modes, ;; since the mode list does not change when a mode gets disabled. (define-setf-handler modable-buffer modes status-buffer (lambda (buffer) (when (window status-buffer) (when (eq buffer (active-buffer (window status-buffer))) (print-status (window status-buffer)))))) (define-setf-handler mode enabled-p status-buffer (lambda (mode) (when (window status-buffer) (when (eq (buffer mode) (active-buffer (window status-buffer))) (print-status (window status-buffer)))))) (define-setf-handler document-buffer url status-buffer (lambda (buffer) (when (window status-buffer) (when (eq buffer (active-buffer (window status-buffer))) (print-status (window status-buffer)))))) (define-setf-handler document-buffer title status-buffer (lambda (buffer) (when (window status-buffer) (when (eq buffer (active-buffer (window status-buffer))) (print-status (window status-buffer)))))) (define-setf-handler window active-buffer status-buffer (lambda (window) (when (eq window (window status-buffer)) (print-status (window status-buffer))))) (define-setf-handler network-buffer status status-buffer (lambda (buffer) (when (window status-buffer) (when (eq buffer (active-buffer (window status-buffer))) (print-status (window status-buffer)))))))
null
https://raw.githubusercontent.com/atlas-engineer/nyxt/073021b9b5c01a0b555c1cf3045c51d7aadc479f/source/status.lisp
lisp
TODO: Firefox-like additional click actions? See -US/kb/mouse-shortcuts-perform-common-tasks However this function changes, it should always: - Prevent IDN/Unicode-spoofing. - Clearly show subdomains (except maybe "trivial" ones) to prevent subdomain takeover attacks. - Retain a clear display of which protocol/scheme is used to discourage e.g. trusting HTTP websites. To avoid warning on redefinition. We need to watch both the buffer `modes' slot and the status of modes, since the mode list does not change when a mode gets disabled.
SPDX - FileCopyrightText : Atlas Engineer LLC SPDX - License - Identifier : BSD-3 - Clause (in-package :nyxt) (export-always 'mode-status) (defgeneric mode-status (status mode) (:method ((status status-buffer) (mode mode)) (if (glyph-mode-presentation-p status) (glyph mode) (princ-to-string mode))) (:documentation "Return a MODE `mode' string description for the STATUS `status-buffer'. Upon returning NIL, the mode is not displayed.")) (defun sort-modes-for-status (modes) "Return visible modes in MODES, with `nyxt/keyscheme-mode:keyscheme-mode' placed first." (multiple-value-bind (keyscheme-mode other-modes) (sera:partition #'nyxt/keyscheme-mode::keyscheme-mode-p (sera:filter #'visible-in-status-p modes)) (append keyscheme-mode other-modes))) (export-always 'format-status-modes) (defmethod format-status-modes ((status status-buffer)) "Render the enabled modes. Any `nyxt/keyscheme-mode:keyscheme-mode' is placed first. This leverages `mode-status' which can be specialized for individual modes." (let ((buffer (current-buffer (window status)))) (if (modable-buffer-p buffer) (let ((sorted-modes (sort-modes-for-status (modes buffer)))) (spinneret:with-html-string (when (nosave-buffer-p buffer) (:span "⚠ nosave")) (:nbutton :buffer status :text "✚" :title (str:concat "Enabled modes: " (modes-string buffer)) (nyxt:toggle-modes)) (loop for mode in sorted-modes collect (let ((mode mode)) (alex:when-let ((formatted-mode (mode-status status mode))) (if (html-string-p formatted-mode) (:raw formatted-mode) (:nbutton :buffer status :text formatted-mode :title (format nil "Describe ~a" mode) (describe-class :class (name mode))))))))) ""))) (defun modes-string (buffer) (when (modable-buffer-p buffer) (format nil "~{~a~^ ~}" (mapcar #'princ-to-string (modes buffer))))) (export-always 'format-status-buttons) (defmethod format-status-buttons ((status status-buffer)) "Render interactive buttons." (spinneret:with-html-string (:nbutton :buffer status :text "←" :title "Backwards" (nyxt/history-mode:history-backwards)) (:nbutton :buffer status :text "↺" :title "Reload" (nyxt:reload-current-buffer)) (:nbutton :buffer status :text "→" :title "Forwards" (nyxt/history-mode:history-forwards) ) (:nbutton :buffer status :text "≡" :title "Execute" (nyxt:execute-command)) (:nbutton :buffer status :text "★" :title "Bookmark this page" (funcall (read-from-string "nyxt/bookmark-mode:bookmark-current-url"))))) (export-always 'format-status-load-status) (defmethod format-status-load-status ((status status-buffer)) (let ((buffer (current-buffer (window status)))) (spinneret:with-html-string (:div :class (if (and (web-buffer-p buffer) (eq (slot-value buffer 'status) :loading)) "loader" ""))))) (export-always 'format-status-url) (defmethod format-status-url ((status status-buffer)) "Formats the currently open URL for the STATUS buffer. MODIFY AT YOUR OWN RISK! The current implementation goes a great way to make the display safe, in particular to prevent IDN-spoofing by showing the Unicode domains as punicode (the Unicode aesthetic domain is shown in parentheses after the URL.)" (let* ((buffer (current-buffer (window status))) (content (multiple-value-bind (aesthetic safe) (render-url (url buffer)) (uiop:strcat (if safe (format nil "~a (~a)" safe aesthetic) aesthetic) (when (title buffer) (str:concat " — " (title buffer))) (when (find (url buffer) (remove buffer (buffer-list)) :test #'url-equal :key #'url) (format nil " (buffer ~a)" (id buffer))))))) (spinneret:with-html-string (:nbutton :buffer status :text content :title content (nyxt:set-url))))) (export-always 'format-status-tabs) (defmethod format-status-tabs ((status status-buffer)) (spinneret:with-html-string (alex:when-let ((internal-buffers (remove-if-not #'internal-url-p (sort-by-time (buffer-list)) :key #'url))) (:nbutton :class (when (internal-url-p (url (current-buffer))) "plain") :buffer status :type "tab" :text (if (sera:single internal-buffers) (prini-to-string (parse-nyxt-url (url (first internal-buffers)))) "internal") (prompt :prompt "Switch to buffer with internal page" :sources (make-instance 'buffer-source :constructor internal-buffers)))) (loop for domain in (remove-duplicates (sera:filter-map #'quri:uri-domain (remove-if #'internal-url-p (mapcar #'url (sort-by-time (buffer-list))))) :test #'equal) collect (let ((domain domain)) (:nbutton :class (when (equal (quri:uri-domain (url (current-buffer))) domain) "plain") :buffer status :type "tab" :text domain (nyxt::switch-buffer-or-query-domain domain)))))) (export-always 'format-status) (defmethod format-status ((status status-buffer)) (let* ((buffer (current-buffer (window status)))) (spinneret:with-html-string (:div :id "container" (:div :id "controls" :class "arrow-right" (:raw (format-status-buttons status))) (:div :id "url" :class "arrow-right" (:raw (format-status-load-status status) (format-status-url status))) (:div :id "tabs" (:raw (format-status-tabs status))) (:div :id "modes" :class "arrow-left" :title (modes-string buffer) (:raw (format-status-modes status))))))) (defvar *setf-handlers* (sera:dict) "A hash-table mapping (CLASS SLOT) pairs to hash-tables mapping OBJECT to HANDLER. OBJECT may be any value. HANDLER is a function of argument the CLASS instance. See `define-setf-handler'.") (export-always 'define-setf-handler) TODO : SLOT or WRITER ? "When (setf (SLOT-WRITER CLASS-INSTANCE) VALUE) is called, all handlers corresponding to (CLASS SLOT) are evaluated with CLASS-INSTANCE as argument. There is a unique HANDLER per BOUND-OBJECT. When BOUND-OBJECT is garbage-collected, the corresponding handler is automatically removed." (alex:with-gensyms (key) (alex:once-only (bound-object) `(progn (let ((,key (list (find-class ',class-name) ',slot))) (handler-bind ((warning (if (gethash ,key *setf-handlers*) #'identity))) (setf (gethash ,bound-object (alex:ensure-gethash ,key *setf-handlers* (tg:make-weak-hash-table :test 'equal :weakness :key))) ,handler) (defmethod (setf ,slot) :after (value (,class-name ,class-name)) (declare (ignorable value)) (dolist (handler (alex:hash-table-values (gethash ,key *setf-handlers*))) (funcall* handler ,class-name))))))))) (defmethod customize-instance :after ((status-buffer status-buffer) &key) "Add setf-handlers calling `print-status' on: - `buffer' `modes', - `document-buffer' `url', - `document-buffer' `title', - `window' `active-buffer'. See also `define-setf-handler'." (define-setf-handler modable-buffer modes status-buffer (lambda (buffer) (when (window status-buffer) (when (eq buffer (active-buffer (window status-buffer))) (print-status (window status-buffer)))))) (define-setf-handler mode enabled-p status-buffer (lambda (mode) (when (window status-buffer) (when (eq (buffer mode) (active-buffer (window status-buffer))) (print-status (window status-buffer)))))) (define-setf-handler document-buffer url status-buffer (lambda (buffer) (when (window status-buffer) (when (eq buffer (active-buffer (window status-buffer))) (print-status (window status-buffer)))))) (define-setf-handler document-buffer title status-buffer (lambda (buffer) (when (window status-buffer) (when (eq buffer (active-buffer (window status-buffer))) (print-status (window status-buffer)))))) (define-setf-handler window active-buffer status-buffer (lambda (window) (when (eq window (window status-buffer)) (print-status (window status-buffer))))) (define-setf-handler network-buffer status status-buffer (lambda (buffer) (when (window status-buffer) (when (eq buffer (active-buffer (window status-buffer))) (print-status (window status-buffer)))))))
55841c21b84f821432711d2d6499ac30b8f724627af43063a9a6be108061524b
anoma/zkp-compiler-shootout
package.lisp
(defpackage :triton-test ;; I really want to use mix, but alas Ι don't want to assume a newer asdf for (:shadowing-import-from :triton :prod :case :tagbody :block :begin :drop :push :pop :return :call) (:use #:serapeum #:cl #:triton #:fiveam) (:local-nicknames) (:export #:run-tests)) (in-package :triton-test)
null
https://raw.githubusercontent.com/anoma/zkp-compiler-shootout/05dce15ba113427942aec7e8e2c1d5e65599b02c/triton-assembler/test/package.lisp
lisp
I really want to use mix, but alas Ι don't want to assume a
(defpackage :triton-test newer asdf for (:shadowing-import-from :triton :prod :case :tagbody :block :begin :drop :push :pop :return :call) (:use #:serapeum #:cl #:triton #:fiveam) (:local-nicknames) (:export #:run-tests)) (in-package :triton-test)
52985ce0a1ec732db6910832489b867664b1c4bc964bd8b7a3cc75a68341df3c
simplex-chat/simplex-chat
WebRTCTests.hs
module WebRTCTests where import Control.Monad.Except import Crypto.Random (getRandomBytes) import qualified Data.ByteString.Base64.URL as U import qualified Data.ByteString.Char8 as B import Simplex.Chat.Mobile.WebRTC import qualified Simplex.Messaging.Crypto as C import Test.Hspec webRTCTests :: Spec webRTCTests = describe "WebRTC crypto" $ do it "encrypts and decrypts media" $ do key <- U.encode <$> getRandomBytes 32 frame <- getRandomBytes 1000 Right frame' <- runExceptT $ chatEncryptMedia key $ frame <> B.replicate reservedSize '\NUL' B.length frame' `shouldBe` B.length frame + reservedSize Right frame'' <- runExceptT $ chatDecryptMedia key frame' frame'' `shouldBe` frame <> B.replicate reservedSize '\NUL' it "should fail on invalid frame size" $ do key <- U.encode <$> getRandomBytes 32 frame <- getRandomBytes 10 runExceptT (chatEncryptMedia key frame) `shouldReturn` Left "frame has no [reserved space for] IV and/or auth tag" runExceptT (chatDecryptMedia key frame) `shouldReturn` Left "frame has no [reserved space for] IV and/or auth tag" it "should fail on invalid key" $ do let key = B.replicate 32 '#' frame <- (<> B.replicate reservedSize '\NUL') <$> getRandomBytes 100 runExceptT (chatEncryptMedia key frame) `shouldReturn` Left "invalid key: invalid character at offset: 0" runExceptT (chatDecryptMedia key frame) `shouldReturn` Left "invalid key: invalid character at offset: 0" it "should fail on invalid auth tag" $ do key <- U.encode <$> getRandomBytes 32 frame <- getRandomBytes 1000 Right frame' <- runExceptT $ chatEncryptMedia key $ frame <> B.replicate reservedSize '\NUL' Right frame'' <- runExceptT $ chatDecryptMedia key frame' frame'' `shouldBe` frame <> B.replicate reservedSize '\NUL' let (encFrame, rest) = B.splitAt (B.length frame' - reservedSize) frame (_tag, iv) = B.splitAt C.authTagSize rest badFrame = encFrame <> B.replicate C.authTagSize '\NUL' <> iv runExceptT (chatDecryptMedia key badFrame) `shouldReturn` Left "AESDecryptError"
null
https://raw.githubusercontent.com/simplex-chat/simplex-chat/01acbb970ae7762e1551e352131453e77a601764/tests/WebRTCTests.hs
haskell
module WebRTCTests where import Control.Monad.Except import Crypto.Random (getRandomBytes) import qualified Data.ByteString.Base64.URL as U import qualified Data.ByteString.Char8 as B import Simplex.Chat.Mobile.WebRTC import qualified Simplex.Messaging.Crypto as C import Test.Hspec webRTCTests :: Spec webRTCTests = describe "WebRTC crypto" $ do it "encrypts and decrypts media" $ do key <- U.encode <$> getRandomBytes 32 frame <- getRandomBytes 1000 Right frame' <- runExceptT $ chatEncryptMedia key $ frame <> B.replicate reservedSize '\NUL' B.length frame' `shouldBe` B.length frame + reservedSize Right frame'' <- runExceptT $ chatDecryptMedia key frame' frame'' `shouldBe` frame <> B.replicate reservedSize '\NUL' it "should fail on invalid frame size" $ do key <- U.encode <$> getRandomBytes 32 frame <- getRandomBytes 10 runExceptT (chatEncryptMedia key frame) `shouldReturn` Left "frame has no [reserved space for] IV and/or auth tag" runExceptT (chatDecryptMedia key frame) `shouldReturn` Left "frame has no [reserved space for] IV and/or auth tag" it "should fail on invalid key" $ do let key = B.replicate 32 '#' frame <- (<> B.replicate reservedSize '\NUL') <$> getRandomBytes 100 runExceptT (chatEncryptMedia key frame) `shouldReturn` Left "invalid key: invalid character at offset: 0" runExceptT (chatDecryptMedia key frame) `shouldReturn` Left "invalid key: invalid character at offset: 0" it "should fail on invalid auth tag" $ do key <- U.encode <$> getRandomBytes 32 frame <- getRandomBytes 1000 Right frame' <- runExceptT $ chatEncryptMedia key $ frame <> B.replicate reservedSize '\NUL' Right frame'' <- runExceptT $ chatDecryptMedia key frame' frame'' `shouldBe` frame <> B.replicate reservedSize '\NUL' let (encFrame, rest) = B.splitAt (B.length frame' - reservedSize) frame (_tag, iv) = B.splitAt C.authTagSize rest badFrame = encFrame <> B.replicate C.authTagSize '\NUL' <> iv runExceptT (chatDecryptMedia key badFrame) `shouldReturn` Left "AESDecryptError"
6bdca148971239baf5ddbabf2882608caf28223ff8d08dc59861d1c2fa0fe527
Fresheyeball/Shpadoinkle
Search.hs
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DerivingStrategies #-} # LANGUAGE GeneralizedNewtypeDeriving # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ViewPatterns # module Shpadoinkle.Widgets.Types.Search where import Data.Aeson (FromJSON, ToJSON) import Data.Foldable as F (Foldable (foldl')) import Data.List (sort) import Data.Maybe (mapMaybe) import Data.String (IsString) import Data.Text (Text, isInfixOf, splitOn, strip, toLower, unpack) import GHC.Generics (Generic) import Shpadoinkle (NFData) import Text.EditDistance (defaultEditCosts, levenshteinDistance) newtype Search = Search { unSearch :: Text } deriving newtype (Eq, Ord, Show, Read, IsString, Semigroup, Monoid, ToJSON, FromJSON) deriving stock Generic deriving anyclass NFData newtype EditDistance = EditDistance { unEditDistance :: Int } deriving newtype (Eq, Ord, Show, Read, ToJSON, FromJSON) deriving stock Generic deriving anyclass NFData data Levenshtiened a = Levenshtiened { _distance :: !EditDistance, _unLevenshtiened :: a } deriving (Eq, Show, Read, Generic, NFData) instance Eq a => Ord (Levenshtiened a) where compare (Levenshtiened x _) (Levenshtiened y _) = unEditDistance x `compare` unEditDistance y mkLevenshtiened :: Text -> Search -> a -> Levenshtiened a mkLevenshtiened t (Search s) = Levenshtiened . EditDistance $ levenshteinDistance defaultEditCosts (prep s) (prep t) where prep = unpack . strip forgivingly :: Search -> Text -> Bool forgivingly (Search (strip -> "")) _ = True forgivingly (Search s) haystack = Prelude.all test . splitOn " " $ strip s where test "" = False test needle = forgive needle `isInfixOf` forgive haystack forgive = toLower . strip concatFuzzy :: [a -> Text] -> a -> Text concatFuzzy = F.foldl' (\f g a -> f a <> " " <> g a) (const "") fuzzySearch :: Ord a => [a -> Text] -> Search -> [a] -> [a] fuzzySearch toChunks s = fmap _unLevenshtiened . sort . mapMaybe (\x -> let hay = concatFuzzy toChunks x in if forgivingly s hay then Just $ mkLevenshtiened hay s x else Nothing )
null
https://raw.githubusercontent.com/Fresheyeball/Shpadoinkle/8e0efbb11857a1af47038dae07b8140291c251ed/widgets/Shpadoinkle/Widgets/Types/Search.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE OverloadedStrings #
# LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE ViewPatterns # module Shpadoinkle.Widgets.Types.Search where import Data.Aeson (FromJSON, ToJSON) import Data.Foldable as F (Foldable (foldl')) import Data.List (sort) import Data.Maybe (mapMaybe) import Data.String (IsString) import Data.Text (Text, isInfixOf, splitOn, strip, toLower, unpack) import GHC.Generics (Generic) import Shpadoinkle (NFData) import Text.EditDistance (defaultEditCosts, levenshteinDistance) newtype Search = Search { unSearch :: Text } deriving newtype (Eq, Ord, Show, Read, IsString, Semigroup, Monoid, ToJSON, FromJSON) deriving stock Generic deriving anyclass NFData newtype EditDistance = EditDistance { unEditDistance :: Int } deriving newtype (Eq, Ord, Show, Read, ToJSON, FromJSON) deriving stock Generic deriving anyclass NFData data Levenshtiened a = Levenshtiened { _distance :: !EditDistance, _unLevenshtiened :: a } deriving (Eq, Show, Read, Generic, NFData) instance Eq a => Ord (Levenshtiened a) where compare (Levenshtiened x _) (Levenshtiened y _) = unEditDistance x `compare` unEditDistance y mkLevenshtiened :: Text -> Search -> a -> Levenshtiened a mkLevenshtiened t (Search s) = Levenshtiened . EditDistance $ levenshteinDistance defaultEditCosts (prep s) (prep t) where prep = unpack . strip forgivingly :: Search -> Text -> Bool forgivingly (Search (strip -> "")) _ = True forgivingly (Search s) haystack = Prelude.all test . splitOn " " $ strip s where test "" = False test needle = forgive needle `isInfixOf` forgive haystack forgive = toLower . strip concatFuzzy :: [a -> Text] -> a -> Text concatFuzzy = F.foldl' (\f g a -> f a <> " " <> g a) (const "") fuzzySearch :: Ord a => [a -> Text] -> Search -> [a] -> [a] fuzzySearch toChunks s = fmap _unLevenshtiened . sort . mapMaybe (\x -> let hay = concatFuzzy toChunks x in if forgivingly s hay then Just $ mkLevenshtiened hay s x else Nothing )
38b4c02dedf4a5d0a8e95b778a5c268c53fa62e2c73245a7e43a2319f08b9cf9
libguestfs/supermin
format_ext2_kernel.mli
supermin 5 * Copyright ( C ) 2009 - 2016 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) 2009-2016 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 *) (** For [--build -f ext2] this module chooses a kernel to use and either links to it or copies it. See also the {!Format_ext2} module. *) val build_kernel : int -> string -> bool -> string -> string * string (** [build_kernel debug host_cpu copy_kernel kernel] chooses the kernel to use and links to it or copies it into the appliance directory. The output is written to the file [kernel]. The function returns the [kernel_version, modpath] tuple as a side-effect of locating the kernel. *)
null
https://raw.githubusercontent.com/libguestfs/supermin/fd9f17c7eb63979af882533a0d234bfc8ca42de3/src/format_ext2_kernel.mli
ocaml
* For [--build -f ext2] this module chooses a kernel to use and either links to it or copies it. See also the {!Format_ext2} module. * [build_kernel debug host_cpu copy_kernel kernel] chooses the kernel to use and links to it or copies it into the appliance directory. The output is written to the file [kernel]. The function returns the [kernel_version, modpath] tuple as a side-effect of locating the kernel.
supermin 5 * Copyright ( C ) 2009 - 2016 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) 2009-2016 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 *) val build_kernel : int -> string -> bool -> string -> string * string
ec6fa086b9cd26049504f8d9a0689b81840be29129cefed8e803f24686b5d182
g-andrade/erlwitness
erlwitness_lobby.erl
% vim: set expandtab softtabstop=4 shiftwidth=4: -module(erlwitness_lobby). -author('Guilherme Andrade <erlwitness(at)gandrade(dot)net>'). -behaviour(gen_server). %% API functions -export([watch/2, unwatch/2, unwatch_by_pid/1, watchers_local_lookup/1, is_entity_watched_by/2, is_entity_watched/1]). -export([start_link/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -ignore_xref([{start_link, 0}, {is_entity_watched, 1}]). -record(state, { monitored_watchers = [] :: [{Monitor :: reference(), WatcherPid :: pid()}] }). -record(watcher, { entity :: erlwitness:entity(), watcher_pid :: pid() }). -define(TABLE, ?MODULE). -define(SERVER, ?MODULE). %%%=================================================================== %%% API functions %%%=================================================================== -spec watch(Entity :: erlwitness:entity(), WatcherPid :: pid()) -> boolean(). watch(Entity, WatcherPid) when is_pid(WatcherPid) -> Watcher = #watcher{entity = Entity, watcher_pid = WatcherPid}, {Replies, _BadNodes} = gen_server:multi_call(?SERVER, {watch, Watcher}), length(Replies) > 0. -spec unwatch(Entity :: erlwitness:entity(), WatcherPid :: pid()) -> ok. unwatch(Entity, WatcherPid) when is_pid(WatcherPid) -> Watcher = #watcher{entity = Entity, watcher_pid = WatcherPid}, abcast = gen_server:abcast(?SERVER, {unwatch, Watcher}), ok. -spec unwatch_by_pid(WatcherPid :: pid()) -> ok. unwatch_by_pid(WatcherPid) when is_pid(WatcherPid) -> abcast = gen_server:abcast(?SERVER, {unwatch_pid, WatcherPid}), ok. -spec watchers_local_lookup(Entity :: erlwitness:entity()) -> [pid()]. watchers_local_lookup(Entity) -> Watchers = ets:lookup(?TABLE, Entity), [Watcher#watcher.watcher_pid || Watcher <- Watchers]. -spec is_entity_watched_by(Entity :: erlwitness:entity(), WatcherPid :: pid()) -> boolean(). is_entity_watched_by(Entity, WatcherPid) -> lists:member(#watcher{entity = Entity, watcher_pid=WatcherPid}, ets:lookup(?TABLE, Entity)). -spec is_entity_watched(Entity :: erlwitness:entity()) -> boolean(). is_entity_watched(Entity) -> ets:member(?TABLE, Entity). %%-------------------------------------------------------------------- %% @doc %% Starts the server %% ( ) - > { ok , Pid } | ignore | { error , Error } %% @end %%-------------------------------------------------------------------- start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %%-------------------------------------------------------------------- @private %% @doc %% Initializes the server %% ) - > { ok , State } | { ok , State , Timeout } | %% ignore | %% {stop, Reason} %% @end %%-------------------------------------------------------------------- init([]) -> ?TABLE = ets:new(?TABLE, [bag, named_table, protected, {keypos, #watcher.entity}, {read_concurrency, true}]), ok = net_kernel:monitor_nodes(true, [{node_type, visible}]), {ok, #state{}}. %%-------------------------------------------------------------------- @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({watch, #watcher{ watcher_pid=Pid }=Watcher}, _From, State) when is_pid(Pid), Pid /= self() -> {reply, ok, handle_registration(State, Watcher)}; handle_call(_Request, _From, State) -> {noreply, State}. %%-------------------------------------------------------------------- @private %% @doc %% Handling cast messages %% @spec handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_cast({watch, #watcher{ watcher_pid=Pid }=Watcher}, State) when is_pid(Pid), Pid /= self() -> {noreply, handle_registration(State, Watcher)}; handle_cast({unwatch, #watcher{ watcher_pid=Pid }=Watcher}, State) when is_pid(Pid) -> true = ets:delete_object(?TABLE, Watcher), case ets:match(?TABLE, #watcher{ entity='$1', watcher_pid=Pid }) of [_|_] -> {noreply, State}; [] -> % Last watcher for this pid unwatched; unmonitor process {noreply, handle_pid_unregistration(State, Pid)} end; handle_cast({unwatch_pid, Pid}, State) when is_pid(Pid) -> {noreply, handle_pid_unregistration(State, Pid)}; handle_cast(_Msg, State) -> {noreply, State}. %%-------------------------------------------------------------------- @private %% @doc %% Handling all non call/cast messages %% , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_info({nodeup, Node, _}, #state{}=State) when Node /= node() -> MatchSpec = ets:fun2ms(fun(#watcher{ watcher_pid=Pid }=Watcher) when node(Pid) == node() -> Watcher end), LocalWatchers = ets:select(?TABLE, MatchSpec), lists:foreach(fun (#watcher{}=Watcher) -> gen_server:cast({?SERVER, Node}, {watch, Watcher}) end, LocalWatchers), {noreply, State}; handle_info({nodedown, _Node, _}, #state{}=State) -> {noreply, State}; handle_info({'DOWN', _Ref, process, Pid, _Reason}, #state{}=State) -> {noreply, handle_pid_unregistration(State, Pid)}; 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 %%%=================================================================== -spec handle_pid_unregistration(#state{}, pid()) -> #state{}. handle_pid_unregistration(#state{ monitored_watchers=Monitors }=State, Pid) -> NewMonitors = lists:keydelete(Pid, 2, Monitors), true = ets:match_delete(?TABLE, #watcher{ entity='_', watcher_pid=Pid }), State#state{ monitored_watchers=NewMonitors }. -spec handle_registration(#state{}, #watcher{}) -> #state{}. handle_registration(#state{ monitored_watchers=Monitors }=State, #watcher{ entity=Entity, watcher_pid=Pid }=Watcher) -> case {lists:member(Watcher, ets:lookup(?TABLE, Entity)), lists:keymember(Pid, 2, Monitors)} of {true, true} -> State; {false, true} -> % We're already monitoring this watcher true = ets:insert(?TABLE, Watcher), State; {false, false} -> Monitor = monitor(process, Pid), NewMonitors = [{Monitor, Pid} | Monitors], NewState = State#state{ monitored_watchers=NewMonitors }, true = ets:insert(?TABLE, Watcher), NewState end.
null
https://raw.githubusercontent.com/g-andrade/erlwitness/047ea86ea2fec9c3dab1ef091a3a1dfea23abaad/src/erlwitness_lobby.erl
erlang
vim: set expandtab softtabstop=4 shiftwidth=4: API functions gen_server callbacks =================================================================== API functions =================================================================== -------------------------------------------------------------------- @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 -------------------------------------------------------------------- Last watcher for this pid unwatched; unmonitor process -------------------------------------------------------------------- @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 -------------------------------------------------------------------- =================================================================== =================================================================== We're already monitoring this watcher
-module(erlwitness_lobby). -author('Guilherme Andrade <erlwitness(at)gandrade(dot)net>'). -behaviour(gen_server). -export([watch/2, unwatch/2, unwatch_by_pid/1, watchers_local_lookup/1, is_entity_watched_by/2, is_entity_watched/1]). -export([start_link/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -ignore_xref([{start_link, 0}, {is_entity_watched, 1}]). -record(state, { monitored_watchers = [] :: [{Monitor :: reference(), WatcherPid :: pid()}] }). -record(watcher, { entity :: erlwitness:entity(), watcher_pid :: pid() }). -define(TABLE, ?MODULE). -define(SERVER, ?MODULE). -spec watch(Entity :: erlwitness:entity(), WatcherPid :: pid()) -> boolean(). watch(Entity, WatcherPid) when is_pid(WatcherPid) -> Watcher = #watcher{entity = Entity, watcher_pid = WatcherPid}, {Replies, _BadNodes} = gen_server:multi_call(?SERVER, {watch, Watcher}), length(Replies) > 0. -spec unwatch(Entity :: erlwitness:entity(), WatcherPid :: pid()) -> ok. unwatch(Entity, WatcherPid) when is_pid(WatcherPid) -> Watcher = #watcher{entity = Entity, watcher_pid = WatcherPid}, abcast = gen_server:abcast(?SERVER, {unwatch, Watcher}), ok. -spec unwatch_by_pid(WatcherPid :: pid()) -> ok. unwatch_by_pid(WatcherPid) when is_pid(WatcherPid) -> abcast = gen_server:abcast(?SERVER, {unwatch_pid, WatcherPid}), ok. -spec watchers_local_lookup(Entity :: erlwitness:entity()) -> [pid()]. watchers_local_lookup(Entity) -> Watchers = ets:lookup(?TABLE, Entity), [Watcher#watcher.watcher_pid || Watcher <- Watchers]. -spec is_entity_watched_by(Entity :: erlwitness:entity(), WatcherPid :: pid()) -> boolean(). is_entity_watched_by(Entity, WatcherPid) -> lists:member(#watcher{entity = Entity, watcher_pid=WatcherPid}, ets:lookup(?TABLE, Entity)). -spec is_entity_watched(Entity :: erlwitness:entity()) -> boolean(). is_entity_watched(Entity) -> ets:member(?TABLE, Entity). ( ) - > { ok , Pid } | ignore | { error , Error } start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). @private ) - > { ok , State } | { ok , State , Timeout } | init([]) -> ?TABLE = ets:new(?TABLE, [bag, named_table, protected, {keypos, #watcher.entity}, {read_concurrency, true}]), ok = net_kernel:monitor_nodes(true, [{node_type, visible}]), {ok, #state{}}. @private , From , State ) - > { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | handle_call({watch, #watcher{ watcher_pid=Pid }=Watcher}, _From, State) when is_pid(Pid), Pid /= self() -> {reply, ok, handle_registration(State, Watcher)}; handle_call(_Request, _From, State) -> {noreply, State}. @private @spec handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_cast({watch, #watcher{ watcher_pid=Pid }=Watcher}, State) when is_pid(Pid), Pid /= self() -> {noreply, handle_registration(State, Watcher)}; handle_cast({unwatch, #watcher{ watcher_pid=Pid }=Watcher}, State) when is_pid(Pid) -> true = ets:delete_object(?TABLE, Watcher), case ets:match(?TABLE, #watcher{ entity='$1', watcher_pid=Pid }) of [_|_] -> {noreply, State}; [] -> {noreply, handle_pid_unregistration(State, Pid)} end; handle_cast({unwatch_pid, Pid}, State) when is_pid(Pid) -> {noreply, handle_pid_unregistration(State, Pid)}; handle_cast(_Msg, State) -> {noreply, State}. @private , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_info({nodeup, Node, _}, #state{}=State) when Node /= node() -> MatchSpec = ets:fun2ms(fun(#watcher{ watcher_pid=Pid }=Watcher) when node(Pid) == node() -> Watcher end), LocalWatchers = ets:select(?TABLE, MatchSpec), lists:foreach(fun (#watcher{}=Watcher) -> gen_server:cast({?SERVER, Node}, {watch, Watcher}) end, LocalWatchers), {noreply, State}; handle_info({nodedown, _Node, _}, #state{}=State) -> {noreply, State}; handle_info({'DOWN', _Ref, process, Pid, _Reason}, #state{}=State) -> {noreply, handle_pid_unregistration(State, Pid)}; 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 -spec handle_pid_unregistration(#state{}, pid()) -> #state{}. handle_pid_unregistration(#state{ monitored_watchers=Monitors }=State, Pid) -> NewMonitors = lists:keydelete(Pid, 2, Monitors), true = ets:match_delete(?TABLE, #watcher{ entity='_', watcher_pid=Pid }), State#state{ monitored_watchers=NewMonitors }. -spec handle_registration(#state{}, #watcher{}) -> #state{}. handle_registration(#state{ monitored_watchers=Monitors }=State, #watcher{ entity=Entity, watcher_pid=Pid }=Watcher) -> case {lists:member(Watcher, ets:lookup(?TABLE, Entity)), lists:keymember(Pid, 2, Monitors)} of {true, true} -> State; {false, true} -> true = ets:insert(?TABLE, Watcher), State; {false, false} -> Monitor = monitor(process, Pid), NewMonitors = [{Monitor, Pid} | Monitors], NewState = State#state{ monitored_watchers=NewMonitors }, true = ets:insert(?TABLE, Watcher), NewState end.
526797efc89dea1ef346436f25232d4201faa44d141a765e793f5bb9110ceb1f
GaloisInc/ivory
FibTutorial.hs
# LANGUAGE DataKinds # # LANGUAGE TypeOperators # module FibTutorial where import Ivory.Language import qualified Ivory.Compile.C.CmdlineFrontend as C (compile) fib_loop :: Def ('[Ix 1000] ':-> Uint32) fib_loop = proc "fib_loop" $ \ n -> body $ do a <- local (ival 0) b <- local (ival 1) n `times` \ _ -> do a' <- deref a b' <- deref b store a b' store b (a' + b') result <- deref a ret result fib_tutorial_module :: Module fib_tutorial_module = package "fib_tutorial" $ do incl fib_loop main :: IO () main = C.compile [ fib_tutorial_module ] []
null
https://raw.githubusercontent.com/GaloisInc/ivory/53a0795b4fbeb0b7da0f6cdaccdde18849a78cd6/ivory-examples/examples/FibTutorial.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE TypeOperators # module FibTutorial where import Ivory.Language import qualified Ivory.Compile.C.CmdlineFrontend as C (compile) fib_loop :: Def ('[Ix 1000] ':-> Uint32) fib_loop = proc "fib_loop" $ \ n -> body $ do a <- local (ival 0) b <- local (ival 1) n `times` \ _ -> do a' <- deref a b' <- deref b store a b' store b (a' + b') result <- deref a ret result fib_tutorial_module :: Module fib_tutorial_module = package "fib_tutorial" $ do incl fib_loop main :: IO () main = C.compile [ fib_tutorial_module ] []
b8383794af82acb5f202c16614a1ad6ae0c09a576b6a465a95a8bc863a79fe5a
cemerick/friend
middleware.clj
(ns test-friend.middleware (:use clojure.test [compojure.core :only (defroutes GET)] [cemerick.friend :only (wrap-authorize)])) (defroutes ^{:private true} routes (GET "/path" request "Response")) (deftest wrap-authorize-throws-on-empty-role-set (testing "wrap-authorize throws IllegalArgumentException on empty roles set" (is (thrown? IllegalArgumentException (wrap-authorize routes #{})))))
null
https://raw.githubusercontent.com/cemerick/friend/75bb607179515c6abd0a76a11ee97895fb758963/test/test_friend/middleware.clj
clojure
(ns test-friend.middleware (:use clojure.test [compojure.core :only (defroutes GET)] [cemerick.friend :only (wrap-authorize)])) (defroutes ^{:private true} routes (GET "/path" request "Response")) (deftest wrap-authorize-throws-on-empty-role-set (testing "wrap-authorize throws IllegalArgumentException on empty roles set" (is (thrown? IllegalArgumentException (wrap-authorize routes #{})))))
2c17baa5112f8679d39c9304e7d8b9106d3ce9df42ae795cfa32b755d1ac9694
stumpwm/stumpwm-contrib
lock.lisp
(in-package #:stump-lock) (defvar *password* nil "The password to unlock.") (stumpwm:defcommand lock-screen () () (unless *password* (error "A password needs to be set. Please read the instructions.")) (loop (if (string= (let ((stumpwm::*input-history* nil)) (stumpwm:read-one-line (stumpwm:current-screen) (format nil "The screen is locked.~%Enter password: ") :password t)) *password*) (return) (sleep (+ 2 (random 3.0))))))
null
https://raw.githubusercontent.com/stumpwm/stumpwm-contrib/a7dc1c663d04e6c73a4772c8a6ad56a34381096a/util/stump-lock/lock.lisp
lisp
(in-package #:stump-lock) (defvar *password* nil "The password to unlock.") (stumpwm:defcommand lock-screen () () (unless *password* (error "A password needs to be set. Please read the instructions.")) (loop (if (string= (let ((stumpwm::*input-history* nil)) (stumpwm:read-one-line (stumpwm:current-screen) (format nil "The screen is locked.~%Enter password: ") :password t)) *password*) (return) (sleep (+ 2 (random 3.0))))))
b6a40afb821932df2aa05e4e7e4a97b6dc84fdcdd3ff350e59df93e4ec9ed032
hugomg/scfgc
id.ml
open Core_kernel.Std module type S = sig type t with sexp val to_int : t -> int val fresh : unit -> t include Comparable.S with type t := t include Hashable.S with type t := t end module Make ( ) : S = struct type t = int with sexp let to_int x = x let next = ref 0 let fresh () = let id = !next in next := id + 1; id include Comparable.Make(Int) include Hashable.Make(Int) end
null
https://raw.githubusercontent.com/hugomg/scfgc/9604ef317a23ce51c46d8e5d03e6597081abc3cd/id.ml
ocaml
open Core_kernel.Std module type S = sig type t with sexp val to_int : t -> int val fresh : unit -> t include Comparable.S with type t := t include Hashable.S with type t := t end module Make ( ) : S = struct type t = int with sexp let to_int x = x let next = ref 0 let fresh () = let id = !next in next := id + 1; id include Comparable.Make(Int) include Hashable.Make(Int) end
4c150f42013e5b88a87b9695e9a787cec7b52610598d715bcd67b43aaf445766
david-broman/modelyze
sundials.mli
Modeling Kernel Language ( Modelyze ) evaluator Copyright ( C ) 2010 - 2012 This program is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program . If not , see < / > . Modeling Kernel Language (Modelyze) evaluator Copyright (C) 2010-2012 David Broman This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see </>. *) module Ida : sig * Wrapper module for Sundial 's DAE solver IDA exception Eqs_mismatch (** Raised when the number of equations supplied (e.g. array sizes) are wrong *) exception Init_error (** Raised when there is an error in the init procedure. *) type st (** The simulation instance type *) type residual = float -> float array -> float array -> float array * Type of the residual callback function . Parameter 1 is the current simulation time . Parameter 2 is the current value of the dependent variable vector y(t ) . Parameter 3 is the current value of y'(t ) . The function should return the residual vector F(t , y , y ' ) . Note that all three vectors must have same size as the number of equations . simulation time. Parameter 2 is the current value of the dependent variable vector y(t). Parameter 3 is the current value of y'(t). The function should return the residual vector F(t,y,y'). Note that all three vectors must have same size as the number of equations. *) type rootfinder = float -> float array -> float array -> float array * Type of the root finder callback function . Parameter is the current simulation time . Parameter 2 is the current value of the dependent variable vector y(t ) . Parameter 3 is the current value of y'(t ) . The function should return an array with the root differences sought . Note that the size of this array should be the same as the one defined when function [ rootinit ] was called simulation time. Parameter 2 is the current value of the dependent variable vector y(t). Parameter 3 is the current value of y'(t). The function should return an array with the root differences sought. Note that the size of this array should be the same as the one defined when function [rootinit] was called *) val make : ?start_time:float -> ?reltol:float -> ?abstol:float -> ?roots:int -> ?rootfun:rootfinder -> float array -> float array -> float array -> residual -> st * [ make ~start_time : time ~reltol : rt ~abstol : at ~roots : nr ~rootfun : rootf y yp res ] creates a new simulation instance with start time [ time ] , relative error tolerance [ rt ] , absolute error tolerance [ at ] , number of roots to find [ nr ] , the root finder function [ rootf ] , initial values [ y ] , inital derivative values [ yp ] , and the residual function [ res ] . Both the realtive and absolute error tolerances are default set to 1.0e-5 and the default start time is 0 . By default , there are no root finders . If a root finder should be used , both then number of roots must be defined [ roots ] and the root function [ ] . See types [ residual ] and [ rootfinder ] for more information about the callback function . The function can throw exceptions [ Eqs_mismatch ] and [ Init_error ] . creates a new simulation instance with start time [time], relative error tolerance [rt], absolute error tolerance [at], number of roots to find [nr], the root finder function [rootf], initial values [y], inital derivative values [yp], and the residual function [res]. Both the realtive and absolute error tolerances are default set to 1.0e-5 and the default start time is 0. By default, there are no root finders. If a root finder should be used, both then number of roots must be defined [roots] and the root function [rootfun]. See types [residual] and [rootfinder] for more information about the callback function. The function can throw exceptions [Eqs_mismatch] and [Init_error]. *) val reinit: st -> unit (** Reinitialize the solver again with the same time and value as currently exists in the simulation instance *) val close: st -> unit (** Close a simulation instance. This function must be called after using the system to free up memory. *) val equations : st -> int (** Returns the number of equations. *) val reltol : st -> float (** Returns the current relative error tolerance. *) val abstol : st -> float (** Returns the current absolute error tolerance. *) val y : st -> float array (** Returns an array of variables. *) val yp : st -> float array (** Returns an array of derivative variables. *) val step : st -> float -> float * [ step ] tries to simulate [ t ] time forward and returns the time after the step . If something goes wrong , the step time zero will be returned . the time after the step. If something goes wrong, the step time zero will be returned. *) val time : st -> float (** Returns the current simulation time *) val roots : st -> int array * Returns an array representing the different roots . A zero element means no root found , and a non - zero element that the root was found . An empty array is returned if no roots at all were detected . This function should always be called after the [ step ] function . element means no root found, and a non-zero element that the root was found. An empty array is returned if no roots at all were detected. This function should always be called after the [step] function.*) val set : st -> float array -> float array -> unit * Set the y vector ( parameter 2 ) and yp vector ( parameter 3 ) . end
null
https://raw.githubusercontent.com/david-broman/modelyze/e48c934283e683e268a9dfd0fed49d3c10277298/ext/sundials/sundials.mli
ocaml
* Raised when the number of equations supplied (e.g. array sizes) are wrong * Raised when there is an error in the init procedure. * The simulation instance type * Reinitialize the solver again with the same time and value as currently exists in the simulation instance * Close a simulation instance. This function must be called after using the system to free up memory. * Returns the number of equations. * Returns the current relative error tolerance. * Returns the current absolute error tolerance. * Returns an array of variables. * Returns an array of derivative variables. * Returns the current simulation time
Modeling Kernel Language ( Modelyze ) evaluator Copyright ( C ) 2010 - 2012 This program is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program . If not , see < / > . Modeling Kernel Language (Modelyze) evaluator Copyright (C) 2010-2012 David Broman This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see </>. *) module Ida : sig * Wrapper module for Sundial 's DAE solver IDA exception Eqs_mismatch exception Init_error type st type residual = float -> float array -> float array -> float array * Type of the residual callback function . Parameter 1 is the current simulation time . Parameter 2 is the current value of the dependent variable vector y(t ) . Parameter 3 is the current value of y'(t ) . The function should return the residual vector F(t , y , y ' ) . Note that all three vectors must have same size as the number of equations . simulation time. Parameter 2 is the current value of the dependent variable vector y(t). Parameter 3 is the current value of y'(t). The function should return the residual vector F(t,y,y'). Note that all three vectors must have same size as the number of equations. *) type rootfinder = float -> float array -> float array -> float array * Type of the root finder callback function . Parameter is the current simulation time . Parameter 2 is the current value of the dependent variable vector y(t ) . Parameter 3 is the current value of y'(t ) . The function should return an array with the root differences sought . Note that the size of this array should be the same as the one defined when function [ rootinit ] was called simulation time. Parameter 2 is the current value of the dependent variable vector y(t). Parameter 3 is the current value of y'(t). The function should return an array with the root differences sought. Note that the size of this array should be the same as the one defined when function [rootinit] was called *) val make : ?start_time:float -> ?reltol:float -> ?abstol:float -> ?roots:int -> ?rootfun:rootfinder -> float array -> float array -> float array -> residual -> st * [ make ~start_time : time ~reltol : rt ~abstol : at ~roots : nr ~rootfun : rootf y yp res ] creates a new simulation instance with start time [ time ] , relative error tolerance [ rt ] , absolute error tolerance [ at ] , number of roots to find [ nr ] , the root finder function [ rootf ] , initial values [ y ] , inital derivative values [ yp ] , and the residual function [ res ] . Both the realtive and absolute error tolerances are default set to 1.0e-5 and the default start time is 0 . By default , there are no root finders . If a root finder should be used , both then number of roots must be defined [ roots ] and the root function [ ] . See types [ residual ] and [ rootfinder ] for more information about the callback function . The function can throw exceptions [ Eqs_mismatch ] and [ Init_error ] . creates a new simulation instance with start time [time], relative error tolerance [rt], absolute error tolerance [at], number of roots to find [nr], the root finder function [rootf], initial values [y], inital derivative values [yp], and the residual function [res]. Both the realtive and absolute error tolerances are default set to 1.0e-5 and the default start time is 0. By default, there are no root finders. If a root finder should be used, both then number of roots must be defined [roots] and the root function [rootfun]. See types [residual] and [rootfinder] for more information about the callback function. The function can throw exceptions [Eqs_mismatch] and [Init_error]. *) val reinit: st -> unit val close: st -> unit val equations : st -> int val reltol : st -> float val abstol : st -> float val y : st -> float array val yp : st -> float array val step : st -> float -> float * [ step ] tries to simulate [ t ] time forward and returns the time after the step . If something goes wrong , the step time zero will be returned . the time after the step. If something goes wrong, the step time zero will be returned. *) val time : st -> float val roots : st -> int array * Returns an array representing the different roots . A zero element means no root found , and a non - zero element that the root was found . An empty array is returned if no roots at all were detected . This function should always be called after the [ step ] function . element means no root found, and a non-zero element that the root was found. An empty array is returned if no roots at all were detected. This function should always be called after the [step] function.*) val set : st -> float array -> float array -> unit * Set the y vector ( parameter 2 ) and yp vector ( parameter 3 ) . end
58a6a03b997f445cd31ed165d867be55428f6507b9568339ca33d94ad2e57fab
oakes/paren-soup
prod.clj
(require '[clojure.java.io :as io] '[clojure.string :as str] '[cljs.build.api :as api] '[leiningen.core.project :as p :refer [defproject]] '[leiningen.install :refer [install]] '[leiningen.deploy :refer [deploy]]) (defn read-project-clj [] (p/ensure-dynamic-classloader) (-> "project.clj" load-file var-get)) (defn read-deps-edn [aliases-to-include] (let [{:keys [paths deps aliases]} (-> "deps.edn" slurp clojure.edn/read-string) deps (->> (select-keys aliases aliases-to-include) vals (mapcat :extra-deps) (into deps) (map (fn parse-coord [coord] (let [[artifact info] coord s (str artifact)] (if-let [i (str/index-of s "$")] [(symbol (subs s 0 i)) (assoc info :classifier (subs s (inc i)))] coord)))) (reduce (fn [deps [artifact info]] (if-let [version (:mvn/version info)] (conj deps (transduce cat conj [artifact version] (select-keys info [:exclusions :classifier]))) deps)) [])) paths (->> (select-keys aliases aliases-to-include) vals (mapcat :extra-paths) (into paths))] {:dependencies deps :source-paths [] :resource-paths paths})) (defn delete-children-recursively! [f] (when (.isDirectory f) (doseq [f2 (.listFiles f)] (delete-children-recursively! f2))) (when (.exists f) (io/delete-file f))) (defn build-cljs [file-name opts] (let [out-file (str "resources/public/" file-name ".js") out-dir (str "resources/public/" file-name ".out")] (println "Building" out-file) (delete-children-recursively! (io/file out-dir)) (api/build "src" (merge {:output-to out-file :output-dir out-dir} opts)) (delete-children-recursively! (io/file out-dir)))) (defmulti task first) (defmethod task :default [_] (let [all-tasks (-> task methods (dissoc :default) keys sort) interposed (->> all-tasks (interpose ", ") (apply str))] (println "Unknown or missing task. Choose one of:" interposed) (System/exit 1))) (defmethod task "build" [_] (-> (read-project-clj) p/init-project) (build-cljs "paren-soup" {:main 'paren-soup.prod :optimizations :advanced}) (build-cljs "paren-soup-compiler" {:main 'paren-soup.compiler :optimizations :simple :static-fns true :optimize-constants true}) (build-cljs "paren-soup-with-compiler" {:main 'paren-soup.core :optimizations :simple :static-fns true :optimize-constants true})) (defmethod task "install" [_] (-> (read-project-clj) (merge (read-deps-edn [])) p/init-project install) (System/exit 0)) (defmethod task "deploy" [_] (-> (read-project-clj) (merge (read-deps-edn [])) p/init-project (deploy "clojars")) (System/exit 0)) ;; entry point (task *command-line-args*)
null
https://raw.githubusercontent.com/oakes/paren-soup/15f55ebb40ee30f75ca960d381ddebd094a76f3d/prod.clj
clojure
entry point
(require '[clojure.java.io :as io] '[clojure.string :as str] '[cljs.build.api :as api] '[leiningen.core.project :as p :refer [defproject]] '[leiningen.install :refer [install]] '[leiningen.deploy :refer [deploy]]) (defn read-project-clj [] (p/ensure-dynamic-classloader) (-> "project.clj" load-file var-get)) (defn read-deps-edn [aliases-to-include] (let [{:keys [paths deps aliases]} (-> "deps.edn" slurp clojure.edn/read-string) deps (->> (select-keys aliases aliases-to-include) vals (mapcat :extra-deps) (into deps) (map (fn parse-coord [coord] (let [[artifact info] coord s (str artifact)] (if-let [i (str/index-of s "$")] [(symbol (subs s 0 i)) (assoc info :classifier (subs s (inc i)))] coord)))) (reduce (fn [deps [artifact info]] (if-let [version (:mvn/version info)] (conj deps (transduce cat conj [artifact version] (select-keys info [:exclusions :classifier]))) deps)) [])) paths (->> (select-keys aliases aliases-to-include) vals (mapcat :extra-paths) (into paths))] {:dependencies deps :source-paths [] :resource-paths paths})) (defn delete-children-recursively! [f] (when (.isDirectory f) (doseq [f2 (.listFiles f)] (delete-children-recursively! f2))) (when (.exists f) (io/delete-file f))) (defn build-cljs [file-name opts] (let [out-file (str "resources/public/" file-name ".js") out-dir (str "resources/public/" file-name ".out")] (println "Building" out-file) (delete-children-recursively! (io/file out-dir)) (api/build "src" (merge {:output-to out-file :output-dir out-dir} opts)) (delete-children-recursively! (io/file out-dir)))) (defmulti task first) (defmethod task :default [_] (let [all-tasks (-> task methods (dissoc :default) keys sort) interposed (->> all-tasks (interpose ", ") (apply str))] (println "Unknown or missing task. Choose one of:" interposed) (System/exit 1))) (defmethod task "build" [_] (-> (read-project-clj) p/init-project) (build-cljs "paren-soup" {:main 'paren-soup.prod :optimizations :advanced}) (build-cljs "paren-soup-compiler" {:main 'paren-soup.compiler :optimizations :simple :static-fns true :optimize-constants true}) (build-cljs "paren-soup-with-compiler" {:main 'paren-soup.core :optimizations :simple :static-fns true :optimize-constants true})) (defmethod task "install" [_] (-> (read-project-clj) (merge (read-deps-edn [])) p/init-project install) (System/exit 0)) (defmethod task "deploy" [_] (-> (read-project-clj) (merge (read-deps-edn [])) p/init-project (deploy "clojars")) (System/exit 0)) (task *command-line-args*)
c5ace1b185f663531bfb524c992df9fedae6b50e5adae01b8bd629a74f410632
brianium/tomaat
slack.cljs
(ns tomaat.worker.slack (:require-macros [cljs.core.async.macros :refer [go]]) (:require [cljs-http.client :as http] [cljs.core.async :refer [<!]] [goog.uri.utils :as uri] [tomaat.data :as data])) (defn query "Creates encoded query string params from a hash map" [params] (->> params clj->js (uri/appendParamsFromMap ""))) (defn encode-json "Converts a hash map to json and encodes the whole structure" [data] (.stringify js/JSON (clj->js data))) (defn url "Create a slack api url" [action params] (-> "/" (str action) (str (query params)))) (defn request "Performs an http get request and returns a core.async channel" [action params] (http/get (url action params))) (defn with-token "Executes the given function if a slack token has been stored" [fn-request] (let [settings (data/read)] (when-let [token (:token settings)] (fn-request token)))) (defn with-dnd "Executes the given function if the dnd settingh has been stored" [dnd-function] (let [settings (data/read) token (:token settings) dnd? (:dnd settings)] (when (and token dnd?) (dnd-function token)))) (defn start-dnd "Turns on Do Not Disturb mode for the user" [] (with-dnd #(request "dnd.setSnooze" {:num_minutes 25 :token %}))) (defn end-dnd "Ends the user's Do Not Disturb session immediately" [] (with-dnd #(request "dnd.endDnd" {:token %}))) (defn update-profile "Updates token user's profile with the given text and emoji" [text emoji] (with-token #(request "users.profile.set" {:profile (encode-json {:status_text text :status_emoji emoji}) :token %}))) (defn start-pomodoro "Updates the token user's profile with pom text and a tomato!" [event id] (update-profile "pom party" ":tomato:") (start-dnd)) (defn stop-pomodoro "Stopping the pomodoro clears the user profile of any pom related business" ([] (update-profile "" "") (end-dnd)) ([event id] (stop-pomodoro))) (defn post-notification "Notifies the user's slackbot channel that the pom is complete and it's time to take a break from all their labors." [token] (go (let [response (<! (request "auth.test" {:token token})) user-id (get-in response [:body :user_id])] (request "chat.postMessage" {:token token :channel user-id :as_user false :icon_emoji ":tomato:" :text "Pom complete! Time to take a break :sweat_smile:"})))) (defn notify "Notifies user via slackbot if configured to do so" [] (let [settings (data/read) token (:token settings) slack-me? (:slack-me settings)] (when (and token slack-me?) (post-notification token)))) ;;; Completing a pomodoro involves stopping it and notifiying the user (def complete-pomodoro (juxt stop-pomodoro notify))
null
https://raw.githubusercontent.com/brianium/tomaat/990cb7c496796c567613ec7ea8c9855f397c45c2/src/tomaat/worker/slack.cljs
clojure
Completing a pomodoro involves stopping it and notifiying the user
(ns tomaat.worker.slack (:require-macros [cljs.core.async.macros :refer [go]]) (:require [cljs-http.client :as http] [cljs.core.async :refer [<!]] [goog.uri.utils :as uri] [tomaat.data :as data])) (defn query "Creates encoded query string params from a hash map" [params] (->> params clj->js (uri/appendParamsFromMap ""))) (defn encode-json "Converts a hash map to json and encodes the whole structure" [data] (.stringify js/JSON (clj->js data))) (defn url "Create a slack api url" [action params] (-> "/" (str action) (str (query params)))) (defn request "Performs an http get request and returns a core.async channel" [action params] (http/get (url action params))) (defn with-token "Executes the given function if a slack token has been stored" [fn-request] (let [settings (data/read)] (when-let [token (:token settings)] (fn-request token)))) (defn with-dnd "Executes the given function if the dnd settingh has been stored" [dnd-function] (let [settings (data/read) token (:token settings) dnd? (:dnd settings)] (when (and token dnd?) (dnd-function token)))) (defn start-dnd "Turns on Do Not Disturb mode for the user" [] (with-dnd #(request "dnd.setSnooze" {:num_minutes 25 :token %}))) (defn end-dnd "Ends the user's Do Not Disturb session immediately" [] (with-dnd #(request "dnd.endDnd" {:token %}))) (defn update-profile "Updates token user's profile with the given text and emoji" [text emoji] (with-token #(request "users.profile.set" {:profile (encode-json {:status_text text :status_emoji emoji}) :token %}))) (defn start-pomodoro "Updates the token user's profile with pom text and a tomato!" [event id] (update-profile "pom party" ":tomato:") (start-dnd)) (defn stop-pomodoro "Stopping the pomodoro clears the user profile of any pom related business" ([] (update-profile "" "") (end-dnd)) ([event id] (stop-pomodoro))) (defn post-notification "Notifies the user's slackbot channel that the pom is complete and it's time to take a break from all their labors." [token] (go (let [response (<! (request "auth.test" {:token token})) user-id (get-in response [:body :user_id])] (request "chat.postMessage" {:token token :channel user-id :as_user false :icon_emoji ":tomato:" :text "Pom complete! Time to take a break :sweat_smile:"})))) (defn notify "Notifies user via slackbot if configured to do so" [] (let [settings (data/read) token (:token settings) slack-me? (:slack-me settings)] (when (and token slack-me?) (post-notification token)))) (def complete-pomodoro (juxt stop-pomodoro notify))
416e671af69185c982303d226333910c8d4032ab82ec3ddd0fc44e9ed1315b82
oden-lang/oden
PolymorphicSpec.hs
module Oden.Type.PolymorphicSpec where import Oden.Identifier import Oden.Metadata import Oden.QualifiedName import Oden.SourceInfo import Oden.Type.Polymorphic import Test.Hspec missing :: Metadata SourceInfo missing = Metadata Missing named :: String -> Type -> Type named = TNamed missing . nameInUniverse typeInt :: Type typeInt = TCon missing (nameInUniverse "int") spec = do describe "underlying" $ do it "returns unnamed types as-is" $ underlying typeInt `shouldBe` typeInt it "returns the underlying named type one level down" $ underlying (named "A" typeInt) `shouldBe` typeInt it "returns the underlying named type one level down" $ underlying (named "A" $ named "B" typeInt) `shouldBe` typeInt describe "rowToList" $ do it "return an empty list for an empty row" $ rowToList (REmpty missing) `shouldBe` [] it "return a one-element list for a single extension" $ rowToList (RExtension missing (Identifier "foo") typeInt (REmpty missing)) `shouldBe` [(Identifier "foo", typeInt)] it "return a list with a pair for each extension" $ rowToList (RExtension missing (Identifier "foo") typeInt (RExtension missing (Identifier "bar") typeInt (REmpty missing))) `shouldBe` [(Identifier "foo", typeInt), (Identifier "bar", typeInt)] it "ignore row variable" $ rowToList (RExtension missing (Identifier "foo") typeInt (RExtension missing (Identifier "bar") typeInt (TVar missing (TV "a")))) `shouldBe` [(Identifier "foo", typeInt), (Identifier "bar", typeInt)]
null
https://raw.githubusercontent.com/oden-lang/oden/10c99b59c8b77c4db51ade9a4d8f9573db7f4d14/test/Oden/Type/PolymorphicSpec.hs
haskell
module Oden.Type.PolymorphicSpec where import Oden.Identifier import Oden.Metadata import Oden.QualifiedName import Oden.SourceInfo import Oden.Type.Polymorphic import Test.Hspec missing :: Metadata SourceInfo missing = Metadata Missing named :: String -> Type -> Type named = TNamed missing . nameInUniverse typeInt :: Type typeInt = TCon missing (nameInUniverse "int") spec = do describe "underlying" $ do it "returns unnamed types as-is" $ underlying typeInt `shouldBe` typeInt it "returns the underlying named type one level down" $ underlying (named "A" typeInt) `shouldBe` typeInt it "returns the underlying named type one level down" $ underlying (named "A" $ named "B" typeInt) `shouldBe` typeInt describe "rowToList" $ do it "return an empty list for an empty row" $ rowToList (REmpty missing) `shouldBe` [] it "return a one-element list for a single extension" $ rowToList (RExtension missing (Identifier "foo") typeInt (REmpty missing)) `shouldBe` [(Identifier "foo", typeInt)] it "return a list with a pair for each extension" $ rowToList (RExtension missing (Identifier "foo") typeInt (RExtension missing (Identifier "bar") typeInt (REmpty missing))) `shouldBe` [(Identifier "foo", typeInt), (Identifier "bar", typeInt)] it "ignore row variable" $ rowToList (RExtension missing (Identifier "foo") typeInt (RExtension missing (Identifier "bar") typeInt (TVar missing (TV "a")))) `shouldBe` [(Identifier "foo", typeInt), (Identifier "bar", typeInt)]
975353b59e5c3ae5df97649b17feb7b4e4d310481149f1e5707088cc822dc0c1
let-def/menhir
preFront.ml
(**************************************************************************) (* *) Menhir (* *) , INRIA Rocquencourt , PPS , Université Paris Diderot (* *) Copyright 2005 - 2008 Institut National de Recherche en Informatique (* et en Automatique. All rights reserved. This file is distributed *) under the terms of the Q Public License version 1.0 , with the change (* described in file LICENSE. *) (* *) (**************************************************************************) open Printf open Syntax let read_whole_file filename = Open the file in text mode , so that ( under Windows ) CRLF is converted to LF . This guarantees that one byte is one character and seems to be required in order to report accurate positions . This guarantees that one byte is one character and seems to be required in order to report accurate positions. *) let channel = open_in filename in (* The standard library functions [pos_in] and [seek_in] do not work correctly when CRLF conversion is being performed, so we abandon their use. (They were used to go and extract the text of semantic actions.) Instead we load the entire file into memory up front, and work with a string. *) The standard library function [ in_channel_length ] does not work correctly when CRLF conversion is being performed , so we do not use it to read the whole file . And the standard library function [ Buffer.add_channel ] uses [ really_input ] internally , so we can not use it either . . when CRLF conversion is being performed, so we do not use it to read the whole file. And the standard library function [Buffer.add_channel] uses [really_input] internally, so we cannot use it either. Bummer. *) let block_size = 16384 in let b = Buffer.create block_size in let s = String.create block_size in let rec loop () = let read = input channel s 0 block_size in if read > 0 then begin Buffer.add_substring b s 0 read; loop() end in loop(); close_in channel; Buffer.contents b let load_partial_grammar filename = let validExt = if Settings.coq then ".vy" else ".mly" in if Filename.check_suffix filename validExt then Error.set_filename filename else Error.error [] (sprintf "argument file names should end in %s. \"%s\" is not accepted." validExt filename); try let contents = read_whole_file filename in Error.file_contents := Some contents; let lexbuf = Lexing.from_string contents in lexbuf.Lexing.lex_curr_p <- { Lexing.pos_fname = filename; Lexing.pos_lnum = 1; Lexing.pos_bol = 0; Lexing.pos_cnum = 0 }; let grammar = { (Parser.grammar Lexer.main lexbuf) with ConcreteSyntax.pg_filename = filename } in Error.file_contents := None; If there were errors during parsing , stop . This has to be done explicitly here because the parser performs error recovery and does not die at the first error . One could even go further and attempt to work with the grammar in spite of the parse errors , but we choose not to . explicitly here because the parser performs error recovery and does not die at the first error. One could even go further and attempt to work with the grammar in spite of the parse errors, but we choose not to. *) if Error.errors () then exit 1 else grammar with Sys_error msg -> Error.error [] msg let partial_grammars = List.map load_partial_grammar Settings.filenames let () = Time.tick "Lexing and parsing" let parameterized_grammar = PartialGrammar.join_partial_grammars partial_grammars let grammar = ParameterizedGrammar.expand parameterized_grammar let () = Time.tick "Joining and expanding"
null
https://raw.githubusercontent.com/let-def/menhir/e8ba7bef219acd355798072c42abbd11335ecf09/src/preFront.ml
ocaml
************************************************************************ et en Automatique. All rights reserved. This file is distributed described in file LICENSE. ************************************************************************ The standard library functions [pos_in] and [seek_in] do not work correctly when CRLF conversion is being performed, so we abandon their use. (They were used to go and extract the text of semantic actions.) Instead we load the entire file into memory up front, and work with a string.
Menhir , INRIA Rocquencourt , PPS , Université Paris Diderot Copyright 2005 - 2008 Institut National de Recherche en Informatique under the terms of the Q Public License version 1.0 , with the change open Printf open Syntax let read_whole_file filename = Open the file in text mode , so that ( under Windows ) CRLF is converted to LF . This guarantees that one byte is one character and seems to be required in order to report accurate positions . This guarantees that one byte is one character and seems to be required in order to report accurate positions. *) let channel = open_in filename in The standard library function [ in_channel_length ] does not work correctly when CRLF conversion is being performed , so we do not use it to read the whole file . And the standard library function [ Buffer.add_channel ] uses [ really_input ] internally , so we can not use it either . . when CRLF conversion is being performed, so we do not use it to read the whole file. And the standard library function [Buffer.add_channel] uses [really_input] internally, so we cannot use it either. Bummer. *) let block_size = 16384 in let b = Buffer.create block_size in let s = String.create block_size in let rec loop () = let read = input channel s 0 block_size in if read > 0 then begin Buffer.add_substring b s 0 read; loop() end in loop(); close_in channel; Buffer.contents b let load_partial_grammar filename = let validExt = if Settings.coq then ".vy" else ".mly" in if Filename.check_suffix filename validExt then Error.set_filename filename else Error.error [] (sprintf "argument file names should end in %s. \"%s\" is not accepted." validExt filename); try let contents = read_whole_file filename in Error.file_contents := Some contents; let lexbuf = Lexing.from_string contents in lexbuf.Lexing.lex_curr_p <- { Lexing.pos_fname = filename; Lexing.pos_lnum = 1; Lexing.pos_bol = 0; Lexing.pos_cnum = 0 }; let grammar = { (Parser.grammar Lexer.main lexbuf) with ConcreteSyntax.pg_filename = filename } in Error.file_contents := None; If there were errors during parsing , stop . This has to be done explicitly here because the parser performs error recovery and does not die at the first error . One could even go further and attempt to work with the grammar in spite of the parse errors , but we choose not to . explicitly here because the parser performs error recovery and does not die at the first error. One could even go further and attempt to work with the grammar in spite of the parse errors, but we choose not to. *) if Error.errors () then exit 1 else grammar with Sys_error msg -> Error.error [] msg let partial_grammars = List.map load_partial_grammar Settings.filenames let () = Time.tick "Lexing and parsing" let parameterized_grammar = PartialGrammar.join_partial_grammars partial_grammars let grammar = ParameterizedGrammar.expand parameterized_grammar let () = Time.tick "Joining and expanding"
cd0db99ab6c3443cf77a70750cde6104de73ec8ea16f854b235c3220d7406393
erleans/pgo
pgo_query_cache.erl
-module(pgo_query_cache). -export([start_link/0, lookup/2, insert/3, reset/0, delete/1]). -export([init/1, callback_mode/0, ready/3, terminate/3]). -record(data, {}). start_link() -> gen_statem:start_link({local, ?MODULE}, ?MODULE, [], []). lookup(Pool, Query) -> case ets:lookup(?MODULE, {Pool, Query}) of [{_Query, RowDescription}] -> RowDescription; [] -> not_found end. insert(Pool, Query, RowDescription) -> ets:insert(?MODULE, {{Pool, Query}, RowDescription}). reset() -> gen_statem:call(?MODULE, reset). delete(Query) -> gen_statem:cast(?MODULE, {delete, Query}). init([]) -> erlang:process_flag(trap_exit, true), ets:new(?MODULE, [named_table, public, {read_concurrency, true}]), {ok, ready, #data{}}. callback_mode() -> state_functions. ready(_, _, _Data=#data{}) -> keep_state_and_data. terminate(_, _, #data{}) -> ok.
null
https://raw.githubusercontent.com/erleans/pgo/1c9a0992bc41f2ecd0328fbee1151b75843ac979/src/pgo_query_cache.erl
erlang
-module(pgo_query_cache). -export([start_link/0, lookup/2, insert/3, reset/0, delete/1]). -export([init/1, callback_mode/0, ready/3, terminate/3]). -record(data, {}). start_link() -> gen_statem:start_link({local, ?MODULE}, ?MODULE, [], []). lookup(Pool, Query) -> case ets:lookup(?MODULE, {Pool, Query}) of [{_Query, RowDescription}] -> RowDescription; [] -> not_found end. insert(Pool, Query, RowDescription) -> ets:insert(?MODULE, {{Pool, Query}, RowDescription}). reset() -> gen_statem:call(?MODULE, reset). delete(Query) -> gen_statem:cast(?MODULE, {delete, Query}). init([]) -> erlang:process_flag(trap_exit, true), ets:new(?MODULE, [named_table, public, {read_concurrency, true}]), {ok, ready, #data{}}. callback_mode() -> state_functions. ready(_, _, _Data=#data{}) -> keep_state_and_data. terminate(_, _, #data{}) -> ok.
f755effd7a596a787d6a6c7257c7e45ad9b89e95d4b355a90f485ceb974468ba
iand675/hs-opentelemetry
Resource_Fields.hs
{- This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. -} {-# LANGUAGE BangPatterns #-} {- This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. -} # LANGUAGE DataKinds # {- This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. -} # LANGUAGE DerivingStrategies # {- This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. -} # LANGUAGE FlexibleContexts # {- This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. -} # LANGUAGE FlexibleInstances # {- This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. -} # LANGUAGE GeneralizedNewtypeDeriving # {- This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. -} # LANGUAGE MagicHash # {- This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. -} # LANGUAGE MultiParamTypeClasses # {- This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. -} {-# LANGUAGE OverloadedStrings #-} {- This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. -} # LANGUAGE PatternSynonyms # {- This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. -} # LANGUAGE ScopedTypeVariables # {- This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. -} # LANGUAGE TypeApplications # {- This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. -} # LANGUAGE TypeFamilies # {- This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. -} # LANGUAGE UndecidableInstances # {- This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. -} # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -Wno - dodgy - exports # {-# OPTIONS_GHC -Wno-duplicate-exports #-} {-# OPTIONS_GHC -Wno-unused-imports #-} module Proto.Opentelemetry.Proto.Resource.V1.Resource_Fields where import qualified Data.ProtoLens.Runtime.Data.ByteString as Data.ByteString import qualified Data.ProtoLens.Runtime.Data.ByteString.Char8 as Data.ByteString.Char8 import qualified Data.ProtoLens.Runtime.Data.Int as Data.Int import qualified Data.ProtoLens.Runtime.Data.Map as Data.Map import qualified Data.ProtoLens.Runtime.Data.Monoid as Data.Monoid import qualified Data.ProtoLens.Runtime.Data.ProtoLens as Data.ProtoLens import qualified Data.ProtoLens.Runtime.Data.ProtoLens.Encoding.Bytes as Data.ProtoLens.Encoding.Bytes import qualified Data.ProtoLens.Runtime.Data.ProtoLens.Encoding.Growing as Data.ProtoLens.Encoding.Growing import qualified Data.ProtoLens.Runtime.Data.ProtoLens.Encoding.Parser.Unsafe as Data.ProtoLens.Encoding.Parser.Unsafe import qualified Data.ProtoLens.Runtime.Data.ProtoLens.Encoding.Wire as Data.ProtoLens.Encoding.Wire import qualified Data.ProtoLens.Runtime.Data.ProtoLens.Field as Data.ProtoLens.Field import qualified Data.ProtoLens.Runtime.Data.ProtoLens.Message.Enum as Data.ProtoLens.Message.Enum import qualified Data.ProtoLens.Runtime.Data.ProtoLens.Service.Types as Data.ProtoLens.Service.Types import qualified Data.ProtoLens.Runtime.Data.Text as Data.Text import qualified Data.ProtoLens.Runtime.Data.Text.Encoding as Data.Text.Encoding import qualified Data.ProtoLens.Runtime.Data.Vector as Data.Vector import qualified Data.ProtoLens.Runtime.Data.Vector.Generic as Data.Vector.Generic import qualified Data.ProtoLens.Runtime.Data.Vector.Unboxed as Data.Vector.Unboxed import qualified Data.ProtoLens.Runtime.Data.Word as Data.Word import qualified Data.ProtoLens.Runtime.Lens.Family2 as Lens.Family2 import qualified Data.ProtoLens.Runtime.Lens.Family2.Unchecked as Lens.Family2.Unchecked import qualified Data.ProtoLens.Runtime.Prelude as Prelude import qualified Data.ProtoLens.Runtime.Text.Read as Text.Read import qualified Proto.Opentelemetry.Proto.Common.V1.Common attributes :: forall f s a. ( Prelude.Functor f , Data.ProtoLens.Field.HasField s "attributes" a ) => Lens.Family2.LensLike' f s a attributes = Data.ProtoLens.Field.field @"attributes" droppedAttributesCount :: forall f s a. ( Prelude.Functor f , Data.ProtoLens.Field.HasField s "droppedAttributesCount" a ) => Lens.Family2.LensLike' f s a droppedAttributesCount = Data.ProtoLens.Field.field @"droppedAttributesCount" vec'attributes :: forall f s a. ( Prelude.Functor f , Data.ProtoLens.Field.HasField s "vec'attributes" a ) => Lens.Family2.LensLike' f s a vec'attributes = Data.ProtoLens.Field.field @"vec'attributes"
null
https://raw.githubusercontent.com/iand675/hs-opentelemetry/b08550db292ca0d8b9ce9156988e6d08dd6a2e61/otlp/src/Proto/Opentelemetry/Proto/Resource/V1/Resource_Fields.hs
haskell
This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. # LANGUAGE BangPatterns # This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. # LANGUAGE OverloadedStrings # This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. This file was auto-generated from opentelemetry/proto/resource/v1/resource.proto by the proto-lens-protoc program. # OPTIONS_GHC -Wno-duplicate-exports # # OPTIONS_GHC -Wno-unused-imports #
# LANGUAGE DataKinds # # LANGUAGE DerivingStrategies # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE MagicHash # # LANGUAGE MultiParamTypeClasses # # LANGUAGE PatternSynonyms # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -Wno - dodgy - exports # module Proto.Opentelemetry.Proto.Resource.V1.Resource_Fields where import qualified Data.ProtoLens.Runtime.Data.ByteString as Data.ByteString import qualified Data.ProtoLens.Runtime.Data.ByteString.Char8 as Data.ByteString.Char8 import qualified Data.ProtoLens.Runtime.Data.Int as Data.Int import qualified Data.ProtoLens.Runtime.Data.Map as Data.Map import qualified Data.ProtoLens.Runtime.Data.Monoid as Data.Monoid import qualified Data.ProtoLens.Runtime.Data.ProtoLens as Data.ProtoLens import qualified Data.ProtoLens.Runtime.Data.ProtoLens.Encoding.Bytes as Data.ProtoLens.Encoding.Bytes import qualified Data.ProtoLens.Runtime.Data.ProtoLens.Encoding.Growing as Data.ProtoLens.Encoding.Growing import qualified Data.ProtoLens.Runtime.Data.ProtoLens.Encoding.Parser.Unsafe as Data.ProtoLens.Encoding.Parser.Unsafe import qualified Data.ProtoLens.Runtime.Data.ProtoLens.Encoding.Wire as Data.ProtoLens.Encoding.Wire import qualified Data.ProtoLens.Runtime.Data.ProtoLens.Field as Data.ProtoLens.Field import qualified Data.ProtoLens.Runtime.Data.ProtoLens.Message.Enum as Data.ProtoLens.Message.Enum import qualified Data.ProtoLens.Runtime.Data.ProtoLens.Service.Types as Data.ProtoLens.Service.Types import qualified Data.ProtoLens.Runtime.Data.Text as Data.Text import qualified Data.ProtoLens.Runtime.Data.Text.Encoding as Data.Text.Encoding import qualified Data.ProtoLens.Runtime.Data.Vector as Data.Vector import qualified Data.ProtoLens.Runtime.Data.Vector.Generic as Data.Vector.Generic import qualified Data.ProtoLens.Runtime.Data.Vector.Unboxed as Data.Vector.Unboxed import qualified Data.ProtoLens.Runtime.Data.Word as Data.Word import qualified Data.ProtoLens.Runtime.Lens.Family2 as Lens.Family2 import qualified Data.ProtoLens.Runtime.Lens.Family2.Unchecked as Lens.Family2.Unchecked import qualified Data.ProtoLens.Runtime.Prelude as Prelude import qualified Data.ProtoLens.Runtime.Text.Read as Text.Read import qualified Proto.Opentelemetry.Proto.Common.V1.Common attributes :: forall f s a. ( Prelude.Functor f , Data.ProtoLens.Field.HasField s "attributes" a ) => Lens.Family2.LensLike' f s a attributes = Data.ProtoLens.Field.field @"attributes" droppedAttributesCount :: forall f s a. ( Prelude.Functor f , Data.ProtoLens.Field.HasField s "droppedAttributesCount" a ) => Lens.Family2.LensLike' f s a droppedAttributesCount = Data.ProtoLens.Field.field @"droppedAttributesCount" vec'attributes :: forall f s a. ( Prelude.Functor f , Data.ProtoLens.Field.HasField s "vec'attributes" a ) => Lens.Family2.LensLike' f s a vec'attributes = Data.ProtoLens.Field.field @"vec'attributes"
6f64754a3c1f74019ac38496e188e81fe5c1c4b7eaf6f5939035ffe993d597bc
Mallku2/lua-redex-model
grammar.rkt
#lang racket (require redex) Core language grammar definition (define-language core-lang [s \; break (return e) functioncall ($builtIn Name (e ...)) ((var ...) = (e ...)) (do s end) (if e then s else s end) (while e do s end) (local (Name ...) = (e ...) in s end) (s_1 s_2 ...) ; Run-time statements (< e ... >) ((((v \[ v \])) = (v))specCondLabel) ($err v) ((s)ProtectedMode) ((s)ProtectedMode v) ; xpcall's protected mode ((s)Return) ((s)Break) ((v (v ...))WrongFunCall) ($nextItWhile e do s end)] [specCondLabel FieldAssignWrongKey FieldAssignOverNonTable KeyNotFound NonTableIndexed ArithWrongOps StrConcatWrongOps EqFail OrdCompWrongOps NegWrongOp StrLenWrongOp] [Boolean true false] [v nil Boolean Number String objref] [vlist (v ...)] ; Variables' Identifiers' syntactic category, to ease the definition of the ; substitution function. [id Name <<<] [parameters (Name ...) (Name ... <<<)] ; This syntactic category is added to ease meta-functions' definitions. [functiondef (function Name parameters s end)] [e v <<< var ; To allow function calls in protected mode, in place of expressions. functioncall ($builtIn Name (e ...)) (\( e \)) tableconstructor functiondef (e binop e) (unop e) ; Run-time expressions r (< e ... >) ($err v) ((s)FunCall) ; To allow expressions like ((((e)FunctionCall))FunctionCall) ((e)FunCall) ((e)ProtectedMode) ((v \[ v \])specCondLabel) ((v binop v)specCondLabel) ((unop v)specCondLabel) ((v (v ...))WrongFunCall)] [functioncall (e (e ...)) (e : Name (e ...))] [tableconstructor (\{ field ... \})] [evaluatedtable (\{ efield ... \})] [arithop + - * / ^ %] [relop < <= > >=] ; Not short-circuit binop [strictbinop arithop relop == ..] [binop strictbinop and or] [unop - not \#] ; Name can be anything except a keyword of the language [Name variable-not-otherwise-mentioned] ( \ ( exp \ ) ) ] [var Name (e \[ e \]) ; run-time expression evar] [evar r (v \[ v \])] [field (\[ e \] = e) ; We need to allow fields like this e] [efield (\[ v \] = v) v] ; Number represents real (double-precision floating-point) numbers [Number real] [String string] ; ; ; ; ;;;;; ; ; ;; ; ; ; ; ;;;;;; ;;;; ;;;; ;;;; ;;;; ; ;; ; ;; ;; ;; ; ;; ;; ; ; ; ;;;;; ; ; ; ; ; ; ; ; ;; ; ; ; ; ;;;;;; ;;;; ; ; ; ; ; ; ; ; ; ; ;; ; ;; ;; ; ;; ; ; ; ; ;;;;; ;;; ;;;; ; ;;;; ;;;; ; ; ; ; This syntactic category is added to ease meta-functions' definitions. [intreptable (tableconstructor objref) (tableconstructor nil)] ; Values that we can store in an object store [object functiondef intreptable] [r (ref number)] [objref (objr number)] [rst (r v)] [σ ((r v) ...)] [objrefst (objref object)] [θ ((objref object) ...)] ; ; ; ; ;;;;;;; ;;;; ; ; ; ; ; ; ; ; ; ; ; ;;;; ; ;;; ;;;;;; ;; ;; ; ; ;; ;; ; ;; ;; ;; ; ; ; ; ; ;;;;;;; ; ; ; ; ; ; ; ; ;; ; ; ; ; ; ; ; ; ; ; ;; ; ; ;;;; ; ; ; ; ; ; ;; ; ; ;; ;; ; ; ;; ;; ; ; ; ; ; ; ;;;;;;; ;; ;; ;;;; ;;;; ; ; ;;; ;; ;; ; ; ; ; No labelled-blocks, no protected mode [Elenlnp (v ... Enlnp e ...)] [Enlnp hole ; Statements (do Enlnp end) (if Enlnp then s else s end) (local (Name ...) = Elenlnp in s end) ((evar ... (Enlnp \[ e \]) var ...) = (e ...)) ((evar ... (v \[ Enlnp \]) var ...) = (e ...)) ((evar ...) = Elenlnp) (break Name Enlnp) (return Enlnp) (Enlnp s ...) ; Function call, method call, built-in services (Enlnp (e ...)) (v Elenlnp) ($builtIn Name Elenlnp) (Enlnp : Name (e ...)) ; Expressions ((Enlnp)FunCall) (\( Enlnp \)) (Enlnp binop e) (v strictbinop Enlnp) (unop Enlnp) (< v ... Enlnp e ... >) (\{ efield ... (\[ Enlnp \] = e) field ... \}) (\{ efield ... (\[ v \] = Enlnp) field ... \}) (\{ efield ... Enlnp field ... \}) (Enlnp \[ e \]) (v \[ Enlnp \])] ; No labelled-blocks Simple induction on the structure helps to prove that an Elf is the ; desired evaluation context (for the inductive case: think that any evaluation context of the desired category , that has one or more ( ( ... ) ProtectedMode ) phrases , begins being a Enlnp ( even it could be a hole ) , then the first ( ( ... ) ) appears , and what 's left is , by i.h . , an Elf context . That 's what the second production ; describes. [Elf Enlnp (in-hole Enlnp ((Elf)ProtectedMode))] ; No Protected Mode [Enp Enlnp (in-hole Enlnp ((Enp)Break)) (in-hole Enlnp ((Enp)Return))] ; All possible evaluation contexts [E Enlnp (in-hole Enlnp ((E)Return)) (in-hole Enlnp ((Enp)Break)) (in-hole Enlnp ((E)ProtectedMode))] ; List of expressions where a tuple is truncated [Etel (v ... hole e_1 e_2 ...)] ; Immediate evaluation contexts where a tuple is truncated Propertie : it must occur that there is no sub - phrase of this evaluation ; contexts that is also an evaluation context: for example, ( break Name ( < Etel > ) ) is not a valid member of Et , as ( < Etel > ) is a member of Et . [Et (if hole then s else s_2 end) (local (Name ...) = Etel in s end) ((evar ... (hole \[ e \]) var ...) = (e ...)) ((evar ... (v \[ hole \]) var ...) = (e ...)) ((evar ...) = Etel) (hole (e ...)) (v Etel) ($builtIn Name Etel) (hole : Name (e ...)) (hole binop e) (v strictbinop hole) (unop hole) (< v ... hole e_1 e_2 ... >) (\{ efield ... (\[ hole \] = e) field ... \}) (\{ efield ... (\[ v \] = hole) field ... \}) (\{ efield ... hole field_1 field ... \}) (hole \[ e \]) (v \[ hole \])] ; List of expressions where a tuple is unwrapped [Euel (v ... hole)] ; Immediate evaluation contexts where a tuple is unwrapped [Eu (local (Name ...) = Euel in s end) ((evar ...) = Euel) (v Euel) ($builtIn Name Euel) (< v ... hole >) (\{ efield ... hole \})] ; Evaluation contexts where tuples are discarded [Ed hole (do Ed end) (Ed s_1 s_2 ...) ((Ed)Break)] ) ; Export core-lang grammar definition (provide core-lang)
null
https://raw.githubusercontent.com/Mallku2/lua-redex-model/13a1b8cacbdc72a1b5cb1a1f140f21cc974d71c3/grammar.rkt
racket
Run-time statements xpcall's protected mode Variables' Identifiers' syntactic category, to ease the definition of the substitution function. This syntactic category is added to ease meta-functions' definitions. To allow function calls in protected mode, in place of expressions. Run-time expressions To allow expressions like ((((e)FunctionCall))FunctionCall) Not short-circuit binop Name can be anything except a keyword of the language run-time expression We need to allow fields like this Number represents real (double-precision floating-point) numbers ;;;;; ; ;; ; ; ; ;;;;;; ;;;; ;;;; ;;;; ;;;; ;; ; ;; ;; ;; ; ;; ;; ; ; ;;;;; ; ; ; ; ; ; ; ;; ; ; ; ; ;;;;;; ;;;; ; ; ; ; ; ; ; ; ;; ; ;; ;; ; ;; ; ; ; ;;;;; ;;; ;;;; ; ;;;; ;;;; This syntactic category is added to ease meta-functions' definitions. Values that we can store in an object store ;;;;;;; ;;;; ; ; ; ; ; ; ; ; ; ;;;; ; ;;; ;;;;;; ;; ;; ; ;; ;; ; ;; ;; ;; ; ; ; ; ;;;;;;; ; ; ; ; ; ; ; ; ;; ; ; ; ; ; ; ; ; ; ;; ; ;;;; ; ; ; ; ; ; ;; ; ;; ;; ; ; ;; ;; ; ; ; ; ; ;;;;;;; ;; ;; ;;;; ;;;; ; ; ;;; ;; ;; No labelled-blocks, no protected mode Statements Function call, method call, built-in services Expressions No labelled-blocks desired evaluation context (for the inductive case: think that any evaluation describes. No Protected Mode All possible evaluation contexts List of expressions where a tuple is truncated Immediate evaluation contexts where a tuple is truncated contexts that is also an evaluation context: for example, List of expressions where a tuple is unwrapped Immediate evaluation contexts where a tuple is unwrapped Evaluation contexts where tuples are discarded Export core-lang grammar definition
#lang racket (require redex) Core language grammar definition (define-language core-lang break (return e) functioncall ($builtIn Name (e ...)) ((var ...) = (e ...)) (do s end) (if e then s else s end) (while e do s end) (local (Name ...) = (e ...) in s end) (s_1 s_2 ...) (< e ... >) ((((v \[ v \])) = (v))specCondLabel) ($err v) ((s)ProtectedMode) ((s)Return) ((s)Break) ((v (v ...))WrongFunCall) ($nextItWhile e do s end)] [specCondLabel FieldAssignWrongKey FieldAssignOverNonTable KeyNotFound NonTableIndexed ArithWrongOps StrConcatWrongOps EqFail OrdCompWrongOps NegWrongOp StrLenWrongOp] [Boolean true false] [v nil Boolean Number String objref] [vlist (v ...)] [id Name <<<] [parameters (Name ...) (Name ... <<<)] [functiondef (function Name parameters s end)] [e v <<< var functioncall ($builtIn Name (e ...)) (\( e \)) tableconstructor functiondef (e binop e) (unop e) r (< e ... >) ($err v) ((s)FunCall) ((e)FunCall) ((e)ProtectedMode) ((v \[ v \])specCondLabel) ((v binop v)specCondLabel) ((unop v)specCondLabel) ((v (v ...))WrongFunCall)] [functioncall (e (e ...)) (e : Name (e ...))] [tableconstructor (\{ field ... \})] [evaluatedtable (\{ efield ... \})] [arithop + - * / ^ %] [relop < <= > >=] [strictbinop arithop relop == ..] [binop strictbinop and or] [unop - not \#] [Name variable-not-otherwise-mentioned] ( \ ( exp \ ) ) ] [var Name (e \[ e \]) evar] [evar r (v \[ v \])] [field (\[ e \] = e) e] [efield (\[ v \] = v) v] [Number real] [String string] [intreptable (tableconstructor objref) (tableconstructor nil)] [object functiondef intreptable] [r (ref number)] [objref (objr number)] [rst (r v)] [σ ((r v) ...)] [objrefst (objref object)] [θ ((objref object) ...)] [Elenlnp (v ... Enlnp e ...)] [Enlnp hole (do Enlnp end) (if Enlnp then s else s end) (local (Name ...) = Elenlnp in s end) ((evar ... (Enlnp \[ e \]) var ...) = (e ...)) ((evar ... (v \[ Enlnp \]) var ...) = (e ...)) ((evar ...) = Elenlnp) (break Name Enlnp) (return Enlnp) (Enlnp s ...) (Enlnp (e ...)) (v Elenlnp) ($builtIn Name Elenlnp) (Enlnp : Name (e ...)) ((Enlnp)FunCall) (\( Enlnp \)) (Enlnp binop e) (v strictbinop Enlnp) (unop Enlnp) (< v ... Enlnp e ... >) (\{ efield ... (\[ Enlnp \] = e) field ... \}) (\{ efield ... (\[ v \] = Enlnp) field ... \}) (\{ efield ... Enlnp field ... \}) (Enlnp \[ e \]) (v \[ Enlnp \])] Simple induction on the structure helps to prove that an Elf is the context of the desired category , that has one or more ( ( ... ) ProtectedMode ) phrases , begins being a Enlnp ( even it could be a hole ) , then the first ( ( ... ) ) appears , and what 's left is , by i.h . , an Elf context . That 's what the second production [Elf Enlnp (in-hole Enlnp ((Elf)ProtectedMode))] [Enp Enlnp (in-hole Enlnp ((Enp)Break)) (in-hole Enlnp ((Enp)Return))] [E Enlnp (in-hole Enlnp ((E)Return)) (in-hole Enlnp ((Enp)Break)) (in-hole Enlnp ((E)ProtectedMode))] [Etel (v ... hole e_1 e_2 ...)] Propertie : it must occur that there is no sub - phrase of this evaluation ( break Name ( < Etel > ) ) is not a valid member of Et , as ( < Etel > ) is a member of Et . [Et (if hole then s else s_2 end) (local (Name ...) = Etel in s end) ((evar ... (hole \[ e \]) var ...) = (e ...)) ((evar ... (v \[ hole \]) var ...) = (e ...)) ((evar ...) = Etel) (hole (e ...)) (v Etel) ($builtIn Name Etel) (hole : Name (e ...)) (hole binop e) (v strictbinop hole) (unop hole) (< v ... hole e_1 e_2 ... >) (\{ efield ... (\[ hole \] = e) field ... \}) (\{ efield ... (\[ v \] = hole) field ... \}) (\{ efield ... hole field_1 field ... \}) (hole \[ e \]) (v \[ hole \])] [Euel (v ... hole)] [Eu (local (Name ...) = Euel in s end) ((evar ...) = Euel) (v Euel) ($builtIn Name Euel) (< v ... hole >) (\{ efield ... hole \})] [Ed hole (do Ed end) (Ed s_1 s_2 ...) ((Ed)Break)] ) (provide core-lang)
84dbb10974589e66d905a0cf722f0b8d68f9b785ed4c7df2846ece49291791f2
smanek/trivial-lisp-webapp
request.lisp
-*- Mode : LISP ; Syntax : COMMON - LISP ; Package : HUNCHENTOOT ; Base : 10 -*- $ Header : /usr / local / cvsrep / hunchentoot / request.lisp , v 1.35 2008/02/13 16:02:18 edi Exp $ Copyright ( c ) 2004 - 2009 , Dr. . All rights reserved . ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :hunchentoot) (defclass request () ((acceptor :initarg :acceptor :documentation "The acceptor which created this request object." :reader request-acceptor) (headers-in :initarg :headers-in :documentation "An alist of the incoming headers." :reader headers-in) (method :initarg :method :documentation "The request method as a keyword." :reader request-method) (uri :initarg :uri :documentation "The request URI as a string." :reader request-uri) (server-protocol :initarg :server-protocol :documentation "The HTTP protocol as a keyword." :reader server-protocol) (remote-addr :initarg :remote-addr :documentation "The IP address of the client that initiated this request." :reader remote-addr) (remote-port :initarg :remote-port :documentation "The TCP port number of the client socket from which this request originated." :reader remote-port) (content-stream :initarg :content-stream :reader content-stream :documentation "A stream from which the request body can be read if there is one.") (cookies-in :initform nil :documentation "An alist of the cookies sent by the client." :reader cookies-in) (get-parameters :initform nil :documentation "An alist of the GET parameters sent by the client." :reader get-parameters) (post-parameters :initform nil :documentation "An alist of the POST parameters sent by the client." :reader post-parameters) (script-name :initform nil :documentation "The URI requested by the client without the query string." :reader script-name) (query-string :initform nil :documentation "The query string of this request." :reader query-string) (session :initform nil :accessor session :documentation "The session object associated with this request.") (aux-data :initform nil :accessor aux-data :documentation "Used to keep a user-modifiable alist with arbitrary data during the request.") (raw-post-data :initform nil :documentation "The raw string sent as the body of a POST request, populated only if not a multipart/form-data request.")) (:documentation "Objects of this class hold all the information about an incoming request. They are created automatically by acceptors and can be accessed by the corresponding handler. You should not mess with the slots of these objects directly, but you can subclass REQUEST in order to implement your own behaviour. See the REQUEST-CLASS slot of the ACCEPTOR class.")) (defgeneric process-request (request) (:documentation "This function is called by PROCESS-CONNECTION after the incoming headers have been read. It selects and calls a handler and sends the output of this handler to the client using START-OUTPUT. It also sets up simple error handling for the request handler. Note that PROCESS-CONNECTION is called once per connection and loops in case of a persistent connection while PROCESS-REQUEST is called anew for each request. Like PROCESS-CONNECTION, this might be a good place to introduce around methods which bind special variables or do other interesting things. The return value of this function is ignored.")) (defun convert-hack (string external-format) "The rfc2388 package is buggy in that it operates on a character stream and thus only accepts encodings which are 8 bit transparent. In order to support different encodings for parameter values submitted, we post process whatever string values the rfc2388 package has returned." (flex:octets-to-string (map '(vector (unsigned-byte 8) *) 'char-code string) :external-format external-format)) (defun parse-rfc2388-form-data (stream content-type-header external-format) "Creates an alist of POST parameters from the stream STREAM which is supposed to be of content type 'multipart/form-data'." (let* ((parsed-content-type-header (rfc2388:parse-header content-type-header :value)) (boundary (or (cdr (rfc2388:find-parameter "BOUNDARY" (rfc2388:header-parameters parsed-content-type-header))) (return-from parse-rfc2388-form-data)))) (loop for part in (rfc2388:parse-mime stream boundary) for headers = (rfc2388:mime-part-headers part) for content-disposition-header = (rfc2388:find-content-disposition-header headers) for name = (cdr (rfc2388:find-parameter "NAME" (rfc2388:header-parameters content-disposition-header))) when name collect (cons name (let ((contents (rfc2388:mime-part-contents part))) (if (pathnamep contents) (list contents (rfc2388:get-file-name headers) (rfc2388:content-type part :as-string t)) (convert-hack contents external-format))))))) (defun get-post-data (&key (request *request*) want-stream (already-read 0)) "Reads the request body from the stream and stores the raw contents \(as an array of octets) in the corresponding slot of the REQUEST object. Returns just the stream if WANT-STREAM is true. If there's a Content-Length header, it is assumed, that ALREADY-READ octets have already been read." (let* ((headers-in (headers-in request)) (content-length (when-let (content-length-header (cdr (assoc :content-length headers-in :test #'eq))) (parse-integer content-length-header :junk-allowed t))) (content-stream (content-stream request))) (setf (slot-value request 'raw-post-data) (cond (want-stream (let ((stream (make-flexi-stream content-stream :external-format +latin-1+))) (when content-length (setf (flexi-stream-bound stream) content-length)) stream)) ((and content-length (> content-length already-read)) (decf content-length already-read) (when (input-chunking-p) see RFC 2616 , section 4.4 (log-message :warning "Got Content-Length header although input chunking is on.")) (let ((content (make-array content-length :element-type 'octet))) (read-sequence content content-stream) content)) ((input-chunking-p) (loop with buffer = (make-array +buffer-length+ :element-type 'octet) with content = (make-array 0 :element-type 'octet :adjustable t) for index = 0 then (+ index pos) for pos = (read-sequence buffer content-stream) do (adjust-array content (+ index pos)) (replace content buffer :start1 index :end2 pos) while (= pos +buffer-length+) finally (return content))))))) (defmethod initialize-instance :after ((request request) &rest init-args) "The only initarg for a REQUEST object is :HEADERS-IN. All other slot values are computed in this :AFTER method." (declare (ignore init-args)) (with-slots (headers-in cookies-in get-parameters script-name query-string session) request (handler-case (progn (let* ((uri (request-uri request)) (match-start (position #\? uri))) (cond (match-start (setq script-name (subseq uri 0 match-start) query-string (subseq uri (1+ match-start)))) (t (setq script-name uri)))) ;; some clients (e.g. ASDF-INSTALL) send requests like " GET / foo.html HTTP/1.0 " ... (setq script-name (regex-replace "^https?://[^/]+" script-name "")) ;; compute GET parameters from query string and cookies from ;; the incoming 'Cookie' header (setq get-parameters (form-url-encoded-list-to-alist (split "&" query-string)) cookies-in (form-url-encoded-list-to-alist (split "\\s*[,;]\\s*" (cdr (assoc :cookie headers-in :test #'eq))) +utf-8+) session (session-verify request) *session* session)) (error (condition) (log-message :error "Error when creating REQUEST object: ~A" condition) ;; we assume it's not our fault... (setf (return-code*) +http-bad-request+))))) (defmethod process-request (request) "Standard implementation for processing a request. You should not change or replace this functionality unless you know what you're doing." (let (*tmp-files* *headers-sent*) (unwind-protect (with-mapped-conditions () (let* ((*request* request) (*within-request-p* t)) (multiple-value-bind (body error) (catch 'handler-done (invoke-process-request-with-error-handling *acceptor* *request* (lambda () ;; skip dispatch if bad request (when (eql (return-code *reply*) +http-ok+) ;; now do the work (funcall (acceptor-request-dispatcher *acceptor*) *request*))))) (when error (setf (return-code *reply*) +http-internal-server-error+)) (start-output :content (cond ((and error *show-lisp-errors-p*) (format nil "<pre>~A</pre>" (escape-for-html (format nil "~A" error)))) (error "An error has occured.") (t body)))))) (dolist (path *tmp-files*) (when (and (pathnamep path) (probe-file path)) the handler may have chosen to ( re)move the uploaded ;; file, so ignore errors that happen during deletion (ignore-errors (delete-file path))))))) (defun within-request-p () "True if we're in the context of a request, otherwise nil." *within-request-p*) (defun parse-multipart-form-data (request external-format) "Parse the REQUEST body as multipart/form-data, assuming that its content type has already been verified. Returns the form data as alist or NIL if there was no data or the data could not be parsed." (handler-case (let ((content-stream (make-flexi-stream (content-stream request) :external-format +latin-1+))) (prog1 (parse-rfc2388-form-data content-stream (header-in :content-type request) external-format) (let ((stray-data (get-post-data :already-read (flexi-stream-position content-stream)))) (when (and stray-data (plusp (length stray-data))) (hunchentoot-warn "~A octets of stray data after form-data sent by client." (length stray-data)))))) (error (condition) (log-message :error "While parsing multipart/form-data parameters: ~A" condition) nil))) (defun maybe-read-post-parameters (&key (request *request*) force external-format) "Make surce that any POST parameters in the REQUEST are parsed. The body of the request must be either application/x-www-form-urlencoded or multipart/form-data to be considered as containing POST parameters. If FORCE is true, parsing is done unconditionally. Otherwise, parsing will only be done if the RAW-POST-DATA slot in the REQUEST is false. EXTERNAL-FORMAT specifies the external format of the data in the request body. By default, the encoding is determined from the Content-Type header of the request or from *HUNCHENTOOT-DEFAULT-EXTERNAL-FORMAT* if none is found." (when (and (header-in :content-type request) (member (request-method request) *methods-for-post-parameters* :test #'eq) (or force (not (slot-value request 'raw-post-data))) ca n't reparse multipart posts , even when FORCEd (not (eq t (slot-value request 'raw-post-data)))) (unless (or (header-in :content-length request) (input-chunking-p)) (log-message :warning "Can't read request body because there's ~ no Content-Length header and input chunking is off.") (return-from maybe-read-post-parameters nil)) (handler-case (multiple-value-bind (type subtype charset) (parse-content-type (header-in :content-type request)) (let ((external-format (or external-format (when charset (handler-case (make-external-format charset :eol-style :lf) (error () (hunchentoot-warn "Ignoring ~ unknown character set ~A in request content type." charset)))) *hunchentoot-default-external-format*))) (setf (slot-value request 'post-parameters) (cond ((and (string-equal type "application") (string-equal subtype "x-www-form-urlencoded")) (form-url-encoded-list-to-alist (split "&" (raw-post-data :request request :external-format +latin-1+)) external-format)) ((and (string-equal type "multipart") (string-equal subtype "form-data")) (prog1 (parse-multipart-form-data request external-format) (setf (slot-value request 'raw-post-data) t))))))) (error (condition) (log-message :error "Error when reading POST parameters from body: ~A" condition) ;; this is not the right thing to do because it could happen ;; that we aren't finished reading from the request stream and ;; can't send a reply - to be revisited (setf (return-code*) +http-bad-request+ *close-hunchentoot-stream* t) (abort-request-handler))))) (defun recompute-request-parameters (&key (request *request*) (external-format *hunchentoot-default-external-format*)) "Recomputes the GET and POST parameters for the REQUEST object REQUEST. This only makes sense if you're switching external formats during the request." (maybe-read-post-parameters :request request :force t :external-format external-format) (setf (slot-value request 'get-parameters) (form-url-encoded-list-to-alist (split "&" (query-string request)) external-format)) (values)) (defun script-name* (&optional (request *request*)) "Returns the file name of the REQUEST object REQUEST. That's the requested URI without the query string \(i.e the GET parameters)." (script-name request)) (defun query-string* (&optional (request *request*)) "Returns the query string of the REQUEST object REQUEST. That's the part behind the question mark \(i.e. the GET parameters)." (query-string request)) (defun get-parameters* (&optional (request *request*)) "Returns an alist of the GET parameters associated with the REQUEST object REQUEST." (get-parameters request)) (defmethod post-parameters :before ((request request)) ;; Force here because if someone calls POST-PARAMETERS they actually ;; want them, regardless of why the RAW-POST-DATA has been filled in . ( For instance , if has been called , filling in ;; RAW-POST-DATA, and then subsequent code calls POST-PARAMETERS, without the : FORCE flag POST - PARAMETERS would return NIL . ) (maybe-read-post-parameters :request request :force (not (slot-value request 'post-parameters)))) (defun post-parameters* (&optional (request *request*)) "Returns an alist of the POST parameters associated with the REQUEST object REQUEST." (post-parameters request)) (defun headers-in* (&optional (request *request*)) "Returns an alist of the incoming headers associated with the REQUEST object REQUEST." (headers-in request)) (defun cookies-in* (&optional (request *request*)) "Returns an alist of all cookies associated with the REQUEST object REQUEST." (cookies-in request)) (defgeneric header-in (name request) (:documentation "Returns the incoming header with name NAME. NAME can be a keyword \(recommended) or a string.") (:method (name request) (cdr (assoc* name (headers-in request))))) (defun header-in* (name &optional (request *request*)) "Returns the incoming header with name NAME. NAME can be a keyword \(recommended) or a string." (header-in name request)) (defun authorization (&optional (request *request*)) "Returns as two values the user and password \(if any) as encoded in the 'AUTHORIZATION' header. Returns NIL if there is no such header." (let* ((authorization (header-in :authorization request)) (start (and authorization (> (length authorization) 5) (string-equal "Basic" authorization :end2 5) (scan "\\S" authorization :start 5)))) (when start (destructuring-bind (&optional user password) (split ":" (base64:base64-string-to-string (subseq authorization start))) (values user password))))) (defun remote-addr* (&optional (request *request*)) "Returns the address the current request originated from." (remote-addr request)) (defun remote-port* (&optional (request *request*)) "Returns the port the current request originated from." (remote-port request)) (defun real-remote-addr (&optional (request *request*)) "Returns the 'X-Forwarded-For' incoming http header as the second value in the form of a list of IP addresses and the first element of this list as the first value if this header exists. Otherwise returns the value of REMOTE-ADDR as the only value." (let ((x-forwarded-for (header-in :x-forwarded-for request))) (cond (x-forwarded-for (let ((addresses (split "\\s*,\\s*" x-forwarded-for))) (values (first addresses) addresses))) (t (remote-addr request))))) (defun host (&optional (request *request*)) "Returns the 'Host' incoming http header value." (header-in :host request)) (defun request-uri* (&optional (request *request*)) "Returns the request URI." (request-uri request)) (defun request-method* (&optional (request *request*)) "Returns the request method as a Lisp keyword." (request-method request)) (defun server-protocol* (&optional (request *request*)) "Returns the request protocol as a Lisp keyword." (server-protocol request)) (defun user-agent (&optional (request *request*)) "Returns the 'User-Agent' http header." (header-in :user-agent request)) (defun cookie-in (name &optional (request *request*)) "Returns the cookie with the name NAME \(a string) as sent by the browser - or NIL if there is none." (cdr (assoc name (cookies-in request) :test #'string=))) (defun referer (&optional (request *request*)) "Returns the 'Referer' \(sic!) http header." (header-in :referer request)) (defun get-parameter (name &optional (request *request*)) "Returns the GET parameter with name NAME \(a string) - or NIL if there is none. Search is case-sensitive." (cdr (assoc name (get-parameters request) :test #'string=))) (defun post-parameter (name &optional (request *request*)) "Returns the POST parameter with name NAME \(a string) - or NIL if there is none. Search is case-sensitive." (cdr (assoc name (post-parameters request) :test #'string=))) (defun parameter (name &optional (request *request*)) "Returns the GET or the POST parameter with name NAME \(a string) - or NIL if there is none. If both a GET and a POST parameter with the same name exist the GET parameter is returned. Search is case-sensitive." (or (get-parameter name request) (post-parameter name request))) (defun handle-if-modified-since (time &optional (request *request*)) "Handles the 'If-Modified-Since' header of REQUEST. The date string is compared to the one generated from the supplied universal time TIME." (let ((if-modified-since (header-in :if-modified-since request)) (time-string (rfc-1123-date time))) simple string comparison is sufficient ; see RFC 2616 14.25 (when (and if-modified-since (equal if-modified-since time-string)) (setf (return-code*) +http-not-modified+) (abort-request-handler)) (values))) (defun external-format-from-content-type (content-type) "Creates and returns an external format corresponding to the value of the content type header provided in CONTENT-TYPE. If the content type was not set or if the character set specified was invalid, NIL is returned." (when content-type (when-let (charset (nth-value 2 (parse-content-type content-type))) (handler-case (make-external-format (as-keyword charset) :eol-style :lf) (error () (hunchentoot-warn "Invalid character set ~S in request has been ignored." charset)))))) (defun raw-post-data (&key (request *request*) external-format force-text force-binary want-stream) "Returns the content sent by the client if there was any \(unless the content type was \"multipart/form-data\"). By default, the result is a string if the type of the `Content-Type' media type is \"text\", and a vector of octets otherwise. In the case of a string, the external format to be used to decode the content will be determined from the `charset' parameter sent by the client \(or otherwise *HUNCHENTOOT-DEFAULT-EXTERNAL-FORMAT* will be used). You can also provide an external format explicitly \(through EXTERNAL-FORMAT) in which case the result will unconditionally be a string. Likewise, you can provide a true value for FORCE-TEXT which will force Hunchentoot to act as if the type of the media type had been \"text\". Or you can provide a true value for FORCE-BINARY which means that you want a vector of octets at any rate. If, however, you provide a true value for WANT-STREAM, the other parameters are ignored and you'll get the content \(flexi) stream to read from it yourself. It is then your responsibility to read the correct amount of data, because otherwise you won't be able to return a response to the client. If the content type of the request was `multipart/form-data' or `application/x-www-form-urlencoded', the content has been read by Hunchentoot already and you can't read from the stream anymore. You can call RAW-POST-DATA more than once per request, but you can't mix calls which have different values for WANT-STREAM. Note that this function is slightly misnamed because a client can send content even if the request method is not POST." (when (and force-binary force-text) (parameter-error "It doesn't make sense to set both FORCE-BINARY and FORCE-TEXT to a true value.")) (unless (or external-format force-binary) (setq external-format (or (external-format-from-content-type (header-in :content-type request)) (when force-text *hunchentoot-default-external-format*)))) (let ((raw-post-data (or (slot-value request 'raw-post-data) (get-post-data :request request :want-stream want-stream)))) (cond ((typep raw-post-data 'stream) raw-post-data) ((member raw-post-data '(t nil)) nil) (external-format (octets-to-string raw-post-data :external-format external-format)) (t raw-post-data)))) (defun aux-request-value (symbol &optional (request *request*)) "Returns the value associated with SYMBOL from the request object REQUEST \(the default is the current request) if it exists. The second return value is true if such a value was found." (when request (let ((found (assoc symbol (aux-data request) :test #'eq))) (values (cdr found) found)))) (defsetf aux-request-value (symbol &optional request) (new-value) "Sets the value associated with SYMBOL from the request object REQUEST \(default is *REQUEST*). If there is already a value associated with SYMBOL it will be replaced." (with-rebinding (symbol) (with-unique-names (place %request) `(let* ((,%request (or ,request *request*)) (,place (assoc ,symbol (aux-data ,%request) :test #'eq))) (cond (,place (setf (cdr ,place) ,new-value)) (t (push (cons ,symbol ,new-value) (aux-data ,%request)) ,new-value)))))) (defun delete-aux-request-value (symbol &optional (request *request*)) "Removes the value associated with SYMBOL from the request object REQUEST." (when request (setf (aux-data request) (delete symbol (aux-data request) :key #'car :test #'eq))) (values))
null
https://raw.githubusercontent.com/smanek/trivial-lisp-webapp/36816c17ea378822e02a123c1be960fd9ce3e29d/aux/hunchentoot/request.lisp
lisp
Syntax : COMMON - LISP ; Package : HUNCHENTOOT ; Base : 10 -*- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. some clients (e.g. ASDF-INSTALL) send requests like compute GET parameters from query string and cookies from the incoming 'Cookie' header we assume it's not our fault... skip dispatch if bad request now do the work file, so ignore errors that happen during deletion this is not the right thing to do because it could happen that we aren't finished reading from the request stream and can't send a reply - to be revisited Force here because if someone calls POST-PARAMETERS they actually want them, regardless of why the RAW-POST-DATA has been filled RAW-POST-DATA, and then subsequent code calls POST-PARAMETERS, see RFC 2616 14.25
$ Header : /usr / local / cvsrep / hunchentoot / request.lisp , v 1.35 2008/02/13 16:02:18 edi Exp $ Copyright ( c ) 2004 - 2009 , Dr. . All rights reserved . DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , (in-package :hunchentoot) (defclass request () ((acceptor :initarg :acceptor :documentation "The acceptor which created this request object." :reader request-acceptor) (headers-in :initarg :headers-in :documentation "An alist of the incoming headers." :reader headers-in) (method :initarg :method :documentation "The request method as a keyword." :reader request-method) (uri :initarg :uri :documentation "The request URI as a string." :reader request-uri) (server-protocol :initarg :server-protocol :documentation "The HTTP protocol as a keyword." :reader server-protocol) (remote-addr :initarg :remote-addr :documentation "The IP address of the client that initiated this request." :reader remote-addr) (remote-port :initarg :remote-port :documentation "The TCP port number of the client socket from which this request originated." :reader remote-port) (content-stream :initarg :content-stream :reader content-stream :documentation "A stream from which the request body can be read if there is one.") (cookies-in :initform nil :documentation "An alist of the cookies sent by the client." :reader cookies-in) (get-parameters :initform nil :documentation "An alist of the GET parameters sent by the client." :reader get-parameters) (post-parameters :initform nil :documentation "An alist of the POST parameters sent by the client." :reader post-parameters) (script-name :initform nil :documentation "The URI requested by the client without the query string." :reader script-name) (query-string :initform nil :documentation "The query string of this request." :reader query-string) (session :initform nil :accessor session :documentation "The session object associated with this request.") (aux-data :initform nil :accessor aux-data :documentation "Used to keep a user-modifiable alist with arbitrary data during the request.") (raw-post-data :initform nil :documentation "The raw string sent as the body of a POST request, populated only if not a multipart/form-data request.")) (:documentation "Objects of this class hold all the information about an incoming request. They are created automatically by acceptors and can be accessed by the corresponding handler. You should not mess with the slots of these objects directly, but you can subclass REQUEST in order to implement your own behaviour. See the REQUEST-CLASS slot of the ACCEPTOR class.")) (defgeneric process-request (request) (:documentation "This function is called by PROCESS-CONNECTION after the incoming headers have been read. It selects and calls a handler and sends the output of this handler to the client using START-OUTPUT. It also sets up simple error handling for the request handler. Note that PROCESS-CONNECTION is called once per connection and loops in case of a persistent connection while PROCESS-REQUEST is called anew for each request. Like PROCESS-CONNECTION, this might be a good place to introduce around methods which bind special variables or do other interesting things. The return value of this function is ignored.")) (defun convert-hack (string external-format) "The rfc2388 package is buggy in that it operates on a character stream and thus only accepts encodings which are 8 bit transparent. In order to support different encodings for parameter values submitted, we post process whatever string values the rfc2388 package has returned." (flex:octets-to-string (map '(vector (unsigned-byte 8) *) 'char-code string) :external-format external-format)) (defun parse-rfc2388-form-data (stream content-type-header external-format) "Creates an alist of POST parameters from the stream STREAM which is supposed to be of content type 'multipart/form-data'." (let* ((parsed-content-type-header (rfc2388:parse-header content-type-header :value)) (boundary (or (cdr (rfc2388:find-parameter "BOUNDARY" (rfc2388:header-parameters parsed-content-type-header))) (return-from parse-rfc2388-form-data)))) (loop for part in (rfc2388:parse-mime stream boundary) for headers = (rfc2388:mime-part-headers part) for content-disposition-header = (rfc2388:find-content-disposition-header headers) for name = (cdr (rfc2388:find-parameter "NAME" (rfc2388:header-parameters content-disposition-header))) when name collect (cons name (let ((contents (rfc2388:mime-part-contents part))) (if (pathnamep contents) (list contents (rfc2388:get-file-name headers) (rfc2388:content-type part :as-string t)) (convert-hack contents external-format))))))) (defun get-post-data (&key (request *request*) want-stream (already-read 0)) "Reads the request body from the stream and stores the raw contents \(as an array of octets) in the corresponding slot of the REQUEST object. Returns just the stream if WANT-STREAM is true. If there's a Content-Length header, it is assumed, that ALREADY-READ octets have already been read." (let* ((headers-in (headers-in request)) (content-length (when-let (content-length-header (cdr (assoc :content-length headers-in :test #'eq))) (parse-integer content-length-header :junk-allowed t))) (content-stream (content-stream request))) (setf (slot-value request 'raw-post-data) (cond (want-stream (let ((stream (make-flexi-stream content-stream :external-format +latin-1+))) (when content-length (setf (flexi-stream-bound stream) content-length)) stream)) ((and content-length (> content-length already-read)) (decf content-length already-read) (when (input-chunking-p) see RFC 2616 , section 4.4 (log-message :warning "Got Content-Length header although input chunking is on.")) (let ((content (make-array content-length :element-type 'octet))) (read-sequence content content-stream) content)) ((input-chunking-p) (loop with buffer = (make-array +buffer-length+ :element-type 'octet) with content = (make-array 0 :element-type 'octet :adjustable t) for index = 0 then (+ index pos) for pos = (read-sequence buffer content-stream) do (adjust-array content (+ index pos)) (replace content buffer :start1 index :end2 pos) while (= pos +buffer-length+) finally (return content))))))) (defmethod initialize-instance :after ((request request) &rest init-args) "The only initarg for a REQUEST object is :HEADERS-IN. All other slot values are computed in this :AFTER method." (declare (ignore init-args)) (with-slots (headers-in cookies-in get-parameters script-name query-string session) request (handler-case (progn (let* ((uri (request-uri request)) (match-start (position #\? uri))) (cond (match-start (setq script-name (subseq uri 0 match-start) query-string (subseq uri (1+ match-start)))) (t (setq script-name uri)))) " GET / foo.html HTTP/1.0 " ... (setq script-name (regex-replace "^https?://[^/]+" script-name "")) (setq get-parameters (form-url-encoded-list-to-alist (split "&" query-string)) cookies-in (form-url-encoded-list-to-alist (split "\\s*[,;]\\s*" (cdr (assoc :cookie headers-in :test #'eq))) +utf-8+) session (session-verify request) *session* session)) (error (condition) (log-message :error "Error when creating REQUEST object: ~A" condition) (setf (return-code*) +http-bad-request+))))) (defmethod process-request (request) "Standard implementation for processing a request. You should not change or replace this functionality unless you know what you're doing." (let (*tmp-files* *headers-sent*) (unwind-protect (with-mapped-conditions () (let* ((*request* request) (*within-request-p* t)) (multiple-value-bind (body error) (catch 'handler-done (invoke-process-request-with-error-handling *acceptor* *request* (lambda () (when (eql (return-code *reply*) +http-ok+) (funcall (acceptor-request-dispatcher *acceptor*) *request*))))) (when error (setf (return-code *reply*) +http-internal-server-error+)) (start-output :content (cond ((and error *show-lisp-errors-p*) (format nil "<pre>~A</pre>" (escape-for-html (format nil "~A" error)))) (error "An error has occured.") (t body)))))) (dolist (path *tmp-files*) (when (and (pathnamep path) (probe-file path)) the handler may have chosen to ( re)move the uploaded (ignore-errors (delete-file path))))))) (defun within-request-p () "True if we're in the context of a request, otherwise nil." *within-request-p*) (defun parse-multipart-form-data (request external-format) "Parse the REQUEST body as multipart/form-data, assuming that its content type has already been verified. Returns the form data as alist or NIL if there was no data or the data could not be parsed." (handler-case (let ((content-stream (make-flexi-stream (content-stream request) :external-format +latin-1+))) (prog1 (parse-rfc2388-form-data content-stream (header-in :content-type request) external-format) (let ((stray-data (get-post-data :already-read (flexi-stream-position content-stream)))) (when (and stray-data (plusp (length stray-data))) (hunchentoot-warn "~A octets of stray data after form-data sent by client." (length stray-data)))))) (error (condition) (log-message :error "While parsing multipart/form-data parameters: ~A" condition) nil))) (defun maybe-read-post-parameters (&key (request *request*) force external-format) "Make surce that any POST parameters in the REQUEST are parsed. The body of the request must be either application/x-www-form-urlencoded or multipart/form-data to be considered as containing POST parameters. If FORCE is true, parsing is done unconditionally. Otherwise, parsing will only be done if the RAW-POST-DATA slot in the REQUEST is false. EXTERNAL-FORMAT specifies the external format of the data in the request body. By default, the encoding is determined from the Content-Type header of the request or from *HUNCHENTOOT-DEFAULT-EXTERNAL-FORMAT* if none is found." (when (and (header-in :content-type request) (member (request-method request) *methods-for-post-parameters* :test #'eq) (or force (not (slot-value request 'raw-post-data))) ca n't reparse multipart posts , even when FORCEd (not (eq t (slot-value request 'raw-post-data)))) (unless (or (header-in :content-length request) (input-chunking-p)) (log-message :warning "Can't read request body because there's ~ no Content-Length header and input chunking is off.") (return-from maybe-read-post-parameters nil)) (handler-case (multiple-value-bind (type subtype charset) (parse-content-type (header-in :content-type request)) (let ((external-format (or external-format (when charset (handler-case (make-external-format charset :eol-style :lf) (error () (hunchentoot-warn "Ignoring ~ unknown character set ~A in request content type." charset)))) *hunchentoot-default-external-format*))) (setf (slot-value request 'post-parameters) (cond ((and (string-equal type "application") (string-equal subtype "x-www-form-urlencoded")) (form-url-encoded-list-to-alist (split "&" (raw-post-data :request request :external-format +latin-1+)) external-format)) ((and (string-equal type "multipart") (string-equal subtype "form-data")) (prog1 (parse-multipart-form-data request external-format) (setf (slot-value request 'raw-post-data) t))))))) (error (condition) (log-message :error "Error when reading POST parameters from body: ~A" condition) (setf (return-code*) +http-bad-request+ *close-hunchentoot-stream* t) (abort-request-handler))))) (defun recompute-request-parameters (&key (request *request*) (external-format *hunchentoot-default-external-format*)) "Recomputes the GET and POST parameters for the REQUEST object REQUEST. This only makes sense if you're switching external formats during the request." (maybe-read-post-parameters :request request :force t :external-format external-format) (setf (slot-value request 'get-parameters) (form-url-encoded-list-to-alist (split "&" (query-string request)) external-format)) (values)) (defun script-name* (&optional (request *request*)) "Returns the file name of the REQUEST object REQUEST. That's the requested URI without the query string \(i.e the GET parameters)." (script-name request)) (defun query-string* (&optional (request *request*)) "Returns the query string of the REQUEST object REQUEST. That's the part behind the question mark \(i.e. the GET parameters)." (query-string request)) (defun get-parameters* (&optional (request *request*)) "Returns an alist of the GET parameters associated with the REQUEST object REQUEST." (get-parameters request)) (defmethod post-parameters :before ((request request)) in . ( For instance , if has been called , filling in without the : FORCE flag POST - PARAMETERS would return NIL . ) (maybe-read-post-parameters :request request :force (not (slot-value request 'post-parameters)))) (defun post-parameters* (&optional (request *request*)) "Returns an alist of the POST parameters associated with the REQUEST object REQUEST." (post-parameters request)) (defun headers-in* (&optional (request *request*)) "Returns an alist of the incoming headers associated with the REQUEST object REQUEST." (headers-in request)) (defun cookies-in* (&optional (request *request*)) "Returns an alist of all cookies associated with the REQUEST object REQUEST." (cookies-in request)) (defgeneric header-in (name request) (:documentation "Returns the incoming header with name NAME. NAME can be a keyword \(recommended) or a string.") (:method (name request) (cdr (assoc* name (headers-in request))))) (defun header-in* (name &optional (request *request*)) "Returns the incoming header with name NAME. NAME can be a keyword \(recommended) or a string." (header-in name request)) (defun authorization (&optional (request *request*)) "Returns as two values the user and password \(if any) as encoded in the 'AUTHORIZATION' header. Returns NIL if there is no such header." (let* ((authorization (header-in :authorization request)) (start (and authorization (> (length authorization) 5) (string-equal "Basic" authorization :end2 5) (scan "\\S" authorization :start 5)))) (when start (destructuring-bind (&optional user password) (split ":" (base64:base64-string-to-string (subseq authorization start))) (values user password))))) (defun remote-addr* (&optional (request *request*)) "Returns the address the current request originated from." (remote-addr request)) (defun remote-port* (&optional (request *request*)) "Returns the port the current request originated from." (remote-port request)) (defun real-remote-addr (&optional (request *request*)) "Returns the 'X-Forwarded-For' incoming http header as the second value in the form of a list of IP addresses and the first element of this list as the first value if this header exists. Otherwise returns the value of REMOTE-ADDR as the only value." (let ((x-forwarded-for (header-in :x-forwarded-for request))) (cond (x-forwarded-for (let ((addresses (split "\\s*,\\s*" x-forwarded-for))) (values (first addresses) addresses))) (t (remote-addr request))))) (defun host (&optional (request *request*)) "Returns the 'Host' incoming http header value." (header-in :host request)) (defun request-uri* (&optional (request *request*)) "Returns the request URI." (request-uri request)) (defun request-method* (&optional (request *request*)) "Returns the request method as a Lisp keyword." (request-method request)) (defun server-protocol* (&optional (request *request*)) "Returns the request protocol as a Lisp keyword." (server-protocol request)) (defun user-agent (&optional (request *request*)) "Returns the 'User-Agent' http header." (header-in :user-agent request)) (defun cookie-in (name &optional (request *request*)) "Returns the cookie with the name NAME \(a string) as sent by the browser - or NIL if there is none." (cdr (assoc name (cookies-in request) :test #'string=))) (defun referer (&optional (request *request*)) "Returns the 'Referer' \(sic!) http header." (header-in :referer request)) (defun get-parameter (name &optional (request *request*)) "Returns the GET parameter with name NAME \(a string) - or NIL if there is none. Search is case-sensitive." (cdr (assoc name (get-parameters request) :test #'string=))) (defun post-parameter (name &optional (request *request*)) "Returns the POST parameter with name NAME \(a string) - or NIL if there is none. Search is case-sensitive." (cdr (assoc name (post-parameters request) :test #'string=))) (defun parameter (name &optional (request *request*)) "Returns the GET or the POST parameter with name NAME \(a string) - or NIL if there is none. If both a GET and a POST parameter with the same name exist the GET parameter is returned. Search is case-sensitive." (or (get-parameter name request) (post-parameter name request))) (defun handle-if-modified-since (time &optional (request *request*)) "Handles the 'If-Modified-Since' header of REQUEST. The date string is compared to the one generated from the supplied universal time TIME." (let ((if-modified-since (header-in :if-modified-since request)) (time-string (rfc-1123-date time))) (when (and if-modified-since (equal if-modified-since time-string)) (setf (return-code*) +http-not-modified+) (abort-request-handler)) (values))) (defun external-format-from-content-type (content-type) "Creates and returns an external format corresponding to the value of the content type header provided in CONTENT-TYPE. If the content type was not set or if the character set specified was invalid, NIL is returned." (when content-type (when-let (charset (nth-value 2 (parse-content-type content-type))) (handler-case (make-external-format (as-keyword charset) :eol-style :lf) (error () (hunchentoot-warn "Invalid character set ~S in request has been ignored." charset)))))) (defun raw-post-data (&key (request *request*) external-format force-text force-binary want-stream) "Returns the content sent by the client if there was any \(unless the content type was \"multipart/form-data\"). By default, the result is a string if the type of the `Content-Type' media type is \"text\", and a vector of octets otherwise. In the case of a string, the external format to be used to decode the content will be determined from the `charset' parameter sent by the client \(or otherwise *HUNCHENTOOT-DEFAULT-EXTERNAL-FORMAT* will be used). You can also provide an external format explicitly \(through EXTERNAL-FORMAT) in which case the result will unconditionally be a string. Likewise, you can provide a true value for FORCE-TEXT which will force Hunchentoot to act as if the type of the media type had been \"text\". Or you can provide a true value for FORCE-BINARY which means that you want a vector of octets at any rate. If, however, you provide a true value for WANT-STREAM, the other parameters are ignored and you'll get the content \(flexi) stream to read from it yourself. It is then your responsibility to read the correct amount of data, because otherwise you won't be able to return a response to the client. If the content type of the request was `multipart/form-data' or `application/x-www-form-urlencoded', the content has been read by Hunchentoot already and you can't read from the stream anymore. You can call RAW-POST-DATA more than once per request, but you can't mix calls which have different values for WANT-STREAM. Note that this function is slightly misnamed because a client can send content even if the request method is not POST." (when (and force-binary force-text) (parameter-error "It doesn't make sense to set both FORCE-BINARY and FORCE-TEXT to a true value.")) (unless (or external-format force-binary) (setq external-format (or (external-format-from-content-type (header-in :content-type request)) (when force-text *hunchentoot-default-external-format*)))) (let ((raw-post-data (or (slot-value request 'raw-post-data) (get-post-data :request request :want-stream want-stream)))) (cond ((typep raw-post-data 'stream) raw-post-data) ((member raw-post-data '(t nil)) nil) (external-format (octets-to-string raw-post-data :external-format external-format)) (t raw-post-data)))) (defun aux-request-value (symbol &optional (request *request*)) "Returns the value associated with SYMBOL from the request object REQUEST \(the default is the current request) if it exists. The second return value is true if such a value was found." (when request (let ((found (assoc symbol (aux-data request) :test #'eq))) (values (cdr found) found)))) (defsetf aux-request-value (symbol &optional request) (new-value) "Sets the value associated with SYMBOL from the request object REQUEST \(default is *REQUEST*). If there is already a value associated with SYMBOL it will be replaced." (with-rebinding (symbol) (with-unique-names (place %request) `(let* ((,%request (or ,request *request*)) (,place (assoc ,symbol (aux-data ,%request) :test #'eq))) (cond (,place (setf (cdr ,place) ,new-value)) (t (push (cons ,symbol ,new-value) (aux-data ,%request)) ,new-value)))))) (defun delete-aux-request-value (symbol &optional (request *request*)) "Removes the value associated with SYMBOL from the request object REQUEST." (when request (setf (aux-data request) (delete symbol (aux-data request) :key #'car :test #'eq))) (values))
ac6b0e2c431d3901014ef4506dde8431d68112d19da0ca24af3feda2b3c225e9
jacekschae/learn-reitit-course-files
routes.clj
(ns cheffy.recipe.routes (:require [cheffy.recipe.handlers :as recipe] [cheffy.responses :as responses] [cheffy.middleware :as mw])) (defn routes [env] (let [db (:jdbc-url env)] ["/recipes" {:swagger {:tags ["recipes"]} :middleware [[mw/wrap-auth0]]} ["" {:get {:handler (recipe/list-all-recipes db) :responses {200 {:body responses/recipes}} :summary "List all recipes"} :post {:handler (recipe/create-recipe! db) :parameters {:body {:name string? :prep-time number? :img string?}} :responses {201 {:body {:recipe-id string?}}} :summary "Create recipe"}}] ["/:recipe-id" ["" {:get {:handler (recipe/retrieve-recipe db) :parameters {:path {:recipe-id string?}} :responses {200 {:body responses/recipe}} :summary "Retrieve recipe"} :put {:handler (recipe/update-recipe! db) :middleware [[mw/wrap-recipe-owner db]] :parameters {:path {:recipe-id string?} :body {:name string? :prep-time number? :public boolean? :img string?}} :responses {204 {:body nil?}} :summary "Update recipe"} :delete {:handler (recipe/delete-recipe! db) :middleware [[mw/wrap-recipe-owner db]] :parameters {:path {:recipe-id string?}} :responses {204 {:body nil?}} :summary "Delete recipe"}}] ["/steps" {:post {:handler (recipe/create-step! db) :parameters {:path {:recipe-id string?} :body {:description string? :sort number?}} :responses {201 {:body {:step-id string?}}} :summary "Create step"} :put {:handler (recipe/update-step! db) :middleware [[mw/wrap-recipe-owner db]] :parameters {:path {:recipe-id string?} :body {:step-id string? :description string? :sort int?}} :responses {204 {:body nil?}} :summary "Update step"} :delete {:handler (recipe/delete-step! db) :middleware [[mw/wrap-recipe-owner db]] :parameters {:path {:recipe-id string?} :body {:step-id string?}} :responses {204 {:body nil?}} :summary "Delete step"}}] ["/ingredients" {:post {:handler (recipe/create-ingredient! db) :parameters {:path {:recipe-id string?} :body {:name string? :sort int? :amount int? :measure string?}} :responses {201 {:body {:ingredient-id string?}}} :summary "Create ingredient"} :put {:handler (recipe/update-ingredient! db) :middleware [[mw/wrap-recipe-owner db]] :parameters {:path {:recipe-id string?} :body {:name string? :ingredient-id string? :sort int? :amount int? :measure string?}} :responses {204 {:body nil?}} :summary "Update ingredient"} :delete {:handler (recipe/delete-ingredient! db) :middleware [[mw/wrap-recipe-owner db]] :parameters {:path {:recipe-id string?} :body {:ingredient-id string?}} :responses {204 {:body nil?}} :summary "Delete ingredient"}}] ["/favorite" {:post {:handler (recipe/favorite-recipe! db) :parameters {:path {:recipe-id string?}} :responses {204 {:body nil?}} :summary "Favorite recipe"} :delete {:handler (recipe/unfavorite-recipe! db) :parameters {:path {:recipe-id string?}} :responses {204 {:body nil?}} :summary "Unfavorite recipe"}}]]]))
null
https://raw.githubusercontent.com/jacekschae/learn-reitit-course-files/c13a8eb622a371ad719d3d9023f1b4eff9392e4c/increments/44-update-role/src/cheffy/recipe/routes.clj
clojure
(ns cheffy.recipe.routes (:require [cheffy.recipe.handlers :as recipe] [cheffy.responses :as responses] [cheffy.middleware :as mw])) (defn routes [env] (let [db (:jdbc-url env)] ["/recipes" {:swagger {:tags ["recipes"]} :middleware [[mw/wrap-auth0]]} ["" {:get {:handler (recipe/list-all-recipes db) :responses {200 {:body responses/recipes}} :summary "List all recipes"} :post {:handler (recipe/create-recipe! db) :parameters {:body {:name string? :prep-time number? :img string?}} :responses {201 {:body {:recipe-id string?}}} :summary "Create recipe"}}] ["/:recipe-id" ["" {:get {:handler (recipe/retrieve-recipe db) :parameters {:path {:recipe-id string?}} :responses {200 {:body responses/recipe}} :summary "Retrieve recipe"} :put {:handler (recipe/update-recipe! db) :middleware [[mw/wrap-recipe-owner db]] :parameters {:path {:recipe-id string?} :body {:name string? :prep-time number? :public boolean? :img string?}} :responses {204 {:body nil?}} :summary "Update recipe"} :delete {:handler (recipe/delete-recipe! db) :middleware [[mw/wrap-recipe-owner db]] :parameters {:path {:recipe-id string?}} :responses {204 {:body nil?}} :summary "Delete recipe"}}] ["/steps" {:post {:handler (recipe/create-step! db) :parameters {:path {:recipe-id string?} :body {:description string? :sort number?}} :responses {201 {:body {:step-id string?}}} :summary "Create step"} :put {:handler (recipe/update-step! db) :middleware [[mw/wrap-recipe-owner db]] :parameters {:path {:recipe-id string?} :body {:step-id string? :description string? :sort int?}} :responses {204 {:body nil?}} :summary "Update step"} :delete {:handler (recipe/delete-step! db) :middleware [[mw/wrap-recipe-owner db]] :parameters {:path {:recipe-id string?} :body {:step-id string?}} :responses {204 {:body nil?}} :summary "Delete step"}}] ["/ingredients" {:post {:handler (recipe/create-ingredient! db) :parameters {:path {:recipe-id string?} :body {:name string? :sort int? :amount int? :measure string?}} :responses {201 {:body {:ingredient-id string?}}} :summary "Create ingredient"} :put {:handler (recipe/update-ingredient! db) :middleware [[mw/wrap-recipe-owner db]] :parameters {:path {:recipe-id string?} :body {:name string? :ingredient-id string? :sort int? :amount int? :measure string?}} :responses {204 {:body nil?}} :summary "Update ingredient"} :delete {:handler (recipe/delete-ingredient! db) :middleware [[mw/wrap-recipe-owner db]] :parameters {:path {:recipe-id string?} :body {:ingredient-id string?}} :responses {204 {:body nil?}} :summary "Delete ingredient"}}] ["/favorite" {:post {:handler (recipe/favorite-recipe! db) :parameters {:path {:recipe-id string?}} :responses {204 {:body nil?}} :summary "Favorite recipe"} :delete {:handler (recipe/unfavorite-recipe! db) :parameters {:path {:recipe-id string?}} :responses {204 {:body nil?}} :summary "Unfavorite recipe"}}]]]))
8f249ff7efdb84faf9577412f050eb39fdce68db002e83f29fb4fb2e13ab92a7
seandepagnier/cruisingplot
autopilot.scm
Copyright ( C ) 2011 , 2012 < > ;; This Program is free software ; you can redistribute it and/or ;; modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at your option ) any later version . (declare (unit autopilot)) ; make && ./cruisingplot -v -swindvane-control -ause-windvane -d wind-vane ; The goal is to keep the boat on course by measuring it's motion, ; then estimating what the motion will be in the future with various ; helm changes. (define desired-heading #f) (define sensor-history '()) (define pitch-misalignment #f) (define gps-magnetic-declination #f) (define gps-magnetic-declination-timeout 0) (define (new-derivative-value initial-value) (list initial-value 0 0)) (define (update-derivative-value derivative value subtract-values) (if (first derivative) (let*((d (subtract-values value (first derivative))) (dd (subtract-values d (second derivative)))) (list value d dd (fourth derivative))) (list value 0 0 subtract-values))) (define (create-autopilot arg) (define options (create-options `(,(make-number-verifier 'period "how fast to reach course in seconds" 10 1 20) ,(make-number-verifier 'dampening-factor "dampening factor, 1 for critical" 1 0 10) ,(make-boolean-verifier 'use-windvane "use wind vane for primary feedback" 'false) ,(make-boolean-verifier 'use-gps-heading "use gps instead of magnetic heading" 'false) ,(make-unspecified-number-verifier 'heading "compass heading to hold, 0-360 or -1 for current" #f 0 360) ) "-autopilot heading=90,period=5,dampening-factor=.8" (create-motor-options))) (parse-basic-options-string options arg) (set! desired-heading (options 'heading)) ; read from sensors at 10hz and average (create-periodic-task "autopilot-sensor-reader" .1 update-sensor-history) (let ((heading (new-derivative-value #f)) (windvane (new-derivative-value #f)) (gain-h .03) (gain-r .02) (pitch-tilt-angle 5) (roll-round-up-factor 0) (heading-history '()) (motor (motor-open options motor-command))) (create-periodic-task "autopilot-update" 1 (lambda () (update-gps-declination) (let*((pitch-compensated-sensor-history (compensate-history-pitch sensor-history pitch-tilt-angle)) (heading1 (heading-from-history-1 pitch-compensated-sensor-history)) (heading2 (heading-from-history-2 pitch-compensated-sensor-history)) (roll (roll-from-history-1 pitch-compensated-sensor-history)) (gps-heading (computation-calculate-exists 'gps-heading)) (gps-magnetic-heading (if (and gps-heading gps-magnetic-declination) (+ gps-heading gps-magnetic-declination) #f))) (set! heading (update-derivative-value heading (if (options 'use-gps-heading) gps-magnetic-heading heading1) phase-difference-degrees)) (set! windvane (update-derivative-value windvane (sensor-query 'windvane) -)) (cond ((options 'use-windvane) (cond ((first windvane) (let ((data (map (lambda (s) (list (first s) (fourth s))) sensor-history))) (if (not (any not (map (lambda (x) (not (any not x))) data))) (let ((max-wave (find-wave data 2 17))) (print "max-wave " max-wave)))) (let ((cmd (calc-windvane-command windvane heading gps-magnetic-heading))) (cond (windvane-control-port (write (* 100 cmd) windvane-control-port) (newline windvane-control-port))) (motor-command-velocity motor cmd))) (else (print "waiting on windvane input")))) ((first heading) (if (not desired-heading) (set! desired-heading (first heading))) (let*((heading-error (phase-difference-degrees (first heading) (- desired-heading (if roll (* roll roll-round-up-factor) 0))))) error and rate must not be zero for feedback .. ; we are already perfect in this case (if (not (and (zero? heading-error) (zero? (second heading)))) (set! heading-history (append (if (>= (length heading-history) 30) (cdr heading-history) heading-history) (list (list heading-error (second heading) (third heading)))))) ; PID command = a*heading-error + b*accumulated-error + c*heading-rate (let ((cmd (+ (* gain-h heading-error) (* gain-r (second heading))))) (cond (windvane-control-port (write (* 100 cmd) windvane-control-port) (newline windvane-control-port))) (motor-command-velocity motor cmd)))) (else (print "autopilot is waiting for heading update")))))))) (define (update-gps-declination) (cond ((and (computation-exists? 'gps-heading) (or (not gps-magnetic-declination) (>= gps-magnetic-declination-timeout 1000))) (set! gps-magnetic-declination (computation-calculate 'gps-magnetic-declination)) (set! gps-magnetic-declination-timeout 0)) (else (set! gps-magnetic-declination-timeout (+ gps-magnetic-declination-timeout 1))))) (define (compensate-history-pitch sensor-history pitch-tilt-angle) (let ((current-pitch (pitch-from-history-1 sensor-history))) (set! pitch-misalignment (cond ((and current-pitch pitch-misalignment) (+ (* .99 pitch-misalignment) (* .01 current-pitch))) (current-pitch current-pitch) (else #f))) (history-cancel-pitch (+ pitch-tilt-angle (if pitch-misalignment pitch-misalignment 0)) sensor-history))) (define (update-sensor-history) (let ((accel (sensor-query-indexes 'accel '(0 1 2))) (mag (sensor-query-indexes 'mag '(0 1 2))) (wind-vane (sensor-query 'windvane))) (let ((measurement (list accel mag wind-vane))) (set! sensor-history (append (if (>= (length sensor-history) 120) (cdr sensor-history) sensor-history) (list (cons (elapsed-seconds) measurement))))))) (define (motor-command command) (case command ((port) (set! desired-heading (phase-difference-degrees desired-heading 3))) ((port-long) (set! desired-heading (phase-difference-degrees desired-heading 15))) ((starboard) (set! desired-heading (phase-difference-degrees desired-heading 3))) ((starboard-long) (set! desired-heading (phase-difference-degrees desired-heading 15))))) (define (+map a b) (if (or (not a) (not b) (any not a) (any not b)) #f (map + a b))) (define (pitch-from-history-1 history) (let ((history-accel-sum (fold +map '(0 0 0) (map cadr history))) (l (length history))) (if (or (zero? l) (not history-accel-sum)) #f (accelerometer-pitch (map (lambda (h) (/ h l)) history-accel-sum))))) (define (history-cancel-pitch pitch history) ; (print "history-cancel-pitch " pitch history) (let ((q (angle-vector->quaternion (deg2rad (if pitch pitch 0)) '(0 1 0)))) (map (lambda (h) (list (first h) (if (any not (second h)) (second h) (apply-quaternion-to-vector q (second h))) (if (any not (third h)) (third h) (apply-quaternion-to-vector q (third h))) (fourth h))) history))) (define (roll-from-history-1 history) (let ((history-accel-sum (fold +map '(0 0 0) (map cadr history))) (l (length history))) (if (or (zero? l) (not history-accel-sum)) #f (accelerometer-roll (map (lambda (h) (/ h l)) history-accel-sum))))) (define (heading-from-history-1 history) (let ((history-sum (fold (lambda (a b) (if (or (not a) (not b) (any not (map (lambda (x) (not (any not x))) a)) (any not (map (lambda (x) (not (any not x))) b))) #f (list (map + (first a) (first b)) (map + (second a) (second b))))) '((0 0 0) (0 0 0)) (map (lambda (h) (list (second h) (third h))) history))) (l (length history))) (if (or (not history-sum) (zero? l) (any not (first history-sum)) (any not (first history-sum))) #f (let ((accel (map (lambda (h) (/ h l)) (first history-sum))) (mag (map (lambda (h) (/ h l)) (second history-sum)))) (magnetometer-heading accel mag))))) (define (heading-from-history-2 history) (let ((measurement-history (map cdr history)) (l (length history))) (let ((accels (map first measurement-history)) (mags (map second measurement-history))) (if (or (zero? l) (any (lambda (x) (any not x)) accels) (any (lambda (x) (any not x)) mags)) #f (/ (fold + 0 (map magnetometer-heading accels mags)) l))))) (define windvane-control-port #f) (define (set-windvane-control-port! port) (set! windvane-control-port port)) h '' + 2 c w h ' + h = 0 ; 2 ; - h'' - w h ; c = ----------- ; 2 w h' ; ; w = 1 / period ; for critical dampening , c = 1 (define (calculate-dampening-factor heading heading-rate heading-rate-rate period) (let ((w (/ period))) (let ((num (- (+ heading-rate-rate (* (square w) heading)))) (dem (* 2 w heading-rate))) (cond ((zero? num) 0) ((zero? dem) (* num +inf)) (/ num dem))))) ; ; command autopilot based on h'' ; command = -gain(2 c w h ' + ) (define (calculate-filter-command heading-error heading-rate period dampening-factor gain) ; (print "args " heading-error " " heading-rate " " period " " dampening-factor " " gain) (let ((w (/ period)) (c dampening-factor)) (- (* gain (+ (* 2 c w heading-rate) (* (square w) heading-error)))))) ; update gain to reach critical dampening (define (compute-autopilot-gain heading-error heading-rate heading-rate-rate period gain) (let ((df (calculate-dampening-factor heading-error heading-rate heading-rate-rate period)) (lp .1)) (let ((newfac (cond ((> df 1.1) 1.02) ((< df .9) .98) (else 0)))) (let ((new-gain (+ (* gain newfac lp) (* (- 1 lp) gain)))) (print "gain " gain " new-gain " new-gain " df " df) new-gain)))) ; steer to wind algorithm (define (calc-windvane-command windvane heading gps-magnetic-heading) (let ((cmd (+ (* 2 (first windvane)) (* .3 (second windvane))))) (print "cmd = " cmd " = 1*" (first windvane) " + 1*" (second windvane)) cmd)) ; Create a map based on wind direction vs heading rate of change ; vs rudder position ; balanced on both tacks ; find centerpoint ; rate of change of 5 adaptive autopilot uses gps data as feedback to self - calibrate ; ; this autopilot uses pre-calibrated mag and accel data ;
null
https://raw.githubusercontent.com/seandepagnier/cruisingplot/d3d83e7372e2c5ce1a8e8071286e30c2028088cf/autopilot.scm
scheme
you can redistribute it and/or modify it under the terms of the GNU General Public either make && ./cruisingplot -v -swindvane-control -ause-windvane -d wind-vane The goal is to keep the boat on course by measuring it's motion, then estimating what the motion will be in the future with various helm changes. read from sensors at 10hz and average we are already perfect in this case PID command = a*heading-error + b*accumulated-error + c*heading-rate (print "history-cancel-pitch " pitch history) - h'' - w h c = ----------- 2 w h' w = 1 / period command autopilot based on h'' (print "args " heading-error " " heading-rate " " period " " dampening-factor " " gain) update gain to reach critical dampening steer to wind algorithm Create a map based on wind direction vs heading rate of change vs rudder position balanced on both tacks find centerpoint this autopilot uses pre-calibrated mag and accel data
Copyright ( C ) 2011 , 2012 < > version 3 of the License , or ( at your option ) any later version . (declare (unit autopilot)) (define desired-heading #f) (define sensor-history '()) (define pitch-misalignment #f) (define gps-magnetic-declination #f) (define gps-magnetic-declination-timeout 0) (define (new-derivative-value initial-value) (list initial-value 0 0)) (define (update-derivative-value derivative value subtract-values) (if (first derivative) (let*((d (subtract-values value (first derivative))) (dd (subtract-values d (second derivative)))) (list value d dd (fourth derivative))) (list value 0 0 subtract-values))) (define (create-autopilot arg) (define options (create-options `(,(make-number-verifier 'period "how fast to reach course in seconds" 10 1 20) ,(make-number-verifier 'dampening-factor "dampening factor, 1 for critical" 1 0 10) ,(make-boolean-verifier 'use-windvane "use wind vane for primary feedback" 'false) ,(make-boolean-verifier 'use-gps-heading "use gps instead of magnetic heading" 'false) ,(make-unspecified-number-verifier 'heading "compass heading to hold, 0-360 or -1 for current" #f 0 360) ) "-autopilot heading=90,period=5,dampening-factor=.8" (create-motor-options))) (parse-basic-options-string options arg) (set! desired-heading (options 'heading)) (create-periodic-task "autopilot-sensor-reader" .1 update-sensor-history) (let ((heading (new-derivative-value #f)) (windvane (new-derivative-value #f)) (gain-h .03) (gain-r .02) (pitch-tilt-angle 5) (roll-round-up-factor 0) (heading-history '()) (motor (motor-open options motor-command))) (create-periodic-task "autopilot-update" 1 (lambda () (update-gps-declination) (let*((pitch-compensated-sensor-history (compensate-history-pitch sensor-history pitch-tilt-angle)) (heading1 (heading-from-history-1 pitch-compensated-sensor-history)) (heading2 (heading-from-history-2 pitch-compensated-sensor-history)) (roll (roll-from-history-1 pitch-compensated-sensor-history)) (gps-heading (computation-calculate-exists 'gps-heading)) (gps-magnetic-heading (if (and gps-heading gps-magnetic-declination) (+ gps-heading gps-magnetic-declination) #f))) (set! heading (update-derivative-value heading (if (options 'use-gps-heading) gps-magnetic-heading heading1) phase-difference-degrees)) (set! windvane (update-derivative-value windvane (sensor-query 'windvane) -)) (cond ((options 'use-windvane) (cond ((first windvane) (let ((data (map (lambda (s) (list (first s) (fourth s))) sensor-history))) (if (not (any not (map (lambda (x) (not (any not x))) data))) (let ((max-wave (find-wave data 2 17))) (print "max-wave " max-wave)))) (let ((cmd (calc-windvane-command windvane heading gps-magnetic-heading))) (cond (windvane-control-port (write (* 100 cmd) windvane-control-port) (newline windvane-control-port))) (motor-command-velocity motor cmd))) (else (print "waiting on windvane input")))) ((first heading) (if (not desired-heading) (set! desired-heading (first heading))) (let*((heading-error (phase-difference-degrees (first heading) (- desired-heading (if roll (* roll roll-round-up-factor) 0))))) error and rate must not be zero for feedback .. (if (not (and (zero? heading-error) (zero? (second heading)))) (set! heading-history (append (if (>= (length heading-history) 30) (cdr heading-history) heading-history) (list (list heading-error (second heading) (third heading)))))) (let ((cmd (+ (* gain-h heading-error) (* gain-r (second heading))))) (cond (windvane-control-port (write (* 100 cmd) windvane-control-port) (newline windvane-control-port))) (motor-command-velocity motor cmd)))) (else (print "autopilot is waiting for heading update")))))))) (define (update-gps-declination) (cond ((and (computation-exists? 'gps-heading) (or (not gps-magnetic-declination) (>= gps-magnetic-declination-timeout 1000))) (set! gps-magnetic-declination (computation-calculate 'gps-magnetic-declination)) (set! gps-magnetic-declination-timeout 0)) (else (set! gps-magnetic-declination-timeout (+ gps-magnetic-declination-timeout 1))))) (define (compensate-history-pitch sensor-history pitch-tilt-angle) (let ((current-pitch (pitch-from-history-1 sensor-history))) (set! pitch-misalignment (cond ((and current-pitch pitch-misalignment) (+ (* .99 pitch-misalignment) (* .01 current-pitch))) (current-pitch current-pitch) (else #f))) (history-cancel-pitch (+ pitch-tilt-angle (if pitch-misalignment pitch-misalignment 0)) sensor-history))) (define (update-sensor-history) (let ((accel (sensor-query-indexes 'accel '(0 1 2))) (mag (sensor-query-indexes 'mag '(0 1 2))) (wind-vane (sensor-query 'windvane))) (let ((measurement (list accel mag wind-vane))) (set! sensor-history (append (if (>= (length sensor-history) 120) (cdr sensor-history) sensor-history) (list (cons (elapsed-seconds) measurement))))))) (define (motor-command command) (case command ((port) (set! desired-heading (phase-difference-degrees desired-heading 3))) ((port-long) (set! desired-heading (phase-difference-degrees desired-heading 15))) ((starboard) (set! desired-heading (phase-difference-degrees desired-heading 3))) ((starboard-long) (set! desired-heading (phase-difference-degrees desired-heading 15))))) (define (+map a b) (if (or (not a) (not b) (any not a) (any not b)) #f (map + a b))) (define (pitch-from-history-1 history) (let ((history-accel-sum (fold +map '(0 0 0) (map cadr history))) (l (length history))) (if (or (zero? l) (not history-accel-sum)) #f (accelerometer-pitch (map (lambda (h) (/ h l)) history-accel-sum))))) (define (history-cancel-pitch pitch history) (let ((q (angle-vector->quaternion (deg2rad (if pitch pitch 0)) '(0 1 0)))) (map (lambda (h) (list (first h) (if (any not (second h)) (second h) (apply-quaternion-to-vector q (second h))) (if (any not (third h)) (third h) (apply-quaternion-to-vector q (third h))) (fourth h))) history))) (define (roll-from-history-1 history) (let ((history-accel-sum (fold +map '(0 0 0) (map cadr history))) (l (length history))) (if (or (zero? l) (not history-accel-sum)) #f (accelerometer-roll (map (lambda (h) (/ h l)) history-accel-sum))))) (define (heading-from-history-1 history) (let ((history-sum (fold (lambda (a b) (if (or (not a) (not b) (any not (map (lambda (x) (not (any not x))) a)) (any not (map (lambda (x) (not (any not x))) b))) #f (list (map + (first a) (first b)) (map + (second a) (second b))))) '((0 0 0) (0 0 0)) (map (lambda (h) (list (second h) (third h))) history))) (l (length history))) (if (or (not history-sum) (zero? l) (any not (first history-sum)) (any not (first history-sum))) #f (let ((accel (map (lambda (h) (/ h l)) (first history-sum))) (mag (map (lambda (h) (/ h l)) (second history-sum)))) (magnetometer-heading accel mag))))) (define (heading-from-history-2 history) (let ((measurement-history (map cdr history)) (l (length history))) (let ((accels (map first measurement-history)) (mags (map second measurement-history))) (if (or (zero? l) (any (lambda (x) (any not x)) accels) (any (lambda (x) (any not x)) mags)) #f (/ (fold + 0 (map magnetometer-heading accels mags)) l))))) (define windvane-control-port #f) (define (set-windvane-control-port! port) (set! windvane-control-port port)) h '' + 2 c w h ' + h = 0 2 for critical dampening , c = 1 (define (calculate-dampening-factor heading heading-rate heading-rate-rate period) (let ((w (/ period))) (let ((num (- (+ heading-rate-rate (* (square w) heading)))) (dem (* 2 w heading-rate))) (cond ((zero? num) 0) ((zero? dem) (* num +inf)) (/ num dem))))) command = -gain(2 c w h ' + ) (define (calculate-filter-command heading-error heading-rate period dampening-factor gain) (let ((w (/ period)) (c dampening-factor)) (- (* gain (+ (* 2 c w heading-rate) (* (square w) heading-error)))))) (define (compute-autopilot-gain heading-error heading-rate heading-rate-rate period gain) (let ((df (calculate-dampening-factor heading-error heading-rate heading-rate-rate period)) (lp .1)) (let ((newfac (cond ((> df 1.1) 1.02) ((< df .9) .98) (else 0)))) (let ((new-gain (+ (* gain newfac lp) (* (- 1 lp) gain)))) (print "gain " gain " new-gain " new-gain " df " df) new-gain)))) (define (calc-windvane-command windvane heading gps-magnetic-heading) (let ((cmd (+ (* 2 (first windvane)) (* .3 (second windvane))))) (print "cmd = " cmd " = 1*" (first windvane) " + 1*" (second windvane)) cmd)) rate of change of 5 adaptive autopilot uses gps data as feedback to self - calibrate
1b434378d8bd7d859b682993f156d449c560e9cd763ec9c200e8b41397ab0c47
jgbm/cpgv
CPToGV.hs
module CPToGV where import Data.Maybe import qualified CP.Syntax as CP import CP.Printer import GV.Syntax (dual) import qualified GV.Syntax as GV xSession :: CP.Prop -> GV.Session xSession (CP.Times a b) = GV.Output (xTypeDual a) (xSession b) xSession (CP.Par a b) = GV.Input (xType a) (xSession b) xSession (CP.Plus cs) = GV.Sum (map (\(x, a) -> (x, xSession a)) cs) xSession (CP.With cs) = GV.Choice (map (\(x, a) -> (x, xSession a)) cs) xSession (CP.One) = GV.OutTerm xSession (CP.Bottom) = GV.InTerm xSession (CP.OfCourse a) = GV.Server (xSession a) xSession (CP.WhyNot a) = GV.Service (xSession a) xSession (CP.Var v []) = GV.SVar v xSession (CP.Neg v) = GV.Neg v xSession (CP.Univ v a) = GV.InputType v (xSession a) xSession (CP.Exist v a) = GV.OutputType v (xSession a) xSession s = error ("xSession missing " ++ show s) xType :: CP.Prop -> GV.Type xType = GV.Lift . xSession xTypeDual :: CP.Prop -> GV.Type xTypeDual = GV.Lift . dual . xSession xId = id type TypeEnv = [(String, CP.Prop)] extend :: TypeEnv -> (String, CP.Prop) -> TypeEnv extend = flip (:) find x env = fromJust (lookup x env) xTerm :: TypeEnv -> CP.Proc -> GV.Term xTerm env (CP.ProcVar x []) = GV.Var x xTerm env (CP.Link x y) = GV.Link (GV.Var x) (GV.Var y) xTerm env (CP.Cut x t p q) = GV.Let (GV.BindName x) (GV.Fork x (xSession t) (xTerm (extend env (x, t)) p)) (xTerm (extend env (x, CP.dual t)) q) xTerm env (CP.Out x y p q) = GV.Let (GV.BindName x) (GV.Send (GV.Fork y (xSession yt) (xTerm (extend env (y, yt)) p)) (GV.Var x)) (xTerm (extend env (x, xt)) q) where (yt `CP.Times` xt) = find x env xTerm env (CP.In x y r) = GV.Let (GV.BindPair y x) (GV.Receive (GV.Var x)) (xTerm (extend (extend env (y,yt)) (x, xt)) r) where (yt `CP.Par` xt) = find x env xTerm env (CP.Select x l p) = GV.Let (GV.BindName x) (GV.Select l (GV.Var x)) (xTerm (extend env (x, xt)) p) where (CP.Plus lts) = find x env xt = findLabel l lts findLabel l ((l', t) : lts) | l == l' = t | otherwise = findLabel l lts xTerm env (CP.Case x cs@(_:_)) = GV.Case (GV.Var x) (map (\(l, p) -> branch l p) cs) where branch l p = (xId l, x, xTerm (extend env (x, xt)) p) where (CP.With lts) = find x env xt = findLabel l lts findLabel l ((l', t) : lts) | l == l' = t | otherwise = findLabel l lts xTerm env (CP.EmptyCase x xs) = GV.EmptyCase (GV.Var (xId x)) (map xId xs) (GV.Lift GV.OutTerm) xTerm env (CP.Replicate s x p) = GV.Link (GV.Var s) (GV.Serve x (xSession xt) (xTerm (extend env (x, xt)) p)) where (CP.OfCourse xt) = find s env xTerm env (CP.Derelict s x p) = GV.Let (GV.BindName x) (GV.Fork x (dual (xSession xt)) (GV.Link (GV.Var x) (GV.Request (GV.Var s)))) (xTerm (extend env (x, xt)) p) where (CP.WhyNot xt) = find s env xTerm env (CP.SendProp x a p) = GV.Let (GV.BindName x') (GV.SendType (xSession a) (GV.Var x')) (xTerm (extend env (x, xt)) p) where x' = xId x (CP.Exist v t) = find x env xt = CP.inst v a t xTerm env (CP.ReceiveProp x v p) = GV.Let (GV.BindName x') (GV.ReceiveType (GV.Var x')) (xTerm (extend env (x, xt)) p) where x' = xId x (CP.Univ v xt) = find x env xTerm env (CP.EmptyOut x) = GV.Var (xId x) xTerm env (CP.EmptyIn x p) = xTerm env p xTerm _ t = error $ "No xTerm case for " ++ show (pretty t)
null
https://raw.githubusercontent.com/jgbm/cpgv/1d06a6b47de4977dfa939a661ccd6ffcdcc5ec9e/CPToGV.hs
haskell
module CPToGV where import Data.Maybe import qualified CP.Syntax as CP import CP.Printer import GV.Syntax (dual) import qualified GV.Syntax as GV xSession :: CP.Prop -> GV.Session xSession (CP.Times a b) = GV.Output (xTypeDual a) (xSession b) xSession (CP.Par a b) = GV.Input (xType a) (xSession b) xSession (CP.Plus cs) = GV.Sum (map (\(x, a) -> (x, xSession a)) cs) xSession (CP.With cs) = GV.Choice (map (\(x, a) -> (x, xSession a)) cs) xSession (CP.One) = GV.OutTerm xSession (CP.Bottom) = GV.InTerm xSession (CP.OfCourse a) = GV.Server (xSession a) xSession (CP.WhyNot a) = GV.Service (xSession a) xSession (CP.Var v []) = GV.SVar v xSession (CP.Neg v) = GV.Neg v xSession (CP.Univ v a) = GV.InputType v (xSession a) xSession (CP.Exist v a) = GV.OutputType v (xSession a) xSession s = error ("xSession missing " ++ show s) xType :: CP.Prop -> GV.Type xType = GV.Lift . xSession xTypeDual :: CP.Prop -> GV.Type xTypeDual = GV.Lift . dual . xSession xId = id type TypeEnv = [(String, CP.Prop)] extend :: TypeEnv -> (String, CP.Prop) -> TypeEnv extend = flip (:) find x env = fromJust (lookup x env) xTerm :: TypeEnv -> CP.Proc -> GV.Term xTerm env (CP.ProcVar x []) = GV.Var x xTerm env (CP.Link x y) = GV.Link (GV.Var x) (GV.Var y) xTerm env (CP.Cut x t p q) = GV.Let (GV.BindName x) (GV.Fork x (xSession t) (xTerm (extend env (x, t)) p)) (xTerm (extend env (x, CP.dual t)) q) xTerm env (CP.Out x y p q) = GV.Let (GV.BindName x) (GV.Send (GV.Fork y (xSession yt) (xTerm (extend env (y, yt)) p)) (GV.Var x)) (xTerm (extend env (x, xt)) q) where (yt `CP.Times` xt) = find x env xTerm env (CP.In x y r) = GV.Let (GV.BindPair y x) (GV.Receive (GV.Var x)) (xTerm (extend (extend env (y,yt)) (x, xt)) r) where (yt `CP.Par` xt) = find x env xTerm env (CP.Select x l p) = GV.Let (GV.BindName x) (GV.Select l (GV.Var x)) (xTerm (extend env (x, xt)) p) where (CP.Plus lts) = find x env xt = findLabel l lts findLabel l ((l', t) : lts) | l == l' = t | otherwise = findLabel l lts xTerm env (CP.Case x cs@(_:_)) = GV.Case (GV.Var x) (map (\(l, p) -> branch l p) cs) where branch l p = (xId l, x, xTerm (extend env (x, xt)) p) where (CP.With lts) = find x env xt = findLabel l lts findLabel l ((l', t) : lts) | l == l' = t | otherwise = findLabel l lts xTerm env (CP.EmptyCase x xs) = GV.EmptyCase (GV.Var (xId x)) (map xId xs) (GV.Lift GV.OutTerm) xTerm env (CP.Replicate s x p) = GV.Link (GV.Var s) (GV.Serve x (xSession xt) (xTerm (extend env (x, xt)) p)) where (CP.OfCourse xt) = find s env xTerm env (CP.Derelict s x p) = GV.Let (GV.BindName x) (GV.Fork x (dual (xSession xt)) (GV.Link (GV.Var x) (GV.Request (GV.Var s)))) (xTerm (extend env (x, xt)) p) where (CP.WhyNot xt) = find s env xTerm env (CP.SendProp x a p) = GV.Let (GV.BindName x') (GV.SendType (xSession a) (GV.Var x')) (xTerm (extend env (x, xt)) p) where x' = xId x (CP.Exist v t) = find x env xt = CP.inst v a t xTerm env (CP.ReceiveProp x v p) = GV.Let (GV.BindName x') (GV.ReceiveType (GV.Var x')) (xTerm (extend env (x, xt)) p) where x' = xId x (CP.Univ v xt) = find x env xTerm env (CP.EmptyOut x) = GV.Var (xId x) xTerm env (CP.EmptyIn x p) = xTerm env p xTerm _ t = error $ "No xTerm case for " ++ show (pretty t)
101ed3976e9df854958d92685d6027e29130b8244cae672ec2c33cdda3e8608c
scalaris-team/scalaris
db_generator_SUITE.erl
2013 Zuse Institute Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; % you may not use this file except in compliance with the License. % You may obtain a copy of the License at % % -2.0 % % Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % See the License for the specific language governing permissions and % limitations under the License. @author < > %% @doc Unit tests for test/db_generator.erl. %% @end %% @version $Id$ -module(db_generator_SUITE). -author(''). -vsn('$Id$'). -compile(export_all). -include("unittest.hrl"). -include("scalaris.hrl"). all() -> [ tester_get_db3, tester_get_db4 ]. suite() -> [ {timetrap, {seconds, 90}} ]. init_per_suite(Config) -> tester:register_type_checker({typedef, intervals, interval, []}, intervals, is_well_formed), tester:register_type_checker({typedef, intervals, continuous_interval, []}, intervals, is_continuous), tester:register_value_creator({typedef, random_bias, generator, []}, random_bias, tester_create_generator, 3), tester:register_value_creator({typedef, intervals, interval, []}, intervals, tester_create_interval, 1), tester:register_value_creator({typedef, intervals, continuous_interval, []}, intervals, tester_create_continuous_interval, 4), rt_SUITE:register_value_creator(), unittest_helper:start_minimal_procs(Config, [], true). end_per_suite(Config) -> tester:unregister_value_creator({typedef, random_bias, generator, []}), tester:unregister_value_creator({typedef, intervals, interval, []}), tester:unregister_value_creator({typedef, intervals, continuous_interval, []}), tester:unregister_type_checker({typedef, intervals, interval, []}), tester:unregister_type_checker({typedef, intervals, continuous_interval, []}), rt_SUITE:unregister_value_creator(), _ = unittest_helper:stop_minimal_procs(Config), ok. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % db_generator : get_db/3 and db_generator : % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec prop_get_db3(I::intervals:continuous_interval(), ItemCount::1..1000, db_generator:db_distribution()) -> true. prop_get_db3(Interval, ItemCount0, Distribution0 = {non_uniform, RanGen}) -> ItemCount = erlang:min(ItemCount0, random_bias:numbers_left(RanGen)), prop_get_db3_(Interval, ItemCount, db_generator:feeder_fix_rangen(Distribution0, ItemCount)); prop_get_db3(Interval, ItemCount, Distribution) -> prop_get_db3_(Interval, ItemCount, Distribution). -spec prop_get_db3_(I::intervals:continuous_interval(), ItemCount::1..1000, db_generator:db_distribution()) -> true. prop_get_db3_(Interval, ItemCount, Distribution) -> Result = db_generator:get_db(Interval, ItemCount, Distribution), ?equals([Key || Key <- Result, not intervals:in(Key, Interval)], []), ?compare(fun erlang:'=<'/2, length(Result), ItemCount), ?equals(length(Result), length(lists:usort(Result))), ?implies(length(intervals:split(Interval, ItemCount)) == ItemCount, ?equals(length(Result), ItemCount)). -spec prop_get_db4(I::intervals:continuous_interval(), ItemCount::1..1000, db_generator:db_distribution(), Options::[db_generator:option()]) -> true. prop_get_db4(Interval, ItemCount0, Distribution0 = {non_uniform, RanGen}, Options) -> ItemCount = erlang:min(ItemCount0, random_bias:numbers_left(RanGen)), prop_get_db4_(Interval, ItemCount, db_generator:feeder_fix_rangen(Distribution0, ItemCount), Options); prop_get_db4(Interval, ItemCount, Distribution, Options) -> prop_get_db4_(Interval, ItemCount, Distribution, Options). -spec prop_get_db4_(I::intervals:continuous_interval(), ItemCount::1..1000, db_generator:db_distribution(), Options::[db_generator:option()]) -> true. prop_get_db4_(Interval, ItemCount, Distribution, Options) -> Result = db_generator:get_db(Interval, ItemCount, Distribution, Options), case proplists:get_value(output, Options, list_key) of list_key -> ?equals([Key || Key <- Result, not intervals:in(Key, Interval)], []); list_keytpl -> ?equals([Key || {Key} <- Result, not intervals:in(Key, Interval)], []); list_key_val -> ?equals([Key || {Key, _Val} <- Result, not intervals:in(Key, Interval)], []) end, ?compare(fun erlang:'=<'/2, length(Result), ItemCount), ?equals(length(Result), length(lists:usort(Result))), ?implies(length(intervals:split(Interval, ItemCount)) == ItemCount, ?equals(length(Result), ItemCount)). tester_get_db3(_Config) -> prop_get_db3(intervals:new(?MINUS_INFINITY), 844, random), tester:test(?MODULE, prop_get_db3, 3, 500, [{threads, 4}]). tester_get_db4(_Config) -> prop_get_db4(intervals:new(?MINUS_INFINITY), 1, {non_uniform, random_bias:binomial(50, 0.06755763133001705)}, [{output,list_key}]), tester:test(?MODULE, prop_get_db4, 4, 500, [{threads, 4}]).
null
https://raw.githubusercontent.com/scalaris-team/scalaris/feb894d54e642bb3530e709e730156b0ecc1635f/test/db_generator_SUITE.erl
erlang
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. @doc Unit tests for test/db_generator.erl. @end @version $Id$
2013 Zuse Institute Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , @author < > -module(db_generator_SUITE). -author(''). -vsn('$Id$'). -compile(export_all). -include("unittest.hrl"). -include("scalaris.hrl"). all() -> [ tester_get_db3, tester_get_db4 ]. suite() -> [ {timetrap, {seconds, 90}} ]. init_per_suite(Config) -> tester:register_type_checker({typedef, intervals, interval, []}, intervals, is_well_formed), tester:register_type_checker({typedef, intervals, continuous_interval, []}, intervals, is_continuous), tester:register_value_creator({typedef, random_bias, generator, []}, random_bias, tester_create_generator, 3), tester:register_value_creator({typedef, intervals, interval, []}, intervals, tester_create_interval, 1), tester:register_value_creator({typedef, intervals, continuous_interval, []}, intervals, tester_create_continuous_interval, 4), rt_SUITE:register_value_creator(), unittest_helper:start_minimal_procs(Config, [], true). end_per_suite(Config) -> tester:unregister_value_creator({typedef, random_bias, generator, []}), tester:unregister_value_creator({typedef, intervals, interval, []}), tester:unregister_value_creator({typedef, intervals, continuous_interval, []}), tester:unregister_type_checker({typedef, intervals, interval, []}), tester:unregister_type_checker({typedef, intervals, continuous_interval, []}), rt_SUITE:unregister_value_creator(), _ = unittest_helper:stop_minimal_procs(Config), ok. db_generator : get_db/3 and db_generator : -spec prop_get_db3(I::intervals:continuous_interval(), ItemCount::1..1000, db_generator:db_distribution()) -> true. prop_get_db3(Interval, ItemCount0, Distribution0 = {non_uniform, RanGen}) -> ItemCount = erlang:min(ItemCount0, random_bias:numbers_left(RanGen)), prop_get_db3_(Interval, ItemCount, db_generator:feeder_fix_rangen(Distribution0, ItemCount)); prop_get_db3(Interval, ItemCount, Distribution) -> prop_get_db3_(Interval, ItemCount, Distribution). -spec prop_get_db3_(I::intervals:continuous_interval(), ItemCount::1..1000, db_generator:db_distribution()) -> true. prop_get_db3_(Interval, ItemCount, Distribution) -> Result = db_generator:get_db(Interval, ItemCount, Distribution), ?equals([Key || Key <- Result, not intervals:in(Key, Interval)], []), ?compare(fun erlang:'=<'/2, length(Result), ItemCount), ?equals(length(Result), length(lists:usort(Result))), ?implies(length(intervals:split(Interval, ItemCount)) == ItemCount, ?equals(length(Result), ItemCount)). -spec prop_get_db4(I::intervals:continuous_interval(), ItemCount::1..1000, db_generator:db_distribution(), Options::[db_generator:option()]) -> true. prop_get_db4(Interval, ItemCount0, Distribution0 = {non_uniform, RanGen}, Options) -> ItemCount = erlang:min(ItemCount0, random_bias:numbers_left(RanGen)), prop_get_db4_(Interval, ItemCount, db_generator:feeder_fix_rangen(Distribution0, ItemCount), Options); prop_get_db4(Interval, ItemCount, Distribution, Options) -> prop_get_db4_(Interval, ItemCount, Distribution, Options). -spec prop_get_db4_(I::intervals:continuous_interval(), ItemCount::1..1000, db_generator:db_distribution(), Options::[db_generator:option()]) -> true. prop_get_db4_(Interval, ItemCount, Distribution, Options) -> Result = db_generator:get_db(Interval, ItemCount, Distribution, Options), case proplists:get_value(output, Options, list_key) of list_key -> ?equals([Key || Key <- Result, not intervals:in(Key, Interval)], []); list_keytpl -> ?equals([Key || {Key} <- Result, not intervals:in(Key, Interval)], []); list_key_val -> ?equals([Key || {Key, _Val} <- Result, not intervals:in(Key, Interval)], []) end, ?compare(fun erlang:'=<'/2, length(Result), ItemCount), ?equals(length(Result), length(lists:usort(Result))), ?implies(length(intervals:split(Interval, ItemCount)) == ItemCount, ?equals(length(Result), ItemCount)). tester_get_db3(_Config) -> prop_get_db3(intervals:new(?MINUS_INFINITY), 844, random), tester:test(?MODULE, prop_get_db3, 3, 500, [{threads, 4}]). tester_get_db4(_Config) -> prop_get_db4(intervals:new(?MINUS_INFINITY), 1, {non_uniform, random_bias:binomial(50, 0.06755763133001705)}, [{output,list_key}]), tester:test(?MODULE, prop_get_db4, 4, 500, [{threads, 4}]).
ed1cf282d2469ecaa2d01ca698c842dd4e93a5de5e5305589beecfe6f9cf3357
robert-strandh/SICL
packages.lisp
(cl:in-package #:common-lisp-user) (defpackage #:sicl-boot-stealth-mixin (:use #:common-lisp) (:import-from #:sicl-boot #:load-source-file #:load-source-file-using-client #:ensure-asdf-system #:ensure-asdf-system-using-client #:import-functions-from-host) (:local-nicknames (#:env #:sicl-environment)) (:export #:boot))
null
https://raw.githubusercontent.com/robert-strandh/SICL/95bec48848029500a7a57f520e8bd86d95192c04/Code/Boot/Stealth-mixin/packages.lisp
lisp
(cl:in-package #:common-lisp-user) (defpackage #:sicl-boot-stealth-mixin (:use #:common-lisp) (:import-from #:sicl-boot #:load-source-file #:load-source-file-using-client #:ensure-asdf-system #:ensure-asdf-system-using-client #:import-functions-from-host) (:local-nicknames (#:env #:sicl-environment)) (:export #:boot))
b47a942cb527803a61ca3e268c1d3968ab914d32671a0a83320e486680489501
yokolet/clementine
string.cljs
Copyright ( c ) . All rights reserved . ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns clojure.string (:refer-clojure :exclude [replace reverse]) (:require [goog.string :as gstring] [goog.string.StringBuffer :as gstringbuf])) (defn- seq-reverse [coll] (reduce conj () coll)) (defn reverse "Returns s with its characters reversed." [s] (.. s (split "") (reverse) (join ""))) (defn replace "Replaces all instance of match with replacement in s. match/replacement can be: string / string pattern / (string or function of match)." [s match replacement] (cond (string? match) (.replace s (js/RegExp. (gstring/regExpEscape match) "g") replacement) (.hasOwnProperty match "source") (.replace s (js/RegExp. (.-source match) "g") replacement) :else (throw (str "Invalid match arg: " match)))) (defn replace-first "Replaces the first instance of match with replacement in s. match/replacement can be: string / string pattern / (string or function of match)." [s match replacement] (.replace s match replacement)) (defn join "Returns a string of all elements in coll, as returned by (seq coll), separated by an optional separator." ([coll] (apply str coll)) ([separator coll] (apply str (interpose separator coll)))) (defn upper-case "Converts string to all upper-case." [s] (. s (toUpperCase))) (defn lower-case "Converts string to all lower-case." [s] (. s (toLowerCase))) (defn capitalize "Converts first character of the string to upper-case, all other characters to lower-case." [s] (if (< (count s) 2) (upper-case s) (str (upper-case (subs s 0 1)) (lower-case (subs s 1))))) The JavaScript split function takes a limit argument but the return value is not the same as the Java split function . ;; Java : ( .split " a - b - c " # " - " 2 ) = > [ " a " " b - c " ] JavaScript : ( .split " a - b - c " # " - " 2 ) = > [ " a " " b " ] ;; For consistency , the three arg version has been implemented to mimic Java 's behavior . (defn split "Splits string on a regular expression. Optional argument limit is the maximum number of splits. Not lazy. Returns vector of the splits." ([s re] (vec (.split (str s) re))) ([s re limit] (if (< limit 1) (vec (.split (str s) re)) (loop [s s limit limit parts []] (if (= limit 1) (conj parts s) (if-let [m (re-find re s)] (let [index (.indexOf s m)] (recur (.substring s (+ index (count m))) (dec limit) (conj parts (.substring s 0 index)))) (conj parts s))))))) (defn split-lines "Splits s on \n or \r\n." [s] (split s #"\n|\r\n")) (defn trim "Removes whitespace from both ends of string." [s] (gstring/trim s)) (defn triml "Removes whitespace from the left side of string." [s] (gstring/trimLeft s)) (defn trimr "Removes whitespace from the right side of string." [s] (gstring/trimRight s)) (defn trim-newline "Removes all trailing newline \\n or return \\r characters from string. Similar to Perl's chomp." [s] (loop [index (.-length s)] (if (zero? index) "" (let [ch (get s (dec index))] (if (or (= ch \newline) (= ch \return)) (recur (dec index)) (.substring s 0 index)))))) (defn blank? "True is s is nil, empty, or contains only whitespace." [s] (gstring/isEmptySafe s)) (defn escape "Return a new string, using cmap to escape each character ch from s as follows: If (cmap ch) is nil, append ch to the new string. If (cmap ch) is non-nil, append (str (cmap ch)) instead." [s cmap] (let [buffer (gstring/StringBuffer.) length (.-length s)] (loop [index 0] (if (= length index) (. buffer (toString)) (let [ch (.charAt s index)] (if-let [replacement (get cmap ch)] (.append buffer (str replacement)) (.append buffer ch)) (recur (inc index)))))))
null
https://raw.githubusercontent.com/yokolet/clementine/b26c2318625e49606b5cc3b95cc9e1f5085ac309/ext/clojure-clojurescript-bef56a7/src/cljs/clojure/string.cljs
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software.
Copyright ( c ) . All rights reserved . (ns clojure.string (:refer-clojure :exclude [replace reverse]) (:require [goog.string :as gstring] [goog.string.StringBuffer :as gstringbuf])) (defn- seq-reverse [coll] (reduce conj () coll)) (defn reverse "Returns s with its characters reversed." [s] (.. s (split "") (reverse) (join ""))) (defn replace "Replaces all instance of match with replacement in s. match/replacement can be: string / string pattern / (string or function of match)." [s match replacement] (cond (string? match) (.replace s (js/RegExp. (gstring/regExpEscape match) "g") replacement) (.hasOwnProperty match "source") (.replace s (js/RegExp. (.-source match) "g") replacement) :else (throw (str "Invalid match arg: " match)))) (defn replace-first "Replaces the first instance of match with replacement in s. match/replacement can be: string / string pattern / (string or function of match)." [s match replacement] (.replace s match replacement)) (defn join "Returns a string of all elements in coll, as returned by (seq coll), separated by an optional separator." ([coll] (apply str coll)) ([separator coll] (apply str (interpose separator coll)))) (defn upper-case "Converts string to all upper-case." [s] (. s (toUpperCase))) (defn lower-case "Converts string to all lower-case." [s] (. s (toLowerCase))) (defn capitalize "Converts first character of the string to upper-case, all other characters to lower-case." [s] (if (< (count s) 2) (upper-case s) (str (upper-case (subs s 0 1)) (lower-case (subs s 1))))) The JavaScript split function takes a limit argument but the return value is not the same as the Java split function . Java : ( .split " a - b - c " # " - " 2 ) = > [ " a " " b - c " ] JavaScript : ( .split " a - b - c " # " - " 2 ) = > [ " a " " b " ] For consistency , the three arg version has been implemented to mimic Java 's behavior . (defn split "Splits string on a regular expression. Optional argument limit is the maximum number of splits. Not lazy. Returns vector of the splits." ([s re] (vec (.split (str s) re))) ([s re limit] (if (< limit 1) (vec (.split (str s) re)) (loop [s s limit limit parts []] (if (= limit 1) (conj parts s) (if-let [m (re-find re s)] (let [index (.indexOf s m)] (recur (.substring s (+ index (count m))) (dec limit) (conj parts (.substring s 0 index)))) (conj parts s))))))) (defn split-lines "Splits s on \n or \r\n." [s] (split s #"\n|\r\n")) (defn trim "Removes whitespace from both ends of string." [s] (gstring/trim s)) (defn triml "Removes whitespace from the left side of string." [s] (gstring/trimLeft s)) (defn trimr "Removes whitespace from the right side of string." [s] (gstring/trimRight s)) (defn trim-newline "Removes all trailing newline \\n or return \\r characters from string. Similar to Perl's chomp." [s] (loop [index (.-length s)] (if (zero? index) "" (let [ch (get s (dec index))] (if (or (= ch \newline) (= ch \return)) (recur (dec index)) (.substring s 0 index)))))) (defn blank? "True is s is nil, empty, or contains only whitespace." [s] (gstring/isEmptySafe s)) (defn escape "Return a new string, using cmap to escape each character ch from s as follows: If (cmap ch) is nil, append ch to the new string. If (cmap ch) is non-nil, append (str (cmap ch)) instead." [s cmap] (let [buffer (gstring/StringBuffer.) length (.-length s)] (loop [index 0] (if (= length index) (. buffer (toString)) (let [ch (.charAt s index)] (if-let [replacement (get cmap ch)] (.append buffer (str replacement)) (.append buffer ch)) (recur (inc index)))))))
2e724f715aad74477bea0d26fc26a90eb9b47601d8bd4446c8c62d89eed4bdf1
sarabander/p2pu-sicp
Ex1.5.scm
Exercise 1.5 (define (p) (p)) (define (test x y) (if (= x 0) 0 y)) (test 0 (p)) (test 0 7) (test 3 -4) applicative order - arguments will be evaluated first , ;; then procedure will be applied to them - therefore procedure (p) in ( test 0 ( p ) ) will be called immediately . ;; Result is an infinite loop. ;; ;; normal order - evaluation of the arguments will be postponed ;; until they are needed. The arguments of (test ) will be passed unevaluated to the procedure body . In the case of ( test 0 ( p ) ) , ;; the execution never reaches (p) because of the predicate (= x 0).
null
https://raw.githubusercontent.com/sarabander/p2pu-sicp/fbc49b67dac717da1487629fb2d7a7d86dfdbe32/1.1/Ex1.5.scm
scheme
then procedure will be applied to them - therefore procedure (p) Result is an infinite loop. normal order - evaluation of the arguments will be postponed until they are needed. The arguments of (test ) will be passed the execution never reaches (p) because of the predicate (= x 0).
Exercise 1.5 (define (p) (p)) (define (test x y) (if (= x 0) 0 y)) (test 0 (p)) (test 0 7) (test 3 -4) applicative order - arguments will be evaluated first , in ( test 0 ( p ) ) will be called immediately . unevaluated to the procedure body . In the case of ( test 0 ( p ) ) ,
525b86e9dc5b452b1fda3d10cd807aa9e58f7feeed5c7788702cb08e8aefead5
mitchellwrosen/planet-mitchell
Lazy.hs
module Map.Int.Lazy ( module Data.IntMap.Lazy ) where import Data.IntMap.Lazy
null
https://raw.githubusercontent.com/mitchellwrosen/planet-mitchell/18dd83204e70fffcd23fe12dd3a80f70b7fa409b/planet-mitchell/src/Map/Int/Lazy.hs
haskell
module Map.Int.Lazy ( module Data.IntMap.Lazy ) where import Data.IntMap.Lazy
f3c7cf6c57005aff9a28058fe166b9b8fbdfaa6ef40af368b159bd6a35d2e6d3
aantron/luv
condition.ml
This file is part of Luv , released under the MIT license . See LICENSE.md for details , or visit . details, or visit . *) type t = C.Types.Condition.t Ctypes.ptr let init () = let condition = Ctypes.addr (Ctypes.make C.Types.Condition.t) in C.Functions.Condition.init condition |> Error.to_result condition let destroy = C.Functions.Condition.destroy let signal = C.Functions.Condition.signal let broadcast = C.Functions.Condition.broadcast let wait = C.Blocking.Condition.wait let timedwait condition mutex interval = C.Blocking.Condition.timedwait condition mutex (Unsigned.UInt64.of_int interval) |> Error.to_result ()
null
https://raw.githubusercontent.com/aantron/luv/4b49d3edad2179c76d685500edf1b44f61ec4be8/src/condition.ml
ocaml
This file is part of Luv , released under the MIT license . See LICENSE.md for details , or visit . details, or visit . *) type t = C.Types.Condition.t Ctypes.ptr let init () = let condition = Ctypes.addr (Ctypes.make C.Types.Condition.t) in C.Functions.Condition.init condition |> Error.to_result condition let destroy = C.Functions.Condition.destroy let signal = C.Functions.Condition.signal let broadcast = C.Functions.Condition.broadcast let wait = C.Blocking.Condition.wait let timedwait condition mutex interval = C.Blocking.Condition.timedwait condition mutex (Unsigned.UInt64.of_int interval) |> Error.to_result ()
e73cc9cecce6ab33c6fd7c01ad0ec9de78e6045d8907b4c820029613718be142
onedata/op-worker
dataset_rest_routes.erl
%%%-------------------------------------------------------------------- %%% This file has been automatically generated from Swagger %%% specification - DO NOT EDIT! %%% ( C ) 2019 - 2021 ACK CYFRONET AGH This software is released under the MIT license cited in ' LICENSE.txt ' . %%% @end %%%-------------------------------------------------------------------- %%% @doc %%% This module contains definitions of dataset REST methods. %%% @end %%%-------------------------------------------------------------------- -module(dataset_rest_routes). -include("http/rest.hrl"). -export([routes/0]). %%%=================================================================== %%% API %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Definitions of dataset REST paths. %% @end %%-------------------------------------------------------------------- -spec routes() -> [{binary(), module(), #rest_req{}}]. routes() -> [ %% List space top datasets {<<"/spaces/:sid/datasets">>, rest_handler, #rest_req{ method = 'GET', produces = [<<"application/json">>], b_gri = #b_gri{ type = op_space, id = ?BINDING(sid), aspect = datasets, scope = private } }}, %% List child datasets of a dataset {<<"/datasets/:did/children">>, rest_handler, #rest_req{ method = 'GET', produces = [<<"application/json">>], b_gri = #b_gri{ type = op_dataset, id = ?BINDING(did), aspect = children, scope = private } }}, Establish dataset {<<"/datasets">>, rest_handler, #rest_req{ method = 'POST', parse_body = as_json_params, consumes = [<<"application/json">>], produces = [<<"application/json">>], b_gri = #b_gri{ type = op_dataset, id = undefined, aspect = instance, scope = private } }}, %% Remove dataset {<<"/datasets/:did">>, rest_handler, #rest_req{ method = 'DELETE', b_gri = #b_gri{ type = op_dataset, id = ?BINDING(did), aspect = instance, scope = private } }}, %% Get dataset information {<<"/datasets/:did">>, rest_handler, #rest_req{ method = 'GET', produces = [<<"application/json">>], b_gri = #b_gri{ type = op_dataset, id = ?BINDING(did), aspect = instance, scope = private } }}, %% Update dataset {<<"/datasets/:did">>, rest_handler, #rest_req{ method = 'PATCH', parse_body = as_json_params, consumes = [<<"application/json">>], b_gri = #b_gri{ type = op_dataset, id = ?BINDING(did), aspect = instance, scope = private } }}, %% Get dataset summary for file or directory {<<"/data/:id/dataset/summary">>, rest_handler, #rest_req{ method = 'GET', produces = [<<"application/json">>], b_gri = #b_gri{ type = op_file, id = ?OBJECTID_BINDING(id), aspect = dataset_summary, scope = private } }} ].
null
https://raw.githubusercontent.com/onedata/op-worker/a06e0e0064e2cbea4706df1dc2dde12e0aa77091/src/http/rest/routes/dataset_rest_routes.erl
erlang
-------------------------------------------------------------------- This file has been automatically generated from Swagger specification - DO NOT EDIT! @end -------------------------------------------------------------------- @doc This module contains definitions of dataset REST methods. @end -------------------------------------------------------------------- =================================================================== API =================================================================== -------------------------------------------------------------------- @doc Definitions of dataset REST paths. @end -------------------------------------------------------------------- List space top datasets List child datasets of a dataset Remove dataset Get dataset information Update dataset Get dataset summary for file or directory
( C ) 2019 - 2021 ACK CYFRONET AGH This software is released under the MIT license cited in ' LICENSE.txt ' . -module(dataset_rest_routes). -include("http/rest.hrl"). -export([routes/0]). -spec routes() -> [{binary(), module(), #rest_req{}}]. routes() -> [ {<<"/spaces/:sid/datasets">>, rest_handler, #rest_req{ method = 'GET', produces = [<<"application/json">>], b_gri = #b_gri{ type = op_space, id = ?BINDING(sid), aspect = datasets, scope = private } }}, {<<"/datasets/:did/children">>, rest_handler, #rest_req{ method = 'GET', produces = [<<"application/json">>], b_gri = #b_gri{ type = op_dataset, id = ?BINDING(did), aspect = children, scope = private } }}, Establish dataset {<<"/datasets">>, rest_handler, #rest_req{ method = 'POST', parse_body = as_json_params, consumes = [<<"application/json">>], produces = [<<"application/json">>], b_gri = #b_gri{ type = op_dataset, id = undefined, aspect = instance, scope = private } }}, {<<"/datasets/:did">>, rest_handler, #rest_req{ method = 'DELETE', b_gri = #b_gri{ type = op_dataset, id = ?BINDING(did), aspect = instance, scope = private } }}, {<<"/datasets/:did">>, rest_handler, #rest_req{ method = 'GET', produces = [<<"application/json">>], b_gri = #b_gri{ type = op_dataset, id = ?BINDING(did), aspect = instance, scope = private } }}, {<<"/datasets/:did">>, rest_handler, #rest_req{ method = 'PATCH', parse_body = as_json_params, consumes = [<<"application/json">>], b_gri = #b_gri{ type = op_dataset, id = ?BINDING(did), aspect = instance, scope = private } }}, {<<"/data/:id/dataset/summary">>, rest_handler, #rest_req{ method = 'GET', produces = [<<"application/json">>], b_gri = #b_gri{ type = op_file, id = ?OBJECTID_BINDING(id), aspect = dataset_summary, scope = private } }} ].
e297fcc7d36b64493e6a64eec637cecce91eced000b43ab8c7506acd2676daf5
avsm/platform
opamSwitch.mli
(**************************************************************************) (* *) Copyright 2012 - 2015 OCamlPro Copyright 2012 INRIA (* *) (* All rights reserved. This file is distributed under the terms of the *) GNU Lesser General Public License version 2.1 , with the special (* exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (** The type for switch names *) include OpamStd.ABSTRACT (** System switch name *) val unset: t (** Determines wether this switch is internal (bound to a prefix within the opam root) or living somewhere else, in which case its prefix dir is inferred from its name using [get_root] *) val is_external: t -> bool (** Returns the root directory of the switch with the given name, assuming the given opam root *) val get_root: OpamFilename.Dir.t -> t -> OpamFilename.Dir.t (** The relative dirname in which the opam switch prefix sits for external switches ("_opam") *) val external_dirname: string (** Returns an external switch handle from a directory name. Resolves to the destination if [external_dirname] at the given dir is a symlink to another [external_dirname]. *) val of_dirname: OpamFilename.Dir.t -> t
null
https://raw.githubusercontent.com/avsm/platform/b254e3c6b60f3c0c09dfdcde92eb1abdc267fa1c/duniverse/opam-client.2.0.5%2Bdune/src/format/opamSwitch.mli
ocaml
************************************************************************ All rights reserved. This file is distributed under the terms of the exception on linking described in the file LICENSE. ************************************************************************ * The type for switch names * System switch name * Determines wether this switch is internal (bound to a prefix within the opam root) or living somewhere else, in which case its prefix dir is inferred from its name using [get_root] * Returns the root directory of the switch with the given name, assuming the given opam root * The relative dirname in which the opam switch prefix sits for external switches ("_opam") * Returns an external switch handle from a directory name. Resolves to the destination if [external_dirname] at the given dir is a symlink to another [external_dirname].
Copyright 2012 - 2015 OCamlPro Copyright 2012 INRIA GNU Lesser General Public License version 2.1 , with the special include OpamStd.ABSTRACT val unset: t val is_external: t -> bool val get_root: OpamFilename.Dir.t -> t -> OpamFilename.Dir.t val external_dirname: string val of_dirname: OpamFilename.Dir.t -> t
759c492d546b168f2e7489dd8703b8b2121b66f69ac7690c4ec3a83988447449
MLstate/opalang
RAList.mli
(** result of a comparison *) type comparison = Lesser | Equal | Greater (** invalid access of the ith element when only n elements (Invalid_subscript(i,n)) *) exception Invalid_subscript of (int*int) (** invalid operation on empty ra_list *) exception Empty type 'a ra_list * classic operations of list , all O(1 ) module AsList : sig exception StopFold (*to implement fold until *) val is_empty : 'a ra_list -> bool val empty : 'a ra_list val cons : 'a -> 'a ra_list -> 'a ra_list val head : 'a ra_list -> 'a (* raise Empty *) val tail : 'a ra_list -> 'a ra_list (* raise Empty *) catch StopFold to implement fold until catch StopFold to implement fold until end (** classic operations of functional array, O(ln(N)) *) module AsArray : sig val size : 'a ra_list -> int val get : 'a ra_list -> int -> 'a (* raise Invalid_subscript *) val update : 'a ra_list -> int -> 'a -> 'a ra_list (* raise Invalid_subscript *) end module AsMonotoniousList : sig (** return the lastest entry that is <= hypothetical asked entry, via the comparison function which asked entry has already been passed to (facilitate comparison on projection) *) val get_lesser : ('a -> comparison ) -> 'a ra_list -> 'a (* raise Not_found *) (* val get *) end
null
https://raw.githubusercontent.com/MLstate/opalang/424b369160ce693406cece6ac033d75d85f5df4f/ocamllib/libbase/RAList.mli
ocaml
* result of a comparison * invalid access of the ith element when only n elements (Invalid_subscript(i,n)) * invalid operation on empty ra_list to implement fold until raise Empty raise Empty * classic operations of functional array, O(ln(N)) raise Invalid_subscript raise Invalid_subscript * return the lastest entry that is <= hypothetical asked entry, via the comparison function which asked entry has already been passed to (facilitate comparison on projection) raise Not_found val get
type comparison = Lesser | Equal | Greater exception Invalid_subscript of (int*int) exception Empty type 'a ra_list * classic operations of list , all O(1 ) module AsList : sig val is_empty : 'a ra_list -> bool val empty : 'a ra_list val cons : 'a -> 'a ra_list -> 'a ra_list catch StopFold to implement fold until catch StopFold to implement fold until end module AsArray : sig val size : 'a ra_list -> int end module AsMonotoniousList : sig end
b24464e571a36abd9aa98b85c79d5139bd66574bb6f5b500a6f69dc51f59733e
HaskellForCats/HaskellForCats
3_b_Lists.hs
module Ch1Lists where import Data.Char import Test.QuickCheck -- Lists are the primary data structure in LISP like languages. Where as Arrays are the primary data collection in C derived languages like Java . examp1 = [x*x | x <- [1,2,3] ] -- [1,4,9] examp2 = [toLower c | c <- "Hello From Haskell"] " hello from " examp3 = [ (x, even x) | x <- [1,2,3] ] -- [(1,False),(2,True),(3,False)] {------ notes ------------------------------- [x*x | x <- [1,2,3] ] is a list comprehension x <- [1,2,3] is a generator <- means "drawn from" [(1,False).....] pairs in a list | are guards and they evaluate true or false isLower Converts a letter to the corresponding lower-case letter, if any. Any other character is returned unchanged. ------------------------------------------} examp4 = [x|x <-[1..5], odd x] -- [1,3,5] examp5 = [x*x | x <-[1..5], odd x] [ 1,9,25 ] examp6 = [x|x <- [42, -5, 24, 0, -3], x >= 0] [ 42,24,0 ] examp7 = [ toLower c | c <- "Hello, World!", isAlpha c ] -- "helloworld" {------ notes ------------------------------- isAlpha Selects alphabetic Unicode characters (lower-case, upper-case and title-case letters, plus letters of caseless scripts and modifiers letters). ------------------------------------------} f1 = sum [1,2,3] 6 f2 = sum [] -- 0 f3 = sum [x*x| x <- [1,2,3], odd x] 10 f4 = product [1,2,3,4] 24 f5 = product [] 1 factorial n = product [1..n] f6 = factorial 4 24 ----- notes ------------------------------- When you encounter a function you can politely ask Are you Associative ? What is you identity element ? For + and - it will be 0 For * and / it will be 1 for [ ] it my be 1 or 0 [ 1 .. n ] a list from 1 to whatever n is eager oop languages would hate this notation and choke on trying to call a potentially infinite list ----------------------------------------- When you encounter a function you can politely ask Are you Associative? What is you identity element? For + and - it will be 0 For * and / it will be 1 for [] it my be 1 or 0 [1..n] a list from 1 to whatever n is eager oop languages would hate this notation and choke on trying to call a potentially infinite list ------------------------------------------} squares :: [Integer] -> [Integer] squares xs = [x * x | x <- xs] odds :: [Integer] -> [Integer] odds xs = [x|x <- xs, odd x] sumSqOdd :: [Integer] -> Integer sumSqOdd xs = sum [x*x | x <- xs, odd x] ------ QuickCheck required here ---------------- -- prop_sumSqOdd :: [Integer] -> Bool prop_sumSqOdd xs = sum (squares (odds xs)) == sumSqOdd xs -------------------------------------------- Running quickCheck from the prompt with prop_sumSqOdd as it 's argument . * Ch1Lists > quickCheck prop_sumSqOdd Loading package array-0.4.0.1 ... linking ... done . Loading package deepseq-1.3.0.1 ... linking ... done . Loading package bytestring-0.10.0.2 ... linking ... done . Loading package Win32 - 2.3.0.0 ... linking ... done . Loading package old - locale-1.0.0.5 ... linking ... done . Loading package time-1.4.0.1 ... linking ... done . Loading package random-1.0.1.1 ... linking ... done . Loading package containers-0.5.0.0 ... linking ... done . Loading package pretty-1.1.1.0 ... linking ... done . Loading package template - haskell ... linking ... done . Loading package QuickCheck-2.6 ... linking ... done . + + + OK , passed 100 tests . ------------------------------------------------------ Running quickCheck from the prompt with prop_sumSqOdd as it's argument. *Ch1Lists> quickCheck prop_sumSqOdd Loading package array-0.4.0.1 ... linking ... done. Loading package deepseq-1.3.0.1 ... linking ... done. Loading package bytestring-0.10.0.2 ... linking ... done. Loading package Win32-2.3.0.0 ... linking ... done. Loading package old-locale-1.0.0.5 ... linking ... done. Loading package time-1.4.0.1 ... linking ... done. Loading package random-1.0.1.1 ... linking ... done. Loading package containers-0.5.0.0 ... linking ... done. Loading package pretty-1.1.1.0 ... linking ... done. Loading package template-haskell ... linking ... done. Loading package QuickCheck-2.6 ... linking ... done. +++ OK, passed 100 tests. -------------------------------------------------------}
null
https://raw.githubusercontent.com/HaskellForCats/HaskellForCats/2d7a15c0cdaa262c157bbf37af6e72067bc279bc/30MinHaskell/z_notes/3_b_Lists.hs
haskell
Lists are the primary data structure in LISP like languages. [1,4,9] [(1,False),(2,True),(3,False)] ----- notes ------------------------------- [x*x | x <- [1,2,3] ] is a list comprehension x <- [1,2,3] is a generator <- means "drawn from" [(1,False).....] pairs in a list | are guards and they evaluate true or false isLower Converts a letter to the corresponding lower-case letter, if any. Any other character is returned unchanged. ----------------------------------------- [1,3,5] "helloworld" ----- notes ------------------------------- isAlpha Selects alphabetic Unicode characters (lower-case, upper-case and title-case letters, plus letters of caseless scripts and modifiers letters). ----------------------------------------- 0 --- notes ------------------------------- --------------------------------------- ----------------------------------------} ---- QuickCheck required here ---------------- prop_sumSqOdd :: [Integer] -> Bool ------------------------------------------ ---------------------------------------------------- -----------------------------------------------------}
module Ch1Lists where import Data.Char import Test.QuickCheck Where as Arrays are the primary data collection in C derived languages like Java . examp1 = [x*x | x <- [1,2,3] ] examp2 = [toLower c | c <- "Hello From Haskell"] " hello from " examp3 = [ (x, even x) | x <- [1,2,3] ] examp4 = [x|x <-[1..5], odd x] examp5 = [x*x | x <-[1..5], odd x] [ 1,9,25 ] examp6 = [x|x <- [42, -5, 24, 0, -3], x >= 0] [ 42,24,0 ] examp7 = [ toLower c | c <- "Hello, World!", isAlpha c ] f1 = sum [1,2,3] 6 f2 = sum [] f3 = sum [x*x| x <- [1,2,3], odd x] 10 f4 = product [1,2,3,4] 24 f5 = product [] 1 factorial n = product [1..n] f6 = factorial 4 24 When you encounter a function you can politely ask Are you Associative ? What is you identity element ? For + and - it will be 0 For * and / it will be 1 for [ ] it my be 1 or 0 [ 1 .. n ] a list from 1 to whatever n is eager oop languages would hate this notation and choke on trying to call a potentially infinite list When you encounter a function you can politely ask Are you Associative? What is you identity element? For + and - it will be 0 For * and / it will be 1 for [] it my be 1 or 0 [1..n] a list from 1 to whatever n is eager oop languages would hate this notation and choke on trying to call a potentially infinite list squares :: [Integer] -> [Integer] squares xs = [x * x | x <- xs] odds :: [Integer] -> [Integer] odds xs = [x|x <- xs, odd x] sumSqOdd :: [Integer] -> Integer sumSqOdd xs = sum [x*x | x <- xs, odd x] prop_sumSqOdd xs = sum (squares (odds xs)) == sumSqOdd xs Running quickCheck from the prompt with prop_sumSqOdd as it 's argument . * Ch1Lists > quickCheck prop_sumSqOdd Loading package array-0.4.0.1 ... linking ... done . Loading package deepseq-1.3.0.1 ... linking ... done . Loading package bytestring-0.10.0.2 ... linking ... done . Loading package Win32 - 2.3.0.0 ... linking ... done . Loading package old - locale-1.0.0.5 ... linking ... done . Loading package time-1.4.0.1 ... linking ... done . Loading package random-1.0.1.1 ... linking ... done . Loading package containers-0.5.0.0 ... linking ... done . Loading package pretty-1.1.1.0 ... linking ... done . Loading package template - haskell ... linking ... done . Loading package QuickCheck-2.6 ... linking ... done . + + + OK , passed 100 tests . Running quickCheck from the prompt with prop_sumSqOdd as it's argument. *Ch1Lists> quickCheck prop_sumSqOdd Loading package array-0.4.0.1 ... linking ... done. Loading package deepseq-1.3.0.1 ... linking ... done. Loading package bytestring-0.10.0.2 ... linking ... done. Loading package Win32-2.3.0.0 ... linking ... done. Loading package old-locale-1.0.0.5 ... linking ... done. Loading package time-1.4.0.1 ... linking ... done. Loading package random-1.0.1.1 ... linking ... done. Loading package containers-0.5.0.0 ... linking ... done. Loading package pretty-1.1.1.0 ... linking ... done. Loading package template-haskell ... linking ... done. Loading package QuickCheck-2.6 ... linking ... done. +++ OK, passed 100 tests.
7453ce200e4d2a66dffc89b8d723eb4d0aa6c85687c9dc6ce27ddb1799583e33
nshimaza/thread-supervisor
SupervisorSpec.hs
# OPTIONS_GHC -Wno - orphans # # OPTIONS_GHC -Wno - type - defaults # module Control.Concurrent.SupervisorSpec where import Data.Default (def) import Data.Foldable (for_) import Data.Functor (($>)) import Data.List (unzip4) import Data.Maybe (isJust, isNothing) import Data.Traversable (for) import Data.Typeable (typeOf) import System.Clock (TimeSpec (..)) import UnliftIO (StringException (..), async, asyncThreadId, atomically, cancel, fromException, isEmptyMVar, mask_, newEmptyMVar, newTQueueIO, newTVarIO, poll, putMVar, readMVar, readTQueue, readTVarIO, takeMVar, throwString, wait, withAsync, withAsyncWithUnmask, writeTQueue, writeTVar) import UnliftIO.Concurrent (killThread, myThreadId, threadDelay) import Test.Hspec import Test.Hspec.QuickCheck import Control.Concurrent.Supervisor hiding (length) {-# ANN module "HLint: ignore Reduce duplication" #-} {-# ANN module "HLint: ignore Use head" #-} instance Eq ExitReason where (UncaughtException _) == _ = error "should not compare exception by Eq" _ == (UncaughtException _) = error "should not compare exception by Eq" Normal == Normal = True Killed == Killed = True _ == _ = False reasonToString :: ExitReason -> String reasonToString (UncaughtException e) = toStr $ fromException e where toStr (Just (StringException str _)) = str toStr _ = error "Not a StringException" reasonToString _ = error "ExitReason is not Uncaught Exception" data ConstServerCmd = AskFst (ServerCallback Int) | AskSnd (ServerCallback Char) data TickerServerCmd = Tick (ServerCallback Int) | Tack tickerServer :: Inbox TickerServerCmd -> IO Int tickerServer = newStateMachine 0 handler where handler s (Tick cont) = cont s $> Right (s + 1) handler s Tack = pure $ Right (s + 1) data SimpleCountingServerCmd = CountUp (ServerCallback Int) | Finish simpleCountingServer :: Int -> Inbox SimpleCountingServerCmd -> IO Int simpleCountingServer n = newStateMachine n handler where handler s (CountUp cont) = cont s $> Right (s + 1) handler s Finish = pure (Left s) callCountUp :: ActorQ SimpleCountingServerCmd -> IO (Maybe Int) callCountUp q = call def q CountUp castFinish :: ActorQ SimpleCountingServerCmd -> IO () castFinish q = cast q Finish spec :: Spec spec = do describe "Actor" $ do prop "accepts ActorHandler and returns action with ActorQ" $ \n -> do Actor actorQ action <- newActor receive send actorQ (n :: Int) r2 <- action r2 `shouldBe` n prop "can send a message to itself" $ \n -> do Actor actorQ action <- newActor $ \inbox -> do msg <- receive inbox sendToMe inbox (msg + 1) receive inbox send actorQ (n :: Int) r2 <- action r2 `shouldBe` (n + 1) describe "State machine behavior" $ do it "returns result when event handler returns Left" $ do Actor actorQ statem <- newActor $ newStateMachine () $ \_ _ -> pure $ Left "Hello" send actorQ () r <- statem r `shouldBe` "Hello" it "consumes message in the queue until exit" $ do let until5 q 5 = pure $ Left ("Done", q) until5 q _ = pure $ Right q actorHandler inbox = newStateMachine inbox until5 inbox Actor actorQ statem <- newActor actorHandler for_ [1..7] $ send actorQ (r, lastQ) <- statem r `shouldBe` "Done" msg <- receive lastQ msg `shouldBe` 6 it "passes next state with Right" $ do let handler True _ = pure $ Right False handler False _ = pure $ Left "Finished" Actor actorQ statem <- newActor $ newStateMachine True handler for_ [(), ()] $ send actorQ r <- statem r `shouldBe` "Finished" it "runs state machine by consuming messages until handler returns Left" $ do let handler n 10 = pure $ Left (n + 10) handler n x = pure $ Right (n + x) Actor actorQ statem <- newActor $ newStateMachine 0 handler for_ [1..100] $ send actorQ r <- statem r `shouldBe` 55 describe "Server" $ do it "has call method which return value synchronously" $ do let handler s (AskFst cont) = cont (fst s) $> Right s handler s (AskSnd cont) = cont (snd s) $> Right s Actor srvQ srv <- newActor $ newStateMachine (1, 'a') handler withAsync srv $ \_ -> do r1 <- call def srvQ AskFst r1 `shouldBe` Just 1 r2 <- call def srvQ AskSnd r2 `shouldBe` Just 'a' it "keeps its own state and cast changes the state" $ do Actor srvQ srv <- newActor tickerServer withAsync srv $ \_ -> do r1 <- call def srvQ Tick r1 `shouldBe` Just 0 cast srvQ Tack r2 <- call def srvQ Tick r2 `shouldBe` Just 2 it "keeps its own state and callIgnore changes the state" $ do Actor srvQ srv <- newActor tickerServer withAsync srv $ \_ -> do r1 <- call def srvQ Tick r1 `shouldBe` Just 0 callIgnore srvQ Tick r2 <- call def srvQ Tick r2 `shouldBe` Just 2 it "keeps its own state and call can change the state" $ do Actor srvQ srv <- newActor $ simpleCountingServer 0 withAsync srv $ \_ -> do r1 <- callCountUp srvQ r1 `shouldBe` Just 0 r2 <- callCountUp srvQ r2 `shouldBe` Just 1 it "timeouts call method when server is not responding" $ do blocker <- newEmptyMVar let handler _ _ = takeMVar blocker $> Right () Actor srvQ srv <- newActor $ newStateMachine () handler withAsync srv $ \_ -> do r1 <- call (CallTimeout 10000) srvQ AskFst (r1 :: Maybe Int) `shouldBe` Nothing describe "Monitored IO action" $ do it "reports exit code Normal on normal exit" $ do trigger <- newEmptyMVar mark <- newEmptyMVar let monitor reason tid = putMVar mark (reason, tid) monitoredAction = watch monitor $ readMVar trigger $> () mask_ $ withAsyncWithUnmask monitoredAction $ \a -> do noReport <- isEmptyMVar mark noReport `shouldBe` True putMVar trigger () report <- takeMVar mark report `shouldBe` (Normal, asyncThreadId a) it "reports exit code UncaughtException on synchronous exception which wasn't caught" $ do trigger <- newEmptyMVar mark <- newEmptyMVar let monitor reason tid = putMVar mark (reason, tid) monitoredAction = watch monitor $ readMVar trigger *> throwString "oops" $> () mask_ $ withAsyncWithUnmask monitoredAction $ \a -> do noReport <- isEmptyMVar mark noReport `shouldBe` True putMVar trigger () (reason, tid) <- takeMVar mark tid `shouldBe` asyncThreadId a reasonToString reason `shouldBe` "oops" it "reports exit code Killed when it received asynchronous exception" $ do blocker <- newEmptyMVar mark <- newEmptyMVar let monitor reason tid = putMVar mark (reason, tid) monitoredAction = watch monitor $ readMVar blocker $> () mask_ $ withAsyncWithUnmask monitoredAction $ \a -> do noReport <- isEmptyMVar mark noReport `shouldBe` True cancel a report <- takeMVar mark report `shouldBe` (Killed, asyncThreadId a) it "can nest monitors and notify its normal exit to both" $ do trigger <- newEmptyMVar mark1 <- newEmptyMVar mark2 <- newEmptyMVar let monitor1 reason tid = putMVar mark1 (reason, tid) monitoredAction1 = watch monitor1 $ readMVar trigger $> () monitor2 reason tid = putMVar mark2 (reason, tid) monitoredAction2 = nestWatch monitor2 monitoredAction1 mask_ $ withAsyncWithUnmask monitoredAction2 $ \a -> do noReport1 <- isEmptyMVar mark1 noReport1 `shouldBe` True noReport2 <- isEmptyMVar mark2 noReport2 `shouldBe` True putMVar trigger () report1 <- takeMVar mark1 report1 `shouldBe` (Normal, asyncThreadId a) report2 <- takeMVar mark2 report2 `shouldBe` (Normal, asyncThreadId a) it "can nest monitors and notify UncaughtException to both" $ do trigger <- newEmptyMVar mark1 <- newEmptyMVar mark2 <- newEmptyMVar let monitor1 reason tid = putMVar mark1 (reason, tid) monitoredAction1 = watch monitor1 $ readMVar trigger *> throwString "oops" $> () monitor2 reason tid = putMVar mark2 (reason, tid) monitoredAction2 = nestWatch monitor2 monitoredAction1 mask_ $ withAsyncWithUnmask monitoredAction2 $ \a -> do noReport1 <- isEmptyMVar mark1 noReport1 `shouldBe` True noReport2 <- isEmptyMVar mark2 noReport2 `shouldBe` True putMVar trigger () (reason1, tid1) <- takeMVar mark1 tid1 `shouldBe` asyncThreadId a reasonToString reason1 `shouldBe` "oops" (reason2, tid2) <- takeMVar mark2 tid2 `shouldBe` asyncThreadId a reasonToString reason2 `shouldBe` "oops" it "can nest monitors and notify Killed to both" $ do blocker <- newEmptyMVar mark1 <- newEmptyMVar mark2 <- newEmptyMVar let monitor1 reason tid = putMVar mark1 (reason, tid) monitoredAction1 = watch monitor1 $ readMVar blocker $> () monitor2 reason tid = putMVar mark2 (reason, tid) monitoredAction2 = nestWatch monitor2 monitoredAction1 mask_ $ withAsyncWithUnmask monitoredAction2 $ \a -> do noReport1 <- isEmptyMVar mark1 noReport1 `shouldBe` True noReport2 <- isEmptyMVar mark2 noReport2 `shouldBe` True cancel a report1 <- takeMVar mark1 report1 `shouldBe` (Killed, asyncThreadId a) report2 <- takeMVar mark2 report2 `shouldBe` (Killed, asyncThreadId a) it "can nest many monitors and notify its normal exit to all" $ do trigger <- newEmptyMVar marks <- for [1..100] $ const newEmptyMVar let monitors = map (\mark reason tid -> putMVar mark (reason, tid)) marks nestedMonitoredAction = foldr nestWatch (noWatch $ readMVar trigger $> ()) monitors mask_ $ withAsyncWithUnmask nestedMonitoredAction $ \a -> do noReports <- for marks isEmptyMVar noReports `shouldSatisfy` and putMVar trigger () reports <- for marks takeMVar reports `shouldSatisfy` all (== (Normal, asyncThreadId a)) it "can nest many monitors and notify UncaughtException to all" $ do trigger <- newEmptyMVar marks <- for [1..100] $ const newEmptyMVar let monitors = map (\mark reason tid -> putMVar mark (reason, tid)) marks nestedMonitoredAction = foldr nestWatch (noWatch $ readMVar trigger *> throwString "oops" $> ()) monitors mask_ $ withAsyncWithUnmask nestedMonitoredAction $ \a -> do noReports <- for marks isEmptyMVar noReports `shouldSatisfy` and putMVar trigger () reports <- for marks takeMVar reports `shouldSatisfy` all ((==) (asyncThreadId a) . snd) reports `shouldSatisfy` all ((==) "oops" . reasonToString . fst) it "can nest many monitors and notify Killed to all" $ do blocker <- newEmptyMVar marks <- for [1..100] $ const newEmptyMVar let monitors = map (\mark reason tid -> putMVar mark (reason, tid)) marks nestedMonitoredAction = foldr nestWatch (noWatch $ readMVar blocker $> ()) monitors mask_ $ withAsyncWithUnmask nestedMonitoredAction $ \a -> do noReports <- for marks isEmptyMVar noReports `shouldSatisfy` and cancel a reports <- for marks takeMVar reports `shouldSatisfy` all (== (Killed, asyncThreadId a)) describe "SimpleOneForOneSupervisor" $ do it "starts a dynamic child" $ do trigger <- newEmptyMVar mark <- newEmptyMVar blocker <- newEmptyMVar var <- newTVarIO (0 :: Int) Actor svQ sv <- newActor newSimpleOneForOneSupervisor withAsync sv $ \_ -> do maybeChildAsync <- newChild def svQ $ newChildSpec Temporary $ do readMVar trigger atomically $ writeTVar var 1 putMVar mark () _ <- readMVar blocker pure () isJust maybeChildAsync `shouldBe` True currentVal0 <- readTVarIO var currentVal0 `shouldBe` 0 putMVar trigger () readMVar mark currentVal1 <- readTVarIO var currentVal1 `shouldBe` 1 it "does not restart finished dynamic child regardless restart type" $ do Actor svQ sv <- newActor newSimpleOneForOneSupervisor withAsync sv $ \_ -> for_ [Permanent, Transient, Temporary] $ \restart -> do startMark <- newEmptyMVar trigger <- newEmptyMVar finishMark <- newEmptyMVar Just _ <- newChild def svQ $ newChildSpec restart $ do putMVar startMark () readMVar trigger putMVar finishMark () pure () takeMVar startMark putMVar trigger () takeMVar finishMark threadDelay 1000 r <- isEmptyMVar startMark r `shouldBe` True it "does not exit itself by massive child crash" $ do Actor svQ sv <- newActor newSimpleOneForOneSupervisor withAsync sv $ \a -> do blocker <- newEmptyMVar for_ [1..10] $ \_ -> do Just tid <- newChild def svQ $ newChildSpec Permanent $ readMVar blocker $> () killThread tid threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing maybeAsync <- newChild def svQ $ newChildSpec Permanent $ readMVar blocker $> () isJust maybeAsync `shouldBe` True it "kills all children when it is killed" $ do rs <- for [1..10] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Temporary $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor svQ sv <- newActor newSimpleOneForOneSupervisor withAsync sv $ \_ -> do for_ procs $ newChild def svQ rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..10] reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Killed . fst) it "can be killed when children is finishing at the same time" $ do let volume = 1000 rs <- for [1..volume] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Temporary $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor svQ sv <- newActor newSimpleOneForOneSupervisor withAsync sv $ \_ -> do for_ procs $ newChild def svQ rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..volume] _ <- async $ for_ childQs $ \ch -> threadDelay 1000 *> castFinish ch threadDelay (100 * 1000) reports <- for childMons takeMVar length reports `shouldBe` volume let normalCount = length . filter ((==) Normal . fst) $ reports killedCount = length . filter ((==) Killed . fst) $ reports normalCount `shouldNotBe` 0 killedCount `shouldNotBe` 0 normalCount + killedCount `shouldBe` volume describe "IntenseRestartDetector" $ do it "returns True if 1 crash in 0 maximum restart intensity" $ do let crash = TimeSpec 0 0 detector = newIntenseRestartDetector $ RestartSensitivity 0 (TimeSpec 5 0) (result, _) = detectIntenseRestart detector crash result `shouldBe` True it "returns True if 1 crash in 0 maximum restart intensity regardless with period" $ do let crash = TimeSpec 0 0 detector = newIntenseRestartDetector $ RestartSensitivity 0 (TimeSpec 0 0) (result, _) = detectIntenseRestart detector crash result `shouldBe` True it "returns False if 1 crash in 1 maximum restart intensity" $ do let crash = TimeSpec 0 0 detector = newIntenseRestartDetector $ RestartSensitivity 1 (TimeSpec 5 0) (result, _) = detectIntenseRestart detector crash result `shouldBe` False it "returns True if 2 crash in 1 maximum restart intensity within given period" $ do let crash1 = TimeSpec 0 0 detector1 = newIntenseRestartDetector $ RestartSensitivity 1 (TimeSpec 5 0) (_, detector2) = detectIntenseRestart detector1 crash1 crash2 = TimeSpec 2 0 (result, _) = detectIntenseRestart detector2 crash2 result `shouldBe` True it "returns False if 2 crash in 1 maximum restart intensity but longer interval than given period" $ do let crash1 = TimeSpec 0 0 detector1 = newIntenseRestartDetector $ RestartSensitivity 1 (TimeSpec 5 0) (_, detector2) = detectIntenseRestart detector1 crash1 crash2 = TimeSpec 10 0 (result, _) = detectIntenseRestart detector2 crash2 result `shouldBe` False it "returns False if 1 crash in 2 maximum restart intensity" $ do let crash = TimeSpec 0 0 detector = newIntenseRestartDetector $ RestartSensitivity 2 (TimeSpec 5 0) (result, _) = detectIntenseRestart detector crash result `shouldBe` False it "returns False if 2 crash in 2 maximum restart intensity" $ do let crash1 = TimeSpec 0 0 detector1 = newIntenseRestartDetector $ RestartSensitivity 2 (TimeSpec 5 0) (_, detector2) = detectIntenseRestart detector1 crash1 crash2 = TimeSpec 2 0 (result, _) = detectIntenseRestart detector2 crash2 result `shouldBe` False it "returns True if 3 crash in 2 maximum restart intensity within given period" $ do let crash1 = TimeSpec 0 0 detector1 = newIntenseRestartDetector $ RestartSensitivity 2 (TimeSpec 5 0) (_, detector2) = detectIntenseRestart detector1 crash1 crash2 = TimeSpec 2 0 (_, detector3) = detectIntenseRestart detector2 crash2 crash3 = TimeSpec 3 0 (result, _) = detectIntenseRestart detector3 crash3 result `shouldBe` True it "returns False if 3 crash in 2 maximum restart intensity but longer interval than given period" $ do let crash1 = TimeSpec 0 0 detector1 = newIntenseRestartDetector $ RestartSensitivity 2 (TimeSpec 5 0) (_, detector2) = detectIntenseRestart detector1 crash1 crash2 = TimeSpec 2 0 (_, detector3) = detectIntenseRestart detector2 crash2 crash3 = TimeSpec 6 0 (result, _) = detectIntenseRestart detector3 crash3 result `shouldBe` False describe "One-for-one Supervisor with static children" $ do it "automatically starts children based on given ProcessSpec list" $ do rs <- for [1,2,3] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, _, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def procs withAsync sv $ \_ -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1,2,3] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2,3,4] it "automatically restarts finished children with permanent restart type" $ do rs <- for [1,2,3] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def { restartSensitivityIntensity = 3 } procs withAsync sv $ \_ -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1,2,3] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2,3,4] for_ childQs $ \ch -> castFinish ch reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Normal . fst) rs3 <- for childQs callCountUp rs3 `shouldBe` Just <$> [1,2,3] rs4 <- for childQs callCountUp rs4 `shouldBe` Just <$> [2,3,4] it "restarts neither normally finished transient nor temporary child" $ do rs <- for [Transient, Temporary] $ \restart -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec restart $ watch monitor $ putMVar marker () *> takeMVar trigger $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForOne def { restartSensitivityIntensity = 2 } procs withAsync sv $ \_ -> do rs1 <- for markers takeMVar rs1 `shouldBe` [(), ()] for_ triggers $ \t -> putMVar t () reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Normal . fst) threadDelay 1000 rs2 <- for markers $ \m -> isEmptyMVar m rs2 `shouldBe` [True, True] it "restarts crashed transient child but does not restart crashed temporary child" $ do rs <- for [Transient, Temporary] $ \restart -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec restart $ watch monitor $ putMVar marker () *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForOne def { restartSensitivityIntensity = 2 } procs withAsync sv $ \_ -> do rs1 <- for markers takeMVar rs1 `shouldBe` [(), ()] for_ triggers $ \t -> putMVar t () reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) "oops" . reasonToString . fst) threadDelay 10000 rs2 <- for markers $ \m -> isEmptyMVar m rs2 `shouldBe` [False, True] it "restarts killed transient child but does not restart killed temporary child" $ do blocker <- newEmptyMVar rs <- for [Transient, Temporary] $ \restart -> do marker <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec restart $ watch monitor $ (myThreadId >>= putMVar marker) *> takeMVar blocker $> () pure (marker, childMon, process) let (markers, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def { restartSensitivityIntensity = 2 } procs withAsync sv $ \_ -> do tids <- for markers takeMVar for_ tids killThread reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Killed . fst) threadDelay 10000 rs1 <- for markers $ \m -> isEmptyMVar m rs1 `shouldBe` [False, True] it "kills all children when it is killed" $ do rs <- for [1..10] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def procs withAsync sv $ \_ -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..10] reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Killed . fst) it "can be killed when children is finishing at the same time" $ do let volume = 2000 rs <- for [1..volume] $ \n -> do childMon <- newTQueueIO Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = atomically $ writeTQueue childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def { restartSensitivityIntensity = 1000 } procs withAsync sv $ \_ -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..volume] _ <- async $ for_ childQs $ \ch -> threadDelay 1000 *> castFinish ch threadDelay (100 * 1000) reports <- for childMons $ atomically . readTQueue length reports `shouldBe` volume let normalCount = length . filter ((==) Normal . fst) $ reports killedCount = length . filter ((==) Killed . fst) $ reports normalCount `shouldNotBe` 0 killedCount `shouldNotBe` 0 normalCount + killedCount `shouldBe` volume it "intensive normal exit of permanent child causes termination of Supervisor itself" $ do rs <- for [1,2] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def procs withAsync sv $ \a -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1,2] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2,3] castFinish (head childQs) report1 <- takeMVar (head childMons) fst report1 `shouldBe` Normal rs3 <- for childQs callCountUp rs3 `shouldBe` Just <$> [1,4] castFinish (head childQs) report2 <- takeMVar (head childMons) fst report2 `shouldBe` Normal r <- wait a r `shouldBe` () it "intensive crash of permanent child causes termination of Supervisor itself" $ do rs <- for [1,2] $ \_ -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ putMVar marker () *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForOne def procs withAsync sv $ \a -> do rs1 <- for markers takeMVar rs1 `shouldBe` [(), ()] putMVar (head triggers) () report1 <- takeMVar $ head childMons report1 `shouldSatisfy` ((==) "oops" . reasonToString . fst) threadDelay 1000 rs2 <- takeMVar $ head markers rs2 `shouldBe` () putMVar (triggers !! 1) () report2 <- takeMVar $ childMons !! 1 report2 `shouldSatisfy` ((==) "oops" . reasonToString . fst) r <- wait a r `shouldBe` () it "intensive killing permanent child causes termination of Supervisor itself" $ do blocker <- newEmptyMVar rs <- for [1,2] $ \_ -> do marker <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ (myThreadId >>= putMVar marker) *> takeMVar blocker $> () pure (marker, childMon, process) let (markers, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def procs withAsync sv $ \a -> do tids <- for markers takeMVar killThread $ head tids report1 <- takeMVar $ head childMons fst report1 `shouldBe` Killed threadDelay 1000 rs2 <- isEmptyMVar $ head markers rs2 `shouldBe` False tid2 <- takeMVar $ head markers killThread tid2 report2 <- takeMVar $ head childMons fst report2 `shouldBe` Killed r <- wait a r `shouldBe` () it "intensive normal exit of transient child does not terminate Supervisor" $ do rs <- for [1..10] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Transient $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def procs withAsync sv $ \a -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..10] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2..11] for_ childQs $ \ch -> castFinish ch reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Normal . fst) threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing it "intensive crash of transient child causes termination of Supervisor itself" $ do rs <- for [1,2] $ \_ -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Transient $ watch monitor $ putMVar marker () *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForOne def procs withAsync sv $ \a -> do rs1 <- for markers takeMVar rs1 `shouldBe` [(), ()] putMVar (head triggers) () report1 <- takeMVar $ head childMons report1 `shouldSatisfy` ((==) "oops" . reasonToString . fst) threadDelay 1000 rs2 <- takeMVar $ head markers rs2 `shouldBe` () putMVar (triggers !! 1) () report2 <- takeMVar $ childMons !! 1 report2 `shouldSatisfy` ((==) "oops" . reasonToString . fst) r <- wait a r `shouldBe` () it "intensive killing transient child causes termination of Supervisor itself" $ do blocker <- newEmptyMVar rs <- for [1,2] $ \_ -> do marker <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Transient $ watch monitor $ (myThreadId >>= putMVar marker) *> takeMVar blocker $> () pure (marker, childMon, process) let (markers, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def procs withAsync sv $ \a -> do tids <- for markers takeMVar killThread $ head tids report1 <- takeMVar $ head childMons fst report1 `shouldBe` Killed threadDelay 1000 rs2 <- isEmptyMVar $ head markers rs2 `shouldBe` False tid2 <- takeMVar $ head markers killThread tid2 report2 <- takeMVar $ head childMons fst report2 `shouldBe` Killed r <- wait a r `shouldBe` () it "intensive normal exit of temporary child does not terminate Supervisor" $ do rs <- for [1..10] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Temporary $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def procs withAsync sv $ \a -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..10] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2..11] for_ childQs $ \ch -> castFinish ch reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Normal . fst) threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing it "intensive crash of temporary child does not terminate Supervisor" $ do rs <- for [1..10] $ \_ -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Temporary $ watch monitor $ putMVar marker () *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForOne def procs withAsync sv $ \a -> do rs1 <- for markers takeMVar rs1 `shouldBe` replicate 10 () for_ triggers $ \t -> putMVar t () reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) "oops" . reasonToString . fst) threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing it "intensive killing temporary child does not terminate Supervisor" $ do rs <- for [1..10] $ \_ -> do marker <- newEmptyMVar blocker <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Temporary $ watch monitor $ (myThreadId >>= putMVar marker) *> takeMVar blocker $> () pure (marker, childMon, process) let (markers, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def procs withAsync sv $ \a -> do tids <- for markers takeMVar for_ tids killThread reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Killed . fst) threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing it "longer interval multiple normal exit of permanent child does not terminate Supervisor" $ do rs <- for [1..10] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def { restartSensitivityPeriod = TimeSpec 0 1000 } procs withAsync sv $ \a -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..10] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2..11] for_ childQs $ \ch -> threadDelay 1000 *> castFinish ch reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Normal . fst) threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing it "longer interval multiple crash of transient child does not terminate Supervisor" $ do rs <- for [1..10] $ \_ -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Transient $ watch monitor $ putMVar marker () *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForOne def { restartSensitivityPeriod = TimeSpec 0 1000 } procs withAsync sv $ \a -> do rs1 <- for markers takeMVar rs1 `shouldBe` replicate 10 () for_ triggers $ \t -> threadDelay 1000 *> putMVar t () reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) "oops" . reasonToString . fst) threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing it "longer interval multiple killing transient child does not terminate Supervisor" $ do rs <- for [1..10] $ \_ -> do marker <- newEmptyMVar blocker <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Transient $ watch monitor $ (myThreadId >>= putMVar marker) *> takeMVar blocker $> () pure (marker, childMon, process) let (markers, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def { restartSensitivityPeriod = TimeSpec 0 1000 } procs withAsync sv $ \a -> do tids <- for markers takeMVar for_ tids $ \tid -> threadDelay 1000 *> killThread tid reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Killed . fst) threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing describe "One-for-all Supervisor with static children" $ do it "automatically starts children based on given ProcessSpec list" $ do rs <- for [1,2,3] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, _, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \_ -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1,2,3] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2,3,4] it "automatically restarts all static children when one of permanent children finished" $ do rs <- for [1,2,3] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \_ -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1,2,3] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2,3,4] castFinish (head childQs) reports <- for childMons takeMVar fst <$> reports `shouldBe` [Normal, Killed, Killed] rs3 <- for childQs callCountUp rs3 `shouldBe` Just <$> [1,2,3] rs4 <- for childQs callCountUp rs4 `shouldBe` Just <$> [2,3,4] it "does not restart children on normal exit of transient or temporary child" $ do rs <- for [Transient, Temporary] $ \restart -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec restart $ watch monitor $ putMVar marker () *> takeMVar trigger $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForAll def { restartSensitivityIntensity = 2 } procs withAsync sv $ \_ -> do rs1 <- for markers takeMVar rs1 `shouldBe` [(), ()] putMVar (head triggers) () (reason1, _) <- takeMVar $ head childMons reason1 `shouldBe` Normal threadDelay 1000 rs2 <- for markers $ \m -> isEmptyMVar m rs2 `shouldBe` [True, True] putMVar (triggers !! 1) () (reason2, _) <- takeMVar $ childMons !! 1 reason2 `shouldBe` Normal threadDelay 1000 rs3 <- for markers $ \m -> isEmptyMVar m rs3 `shouldBe` [True, True] it "restarts all static children when one of transient child crashed or killed" $ do rs <- for [Transient, Temporary] $ \restart -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec restart $ watch monitor $ (myThreadId >>= putMVar marker) *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForAll def { restartSensitivityIntensity = 2 } procs withAsync sv $ \a -> do for_ markers takeMVar putMVar (head triggers) () reports <- for childMons takeMVar fst (reports !! 0) `shouldSatisfy` ((==) "oops" . reasonToString) fst (reports !! 1) `shouldBe` Killed threadDelay 1000 tids <- for markers takeMVar killThread $ head tids reports1 <- for childMons takeMVar fst <$> reports1 `shouldBe` [Killed, Killed] threadDelay 1000 rs3 <- for markers takeMVar typeOf <$> rs3 `shouldBe` replicate 2 (typeOf $ asyncThreadId a) it "does not restarts any children even if a temporary child crashed" $ do rs <- for [Transient, Temporary] $ \restart -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec restart $ watch monitor $ putMVar marker () *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \_ -> do rs1 <- for markers takeMVar rs1 `shouldBe` [(), ()] putMVar (triggers !! 1) () (reason, _) <- takeMVar $ childMons !! 1 reason `shouldSatisfy` ((==) "oops" . reasonToString) threadDelay 1000 rs2 <- for markers isEmptyMVar rs2 `shouldBe` [True, True] it "does not restarts any children even if a temporary child killed" $ do rs <- for [Transient, Temporary] $ \restart -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec restart $ watch monitor $ (myThreadId >>= putMVar marker) *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, childMon, process) let (markers, _, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \_ -> do tids <- for markers takeMVar killThread $ tids !! 1 (reason, _) <- takeMVar $ childMons !! 1 reason `shouldBe` Killed threadDelay 1000 rs2 <- for markers isEmptyMVar rs2 `shouldBe` [True, True] it "kills all children when it is killed" $ do rs <- for [1..10] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \_ -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..10] reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Killed . fst) it "can be killed when children is finishing at the same time" $ do let volume = 1000 rs <- for [1..volume] $ \n -> do childMon <- newTQueueIO Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = atomically $ writeTQueue childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \_ -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..volume] _ <- async $ threadDelay 1000 *> castFinish (head childQs) threadDelay (100 * 1000) reports <- for childMons $ atomically . readTQueue (fst . head) reports `shouldBe` Normal tail reports `shouldSatisfy` all ((==) Killed . fst) it "intensive normal exit of permanent child causes termination of Supervisor itself" $ do rs <- for [1,2] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \a -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1,2] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2,3] castFinish (head childQs) reports1 <- for childMons takeMVar fst <$> reports1 `shouldBe` [Normal, Killed] rs3 <- for childQs callCountUp rs3 `shouldBe` Just <$> [1,2] castFinish (head childQs) reports2 <- for childMons takeMVar fst <$> reports2 `shouldBe` [Normal, Killed] r <- wait a r `shouldBe` () it "intensive crash of permanent child causes termination of Supervisor itself" $ do rs <- for [1,2] $ \_ -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ putMVar marker () *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \a -> do rs1 <- for markers takeMVar rs1 `shouldBe` [(), ()] putMVar (head triggers) () reports1 <- for childMons takeMVar fst (reports1 !! 0) `shouldSatisfy` ((==) "oops" . reasonToString) fst (reports1 !! 1) `shouldBe` Killed threadDelay 1000 rs2 <- for markers takeMVar rs2 `shouldBe` [(), ()] putMVar (triggers !! 1) () reports2 <- for childMons takeMVar fst (reports2 !! 0) `shouldBe` Killed fst (reports2 !! 1) `shouldSatisfy` ((==) "oops" . reasonToString) r <- wait a r `shouldBe` () it "intensive killing permanent child causes termination of Supervisor itself" $ do blocker <- newEmptyMVar rs <- for [1,2] $ \_ -> do marker <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ (myThreadId >>= putMVar marker) *> takeMVar blocker $> () pure (marker, childMon, process) let (markers, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \a -> do tids <- for markers takeMVar killThread $ head tids reports1 <- for childMons takeMVar fst <$> reports1 `shouldBe` [Killed, Killed] threadDelay 1000 rs2 <- for markers isEmptyMVar rs2 `shouldBe` [False, False] tid2 <- takeMVar $ head markers killThread tid2 reports2 <- for childMons takeMVar fst <$> reports2 `shouldBe` [Killed, Killed] r <- wait a r `shouldBe` () it "intensive normal exit of transient child does not terminate Supervisor" $ do rs <- for [1..10] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Transient $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \a -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..10] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2..11] for_ childQs $ \ch -> castFinish ch reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Normal . fst) threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing it "intensive crash of transient child causes termination of Supervisor itself" $ do rs <- for [1,2] $ \_ -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Transient $ watch monitor $ putMVar marker () *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \a -> do rs1 <- for markers takeMVar rs1 `shouldBe` [(), ()] putMVar (head triggers) () reports1 <- for childMons takeMVar fst (reports1 !! 0) `shouldSatisfy` ((==) "oops" . reasonToString) fst (reports1 !! 1) `shouldBe` Killed threadDelay 1000 rs2 <- for markers takeMVar rs2 `shouldBe` [(), ()] putMVar (triggers !! 1) () reports2 <- for childMons takeMVar fst (reports2 !! 0) `shouldBe` Killed fst (reports2 !! 1) `shouldSatisfy` ((==) "oops" . reasonToString) r <- wait a r `shouldBe` () it "intensive killing transient child causes termination of Supervisor itself" $ do blocker <- newEmptyMVar rs <- for [1,2] $ \_ -> do marker <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Transient $ watch monitor $ (myThreadId >>= putMVar marker) *> takeMVar blocker $> () pure (marker, childMon, process) let (markers, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \a -> do tids1 <- for markers takeMVar killThread $ head tids1 reports1 <- for childMons takeMVar fst <$> reports1 `shouldBe` [Killed, Killed] threadDelay 1000 rs2 <- for markers isEmptyMVar rs2 `shouldBe` [False, False] tids2 <- for markers takeMVar killThread $ tids2 !! 1 reports2 <- for childMons takeMVar fst <$> reports2 `shouldBe` [Killed, Killed] r <- wait a r `shouldBe` () it "intensive normal exit of temporary child does not terminate Supervisor" $ do rs <- for [1..10] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Temporary $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \a -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..10] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2..11] for_ childQs $ \ch -> castFinish ch reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Normal . fst) threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing it "intensive crash of temporary child does not terminate Supervisor" $ do rs <- for [1..10] $ \_ -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Temporary $ watch monitor $ putMVar marker () *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \a -> do rs1 <- for markers takeMVar rs1 `shouldBe` replicate 10 () for_ triggers $ \t -> putMVar t () reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) "oops" . reasonToString . fst) threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing it "intensive killing temporary child does not terminate Supervisor" $ do rs <- for [1..10] $ \_ -> do marker <- newEmptyMVar blocker <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Temporary $ watch monitor $ (myThreadId >>= putMVar marker) *> takeMVar blocker $> () pure (marker, childMon, process) let (markers, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \a -> do tids <- for markers takeMVar for_ tids killThread reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Killed . fst) threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing it "longer interval multiple normal exit of permanent child does not terminate Supervisor" $ do rs <- for [1..10] $ \n -> do Actor childQ child <- newActor $ simpleCountingServer n let process = newChildSpec Permanent $ child $> () pure (childQ, process) let (childQs, procs) = unzip rs Actor _ sv <- newActor $ newSupervisor OneForAll def { restartSensitivityPeriod = TimeSpec 0 1000 } procs withAsync sv $ \a -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..10] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2..11] for_ childQs $ \ch -> threadDelay 1000 *> castFinish ch threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing rs3 <- for childQs callCountUp rs3 `shouldBe` Just <$> [1..10] it "longer interval multiple crash of transient child does not terminate Supervisor" $ do rs <- for [1..10] $ \_ -> do marker <- newTVarIO False trigger <- newEmptyMVar let process = newChildSpec Transient $ atomically (writeTVar marker True) *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, process) let (markers, triggers, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForAll def { restartSensitivityPeriod = TimeSpec 0 1000 } procs withAsync sv $ \a -> do threadDelay 1000 rs1 <- for markers readTVarIO rs1 `shouldBe` replicate 10 True for_ markers $ \m -> atomically $ writeTVar m True for_ triggers $ \t -> threadDelay 1000 *> putMVar t () threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing rs2 <- for markers readTVarIO rs2 `shouldBe` replicate 10 True it "longer interval multiple killing transient child does not terminate Supervisor" $ do myTid <- myThreadId rs <- for [1..3] $ \_ -> do marker <- newTVarIO myTid blocker <- newEmptyMVar let process = newChildSpec Transient $ (myThreadId >>= atomically . writeTVar marker) *> takeMVar blocker $> () pure (marker, process) let (markers, procs) = unzip rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \a -> do threadDelay 10000 tids <- for markers readTVarIO tids `shouldSatisfy` notElem myTid for_ tids killThread threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing tids1 <- for markers readTVarIO tids1 `shouldSatisfy` notElem myTid
null
https://raw.githubusercontent.com/nshimaza/thread-supervisor/ac7e21eadd2489c85aa9a630ae89c629280032bc/test/Control/Concurrent/SupervisorSpec.hs
haskell
# ANN module "HLint: ignore Reduce duplication" # # ANN module "HLint: ignore Use head" #
# OPTIONS_GHC -Wno - orphans # # OPTIONS_GHC -Wno - type - defaults # module Control.Concurrent.SupervisorSpec where import Data.Default (def) import Data.Foldable (for_) import Data.Functor (($>)) import Data.List (unzip4) import Data.Maybe (isJust, isNothing) import Data.Traversable (for) import Data.Typeable (typeOf) import System.Clock (TimeSpec (..)) import UnliftIO (StringException (..), async, asyncThreadId, atomically, cancel, fromException, isEmptyMVar, mask_, newEmptyMVar, newTQueueIO, newTVarIO, poll, putMVar, readMVar, readTQueue, readTVarIO, takeMVar, throwString, wait, withAsync, withAsyncWithUnmask, writeTQueue, writeTVar) import UnliftIO.Concurrent (killThread, myThreadId, threadDelay) import Test.Hspec import Test.Hspec.QuickCheck import Control.Concurrent.Supervisor hiding (length) instance Eq ExitReason where (UncaughtException _) == _ = error "should not compare exception by Eq" _ == (UncaughtException _) = error "should not compare exception by Eq" Normal == Normal = True Killed == Killed = True _ == _ = False reasonToString :: ExitReason -> String reasonToString (UncaughtException e) = toStr $ fromException e where toStr (Just (StringException str _)) = str toStr _ = error "Not a StringException" reasonToString _ = error "ExitReason is not Uncaught Exception" data ConstServerCmd = AskFst (ServerCallback Int) | AskSnd (ServerCallback Char) data TickerServerCmd = Tick (ServerCallback Int) | Tack tickerServer :: Inbox TickerServerCmd -> IO Int tickerServer = newStateMachine 0 handler where handler s (Tick cont) = cont s $> Right (s + 1) handler s Tack = pure $ Right (s + 1) data SimpleCountingServerCmd = CountUp (ServerCallback Int) | Finish simpleCountingServer :: Int -> Inbox SimpleCountingServerCmd -> IO Int simpleCountingServer n = newStateMachine n handler where handler s (CountUp cont) = cont s $> Right (s + 1) handler s Finish = pure (Left s) callCountUp :: ActorQ SimpleCountingServerCmd -> IO (Maybe Int) callCountUp q = call def q CountUp castFinish :: ActorQ SimpleCountingServerCmd -> IO () castFinish q = cast q Finish spec :: Spec spec = do describe "Actor" $ do prop "accepts ActorHandler and returns action with ActorQ" $ \n -> do Actor actorQ action <- newActor receive send actorQ (n :: Int) r2 <- action r2 `shouldBe` n prop "can send a message to itself" $ \n -> do Actor actorQ action <- newActor $ \inbox -> do msg <- receive inbox sendToMe inbox (msg + 1) receive inbox send actorQ (n :: Int) r2 <- action r2 `shouldBe` (n + 1) describe "State machine behavior" $ do it "returns result when event handler returns Left" $ do Actor actorQ statem <- newActor $ newStateMachine () $ \_ _ -> pure $ Left "Hello" send actorQ () r <- statem r `shouldBe` "Hello" it "consumes message in the queue until exit" $ do let until5 q 5 = pure $ Left ("Done", q) until5 q _ = pure $ Right q actorHandler inbox = newStateMachine inbox until5 inbox Actor actorQ statem <- newActor actorHandler for_ [1..7] $ send actorQ (r, lastQ) <- statem r `shouldBe` "Done" msg <- receive lastQ msg `shouldBe` 6 it "passes next state with Right" $ do let handler True _ = pure $ Right False handler False _ = pure $ Left "Finished" Actor actorQ statem <- newActor $ newStateMachine True handler for_ [(), ()] $ send actorQ r <- statem r `shouldBe` "Finished" it "runs state machine by consuming messages until handler returns Left" $ do let handler n 10 = pure $ Left (n + 10) handler n x = pure $ Right (n + x) Actor actorQ statem <- newActor $ newStateMachine 0 handler for_ [1..100] $ send actorQ r <- statem r `shouldBe` 55 describe "Server" $ do it "has call method which return value synchronously" $ do let handler s (AskFst cont) = cont (fst s) $> Right s handler s (AskSnd cont) = cont (snd s) $> Right s Actor srvQ srv <- newActor $ newStateMachine (1, 'a') handler withAsync srv $ \_ -> do r1 <- call def srvQ AskFst r1 `shouldBe` Just 1 r2 <- call def srvQ AskSnd r2 `shouldBe` Just 'a' it "keeps its own state and cast changes the state" $ do Actor srvQ srv <- newActor tickerServer withAsync srv $ \_ -> do r1 <- call def srvQ Tick r1 `shouldBe` Just 0 cast srvQ Tack r2 <- call def srvQ Tick r2 `shouldBe` Just 2 it "keeps its own state and callIgnore changes the state" $ do Actor srvQ srv <- newActor tickerServer withAsync srv $ \_ -> do r1 <- call def srvQ Tick r1 `shouldBe` Just 0 callIgnore srvQ Tick r2 <- call def srvQ Tick r2 `shouldBe` Just 2 it "keeps its own state and call can change the state" $ do Actor srvQ srv <- newActor $ simpleCountingServer 0 withAsync srv $ \_ -> do r1 <- callCountUp srvQ r1 `shouldBe` Just 0 r2 <- callCountUp srvQ r2 `shouldBe` Just 1 it "timeouts call method when server is not responding" $ do blocker <- newEmptyMVar let handler _ _ = takeMVar blocker $> Right () Actor srvQ srv <- newActor $ newStateMachine () handler withAsync srv $ \_ -> do r1 <- call (CallTimeout 10000) srvQ AskFst (r1 :: Maybe Int) `shouldBe` Nothing describe "Monitored IO action" $ do it "reports exit code Normal on normal exit" $ do trigger <- newEmptyMVar mark <- newEmptyMVar let monitor reason tid = putMVar mark (reason, tid) monitoredAction = watch monitor $ readMVar trigger $> () mask_ $ withAsyncWithUnmask monitoredAction $ \a -> do noReport <- isEmptyMVar mark noReport `shouldBe` True putMVar trigger () report <- takeMVar mark report `shouldBe` (Normal, asyncThreadId a) it "reports exit code UncaughtException on synchronous exception which wasn't caught" $ do trigger <- newEmptyMVar mark <- newEmptyMVar let monitor reason tid = putMVar mark (reason, tid) monitoredAction = watch monitor $ readMVar trigger *> throwString "oops" $> () mask_ $ withAsyncWithUnmask monitoredAction $ \a -> do noReport <- isEmptyMVar mark noReport `shouldBe` True putMVar trigger () (reason, tid) <- takeMVar mark tid `shouldBe` asyncThreadId a reasonToString reason `shouldBe` "oops" it "reports exit code Killed when it received asynchronous exception" $ do blocker <- newEmptyMVar mark <- newEmptyMVar let monitor reason tid = putMVar mark (reason, tid) monitoredAction = watch monitor $ readMVar blocker $> () mask_ $ withAsyncWithUnmask monitoredAction $ \a -> do noReport <- isEmptyMVar mark noReport `shouldBe` True cancel a report <- takeMVar mark report `shouldBe` (Killed, asyncThreadId a) it "can nest monitors and notify its normal exit to both" $ do trigger <- newEmptyMVar mark1 <- newEmptyMVar mark2 <- newEmptyMVar let monitor1 reason tid = putMVar mark1 (reason, tid) monitoredAction1 = watch monitor1 $ readMVar trigger $> () monitor2 reason tid = putMVar mark2 (reason, tid) monitoredAction2 = nestWatch monitor2 monitoredAction1 mask_ $ withAsyncWithUnmask monitoredAction2 $ \a -> do noReport1 <- isEmptyMVar mark1 noReport1 `shouldBe` True noReport2 <- isEmptyMVar mark2 noReport2 `shouldBe` True putMVar trigger () report1 <- takeMVar mark1 report1 `shouldBe` (Normal, asyncThreadId a) report2 <- takeMVar mark2 report2 `shouldBe` (Normal, asyncThreadId a) it "can nest monitors and notify UncaughtException to both" $ do trigger <- newEmptyMVar mark1 <- newEmptyMVar mark2 <- newEmptyMVar let monitor1 reason tid = putMVar mark1 (reason, tid) monitoredAction1 = watch monitor1 $ readMVar trigger *> throwString "oops" $> () monitor2 reason tid = putMVar mark2 (reason, tid) monitoredAction2 = nestWatch monitor2 monitoredAction1 mask_ $ withAsyncWithUnmask monitoredAction2 $ \a -> do noReport1 <- isEmptyMVar mark1 noReport1 `shouldBe` True noReport2 <- isEmptyMVar mark2 noReport2 `shouldBe` True putMVar trigger () (reason1, tid1) <- takeMVar mark1 tid1 `shouldBe` asyncThreadId a reasonToString reason1 `shouldBe` "oops" (reason2, tid2) <- takeMVar mark2 tid2 `shouldBe` asyncThreadId a reasonToString reason2 `shouldBe` "oops" it "can nest monitors and notify Killed to both" $ do blocker <- newEmptyMVar mark1 <- newEmptyMVar mark2 <- newEmptyMVar let monitor1 reason tid = putMVar mark1 (reason, tid) monitoredAction1 = watch monitor1 $ readMVar blocker $> () monitor2 reason tid = putMVar mark2 (reason, tid) monitoredAction2 = nestWatch monitor2 monitoredAction1 mask_ $ withAsyncWithUnmask monitoredAction2 $ \a -> do noReport1 <- isEmptyMVar mark1 noReport1 `shouldBe` True noReport2 <- isEmptyMVar mark2 noReport2 `shouldBe` True cancel a report1 <- takeMVar mark1 report1 `shouldBe` (Killed, asyncThreadId a) report2 <- takeMVar mark2 report2 `shouldBe` (Killed, asyncThreadId a) it "can nest many monitors and notify its normal exit to all" $ do trigger <- newEmptyMVar marks <- for [1..100] $ const newEmptyMVar let monitors = map (\mark reason tid -> putMVar mark (reason, tid)) marks nestedMonitoredAction = foldr nestWatch (noWatch $ readMVar trigger $> ()) monitors mask_ $ withAsyncWithUnmask nestedMonitoredAction $ \a -> do noReports <- for marks isEmptyMVar noReports `shouldSatisfy` and putMVar trigger () reports <- for marks takeMVar reports `shouldSatisfy` all (== (Normal, asyncThreadId a)) it "can nest many monitors and notify UncaughtException to all" $ do trigger <- newEmptyMVar marks <- for [1..100] $ const newEmptyMVar let monitors = map (\mark reason tid -> putMVar mark (reason, tid)) marks nestedMonitoredAction = foldr nestWatch (noWatch $ readMVar trigger *> throwString "oops" $> ()) monitors mask_ $ withAsyncWithUnmask nestedMonitoredAction $ \a -> do noReports <- for marks isEmptyMVar noReports `shouldSatisfy` and putMVar trigger () reports <- for marks takeMVar reports `shouldSatisfy` all ((==) (asyncThreadId a) . snd) reports `shouldSatisfy` all ((==) "oops" . reasonToString . fst) it "can nest many monitors and notify Killed to all" $ do blocker <- newEmptyMVar marks <- for [1..100] $ const newEmptyMVar let monitors = map (\mark reason tid -> putMVar mark (reason, tid)) marks nestedMonitoredAction = foldr nestWatch (noWatch $ readMVar blocker $> ()) monitors mask_ $ withAsyncWithUnmask nestedMonitoredAction $ \a -> do noReports <- for marks isEmptyMVar noReports `shouldSatisfy` and cancel a reports <- for marks takeMVar reports `shouldSatisfy` all (== (Killed, asyncThreadId a)) describe "SimpleOneForOneSupervisor" $ do it "starts a dynamic child" $ do trigger <- newEmptyMVar mark <- newEmptyMVar blocker <- newEmptyMVar var <- newTVarIO (0 :: Int) Actor svQ sv <- newActor newSimpleOneForOneSupervisor withAsync sv $ \_ -> do maybeChildAsync <- newChild def svQ $ newChildSpec Temporary $ do readMVar trigger atomically $ writeTVar var 1 putMVar mark () _ <- readMVar blocker pure () isJust maybeChildAsync `shouldBe` True currentVal0 <- readTVarIO var currentVal0 `shouldBe` 0 putMVar trigger () readMVar mark currentVal1 <- readTVarIO var currentVal1 `shouldBe` 1 it "does not restart finished dynamic child regardless restart type" $ do Actor svQ sv <- newActor newSimpleOneForOneSupervisor withAsync sv $ \_ -> for_ [Permanent, Transient, Temporary] $ \restart -> do startMark <- newEmptyMVar trigger <- newEmptyMVar finishMark <- newEmptyMVar Just _ <- newChild def svQ $ newChildSpec restart $ do putMVar startMark () readMVar trigger putMVar finishMark () pure () takeMVar startMark putMVar trigger () takeMVar finishMark threadDelay 1000 r <- isEmptyMVar startMark r `shouldBe` True it "does not exit itself by massive child crash" $ do Actor svQ sv <- newActor newSimpleOneForOneSupervisor withAsync sv $ \a -> do blocker <- newEmptyMVar for_ [1..10] $ \_ -> do Just tid <- newChild def svQ $ newChildSpec Permanent $ readMVar blocker $> () killThread tid threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing maybeAsync <- newChild def svQ $ newChildSpec Permanent $ readMVar blocker $> () isJust maybeAsync `shouldBe` True it "kills all children when it is killed" $ do rs <- for [1..10] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Temporary $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor svQ sv <- newActor newSimpleOneForOneSupervisor withAsync sv $ \_ -> do for_ procs $ newChild def svQ rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..10] reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Killed . fst) it "can be killed when children is finishing at the same time" $ do let volume = 1000 rs <- for [1..volume] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Temporary $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor svQ sv <- newActor newSimpleOneForOneSupervisor withAsync sv $ \_ -> do for_ procs $ newChild def svQ rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..volume] _ <- async $ for_ childQs $ \ch -> threadDelay 1000 *> castFinish ch threadDelay (100 * 1000) reports <- for childMons takeMVar length reports `shouldBe` volume let normalCount = length . filter ((==) Normal . fst) $ reports killedCount = length . filter ((==) Killed . fst) $ reports normalCount `shouldNotBe` 0 killedCount `shouldNotBe` 0 normalCount + killedCount `shouldBe` volume describe "IntenseRestartDetector" $ do it "returns True if 1 crash in 0 maximum restart intensity" $ do let crash = TimeSpec 0 0 detector = newIntenseRestartDetector $ RestartSensitivity 0 (TimeSpec 5 0) (result, _) = detectIntenseRestart detector crash result `shouldBe` True it "returns True if 1 crash in 0 maximum restart intensity regardless with period" $ do let crash = TimeSpec 0 0 detector = newIntenseRestartDetector $ RestartSensitivity 0 (TimeSpec 0 0) (result, _) = detectIntenseRestart detector crash result `shouldBe` True it "returns False if 1 crash in 1 maximum restart intensity" $ do let crash = TimeSpec 0 0 detector = newIntenseRestartDetector $ RestartSensitivity 1 (TimeSpec 5 0) (result, _) = detectIntenseRestart detector crash result `shouldBe` False it "returns True if 2 crash in 1 maximum restart intensity within given period" $ do let crash1 = TimeSpec 0 0 detector1 = newIntenseRestartDetector $ RestartSensitivity 1 (TimeSpec 5 0) (_, detector2) = detectIntenseRestart detector1 crash1 crash2 = TimeSpec 2 0 (result, _) = detectIntenseRestart detector2 crash2 result `shouldBe` True it "returns False if 2 crash in 1 maximum restart intensity but longer interval than given period" $ do let crash1 = TimeSpec 0 0 detector1 = newIntenseRestartDetector $ RestartSensitivity 1 (TimeSpec 5 0) (_, detector2) = detectIntenseRestart detector1 crash1 crash2 = TimeSpec 10 0 (result, _) = detectIntenseRestart detector2 crash2 result `shouldBe` False it "returns False if 1 crash in 2 maximum restart intensity" $ do let crash = TimeSpec 0 0 detector = newIntenseRestartDetector $ RestartSensitivity 2 (TimeSpec 5 0) (result, _) = detectIntenseRestart detector crash result `shouldBe` False it "returns False if 2 crash in 2 maximum restart intensity" $ do let crash1 = TimeSpec 0 0 detector1 = newIntenseRestartDetector $ RestartSensitivity 2 (TimeSpec 5 0) (_, detector2) = detectIntenseRestart detector1 crash1 crash2 = TimeSpec 2 0 (result, _) = detectIntenseRestart detector2 crash2 result `shouldBe` False it "returns True if 3 crash in 2 maximum restart intensity within given period" $ do let crash1 = TimeSpec 0 0 detector1 = newIntenseRestartDetector $ RestartSensitivity 2 (TimeSpec 5 0) (_, detector2) = detectIntenseRestart detector1 crash1 crash2 = TimeSpec 2 0 (_, detector3) = detectIntenseRestart detector2 crash2 crash3 = TimeSpec 3 0 (result, _) = detectIntenseRestart detector3 crash3 result `shouldBe` True it "returns False if 3 crash in 2 maximum restart intensity but longer interval than given period" $ do let crash1 = TimeSpec 0 0 detector1 = newIntenseRestartDetector $ RestartSensitivity 2 (TimeSpec 5 0) (_, detector2) = detectIntenseRestart detector1 crash1 crash2 = TimeSpec 2 0 (_, detector3) = detectIntenseRestart detector2 crash2 crash3 = TimeSpec 6 0 (result, _) = detectIntenseRestart detector3 crash3 result `shouldBe` False describe "One-for-one Supervisor with static children" $ do it "automatically starts children based on given ProcessSpec list" $ do rs <- for [1,2,3] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, _, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def procs withAsync sv $ \_ -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1,2,3] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2,3,4] it "automatically restarts finished children with permanent restart type" $ do rs <- for [1,2,3] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def { restartSensitivityIntensity = 3 } procs withAsync sv $ \_ -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1,2,3] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2,3,4] for_ childQs $ \ch -> castFinish ch reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Normal . fst) rs3 <- for childQs callCountUp rs3 `shouldBe` Just <$> [1,2,3] rs4 <- for childQs callCountUp rs4 `shouldBe` Just <$> [2,3,4] it "restarts neither normally finished transient nor temporary child" $ do rs <- for [Transient, Temporary] $ \restart -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec restart $ watch monitor $ putMVar marker () *> takeMVar trigger $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForOne def { restartSensitivityIntensity = 2 } procs withAsync sv $ \_ -> do rs1 <- for markers takeMVar rs1 `shouldBe` [(), ()] for_ triggers $ \t -> putMVar t () reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Normal . fst) threadDelay 1000 rs2 <- for markers $ \m -> isEmptyMVar m rs2 `shouldBe` [True, True] it "restarts crashed transient child but does not restart crashed temporary child" $ do rs <- for [Transient, Temporary] $ \restart -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec restart $ watch monitor $ putMVar marker () *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForOne def { restartSensitivityIntensity = 2 } procs withAsync sv $ \_ -> do rs1 <- for markers takeMVar rs1 `shouldBe` [(), ()] for_ triggers $ \t -> putMVar t () reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) "oops" . reasonToString . fst) threadDelay 10000 rs2 <- for markers $ \m -> isEmptyMVar m rs2 `shouldBe` [False, True] it "restarts killed transient child but does not restart killed temporary child" $ do blocker <- newEmptyMVar rs <- for [Transient, Temporary] $ \restart -> do marker <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec restart $ watch monitor $ (myThreadId >>= putMVar marker) *> takeMVar blocker $> () pure (marker, childMon, process) let (markers, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def { restartSensitivityIntensity = 2 } procs withAsync sv $ \_ -> do tids <- for markers takeMVar for_ tids killThread reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Killed . fst) threadDelay 10000 rs1 <- for markers $ \m -> isEmptyMVar m rs1 `shouldBe` [False, True] it "kills all children when it is killed" $ do rs <- for [1..10] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def procs withAsync sv $ \_ -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..10] reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Killed . fst) it "can be killed when children is finishing at the same time" $ do let volume = 2000 rs <- for [1..volume] $ \n -> do childMon <- newTQueueIO Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = atomically $ writeTQueue childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def { restartSensitivityIntensity = 1000 } procs withAsync sv $ \_ -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..volume] _ <- async $ for_ childQs $ \ch -> threadDelay 1000 *> castFinish ch threadDelay (100 * 1000) reports <- for childMons $ atomically . readTQueue length reports `shouldBe` volume let normalCount = length . filter ((==) Normal . fst) $ reports killedCount = length . filter ((==) Killed . fst) $ reports normalCount `shouldNotBe` 0 killedCount `shouldNotBe` 0 normalCount + killedCount `shouldBe` volume it "intensive normal exit of permanent child causes termination of Supervisor itself" $ do rs <- for [1,2] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def procs withAsync sv $ \a -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1,2] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2,3] castFinish (head childQs) report1 <- takeMVar (head childMons) fst report1 `shouldBe` Normal rs3 <- for childQs callCountUp rs3 `shouldBe` Just <$> [1,4] castFinish (head childQs) report2 <- takeMVar (head childMons) fst report2 `shouldBe` Normal r <- wait a r `shouldBe` () it "intensive crash of permanent child causes termination of Supervisor itself" $ do rs <- for [1,2] $ \_ -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ putMVar marker () *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForOne def procs withAsync sv $ \a -> do rs1 <- for markers takeMVar rs1 `shouldBe` [(), ()] putMVar (head triggers) () report1 <- takeMVar $ head childMons report1 `shouldSatisfy` ((==) "oops" . reasonToString . fst) threadDelay 1000 rs2 <- takeMVar $ head markers rs2 `shouldBe` () putMVar (triggers !! 1) () report2 <- takeMVar $ childMons !! 1 report2 `shouldSatisfy` ((==) "oops" . reasonToString . fst) r <- wait a r `shouldBe` () it "intensive killing permanent child causes termination of Supervisor itself" $ do blocker <- newEmptyMVar rs <- for [1,2] $ \_ -> do marker <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ (myThreadId >>= putMVar marker) *> takeMVar blocker $> () pure (marker, childMon, process) let (markers, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def procs withAsync sv $ \a -> do tids <- for markers takeMVar killThread $ head tids report1 <- takeMVar $ head childMons fst report1 `shouldBe` Killed threadDelay 1000 rs2 <- isEmptyMVar $ head markers rs2 `shouldBe` False tid2 <- takeMVar $ head markers killThread tid2 report2 <- takeMVar $ head childMons fst report2 `shouldBe` Killed r <- wait a r `shouldBe` () it "intensive normal exit of transient child does not terminate Supervisor" $ do rs <- for [1..10] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Transient $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def procs withAsync sv $ \a -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..10] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2..11] for_ childQs $ \ch -> castFinish ch reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Normal . fst) threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing it "intensive crash of transient child causes termination of Supervisor itself" $ do rs <- for [1,2] $ \_ -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Transient $ watch monitor $ putMVar marker () *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForOne def procs withAsync sv $ \a -> do rs1 <- for markers takeMVar rs1 `shouldBe` [(), ()] putMVar (head triggers) () report1 <- takeMVar $ head childMons report1 `shouldSatisfy` ((==) "oops" . reasonToString . fst) threadDelay 1000 rs2 <- takeMVar $ head markers rs2 `shouldBe` () putMVar (triggers !! 1) () report2 <- takeMVar $ childMons !! 1 report2 `shouldSatisfy` ((==) "oops" . reasonToString . fst) r <- wait a r `shouldBe` () it "intensive killing transient child causes termination of Supervisor itself" $ do blocker <- newEmptyMVar rs <- for [1,2] $ \_ -> do marker <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Transient $ watch monitor $ (myThreadId >>= putMVar marker) *> takeMVar blocker $> () pure (marker, childMon, process) let (markers, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def procs withAsync sv $ \a -> do tids <- for markers takeMVar killThread $ head tids report1 <- takeMVar $ head childMons fst report1 `shouldBe` Killed threadDelay 1000 rs2 <- isEmptyMVar $ head markers rs2 `shouldBe` False tid2 <- takeMVar $ head markers killThread tid2 report2 <- takeMVar $ head childMons fst report2 `shouldBe` Killed r <- wait a r `shouldBe` () it "intensive normal exit of temporary child does not terminate Supervisor" $ do rs <- for [1..10] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Temporary $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def procs withAsync sv $ \a -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..10] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2..11] for_ childQs $ \ch -> castFinish ch reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Normal . fst) threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing it "intensive crash of temporary child does not terminate Supervisor" $ do rs <- for [1..10] $ \_ -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Temporary $ watch monitor $ putMVar marker () *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForOne def procs withAsync sv $ \a -> do rs1 <- for markers takeMVar rs1 `shouldBe` replicate 10 () for_ triggers $ \t -> putMVar t () reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) "oops" . reasonToString . fst) threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing it "intensive killing temporary child does not terminate Supervisor" $ do rs <- for [1..10] $ \_ -> do marker <- newEmptyMVar blocker <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Temporary $ watch monitor $ (myThreadId >>= putMVar marker) *> takeMVar blocker $> () pure (marker, childMon, process) let (markers, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def procs withAsync sv $ \a -> do tids <- for markers takeMVar for_ tids killThread reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Killed . fst) threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing it "longer interval multiple normal exit of permanent child does not terminate Supervisor" $ do rs <- for [1..10] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def { restartSensitivityPeriod = TimeSpec 0 1000 } procs withAsync sv $ \a -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..10] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2..11] for_ childQs $ \ch -> threadDelay 1000 *> castFinish ch reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Normal . fst) threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing it "longer interval multiple crash of transient child does not terminate Supervisor" $ do rs <- for [1..10] $ \_ -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Transient $ watch monitor $ putMVar marker () *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForOne def { restartSensitivityPeriod = TimeSpec 0 1000 } procs withAsync sv $ \a -> do rs1 <- for markers takeMVar rs1 `shouldBe` replicate 10 () for_ triggers $ \t -> threadDelay 1000 *> putMVar t () reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) "oops" . reasonToString . fst) threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing it "longer interval multiple killing transient child does not terminate Supervisor" $ do rs <- for [1..10] $ \_ -> do marker <- newEmptyMVar blocker <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Transient $ watch monitor $ (myThreadId >>= putMVar marker) *> takeMVar blocker $> () pure (marker, childMon, process) let (markers, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForOne def { restartSensitivityPeriod = TimeSpec 0 1000 } procs withAsync sv $ \a -> do tids <- for markers takeMVar for_ tids $ \tid -> threadDelay 1000 *> killThread tid reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Killed . fst) threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing describe "One-for-all Supervisor with static children" $ do it "automatically starts children based on given ProcessSpec list" $ do rs <- for [1,2,3] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, _, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \_ -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1,2,3] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2,3,4] it "automatically restarts all static children when one of permanent children finished" $ do rs <- for [1,2,3] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \_ -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1,2,3] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2,3,4] castFinish (head childQs) reports <- for childMons takeMVar fst <$> reports `shouldBe` [Normal, Killed, Killed] rs3 <- for childQs callCountUp rs3 `shouldBe` Just <$> [1,2,3] rs4 <- for childQs callCountUp rs4 `shouldBe` Just <$> [2,3,4] it "does not restart children on normal exit of transient or temporary child" $ do rs <- for [Transient, Temporary] $ \restart -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec restart $ watch monitor $ putMVar marker () *> takeMVar trigger $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForAll def { restartSensitivityIntensity = 2 } procs withAsync sv $ \_ -> do rs1 <- for markers takeMVar rs1 `shouldBe` [(), ()] putMVar (head triggers) () (reason1, _) <- takeMVar $ head childMons reason1 `shouldBe` Normal threadDelay 1000 rs2 <- for markers $ \m -> isEmptyMVar m rs2 `shouldBe` [True, True] putMVar (triggers !! 1) () (reason2, _) <- takeMVar $ childMons !! 1 reason2 `shouldBe` Normal threadDelay 1000 rs3 <- for markers $ \m -> isEmptyMVar m rs3 `shouldBe` [True, True] it "restarts all static children when one of transient child crashed or killed" $ do rs <- for [Transient, Temporary] $ \restart -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec restart $ watch monitor $ (myThreadId >>= putMVar marker) *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForAll def { restartSensitivityIntensity = 2 } procs withAsync sv $ \a -> do for_ markers takeMVar putMVar (head triggers) () reports <- for childMons takeMVar fst (reports !! 0) `shouldSatisfy` ((==) "oops" . reasonToString) fst (reports !! 1) `shouldBe` Killed threadDelay 1000 tids <- for markers takeMVar killThread $ head tids reports1 <- for childMons takeMVar fst <$> reports1 `shouldBe` [Killed, Killed] threadDelay 1000 rs3 <- for markers takeMVar typeOf <$> rs3 `shouldBe` replicate 2 (typeOf $ asyncThreadId a) it "does not restarts any children even if a temporary child crashed" $ do rs <- for [Transient, Temporary] $ \restart -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec restart $ watch monitor $ putMVar marker () *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \_ -> do rs1 <- for markers takeMVar rs1 `shouldBe` [(), ()] putMVar (triggers !! 1) () (reason, _) <- takeMVar $ childMons !! 1 reason `shouldSatisfy` ((==) "oops" . reasonToString) threadDelay 1000 rs2 <- for markers isEmptyMVar rs2 `shouldBe` [True, True] it "does not restarts any children even if a temporary child killed" $ do rs <- for [Transient, Temporary] $ \restart -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec restart $ watch monitor $ (myThreadId >>= putMVar marker) *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, childMon, process) let (markers, _, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \_ -> do tids <- for markers takeMVar killThread $ tids !! 1 (reason, _) <- takeMVar $ childMons !! 1 reason `shouldBe` Killed threadDelay 1000 rs2 <- for markers isEmptyMVar rs2 `shouldBe` [True, True] it "kills all children when it is killed" $ do rs <- for [1..10] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \_ -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..10] reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Killed . fst) it "can be killed when children is finishing at the same time" $ do let volume = 1000 rs <- for [1..volume] $ \n -> do childMon <- newTQueueIO Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = atomically $ writeTQueue childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \_ -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..volume] _ <- async $ threadDelay 1000 *> castFinish (head childQs) threadDelay (100 * 1000) reports <- for childMons $ atomically . readTQueue (fst . head) reports `shouldBe` Normal tail reports `shouldSatisfy` all ((==) Killed . fst) it "intensive normal exit of permanent child causes termination of Supervisor itself" $ do rs <- for [1,2] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \a -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1,2] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2,3] castFinish (head childQs) reports1 <- for childMons takeMVar fst <$> reports1 `shouldBe` [Normal, Killed] rs3 <- for childQs callCountUp rs3 `shouldBe` Just <$> [1,2] castFinish (head childQs) reports2 <- for childMons takeMVar fst <$> reports2 `shouldBe` [Normal, Killed] r <- wait a r `shouldBe` () it "intensive crash of permanent child causes termination of Supervisor itself" $ do rs <- for [1,2] $ \_ -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ putMVar marker () *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \a -> do rs1 <- for markers takeMVar rs1 `shouldBe` [(), ()] putMVar (head triggers) () reports1 <- for childMons takeMVar fst (reports1 !! 0) `shouldSatisfy` ((==) "oops" . reasonToString) fst (reports1 !! 1) `shouldBe` Killed threadDelay 1000 rs2 <- for markers takeMVar rs2 `shouldBe` [(), ()] putMVar (triggers !! 1) () reports2 <- for childMons takeMVar fst (reports2 !! 0) `shouldBe` Killed fst (reports2 !! 1) `shouldSatisfy` ((==) "oops" . reasonToString) r <- wait a r `shouldBe` () it "intensive killing permanent child causes termination of Supervisor itself" $ do blocker <- newEmptyMVar rs <- for [1,2] $ \_ -> do marker <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Permanent $ watch monitor $ (myThreadId >>= putMVar marker) *> takeMVar blocker $> () pure (marker, childMon, process) let (markers, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \a -> do tids <- for markers takeMVar killThread $ head tids reports1 <- for childMons takeMVar fst <$> reports1 `shouldBe` [Killed, Killed] threadDelay 1000 rs2 <- for markers isEmptyMVar rs2 `shouldBe` [False, False] tid2 <- takeMVar $ head markers killThread tid2 reports2 <- for childMons takeMVar fst <$> reports2 `shouldBe` [Killed, Killed] r <- wait a r `shouldBe` () it "intensive normal exit of transient child does not terminate Supervisor" $ do rs <- for [1..10] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Transient $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \a -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..10] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2..11] for_ childQs $ \ch -> castFinish ch reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Normal . fst) threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing it "intensive crash of transient child causes termination of Supervisor itself" $ do rs <- for [1,2] $ \_ -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Transient $ watch monitor $ putMVar marker () *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \a -> do rs1 <- for markers takeMVar rs1 `shouldBe` [(), ()] putMVar (head triggers) () reports1 <- for childMons takeMVar fst (reports1 !! 0) `shouldSatisfy` ((==) "oops" . reasonToString) fst (reports1 !! 1) `shouldBe` Killed threadDelay 1000 rs2 <- for markers takeMVar rs2 `shouldBe` [(), ()] putMVar (triggers !! 1) () reports2 <- for childMons takeMVar fst (reports2 !! 0) `shouldBe` Killed fst (reports2 !! 1) `shouldSatisfy` ((==) "oops" . reasonToString) r <- wait a r `shouldBe` () it "intensive killing transient child causes termination of Supervisor itself" $ do blocker <- newEmptyMVar rs <- for [1,2] $ \_ -> do marker <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Transient $ watch monitor $ (myThreadId >>= putMVar marker) *> takeMVar blocker $> () pure (marker, childMon, process) let (markers, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \a -> do tids1 <- for markers takeMVar killThread $ head tids1 reports1 <- for childMons takeMVar fst <$> reports1 `shouldBe` [Killed, Killed] threadDelay 1000 rs2 <- for markers isEmptyMVar rs2 `shouldBe` [False, False] tids2 <- for markers takeMVar killThread $ tids2 !! 1 reports2 <- for childMons takeMVar fst <$> reports2 `shouldBe` [Killed, Killed] r <- wait a r `shouldBe` () it "intensive normal exit of temporary child does not terminate Supervisor" $ do rs <- for [1..10] $ \n -> do childMon <- newEmptyMVar Actor childQ child <- newActor $ simpleCountingServer n let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Temporary $ watch monitor $ child $> () pure (childQ, childMon, process) let (childQs, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \a -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..10] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2..11] for_ childQs $ \ch -> castFinish ch reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Normal . fst) threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing it "intensive crash of temporary child does not terminate Supervisor" $ do rs <- for [1..10] $ \_ -> do marker <- newEmptyMVar trigger <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Temporary $ watch monitor $ putMVar marker () *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, childMon, process) let (markers, triggers, childMons, procs) = unzip4 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \a -> do rs1 <- for markers takeMVar rs1 `shouldBe` replicate 10 () for_ triggers $ \t -> putMVar t () reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) "oops" . reasonToString . fst) threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing it "intensive killing temporary child does not terminate Supervisor" $ do rs <- for [1..10] $ \_ -> do marker <- newEmptyMVar blocker <- newEmptyMVar childMon <- newEmptyMVar let monitor reason tid = putMVar childMon (reason, tid) process = newMonitoredChildSpec Temporary $ watch monitor $ (myThreadId >>= putMVar marker) *> takeMVar blocker $> () pure (marker, childMon, process) let (markers, childMons, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \a -> do tids <- for markers takeMVar for_ tids killThread reports <- for childMons takeMVar reports `shouldSatisfy` all ((==) Killed . fst) threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing it "longer interval multiple normal exit of permanent child does not terminate Supervisor" $ do rs <- for [1..10] $ \n -> do Actor childQ child <- newActor $ simpleCountingServer n let process = newChildSpec Permanent $ child $> () pure (childQ, process) let (childQs, procs) = unzip rs Actor _ sv <- newActor $ newSupervisor OneForAll def { restartSensitivityPeriod = TimeSpec 0 1000 } procs withAsync sv $ \a -> do rs1 <- for childQs callCountUp rs1 `shouldBe` Just <$> [1..10] rs2 <- for childQs callCountUp rs2 `shouldBe` Just <$> [2..11] for_ childQs $ \ch -> threadDelay 1000 *> castFinish ch threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing rs3 <- for childQs callCountUp rs3 `shouldBe` Just <$> [1..10] it "longer interval multiple crash of transient child does not terminate Supervisor" $ do rs <- for [1..10] $ \_ -> do marker <- newTVarIO False trigger <- newEmptyMVar let process = newChildSpec Transient $ atomically (writeTVar marker True) *> takeMVar trigger *> throwString "oops" $> () pure (marker, trigger, process) let (markers, triggers, procs) = unzip3 rs Actor _ sv <- newActor $ newSupervisor OneForAll def { restartSensitivityPeriod = TimeSpec 0 1000 } procs withAsync sv $ \a -> do threadDelay 1000 rs1 <- for markers readTVarIO rs1 `shouldBe` replicate 10 True for_ markers $ \m -> atomically $ writeTVar m True for_ triggers $ \t -> threadDelay 1000 *> putMVar t () threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing rs2 <- for markers readTVarIO rs2 `shouldBe` replicate 10 True it "longer interval multiple killing transient child does not terminate Supervisor" $ do myTid <- myThreadId rs <- for [1..3] $ \_ -> do marker <- newTVarIO myTid blocker <- newEmptyMVar let process = newChildSpec Transient $ (myThreadId >>= atomically . writeTVar marker) *> takeMVar blocker $> () pure (marker, process) let (markers, procs) = unzip rs Actor _ sv <- newActor $ newSupervisor OneForAll def procs withAsync sv $ \a -> do threadDelay 10000 tids <- for markers readTVarIO tids `shouldSatisfy` notElem myTid for_ tids killThread threadDelay 1000 r <- poll a r `shouldSatisfy` isNothing tids1 <- for markers readTVarIO tids1 `shouldSatisfy` notElem myTid
018dc345384b4cc97f762fa0a97b85fc75c0a61fb323cd89489fa898f7e95cd1
input-output-hk/cardano-sl
Main.hs
module Main (main) where import Pos.Util.Log.LoggerConfig (LoggerConfig) import Pos.Infra.Network.Yaml (Topology) import Data.List.Split import System.Environment import Data.Yaml import Control.Monad.Catch import Data.Monoid main :: IO () main = do runTest "logConfigs" checkLogConfig runTest "topologyConfigs" checkTopology outpath <- getEnv "out" writeFile outpath "done" runTest :: FromJSON a => String -> (String -> IO a) -> IO () runTest var func = do paths <- getEnv var let pathList = splitOn " " paths doTest path = do putStrLn $ "testing: " <> path func path mapM_ doTest pathList checkLogConfig :: String -> IO LoggerConfig checkLogConfig path = do either throwM return =<< decodeFileEither path checkTopology :: String -> IO Topology checkTopology path = either throwM return =<< decodeFileEither path
null
https://raw.githubusercontent.com/input-output-hk/cardano-sl/1499214d93767b703b9599369a431e67d83f10a2/yaml-validation/Main.hs
haskell
module Main (main) where import Pos.Util.Log.LoggerConfig (LoggerConfig) import Pos.Infra.Network.Yaml (Topology) import Data.List.Split import System.Environment import Data.Yaml import Control.Monad.Catch import Data.Monoid main :: IO () main = do runTest "logConfigs" checkLogConfig runTest "topologyConfigs" checkTopology outpath <- getEnv "out" writeFile outpath "done" runTest :: FromJSON a => String -> (String -> IO a) -> IO () runTest var func = do paths <- getEnv var let pathList = splitOn " " paths doTest path = do putStrLn $ "testing: " <> path func path mapM_ doTest pathList checkLogConfig :: String -> IO LoggerConfig checkLogConfig path = do either throwM return =<< decodeFileEither path checkTopology :: String -> IO Topology checkTopology path = either throwM return =<< decodeFileEither path
fd95f866cf1fefa571fae6564874b1deccfcec3c69194f1df673f839ff29012d
buntine/Simply-Scheme-Exercises
20-5.scm
; Our name-table procedure uses a fixed width for the column containing the last names of the people in the argument list . Suppose that instead of liking British - invasion music you are into late romantic Russian composers : ; > ( name - table ' ( ( ) ( nicolay rimsky - korsakov ) ( sergei ) ( modest ) ) ) ; ; Alternatively, perhaps you like jazz: > ( name - table ' ( ( ) ( ) ( ) ) ) ; Modify name - table so that it figures out the longest last name in its argument list , adds two for spaces , and uses that number as the width of the first column . (define (name-table names) (name-table-helper names (+ (longest-surname names) 2))) (define (longest-surname names) (if (null? (cdr names)) (count (cadar names)) (find-longest-surname (cdr names) (count (cadar names))))) (define (find-longest-surname names len) (if (null? names) len (let ((namelen (count (cadar names)))) (find-longest-surname (cdr names) (if (> namelen len) namelen len))))) (define (name-table-helper names len) (if (null? names) 'done (begin (display (align (cadar names) len)) (show (caar names)) (name-table-helper (cdr names) len))))
null
https://raw.githubusercontent.com/buntine/Simply-Scheme-Exercises/c6cbf0bd60d6385b506b8df94c348ac5edc7f646/20-input-and-output/20-5.scm
scheme
Our name-table procedure uses a fixed width for the column containing the last Alternatively, perhaps you like jazz:
names of the people in the argument list . Suppose that instead of liking British - invasion music you are into late romantic Russian composers : > ( name - table ' ( ( ) ( nicolay rimsky - korsakov ) ( sergei ) ( modest ) ) ) > ( name - table ' ( ( ) ( ) ( ) ) ) Modify name - table so that it figures out the longest last name in its argument list , adds two for spaces , and uses that number as the width of the first column . (define (name-table names) (name-table-helper names (+ (longest-surname names) 2))) (define (longest-surname names) (if (null? (cdr names)) (count (cadar names)) (find-longest-surname (cdr names) (count (cadar names))))) (define (find-longest-surname names len) (if (null? names) len (let ((namelen (count (cadar names)))) (find-longest-surname (cdr names) (if (> namelen len) namelen len))))) (define (name-table-helper names len) (if (null? names) 'done (begin (display (align (cadar names) len)) (show (caar names)) (name-table-helper (cdr names) len))))
65338dd4448c4bdced4bcc0e2afd1a2eb71248a7c6670fe2a6f8709db36c6feb
ocaml/oasis
test_compile.ml
(******************************************************************************) OASIS : architecture for building OCaml libraries and applications (* *) Copyright ( C ) 2011 - 2016 , Copyright ( C ) 2008 - 2011 , OCamlCore SARL (* *) (* This library is free software; you can redistribute it and/or modify it *) (* under the terms of the GNU Lesser General Public License as published by *) the Free Software Foundation ; either version 2.1 of the License , or ( at (* your option) any later version, with the OCaml static compilation *) (* exception. *) (* *) (* This library is distributed in the hope that it will be useful, but *) (* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY *) (* or FITNESS FOR A PARTICULAR PURPOSE. See the file COPYING for more *) (* details. *) (* *) You should have received a copy of the GNU Lesser General Public License along with this library ; if not , write to the Free Software Foundation , Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA (******************************************************************************) let s = "test" let _ = Stringprep.caml_stringprep_xmpp_nodeprep s
null
https://raw.githubusercontent.com/ocaml/oasis/3d1a9421db92a0882ebc58c5df219b18c1e5681d/test/data/TestFull/with-cclib/src/test_compile.ml
ocaml
**************************************************************************** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by your option) any later version, with the OCaml static compilation exception. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file COPYING for more details. ****************************************************************************
OASIS : architecture for building OCaml libraries and applications Copyright ( C ) 2011 - 2016 , Copyright ( C ) 2008 - 2011 , OCamlCore SARL the Free Software Foundation ; either version 2.1 of the License , or ( at You should have received a copy of the GNU Lesser General Public License along with this library ; if not , write to the Free Software Foundation , Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA let s = "test" let _ = Stringprep.caml_stringprep_xmpp_nodeprep s
16a93d1b06eb217e68b38990517d4b6d84261e3deeb8cc72d34f96946c1e73d6
acl2/acl2
abstract-syntax.lisp
PFCS ( Prime Field Constraint System ) Library ; Copyright ( C ) 2023 Kestrel Institute ( ) ; License : A 3 - clause BSD license . See the LICENSE file distributed with ACL2 . ; Author : ( ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "PFCS") (include-book "centaur/fty/top" :dir :system) (include-book "std/util/defprojection" :dir :system) (include-book "xdoc/defxdoc-plus" :dir :system) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defxdoc+ abstract-syntax :parents (prime-field-constraint-systems) :short "Abstract syntax of PFCSes." :long (xdoc::topstring (xdoc::p "Expressions are built out of constants, variables, and field operations. A basic constraint is an equality between expressions. Constraints may be (conjunctively) grouped into named relations (see @(tsee definition)), which may be conjoined with equality constraints. A system of constraints is a collection of named relations, which are hierarchically organized, and constraints that may reference the relations.")) :order-subtopics t :default-parent t) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (fty::deftagsum expression :short "Fixtype of expressions." :long (xdoc::topstring (xdoc::p "We use any integers as constants. This way, the definition of expression (and of the other syntactic entities) does not depend on (the prime number that defines) the prime field. Semantically, integers are treated modulo the prime.") (xdoc::p "We use (any) symbols for variables.") (xdoc::p "We include just two field operations for now: addition and multiplication. These suffice for arithmetic circuits. Negation, and therefore subtraction, are easily represented, via multiplication by negative one (see @(tsee expression-neg) and @(tsee expression-sub)). We may add other operations in the future, most notably reciprocal, and therefore division. We may also add square roots, and even support user defined functions. Some of these operations will introduce the issue of well-definedness, e.g. non-zero divisors.")) (:const ((value int))) (:var ((name symbol))) (:add ((arg1 expression) (arg2 expression))) (:mul ((arg1 expression) (arg2 expression))) :pred expressionp) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (fty::deflist expression-list :short "Fixtype of lists of expressions." :elt-type expression :true-listp t :elementp-of-nil nil :pred expression-listp) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (fty::deftagsum constraint :short "Fixtype of constraints." :long (xdoc::topstring (xdoc::p "A constraint is either an equality of expressions, or the application of a named relation to argument expressions. We use (any) symbols for relation names.") (xdoc::p "In the future, this may be extended with propositional connectives to combine equalities and applications of named relations.")) (:equal ((left expression) (right expression))) (:relation ((name symbol) (args expression-list))) :pred constraintp) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (fty::deflist constraint-list :short "Fixtype of lists of constraints." :elt-type constraint :true-listp t :elementp-of-nil nil :pred constraint-listp) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (fty::defprod definition :short "Fixtype of definitions of relations." :long (xdoc::topstring (xdoc::p "A relation definition consists of the name of the relation (any symbol), a list of formal parameters (any symbols), and a body consisting of a list of constraints. The constraints are taken conjunctively; but see the discussion in @(tsee constraint) about possible extensions to allow explicit propositional connectives (in which case the body of a definition would presumably be just a single constraint, which may be a conjunction).")) ((name symbol) (para symbol-list) (body constraint-list)) :tag :definition :pred definitionp) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (fty::defoption definition-option definition :short "Fixtype of optional definitions of relations." :pred definition-optionp) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (fty::deflist definition-list :short "Fixtype of lists of definitions of relations." :elt-type definition :true-listp t :elementp-of-nil nil :pred definition-listp /// (defruled rev-of-definition-list-fix (equal (rev (definition-list-fix defs)) (definition-list-fix (rev defs))) :enable definition-list-fix)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (fty::defprod system :short "Fixtype of systems of constraints." :long (xdoc::topstring (xdoc::p "A system consists of a list of definitions and a list of constraints.")) ((definitions definition-list) (constraints constraint-list)) :pred systemp)
null
https://raw.githubusercontent.com/acl2/acl2/560688cd2b96edcacc5594329e238526c2d216d3/books/kestrel/crypto/pfcs/abstract-syntax.lisp
lisp
PFCS ( Prime Field Constraint System ) Library Copyright ( C ) 2023 Kestrel Institute ( ) License : A 3 - clause BSD license . See the LICENSE file distributed with ACL2 . Author : ( ) (in-package "PFCS") (include-book "centaur/fty/top" :dir :system) (include-book "std/util/defprojection" :dir :system) (include-book "xdoc/defxdoc-plus" :dir :system) (defxdoc+ abstract-syntax :parents (prime-field-constraint-systems) :short "Abstract syntax of PFCSes." :long (xdoc::topstring (xdoc::p "Expressions are built out of constants, variables, and field operations. A basic constraint is an equality between expressions. Constraints may be (conjunctively) grouped into named relations (see @(tsee definition)), which may be conjoined with equality constraints. A system of constraints is a collection of named relations, which are hierarchically organized, and constraints that may reference the relations.")) :order-subtopics t :default-parent t) (fty::deftagsum expression :short "Fixtype of expressions." :long (xdoc::topstring (xdoc::p "We use any integers as constants. This way, the definition of expression (and of the other syntactic entities) does not depend on (the prime number that defines) the prime field. Semantically, integers are treated modulo the prime.") (xdoc::p "We use (any) symbols for variables.") (xdoc::p "We include just two field operations for now: addition and multiplication. These suffice for arithmetic circuits. Negation, and therefore subtraction, are easily represented, via multiplication by negative one (see @(tsee expression-neg) and @(tsee expression-sub)). We may add other operations in the future, most notably reciprocal, and therefore division. We may also add square roots, and even support user defined functions. Some of these operations will introduce the issue of well-definedness, e.g. non-zero divisors.")) (:const ((value int))) (:var ((name symbol))) (:add ((arg1 expression) (arg2 expression))) (:mul ((arg1 expression) (arg2 expression))) :pred expressionp) (fty::deflist expression-list :short "Fixtype of lists of expressions." :elt-type expression :true-listp t :elementp-of-nil nil :pred expression-listp) (fty::deftagsum constraint :short "Fixtype of constraints." :long (xdoc::topstring (xdoc::p "A constraint is either an equality of expressions, or the application of a named relation to argument expressions. We use (any) symbols for relation names.") (xdoc::p "In the future, this may be extended with propositional connectives to combine equalities and applications of named relations.")) (:equal ((left expression) (right expression))) (:relation ((name symbol) (args expression-list))) :pred constraintp) (fty::deflist constraint-list :short "Fixtype of lists of constraints." :elt-type constraint :true-listp t :elementp-of-nil nil :pred constraint-listp) (fty::defprod definition :short "Fixtype of definitions of relations." :long (xdoc::topstring (xdoc::p "A relation definition consists of the name of the relation (any symbol), a list of formal parameters (any symbols), and a body consisting of a list of constraints. but see the discussion in @(tsee constraint) about possible extensions to allow explicit propositional connectives (in which case the body of a definition would presumably be just a single constraint, which may be a conjunction).")) ((name symbol) (para symbol-list) (body constraint-list)) :tag :definition :pred definitionp) (fty::defoption definition-option definition :short "Fixtype of optional definitions of relations." :pred definition-optionp) (fty::deflist definition-list :short "Fixtype of lists of definitions of relations." :elt-type definition :true-listp t :elementp-of-nil nil :pred definition-listp /// (defruled rev-of-definition-list-fix (equal (rev (definition-list-fix defs)) (definition-list-fix (rev defs))) :enable definition-list-fix)) (fty::defprod system :short "Fixtype of systems of constraints." :long (xdoc::topstring (xdoc::p "A system consists of a list of definitions and a list of constraints.")) ((definitions definition-list) (constraints constraint-list)) :pred systemp)
65b781310ea8365a3736b774980f3c1c445dd91c281d00038d4a323483382335
dinosaure/art
test_ring.ml
let pp_process_status ppf = function | Unix.WEXITED n -> Format.fprintf ppf "(WEXITED %d)" n | Unix.WSIGNALED n -> Format.fprintf ppf "(WSIGNALED %d)" n | Unix.WSTOPPED n -> Format.fprintf ppf "(WSTOPPED %d)" n let res = ref true let exit_success = 0 let exit_failure = 1 let properly_exited = function Unix.WEXITED 0 -> true | _ -> false let count = ref 0 let show filename = let ic = open_in filename in let rec go ic = match input_line ic with | line -> Format.printf "%s\n%!" line ; go ic | exception End_of_file -> close_in ic in go ic let run order len = let filename = Format.asprintf "%02d-ring.log" !count in incr count ; let log = Unix.openfile filename Unix.[ O_RDWR; O_CREAT; O_TRUNC ] 0o644 in let pid = Unix.create_process_env "./rb.exe" [| "./rb.exe"; "--tmp=./tmp"; string_of_int order; string_of_int len |] [||] Unix.stdin Unix.stdout log in let _, status = Unix.waitpid [] pid in Unix.close log ; res := !res && properly_exited status ; Format.printf ">>> ./rb.exe --tmp=./tmp %d %d: %a.\n%!" order len pp_process_status status ; if not (properly_exited status) then show filename let () = run 15 10 ; run 15 100 ; run 15 1000 ; if !res then exit exit_success else exit exit_failure
null
https://raw.githubusercontent.com/dinosaure/art/40af4c34a2e2ec9632cb73a74ac2ec0fd7f62a81/test/test_ring.ml
ocaml
let pp_process_status ppf = function | Unix.WEXITED n -> Format.fprintf ppf "(WEXITED %d)" n | Unix.WSIGNALED n -> Format.fprintf ppf "(WSIGNALED %d)" n | Unix.WSTOPPED n -> Format.fprintf ppf "(WSTOPPED %d)" n let res = ref true let exit_success = 0 let exit_failure = 1 let properly_exited = function Unix.WEXITED 0 -> true | _ -> false let count = ref 0 let show filename = let ic = open_in filename in let rec go ic = match input_line ic with | line -> Format.printf "%s\n%!" line ; go ic | exception End_of_file -> close_in ic in go ic let run order len = let filename = Format.asprintf "%02d-ring.log" !count in incr count ; let log = Unix.openfile filename Unix.[ O_RDWR; O_CREAT; O_TRUNC ] 0o644 in let pid = Unix.create_process_env "./rb.exe" [| "./rb.exe"; "--tmp=./tmp"; string_of_int order; string_of_int len |] [||] Unix.stdin Unix.stdout log in let _, status = Unix.waitpid [] pid in Unix.close log ; res := !res && properly_exited status ; Format.printf ">>> ./rb.exe --tmp=./tmp %d %d: %a.\n%!" order len pp_process_status status ; if not (properly_exited status) then show filename let () = run 15 10 ; run 15 100 ; run 15 1000 ; if !res then exit exit_success else exit exit_failure
f537856b3922c355f94d89011f66f7844bcc00fa0b924833466cf902c169ebb8
roblaing/erlang-webapp-howto
blog_handler.erl
-module(blog_handler). -behaviour(cowboy_websocket). -export([ init/2 , websocket_handle/2 , websocket_info/2 ]). init(Req, State) -> {cowboy_websocket, Req, State}. % Responds to Frames from client % InFrame :: ping | pong | {text | binary | ping | pong, binary()} websocket_handle({text, Json}, State) -> Proplist = jsx:decode(Json), case proplists:get_value(<<"page">>, Proplist, false) of <<"login">> -> delete_uid(Proplist), Uuid = getuuid(Proplist), RetMsg = jsx:encode([{<<"uuid">>, Uuid}]), {[{text, RetMsg}], State, hibernate}; <<"signup">> -> Name = proplists:get_value(<<"username">>, Proplist), #{num_rows := Rows} = pgo:query("SELECT name FROM users WHERE name=$1::text", [Name]), case Rows of 0 -> delete_uid(Proplist), Id = create_hash(proplists:get_value(<<"user_id">>, Proplist)), Email = proplists:get_value(<<"email">>, Proplist), pgo:query("INSERT INTO users (id, name, email) VALUES ($1::text, $2::text, $3::text)", [Id, Name, Email]), Uuid = getuuid(Proplist), RetMsg = jsx:encode([{<<"uuid">>, Uuid}]); 1 -> RetMsg = jsx:encode([{<<"uuid">>, false}]) end, {[{text, RetMsg}], State, hibernate}; <<"logout">> -> delete_uid(Proplist), {[], State, hibernate}; <<"front">> -> Logged = proplists:get_value(<<"uuid">>, Proplist, false), case ets:lookup(uuids, Logged) of [] -> Uuid = false; [{Logged, _Name}] -> Uuid = Logged end, Posts = getposts(), RetMsg = jsx:encode([{<<"uuid">>, Uuid}, {<<"posts">>, Posts}]), {[{text, RetMsg}], State, hibernate}; <<"newpost">> -> Uuid = proplists:get_value(<<"uuid">>, Proplist, false), Title = proplists:get_value(<<"title">>, Proplist), Art = proplists:get_value(<<"art">>, Proplist), pgo:query("INSERT INTO arts (title, art) VALUES ($1::text, $2::text)", [Title, Art]), RetMsg = jsx:encode([{<<"uuid">>, Uuid}]), {[{text, RetMsg}], State, hibernate} end. % This has to be here, but isn't used. websocket_info(_Info, State) -> {[], State, hibernate}. -spec create_hash(Input::binary()) -> Hexdigest :: string(). %% @doc Rehash the hexdigest read from browser cookie and return as a new hexdigest. create_hash(Binary) -> Salt = "Some very long randomly generated string", <<I:256>> = crypto:mac(hmac, sha256, Salt, Binary), string:lowercase(integer_to_binary(I, 16)). -spec logged_in(Proplist :: [{Uuid::bitstring(), Name::bitstring()}]) -> Name::bitstring() | false. %% @doc Check if uuid is false, and if not that it's a valid ID. logged_in(Proplist) -> Bin = proplists:get_value(<<"uuid">>, Proplist, false), case Bin of false -> false; Uuid -> case ets:lookup(uuids, Uuid) of [] -> false; [{Uuid, Name}] -> ets:lookup(uuids, Uuid), Name end end. -spec delete_uid(Proplist::[{Uuid::bitstring(), Name::bitstring()}]) -> true. %% @doc Call before new login or signup to avoid cluttering ETS with uuid/name pairs which have been overwitten in browsers. delete_uid(Proplist) -> Logged = logged_in(Proplist), case Logged of false -> true; _Name -> Uuid = proplists:get_value(<<"uuid">>, Proplist), ets:delete(uuids, Uuid) end. -spec getuuid(Proplist::[{Uuid::bitstring(), Name::bitstring()}]) -> Uuid::bitstring() | false. %% @doc Return a unique hashkey if the supplied user_id is valid, else false. getuuid(Proplist) -> case proplists:get_value(<<"user_id">>, Proplist, false) of false -> false; Hash -> #{rows := Rows} = pgo:query("SELECT name FROM users WHERE id=$1::text", [create_hash(Hash)]), case Rows of [] -> false; [{Name}] -> String = io_lib:format("~p~p~p", [erlang:system_time(millisecond), make_ref(), node()]), <<I:128>> = crypto:hash(md5, String), Uuid = integer_to_binary(I, 16), Unique = ets:insert_new(uuids, {Uuid, Name}), case Unique of true -> Uuid; false -> getuuid(Proplist) end, Uuid end end. getposts() -> #{rows := Rows} = pgo:query("SELECT id, title, art, created FROM arts ORDER BY created DESC LIMIT 10"), lists:map(fun({Id, Title, Art, Created}) -> [{<<"id">>, Id}, {<<"title">>, Title}, {<<"art">>, Art}, {<<"created">>, Created}] end, Rows).
null
https://raw.githubusercontent.com/roblaing/erlang-webapp-howto/e1731dfc4e2cfdfee88e982d67155b83acd5cc04/unit8/apps/unit8/src/blog_handler.erl
erlang
Responds to Frames from client InFrame :: ping | pong | {text | binary | ping | pong, binary()} This has to be here, but isn't used. @doc Rehash the hexdigest read from browser cookie and return as a new hexdigest. @doc Check if uuid is false, and if not that it's a valid ID. @doc Call before new login or signup to avoid cluttering ETS with uuid/name pairs which have been overwitten in browsers. @doc Return a unique hashkey if the supplied user_id is valid, else false.
-module(blog_handler). -behaviour(cowboy_websocket). -export([ init/2 , websocket_handle/2 , websocket_info/2 ]). init(Req, State) -> {cowboy_websocket, Req, State}. websocket_handle({text, Json}, State) -> Proplist = jsx:decode(Json), case proplists:get_value(<<"page">>, Proplist, false) of <<"login">> -> delete_uid(Proplist), Uuid = getuuid(Proplist), RetMsg = jsx:encode([{<<"uuid">>, Uuid}]), {[{text, RetMsg}], State, hibernate}; <<"signup">> -> Name = proplists:get_value(<<"username">>, Proplist), #{num_rows := Rows} = pgo:query("SELECT name FROM users WHERE name=$1::text", [Name]), case Rows of 0 -> delete_uid(Proplist), Id = create_hash(proplists:get_value(<<"user_id">>, Proplist)), Email = proplists:get_value(<<"email">>, Proplist), pgo:query("INSERT INTO users (id, name, email) VALUES ($1::text, $2::text, $3::text)", [Id, Name, Email]), Uuid = getuuid(Proplist), RetMsg = jsx:encode([{<<"uuid">>, Uuid}]); 1 -> RetMsg = jsx:encode([{<<"uuid">>, false}]) end, {[{text, RetMsg}], State, hibernate}; <<"logout">> -> delete_uid(Proplist), {[], State, hibernate}; <<"front">> -> Logged = proplists:get_value(<<"uuid">>, Proplist, false), case ets:lookup(uuids, Logged) of [] -> Uuid = false; [{Logged, _Name}] -> Uuid = Logged end, Posts = getposts(), RetMsg = jsx:encode([{<<"uuid">>, Uuid}, {<<"posts">>, Posts}]), {[{text, RetMsg}], State, hibernate}; <<"newpost">> -> Uuid = proplists:get_value(<<"uuid">>, Proplist, false), Title = proplists:get_value(<<"title">>, Proplist), Art = proplists:get_value(<<"art">>, Proplist), pgo:query("INSERT INTO arts (title, art) VALUES ($1::text, $2::text)", [Title, Art]), RetMsg = jsx:encode([{<<"uuid">>, Uuid}]), {[{text, RetMsg}], State, hibernate} end. websocket_info(_Info, State) -> {[], State, hibernate}. -spec create_hash(Input::binary()) -> Hexdigest :: string(). create_hash(Binary) -> Salt = "Some very long randomly generated string", <<I:256>> = crypto:mac(hmac, sha256, Salt, Binary), string:lowercase(integer_to_binary(I, 16)). -spec logged_in(Proplist :: [{Uuid::bitstring(), Name::bitstring()}]) -> Name::bitstring() | false. logged_in(Proplist) -> Bin = proplists:get_value(<<"uuid">>, Proplist, false), case Bin of false -> false; Uuid -> case ets:lookup(uuids, Uuid) of [] -> false; [{Uuid, Name}] -> ets:lookup(uuids, Uuid), Name end end. -spec delete_uid(Proplist::[{Uuid::bitstring(), Name::bitstring()}]) -> true. delete_uid(Proplist) -> Logged = logged_in(Proplist), case Logged of false -> true; _Name -> Uuid = proplists:get_value(<<"uuid">>, Proplist), ets:delete(uuids, Uuid) end. -spec getuuid(Proplist::[{Uuid::bitstring(), Name::bitstring()}]) -> Uuid::bitstring() | false. getuuid(Proplist) -> case proplists:get_value(<<"user_id">>, Proplist, false) of false -> false; Hash -> #{rows := Rows} = pgo:query("SELECT name FROM users WHERE id=$1::text", [create_hash(Hash)]), case Rows of [] -> false; [{Name}] -> String = io_lib:format("~p~p~p", [erlang:system_time(millisecond), make_ref(), node()]), <<I:128>> = crypto:hash(md5, String), Uuid = integer_to_binary(I, 16), Unique = ets:insert_new(uuids, {Uuid, Name}), case Unique of true -> Uuid; false -> getuuid(Proplist) end, Uuid end end. getposts() -> #{rows := Rows} = pgo:query("SELECT id, title, art, created FROM arts ORDER BY created DESC LIMIT 10"), lists:map(fun({Id, Title, Art, Created}) -> [{<<"id">>, Id}, {<<"title">>, Title}, {<<"art">>, Art}, {<<"created">>, Created}] end, Rows).
5af981cf23e37d10441600693636bbbbd29c2791febfd78f5a18cc262de092ee
ocaml-doc/doc-ock
docOckPayload.ml
* Copyright ( c ) 2014 < > * * 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) 2014 Leo White <> * * 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 read = let open Parsetree in function | PStr[{ pstr_desc = Pstr_eval({ pexp_desc = Pexp_constant( Parsetree.Pconst_string(str, _)); pexp_loc = loc; _ }, _) ; _ }] -> Some(str, loc) | _ -> None
null
https://raw.githubusercontent.com/ocaml-doc/doc-ock/788aabe6e3d157633890f67042d6a4d0161835a7/src/docOckPayload.ml
ocaml
* Copyright ( c ) 2014 < > * * 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) 2014 Leo White <> * * 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 read = let open Parsetree in function | PStr[{ pstr_desc = Pstr_eval({ pexp_desc = Pexp_constant( Parsetree.Pconst_string(str, _)); pexp_loc = loc; _ }, _) ; _ }] -> Some(str, loc) | _ -> None
09019eeef9fc29ec8248d3e924097cc3f7196ecb8e03adaf99bbba5912ad968c
oreillymedia/etudes-for-erlang
bad_code.erl
%% @author J D Eisenberg <> %% @doc How not to create lists (and a correct example) 2013 J D Eisenberg %% @version 0.1 -module(bad_code). -export([squares/1, squares2/1]). %% @doc Attempt to square a list of numbers. %% This is the worst approach to use, as it generates improper lists. -spec(squares(list()) -> list()). squares(Numbers) -> squares(Numbers, []). squares([], Result) -> Result; squares([H | T], Result) -> squares(T, [Result | H * H ]). %% @doc Another attempt to square a list of numbers. %% This is a bad approach to use; at least you get a list, %% but it's a nested list. -spec(squares2(list()) -> list()). squares2(Numbers) -> squares2(Numbers, []). squares2([], Result) -> Result; squares2([H | T], Result) -> squares2(T, [Result | [H * H] ]).
null
https://raw.githubusercontent.com/oreillymedia/etudes-for-erlang/07200372503a8819f9fcc2856f8cb82451be7b48/code/ch06-interlude/bad_code.erl
erlang
@author J D Eisenberg <> @doc How not to create lists (and a correct example) @version 0.1 @doc Attempt to square a list of numbers. This is the worst approach to use, as it generates improper lists. @doc Another attempt to square a list of numbers. This is a bad approach to use; at least you get a list, but it's a nested list.
2013 J D Eisenberg -module(bad_code). -export([squares/1, squares2/1]). -spec(squares(list()) -> list()). squares(Numbers) -> squares(Numbers, []). squares([], Result) -> Result; squares([H | T], Result) -> squares(T, [Result | H * H ]). -spec(squares2(list()) -> list()). squares2(Numbers) -> squares2(Numbers, []). squares2([], Result) -> Result; squares2([H | T], Result) -> squares2(T, [Result | [H * H] ]).
967d9d4a41559cbfcc7e9b840612c36d8d2a8c99eb69c1ac8fc52f6f5ee8903a
jeannekamikaze/Spear
Step.hs
# LANGUAGE FlexibleInstances # module Spear.Step ( -- * Definitions Step, Elapsed, Dt, -- * Running runStep, -- * Constructors step, sid, spure, sfst, ssnd, sfold, -- * Combinators (.>), (<.), szip, switch, multiSwitch, ) where import Data.List (foldl') import Data.Map (Map) import qualified Data.Map as Map import Data.Monoid type Elapsed = Double type Dt = Float -- | A step function. newtype Step state events input a = Step { runStep :: Elapsed -> Dt -> state -> events -> input -> (a, Step state events input a) } instance Functor (Step s e a) where fmap f (Step s1) = Step $ \elapsed dt g e x -> let (a, s') = s1 elapsed dt g e x in (f a, fmap f s') instance Semigroup (Step s e a a) where (<>) = (.>) instance Monoid (Step s e a a) where mempty = sid mappend (Step s1) (Step s2) = Step $ \elapsed dt g e a -> let (b, s1') = s1 elapsed dt g e a (c, s2') = s2 elapsed dt g e b in (c, mappend s1' s2') -- | Construct a step from a function. step :: (Elapsed -> Dt -> s -> e -> a -> (b, Step s e a b)) -> Step s e a b step = Step -- | Step identity. sid :: Step s e a a sid = Step $ \_ _ _ _ a -> (a, sid) -- | Construct a step from a pure function. spure :: (a -> b) -> Step s e a b spure f = Step $ \_ _ _ _ x -> (f x, spure f) | The step that returns the first component in the tuple . sfst :: Step s e (a, b) a sfst = spure $ \(a, _) -> a | The step that returns the second component in the tuple . ssnd :: Step s e (a, b) b ssnd = spure $ \(_, b) -> b -- | Construct a step that folds a given list of inputs. -- The step is run N+1 times , where N is the size of the input list . sfold :: Step s (Maybe e) a a -> Step s [e] a a sfold s = Step $ \elapsed dt g es a -> case es of [] -> let (b', s') = runStep s elapsed dt g Nothing a in (b', sfold s') es -> let (b', s') = sfold' elapsed dt g s a es in (b', sfold s') sfold' :: Elapsed -> Dt -> s -> Step s (Maybe e) a a -> a -> [e] -> (a, Step s (Maybe e) a a) sfold' elapsed dt g s a es = foldl' f (a', s') es where f (a, s) e = runStep s elapsed dt g (Just e) a (a', s') = runStep s elapsed dt g Nothing a -- Combinators | Compose two steps . (.>) :: Step s e a b -> Step s e b c -> Step s e a c (Step s1) .> (Step s2) = Step $ \elapsed dt g e a -> let (b, s1') = s1 elapsed dt g e a (c, s2') = s2 elapsed dt g e b in (c, s1' .> s2') | Compose two steps . (<.) :: Step s e a b -> Step s e c a -> Step s e c b (<.) = flip (.>) | Evaluate two steps and zip their results . szip :: (a -> b -> c) -> Step s e d a -> Step s e d b -> Step s e d c szip f (Step s1) (Step s2) = Step $ \elapsed dt g e d -> let (a, s1') = s1 elapsed dt g e d (b, s2') = s2 elapsed dt g e d in (f a b, szip f s1' s2') | Construct a step that switches between two steps based on input . -- The initial step is the first one . switch :: Eq e => e -> (Step s (Maybe e) a a) -> e -> (Step s (Maybe e) a a) -> Step s (Maybe e) a a switch flag1 s1 flag2 s2 = switch' s1 flag1 s1 flag2 s2 switch' :: Eq e => (Step s (Maybe e) a a) -> e -> (Step s (Maybe e) a a) -> e -> (Step s (Maybe e) a a) -> Step s (Maybe e) a a switch' cur flag1 s1 flag2 s2 = Step $ \elapsed dt g e a -> case e of Nothing -> let (a', s') = runStep cur elapsed dt g Nothing a in (a', switch' s' flag1 s1 flag2 s2) Just e' -> let next = if e' == flag1 then s1 else if e' == flag2 then s2 else cur (a', s') = runStep next elapsed dt g e a in (a', switch' s' flag1 s1 flag2 s2) -- | Construct a step that switches among multiple steps based on input. multiSwitch :: (Eq e, Ord e) => [(e, Step s (Maybe e) a a)] -> Step s (Maybe e) a a multiSwitch xs = multiSwitch' Nothing sid (Map.fromList xs) multiSwitch' :: (Eq e, Ord e) => Maybe e -> Step s (Maybe e) a a -> Map e (Step s (Maybe e) a a) -> Step s (Maybe e) a a multiSwitch' curKey cur m = Step $ \elapsed dt g e a -> let singleStep = let (a', s') = runStep cur elapsed dt g e a in (a', multiSwitch' curKey s' m) in case e of Nothing -> singleStep Just e' -> case Map.lookup e' m of Nothing -> singleStep Just s -> let (a', s') = runStep s elapsed dt g e a m' = case curKey of Nothing -> m Just key -> Map.insert key cur m in (a', multiSwitch' e s' m')
null
https://raw.githubusercontent.com/jeannekamikaze/Spear/8f2ec33e8c15e523b2b60d3bfd8e6360313a0657/Spear/Step.hs
haskell
* Definitions * Running * Constructors * Combinators | A step function. | Construct a step from a function. | Step identity. | Construct a step from a pure function. | Construct a step that folds a given list of inputs. Combinators | Construct a step that switches among multiple steps based on input.
# LANGUAGE FlexibleInstances # module Spear.Step Step, Elapsed, Dt, runStep, step, sid, spure, sfst, ssnd, sfold, (.>), (<.), szip, switch, multiSwitch, ) where import Data.List (foldl') import Data.Map (Map) import qualified Data.Map as Map import Data.Monoid type Elapsed = Double type Dt = Float newtype Step state events input a = Step { runStep :: Elapsed -> Dt -> state -> events -> input -> (a, Step state events input a) } instance Functor (Step s e a) where fmap f (Step s1) = Step $ \elapsed dt g e x -> let (a, s') = s1 elapsed dt g e x in (f a, fmap f s') instance Semigroup (Step s e a a) where (<>) = (.>) instance Monoid (Step s e a a) where mempty = sid mappend (Step s1) (Step s2) = Step $ \elapsed dt g e a -> let (b, s1') = s1 elapsed dt g e a (c, s2') = s2 elapsed dt g e b in (c, mappend s1' s2') step :: (Elapsed -> Dt -> s -> e -> a -> (b, Step s e a b)) -> Step s e a b step = Step sid :: Step s e a a sid = Step $ \_ _ _ _ a -> (a, sid) spure :: (a -> b) -> Step s e a b spure f = Step $ \_ _ _ _ x -> (f x, spure f) | The step that returns the first component in the tuple . sfst :: Step s e (a, b) a sfst = spure $ \(a, _) -> a | The step that returns the second component in the tuple . ssnd :: Step s e (a, b) b ssnd = spure $ \(_, b) -> b The step is run N+1 times , where N is the size of the input list . sfold :: Step s (Maybe e) a a -> Step s [e] a a sfold s = Step $ \elapsed dt g es a -> case es of [] -> let (b', s') = runStep s elapsed dt g Nothing a in (b', sfold s') es -> let (b', s') = sfold' elapsed dt g s a es in (b', sfold s') sfold' :: Elapsed -> Dt -> s -> Step s (Maybe e) a a -> a -> [e] -> (a, Step s (Maybe e) a a) sfold' elapsed dt g s a es = foldl' f (a', s') es where f (a, s) e = runStep s elapsed dt g (Just e) a (a', s') = runStep s elapsed dt g Nothing a | Compose two steps . (.>) :: Step s e a b -> Step s e b c -> Step s e a c (Step s1) .> (Step s2) = Step $ \elapsed dt g e a -> let (b, s1') = s1 elapsed dt g e a (c, s2') = s2 elapsed dt g e b in (c, s1' .> s2') | Compose two steps . (<.) :: Step s e a b -> Step s e c a -> Step s e c b (<.) = flip (.>) | Evaluate two steps and zip their results . szip :: (a -> b -> c) -> Step s e d a -> Step s e d b -> Step s e d c szip f (Step s1) (Step s2) = Step $ \elapsed dt g e d -> let (a, s1') = s1 elapsed dt g e d (b, s2') = s2 elapsed dt g e d in (f a b, szip f s1' s2') | Construct a step that switches between two steps based on input . The initial step is the first one . switch :: Eq e => e -> (Step s (Maybe e) a a) -> e -> (Step s (Maybe e) a a) -> Step s (Maybe e) a a switch flag1 s1 flag2 s2 = switch' s1 flag1 s1 flag2 s2 switch' :: Eq e => (Step s (Maybe e) a a) -> e -> (Step s (Maybe e) a a) -> e -> (Step s (Maybe e) a a) -> Step s (Maybe e) a a switch' cur flag1 s1 flag2 s2 = Step $ \elapsed dt g e a -> case e of Nothing -> let (a', s') = runStep cur elapsed dt g Nothing a in (a', switch' s' flag1 s1 flag2 s2) Just e' -> let next = if e' == flag1 then s1 else if e' == flag2 then s2 else cur (a', s') = runStep next elapsed dt g e a in (a', switch' s' flag1 s1 flag2 s2) multiSwitch :: (Eq e, Ord e) => [(e, Step s (Maybe e) a a)] -> Step s (Maybe e) a a multiSwitch xs = multiSwitch' Nothing sid (Map.fromList xs) multiSwitch' :: (Eq e, Ord e) => Maybe e -> Step s (Maybe e) a a -> Map e (Step s (Maybe e) a a) -> Step s (Maybe e) a a multiSwitch' curKey cur m = Step $ \elapsed dt g e a -> let singleStep = let (a', s') = runStep cur elapsed dt g e a in (a', multiSwitch' curKey s' m) in case e of Nothing -> singleStep Just e' -> case Map.lookup e' m of Nothing -> singleStep Just s -> let (a', s') = runStep s elapsed dt g e a m' = case curKey of Nothing -> m Just key -> Map.insert key cur m in (a', multiSwitch' e s' m')
d3c278f9f7c65d9fa86c6af2b97cb6580e2dd049adba536bb4a889216576b2e4
joelagnel/stumpwm-goodies
modeline-cpu.lisp
(defvar *prev-user-cpu* 0) (defvar *prev-sys-cpu* 0) (defvar *prev-idle-cpu* 0) (defvar *prev-iowait* 0) (defun current-cpu-usage () "Return the average CPU usage since the last call. First value is percent of CPU in use. Second value is percent of CPU in use by system processes. Third value is percent of time since last call spent waiting for IO (or 0 if not available)." (let ((cpu-result 0) (sys-result 0) (io-result nil)) (with-open-file (in "/proc/stat" :direction :input) (if (eq 'cpu (read in)) (let* ((norm-user (read in)) (nice-user (read in)) (user (+ norm-user nice-user)) (sys (read in)) (idle (read in)) (iowait (or (ignore-errors (read in)) 0)) (step-denom (- (+ user sys idle iowait) (+ *prev-user-cpu* *prev-sys-cpu* *prev-idle-cpu* *prev-iowait*)))) (setf cpu-result (/ (- (+ user sys) (+ *prev-user-cpu* *prev-sys-cpu*)) step-denom) sys-result (/ (- sys *prev-sys-cpu*) step-denom) io-result (/ (- iowait *prev-iowait*) step-denom) *prev-user-cpu* user *prev-sys-cpu* sys *prev-idle-cpu* idle *prev-iowait* iowait)) (warn "Unexpected header"))) (values cpu-result sys-result io-result))) (defun format-current-cpu-usage (stream) "Formats a string representing the current processor usage to STREAM. Arguments are as those to FORMAT, so NIL returns a formatted string and T prints to standard output." (multiple-value-bind (cpu sys io) (current-cpu-usage) (declare (ignore sys)) (format stream "[cpu:~3D%] [io:~3D%]" (truncate (* 100 cpu)) (if io (truncate (* 100 io)) 0)))) ( setf * screen - mode - line - format * ( list " % w " ;; ;; ... some other modeline settings ... ' (: ( format - current - cpu - usage nil ) ) ) )
null
https://raw.githubusercontent.com/joelagnel/stumpwm-goodies/bf9dee6a2e92fea6f2160c37565a74072e367d36/mode-line/modeline-cpu.lisp
lisp
;; ... some other modeline settings ...
(defvar *prev-user-cpu* 0) (defvar *prev-sys-cpu* 0) (defvar *prev-idle-cpu* 0) (defvar *prev-iowait* 0) (defun current-cpu-usage () "Return the average CPU usage since the last call. First value is percent of CPU in use. Second value is percent of CPU in use by system processes. Third value is percent of time since last call spent waiting for IO (or 0 if not available)." (let ((cpu-result 0) (sys-result 0) (io-result nil)) (with-open-file (in "/proc/stat" :direction :input) (if (eq 'cpu (read in)) (let* ((norm-user (read in)) (nice-user (read in)) (user (+ norm-user nice-user)) (sys (read in)) (idle (read in)) (iowait (or (ignore-errors (read in)) 0)) (step-denom (- (+ user sys idle iowait) (+ *prev-user-cpu* *prev-sys-cpu* *prev-idle-cpu* *prev-iowait*)))) (setf cpu-result (/ (- (+ user sys) (+ *prev-user-cpu* *prev-sys-cpu*)) step-denom) sys-result (/ (- sys *prev-sys-cpu*) step-denom) io-result (/ (- iowait *prev-iowait*) step-denom) *prev-user-cpu* user *prev-sys-cpu* sys *prev-idle-cpu* idle *prev-iowait* iowait)) (warn "Unexpected header"))) (values cpu-result sys-result io-result))) (defun format-current-cpu-usage (stream) "Formats a string representing the current processor usage to STREAM. Arguments are as those to FORMAT, so NIL returns a formatted string and T prints to standard output." (multiple-value-bind (cpu sys io) (current-cpu-usage) (declare (ignore sys)) (format stream "[cpu:~3D%] [io:~3D%]" (truncate (* 100 cpu)) (if io (truncate (* 100 io)) 0)))) ( setf * screen - mode - line - format * ( list " % w " ' (: ( format - current - cpu - usage nil ) ) ) )
7291289613541a06ae30784b52d949d7ac5fe2abef1af88cc0ee78eb34a6dd6d
aristidb/aws
Aws.hs
module Aws ( -- * Logging LogLevel(..) , Logger , defaultLog -- * Configuration , Configuration(..) , baseConfiguration , dbgConfiguration -- * Transaction runners -- ** Safe runners , aws , awsRef , pureAws , simpleAws -- ** Unsafe runners , unsafeAws , unsafeAwsRef -- ** URI runners , awsUri -- ** Iterated runners --, awsIteratedAll , awsIteratedSource , awsIteratedList -- * Response -- ** Full HTTP response , HTTPResponseConsumer -- ** Metadata in responses , Response(..) , readResponse , readResponseIO , ResponseMetadata -- ** Memory responses , AsMemoryResponse(..) -- ** Exception types , XmlException(..) , HeaderException(..) , FormException(..) -- * Query -- ** Service configuration , ServiceConfiguration , DefaultServiceConfiguration(..) , NormalQuery , UriOnlyQuery -- ** Expiration , TimeInfo(..) -- * Transactions , Transaction , IteratedTransaction -- * Credentials , Credentials(..) , makeCredentials , credentialsDefaultFile , credentialsDefaultKey , loadCredentialsFromFile , loadCredentialsFromEnv , loadCredentialsFromInstanceMetadata , loadCredentialsFromEnvOrFile , loadCredentialsFromEnvOrFileOrInstanceMetadata , loadCredentialsDefault , anonymousCredentials ) where import Aws.Aws import Aws.Core
null
https://raw.githubusercontent.com/aristidb/aws/9bdc4ee018d0d9047c0434eeb21e2383afaa9ccf/Aws.hs
haskell
* Logging * Configuration * Transaction runners ** Safe runners ** Unsafe runners ** URI runners ** Iterated runners , awsIteratedAll * Response ** Full HTTP response ** Metadata in responses ** Memory responses ** Exception types * Query ** Service configuration ** Expiration * Transactions * Credentials
module Aws LogLevel(..) , Logger , defaultLog , Configuration(..) , baseConfiguration , dbgConfiguration , aws , awsRef , pureAws , simpleAws , unsafeAws , unsafeAwsRef , awsUri , awsIteratedSource , awsIteratedList , HTTPResponseConsumer , Response(..) , readResponse , readResponseIO , ResponseMetadata , AsMemoryResponse(..) , XmlException(..) , HeaderException(..) , FormException(..) , ServiceConfiguration , DefaultServiceConfiguration(..) , NormalQuery , UriOnlyQuery , TimeInfo(..) , Transaction , IteratedTransaction , Credentials(..) , makeCredentials , credentialsDefaultFile , credentialsDefaultKey , loadCredentialsFromFile , loadCredentialsFromEnv , loadCredentialsFromInstanceMetadata , loadCredentialsFromEnvOrFile , loadCredentialsFromEnvOrFileOrInstanceMetadata , loadCredentialsDefault , anonymousCredentials ) where import Aws.Aws import Aws.Core
559f87c08f7925d694a74f8c93cd62939e5a837d744320370c2ce2fbb21c0e3f
li-clutter-org/http2-test
Session.hs
# LANGUAGE FlexibleContexts , Rank2Types # module Rede.SpdyProtocol.Session( -- trivialSession basicSession -- ,showHeadersIfPresent ) where import Control.Concurrent (forkIO) import Control.Monad.IO.Class (liftIO) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Reader import Control.Exception(throwIO) import Data.Conduit -- import Data.IORef import qualified Data.Streaming.Zlib as Z -- import Data.Conduit.Lift (distribute) import qualified Data . Conduit . List as CL import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as LB import Data.ByteString.Char8 (pack) import Data.Default (def) import Control.Concurrent.MVar import qualified Data.Map as MA import Data.Binary.Put (runPut) import qualified Data.Binary as Bi import Data.Binary.Get (runGet) import qualified Data.HashTable.IO as H import qualified Data.Dequeue as D import Rede.SpdyProtocol.Framing.AnyFrame import Rede.SpdyProtocol.Framing.Frame import Rede.SpdyProtocol.Framing.Ping import Rede.SpdyProtocol.Framing.DataFrame import Rede.SpdyProtocol.Framing.RstStream import Rede.SpdyProtocol.Framing.WindowUpdate import Rede.MainLoop.StreamPlug import Rede.SpdyProtocol.Framing.KeyValueBlock import qualified Rede.SpdyProtocol.Framing.Settings as SeF import Rede.SpdyProtocol.Streams.State import Rede.MainLoop.Tokens -- TODO: Move to constants? initialSettings :: SeF.SettingsFrame initialSettings = SeF.SettingsFrame { SeF.prologue = def ,SeF.persistSettings = [ (SeF.InitialWindowSize_S, 65536, SeF.None_PS) ] } goAwayMsg : : -- goAwayMsg = GoA.GoAwayFrame { -- GoA.prologue = def -- ,GoA.statusCode = GoA.OK_GAR -- ,GoA.lastGoodStream = 0 -- } type WaitList = D.BankersDequeue AnyFrame -- A table from stream id to windows reamining list and waiting -- list type StreamWindowInfo = MVar (Int, WaitList) type StreamWaits = H.BasicHashTable Int StreamWindowInfo data SimpleSessionStateRecord = SimpleSessionStateRecord { streamInputs :: MVar (MA.Map Int (MVar AnyFrame)) , streamsOutput : : MVar ( Maybe AnyFrame ) ,sendZLib :: MVar Z.Deflate ,recvZLib :: MVar Z.Inflate ,streamInit :: Int -> IO () -> StreamStateT IO () -> IO () -- Need also a way to do frame-flow control ,streamWaits :: StreamWaits ,initialWindowSize :: MVar Int ,sessionWindow :: MVar Int } type SessionM = ReaderT SimpleSessionStateRecord -- | Super-simple session manager without flow control and such.... -- but using StreamWorkers already.... -- TODO: without proper flow control, we are in troubles.... basicSession :: (StreamWorkerClass serviceParams servicePocket sessionPocket) => servicePocket -> IO ( (Sink AnyFrame IO () ), (Source IO AnyFrame ) ) basicSession worker_service_pocket = do -- Create the input record.... stream_inputs <- newMVar $ MA.empty -- Whatever is put here makes it to the socket, so this -- should go after flow control session_gate <- (newEmptyMVar :: IO (MVar AnyFrame) ) send_zlib <- Z.initDeflateWithDictionary 2 zLibInitDict Z.defaultWindowBits send_zlib_mvar <- newMVar send_zlib recv_zlib <- Z.initInflateWithDictionary Z.defaultWindowBits zLibInitDict recv_zlib_mvar <- newMVar recv_zlib worker_session_pocket <- initSession worker_service_pocket Preserve the IO wrapper make_worker <- return $ initStream worker_service_pocket worker_session_pocket Stream ids pushed from the server start at two stream_waits <- H.new -- TODO: Fix this initial_window_size <- newMVar 65536 session_window <- newMVar 65536 session_record <- return $ SimpleSessionStateRecord { streamInputs = stream_inputs ,sendZLib = send_zlib_mvar ,recvZLib = recv_zlib_mvar ,streamInit = \ stream_id fin -> initStreamState stream_id fin next_stream_id ,streamWaits = stream_waits ,initialWindowSize = initial_window_size ,sessionWindow = session_window } -- hoister <- return $ (\ x -> runReaderT x session_record :: SessionM IO a -> IO a) flow_control_gate <- liftIO $ newEmptyMVar -- This is the end of the pipeline which is closest to the TCP socket in the input direction The " flow_control_gate " variable here is given to newly created streams , it is also used directly by the sink to process WindowUpdate frames ... packet_sink <- return $ transPipe ( \ x -> runReaderT x session_record) (statefulSink make_worker flow_control_gate) -- We will need to run flow control liftIO $ forkIO $ runReaderT (flowControl flow_control_gate session_gate) session_record -- This is the end of the pipeline that is closest to the TCP socket in the output direction packet_source <- return $ transPipe (\ x -> runReaderT x session_record) (createTrivialSource session_gate) return (packet_sink, packet_source) takesInput :: MVar AnyFrame -> Source (StreamStateT IO) AnyFrame takesInput input_mvar = do frame <- liftIO $ takeMVar input_mvar -- liftIO $ putStrLn "Got something" yield frame takesInput input_mvar plugStream :: IO StreamWorker -> MVar AnyFrame -> MVar (Either AnyFrame (Int,Int) ) -> IO ( StreamStateT IO () ) plugStream workerStart input_mvar drop_output_here_mvar = do worker <- workerStart return (( (takesInput input_mvar) $= inputPlug =$= (transPipe liftIO (worker::StreamWorker)) =$= (outputPlug :: Conduit StreamOutputAction (StreamStateT IO) AnyFrame) -- ATTENTION: potential session race-condition here. $$ (streamOutput drop_output_here_mvar) )) -- | Takes output from the stream conduit and puts it on the output mvar. This runs in -- the stream thread. -- ATTENTION: When a stream finishes, the conduit closes and yields a Nothing to -- signal that streamOutput :: MVar (Either AnyFrame (Int,Int) ) -> Sink AnyFrame (StreamStateT IO) () streamOutput output_mvar = do any_frame_maybe <- await case any_frame_maybe of -- The stream is alive Just anyframe -> do liftIO $ putMVar output_mvar $ Left anyframe streamOutput output_mvar --The stream wishes to finish, in this case, do n't put anything in the output MVar , but --call a provided finalizer Nothing -> do lift streamFinalize -- Now let natural finalization of the conduit to take -- place... -- IMPLEMENT: iDropThisFrame (Ping_CFT) iDropThisFrame :: AnyControlFrame -> Bool iDropThisFrame ( SettingsFrame_ACF _ ) = True -- iDropThisFrame (WindowUpdateFrame_ACF _ ) = True iDropThisFrame _ = False -- | Takes a stream worker constructor and properly sets its connections so that -- it can take and place data in the multi-threaded pipeline. statefulSink :: IO StreamWorker -- ^ When needed, create a new stream worker here. -> MVar (Either AnyFrame (Int,Int) ) -- ^ All outputs of this session should be placed here -- (This should go to ) -> Sink AnyFrame (SessionM IO) () statefulSink init_worker flow_control_gate = do anyframe_maybe <- await session_record <- lift $ ask stream_init <- return $ streamInit session_record -- session_window <- return $ sessionWindow session_record case anyframe_maybe of Just anyframe -> do headers_uncompressed <- lift $ uncompressFrameHeaders anyframe case headers_uncompressed of (AnyControl_AF control_frame) | iDropThisFrame control_frame -> do liftIO $ putStrLn $ "Frame dropped: " ++ (show control_frame) # # (AnyControl_AF (WindowUpdateFrame_ACF winupdate) ) -> do stream_id <- return $ streamIdFromFrame winupdate delta_bytes <- return $ deltaWindowSize winupdate liftIO $ putStrLn $ " Window update stream= " + + ( show ) + + " delta= " + + ( show delta_bytes ) liftIO $ putMVar flow_control_gate $ Right (stream_id, delta_bytes) continue -- We started here: sending ping requests.... often we also -- need to answer to them... (AnyControl_AF (PingFrame_ACF ping_frame)) -> do case handlePingFrame ping_frame of Just answer -> liftIO $ putMVar flow_control_gate $ Left $ wrapCF answer Nothing -> return () # # frame@(AnyControl_AF (SynStream_ACF syn_stream)) -> let stream_id = streamIdFromFrame syn_stream inputs = streamInputs session_record fin = do stream_inputs <- takeMVar inputs putMVar inputs $ MA.delete stream_id stream_inputs stream_create = do putStrLn $ "Opening stream " ++ (show stream_id) stream_inputs <- takeMVar inputs input_place <- newEmptyMVar stream_worker <- plugStream init_worker input_place flow_control_gate putMVar inputs $ MA.insert stream_id input_place stream_inputs forkIO $ stream_init stream_id fin $ stream_worker putMVar input_place frame in do liftIO stream_create # # ( AnyControl_AF (RstStreamFrame_ACF rst_stream) ) -> do stream_id <- return $ streamIdFromFrame rst_stream liftIO $ putStrLn $ "Reset stream " ++ (show stream_id) ++ " because: "++ (show $ getFrameResetReason rst_stream) lift $ deleteStream stream_id # # (AnyControl_AF (GoAwayFrame_ACF goaway)) -> do -- To test: the socket should be closed here liftIO $ putStrLn $ "GOAWAY (closing this sink) " ++ (show goaway) -- Don't continue here (AnyControl_AF (SettingsFrame_ACF settings)) -> do case SeF.getDefaultWindowSize settings of Just sz -> do liftIO $ putStrLn $ "Settings window size: " ++ (show sz) liftIO $ modifyMVar_ (initialWindowSize session_record) (\ _ -> return sz) Nothing -> return () # # frame -> do liftIO $ putStrLn $ "Dont't know how to handle ... " ++ (show frame) # # -- Come and recurse... Nothing -> return () -- So must one finish here... where continue = statefulSink init_worker flow_control_gate handlePingFrame :: PingFrame -> Maybe PingFrame handlePingFrame p@(PingFrame _ frame_id) | odd frame_id = Just p handlePingFrame _ = Nothing addBytesToStream :: Int -> Int -> SessionM IO () addBytesToStream stream_id bytecount = do stream_waits <- asks streamWaits if stream_id > 0 then do stream_window_info_maybe <- liftIO $ H.lookup stream_waits stream_id case stream_window_info_maybe of Nothing -> do -- The stream was possibly deleted before, do nothing... return () Just mvar -> do -- Modify it liftIO $ modifyMVar_ mvar $ \ (bytes, deq) -> return (bytes+bytecount, deq) else do -- Surely this refers to the entire thing session_window_mvar <- asks sessionWindow liftIO $ modifyMVar_ session_window_mvar (\ current_value -> return (current_value + bytecount)) initFlowControlOnStream :: Int -> SessionM IO () initFlowControlOnStream stream_id = do stream_waits <- asks streamWaits (window_bytes, queue) <- createStreamWindowInfo stream_id mvar <- liftIO $ newMVar (window_bytes , queue) liftIO $ H.insert stream_waits stream_id mvar createStreamWindowInfo :: Int -> SessionM IO (Int, WaitList) createStreamWindowInfo stream_id = do if odd stream_id then do initial_size_ioref <- asks initialWindowSize sz <- liftIO $ readMVar initial_size_ioref return (sz, D.empty) else do Working around bug on Firefox return (10000000, D.empty) flowControlAllowsFrame :: Int -> AnyFrame -> SessionM IO Bool flowControlAllowsFrame stream_id anyframe = do stream_waits <- asks streamWaits stream_info_mvar_maybe <- liftIO $ H.lookup stream_waits stream_id case stream_info_mvar_maybe of Just stream_info_mvar -> do (bytes_remaining, dq) <- liftIO $ takeMVar stream_info_mvar size_to_send <- return $ associatedLength anyframe available_in_session_mv <- asks sessionWindow available_in_session <- liftIO $ takeMVar available_in_session_mv liftIO $ putStrLn $ " Bytes remaining stream i d " + + ( show ) + + " " + + ( show bytes_remaining ) case ( ((D.length dq) == 0), ((bytes_remaining >= size_to_send) && (size_to_send <= available_in_session) ) ) of (True, True) -> do -- Empty dequeue, enough bytes liftIO $ do putMVar stream_info_mvar (bytes_remaining-size_to_send, dq) putMVar available_in_session_mv (available_in_session - size_to_send) return True _ -> do liftIO $ do putStrLn $ "FRAME of stream " ++ (show stream_id) ++ " DELAYED rem bytes: " ++ (show bytes_remaining) ++ " size_to_send: " ++ (show size_to_send) putMVar stream_info_mvar (bytes_remaining, (D.pushBack dq anyframe)) putMVar available_in_session_mv available_in_session return False Nothing -> -- Stream has been deleted return False flowControlCanPopFrame :: Int -> SessionM IO (Maybe AnyFrame) flowControlCanPopFrame stream_id = do session_record <- ask stream_waits <- asks streamWaits if stream_id > 0 then do stream_info_mvar_maybe <- liftIO $ H.lookup stream_waits stream_id case stream_info_mvar_maybe of Just stream_info_mvar -> do (bytes_remaining, dq) <- liftIO $ takeMVar stream_info_mvar (anyframe_maybe, newqueue) <- return $ D.popFront dq available_in_session_mv <- asks sessionWindow available_in_session <- liftIO $ takeMVar available_in_session_mv (result, newbytes, dq', new_available_in_session) <- case anyframe_maybe of Just anyframe -> if (sz <= bytes_remaining) && (sz <= available_in_session) then do liftIO $ putStrLn $ "Frame of " ++ (show stream_id) ++ " popped!" return ( (Just anyframe), bytes_remaining - sz, newqueue, available_in_session - sz) else do liftIO $ putStrLn $ "Impossible: stream_id= " ++ (show stream_id) ++ " stream bytes avail: " ++ (show bytes_remaining) ++ " session avail: " ++ (show available_in_session) return ( Nothing, bytes_remaining, dq, available_in_session) where sz = associatedLength anyframe Nothing -> return (Nothing, bytes_remaining, dq, available_in_session) liftIO $ do putMVar stream_info_mvar (newbytes, dq') putMVar available_in_session_mv new_available_in_session return result Nothing -> do return Nothing else do -- More complicated case of the session window, go through all the active streams liftIO $ H.foldM (\ p (stream_id', _) -> runReaderT (innerFold p stream_id') session_record) Nothing stream_waits where innerFold p stream_id' = do liftIO $ putStrLn $ " iter : " + + ( show ' ) case p of Just _ -> return p Nothing -> do anyframe_maybe <- flowControlCanPopFrame stream_id' case anyframe_maybe of Just _ -> do return anyframe_maybe Nothing -> do return Nothing -- This one sits on the output stream, checking to see if frames are allowed to leave flowControl :: MVar (Either AnyFrame (Int,Int) ) -- Input frames and window's -- updates come this way -> MVar AnyFrame -- Can output frames go this way -> SessionM IO () flowControl input output = do event <- liftIO $ takeMVar input case event of Left anyframe -> if frameIsFlowControlled anyframe then do stream_id <- return $ streamIdFromAnyFrame anyframe can_send <- flowControlAllowsFrame stream_id anyframe if can_send then do -- No need to wait liftIO $ putMVar output anyframe else do return () else do -- Not flow-controlled, this is most likely headers and synreplies -- generated here in the server, don't obstruct them liftIO $ putMVar output anyframe -- Some of the non-flow controlled frames create send windows when -- they go out, let's take care of that case anyframe of (AnyControl_AF (SynStream_ACF frame) ) -> initFlowControlOnStream $ streamIdFromFrame frame (AnyControl_AF (SynReplyFrame_ACF frame)) -> initFlowControlOnStream $ streamIdFromFrame frame _ -> return () Right (stream_id, window_delta_size) -> do liftIO $ putStrLn $ " Add to stream : " + + ( show ) -- So, I got some more room to send frames -- Notice that this may happen before this fragment ever observes -- a frame on that stream, so we need to be sure it exists... addBytesToStream stream_id window_delta_size sendFramesForStream stream_id output -- Tail-recursively invoke flowControl input output where sendFramesForStream stream_id output' = do popped_frame_maybe <- flowControlCanPopFrame stream_id case popped_frame_maybe of Just anyframe -> do liftIO $ putMVar output' anyframe sendFramesForStream stream_id output' Nothing -> return () associatedLength :: AnyFrame -> Int associatedLength (DataFrame_AF dataframe ) = B.length $ payload dataframe -- Here is where frames pop-up coming from the individual stream -- threads. So, the frames are serialized at this point and any -- incoming Key-value block compressed. This runs on the output -- thread. The parameter output_mvar is a gate that flow control -- uses to put frames which are ready for delivery... createTrivialSource :: MVar AnyFrame -> Source (SessionM IO) AnyFrame createTrivialSource output_mvar = do yield $ wrapCF initialSettings createTrivialSourceLoop :: Source (SessionM IO) AnyFrame where createTrivialSourceLoop = do anyframe_headerscompressed <- lift $ do anyframe <- liftIO $ takeMVar output_mvar compressFrameHeaders anyframe -- This is a good place to remove the entry from the table if -- this frame is the last one in the stream case frameEndsStream anyframe_headerscompressed of Just which_stream -> do liftIO $ putStrLn $ "Stream " ++ (show which_stream) ++ " closed naturally" lift $ deleteStream which_stream Nothing -> return () liftIO $ putStrLn $ "SENDING of: " ++ (show $ streamIdFromAnyFrame anyframe_headerscompressed) yield anyframe_headerscompressed createTrivialSourceLoop deleteStream :: Int -> SessionM IO () deleteStream stream_id = do stream_waits <- asks streamWaits liftIO $ H.delete stream_waits stream_id -- | Use to purge old streams from tables.... frameEndsStream :: AnyFrame -> Maybe Int frameEndsStream (DataFrame_AF dataframe) = if has_fin_flag then Just (streamIdFromFrame dataframe) else Nothing where has_fin_flag = getFrameFlag dataframe Fin_F frameEndsStream _ = Nothing frameIsFlowControlled :: AnyFrame -> Bool frameIsFlowControlled (DataFrame_AF _) = True frameIsFlowControlled _ = False compressFrameHeaders :: AnyFrame -> (SessionM IO) AnyFrame compressFrameHeaders ( AnyControl_AF (SynStream_ACF f)) = do new_frame <- justCompress f return $ wrapCF new_frame compressFrameHeaders ( AnyControl_AF (SynReplyFrame_ACF f )) = do new_frame <- justCompress f return $ wrapCF new_frame compressFrameHeaders ( AnyControl_AF (HeadersFrame_ACF f)) = do new_frame <- justCompress f return $ wrapCF new_frame compressFrameHeaders frame_without_headers = return frame_without_headers uncompressFrameHeaders :: AnyFrame -> (SessionM IO) AnyFrame uncompressFrameHeaders ( AnyControl_AF (SynStream_ACF f)) = do new_frame <- justDecompress f return $ wrapCF new_frame uncompressFrameHeaders ( AnyControl_AF (SynReplyFrame_ACF f )) = do new_frame <- justDecompress f return $ wrapCF new_frame uncompressFrameHeaders ( AnyControl_AF (HeadersFrame_ACF f)) = do new_frame <- justDecompress f return $ wrapCF new_frame uncompressFrameHeaders frame_without_headers = return frame_without_headers justCompress :: CompressedHeadersOnFrame f => f -> SessionM IO f justCompress frame = do send_zlib_mvar <- asks sendZLib case present_headers of UncompressedKeyValueBlock uncompressed_uvl -> do uncompressed_bytes <- return $ LB.toStrict $ runPut $ Bi.put $ uncompressed_uvl new_value <- liftIO $ do withMVar send_zlib_mvar $ \ send_zlib -> do popper <- Z.feedDeflate send_zlib uncompressed_bytes list_piece_1 <- exhaustPopper popper latest_piece <- exhaustPopper $ Z.flushDeflate send_zlib return $ CompressedKeyValueBlock $ B.concat (list_piece_1 ++ latest_piece) return $ setCompressedHeaders frame new_value CompressedKeyValueBlock _ -> error "This was not expected" where present_headers = getCompressedHeaders frame justDecompress :: CompressedHeadersOnFrame f => f -> SessionM IO f justDecompress frame = do recv_zlib_mvar <- asks recvZLib case present_headers of CompressedKeyValueBlock bscmp -> do uncompressed_bytes < - return $ LB.toStrict $ runPut $ Bi.put $ uncompressed_uvl new_value <- liftIO $ do withMVar recv_zlib_mvar $ \ recv_zlib -> do popper <- Z.feedInflate recv_zlib bscmp list_piece_1 <- exhaustPopper popper latest <- Z.flushInflate recv_zlib uncompressed_bytes <- return $ B.concat (list_piece_1 ++ [latest]) return $ UncompressedKeyValueBlock $ runGet Bi.get $ LB.fromChunks [uncompressed_bytes] return $ setCompressedHeaders frame new_value UncompressedKeyValueBlock _ -> error "This was not expected" where present_headers = getCompressedHeaders frame exhaustPopper :: Z.Popper -> IO [B.ByteString] exhaustPopper popper = do x <- popper case x of Z.PRDone -> return [] Z.PRNext bytestring -> do more <- exhaustPopper popper return $ (bytestring:more) Z.PRError e -> do -- When this happens, the only sensible -- thing to do is throw an exception, and trash the entire -- stream.... throwIO e zLibInitDict :: B.ByteString zLibInitDict = pack $ map toEnum [ 0x00, 0x00, 0x00, 0x07, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x00, 0x00, 0x00, 0x04, 0x68, 0x65, 0x61, 0x64, 0x00, 0x00, 0x00, 0x04, 0x70, 0x6f, 0x73, 0x74, 0x00, 0x00, 0x00, 0x03, 0x70, 0x75, 0x74, 0x00, 0x00, 0x00, 0x06, 0x64, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x00, 0x00, 0x00, 0x05, 0x74, 0x72, 0x61, 0x63, 0x65, 0x00, 0x00, 0x00, 0x06, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x00, 0x00, 0x00, 0x0e, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x00, 0x00, 0x00, 0x0f, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x0f, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x00, 0x00, 0x00, 0x0d, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x00, 0x00, 0x00, 0x03, 0x61, 0x67, 0x65, 0x00, 0x00, 0x00, 0x05, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x00, 0x00, 0x00, 0x0d, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x0d, 0x63, 0x61, 0x63, 0x68, 0x65, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x00, 0x00, 0x00, 0x0a, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x62, 0x61, 0x73, 0x65, 0x00, 0x00, 0x00, 0x10, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x10, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x00, 0x00, 0x00, 0x0e, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x00, 0x00, 0x00, 0x10, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x0b, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6d, 0x64, 0x35, 0x00, 0x00, 0x00, 0x0d, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x00, 0x00, 0x00, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x74, 0x79, 0x70, 0x65, 0x00, 0x00, 0x00, 0x04, 0x64, 0x61, 0x74, 0x65, 0x00, 0x00, 0x00, 0x04, 0x65, 0x74, 0x61, 0x67, 0x00, 0x00, 0x00, 0x06, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x00, 0x00, 0x00, 0x07, 0x65, 0x78, 0x70, 0x69, 0x72, 0x65, 0x73, 0x00, 0x00, 0x00, 0x04, 0x66, 0x72, 0x6f, 0x6d, 0x00, 0x00, 0x00, 0x04, 0x68, 0x6f, 0x73, 0x74, 0x00, 0x00, 0x00, 0x08, 0x69, 0x66, 0x2d, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x00, 0x00, 0x00, 0x11, 0x69, 0x66, 0x2d, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x2d, 0x73, 0x69, 0x6e, 0x63, 0x65, 0x00, 0x00, 0x00, 0x0d, 0x69, 0x66, 0x2d, 0x6e, 0x6f, 0x6e, 0x65, 0x2d, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x00, 0x00, 0x00, 0x08, 0x69, 0x66, 0x2d, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x00, 0x00, 0x00, 0x13, 0x69, 0x66, 0x2d, 0x75, 0x6e, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x2d, 0x73, 0x69, 0x6e, 0x63, 0x65, 0x00, 0x00, 0x00, 0x0d, 0x6c, 0x61, 0x73, 0x74, 0x2d, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x00, 0x00, 0x00, 0x08, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x0c, 0x6d, 0x61, 0x78, 0x2d, 0x66, 0x6f, 0x72, 0x77, 0x61, 0x72, 0x64, 0x73, 0x00, 0x00, 0x00, 0x06, 0x70, 0x72, 0x61, 0x67, 0x6d, 0x61, 0x00, 0x00, 0x00, 0x12, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2d, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x65, 0x00, 0x00, 0x00, 0x13, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2d, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x05, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x00, 0x00, 0x00, 0x07, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x72, 0x00, 0x00, 0x00, 0x0b, 0x72, 0x65, 0x74, 0x72, 0x79, 0x2d, 0x61, 0x66, 0x74, 0x65, 0x72, 0x00, 0x00, 0x00, 0x06, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x00, 0x00, 0x00, 0x02, 0x74, 0x65, 0x00, 0x00, 0x00, 0x07, 0x74, 0x72, 0x61, 0x69, 0x6c, 0x65, 0x72, 0x00, 0x00, 0x00, 0x11, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x2d, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x07, 0x75, 0x70, 0x67, 0x72, 0x61, 0x64, 0x65, 0x00, 0x00, 0x00, 0x0a, 0x75, 0x73, 0x65, 0x72, 0x2d, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x00, 0x00, 0x00, 0x04, 0x76, 0x61, 0x72, 0x79, 0x00, 0x00, 0x00, 0x03, 0x76, 0x69, 0x61, 0x00, 0x00, 0x00, 0x07, 0x77, 0x61, 0x72, 0x6e, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x10, 0x77, 0x77, 0x77, 0x2d, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x65, 0x00, 0x00, 0x00, 0x06, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x00, 0x00, 0x00, 0x03, 0x67, 0x65, 0x74, 0x00, 0x00, 0x00, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x00, 0x00, 0x00, 0x06, 0x32, 0x30, 0x30, 0x20, 0x4f, 0x4b, 0x00, 0x00, 0x00, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x08, 0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x03, 0x75, 0x72, 0x6c, 0x00, 0x00, 0x00, 0x06, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x00, 0x00, 0x00, 0x0a, 0x73, 0x65, 0x74, 0x2d, 0x63, 0x6f, 0x6f, 0x6b, 0x69, 0x65, 0x00, 0x00, 0x00, 0x0a, 0x6b, 0x65, 0x65, 0x70, 0x2d, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x00, 0x00, 0x00, 0x06, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x31, 0x30, 0x30, 0x31, 0x30, 0x31, 0x32, 0x30, 0x31, 0x32, 0x30, 0x32, 0x32, 0x30, 0x35, 0x32, 0x30, 0x36, 0x33, 0x30, 0x30, 0x33, 0x30, 0x32, 0x33, 0x30, 0x33, 0x33, 0x30, 0x34, 0x33, 0x30, 0x35, 0x33, 0x30, 0x36, 0x33, 0x30, 0x37, 0x34, 0x30, 0x32, 0x34, 0x30, 0x35, 0x34, 0x30, 0x36, 0x34, 0x30, 0x37, 0x34, 0x30, 0x38, 0x34, 0x30, 0x39, 0x34, 0x31, 0x30, 0x34, 0x31, 0x31, 0x34, 0x31, 0x32, 0x34, 0x31, 0x33, 0x34, 0x31, 0x34, 0x34, 0x31, 0x35, 0x34, 0x31, 0x36, 0x34, 0x31, 0x37, 0x35, 0x30, 0x32, 0x35, 0x30, 0x34, 0x35, 0x30, 0x35, 0x32, 0x30, 0x33, 0x20, 0x4e, 0x6f, 0x6e, 0x2d, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x49, 0x6e, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x32, 0x30, 0x34, 0x20, 0x4e, 0x6f, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x33, 0x30, 0x31, 0x20, 0x4d, 0x6f, 0x76, 0x65, 0x64, 0x20, 0x50, 0x65, 0x72, 0x6d, 0x61, 0x6e, 0x65, 0x6e, 0x74, 0x6c, 0x79, 0x34, 0x30, 0x30, 0x20, 0x42, 0x61, 0x64, 0x20, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x34, 0x30, 0x31, 0x20, 0x55, 0x6e, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x64, 0x34, 0x30, 0x33, 0x20, 0x46, 0x6f, 0x72, 0x62, 0x69, 0x64, 0x64, 0x65, 0x6e, 0x34, 0x30, 0x34, 0x20, 0x4e, 0x6f, 0x74, 0x20, 0x46, 0x6f, 0x75, 0x6e, 0x64, 0x35, 0x30, 0x30, 0x20, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x20, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x35, 0x30, 0x31, 0x20, 0x4e, 0x6f, 0x74, 0x20, 0x49, 0x6d, 0x70, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x65, 0x64, 0x35, 0x30, 0x33, 0x20, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x20, 0x55, 0x6e, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, 0x4a, 0x61, 0x6e, 0x20, 0x46, 0x65, 0x62, 0x20, 0x4d, 0x61, 0x72, 0x20, 0x41, 0x70, 0x72, 0x20, 0x4d, 0x61, 0x79, 0x20, 0x4a, 0x75, 0x6e, 0x20, 0x4a, 0x75, 0x6c, 0x20, 0x41, 0x75, 0x67, 0x20, 0x53, 0x65, 0x70, 0x74, 0x20, 0x4f, 0x63, 0x74, 0x20, 0x4e, 0x6f, 0x76, 0x20, 0x44, 0x65, 0x63, 0x20, 0x30, 0x30, 0x3a, 0x30, 0x30, 0x3a, 0x30, 0x30, 0x20, 0x4d, 0x6f, 0x6e, 0x2c, 0x20, 0x54, 0x75, 0x65, 0x2c, 0x20, 0x57, 0x65, 0x64, 0x2c, 0x20, 0x54, 0x68, 0x75, 0x2c, 0x20, 0x46, 0x72, 0x69, 0x2c, 0x20, 0x53, 0x61, 0x74, 0x2c, 0x20, 0x53, 0x75, 0x6e, 0x2c, 0x20, 0x47, 0x4d, 0x54, 0x63, 0x68, 0x75, 0x6e, 0x6b, 0x65, 0x64, 0x2c, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x68, 0x74, 0x6d, 0x6c, 0x2c, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x70, 0x6e, 0x67, 0x2c, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x6a, 0x70, 0x67, 0x2c, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x67, 0x69, 0x66, 0x2c, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x78, 0x6d, 0x6c, 0x2c, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x78, 0x68, 0x74, 0x6d, 0x6c, 0x2b, 0x78, 0x6d, 0x6c, 0x2c, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x70, 0x6c, 0x61, 0x69, 0x6e, 0x2c, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x6a, 0x61, 0x76, 0x61, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x2c, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x6d, 0x61, 0x78, 0x2d, 0x61, 0x67, 0x65, 0x3d, 0x67, 0x7a, 0x69, 0x70, 0x2c, 0x64, 0x65, 0x66, 0x6c, 0x61, 0x74, 0x65, 0x2c, 0x73, 0x64, 0x63, 0x68, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x3d, 0x75, 0x74, 0x66, 0x2d, 0x38, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x3d, 0x69, 0x73, 0x6f, 0x2d, 0x38, 0x38, 0x35, 0x39, 0x2d, 0x31, 0x2c, 0x75, 0x74, 0x66, 0x2d, 0x2c, 0x2a, 0x2c, 0x65, 0x6e, 0x71, 0x3d, 0x30, 0x2e ]
null
https://raw.githubusercontent.com/li-clutter-org/http2-test/38d6706511f93af875273f7702fa0ea8582d5d8e/hs-src/Rede/SpdyProtocol/Session.hs
haskell
trivialSession ,showHeadersIfPresent import Data.IORef import Data.Conduit.Lift (distribute) TODO: Move to constants? goAwayMsg = GoA.GoAwayFrame { GoA.prologue = def ,GoA.statusCode = GoA.OK_GAR ,GoA.lastGoodStream = 0 } A table from stream id to windows reamining list and waiting list Need also a way to do frame-flow control | Super-simple session manager without flow control and such.... but using StreamWorkers already.... TODO: without proper flow control, we are in troubles.... Create the input record.... Whatever is put here makes it to the socket, so this should go after flow control TODO: Fix this hoister <- return $ (\ x -> runReaderT x session_record :: SessionM IO a -> IO a) This is the end of the pipeline which is closest to the TCP socket in the input direction We will need to run flow control This is the end of the pipeline that is closest to the TCP socket in the output direction liftIO $ putStrLn "Got something" ATTENTION: potential session race-condition here. | Takes output from the stream conduit and puts it on the output mvar. This runs in the stream thread. ATTENTION: When a stream finishes, the conduit closes and yields a Nothing to signal that The stream is alive The stream wishes to finish, in this case, call a provided finalizer Now let natural finalization of the conduit to take place... IMPLEMENT: iDropThisFrame (Ping_CFT) iDropThisFrame (WindowUpdateFrame_ACF _ ) = True | Takes a stream worker constructor and properly sets its connections so that it can take and place data in the multi-threaded pipeline. ^ When needed, create a new stream worker here. ^ All outputs of this session should be placed here (This should go to ) session_window <- return $ sessionWindow session_record We started here: sending ping requests.... often we also need to answer to them... To test: the socket should be closed here Don't continue here Come and recurse... So must one finish here... The stream was possibly deleted before, do nothing... Modify it Surely this refers to the entire thing Empty dequeue, enough bytes Stream has been deleted More complicated case of the session window, go through all the active streams This one sits on the output stream, checking to see if frames are allowed to leave Input frames and window's updates come this way Can output frames go this way No need to wait Not flow-controlled, this is most likely headers and synreplies generated here in the server, don't obstruct them Some of the non-flow controlled frames create send windows when they go out, let's take care of that So, I got some more room to send frames Notice that this may happen before this fragment ever observes a frame on that stream, so we need to be sure it exists... Tail-recursively invoke Here is where frames pop-up coming from the individual stream threads. So, the frames are serialized at this point and any incoming Key-value block compressed. This runs on the output thread. The parameter output_mvar is a gate that flow control uses to put frames which are ready for delivery... This is a good place to remove the entry from the table if this frame is the last one in the stream | Use to purge old streams from tables.... When this happens, the only sensible thing to do is throw an exception, and trash the entire stream....
# LANGUAGE FlexibleContexts , Rank2Types # module Rede.SpdyProtocol.Session( basicSession ) where import Control.Concurrent (forkIO) import Control.Monad.IO.Class (liftIO) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Reader import Control.Exception(throwIO) import Data.Conduit import qualified Data.Streaming.Zlib as Z import qualified Data . Conduit . List as CL import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as LB import Data.ByteString.Char8 (pack) import Data.Default (def) import Control.Concurrent.MVar import qualified Data.Map as MA import Data.Binary.Put (runPut) import qualified Data.Binary as Bi import Data.Binary.Get (runGet) import qualified Data.HashTable.IO as H import qualified Data.Dequeue as D import Rede.SpdyProtocol.Framing.AnyFrame import Rede.SpdyProtocol.Framing.Frame import Rede.SpdyProtocol.Framing.Ping import Rede.SpdyProtocol.Framing.DataFrame import Rede.SpdyProtocol.Framing.RstStream import Rede.SpdyProtocol.Framing.WindowUpdate import Rede.MainLoop.StreamPlug import Rede.SpdyProtocol.Framing.KeyValueBlock import qualified Rede.SpdyProtocol.Framing.Settings as SeF import Rede.SpdyProtocol.Streams.State import Rede.MainLoop.Tokens initialSettings :: SeF.SettingsFrame initialSettings = SeF.SettingsFrame { SeF.prologue = def ,SeF.persistSettings = [ (SeF.InitialWindowSize_S, 65536, SeF.None_PS) ] } goAwayMsg : : type WaitList = D.BankersDequeue AnyFrame type StreamWindowInfo = MVar (Int, WaitList) type StreamWaits = H.BasicHashTable Int StreamWindowInfo data SimpleSessionStateRecord = SimpleSessionStateRecord { streamInputs :: MVar (MA.Map Int (MVar AnyFrame)) , streamsOutput : : MVar ( Maybe AnyFrame ) ,sendZLib :: MVar Z.Deflate ,recvZLib :: MVar Z.Inflate ,streamInit :: Int -> IO () -> StreamStateT IO () -> IO () ,streamWaits :: StreamWaits ,initialWindowSize :: MVar Int ,sessionWindow :: MVar Int } type SessionM = ReaderT SimpleSessionStateRecord basicSession :: (StreamWorkerClass serviceParams servicePocket sessionPocket) => servicePocket -> IO ( (Sink AnyFrame IO () ), (Source IO AnyFrame ) ) basicSession worker_service_pocket = do stream_inputs <- newMVar $ MA.empty session_gate <- (newEmptyMVar :: IO (MVar AnyFrame) ) send_zlib <- Z.initDeflateWithDictionary 2 zLibInitDict Z.defaultWindowBits send_zlib_mvar <- newMVar send_zlib recv_zlib <- Z.initInflateWithDictionary Z.defaultWindowBits zLibInitDict recv_zlib_mvar <- newMVar recv_zlib worker_session_pocket <- initSession worker_service_pocket Preserve the IO wrapper make_worker <- return $ initStream worker_service_pocket worker_session_pocket Stream ids pushed from the server start at two stream_waits <- H.new initial_window_size <- newMVar 65536 session_window <- newMVar 65536 session_record <- return $ SimpleSessionStateRecord { streamInputs = stream_inputs ,sendZLib = send_zlib_mvar ,recvZLib = recv_zlib_mvar ,streamInit = \ stream_id fin -> initStreamState stream_id fin next_stream_id ,streamWaits = stream_waits ,initialWindowSize = initial_window_size ,sessionWindow = session_window } flow_control_gate <- liftIO $ newEmptyMVar The " flow_control_gate " variable here is given to newly created streams , it is also used directly by the sink to process WindowUpdate frames ... packet_sink <- return $ transPipe ( \ x -> runReaderT x session_record) (statefulSink make_worker flow_control_gate) liftIO $ forkIO $ runReaderT (flowControl flow_control_gate session_gate) session_record packet_source <- return $ transPipe (\ x -> runReaderT x session_record) (createTrivialSource session_gate) return (packet_sink, packet_source) takesInput :: MVar AnyFrame -> Source (StreamStateT IO) AnyFrame takesInput input_mvar = do frame <- liftIO $ takeMVar input_mvar yield frame takesInput input_mvar plugStream :: IO StreamWorker -> MVar AnyFrame -> MVar (Either AnyFrame (Int,Int) ) -> IO ( StreamStateT IO () ) plugStream workerStart input_mvar drop_output_here_mvar = do worker <- workerStart return (( (takesInput input_mvar) $= inputPlug =$= (transPipe liftIO (worker::StreamWorker)) =$= (outputPlug :: Conduit StreamOutputAction (StreamStateT IO) AnyFrame) $$ (streamOutput drop_output_here_mvar) )) streamOutput :: MVar (Either AnyFrame (Int,Int) ) -> Sink AnyFrame (StreamStateT IO) () streamOutput output_mvar = do any_frame_maybe <- await case any_frame_maybe of Just anyframe -> do liftIO $ putMVar output_mvar $ Left anyframe streamOutput output_mvar do n't put anything in the output MVar , but Nothing -> do lift streamFinalize iDropThisFrame :: AnyControlFrame -> Bool iDropThisFrame ( SettingsFrame_ACF _ ) = True iDropThisFrame _ = False statefulSink :: -> Sink AnyFrame (SessionM IO) () statefulSink init_worker flow_control_gate = do anyframe_maybe <- await session_record <- lift $ ask stream_init <- return $ streamInit session_record case anyframe_maybe of Just anyframe -> do headers_uncompressed <- lift $ uncompressFrameHeaders anyframe case headers_uncompressed of (AnyControl_AF control_frame) | iDropThisFrame control_frame -> do liftIO $ putStrLn $ "Frame dropped: " ++ (show control_frame) # # (AnyControl_AF (WindowUpdateFrame_ACF winupdate) ) -> do stream_id <- return $ streamIdFromFrame winupdate delta_bytes <- return $ deltaWindowSize winupdate liftIO $ putStrLn $ " Window update stream= " + + ( show ) + + " delta= " + + ( show delta_bytes ) liftIO $ putMVar flow_control_gate $ Right (stream_id, delta_bytes) continue (AnyControl_AF (PingFrame_ACF ping_frame)) -> do case handlePingFrame ping_frame of Just answer -> liftIO $ putMVar flow_control_gate $ Left $ wrapCF answer Nothing -> return () # # frame@(AnyControl_AF (SynStream_ACF syn_stream)) -> let stream_id = streamIdFromFrame syn_stream inputs = streamInputs session_record fin = do stream_inputs <- takeMVar inputs putMVar inputs $ MA.delete stream_id stream_inputs stream_create = do putStrLn $ "Opening stream " ++ (show stream_id) stream_inputs <- takeMVar inputs input_place <- newEmptyMVar stream_worker <- plugStream init_worker input_place flow_control_gate putMVar inputs $ MA.insert stream_id input_place stream_inputs forkIO $ stream_init stream_id fin $ stream_worker putMVar input_place frame in do liftIO stream_create # # ( AnyControl_AF (RstStreamFrame_ACF rst_stream) ) -> do stream_id <- return $ streamIdFromFrame rst_stream liftIO $ putStrLn $ "Reset stream " ++ (show stream_id) ++ " because: "++ (show $ getFrameResetReason rst_stream) lift $ deleteStream stream_id # # (AnyControl_AF (GoAwayFrame_ACF goaway)) -> do liftIO $ putStrLn $ "GOAWAY (closing this sink) " ++ (show goaway) (AnyControl_AF (SettingsFrame_ACF settings)) -> do case SeF.getDefaultWindowSize settings of Just sz -> do liftIO $ putStrLn $ "Settings window size: " ++ (show sz) liftIO $ modifyMVar_ (initialWindowSize session_record) (\ _ -> return sz) Nothing -> return () # # frame -> do liftIO $ putStrLn $ "Dont't know how to handle ... " ++ (show frame) # # where continue = statefulSink init_worker flow_control_gate handlePingFrame :: PingFrame -> Maybe PingFrame handlePingFrame p@(PingFrame _ frame_id) | odd frame_id = Just p handlePingFrame _ = Nothing addBytesToStream :: Int -> Int -> SessionM IO () addBytesToStream stream_id bytecount = do stream_waits <- asks streamWaits if stream_id > 0 then do stream_window_info_maybe <- liftIO $ H.lookup stream_waits stream_id case stream_window_info_maybe of Nothing -> do return () Just mvar -> do liftIO $ modifyMVar_ mvar $ \ (bytes, deq) -> return (bytes+bytecount, deq) else do session_window_mvar <- asks sessionWindow liftIO $ modifyMVar_ session_window_mvar (\ current_value -> return (current_value + bytecount)) initFlowControlOnStream :: Int -> SessionM IO () initFlowControlOnStream stream_id = do stream_waits <- asks streamWaits (window_bytes, queue) <- createStreamWindowInfo stream_id mvar <- liftIO $ newMVar (window_bytes , queue) liftIO $ H.insert stream_waits stream_id mvar createStreamWindowInfo :: Int -> SessionM IO (Int, WaitList) createStreamWindowInfo stream_id = do if odd stream_id then do initial_size_ioref <- asks initialWindowSize sz <- liftIO $ readMVar initial_size_ioref return (sz, D.empty) else do Working around bug on Firefox return (10000000, D.empty) flowControlAllowsFrame :: Int -> AnyFrame -> SessionM IO Bool flowControlAllowsFrame stream_id anyframe = do stream_waits <- asks streamWaits stream_info_mvar_maybe <- liftIO $ H.lookup stream_waits stream_id case stream_info_mvar_maybe of Just stream_info_mvar -> do (bytes_remaining, dq) <- liftIO $ takeMVar stream_info_mvar size_to_send <- return $ associatedLength anyframe available_in_session_mv <- asks sessionWindow available_in_session <- liftIO $ takeMVar available_in_session_mv liftIO $ putStrLn $ " Bytes remaining stream i d " + + ( show ) + + " " + + ( show bytes_remaining ) case ( ((D.length dq) == 0), ((bytes_remaining >= size_to_send) && (size_to_send <= available_in_session) ) ) of (True, True) -> do liftIO $ do putMVar stream_info_mvar (bytes_remaining-size_to_send, dq) putMVar available_in_session_mv (available_in_session - size_to_send) return True _ -> do liftIO $ do putStrLn $ "FRAME of stream " ++ (show stream_id) ++ " DELAYED rem bytes: " ++ (show bytes_remaining) ++ " size_to_send: " ++ (show size_to_send) putMVar stream_info_mvar (bytes_remaining, (D.pushBack dq anyframe)) putMVar available_in_session_mv available_in_session return False Nothing -> return False flowControlCanPopFrame :: Int -> SessionM IO (Maybe AnyFrame) flowControlCanPopFrame stream_id = do session_record <- ask stream_waits <- asks streamWaits if stream_id > 0 then do stream_info_mvar_maybe <- liftIO $ H.lookup stream_waits stream_id case stream_info_mvar_maybe of Just stream_info_mvar -> do (bytes_remaining, dq) <- liftIO $ takeMVar stream_info_mvar (anyframe_maybe, newqueue) <- return $ D.popFront dq available_in_session_mv <- asks sessionWindow available_in_session <- liftIO $ takeMVar available_in_session_mv (result, newbytes, dq', new_available_in_session) <- case anyframe_maybe of Just anyframe -> if (sz <= bytes_remaining) && (sz <= available_in_session) then do liftIO $ putStrLn $ "Frame of " ++ (show stream_id) ++ " popped!" return ( (Just anyframe), bytes_remaining - sz, newqueue, available_in_session - sz) else do liftIO $ putStrLn $ "Impossible: stream_id= " ++ (show stream_id) ++ " stream bytes avail: " ++ (show bytes_remaining) ++ " session avail: " ++ (show available_in_session) return ( Nothing, bytes_remaining, dq, available_in_session) where sz = associatedLength anyframe Nothing -> return (Nothing, bytes_remaining, dq, available_in_session) liftIO $ do putMVar stream_info_mvar (newbytes, dq') putMVar available_in_session_mv new_available_in_session return result Nothing -> do return Nothing else do liftIO $ H.foldM (\ p (stream_id', _) -> runReaderT (innerFold p stream_id') session_record) Nothing stream_waits where innerFold p stream_id' = do liftIO $ putStrLn $ " iter : " + + ( show ' ) case p of Just _ -> return p Nothing -> do anyframe_maybe <- flowControlCanPopFrame stream_id' case anyframe_maybe of Just _ -> do return anyframe_maybe Nothing -> do return Nothing flowControl -> SessionM IO () flowControl input output = do event <- liftIO $ takeMVar input case event of Left anyframe -> if frameIsFlowControlled anyframe then do stream_id <- return $ streamIdFromAnyFrame anyframe can_send <- flowControlAllowsFrame stream_id anyframe if can_send then do liftIO $ putMVar output anyframe else do return () else do liftIO $ putMVar output anyframe case anyframe of (AnyControl_AF (SynStream_ACF frame) ) -> initFlowControlOnStream $ streamIdFromFrame frame (AnyControl_AF (SynReplyFrame_ACF frame)) -> initFlowControlOnStream $ streamIdFromFrame frame _ -> return () Right (stream_id, window_delta_size) -> do liftIO $ putStrLn $ " Add to stream : " + + ( show ) addBytesToStream stream_id window_delta_size sendFramesForStream stream_id output flowControl input output where sendFramesForStream stream_id output' = do popped_frame_maybe <- flowControlCanPopFrame stream_id case popped_frame_maybe of Just anyframe -> do liftIO $ putMVar output' anyframe sendFramesForStream stream_id output' Nothing -> return () associatedLength :: AnyFrame -> Int associatedLength (DataFrame_AF dataframe ) = B.length $ payload dataframe createTrivialSource :: MVar AnyFrame -> Source (SessionM IO) AnyFrame createTrivialSource output_mvar = do yield $ wrapCF initialSettings createTrivialSourceLoop :: Source (SessionM IO) AnyFrame where createTrivialSourceLoop = do anyframe_headerscompressed <- lift $ do anyframe <- liftIO $ takeMVar output_mvar compressFrameHeaders anyframe case frameEndsStream anyframe_headerscompressed of Just which_stream -> do liftIO $ putStrLn $ "Stream " ++ (show which_stream) ++ " closed naturally" lift $ deleteStream which_stream Nothing -> return () liftIO $ putStrLn $ "SENDING of: " ++ (show $ streamIdFromAnyFrame anyframe_headerscompressed) yield anyframe_headerscompressed createTrivialSourceLoop deleteStream :: Int -> SessionM IO () deleteStream stream_id = do stream_waits <- asks streamWaits liftIO $ H.delete stream_waits stream_id frameEndsStream :: AnyFrame -> Maybe Int frameEndsStream (DataFrame_AF dataframe) = if has_fin_flag then Just (streamIdFromFrame dataframe) else Nothing where has_fin_flag = getFrameFlag dataframe Fin_F frameEndsStream _ = Nothing frameIsFlowControlled :: AnyFrame -> Bool frameIsFlowControlled (DataFrame_AF _) = True frameIsFlowControlled _ = False compressFrameHeaders :: AnyFrame -> (SessionM IO) AnyFrame compressFrameHeaders ( AnyControl_AF (SynStream_ACF f)) = do new_frame <- justCompress f return $ wrapCF new_frame compressFrameHeaders ( AnyControl_AF (SynReplyFrame_ACF f )) = do new_frame <- justCompress f return $ wrapCF new_frame compressFrameHeaders ( AnyControl_AF (HeadersFrame_ACF f)) = do new_frame <- justCompress f return $ wrapCF new_frame compressFrameHeaders frame_without_headers = return frame_without_headers uncompressFrameHeaders :: AnyFrame -> (SessionM IO) AnyFrame uncompressFrameHeaders ( AnyControl_AF (SynStream_ACF f)) = do new_frame <- justDecompress f return $ wrapCF new_frame uncompressFrameHeaders ( AnyControl_AF (SynReplyFrame_ACF f )) = do new_frame <- justDecompress f return $ wrapCF new_frame uncompressFrameHeaders ( AnyControl_AF (HeadersFrame_ACF f)) = do new_frame <- justDecompress f return $ wrapCF new_frame uncompressFrameHeaders frame_without_headers = return frame_without_headers justCompress :: CompressedHeadersOnFrame f => f -> SessionM IO f justCompress frame = do send_zlib_mvar <- asks sendZLib case present_headers of UncompressedKeyValueBlock uncompressed_uvl -> do uncompressed_bytes <- return $ LB.toStrict $ runPut $ Bi.put $ uncompressed_uvl new_value <- liftIO $ do withMVar send_zlib_mvar $ \ send_zlib -> do popper <- Z.feedDeflate send_zlib uncompressed_bytes list_piece_1 <- exhaustPopper popper latest_piece <- exhaustPopper $ Z.flushDeflate send_zlib return $ CompressedKeyValueBlock $ B.concat (list_piece_1 ++ latest_piece) return $ setCompressedHeaders frame new_value CompressedKeyValueBlock _ -> error "This was not expected" where present_headers = getCompressedHeaders frame justDecompress :: CompressedHeadersOnFrame f => f -> SessionM IO f justDecompress frame = do recv_zlib_mvar <- asks recvZLib case present_headers of CompressedKeyValueBlock bscmp -> do uncompressed_bytes < - return $ LB.toStrict $ runPut $ Bi.put $ uncompressed_uvl new_value <- liftIO $ do withMVar recv_zlib_mvar $ \ recv_zlib -> do popper <- Z.feedInflate recv_zlib bscmp list_piece_1 <- exhaustPopper popper latest <- Z.flushInflate recv_zlib uncompressed_bytes <- return $ B.concat (list_piece_1 ++ [latest]) return $ UncompressedKeyValueBlock $ runGet Bi.get $ LB.fromChunks [uncompressed_bytes] return $ setCompressedHeaders frame new_value UncompressedKeyValueBlock _ -> error "This was not expected" where present_headers = getCompressedHeaders frame exhaustPopper :: Z.Popper -> IO [B.ByteString] exhaustPopper popper = do x <- popper case x of Z.PRDone -> return [] Z.PRNext bytestring -> do more <- exhaustPopper popper return $ (bytestring:more) Z.PRError e -> do throwIO e zLibInitDict :: B.ByteString zLibInitDict = pack $ map toEnum [ 0x00, 0x00, 0x00, 0x07, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x00, 0x00, 0x00, 0x04, 0x68, 0x65, 0x61, 0x64, 0x00, 0x00, 0x00, 0x04, 0x70, 0x6f, 0x73, 0x74, 0x00, 0x00, 0x00, 0x03, 0x70, 0x75, 0x74, 0x00, 0x00, 0x00, 0x06, 0x64, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x00, 0x00, 0x00, 0x05, 0x74, 0x72, 0x61, 0x63, 0x65, 0x00, 0x00, 0x00, 0x06, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x00, 0x00, 0x00, 0x0e, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x00, 0x00, 0x00, 0x0f, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x0f, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x00, 0x00, 0x00, 0x0d, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x00, 0x00, 0x00, 0x03, 0x61, 0x67, 0x65, 0x00, 0x00, 0x00, 0x05, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x00, 0x00, 0x00, 0x0d, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x0d, 0x63, 0x61, 0x63, 0x68, 0x65, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x00, 0x00, 0x00, 0x0a, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x62, 0x61, 0x73, 0x65, 0x00, 0x00, 0x00, 0x10, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x10, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x00, 0x00, 0x00, 0x0e, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x00, 0x00, 0x00, 0x10, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x0b, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6d, 0x64, 0x35, 0x00, 0x00, 0x00, 0x0d, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x00, 0x00, 0x00, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x74, 0x79, 0x70, 0x65, 0x00, 0x00, 0x00, 0x04, 0x64, 0x61, 0x74, 0x65, 0x00, 0x00, 0x00, 0x04, 0x65, 0x74, 0x61, 0x67, 0x00, 0x00, 0x00, 0x06, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x00, 0x00, 0x00, 0x07, 0x65, 0x78, 0x70, 0x69, 0x72, 0x65, 0x73, 0x00, 0x00, 0x00, 0x04, 0x66, 0x72, 0x6f, 0x6d, 0x00, 0x00, 0x00, 0x04, 0x68, 0x6f, 0x73, 0x74, 0x00, 0x00, 0x00, 0x08, 0x69, 0x66, 0x2d, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x00, 0x00, 0x00, 0x11, 0x69, 0x66, 0x2d, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x2d, 0x73, 0x69, 0x6e, 0x63, 0x65, 0x00, 0x00, 0x00, 0x0d, 0x69, 0x66, 0x2d, 0x6e, 0x6f, 0x6e, 0x65, 0x2d, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x00, 0x00, 0x00, 0x08, 0x69, 0x66, 0x2d, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x00, 0x00, 0x00, 0x13, 0x69, 0x66, 0x2d, 0x75, 0x6e, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x2d, 0x73, 0x69, 0x6e, 0x63, 0x65, 0x00, 0x00, 0x00, 0x0d, 0x6c, 0x61, 0x73, 0x74, 0x2d, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x00, 0x00, 0x00, 0x08, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x0c, 0x6d, 0x61, 0x78, 0x2d, 0x66, 0x6f, 0x72, 0x77, 0x61, 0x72, 0x64, 0x73, 0x00, 0x00, 0x00, 0x06, 0x70, 0x72, 0x61, 0x67, 0x6d, 0x61, 0x00, 0x00, 0x00, 0x12, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2d, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x65, 0x00, 0x00, 0x00, 0x13, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x2d, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x05, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x00, 0x00, 0x00, 0x07, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x72, 0x00, 0x00, 0x00, 0x0b, 0x72, 0x65, 0x74, 0x72, 0x79, 0x2d, 0x61, 0x66, 0x74, 0x65, 0x72, 0x00, 0x00, 0x00, 0x06, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x00, 0x00, 0x00, 0x02, 0x74, 0x65, 0x00, 0x00, 0x00, 0x07, 0x74, 0x72, 0x61, 0x69, 0x6c, 0x65, 0x72, 0x00, 0x00, 0x00, 0x11, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x65, 0x72, 0x2d, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x07, 0x75, 0x70, 0x67, 0x72, 0x61, 0x64, 0x65, 0x00, 0x00, 0x00, 0x0a, 0x75, 0x73, 0x65, 0x72, 0x2d, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x00, 0x00, 0x00, 0x04, 0x76, 0x61, 0x72, 0x79, 0x00, 0x00, 0x00, 0x03, 0x76, 0x69, 0x61, 0x00, 0x00, 0x00, 0x07, 0x77, 0x61, 0x72, 0x6e, 0x69, 0x6e, 0x67, 0x00, 0x00, 0x00, 0x10, 0x77, 0x77, 0x77, 0x2d, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x65, 0x00, 0x00, 0x00, 0x06, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x00, 0x00, 0x00, 0x03, 0x67, 0x65, 0x74, 0x00, 0x00, 0x00, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x00, 0x00, 0x00, 0x06, 0x32, 0x30, 0x30, 0x20, 0x4f, 0x4b, 0x00, 0x00, 0x00, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x08, 0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x03, 0x75, 0x72, 0x6c, 0x00, 0x00, 0x00, 0x06, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x00, 0x00, 0x00, 0x0a, 0x73, 0x65, 0x74, 0x2d, 0x63, 0x6f, 0x6f, 0x6b, 0x69, 0x65, 0x00, 0x00, 0x00, 0x0a, 0x6b, 0x65, 0x65, 0x70, 0x2d, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x00, 0x00, 0x00, 0x06, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x31, 0x30, 0x30, 0x31, 0x30, 0x31, 0x32, 0x30, 0x31, 0x32, 0x30, 0x32, 0x32, 0x30, 0x35, 0x32, 0x30, 0x36, 0x33, 0x30, 0x30, 0x33, 0x30, 0x32, 0x33, 0x30, 0x33, 0x33, 0x30, 0x34, 0x33, 0x30, 0x35, 0x33, 0x30, 0x36, 0x33, 0x30, 0x37, 0x34, 0x30, 0x32, 0x34, 0x30, 0x35, 0x34, 0x30, 0x36, 0x34, 0x30, 0x37, 0x34, 0x30, 0x38, 0x34, 0x30, 0x39, 0x34, 0x31, 0x30, 0x34, 0x31, 0x31, 0x34, 0x31, 0x32, 0x34, 0x31, 0x33, 0x34, 0x31, 0x34, 0x34, 0x31, 0x35, 0x34, 0x31, 0x36, 0x34, 0x31, 0x37, 0x35, 0x30, 0x32, 0x35, 0x30, 0x34, 0x35, 0x30, 0x35, 0x32, 0x30, 0x33, 0x20, 0x4e, 0x6f, 0x6e, 0x2d, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x49, 0x6e, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x32, 0x30, 0x34, 0x20, 0x4e, 0x6f, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x33, 0x30, 0x31, 0x20, 0x4d, 0x6f, 0x76, 0x65, 0x64, 0x20, 0x50, 0x65, 0x72, 0x6d, 0x61, 0x6e, 0x65, 0x6e, 0x74, 0x6c, 0x79, 0x34, 0x30, 0x30, 0x20, 0x42, 0x61, 0x64, 0x20, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x34, 0x30, 0x31, 0x20, 0x55, 0x6e, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x65, 0x64, 0x34, 0x30, 0x33, 0x20, 0x46, 0x6f, 0x72, 0x62, 0x69, 0x64, 0x64, 0x65, 0x6e, 0x34, 0x30, 0x34, 0x20, 0x4e, 0x6f, 0x74, 0x20, 0x46, 0x6f, 0x75, 0x6e, 0x64, 0x35, 0x30, 0x30, 0x20, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x20, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x35, 0x30, 0x31, 0x20, 0x4e, 0x6f, 0x74, 0x20, 0x49, 0x6d, 0x70, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x65, 0x64, 0x35, 0x30, 0x33, 0x20, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x20, 0x55, 0x6e, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, 0x4a, 0x61, 0x6e, 0x20, 0x46, 0x65, 0x62, 0x20, 0x4d, 0x61, 0x72, 0x20, 0x41, 0x70, 0x72, 0x20, 0x4d, 0x61, 0x79, 0x20, 0x4a, 0x75, 0x6e, 0x20, 0x4a, 0x75, 0x6c, 0x20, 0x41, 0x75, 0x67, 0x20, 0x53, 0x65, 0x70, 0x74, 0x20, 0x4f, 0x63, 0x74, 0x20, 0x4e, 0x6f, 0x76, 0x20, 0x44, 0x65, 0x63, 0x20, 0x30, 0x30, 0x3a, 0x30, 0x30, 0x3a, 0x30, 0x30, 0x20, 0x4d, 0x6f, 0x6e, 0x2c, 0x20, 0x54, 0x75, 0x65, 0x2c, 0x20, 0x57, 0x65, 0x64, 0x2c, 0x20, 0x54, 0x68, 0x75, 0x2c, 0x20, 0x46, 0x72, 0x69, 0x2c, 0x20, 0x53, 0x61, 0x74, 0x2c, 0x20, 0x53, 0x75, 0x6e, 0x2c, 0x20, 0x47, 0x4d, 0x54, 0x63, 0x68, 0x75, 0x6e, 0x6b, 0x65, 0x64, 0x2c, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x68, 0x74, 0x6d, 0x6c, 0x2c, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x70, 0x6e, 0x67, 0x2c, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x6a, 0x70, 0x67, 0x2c, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x67, 0x69, 0x66, 0x2c, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x78, 0x6d, 0x6c, 0x2c, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x78, 0x68, 0x74, 0x6d, 0x6c, 0x2b, 0x78, 0x6d, 0x6c, 0x2c, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x70, 0x6c, 0x61, 0x69, 0x6e, 0x2c, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x6a, 0x61, 0x76, 0x61, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x2c, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x6d, 0x61, 0x78, 0x2d, 0x61, 0x67, 0x65, 0x3d, 0x67, 0x7a, 0x69, 0x70, 0x2c, 0x64, 0x65, 0x66, 0x6c, 0x61, 0x74, 0x65, 0x2c, 0x73, 0x64, 0x63, 0x68, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x3d, 0x75, 0x74, 0x66, 0x2d, 0x38, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x3d, 0x69, 0x73, 0x6f, 0x2d, 0x38, 0x38, 0x35, 0x39, 0x2d, 0x31, 0x2c, 0x75, 0x74, 0x66, 0x2d, 0x2c, 0x2a, 0x2c, 0x65, 0x6e, 0x71, 0x3d, 0x30, 0x2e ]
cd8872ca79dd4d01946b3b3cfd1be5a313f1cd50352ed3789611d22c6417b4ae
mattgreen/hython
AttributeDict.hs
module Hython.AttributeDict where import Control.Monad.IO.Class (MonadIO) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap import Data.Text (Text) import Hython.Ref type AttributeDict obj = HashMap Text (Ref obj) empty :: AttributeDict obj empty = HashMap.empty insertRef :: Text -> Ref obj -> AttributeDict obj -> AttributeDict obj insertRef = HashMap.insert lookup :: (MonadIO m) => Text -> AttributeDict obj -> m (Maybe obj) lookup attr dict = case lookupRef attr dict of Just ref -> Just <$> readRef ref Nothing -> return Nothing lookupRef :: Text -> AttributeDict obj -> Maybe (Ref obj) lookupRef = HashMap.lookup fromList :: [(Text, Ref obj)] -> AttributeDict obj fromList = HashMap.fromList new :: AttributeDict obj new = HashMap.empty set :: (MonadIO m) => Text -> obj -> AttributeDict obj -> m (AttributeDict obj) set attr obj dict = case HashMap.lookup attr dict of Just ref -> do writeRef ref obj return dict Nothing -> do ref <- newRef obj return $ HashMap.insert attr ref dict
null
https://raw.githubusercontent.com/mattgreen/hython/fcbde98e9b5a033f0d4bea73ac9914bc5e12b746/src/Hython/AttributeDict.hs
haskell
module Hython.AttributeDict where import Control.Monad.IO.Class (MonadIO) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap import Data.Text (Text) import Hython.Ref type AttributeDict obj = HashMap Text (Ref obj) empty :: AttributeDict obj empty = HashMap.empty insertRef :: Text -> Ref obj -> AttributeDict obj -> AttributeDict obj insertRef = HashMap.insert lookup :: (MonadIO m) => Text -> AttributeDict obj -> m (Maybe obj) lookup attr dict = case lookupRef attr dict of Just ref -> Just <$> readRef ref Nothing -> return Nothing lookupRef :: Text -> AttributeDict obj -> Maybe (Ref obj) lookupRef = HashMap.lookup fromList :: [(Text, Ref obj)] -> AttributeDict obj fromList = HashMap.fromList new :: AttributeDict obj new = HashMap.empty set :: (MonadIO m) => Text -> obj -> AttributeDict obj -> m (AttributeDict obj) set attr obj dict = case HashMap.lookup attr dict of Just ref -> do writeRef ref obj return dict Nothing -> do ref <- newRef obj return $ HashMap.insert attr ref dict
067c393590c5c384b8b5948d7adf3fc387a8c28014fa2a3327b35a932290e297
antono/guix-debian
cmake-build-system.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2013 < > Copyright © 2013 < > Copyright © 2014 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at ;;; your option) any later version. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (guix build cmake-build-system) #:use-module ((guix build gnu-build-system) #:renamer (symbol-prefix-proc 'gnu:)) #:use-module (guix build utils) #:use-module (ice-9 match) #:export (%standard-phases cmake-build)) ;; Commentary: ;; ;; Builder-side code of the standard cmake build procedure. ;; ;; Code: (define* (configure #:key outputs (configure-flags '()) (out-of-source? #t) #:allow-other-keys) "Configure the given package." (let* ((out (assoc-ref outputs "out")) (abs-srcdir (getcwd)) (srcdir (if out-of-source? (string-append "../" (basename abs-srcdir)) "."))) (format #t "source directory: ~s (relative from build: ~s)~%" abs-srcdir srcdir) (when out-of-source? (mkdir "../build") (chdir "../build")) (format #t "build directory: ~s~%" (getcwd)) (let ((args `(,srcdir ,(string-append "-DCMAKE_INSTALL_PREFIX=" out) ;; add input libraries to rpath "-DCMAKE_INSTALL_RPATH_USE_LINK_PATH=TRUE" ;; add (other) libraries of the project itself to rpath ,(string-append "-DCMAKE_INSTALL_RPATH=" out "/lib") ,@configure-flags))) (setenv "CMAKE_LIBRARY_PATH" (getenv "LIBRARY_PATH")) (setenv "CMAKE_INCLUDE_PATH" (getenv "CPATH")) (format #t "running 'cmake' with arguments ~s~%" args) (zero? (apply system* "cmake" args))))) (define* (check #:key (tests? #t) (parallel-tests? #t) (test-target "test") #:allow-other-keys) (let ((gnu-check (assoc-ref gnu:%standard-phases 'check))) (gnu-check #:tests? tests? #:test-target test-target #:parallel-tests? parallel-tests?))) (define %standard-phases Everything is as with the GNU Build System except for the ` configure ' ;; and 'check' phases. (alist-replace 'configure configure (alist-replace 'check check gnu:%standard-phases))) (define* (cmake-build #:key inputs (phases %standard-phases) #:allow-other-keys #:rest args) "Build the given package, applying all of PHASES in order." (apply gnu:gnu-build #:inputs inputs #:phases phases args)) ;;; cmake-build-system.scm ends here
null
https://raw.githubusercontent.com/antono/guix-debian/85ef443788f0788a62010a942973d4f7714d10b4/guix/build/cmake-build-system.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Commentary: Builder-side code of the standard cmake build procedure. Code: add input libraries to rpath add (other) libraries of the project itself to rpath and 'check' phases. cmake-build-system.scm ends here
Copyright © 2013 < > Copyright © 2013 < > Copyright © 2014 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (guix build cmake-build-system) #:use-module ((guix build gnu-build-system) #:renamer (symbol-prefix-proc 'gnu:)) #:use-module (guix build utils) #:use-module (ice-9 match) #:export (%standard-phases cmake-build)) (define* (configure #:key outputs (configure-flags '()) (out-of-source? #t) #:allow-other-keys) "Configure the given package." (let* ((out (assoc-ref outputs "out")) (abs-srcdir (getcwd)) (srcdir (if out-of-source? (string-append "../" (basename abs-srcdir)) "."))) (format #t "source directory: ~s (relative from build: ~s)~%" abs-srcdir srcdir) (when out-of-source? (mkdir "../build") (chdir "../build")) (format #t "build directory: ~s~%" (getcwd)) (let ((args `(,srcdir ,(string-append "-DCMAKE_INSTALL_PREFIX=" out) "-DCMAKE_INSTALL_RPATH_USE_LINK_PATH=TRUE" ,(string-append "-DCMAKE_INSTALL_RPATH=" out "/lib") ,@configure-flags))) (setenv "CMAKE_LIBRARY_PATH" (getenv "LIBRARY_PATH")) (setenv "CMAKE_INCLUDE_PATH" (getenv "CPATH")) (format #t "running 'cmake' with arguments ~s~%" args) (zero? (apply system* "cmake" args))))) (define* (check #:key (tests? #t) (parallel-tests? #t) (test-target "test") #:allow-other-keys) (let ((gnu-check (assoc-ref gnu:%standard-phases 'check))) (gnu-check #:tests? tests? #:test-target test-target #:parallel-tests? parallel-tests?))) (define %standard-phases Everything is as with the GNU Build System except for the ` configure ' (alist-replace 'configure configure (alist-replace 'check check gnu:%standard-phases))) (define* (cmake-build #:key inputs (phases %standard-phases) #:allow-other-keys #:rest args) "Build the given package, applying all of PHASES in order." (apply gnu:gnu-build #:inputs inputs #:phases phases args))
d0ad29b87bf826299a6daf077e0435be4aad4664dac5533417c41957fd4c180e
well-typed/optics
Optics.hs
-- | -- Module: Data.Text.Optics -- Description: Optics for working with strict or lazy 'Text'. -- This module provides ' 's for converting strict or lazy ' Text ' to or from a ' String ' or ' Builder ' , and an ' ' for traversing the individual -- characters of a 'Text'. -- The same combinators support both strict and lazy text using the ' IsText ' -- typeclass. You can import "Data.Text.Strict.Optics" or -- "Data.Text.Lazy.Optics" instead if you prefer monomorphic versions. -- module Data.Text.Optics ( IsText(..) , unpacked , _Text , pattern Text ) where import qualified Data.Text as Strict import qualified Data.Text.Lazy as Lazy import qualified Data.Text.Lazy.Builder as B import Optics.Core import qualified Data.Text.Lazy.Optics as Lazy import qualified Data.Text.Strict.Optics as Strict -- | Traversals for strict or lazy 'Text' class IsText t where -- | This isomorphism can be used to 'pack' (or 'unpack') strict or lazy -- 'Text'. -- -- @ -- 'pack' x ≡ x 'Optics.Operators.^.' 'packed' -- 'unpack' x ≡ x 'Optics.Operators.^.' 're' 'packed' -- 'packed' ≡ 're' 'unpacked' -- @ packed :: Iso' String t -- | Convert between strict or lazy 'Text' and a 'Builder'. -- -- @ -- 'fromText' x ≡ x 'Optics.Operators.^.' 'builder' -- @ builder :: Iso' t B.Builder -- | Traverse the individual characters in strict or lazy 'Text'. -- -- @ -- 'text' = 'unpacked' . 'traversed' -- @ text :: IxTraversal' Int t Char text = unpacked % itraversed # INLINE text # instance IsText String where packed = iso id id text = itraversed builder = Lazy.packed % builder # INLINE packed # # INLINE text # # INLINE builder # -- | This isomorphism can be used to 'unpack' (or 'pack') both strict or lazy -- 'Text'. -- -- @ -- 'unpack' x ≡ x 'Optics.Operators.^.' 'unpacked' -- 'pack' x ≡ x 'Optics.Operators.^.' 're' 'unpacked' -- @ -- This ' ' is provided for notational convenience rather than out of great -- need, since -- -- @ -- 'unpacked' ≡ 're' 'packed' -- @ -- unpacked :: IsText t => Iso' t String unpacked = re packed {-# INLINE unpacked #-} -- | This is an alias for 'unpacked' that makes it clearer how to use it with @('Optics . Operators.#')@. -- -- @ -- '_Text' = 're' 'packed' -- @ -- -- >>> _Text # "hello" :: Strict.Text -- "hello" _Text :: IsText t => Iso' t String _Text = re packed {-# INLINE _Text #-} pattern Text :: IsText t => String -> t pattern Text a <- (view _Text -> a) where Text a = review _Text a instance IsText Strict.Text where packed = Strict.packed builder = Strict.builder text = Strict.text # INLINE packed # # INLINE builder # # INLINE text # instance IsText Lazy.Text where packed = Lazy.packed builder = Lazy.builder text = Lazy.text # INLINE packed # # INLINE builder # # INLINE text #
null
https://raw.githubusercontent.com/well-typed/optics/ba3c5a4d2f110c82238bc2fe7bb187023ab516f5/optics-extra/src/Data/Text/Optics.hs
haskell
| Module: Data.Text.Optics Description: Optics for working with strict or lazy 'Text'. characters of a 'Text'. typeclass. You can import "Data.Text.Strict.Optics" or "Data.Text.Lazy.Optics" instead if you prefer monomorphic versions. | Traversals for strict or lazy 'Text' | This isomorphism can be used to 'pack' (or 'unpack') strict or lazy 'Text'. @ 'pack' x ≡ x 'Optics.Operators.^.' 'packed' 'unpack' x ≡ x 'Optics.Operators.^.' 're' 'packed' 'packed' ≡ 're' 'unpacked' @ | Convert between strict or lazy 'Text' and a 'Builder'. @ 'fromText' x ≡ x 'Optics.Operators.^.' 'builder' @ | Traverse the individual characters in strict or lazy 'Text'. @ 'text' = 'unpacked' . 'traversed' @ | This isomorphism can be used to 'unpack' (or 'pack') both strict or lazy 'Text'. @ 'unpack' x ≡ x 'Optics.Operators.^.' 'unpacked' 'pack' x ≡ x 'Optics.Operators.^.' 're' 'unpacked' @ need, since @ 'unpacked' ≡ 're' 'packed' @ # INLINE unpacked # | This is an alias for 'unpacked' that makes it clearer how to use it with @ '_Text' = 're' 'packed' @ >>> _Text # "hello" :: Strict.Text "hello" # INLINE _Text #
This module provides ' 's for converting strict or lazy ' Text ' to or from a ' String ' or ' Builder ' , and an ' ' for traversing the individual The same combinators support both strict and lazy text using the ' IsText ' module Data.Text.Optics ( IsText(..) , unpacked , _Text , pattern Text ) where import qualified Data.Text as Strict import qualified Data.Text.Lazy as Lazy import qualified Data.Text.Lazy.Builder as B import Optics.Core import qualified Data.Text.Lazy.Optics as Lazy import qualified Data.Text.Strict.Optics as Strict class IsText t where packed :: Iso' String t builder :: Iso' t B.Builder text :: IxTraversal' Int t Char text = unpacked % itraversed # INLINE text # instance IsText String where packed = iso id id text = itraversed builder = Lazy.packed % builder # INLINE packed # # INLINE text # # INLINE builder # This ' ' is provided for notational convenience rather than out of great unpacked :: IsText t => Iso' t String unpacked = re packed @('Optics . Operators.#')@. _Text :: IsText t => Iso' t String _Text = re packed pattern Text :: IsText t => String -> t pattern Text a <- (view _Text -> a) where Text a = review _Text a instance IsText Strict.Text where packed = Strict.packed builder = Strict.builder text = Strict.text # INLINE packed # # INLINE builder # # INLINE text # instance IsText Lazy.Text where packed = Lazy.packed builder = Lazy.builder text = Lazy.text # INLINE packed # # INLINE builder # # INLINE text #
f3d1f7c01d333e80cca961984da50b267b8361894927534e87955b6882efc89f
basho/riaknostic
riaknostic_check_ring_size.erl
%% ------------------------------------------------------------------- %% riaknostic - automated diagnostic tools for Riak %% Copyright ( c ) 2011 Basho Technologies , Inc. All Rights Reserved . %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% %% ------------------------------------------------------------------- @doc Diagnostic that compares the configured %% <code>ring_creation_size</code> to the actual size of the ring. -module(riaknostic_check_ring_size). -behaviour(riaknostic_check). -export([description/0, valid/0, check/0, format/1]). -spec description() -> string(). description() -> "Ring size valid". -spec valid() -> boolean(). valid() -> riaknostic_node:can_connect(). -spec check() -> [{lager:log_level(), term()}]. check() -> Stats = riaknostic_node:stats(), {ring_creation_size, RingSize} = lists:keyfind(ring_creation_size, 1, Stats), {ring_num_partitions, NumPartitions} = lists:keyfind(ring_num_partitions, 1, Stats), { ring_members , RingMembers } = lists : , 1 , Stats ) , = length(RingMembers ) , VnodesPerNode = : round(RingSize / NumRingMembers ) , = : round(RingSize * 0.03 ) , = : round(RingSize * 0.7 ) , lists:append([ [ {notice, {ring_size_unequal, RingSize, NumPartitions}} || RingSize /= NumPartitions ], [ {critical, {ring_size_not_exp2, RingSize}} || (RingSize band -(bnot RingSize)) /= RingSize] [ { notice , { ring_size_too_small , RingSize , NumRingMembers } } || VnodesPerNode = < MinAcceptableVnodesPerNode ] , [ { notice , { too_few_nodes_for_ring , RingSize , NumRingMembers } } || VnodesPerNode > = MaxRecommendedVnodesPerNode ] ]). -spec format(term()) -> {io:format(), [term()]}. format({ring_size_unequal, S, P}) -> {"The configured ring_creation_size (~B) is not equal to the number of partitions in the ring (~B). " "Please verify that the ring_creation_size in app.config is correct.", [S, P]}; format({ring_size_not_exp2, S}) -> {"The configured ring_creation_size (~B) should always be a power of 2. " "Please reconfigure the ring_creation_size in app.config.", [S]}. format({ring_size_too_small , S , N } ) - > { " With a ring_creation_size ( ~B ) and ~B nodes participating in the cluster , each node is responsible for less than 3 % of the data . " % " You have too many nodes for this size ring. " " Please consider migrating data to a cluster with 2 or 4x your current ring size . " , [ S , N ] } ; %format({too_few_nodes_for_ring, S, N}) -> { " With a ring_creation_size ( ~B ) and ~B nodes participating in the cluster , each node is responsible for more than 70 % of the data . " % " You have too few nodes for this size ring. " % "Please consider joining more nodes to your cluster.", [S, N]}.
null
https://raw.githubusercontent.com/basho/riaknostic/dad8939d0ef32fbf435d13697720223293195282/src/riaknostic_check_ring_size.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. ------------------------------------------------------------------- <code>ring_creation_size</code> to the actual size of the ring. " You have too many nodes for this size ring. " format({too_few_nodes_for_ring, S, N}) -> " You have too few nodes for this size ring. " "Please consider joining more nodes to your cluster.", [S, N]}.
riaknostic - automated diagnostic tools for Riak Copyright ( c ) 2011 Basho Technologies , Inc. All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY @doc Diagnostic that compares the configured -module(riaknostic_check_ring_size). -behaviour(riaknostic_check). -export([description/0, valid/0, check/0, format/1]). -spec description() -> string(). description() -> "Ring size valid". -spec valid() -> boolean(). valid() -> riaknostic_node:can_connect(). -spec check() -> [{lager:log_level(), term()}]. check() -> Stats = riaknostic_node:stats(), {ring_creation_size, RingSize} = lists:keyfind(ring_creation_size, 1, Stats), {ring_num_partitions, NumPartitions} = lists:keyfind(ring_num_partitions, 1, Stats), { ring_members , RingMembers } = lists : , 1 , Stats ) , = length(RingMembers ) , VnodesPerNode = : round(RingSize / NumRingMembers ) , = : round(RingSize * 0.03 ) , = : round(RingSize * 0.7 ) , lists:append([ [ {notice, {ring_size_unequal, RingSize, NumPartitions}} || RingSize /= NumPartitions ], [ {critical, {ring_size_not_exp2, RingSize}} || (RingSize band -(bnot RingSize)) /= RingSize] [ { notice , { ring_size_too_small , RingSize , NumRingMembers } } || VnodesPerNode = < MinAcceptableVnodesPerNode ] , [ { notice , { too_few_nodes_for_ring , RingSize , NumRingMembers } } || VnodesPerNode > = MaxRecommendedVnodesPerNode ] ]). -spec format(term()) -> {io:format(), [term()]}. format({ring_size_unequal, S, P}) -> {"The configured ring_creation_size (~B) is not equal to the number of partitions in the ring (~B). " "Please verify that the ring_creation_size in app.config is correct.", [S, P]}; format({ring_size_not_exp2, S}) -> {"The configured ring_creation_size (~B) should always be a power of 2. " "Please reconfigure the ring_creation_size in app.config.", [S]}. format({ring_size_too_small , S , N } ) - > { " With a ring_creation_size ( ~B ) and ~B nodes participating in the cluster , each node is responsible for less than 3 % of the data . " " Please consider migrating data to a cluster with 2 or 4x your current ring size . " , [ S , N ] } ; { " With a ring_creation_size ( ~B ) and ~B nodes participating in the cluster , each node is responsible for more than 70 % of the data . "
7a10e6e7ddbf9678ef35d727a3fa16e5e7573e7500f924e9961991213a512afc
ondrap/dynamodb-simple
Update.hs
# LANGUAGE CPP # #if __GLASGOW_HASKELL__ >= 800 {-# OPTIONS_GHC -Wno-redundant-constraints #-} #endif {-# LANGUAGE DataKinds #-} # LANGUAGE FlexibleContexts # # LANGUAGE GeneralizedNewtypeDeriving # {-# LANGUAGE OverloadedStrings #-} -- | Module for creating update actions -- -- Example as used in nested structure for scan: -- -- > updateItemByKey_ (Proxy :: Proxy Test, ("hashkey", "sortkey")) > ( ( iInt ' + = . 5 ) < > ( iText ' = . " updated " ) < > ( iMText ' = . Nothing ) ) -- The unique " Action " can be added together using the ' < > ' operator . You are not supposed -- to operate on the same attribute simultaneously using multiple actions. module Database.DynamoDB.Update ( Action -- * Update action , (+=.), (-=.), (=.) , setIfNothing , append, prepend , add, delete , delListItem , delHashKey -- * Utility function , dumpActions ) where import Control.Lens (over, _1) import Control.Monad.Supply (Supply, evalSupply, supply) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HMap import Data.Semigroup import qualified Data.Set as Set import qualified Data.Text as T import Network.AWS.DynamoDB.Types (AttributeValue) import Database.DynamoDB.Internal import Database.DynamoDB.Types data ActionValue = ValAttr AttributeValue | IfNotExists NameGen AttributeValue | ListAppend NameGen AttributeValue | ListPrepend NameGen AttributeValue | Plus NameGen AttributeValue -- Add number to existing value | Minus NameGen AttributeValue -- Subtract number from existing value -- | An action for 'Database.DynamoDB.updateItemByKey' functions. newtype Action t = Action ([Set], [Add], [Delete], [Remove]) deriving (Semigroup, Monoid) isNoopAction :: Action t -> Bool isNoopAction (Action ([], [], [], [])) = True isNoopAction _ = False data Set = Set NameGen ActionValue -- General SET data Add = Add NameGen AttributeValue -- Add value to a Set data Delete = Delete NameGen AttributeValue -- Delete value from a Set data Remove = Remove NameGen -- For Maybe types, remove attribute class ActionClass a where dumpAction :: a -> Supply T.Text (T.Text, HashMap T.Text T.Text, HashMap T.Text AttributeValue) asAction :: a -> Action t instance ActionClass Set where asAction a = Action ([a], [], [], []) dumpAction (Set name val) = do (subst, attrnames) <- name supplyName (expr, exprattr, valnames) <- mkActionVal val return (subst <> " = " <> expr, attrnames <> exprattr, valnames) instance ActionClass Add where asAction a = Action ([], [a], [], []) dumpAction (Add name val) = do (subst, attrnames) <- name supplyName idval <- supplyValue let valnames = HMap.singleton idval val return (subst <> " " <> idval, attrnames, valnames) instance ActionClass Delete where asAction a = Action ([], [], [a], []) dumpAction (Delete name val) = do (subst, attrnames) <- name supplyName idval <- supplyValue let valnames = HMap.singleton idval val return (subst <> " " <> idval, attrnames, valnames) instance ActionClass Remove where asAction a = Action ([], [], [], [a]) dumpAction (Remove name) = do (subst, attrnames) <- name supplyName return (subst, attrnames, HMap.empty) -- | Generate an action expression and associated structures from a list of actions dumpActions :: Action t -> Maybe (T.Text, HashMap T.Text T.Text, HashMap T.Text AttributeValue) dumpActions action@(Action (iset, iadd, idelete, iremove)) | isNoopAction action = Nothing | otherwise = Just $ evalSupply eval nameSupply where eval :: Supply T.Text (T.Text, HashMap T.Text T.Text, HashMap T.Text AttributeValue) eval = do dset <- mksection "SET" <$> mapM dumpAction iset dadd <- mksection "ADD" <$> mapM dumpAction iadd ddelete <- mksection "DELETE" <$> mapM dumpAction idelete dremove <- mksection "REMOVE" <$> mapM dumpAction iremove return $ dset <> dadd <> ddelete <> dremove mksection :: T.Text -> [(T.Text, HashMap T.Text T.Text, HashMap T.Text AttributeValue)] -> (T.Text, HashMap T.Text T.Text, HashMap T.Text AttributeValue) mksection _ [] = ("", HMap.empty, HMap.empty) mksection secname xs = let (exprs, attnames, attvals) = mconcat $ map (over _1 (: [])) xs in (" " <> secname <> " " <> T.intercalate "," exprs, attnames, attvals) nameSupply = map (\i -> T.pack ("A" <> show i)) ([1..] :: [Int]) supplyName :: Supply T.Text T.Text supplyName = ("#" <>) <$> supply supplyValue :: Supply T.Text T.Text supplyValue = (":" <> ) <$> supply mkActionVal :: ActionValue -> Supply T.Text (T.Text, HashMap T.Text T.Text, HashMap T.Text AttributeValue) mkActionVal (ValAttr val) = do valname <- supplyValue return (valname, HMap.empty, HMap.singleton valname val) mkActionVal (IfNotExists name val) = do valname <- supplyValue (subst, attrnames) <- name supplyName return ("if_not_exists(" <> subst <> "," <> valname <> ")", attrnames, HMap.singleton valname val) mkActionVal (ListAppend name val) = do valname <- supplyValue (subst, attrnames) <- name supplyName return ("list_append(" <> subst <> "," <> valname <> ")", attrnames, HMap.singleton valname val) mkActionVal (ListPrepend name val) = do valname <- supplyValue (subst, attrnames) <- name supplyName return ("list_append(" <> valname <> "," <> subst <> ")", attrnames, HMap.singleton valname val) mkActionVal (Plus name val) = do valname <- supplyValue (subst, attrnames) <- name supplyName return (subst <> "+" <> valname, attrnames, HMap.singleton valname val) mkActionVal (Minus name val) = do valname <- supplyValue (subst, attrnames) <- name supplyName return (subst <> "-" <> valname, attrnames, HMap.singleton valname val) -- | Add a number to a saved attribute. (+=.) :: (InCollection col tbl 'FullPath, DynamoScalar v typ, IsNumber typ) => Column typ 'TypColumn col -> typ -> Action tbl (+=.) col val = asAction $ Set (nameGen col) (Plus (nameGen col) (dScalarEncode val)) infix 4 +=. -- | Subtract a number from a saved attribute. (-=.) :: (InCollection col tbl 'FullPath, DynamoScalar v typ, IsNumber typ) => Column typ 'TypColumn col -> typ -> Action tbl (-=.) col val = asAction $ Set (nameGen col) (Minus (nameGen col) (dScalarEncode val)) infix 4 -=. -- | Set an attribute to a new value. (=.) :: (InCollection col tbl 'FullPath, DynamoEncodable typ) => Column typ 'TypColumn col -> typ -> Action tbl (=.) col val = case dEncode val of Just attr -> asAction $ Set (nameGen col) (ValAttr attr) Nothing -> asAction $ Remove (nameGen col) infix 4 =. -- | Set on a Maybe type, if it was not set before. setIfNothing :: (InCollection col tbl 'FullPath, DynamoEncodable typ) => Column (Maybe typ) 'TypColumn col -> typ -> Action tbl setIfNothing col val = case dEncode val of Just attr -> asAction $ Set (nameGen col) (IfNotExists (nameGen col) attr) Nothing -> mempty -- | Append a new value to an end of a list. append :: (InCollection col tbl 'FullPath, DynamoEncodable typ) => Column [typ] 'TypColumn col -> [typ] -> Action tbl append col val = case dEncode val of Just attr -> asAction $ Set (nameGen col) (ListAppend (nameGen col) attr) Nothing -> mempty -- | Insert a value to a beginning of a list prepend :: (InCollection col tbl 'FullPath, DynamoEncodable typ) => Column [typ] 'TypColumn col -> [typ] -> Action tbl prepend col val = case dEncode val of Just attr -> asAction $ Set (nameGen col) (ListPrepend (nameGen col) attr) Nothing -> mempty -- | Add a new value to a set. add :: (InCollection col tbl 'FullPath, DynamoEncodable (Set.Set typ)) => Column (Set.Set typ) 'TypColumn col -> Set.Set typ -> Action tbl add col val | Set.null val = mempty | otherwise = maybe mempty (asAction . Add (nameGen col)) (dEncode val) -- | Remove a value from a set. delete :: (InCollection col tbl 'FullPath, DynamoEncodable (Set.Set typ)) => Column (Set.Set typ) 'TypColumn col -> Set.Set typ -> Action tbl delete col val | Set.null val = mempty | otherwise = maybe mempty (asAction . Delete (nameGen col)) (dEncode val) -- | Delete n-th list of an item. delListItem :: InCollection col tbl 'FullPath => Column [typ] 'TypColumn col -> Int -> Action tbl delListItem col idx = asAction $ Remove (nameGen (col <!> idx)) -- | Delete a key from a map. delHashKey :: (InCollection col tbl 'FullPath, IsText key) => Column (HashMap key typ) 'TypColumn col -> key -> Action tbl delHashKey col key = asAction $ Remove (nameGen (col <!:> key))
null
https://raw.githubusercontent.com/ondrap/dynamodb-simple/fb7e3fe37d7e534161274cfd812cd11a82cc384b/src/Database/DynamoDB/Update.hs
haskell
# OPTIONS_GHC -Wno-redundant-constraints # # LANGUAGE DataKinds # # LANGUAGE OverloadedStrings # | Module for creating update actions Example as used in nested structure for scan: > updateItemByKey_ (Proxy :: Proxy Test, ("hashkey", "sortkey")) to operate on the same attribute simultaneously using multiple actions. * Update action * Utility function Add number to existing value Subtract number from existing value | An action for 'Database.DynamoDB.updateItemByKey' functions. General SET Add value to a Set Delete value from a Set For Maybe types, remove attribute | Generate an action expression and associated structures from a list of actions | Add a number to a saved attribute. | Subtract a number from a saved attribute. | Set an attribute to a new value. | Set on a Maybe type, if it was not set before. | Append a new value to an end of a list. | Insert a value to a beginning of a list | Add a new value to a set. | Remove a value from a set. | Delete n-th list of an item. | Delete a key from a map.
# LANGUAGE CPP # #if __GLASGOW_HASKELL__ >= 800 #endif # LANGUAGE FlexibleContexts # # LANGUAGE GeneralizedNewtypeDeriving # > ( ( iInt ' + = . 5 ) < > ( iText ' = . " updated " ) < > ( iMText ' = . Nothing ) ) The unique " Action " can be added together using the ' < > ' operator . You are not supposed module Database.DynamoDB.Update ( Action , (+=.), (-=.), (=.) , setIfNothing , append, prepend , add, delete , delListItem , delHashKey , dumpActions ) where import Control.Lens (over, _1) import Control.Monad.Supply (Supply, evalSupply, supply) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HMap import Data.Semigroup import qualified Data.Set as Set import qualified Data.Text as T import Network.AWS.DynamoDB.Types (AttributeValue) import Database.DynamoDB.Internal import Database.DynamoDB.Types data ActionValue = ValAttr AttributeValue | IfNotExists NameGen AttributeValue | ListAppend NameGen AttributeValue | ListPrepend NameGen AttributeValue newtype Action t = Action ([Set], [Add], [Delete], [Remove]) deriving (Semigroup, Monoid) isNoopAction :: Action t -> Bool isNoopAction (Action ([], [], [], [])) = True isNoopAction _ = False class ActionClass a where dumpAction :: a -> Supply T.Text (T.Text, HashMap T.Text T.Text, HashMap T.Text AttributeValue) asAction :: a -> Action t instance ActionClass Set where asAction a = Action ([a], [], [], []) dumpAction (Set name val) = do (subst, attrnames) <- name supplyName (expr, exprattr, valnames) <- mkActionVal val return (subst <> " = " <> expr, attrnames <> exprattr, valnames) instance ActionClass Add where asAction a = Action ([], [a], [], []) dumpAction (Add name val) = do (subst, attrnames) <- name supplyName idval <- supplyValue let valnames = HMap.singleton idval val return (subst <> " " <> idval, attrnames, valnames) instance ActionClass Delete where asAction a = Action ([], [], [a], []) dumpAction (Delete name val) = do (subst, attrnames) <- name supplyName idval <- supplyValue let valnames = HMap.singleton idval val return (subst <> " " <> idval, attrnames, valnames) instance ActionClass Remove where asAction a = Action ([], [], [], [a]) dumpAction (Remove name) = do (subst, attrnames) <- name supplyName return (subst, attrnames, HMap.empty) dumpActions :: Action t -> Maybe (T.Text, HashMap T.Text T.Text, HashMap T.Text AttributeValue) dumpActions action@(Action (iset, iadd, idelete, iremove)) | isNoopAction action = Nothing | otherwise = Just $ evalSupply eval nameSupply where eval :: Supply T.Text (T.Text, HashMap T.Text T.Text, HashMap T.Text AttributeValue) eval = do dset <- mksection "SET" <$> mapM dumpAction iset dadd <- mksection "ADD" <$> mapM dumpAction iadd ddelete <- mksection "DELETE" <$> mapM dumpAction idelete dremove <- mksection "REMOVE" <$> mapM dumpAction iremove return $ dset <> dadd <> ddelete <> dremove mksection :: T.Text -> [(T.Text, HashMap T.Text T.Text, HashMap T.Text AttributeValue)] -> (T.Text, HashMap T.Text T.Text, HashMap T.Text AttributeValue) mksection _ [] = ("", HMap.empty, HMap.empty) mksection secname xs = let (exprs, attnames, attvals) = mconcat $ map (over _1 (: [])) xs in (" " <> secname <> " " <> T.intercalate "," exprs, attnames, attvals) nameSupply = map (\i -> T.pack ("A" <> show i)) ([1..] :: [Int]) supplyName :: Supply T.Text T.Text supplyName = ("#" <>) <$> supply supplyValue :: Supply T.Text T.Text supplyValue = (":" <> ) <$> supply mkActionVal :: ActionValue -> Supply T.Text (T.Text, HashMap T.Text T.Text, HashMap T.Text AttributeValue) mkActionVal (ValAttr val) = do valname <- supplyValue return (valname, HMap.empty, HMap.singleton valname val) mkActionVal (IfNotExists name val) = do valname <- supplyValue (subst, attrnames) <- name supplyName return ("if_not_exists(" <> subst <> "," <> valname <> ")", attrnames, HMap.singleton valname val) mkActionVal (ListAppend name val) = do valname <- supplyValue (subst, attrnames) <- name supplyName return ("list_append(" <> subst <> "," <> valname <> ")", attrnames, HMap.singleton valname val) mkActionVal (ListPrepend name val) = do valname <- supplyValue (subst, attrnames) <- name supplyName return ("list_append(" <> valname <> "," <> subst <> ")", attrnames, HMap.singleton valname val) mkActionVal (Plus name val) = do valname <- supplyValue (subst, attrnames) <- name supplyName return (subst <> "+" <> valname, attrnames, HMap.singleton valname val) mkActionVal (Minus name val) = do valname <- supplyValue (subst, attrnames) <- name supplyName return (subst <> "-" <> valname, attrnames, HMap.singleton valname val) (+=.) :: (InCollection col tbl 'FullPath, DynamoScalar v typ, IsNumber typ) => Column typ 'TypColumn col -> typ -> Action tbl (+=.) col val = asAction $ Set (nameGen col) (Plus (nameGen col) (dScalarEncode val)) infix 4 +=. (-=.) :: (InCollection col tbl 'FullPath, DynamoScalar v typ, IsNumber typ) => Column typ 'TypColumn col -> typ -> Action tbl (-=.) col val = asAction $ Set (nameGen col) (Minus (nameGen col) (dScalarEncode val)) infix 4 -=. (=.) :: (InCollection col tbl 'FullPath, DynamoEncodable typ) => Column typ 'TypColumn col -> typ -> Action tbl (=.) col val = case dEncode val of Just attr -> asAction $ Set (nameGen col) (ValAttr attr) Nothing -> asAction $ Remove (nameGen col) infix 4 =. setIfNothing :: (InCollection col tbl 'FullPath, DynamoEncodable typ) => Column (Maybe typ) 'TypColumn col -> typ -> Action tbl setIfNothing col val = case dEncode val of Just attr -> asAction $ Set (nameGen col) (IfNotExists (nameGen col) attr) Nothing -> mempty append :: (InCollection col tbl 'FullPath, DynamoEncodable typ) => Column [typ] 'TypColumn col -> [typ] -> Action tbl append col val = case dEncode val of Just attr -> asAction $ Set (nameGen col) (ListAppend (nameGen col) attr) Nothing -> mempty prepend :: (InCollection col tbl 'FullPath, DynamoEncodable typ) => Column [typ] 'TypColumn col -> [typ] -> Action tbl prepend col val = case dEncode val of Just attr -> asAction $ Set (nameGen col) (ListPrepend (nameGen col) attr) Nothing -> mempty add :: (InCollection col tbl 'FullPath, DynamoEncodable (Set.Set typ)) => Column (Set.Set typ) 'TypColumn col -> Set.Set typ -> Action tbl add col val | Set.null val = mempty | otherwise = maybe mempty (asAction . Add (nameGen col)) (dEncode val) delete :: (InCollection col tbl 'FullPath, DynamoEncodable (Set.Set typ)) => Column (Set.Set typ) 'TypColumn col -> Set.Set typ -> Action tbl delete col val | Set.null val = mempty | otherwise = maybe mempty (asAction . Delete (nameGen col)) (dEncode val) delListItem :: InCollection col tbl 'FullPath => Column [typ] 'TypColumn col -> Int -> Action tbl delListItem col idx = asAction $ Remove (nameGen (col <!> idx)) delHashKey :: (InCollection col tbl 'FullPath, IsText key) => Column (HashMap key typ) 'TypColumn col -> key -> Action tbl delHashKey col key = asAction $ Remove (nameGen (col <!:> key))
67efd67f56e33f1974814517551e0630e7ace4e195becdc33cf74b03559d71ec
bnoordhuis/chicken-core
extras.scm
;;; extras.scm - Optional non-standard extensions ; Copyright ( c ) 2008 - 2013 , The Chicken Team Copyright ( c ) 2000 - 2007 , ; All rights reserved. ; ; Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following ; conditions are met: ; ; Redistributions of source code must retain the above copyright notice, this list of conditions and the following ; disclaimer. ; Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following ; disclaimer in the documentation and/or other materials provided with the distribution. ; Neither the name of the author 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 HOLDERS 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. (declare (unit extras) (uses data-structures ports)) (declare (hide fprintf0 generic-write) ) (include "common-declarations.scm") (register-feature! 'extras) ;;; Read expressions from file: (define read-file (let ([read read] [call-with-input-file call-with-input-file] ) (lambda (#!optional (port ##sys#standard-input) (reader read) max) (define (slurp port) (do ((x (reader port) (reader port)) (i 0 (fx+ i 1)) (xs '() (cons x xs)) ) ((or (eof-object? x) (and max (fx>= i max))) (##sys#fast-reverse xs)) ) ) (if (port? port) (slurp port) (call-with-input-file port slurp) ) ) ) ) ;;; Random numbers: (define (randomize . n) (let ((nn (if (null? n) (##sys#flo2fix (fp/ (current-seconds) 1000.0)) ; wall clock time (car n)))) (##sys#check-exact nn 'randomize) (##core#inline "C_randomize" nn) ) ) (define (random n) (##sys#check-exact n 'random) (if (eq? n 0) 0 (##core#inline "C_random_fixnum" n) ) ) ;;; Line I/O: (define read-line (let () (define (fixup str len) (##sys#substring str 0 (if (and (fx>= len 1) (char=? #\return (##core#inline "C_subchar" str (fx- len 1)))) (fx- len 1) len) ) ) (lambda args (let* ([parg (pair? args)] [p (if parg (car args) ##sys#standard-input)] [limit (and parg (pair? (cdr args)) (cadr args))]) (##sys#check-input-port p #t 'read-line) (cond ((##sys#slot (##sys#slot p 2) 8) => (lambda (rl) (rl p limit))) (else (let* ((buffer-len (if limit limit 256)) (buffer (##sys#make-string buffer-len))) (let loop ([i 0]) (if (and limit (fx>= i limit)) (##sys#substring buffer 0 i) (let ([c (##sys#read-char-0 p)]) (if (eof-object? c) (if (fx= i 0) c (##sys#substring buffer 0 i) ) (case c [(#\newline) (##sys#substring buffer 0 i)] [(#\return) (let ([c (peek-char p)]) (if (char=? c #\newline) (begin (##sys#read-char-0 p) (##sys#substring buffer 0 i)) (##sys#substring buffer 0 i) ) ) ] [else (when (fx>= i buffer-len) (set! buffer (##sys#string-append buffer (make-string buffer-len))) (set! buffer-len (fx+ buffer-len buffer-len)) ) (##core#inline "C_setsubchar" buffer i c) (loop (fx+ i 1)) ] ) ) ) ) ) ) ) ) ) ) ) ) (define read-lines (lambda port-and-max (let* ((port (if (pair? port-and-max) (##sys#slot port-and-max 0) ##sys#standard-input)) (rest (and (pair? port-and-max) (##sys#slot port-and-max 1))) (max (if (pair? rest) (##sys#slot rest 0) #f)) ) (define (doread port) (let loop ((lns '()) (n (or max 1000000000)) ) ; this is silly (if (eq? n 0) (##sys#fast-reverse lns) (let ((ln (read-line port))) (if (eof-object? ln) (##sys#fast-reverse lns) (loop (cons ln lns) (fx- n 1)) ) ) ) ) ) (if (string? port) (call-with-input-file port doread) (begin (##sys#check-input-port port #t 'read-lines) (doread port) ) ) ) ) ) (define write-line (lambda (str . port) (let* ((p (if (##core#inline "C_eqp" port '()) ##sys#standard-output (##sys#slot port 0) ) )) (##sys#check-output-port p #t 'write-line) (##sys#check-string str 'write-line) ((##sys#slot (##sys#slot p 2) 3) p str) ; write-string method (##sys#write-char-0 #\newline p)))) ;;; Extended I/O (define (##sys#read-string! n dest port start) (cond ((eq? n 0) 0) (else (when (##sys#slot port 6) ; peeked? (##core#inline "C_setsubchar" dest start (##sys#read-char-0 port)) (set! start (fx+ start 1)) ) (let ((rdstring (##sys#slot (##sys#slot port 2) 7))) (if rdstring (let loop ((start start) (n n) (m 0)) (let ((n2 (rdstring port n dest start))) (##sys#setislot port 5 ; update port-position (fx+ (##sys#slot port 5) n2)) (cond ((eq? n2 0) m) ((or (not n) (fx< n2 n)) (loop (fx+ start n2) (and n (fx- n n2)) (fx+ m n2))) (else (fx+ n2 m))))) (let loop ((start start) (n n) (m 0)) (let ((n2 (let ((c (##sys#read-char-0 port))) (if (eof-object? c) 0 (begin (##core#inline "C_setsubchar" dest start c) 1) ) ) ) ) (cond ((eq? n2 0) m) ((or (not n) (fx< n2 n)) (loop (fx+ start n2) (and n (fx- n n2)) (fx+ m n2)) ) (else (fx+ n2 m))) ))))))) (define (read-string! n dest #!optional (port ##sys#standard-input) (start 0)) (##sys#check-input-port port #t 'read-string!) (##sys#check-string dest 'read-string!) (when n (##sys#check-exact n 'read-string!) (when (fx> (fx+ start n) (##sys#size dest)) (set! n (fx- (##sys#size dest) start)))) (##sys#check-exact start 'read-string!) (##sys#read-string! n dest port start) ) (define-constant read-string-buffer-size 2048) (define ##sys#read-string/port (lambda (n p) (##sys#check-input-port p #t 'read-string) (cond (n (##sys#check-exact n 'read-string) (let* ((str (##sys#make-string n)) (n2 (##sys#read-string! n str p 0)) ) (if (eq? n n2) str (##sys#substring str 0 n2)))) (else (let ([out (open-output-string)] (buf (make-string read-string-buffer-size))) (let loop () (let ((n (##sys#read-string! read-string-buffer-size buf p 0))) (cond ((eq? n 0) (get-output-string out)) (else (write-string buf n out) (loop)))))))))) (define (read-string #!optional n (port ##sys#standard-input)) (##sys#read-string/port n port) ) ;; <procedure>(read-buffered [PORT])</procedure> ;; ;; Reads any remaining data buffered after previous read operations on ;; {{PORT}}. If no remaining data is currently buffered, an empty string ;; is returned. This procedure will never block. Currently only useful for ;; string-, process- and tcp ports. (define (read-buffered #!optional (port ##sys#standard-input)) (##sys#check-input-port port #t 'read-buffered) (let ((rb (##sys#slot (##sys#slot port 2) 9))) ; read-buffered method (if rb (rb port) ""))) ;;; read token of characters that satisfy a predicate (define read-token (lambda (pred . port) (let ([port (optional port ##sys#standard-input)]) (##sys#check-input-port port #t 'read-token) (let ([out (open-output-string)]) (let loop () (let ([c (##sys#peek-char-0 port)]) (if (and (not (eof-object? c)) (pred c)) (begin (##sys#write-char-0 (##sys#read-char-0 port) out) (loop) ) (get-output-string out) ) ) ) ) ) ) ) (define write-string (lambda (s . more) (##sys#check-string s 'write-string) (let-optionals more ([n #f] [port ##sys#standard-output]) (##sys#check-output-port port #t 'write-string) (when n (##sys#check-exact n 'write-string)) ((##sys#slot (##sys#slot port 2) 3) ; write-string port (if (and n (fx< n (##sys#size s))) (##sys#substring s 0 n) s))))) ;;; Binary I/O (define (read-byte #!optional (port ##sys#standard-input)) (##sys#check-input-port port #t 'read-byte) (let ((x (##sys#read-char-0 port))) (if (eof-object? x) x (char->integer x) ) ) ) (define (write-byte byte #!optional (port ##sys#standard-output)) (##sys#check-exact byte 'write-byte) (##sys#check-output-port port #t 'write-byte) (##sys#write-char-0 (integer->char byte) port) ) ;;; Pretty print: ; Copyright ( c ) 1991 , Author : ( ) ; Distribution restrictions: none ; Modified by felix for use with CHICKEN ; (define generic-write (lambda (obj display? width output) (define (read-macro? l) (define (length1? l) (and (pair? l) (null? (cdr l)))) (let ((head (car l)) (tail (cdr l))) (case head ((quote quasiquote unquote unquote-splicing) (length1? tail)) (else #f)))) (define (read-macro-body l) (cadr l)) (define (read-macro-prefix l) (let ((head (car l)) (tail (cdr l))) (case head ((quote) "'") ((quasiquote) "`") ((unquote) ",") ((unquote-splicing) ",@")))) (define (out str col) (and col (output str) (+ col (string-length str)))) (define (wr obj col) (define (wr-expr expr col) (if (read-macro? expr) (wr (read-macro-body expr) (out (read-macro-prefix expr) col)) (wr-lst expr col))) (define (wr-lst l col) (if (pair? l) (let loop ((l (cdr l)) (col (and col (wr (car l) (out "(" col))))) (cond ((not col) col) ((pair? l) (loop (cdr l) (wr (car l) (out " " col)))) ((null? l) (out ")" col)) (else (out ")" (wr l (out " . " col)))))) (out "()" col))) (cond ((pair? obj) (wr-expr obj col)) ((null? obj) (wr-lst obj col)) ((eof-object? obj) (out "#!eof" col)) ((vector? obj) (wr-lst (vector->list obj) (out "#" col))) ((boolean? obj) (out (if obj "#t" "#f") col)) ((##sys#number? obj) (out (##sys#number->string obj) col)) ((symbol? obj) (let ([s (open-output-string)]) (##sys#print obj #t s) (out (get-output-string s) col) ) ) ((procedure? obj) (out (##sys#procedure->string obj) col)) ((string? obj) (if display? (out obj col) (let loop ((i 0) (j 0) (col (out "\"" col))) (if (and col (fx< j (string-length obj))) (let ((c (string-ref obj j))) (cond ((or (char=? c #\\) (char=? c #\")) (loop j (+ j 1) (out "\\" (out (##sys#substring obj i j) col)))) ((or (char<? c #\x20) (char=? c #\x7f)) (loop (fx+ j 1) (fx+ j 1) (let ((col2 (out (##sys#substring obj i j) col))) (cond ((assq c '((#\tab . "\\t") (#\newline . "\\n") (#\return . "\\r") (#\vtab . "\\v") (#\page . "\\f") (#\alarm . "\\a") (#\backspace . "\\b"))) => (lambda (a) (out (cdr a) col2))) (else (out (number->string (char->integer c) 16) (out (if (char<? c #\x10) "0" "") (out "\\x" col2)))))))) (else (loop i (fx+ j 1) col)))) (out "\"" (out (##sys#substring obj i j) col)))))) ((char? obj) (if display? (out (make-string 1 obj) col) (let ([code (char->integer obj)]) (out "#\\" col) (cond [(char-name obj) => (lambda (cn) (out (##sys#slot cn 1) col) ) ] [(fx< code 32) (out "x" col) (out (number->string code 16) col) ] [(fx> code 255) (out (if (fx> code #xffff) "U" "u") col) (out (number->string code 16) col) ] [else (out (make-string 1 obj) col)] ) ) ) ) ((##core#inline "C_undefinedp" obj) (out "#<unspecified>" col)) ((##core#inline "C_anypointerp" obj) (out (##sys#pointer->string obj) col)) ((eq? obj (##sys#slot '##sys#arbitrary-unbound-symbol 0)) (out "#<unbound value>" col) ) ((##sys#generic-structure? obj) (let ([o (open-output-string)]) (##sys#user-print-hook obj #t o) (out (get-output-string o) col) ) ) ((port? obj) (out (string-append "#<port " (##sys#slot obj 3) ">") col)) ((##core#inline "C_bytevectorp" obj) (out "#${" col) (let ((len (##sys#size obj))) (do ((i 0 (fx+ i 1))) ((fx>= i len)) (let ((b (##sys#byte obj i))) (when (fx< b 16) (out "0" col)) (out (##sys#number->string b 16) col))) (out "}" col))) ((##core#inline "C_lambdainfop" obj) (out "#<lambda info " col) (out (##sys#lambda-info->string obj) col) (out ">" col) ) (else (out "#<unprintable object>" col)) ) ) (define (pp obj col) (define (spaces n col) (if (> n 0) (if (> n 7) (spaces (- n 8) (out " " col)) (out (##sys#substring " " 0 n) col)) col)) (define (indent to col) (and col (if (< to col) (and (out (make-string 1 #\newline) col) (spaces to 0)) (spaces (- to col) col)))) (define (pr obj col extra pp-pair) (if (or (pair? obj) (vector? obj)) ; may have to split on multiple lines (let ((result '()) (left (max (+ (- (- width col) extra) 1) max-expr-width))) (generic-write obj display? #f (lambda (str) (set! result (cons str result)) (set! left (- left (string-length str))) (> left 0))) all can be printed on one line (out (reverse-string-append result) col) (if (pair? obj) (pp-pair obj col extra) (pp-list (vector->list obj) (out "#" col) extra pp-expr)))) (wr obj col))) (define (pp-expr expr col extra) (if (read-macro? expr) (pr (read-macro-body expr) (out (read-macro-prefix expr) col) extra pp-expr) (let ((head (car expr))) (if (symbol? head) (let ((proc (style head))) (if proc (proc expr col extra) (if (> (string-length (##sys#symbol->qualified-string head)) max-call-head-width) (pp-general expr col extra #f #f #f pp-expr) (pp-call expr col extra pp-expr)))) (pp-list expr col extra pp-expr))))) ( head ; item3) (define (pp-call expr col extra pp-item) (let ((col* (wr (car expr) (out "(" col)))) (and col (pp-down (cdr expr) col* (+ col* 1) extra pp-item)))) ( ; item3) (define (pp-list l col extra pp-item) (let ((col (out "(" col))) (pp-down l col col extra pp-item))) (define (pp-down l col1 col2 extra pp-item) (let loop ((l l) (col col1)) (and col (cond ((pair? l) (let ((rest (cdr l))) (let ((extra (if (null? rest) (+ extra 1) 0))) (loop rest (pr (car l) (indent col2 col) extra pp-item))))) ((null? l) (out ")" col)) (else (out ")" (pr l (indent col2 (out "." (indent col2 col))) (+ extra 1) pp-item))))))) (define (pp-general expr col extra named? pp-1 pp-2 pp-3) (define (tail1 rest col1 col2 col3) (if (and pp-1 (pair? rest)) (let* ((val1 (car rest)) (rest (cdr rest)) (extra (if (null? rest) (+ extra 1) 0))) (tail2 rest col1 (pr val1 (indent col3 col2) extra pp-1) col3)) (tail2 rest col1 col2 col3))) (define (tail2 rest col1 col2 col3) (if (and pp-2 (pair? rest)) (let* ((val1 (car rest)) (rest (cdr rest)) (extra (if (null? rest) (+ extra 1) 0))) (tail3 rest col1 (pr val1 (indent col3 col2) extra pp-2))) (tail3 rest col1 col2))) (define (tail3 rest col1 col2) (pp-down rest col2 col1 extra pp-3)) (let* ((head (car expr)) (rest (cdr expr)) (col* (wr head (out "(" col)))) (if (and named? (pair? rest)) (let* ((name (car rest)) (rest (cdr rest)) (col** (wr name (out " " col*)))) (tail1 rest (+ col indent-general) col** (+ col** 1))) (tail1 rest (+ col indent-general) col* (+ col* 1))))) (define (pp-expr-list l col extra) (pp-list l col extra pp-expr)) (define (pp-lambda expr col extra) (pp-general expr col extra #f pp-expr-list #f pp-expr)) (define (pp-if expr col extra) (pp-general expr col extra #f pp-expr #f pp-expr)) (define (pp-cond expr col extra) (pp-call expr col extra pp-expr-list)) (define (pp-case expr col extra) (pp-general expr col extra #f pp-expr #f pp-expr-list)) (define (pp-and expr col extra) (pp-call expr col extra pp-expr)) (define (pp-let expr col extra) (let* ((rest (cdr expr)) (named? (and (pair? rest) (symbol? (car rest))))) (pp-general expr col extra named? pp-expr-list #f pp-expr))) (define (pp-begin expr col extra) (pp-general expr col extra #f #f #f pp-expr)) (define (pp-do expr col extra) (pp-general expr col extra #f pp-expr-list pp-expr-list pp-expr)) ;; define formatting style (change these to suit your style) (define indent-general 2) (define max-call-head-width 5) (define max-expr-width 50) (define (style head) (case head ((lambda let* letrec define) pp-lambda) ((if set!) pp-if) ((cond) pp-cond) ((case) pp-case) ((and or) pp-and) ((let) pp-let) ((begin) pp-begin) ((do) pp-do) (else #f))) (pr obj col 0 pp-expr)) (if width (out (make-string 1 #\newline) (pp obj 0)) (wr obj 0)))) ; (pretty-print obj port) pretty prints 'obj' on 'port'. The current ; output port is used if 'port' is not specified. (define pretty-print-width (make-parameter 79)) (define (pretty-print obj . opt) (let ((port (if (pair? opt) (car opt) (current-output-port)))) (generic-write obj #f (pretty-print-width) (lambda (s) (display s port) #t)) (##core#undefined) ) ) (define pp pretty-print) ;;; Write simple formatted output: (define fprintf0 (lambda (loc port msg args) (when port (##sys#check-output-port port #t loc)) (let ((out (if (and port (##sys#tty-port? port)) port (open-output-string)))) (let rec ([msg msg] [args args]) (##sys#check-string msg loc) (let ((index 0) (len (##sys#size msg)) ) (define (fetch) (let ((c (##core#inline "C_subchar" msg index))) (set! index (fx+ index 1)) c) ) (define (next) (if (##core#inline "C_eqp" args '()) (##sys#error loc "too few arguments to formatted output procedure") (let ((x (##sys#slot args 0))) (set! args (##sys#slot args 1)) x) ) ) (let loop () (unless (fx>= index len) (let ((c (fetch))) (if (and (eq? c #\~) (fx< index len)) (let ((dchar (fetch))) (case (char-upcase dchar) ((#\S) (write (next) out)) ((#\A) (display (next) out)) ((#\C) (##sys#write-char-0 (next) out)) ((#\B) (display (##sys#number->string (next) 2) out)) ((#\O) (display (##sys#number->string (next) 8) out)) ((#\X) (display (##sys#number->string (next) 16) out)) ((#\!) (##sys#flush-output out)) ((#\?) (let* ([fstr (next)] [lst (next)] ) (##sys#check-list lst loc) (rec fstr lst) out) ) ((#\~) (##sys#write-char-0 #\~ out)) ((#\% #\N) (newline out)) (else (if (char-whitespace? dchar) (let skip ((c (fetch))) (if (char-whitespace? c) (skip (fetch)) (set! index (fx- index 1)) ) ) (##sys#error loc "illegal format-string character" dchar) ) ) ) ) (##sys#write-char-0 c out) ) (loop) ) ) ) ) ) (cond ((not port) (get-output-string out)) ((not (eq? out port)) (##sys#print (get-output-string out) #f port) ) ) ) ) ) (define (fprintf port fstr . args) (fprintf0 'fprintf port fstr args) ) (define (printf fstr . args) (fprintf0 'printf ##sys#standard-output fstr args) ) (define (sprintf fstr . args) (fprintf0 'sprintf #f fstr args) ) (define format (lambda (fmt-or-dst . args) (apply (cond [(not fmt-or-dst) sprintf] [(boolean? fmt-or-dst) printf] [(string? fmt-or-dst) (set! args (cons fmt-or-dst args)) sprintf] [(output-port? fmt-or-dst) (set! args (cons fmt-or-dst args)) fprintf] [else (##sys#error 'format "illegal destination" fmt-or-dst args)]) args) ) ) (register-feature! 'srfi-28)
null
https://raw.githubusercontent.com/bnoordhuis/chicken-core/56d30e3be095b6abe1bddcfe10505fa726a43bb5/extras.scm
scheme
extras.scm - Optional non-standard extensions All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 HOLDERS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Read expressions from file: Random numbers: wall clock time Line I/O: this is silly write-string method Extended I/O peeked? update port-position <procedure>(read-buffered [PORT])</procedure> Reads any remaining data buffered after previous read operations on {{PORT}}. If no remaining data is currently buffered, an empty string is returned. This procedure will never block. Currently only useful for string-, process- and tcp ports. read-buffered method read token of characters that satisfy a predicate write-string Binary I/O Pretty print: Distribution restrictions: none may have to split on multiple lines item3) item3) define formatting style (change these to suit your style) (pretty-print obj port) pretty prints 'obj' on 'port'. The current output port is used if 'port' is not specified. Write simple formatted output:
Copyright ( c ) 2008 - 2013 , The Chicken Team Copyright ( c ) 2000 - 2007 , THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR (declare (unit extras) (uses data-structures ports)) (declare (hide fprintf0 generic-write) ) (include "common-declarations.scm") (register-feature! 'extras) (define read-file (let ([read read] [call-with-input-file call-with-input-file] ) (lambda (#!optional (port ##sys#standard-input) (reader read) max) (define (slurp port) (do ((x (reader port) (reader port)) (i 0 (fx+ i 1)) (xs '() (cons x xs)) ) ((or (eof-object? x) (and max (fx>= i max))) (##sys#fast-reverse xs)) ) ) (if (port? port) (slurp port) (call-with-input-file port slurp) ) ) ) ) (define (randomize . n) (let ((nn (if (null? n) (car n)))) (##sys#check-exact nn 'randomize) (##core#inline "C_randomize" nn) ) ) (define (random n) (##sys#check-exact n 'random) (if (eq? n 0) 0 (##core#inline "C_random_fixnum" n) ) ) (define read-line (let () (define (fixup str len) (##sys#substring str 0 (if (and (fx>= len 1) (char=? #\return (##core#inline "C_subchar" str (fx- len 1)))) (fx- len 1) len) ) ) (lambda args (let* ([parg (pair? args)] [p (if parg (car args) ##sys#standard-input)] [limit (and parg (pair? (cdr args)) (cadr args))]) (##sys#check-input-port p #t 'read-line) (cond ((##sys#slot (##sys#slot p 2) 8) => (lambda (rl) (rl p limit))) (else (let* ((buffer-len (if limit limit 256)) (buffer (##sys#make-string buffer-len))) (let loop ([i 0]) (if (and limit (fx>= i limit)) (##sys#substring buffer 0 i) (let ([c (##sys#read-char-0 p)]) (if (eof-object? c) (if (fx= i 0) c (##sys#substring buffer 0 i) ) (case c [(#\newline) (##sys#substring buffer 0 i)] [(#\return) (let ([c (peek-char p)]) (if (char=? c #\newline) (begin (##sys#read-char-0 p) (##sys#substring buffer 0 i)) (##sys#substring buffer 0 i) ) ) ] [else (when (fx>= i buffer-len) (set! buffer (##sys#string-append buffer (make-string buffer-len))) (set! buffer-len (fx+ buffer-len buffer-len)) ) (##core#inline "C_setsubchar" buffer i c) (loop (fx+ i 1)) ] ) ) ) ) ) ) ) ) ) ) ) ) (define read-lines (lambda port-and-max (let* ((port (if (pair? port-and-max) (##sys#slot port-and-max 0) ##sys#standard-input)) (rest (and (pair? port-and-max) (##sys#slot port-and-max 1))) (max (if (pair? rest) (##sys#slot rest 0) #f)) ) (define (doread port) (let loop ((lns '()) (if (eq? n 0) (##sys#fast-reverse lns) (let ((ln (read-line port))) (if (eof-object? ln) (##sys#fast-reverse lns) (loop (cons ln lns) (fx- n 1)) ) ) ) ) ) (if (string? port) (call-with-input-file port doread) (begin (##sys#check-input-port port #t 'read-lines) (doread port) ) ) ) ) ) (define write-line (lambda (str . port) (let* ((p (if (##core#inline "C_eqp" port '()) ##sys#standard-output (##sys#slot port 0) ) )) (##sys#check-output-port p #t 'write-line) (##sys#check-string str 'write-line) (##sys#write-char-0 #\newline p)))) (define (##sys#read-string! n dest port start) (cond ((eq? n 0) 0) (else (##core#inline "C_setsubchar" dest start (##sys#read-char-0 port)) (set! start (fx+ start 1)) ) (let ((rdstring (##sys#slot (##sys#slot port 2) 7))) (if rdstring (let loop ((start start) (n n) (m 0)) (let ((n2 (rdstring port n dest start))) (fx+ (##sys#slot port 5) n2)) (cond ((eq? n2 0) m) ((or (not n) (fx< n2 n)) (loop (fx+ start n2) (and n (fx- n n2)) (fx+ m n2))) (else (fx+ n2 m))))) (let loop ((start start) (n n) (m 0)) (let ((n2 (let ((c (##sys#read-char-0 port))) (if (eof-object? c) 0 (begin (##core#inline "C_setsubchar" dest start c) 1) ) ) ) ) (cond ((eq? n2 0) m) ((or (not n) (fx< n2 n)) (loop (fx+ start n2) (and n (fx- n n2)) (fx+ m n2)) ) (else (fx+ n2 m))) ))))))) (define (read-string! n dest #!optional (port ##sys#standard-input) (start 0)) (##sys#check-input-port port #t 'read-string!) (##sys#check-string dest 'read-string!) (when n (##sys#check-exact n 'read-string!) (when (fx> (fx+ start n) (##sys#size dest)) (set! n (fx- (##sys#size dest) start)))) (##sys#check-exact start 'read-string!) (##sys#read-string! n dest port start) ) (define-constant read-string-buffer-size 2048) (define ##sys#read-string/port (lambda (n p) (##sys#check-input-port p #t 'read-string) (cond (n (##sys#check-exact n 'read-string) (let* ((str (##sys#make-string n)) (n2 (##sys#read-string! n str p 0)) ) (if (eq? n n2) str (##sys#substring str 0 n2)))) (else (let ([out (open-output-string)] (buf (make-string read-string-buffer-size))) (let loop () (let ((n (##sys#read-string! read-string-buffer-size buf p 0))) (cond ((eq? n 0) (get-output-string out)) (else (write-string buf n out) (loop)))))))))) (define (read-string #!optional n (port ##sys#standard-input)) (##sys#read-string/port n port) ) (define (read-buffered #!optional (port ##sys#standard-input)) (##sys#check-input-port port #t 'read-buffered) (if rb (rb port) ""))) (define read-token (lambda (pred . port) (let ([port (optional port ##sys#standard-input)]) (##sys#check-input-port port #t 'read-token) (let ([out (open-output-string)]) (let loop () (let ([c (##sys#peek-char-0 port)]) (if (and (not (eof-object? c)) (pred c)) (begin (##sys#write-char-0 (##sys#read-char-0 port) out) (loop) ) (get-output-string out) ) ) ) ) ) ) ) (define write-string (lambda (s . more) (##sys#check-string s 'write-string) (let-optionals more ([n #f] [port ##sys#standard-output]) (##sys#check-output-port port #t 'write-string) (when n (##sys#check-exact n 'write-string)) port (if (and n (fx< n (##sys#size s))) (##sys#substring s 0 n) s))))) (define (read-byte #!optional (port ##sys#standard-input)) (##sys#check-input-port port #t 'read-byte) (let ((x (##sys#read-char-0 port))) (if (eof-object? x) x (char->integer x) ) ) ) (define (write-byte byte #!optional (port ##sys#standard-output)) (##sys#check-exact byte 'write-byte) (##sys#check-output-port port #t 'write-byte) (##sys#write-char-0 (integer->char byte) port) ) Copyright ( c ) 1991 , Author : ( ) Modified by felix for use with CHICKEN (define generic-write (lambda (obj display? width output) (define (read-macro? l) (define (length1? l) (and (pair? l) (null? (cdr l)))) (let ((head (car l)) (tail (cdr l))) (case head ((quote quasiquote unquote unquote-splicing) (length1? tail)) (else #f)))) (define (read-macro-body l) (cadr l)) (define (read-macro-prefix l) (let ((head (car l)) (tail (cdr l))) (case head ((quote) "'") ((quasiquote) "`") ((unquote) ",") ((unquote-splicing) ",@")))) (define (out str col) (and col (output str) (+ col (string-length str)))) (define (wr obj col) (define (wr-expr expr col) (if (read-macro? expr) (wr (read-macro-body expr) (out (read-macro-prefix expr) col)) (wr-lst expr col))) (define (wr-lst l col) (if (pair? l) (let loop ((l (cdr l)) (col (and col (wr (car l) (out "(" col))))) (cond ((not col) col) ((pair? l) (loop (cdr l) (wr (car l) (out " " col)))) ((null? l) (out ")" col)) (else (out ")" (wr l (out " . " col)))))) (out "()" col))) (cond ((pair? obj) (wr-expr obj col)) ((null? obj) (wr-lst obj col)) ((eof-object? obj) (out "#!eof" col)) ((vector? obj) (wr-lst (vector->list obj) (out "#" col))) ((boolean? obj) (out (if obj "#t" "#f") col)) ((##sys#number? obj) (out (##sys#number->string obj) col)) ((symbol? obj) (let ([s (open-output-string)]) (##sys#print obj #t s) (out (get-output-string s) col) ) ) ((procedure? obj) (out (##sys#procedure->string obj) col)) ((string? obj) (if display? (out obj col) (let loop ((i 0) (j 0) (col (out "\"" col))) (if (and col (fx< j (string-length obj))) (let ((c (string-ref obj j))) (cond ((or (char=? c #\\) (char=? c #\")) (loop j (+ j 1) (out "\\" (out (##sys#substring obj i j) col)))) ((or (char<? c #\x20) (char=? c #\x7f)) (loop (fx+ j 1) (fx+ j 1) (let ((col2 (out (##sys#substring obj i j) col))) (cond ((assq c '((#\tab . "\\t") (#\newline . "\\n") (#\return . "\\r") (#\vtab . "\\v") (#\page . "\\f") (#\alarm . "\\a") (#\backspace . "\\b"))) => (lambda (a) (out (cdr a) col2))) (else (out (number->string (char->integer c) 16) (out (if (char<? c #\x10) "0" "") (out "\\x" col2)))))))) (else (loop i (fx+ j 1) col)))) (out "\"" (out (##sys#substring obj i j) col)))))) ((char? obj) (if display? (out (make-string 1 obj) col) (let ([code (char->integer obj)]) (out "#\\" col) (cond [(char-name obj) => (lambda (cn) (out (##sys#slot cn 1) col) ) ] [(fx< code 32) (out "x" col) (out (number->string code 16) col) ] [(fx> code 255) (out (if (fx> code #xffff) "U" "u") col) (out (number->string code 16) col) ] [else (out (make-string 1 obj) col)] ) ) ) ) ((##core#inline "C_undefinedp" obj) (out "#<unspecified>" col)) ((##core#inline "C_anypointerp" obj) (out (##sys#pointer->string obj) col)) ((eq? obj (##sys#slot '##sys#arbitrary-unbound-symbol 0)) (out "#<unbound value>" col) ) ((##sys#generic-structure? obj) (let ([o (open-output-string)]) (##sys#user-print-hook obj #t o) (out (get-output-string o) col) ) ) ((port? obj) (out (string-append "#<port " (##sys#slot obj 3) ">") col)) ((##core#inline "C_bytevectorp" obj) (out "#${" col) (let ((len (##sys#size obj))) (do ((i 0 (fx+ i 1))) ((fx>= i len)) (let ((b (##sys#byte obj i))) (when (fx< b 16) (out "0" col)) (out (##sys#number->string b 16) col))) (out "}" col))) ((##core#inline "C_lambdainfop" obj) (out "#<lambda info " col) (out (##sys#lambda-info->string obj) col) (out ">" col) ) (else (out "#<unprintable object>" col)) ) ) (define (pp obj col) (define (spaces n col) (if (> n 0) (if (> n 7) (spaces (- n 8) (out " " col)) (out (##sys#substring " " 0 n) col)) col)) (define (indent to col) (and col (if (< to col) (and (out (make-string 1 #\newline) col) (spaces to 0)) (spaces (- to col) col)))) (define (pr obj col extra pp-pair) (let ((result '()) (left (max (+ (- (- width col) extra) 1) max-expr-width))) (generic-write obj display? #f (lambda (str) (set! result (cons str result)) (set! left (- left (string-length str))) (> left 0))) all can be printed on one line (out (reverse-string-append result) col) (if (pair? obj) (pp-pair obj col extra) (pp-list (vector->list obj) (out "#" col) extra pp-expr)))) (wr obj col))) (define (pp-expr expr col extra) (if (read-macro? expr) (pr (read-macro-body expr) (out (read-macro-prefix expr) col) extra pp-expr) (let ((head (car expr))) (if (symbol? head) (let ((proc (style head))) (if proc (proc expr col extra) (if (> (string-length (##sys#symbol->qualified-string head)) max-call-head-width) (pp-general expr col extra #f #f #f pp-expr) (pp-call expr col extra pp-expr)))) (pp-list expr col extra pp-expr))))) ( head (define (pp-call expr col extra pp-item) (let ((col* (wr (car expr) (out "(" col)))) (and col (pp-down (cdr expr) col* (+ col* 1) extra pp-item)))) ( (define (pp-list l col extra pp-item) (let ((col (out "(" col))) (pp-down l col col extra pp-item))) (define (pp-down l col1 col2 extra pp-item) (let loop ((l l) (col col1)) (and col (cond ((pair? l) (let ((rest (cdr l))) (let ((extra (if (null? rest) (+ extra 1) 0))) (loop rest (pr (car l) (indent col2 col) extra pp-item))))) ((null? l) (out ")" col)) (else (out ")" (pr l (indent col2 (out "." (indent col2 col))) (+ extra 1) pp-item))))))) (define (pp-general expr col extra named? pp-1 pp-2 pp-3) (define (tail1 rest col1 col2 col3) (if (and pp-1 (pair? rest)) (let* ((val1 (car rest)) (rest (cdr rest)) (extra (if (null? rest) (+ extra 1) 0))) (tail2 rest col1 (pr val1 (indent col3 col2) extra pp-1) col3)) (tail2 rest col1 col2 col3))) (define (tail2 rest col1 col2 col3) (if (and pp-2 (pair? rest)) (let* ((val1 (car rest)) (rest (cdr rest)) (extra (if (null? rest) (+ extra 1) 0))) (tail3 rest col1 (pr val1 (indent col3 col2) extra pp-2))) (tail3 rest col1 col2))) (define (tail3 rest col1 col2) (pp-down rest col2 col1 extra pp-3)) (let* ((head (car expr)) (rest (cdr expr)) (col* (wr head (out "(" col)))) (if (and named? (pair? rest)) (let* ((name (car rest)) (rest (cdr rest)) (col** (wr name (out " " col*)))) (tail1 rest (+ col indent-general) col** (+ col** 1))) (tail1 rest (+ col indent-general) col* (+ col* 1))))) (define (pp-expr-list l col extra) (pp-list l col extra pp-expr)) (define (pp-lambda expr col extra) (pp-general expr col extra #f pp-expr-list #f pp-expr)) (define (pp-if expr col extra) (pp-general expr col extra #f pp-expr #f pp-expr)) (define (pp-cond expr col extra) (pp-call expr col extra pp-expr-list)) (define (pp-case expr col extra) (pp-general expr col extra #f pp-expr #f pp-expr-list)) (define (pp-and expr col extra) (pp-call expr col extra pp-expr)) (define (pp-let expr col extra) (let* ((rest (cdr expr)) (named? (and (pair? rest) (symbol? (car rest))))) (pp-general expr col extra named? pp-expr-list #f pp-expr))) (define (pp-begin expr col extra) (pp-general expr col extra #f #f #f pp-expr)) (define (pp-do expr col extra) (pp-general expr col extra #f pp-expr-list pp-expr-list pp-expr)) (define indent-general 2) (define max-call-head-width 5) (define max-expr-width 50) (define (style head) (case head ((lambda let* letrec define) pp-lambda) ((if set!) pp-if) ((cond) pp-cond) ((case) pp-case) ((and or) pp-and) ((let) pp-let) ((begin) pp-begin) ((do) pp-do) (else #f))) (pr obj col 0 pp-expr)) (if width (out (make-string 1 #\newline) (pp obj 0)) (wr obj 0)))) (define pretty-print-width (make-parameter 79)) (define (pretty-print obj . opt) (let ((port (if (pair? opt) (car opt) (current-output-port)))) (generic-write obj #f (pretty-print-width) (lambda (s) (display s port) #t)) (##core#undefined) ) ) (define pp pretty-print) (define fprintf0 (lambda (loc port msg args) (when port (##sys#check-output-port port #t loc)) (let ((out (if (and port (##sys#tty-port? port)) port (open-output-string)))) (let rec ([msg msg] [args args]) (##sys#check-string msg loc) (let ((index 0) (len (##sys#size msg)) ) (define (fetch) (let ((c (##core#inline "C_subchar" msg index))) (set! index (fx+ index 1)) c) ) (define (next) (if (##core#inline "C_eqp" args '()) (##sys#error loc "too few arguments to formatted output procedure") (let ((x (##sys#slot args 0))) (set! args (##sys#slot args 1)) x) ) ) (let loop () (unless (fx>= index len) (let ((c (fetch))) (if (and (eq? c #\~) (fx< index len)) (let ((dchar (fetch))) (case (char-upcase dchar) ((#\S) (write (next) out)) ((#\A) (display (next) out)) ((#\C) (##sys#write-char-0 (next) out)) ((#\B) (display (##sys#number->string (next) 2) out)) ((#\O) (display (##sys#number->string (next) 8) out)) ((#\X) (display (##sys#number->string (next) 16) out)) ((#\!) (##sys#flush-output out)) ((#\?) (let* ([fstr (next)] [lst (next)] ) (##sys#check-list lst loc) (rec fstr lst) out) ) ((#\~) (##sys#write-char-0 #\~ out)) ((#\% #\N) (newline out)) (else (if (char-whitespace? dchar) (let skip ((c (fetch))) (if (char-whitespace? c) (skip (fetch)) (set! index (fx- index 1)) ) ) (##sys#error loc "illegal format-string character" dchar) ) ) ) ) (##sys#write-char-0 c out) ) (loop) ) ) ) ) ) (cond ((not port) (get-output-string out)) ((not (eq? out port)) (##sys#print (get-output-string out) #f port) ) ) ) ) ) (define (fprintf port fstr . args) (fprintf0 'fprintf port fstr args) ) (define (printf fstr . args) (fprintf0 'printf ##sys#standard-output fstr args) ) (define (sprintf fstr . args) (fprintf0 'sprintf #f fstr args) ) (define format (lambda (fmt-or-dst . args) (apply (cond [(not fmt-or-dst) sprintf] [(boolean? fmt-or-dst) printf] [(string? fmt-or-dst) (set! args (cons fmt-or-dst args)) sprintf] [(output-port? fmt-or-dst) (set! args (cons fmt-or-dst args)) fprintf] [else (##sys#error 'format "illegal destination" fmt-or-dst args)]) args) ) ) (register-feature! 'srfi-28)
364a841dd93673c57f320a89a93209fda8f12a00b99f80674768d3ff829581bd
hipsleek/hipsleek
specutil.ml
#include "xdebug.cppo" open VarGen open Globals module DD = Debug open Gen open Exc.GTable open Cformula open Cpure open Cprinter module CP = Cpure module MCP = Mcpure module CF = Cformula module TP = Tpdispatcher module IF = Iformula module I = Iast module C = Cast type pure_dom = { para_names : spec_var list; TODO (* inductive_def : ...;*) } (******************************************************************************) let rec size_of_heap (fml:CF.h_formula) : (CP.exp*CP.p_formula list) = match fml with | Star {h_formula_star_h1 = h1; h_formula_star_h2 = h2; h_formula_star_pos = pos} -> let res1 = size_of_heap h1 in let res2 = size_of_heap h2 in (Add (fst res1,fst res2,pos), snd res1 @ snd res2) | Conj {h_formula_conj_h1 = h1; h_formula_conj_h2 = h2; h_formula_conj_pos = pos} -> let res1 = size_of_heap h1 in let res2 = size_of_heap h2 in (Add (fst res1,fst res2,pos), snd res1 @ snd res2) | Phase _ -> report_error no_pos "size_of_heap: Do not expect Phase" | DataNode _ -> (IConst (1,no_pos), []) | ViewNode vn -> let v = List.hd (List.rev vn.h_formula_view_arguments) in let p = Var (v,no_pos) in let rel = RelForm (SpecVar (RelT[], vn.h_formula_view_name, Unprimed), [p], no_pos) in (p,[rel]) | Hole _ -> report_error no_pos "size_of_heap: Do not expect Hole" | HRel _ -> report_error no_pos "size_of_heap: Do not expect HRel" | HTrue | HFalse | HEmp -> (IConst (0,no_pos),[]) let size_of_fml (fml:CF.formula) (lhs_para:CP.spec_var): (CF.formula * CP.formula) = match fml with | CF.Or _ -> report_error no_pos "size_of_fml: Do not expect Or formula" | CF.Base b -> let p,rel = size_of_heap b.formula_base_heap in let pure = mkEqExp (Var (lhs_para,no_pos)) p no_pos in let rels = List.map (fun r -> BForm ((r,None),None)) rel in let pure2 = List.fold_left (fun f1 f2 -> CP.mkAnd f1 f2 no_pos) pure rels in let mix = MCP.mix_of_pure (CP.mkAnd (MCP.pure_of_mix b.formula_base_pure) pure no_pos) in (CF.Base {b with formula_base_pure = mix}, pure2) | CF.Exists e -> let p,rel = size_of_heap e.formula_exists_heap in let pure = mkEqExp (Var (lhs_para,no_pos)) p no_pos in let rels = List.map (fun r -> BForm ((r,None),None)) rel in let pure2 = List.fold_left (fun f1 f2 -> CP.mkAnd f1 f2 no_pos) pure rels in let mix = MCP.mix_of_pure (CP.mkAnd (MCP.pure_of_mix e.formula_exists_pure) pure no_pos) in (CF.Exists {e with formula_exists_pure = mix}, pure2) let rec size_of (fml:CF.struc_formula) (lhs_para:CP.spec_var): (CF.struc_formula*CP.formula list) = match fml with | ECase b -> let res = List.map (fun (p,c) -> let r = size_of c lhs_para in ((p,fst r),snd r)) b.formula_case_branches in let r1,r2 = List.split res in (ECase {b with formula_case_branches = r1}, List.concat r2) | EBase b -> let rbase = size_of_fml b.formula_struc_base lhs_para in let rcont = (match b.formula_struc_continuation with | None -> (None,[]) | Some f -> let r = size_of f lhs_para in (Some (fst r),snd r)) in (EBase {b with formula_struc_base = fst rbase; formula_struc_continuation = fst rcont}, (snd rbase) :: (snd rcont)) | EAssume(svl,f,fl,t) -> let r = size_of_fml f lhs_para in (EAssume(svl,fst r,fl,t),[snd r]) | EInfer b -> let r = size_of b.formula_inf_continuation lhs_para in (EInfer {b with formula_inf_continuation = fst r}, snd r) | EList b -> let res = List.map (fun (l,e) -> let r = size_of e lhs_para in ((l,fst r),snd r)) b in let r1,r2 = List.split res in (EList r1,List.concat r2) | EOr b -> let r1 = size_of b.formula_struc_or_f1 lhs_para in let r2 = size_of b.formula_struc_or_f2 lhs_para in (EOr {b with formula_struc_or_f1 = fst r1; formula_struc_or_f2 = fst r2}, snd r1 @ snd r2) (******************************************************************************) let gen_struc_fml (orig_fml:CF.struc_formula) (abs_dom:pure_dom) sub_pair: (CF.struc_formula*CP.formula list) = let updated_fml = CF.tran_spec orig_fml sub_pair in let new_fml,new_pures = size_of (fst updated_fml) (List.hd abs_dom.para_names) in new_fml,new_pures (* TODO: abs_dom *) Primitive case : size ( ) . See more in gen_pred.txt let gen_pred_def (orig_def:C.view_decl) (abs_dom:pure_dom): C.view_decl = let new_view_name = fresh_old_name orig_def.C.view_name in let new_view_vars = orig_def.C.view_vars @ abs_dom.para_names in let sub_pair = ((orig_def.C.view_name,orig_def.C.view_vars),(new_view_name,new_view_vars)) in let new_fml,new_pures = gen_struc_fml orig_def.C.view_formula abs_dom sub_pair in let additional_inv = Fixcalc.compute_pure_inv new_pures new_view_name abs_dom.para_names in let new_inv = MCP.mix_of_pure (CP.mkAnd (MCP.pure_of_mix orig_def.C.view_user_inv) additional_inv no_pos) in let new_def = {orig_def with C.view_name = new_view_name; C.view_vars = new_view_vars; C.view_formula = new_fml; C.view_user_inv = new_inv;} in new_def let string_of_view_decl v = let rec string_of_elems elems string_of sep = match elems with | [] -> "" | h::[] -> string_of h | h::t -> (string_of h) ^ sep ^ (string_of_elems t string_of sep) in v.C.view_name ^ "<" ^ (string_of_elems v.C.view_vars string_of_spec_var ",") ^ "> == " ^ (string_of_struc_formula v.C.view_formula) ^ "inv " ^ (string_of_mix_formula v.C.view_user_inv) ^ ";" let test prog = let orig_def = List.hd prog.C.prog_view_decls in let () = print_endline_quiet ("\n\n" ^ string_of_view_decl orig_def) in let () = print_endline_quiet "\n\n" in let abs_dom = {para_names = [SpecVar (Int, "n", Unprimed)]} in let new_def = gen_pred_def orig_def abs_dom in print_endline_quiet (string_of_view_decl new_def)
null
https://raw.githubusercontent.com/hipsleek/hipsleek/596f7fa7f67444c8309da2ca86ba4c47d376618c/bef_indent/specutil.ml
ocaml
inductive_def : ...; **************************************************************************** **************************************************************************** TODO: abs_dom
#include "xdebug.cppo" open VarGen open Globals module DD = Debug open Gen open Exc.GTable open Cformula open Cpure open Cprinter module CP = Cpure module MCP = Mcpure module CF = Cformula module TP = Tpdispatcher module IF = Iformula module I = Iast module C = Cast type pure_dom = { para_names : spec_var list; TODO } let rec size_of_heap (fml:CF.h_formula) : (CP.exp*CP.p_formula list) = match fml with | Star {h_formula_star_h1 = h1; h_formula_star_h2 = h2; h_formula_star_pos = pos} -> let res1 = size_of_heap h1 in let res2 = size_of_heap h2 in (Add (fst res1,fst res2,pos), snd res1 @ snd res2) | Conj {h_formula_conj_h1 = h1; h_formula_conj_h2 = h2; h_formula_conj_pos = pos} -> let res1 = size_of_heap h1 in let res2 = size_of_heap h2 in (Add (fst res1,fst res2,pos), snd res1 @ snd res2) | Phase _ -> report_error no_pos "size_of_heap: Do not expect Phase" | DataNode _ -> (IConst (1,no_pos), []) | ViewNode vn -> let v = List.hd (List.rev vn.h_formula_view_arguments) in let p = Var (v,no_pos) in let rel = RelForm (SpecVar (RelT[], vn.h_formula_view_name, Unprimed), [p], no_pos) in (p,[rel]) | Hole _ -> report_error no_pos "size_of_heap: Do not expect Hole" | HRel _ -> report_error no_pos "size_of_heap: Do not expect HRel" | HTrue | HFalse | HEmp -> (IConst (0,no_pos),[]) let size_of_fml (fml:CF.formula) (lhs_para:CP.spec_var): (CF.formula * CP.formula) = match fml with | CF.Or _ -> report_error no_pos "size_of_fml: Do not expect Or formula" | CF.Base b -> let p,rel = size_of_heap b.formula_base_heap in let pure = mkEqExp (Var (lhs_para,no_pos)) p no_pos in let rels = List.map (fun r -> BForm ((r,None),None)) rel in let pure2 = List.fold_left (fun f1 f2 -> CP.mkAnd f1 f2 no_pos) pure rels in let mix = MCP.mix_of_pure (CP.mkAnd (MCP.pure_of_mix b.formula_base_pure) pure no_pos) in (CF.Base {b with formula_base_pure = mix}, pure2) | CF.Exists e -> let p,rel = size_of_heap e.formula_exists_heap in let pure = mkEqExp (Var (lhs_para,no_pos)) p no_pos in let rels = List.map (fun r -> BForm ((r,None),None)) rel in let pure2 = List.fold_left (fun f1 f2 -> CP.mkAnd f1 f2 no_pos) pure rels in let mix = MCP.mix_of_pure (CP.mkAnd (MCP.pure_of_mix e.formula_exists_pure) pure no_pos) in (CF.Exists {e with formula_exists_pure = mix}, pure2) let rec size_of (fml:CF.struc_formula) (lhs_para:CP.spec_var): (CF.struc_formula*CP.formula list) = match fml with | ECase b -> let res = List.map (fun (p,c) -> let r = size_of c lhs_para in ((p,fst r),snd r)) b.formula_case_branches in let r1,r2 = List.split res in (ECase {b with formula_case_branches = r1}, List.concat r2) | EBase b -> let rbase = size_of_fml b.formula_struc_base lhs_para in let rcont = (match b.formula_struc_continuation with | None -> (None,[]) | Some f -> let r = size_of f lhs_para in (Some (fst r),snd r)) in (EBase {b with formula_struc_base = fst rbase; formula_struc_continuation = fst rcont}, (snd rbase) :: (snd rcont)) | EAssume(svl,f,fl,t) -> let r = size_of_fml f lhs_para in (EAssume(svl,fst r,fl,t),[snd r]) | EInfer b -> let r = size_of b.formula_inf_continuation lhs_para in (EInfer {b with formula_inf_continuation = fst r}, snd r) | EList b -> let res = List.map (fun (l,e) -> let r = size_of e lhs_para in ((l,fst r),snd r)) b in let r1,r2 = List.split res in (EList r1,List.concat r2) | EOr b -> let r1 = size_of b.formula_struc_or_f1 lhs_para in let r2 = size_of b.formula_struc_or_f2 lhs_para in (EOr {b with formula_struc_or_f1 = fst r1; formula_struc_or_f2 = fst r2}, snd r1 @ snd r2) let gen_struc_fml (orig_fml:CF.struc_formula) (abs_dom:pure_dom) sub_pair: (CF.struc_formula*CP.formula list) = let updated_fml = CF.tran_spec orig_fml sub_pair in let new_fml,new_pures = size_of (fst updated_fml) (List.hd abs_dom.para_names) in new_fml,new_pures Primitive case : size ( ) . See more in gen_pred.txt let gen_pred_def (orig_def:C.view_decl) (abs_dom:pure_dom): C.view_decl = let new_view_name = fresh_old_name orig_def.C.view_name in let new_view_vars = orig_def.C.view_vars @ abs_dom.para_names in let sub_pair = ((orig_def.C.view_name,orig_def.C.view_vars),(new_view_name,new_view_vars)) in let new_fml,new_pures = gen_struc_fml orig_def.C.view_formula abs_dom sub_pair in let additional_inv = Fixcalc.compute_pure_inv new_pures new_view_name abs_dom.para_names in let new_inv = MCP.mix_of_pure (CP.mkAnd (MCP.pure_of_mix orig_def.C.view_user_inv) additional_inv no_pos) in let new_def = {orig_def with C.view_name = new_view_name; C.view_vars = new_view_vars; C.view_formula = new_fml; C.view_user_inv = new_inv;} in new_def let string_of_view_decl v = let rec string_of_elems elems string_of sep = match elems with | [] -> "" | h::[] -> string_of h | h::t -> (string_of h) ^ sep ^ (string_of_elems t string_of sep) in v.C.view_name ^ "<" ^ (string_of_elems v.C.view_vars string_of_spec_var ",") ^ "> == " ^ (string_of_struc_formula v.C.view_formula) ^ "inv " ^ (string_of_mix_formula v.C.view_user_inv) ^ ";" let test prog = let orig_def = List.hd prog.C.prog_view_decls in let () = print_endline_quiet ("\n\n" ^ string_of_view_decl orig_def) in let () = print_endline_quiet "\n\n" in let abs_dom = {para_names = [SpecVar (Int, "n", Unprimed)]} in let new_def = gen_pred_def orig_def abs_dom in print_endline_quiet (string_of_view_decl new_def)
b7440cac194439776b3678b03b194138d456c9811d53782ea79d450521a0d7fe
dradtke/Lisp-Text-Editor
context.lisp
(in-package :cl-cairo2) ;;;; Notes ;;;; ;;;; need to write: cairo - get - target ;;;; push-group-with-content ;;;; get-group-target ;;;; ;;;; ;;;; not sure anyone needs: ;;;; get/set-user-data ;;;; get-reference-count ;;;; ;;;; context class ;;;; (defclass context (cairo-object) ((width :initarg :width :reader width) (height :initarg :height :reader height) (pixel-based-p :initarg :pixel-based-p :reader pixel-based-p))) (define-foreign-type context-type () () (:actual-type :pointer) (:simple-parser context)) (defmethod translate-to-foreign (context (type context-type)) (get-pointer context)) (defmethod expand-to-foreign (context (type context-type)) `(get-pointer ,context)) (defvar *context* nil "The default context for cl-cairo2 functions.") (defmacro with-context ((context) &body body) "Set *context* to context for body." `(let ((*context* ,context)) ,@body)) (defmethod lowlevel-destroy ((context context)) (cairo_destroy (get-pointer context))) (defmethod lowlevel-status ((context context)) (lookup-cairo-enum (cairo_status (get-pointer context)) table-status)) (defmethod print-object ((obj context) stream) "Print a context object." (print-unreadable-object (obj stream :type t) (with-slots (pointer width height pixel-based-p) obj (format stream "pointer: ~a, width: ~a, height: ~a, pixel-based-p: ~a" pointer width height pixel-based-p)))) (defun create-context (surface) (with-cairo-object (surface pointer) (let* ((context (make-instance 'context :pointer (cairo_create pointer) :width (width surface) :height (height surface) :pixel-based-p (pixel-based-p surface))) (context-pointer (slot-value context 'pointer))) ;; register finalizer it HAS to be CAIRO_DESTROY , not LOWLEVEL - DESTROY , ;; since: ;; 1) we're not allowed to access the object in the finaliser 2 ) doing so creates a ref that will prevent the finaliser ;; from ever running (tg:finalize context #'(lambda () (cairo_destroy context-pointer)))))) cairo - objects ' destroy calling lowlevel - destroy should suffice . todo : check this ;(defmethod destroy ((object context)) ; (with-slots (pointer) object ; (when pointer ; (cairo_destroy pointer) ( setf pointer nil ) ) ) ; ;; deregister finalizer ; (tg:cancel-finalization object)) (defgeneric sync (object) (:documentation "Synchronize contents of the object with the physical device if needed.")) (defgeneric sync-lock (object) (:documentation "Suspend syncing (ie sync will have no effect) until sync-unlock is called. Calls to sync-lock nest.")) (defgeneric sync-unlock (object) (:documentation "Undo a call to sync-lock.")) (defgeneric sync-reset (object) (:documentation "Undo all calls to sync, ie object will be synced (if necessary) no matter how many times sync was called before.")) ;; most contexts don't need syncing (defmethod sync ((object context))) (defmethod sync-lock ((object context))) (defmethod sync-unlock ((object context))) (defmethod sync-reset ((object context))) (defmacro with-sync-lock ((context) &body body) "Lock sync for context for the duration of body. Protected against nonlocal exits." (once-only (context) `(progn (sync-lock ,context) (unwind-protect (progn ,@body) (sync-unlock ,context))))) ;;;; ;;;; default context and convenience macros ;;;; (defmacro with-png-file ((filename format width height &key (surface (gensym)) (context '*context*)) &body body) "Execute the body with context (defaults to *context*) bound to a newly created png file, and close it after executing body. The surface will be bound to surface-name." (check-type context symbol) (check-type surface symbol) `(let* ((,surface (create-image-surface ,format ,width ,height)) (,context (create-context ,surface))) (unwind-protect (progn ,@body) (progn (surface-write-to-png ,surface ,filename) (destroy ,context) (destroy ,surface))))) (defmacro with-context-pointer ((context pointer) &body body) "Execute body with pointer pointing to context, and check status." (let ((status (gensym)) (pointer-name pointer)) `(with-slots ((,pointer-name pointer)) ,context (if ,pointer-name (multiple-value-prog1 (progn ,@body) (let ((,status (lookup-cairo-enum (cairo_status ,pointer-name) table-status))) (unless (eq ,status :success) (warn "function returned with status ~a." ,status)))) (warn "context is not alive"))))) (defmacro define-with-default-context (name &rest args) "Define cairo function with context as its last optional argument (defaulting to *context*) and args as the rest, automatically mapping name to the appropriate cairo function." `(defun ,name (,@args &optional (context *context*)) (with-context-pointer (context pointer) (,(prepend-intern "cairo_" name) pointer ,@args)))) (defmacro define-with-default-context-sync (name &rest args) "Define cairo function with context as its last keyword argument (defaulting to *context*) and args as the rest, automatically mapping name to the appropriate cairo function. sync will be called after the operation." `(defun ,name (,@args &optional (context *context*)) (with-context-pointer (context pointer) (,(prepend-intern "cairo_" name) pointer ,@args)) (sync context))) (defmacro define-flexible ((name pointer &rest args) &body body) "Like define-with-default-context, but with arbitrary body, pointer will point to the context." `(defun ,name (,@args &optional (context *context*)) (with-context-pointer (context ,pointer) ,@body))) (defmacro define-many-with-default-context (&body args) "Apply define-with-default context to a list. Each item is itself a list, first element gives the function name, the rest the arguments." `(progn ,@(loop for arglist in args collect `(define-with-default-context ,(car arglist) ,@(cdr arglist))))) (defmacro define-get-set (property) "Define set-property and get-property functions." `(progn (define-with-default-context ,(prepend-intern "get-" property :replace-dash nil)) (define-with-default-context ,(prepend-intern "set-" property :replace-dash nil) ,property))) (defmacro define-get-set-using-table (property) "Define set-property and get-property functions, where property is looked up in table-property for conversion into Cairo's enum constants." `(progn (define-flexible (,(prepend-intern "get-" property :replace-dash nil) pointer) (lookup-cairo-enum (,(prepend-intern "cairo_get_" property) pointer) ,(prepend-intern "table-" property :replace-dash nil))) (define-flexible (,(prepend-intern "set-" property :replace-dash nil) pointer ,property) (,(prepend-intern "cairo_set_" property) pointer (lookup-enum ,property ,(prepend-intern "table-" property :replace-dash nil)))))) ;;;; ;;;; simple functions using context ;;;; (define-many-with-default-context (save) (restore) (push-group) (pop-group) (pop-group-to-source) (set-source-rgb red green blue) (set-source-rgba red green blue alpha) (clip) (clip-preserve) (reset-clip) (copy-page) (show-page)) (define-with-default-context-sync fill-preserve) (define-with-default-context-sync paint) (define-with-default-context-sync paint-with-alpha alpha) (define-with-default-context-sync stroke) (define-with-default-context-sync stroke-preserve) (define-flexible (mask-surface context-pointer surface x y) (with-alive-object (surface surface-pointer) (with-checked-status surface (cairo_mask_surface context-pointer surface-pointer x y)))) (defun set-source-surface (image x y &optional (context *context*)) (with-alive-object (image i-pointer) (with-context-pointer (context c-pointer) (cairo_set_source_surface c-pointer i-pointer x y)))) ;;;; get-target (defun get-target (context) "Obtain the target surface of a given context. Width and height will be nil, as cairo can't provide that in general." (new-surface-with-check (cairo_get_target (slot-value context 'pointer)) nil nil nil t)) ;;;; ;;;; set colors using the cl-colors library ;;;; (defgeneric set-source-color (color &optional context)) (defmethod set-source-color ((color rgb) &optional (context *context*)) (with-slots (red green blue) color (set-source-rgb red green blue context))) (defmethod set-source-color ((color rgba) &optional (context *context*)) (with-slots (red green blue alpha) color (set-source-rgba red green blue alpha context))) (defmethod set-source-color ((color hsv) &optional (context *context*)) (with-slots (red green blue) (hsv->rgb color) (set-source-rgb red green blue context))) ;;;; ;;;; functions that get/set a property without any conversion ;;;; (define-get-set line-width) (define-get-set miter-limit) (define-get-set tolerance) ;;;; ;;;; functions that get/set a property using a lookup table ;;;; (define-get-set-using-table antialias) (define-get-set-using-table fill-rule) (define-get-set-using-table line-cap) (define-get-set-using-table line-join) (define-get-set-using-table operator) ;; fill-path: it should simply be fill, but it is renamed so it does ;; not clash with cl-user:fill (define-flexible (fill-path pointer) (cairo_fill pointer) (sync context)) (define-flexible (set-dash pointer offset dashes) (let ((num-dashes (length dashes))) (with-foreign-object (dashes-pointer :double num-dashes) (copy-double-vector-to-pointer (coerce dashes 'vector) dashes-pointer) (cairo_set_dash pointer dashes-pointer num-dashes offset)))) (define-flexible (get-dash pointer) "Return two values: dashes as a vector and the offset." (let ((num-dashes (cairo_get_dash_count pointer))) (with-foreign-objects ((dashes-pointer :double num-dashes) (offset-pointer :double)) (cairo_get_dash pointer dashes-pointer offset-pointer) (values (copy-pointer-to-double-vector num-dashes dashes-pointer) (mem-ref offset-pointer :double))))) (defmacro define-get-extents (name) "Define functions that query two coordinate pairs." `(define-flexible (,name pointer) (with-foreign-objects ((x1 :double) (y1 :double) (x2 :double) (y2 :double)) (,(prepend-intern "cairo_" name) pointer x1 y1 x2 y2) (values (mem-ref x1 :double) (mem-ref y1 :double) (mem-ref x2 :double) (mem-ref y2 :double))))) (define-get-extents clip-extents) (define-get-extents fill-extents) (define-flexible (in-fill pointer x y) (not (zerop (cairo_in_fill pointer x y)))) (define-flexible (in-stroke pointer x y) (not (zerop (cairo_in_stroke pointer x y)))) (define-flexible (in-clip pointer x y) (not (zerop (cairo_in_clip pointer x y)))) ;;;; ;;;; convenience functions for creating contexts directly ;;;; (defmacro define-create-context (type) `(defun ,(prepend-intern "create-" type :replace-dash nil :suffix "-context") (filename width height) "Create a surface, then a context for a file, then destroy (dereference) the surface. The user only needs to destroy the context when done." (let* ((surface (,(prepend-intern "create-" type :replace-dash nil :suffix "-surface") filename width height)) (context (create-context surface))) (destroy surface) context))) (define-create-context ps) (define-create-context pdf) (define-create-context svg) ;;;; a help macro for deprecating fns with define - compiler - macro ;;;; (defmacro deprecate (oldfn newfn &rest args) (format *error-output* "~&WARNING: ~A is deprecated. Use ~A instead.~%" oldfn newfn) (if (< 0 (length args)) `(,newfn ,@args) `(,newfn)))
null
https://raw.githubusercontent.com/dradtke/Lisp-Text-Editor/b0947828eda82d7edd0df8ec2595e7491a633580/quicklisp/dists/quicklisp/software/cl-cairo2-20120208-git/src/context.lisp
lisp
need to write: push-group-with-content get-group-target not sure anyone needs: get/set-user-data get-reference-count context class register finalizer since: 1) we're not allowed to access the object in the finaliser from ever running (defmethod destroy ((object context)) (with-slots (pointer) object (when pointer (cairo_destroy pointer) ;; deregister finalizer (tg:cancel-finalization object)) most contexts don't need syncing default context and convenience macros simple functions using context get-target set colors using the cl-colors library functions that get/set a property without any conversion functions that get/set a property using a lookup table fill-path: it should simply be fill, but it is renamed so it does not clash with cl-user:fill convenience functions for creating contexts directly
(in-package :cl-cairo2) Notes cairo - get - target (defclass context (cairo-object) ((width :initarg :width :reader width) (height :initarg :height :reader height) (pixel-based-p :initarg :pixel-based-p :reader pixel-based-p))) (define-foreign-type context-type () () (:actual-type :pointer) (:simple-parser context)) (defmethod translate-to-foreign (context (type context-type)) (get-pointer context)) (defmethod expand-to-foreign (context (type context-type)) `(get-pointer ,context)) (defvar *context* nil "The default context for cl-cairo2 functions.") (defmacro with-context ((context) &body body) "Set *context* to context for body." `(let ((*context* ,context)) ,@body)) (defmethod lowlevel-destroy ((context context)) (cairo_destroy (get-pointer context))) (defmethod lowlevel-status ((context context)) (lookup-cairo-enum (cairo_status (get-pointer context)) table-status)) (defmethod print-object ((obj context) stream) "Print a context object." (print-unreadable-object (obj stream :type t) (with-slots (pointer width height pixel-based-p) obj (format stream "pointer: ~a, width: ~a, height: ~a, pixel-based-p: ~a" pointer width height pixel-based-p)))) (defun create-context (surface) (with-cairo-object (surface pointer) (let* ((context (make-instance 'context :pointer (cairo_create pointer) :width (width surface) :height (height surface) :pixel-based-p (pixel-based-p surface))) (context-pointer (slot-value context 'pointer))) it HAS to be CAIRO_DESTROY , not LOWLEVEL - DESTROY , 2 ) doing so creates a ref that will prevent the finaliser (tg:finalize context #'(lambda () (cairo_destroy context-pointer)))))) cairo - objects ' destroy calling lowlevel - destroy should suffice . todo : check this ( setf pointer nil ) ) ) (defgeneric sync (object) (:documentation "Synchronize contents of the object with the physical device if needed.")) (defgeneric sync-lock (object) (:documentation "Suspend syncing (ie sync will have no effect) until sync-unlock is called. Calls to sync-lock nest.")) (defgeneric sync-unlock (object) (:documentation "Undo a call to sync-lock.")) (defgeneric sync-reset (object) (:documentation "Undo all calls to sync, ie object will be synced (if necessary) no matter how many times sync was called before.")) (defmethod sync ((object context))) (defmethod sync-lock ((object context))) (defmethod sync-unlock ((object context))) (defmethod sync-reset ((object context))) (defmacro with-sync-lock ((context) &body body) "Lock sync for context for the duration of body. Protected against nonlocal exits." (once-only (context) `(progn (sync-lock ,context) (unwind-protect (progn ,@body) (sync-unlock ,context))))) (defmacro with-png-file ((filename format width height &key (surface (gensym)) (context '*context*)) &body body) "Execute the body with context (defaults to *context*) bound to a newly created png file, and close it after executing body. The surface will be bound to surface-name." (check-type context symbol) (check-type surface symbol) `(let* ((,surface (create-image-surface ,format ,width ,height)) (,context (create-context ,surface))) (unwind-protect (progn ,@body) (progn (surface-write-to-png ,surface ,filename) (destroy ,context) (destroy ,surface))))) (defmacro with-context-pointer ((context pointer) &body body) "Execute body with pointer pointing to context, and check status." (let ((status (gensym)) (pointer-name pointer)) `(with-slots ((,pointer-name pointer)) ,context (if ,pointer-name (multiple-value-prog1 (progn ,@body) (let ((,status (lookup-cairo-enum (cairo_status ,pointer-name) table-status))) (unless (eq ,status :success) (warn "function returned with status ~a." ,status)))) (warn "context is not alive"))))) (defmacro define-with-default-context (name &rest args) "Define cairo function with context as its last optional argument (defaulting to *context*) and args as the rest, automatically mapping name to the appropriate cairo function." `(defun ,name (,@args &optional (context *context*)) (with-context-pointer (context pointer) (,(prepend-intern "cairo_" name) pointer ,@args)))) (defmacro define-with-default-context-sync (name &rest args) "Define cairo function with context as its last keyword argument (defaulting to *context*) and args as the rest, automatically mapping name to the appropriate cairo function. sync will be called after the operation." `(defun ,name (,@args &optional (context *context*)) (with-context-pointer (context pointer) (,(prepend-intern "cairo_" name) pointer ,@args)) (sync context))) (defmacro define-flexible ((name pointer &rest args) &body body) "Like define-with-default-context, but with arbitrary body, pointer will point to the context." `(defun ,name (,@args &optional (context *context*)) (with-context-pointer (context ,pointer) ,@body))) (defmacro define-many-with-default-context (&body args) "Apply define-with-default context to a list. Each item is itself a list, first element gives the function name, the rest the arguments." `(progn ,@(loop for arglist in args collect `(define-with-default-context ,(car arglist) ,@(cdr arglist))))) (defmacro define-get-set (property) "Define set-property and get-property functions." `(progn (define-with-default-context ,(prepend-intern "get-" property :replace-dash nil)) (define-with-default-context ,(prepend-intern "set-" property :replace-dash nil) ,property))) (defmacro define-get-set-using-table (property) "Define set-property and get-property functions, where property is looked up in table-property for conversion into Cairo's enum constants." `(progn (define-flexible (,(prepend-intern "get-" property :replace-dash nil) pointer) (lookup-cairo-enum (,(prepend-intern "cairo_get_" property) pointer) ,(prepend-intern "table-" property :replace-dash nil))) (define-flexible (,(prepend-intern "set-" property :replace-dash nil) pointer ,property) (,(prepend-intern "cairo_set_" property) pointer (lookup-enum ,property ,(prepend-intern "table-" property :replace-dash nil)))))) (define-many-with-default-context (save) (restore) (push-group) (pop-group) (pop-group-to-source) (set-source-rgb red green blue) (set-source-rgba red green blue alpha) (clip) (clip-preserve) (reset-clip) (copy-page) (show-page)) (define-with-default-context-sync fill-preserve) (define-with-default-context-sync paint) (define-with-default-context-sync paint-with-alpha alpha) (define-with-default-context-sync stroke) (define-with-default-context-sync stroke-preserve) (define-flexible (mask-surface context-pointer surface x y) (with-alive-object (surface surface-pointer) (with-checked-status surface (cairo_mask_surface context-pointer surface-pointer x y)))) (defun set-source-surface (image x y &optional (context *context*)) (with-alive-object (image i-pointer) (with-context-pointer (context c-pointer) (cairo_set_source_surface c-pointer i-pointer x y)))) (defun get-target (context) "Obtain the target surface of a given context. Width and height will be nil, as cairo can't provide that in general." (new-surface-with-check (cairo_get_target (slot-value context 'pointer)) nil nil nil t)) (defgeneric set-source-color (color &optional context)) (defmethod set-source-color ((color rgb) &optional (context *context*)) (with-slots (red green blue) color (set-source-rgb red green blue context))) (defmethod set-source-color ((color rgba) &optional (context *context*)) (with-slots (red green blue alpha) color (set-source-rgba red green blue alpha context))) (defmethod set-source-color ((color hsv) &optional (context *context*)) (with-slots (red green blue) (hsv->rgb color) (set-source-rgb red green blue context))) (define-get-set line-width) (define-get-set miter-limit) (define-get-set tolerance) (define-get-set-using-table antialias) (define-get-set-using-table fill-rule) (define-get-set-using-table line-cap) (define-get-set-using-table line-join) (define-get-set-using-table operator) (define-flexible (fill-path pointer) (cairo_fill pointer) (sync context)) (define-flexible (set-dash pointer offset dashes) (let ((num-dashes (length dashes))) (with-foreign-object (dashes-pointer :double num-dashes) (copy-double-vector-to-pointer (coerce dashes 'vector) dashes-pointer) (cairo_set_dash pointer dashes-pointer num-dashes offset)))) (define-flexible (get-dash pointer) "Return two values: dashes as a vector and the offset." (let ((num-dashes (cairo_get_dash_count pointer))) (with-foreign-objects ((dashes-pointer :double num-dashes) (offset-pointer :double)) (cairo_get_dash pointer dashes-pointer offset-pointer) (values (copy-pointer-to-double-vector num-dashes dashes-pointer) (mem-ref offset-pointer :double))))) (defmacro define-get-extents (name) "Define functions that query two coordinate pairs." `(define-flexible (,name pointer) (with-foreign-objects ((x1 :double) (y1 :double) (x2 :double) (y2 :double)) (,(prepend-intern "cairo_" name) pointer x1 y1 x2 y2) (values (mem-ref x1 :double) (mem-ref y1 :double) (mem-ref x2 :double) (mem-ref y2 :double))))) (define-get-extents clip-extents) (define-get-extents fill-extents) (define-flexible (in-fill pointer x y) (not (zerop (cairo_in_fill pointer x y)))) (define-flexible (in-stroke pointer x y) (not (zerop (cairo_in_stroke pointer x y)))) (define-flexible (in-clip pointer x y) (not (zerop (cairo_in_clip pointer x y)))) (defmacro define-create-context (type) `(defun ,(prepend-intern "create-" type :replace-dash nil :suffix "-context") (filename width height) "Create a surface, then a context for a file, then destroy (dereference) the surface. The user only needs to destroy the context when done." (let* ((surface (,(prepend-intern "create-" type :replace-dash nil :suffix "-surface") filename width height)) (context (create-context surface))) (destroy surface) context))) (define-create-context ps) (define-create-context pdf) (define-create-context svg) a help macro for deprecating fns with define - compiler - macro (defmacro deprecate (oldfn newfn &rest args) (format *error-output* "~&WARNING: ~A is deprecated. Use ~A instead.~%" oldfn newfn) (if (< 0 (length args)) `(,newfn ,@args) `(,newfn)))
fa4d7ff0efcd76558f4bc6ebc49dc03c269ae223517b835f3f5fb0990d39cf44
NorfairKing/smos
Admin.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # # LANGUAGE TemplateHaskell # module Smos.Web.Server.Handler.Admin ( getAdminPanelR, postAdminMigrateFilesR, getAdminUserR, postAdminUserSetSubscriptionR, ) where import Smos.Web.Server.Handler.Import getAdminPanelR :: Handler Html getAdminPanelR = withAdminLogin $ \t -> do users <- runClientOrErr $ clientGetUsers t now <- liftIO getCurrentTime token <- genToken withNavBar $(widgetFile "admin/panel") postAdminMigrateFilesR :: Handler Html postAdminMigrateFilesR = withAdminLogin $ \t -> do NoContent <- runClientOrErr $ clientPostMigrateFiles t redirect AdminPanelR getAdminUserR :: Username -> Handler Html getAdminUserR username = withAdminLogin $ \t -> do user <- runClientOrErr $ clientGetUser t username now <- liftIO getCurrentTime token <- genToken withNavBar $(widgetFile "admin/user") postAdminUserSetSubscriptionR :: Username -> Handler Html postAdminUserSetSubscriptionR username = withAdminLogin $ \t -> do endDate <- runInputPost $ ireq dayField "end-date" NoContent <- runClientOrErr $ clientPutUserSubscription t username $ UTCTime endDate 0 redirect $ AdminUserR username
null
https://raw.githubusercontent.com/NorfairKing/smos/4891d1c7a462040ac63771058ab35e35abb4e46d/smos-web-server/src/Smos/Web/Server/Handler/Admin.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE RecordWildCards # # LANGUAGE TemplateHaskell # module Smos.Web.Server.Handler.Admin ( getAdminPanelR, postAdminMigrateFilesR, getAdminUserR, postAdminUserSetSubscriptionR, ) where import Smos.Web.Server.Handler.Import getAdminPanelR :: Handler Html getAdminPanelR = withAdminLogin $ \t -> do users <- runClientOrErr $ clientGetUsers t now <- liftIO getCurrentTime token <- genToken withNavBar $(widgetFile "admin/panel") postAdminMigrateFilesR :: Handler Html postAdminMigrateFilesR = withAdminLogin $ \t -> do NoContent <- runClientOrErr $ clientPostMigrateFiles t redirect AdminPanelR getAdminUserR :: Username -> Handler Html getAdminUserR username = withAdminLogin $ \t -> do user <- runClientOrErr $ clientGetUser t username now <- liftIO getCurrentTime token <- genToken withNavBar $(widgetFile "admin/user") postAdminUserSetSubscriptionR :: Username -> Handler Html postAdminUserSetSubscriptionR username = withAdminLogin $ \t -> do endDate <- runInputPost $ ireq dayField "end-date" NoContent <- runClientOrErr $ clientPutUserSubscription t username $ UTCTime endDate 0 redirect $ AdminUserR username
34618234c33a9b8e965ece8c46a079dc5be580bdd140bd9d50cb9a68acc7fd1b
brianium/yoose
generators.clj
(ns brianium.yoose.async.generators (:require [clojure.core.async :as async] [clojure.spec.alpha :as s] [clojure.spec.gen.alpha :as gen] [brianium.yoose.async :as yoose-async])) (defn chan [] (s/gen #{ (async/chan) })) (defn use-case [] (let [in (gen/generate (chan)) out (gen/generate (chan)) yoose-case (yoose-async/make-use-case in out)] (s/gen #{ yoose-case })))
null
https://raw.githubusercontent.com/brianium/yoose/c4f2892798cbdfef726ce221723c9397108e472e/src/brianium/yoose/async/generators.clj
clojure
(ns brianium.yoose.async.generators (:require [clojure.core.async :as async] [clojure.spec.alpha :as s] [clojure.spec.gen.alpha :as gen] [brianium.yoose.async :as yoose-async])) (defn chan [] (s/gen #{ (async/chan) })) (defn use-case [] (let [in (gen/generate (chan)) out (gen/generate (chan)) yoose-case (yoose-async/make-use-case in out)] (s/gen #{ yoose-case })))
9e4695dc50d42a6a2bb7350d96e3c19671fc6e1b44d94ea259c6c7b947d0731e
finnishtransportagency/harja
laskutusyhteenvedot.clj
(ns harja.palvelin.ajastetut-tehtavat.laskutusyhteenvedot "Ajastettu tehtävä laskutusyhteenvetojen muodostamiseksi valmiiksi välimuistiin" (:require [com.stuartsierra.component :as component] [harja.kyselyt.laskutusyhteenveto :as q] [harja.palvelin.tyokalut.lukot :as lukot] [taoensso.timbre :as log] [harja.pvm :as pvm] [harja.palvelin.tyokalut.ajastettu-tehtava :as ajastettu-tehtava] [harja.kyselyt.konversio :as konv])) (defn- muodosta-laskutusyhteenveto [db alku loppu urakka] (let [[hk-alku hk-loppu :as hk] (pvm/paivamaaran-hoitokausi alku) sql {:urakka urakka :hk_alkupvm hk-alku :hk_loppupvm hk-loppu :aikavali_alkupvm alku :aikavali_loppupvm loppu}] (when-not (= hk (pvm/paivamaaran-hoitokausi loppu)) (log/error "Alku- ja loppupäivämäärä laskutusyhteenvedolle eivät ole samalla hoitokaudella")) (q/hae-laskutusyhteenvedon-tiedot db sql))) 30min lukko , estää molemmilta nodeilta ajamisen (def lukon-vanhenemisaika-sekunteina (* 60 30)) (defn- muodosta-laskutusyhteenvedot [db] (let [[alku loppu] (map #(-> % pvm/dateksi konv/sql-date) (pvm/ed-kk-date-vektorina (pvm/joda-timeksi (pvm/nyt))))] (log/info "Muodostetaan laskutusyhteenvedot valmiiksi") (doseq [{:keys [id nimi]} (q/hae-urakat-joille-laskutusyhteenveto-voidaan-tehda db {:alku alku :loppu loppu})] (log/info "Muodostetaan laskutusyhteenveto valmiiksi urakalle: " nimi) (lukot/yrita-ajaa-lukon-kanssa db (str "laskutusyhteenveto:" id) #(try (muodosta-laskutusyhteenveto db alku loppu id) (catch Throwable t (log/error t "Virhe muodostettaessa laskutusyhteenvetoa, urakka: " id ", aikavali " alku " -- " loppu))) lukon-vanhenemisaika-sekunteina)))) (defn- ajasta [db] (log/info "Ajastetaan laskutusyhteenvetojen muodostus päivittäin") (ajastettu-tehtava/ajasta-paivittain [2 0 0] (fn [_] (muodosta-laskutusyhteenvedot db)))) (defrecord LaskutusyhteenvetojenMuodostus [] component/Lifecycle (start [{db :db :as this}] (assoc this ::laskutusyhteenvetojen-ajastus (ajasta db))) (stop [{poista ::laskutusyhteenvetojen-ajastus :as this}] (poista) (dissoc this ::laskutusyhteenvetojen-ajastus)))
null
https://raw.githubusercontent.com/finnishtransportagency/harja/79b402d6829160743d4bff523b6364b46c59176a/src/clj/harja/palvelin/ajastetut_tehtavat/laskutusyhteenvedot.clj
clojure
(ns harja.palvelin.ajastetut-tehtavat.laskutusyhteenvedot "Ajastettu tehtävä laskutusyhteenvetojen muodostamiseksi valmiiksi välimuistiin" (:require [com.stuartsierra.component :as component] [harja.kyselyt.laskutusyhteenveto :as q] [harja.palvelin.tyokalut.lukot :as lukot] [taoensso.timbre :as log] [harja.pvm :as pvm] [harja.palvelin.tyokalut.ajastettu-tehtava :as ajastettu-tehtava] [harja.kyselyt.konversio :as konv])) (defn- muodosta-laskutusyhteenveto [db alku loppu urakka] (let [[hk-alku hk-loppu :as hk] (pvm/paivamaaran-hoitokausi alku) sql {:urakka urakka :hk_alkupvm hk-alku :hk_loppupvm hk-loppu :aikavali_alkupvm alku :aikavali_loppupvm loppu}] (when-not (= hk (pvm/paivamaaran-hoitokausi loppu)) (log/error "Alku- ja loppupäivämäärä laskutusyhteenvedolle eivät ole samalla hoitokaudella")) (q/hae-laskutusyhteenvedon-tiedot db sql))) 30min lukko , estää molemmilta nodeilta ajamisen (def lukon-vanhenemisaika-sekunteina (* 60 30)) (defn- muodosta-laskutusyhteenvedot [db] (let [[alku loppu] (map #(-> % pvm/dateksi konv/sql-date) (pvm/ed-kk-date-vektorina (pvm/joda-timeksi (pvm/nyt))))] (log/info "Muodostetaan laskutusyhteenvedot valmiiksi") (doseq [{:keys [id nimi]} (q/hae-urakat-joille-laskutusyhteenveto-voidaan-tehda db {:alku alku :loppu loppu})] (log/info "Muodostetaan laskutusyhteenveto valmiiksi urakalle: " nimi) (lukot/yrita-ajaa-lukon-kanssa db (str "laskutusyhteenveto:" id) #(try (muodosta-laskutusyhteenveto db alku loppu id) (catch Throwable t (log/error t "Virhe muodostettaessa laskutusyhteenvetoa, urakka: " id ", aikavali " alku " -- " loppu))) lukon-vanhenemisaika-sekunteina)))) (defn- ajasta [db] (log/info "Ajastetaan laskutusyhteenvetojen muodostus päivittäin") (ajastettu-tehtava/ajasta-paivittain [2 0 0] (fn [_] (muodosta-laskutusyhteenvedot db)))) (defrecord LaskutusyhteenvetojenMuodostus [] component/Lifecycle (start [{db :db :as this}] (assoc this ::laskutusyhteenvetojen-ajastus (ajasta db))) (stop [{poista ::laskutusyhteenvetojen-ajastus :as this}] (poista) (dissoc this ::laskutusyhteenvetojen-ajastus)))
b09e734de98fc38353c1addfe5eed5dcc4ca58d7ca292d760aa75b6c4150b155
marcoheisig/Petalisp
kernel-interpreter.lisp
© 2016 - 2023 - license : GNU AGPLv3 -*- coding : utf-8 -*- (in-package #:petalisp.ir) ;;; In this file we define a simple kernel interpreter. The interpreter ;;; can be used for testing or for executing small kernels for which ;;; compilation is not worth it. (defun interpret-kernel (kernel iteration-space) (let* ((instruction-vector (kernel-instruction-vector kernel)) (offset-vector (make-array (length instruction-vector))) (value-vector-length 0)) (declare (simple-vector instruction-vector offset-vector)) ;; Compute the number of entries in the value vector, and have the ;; entry of the offset vector of each instruction point to the correct ;; place in the value vector. (loop for instruction across instruction-vector for instruction-number from 0 for number-of-values = (instruction-number-of-values instruction) do (assert (= instruction-number (instruction-number instruction))) do (setf (svref offset-vector instruction-number) value-vector-length) do (incf value-vector-length number-of-values)) ;; Introduce the value vector and functions working on it. (let ((value-vector (make-array value-vector-length))) (declare (simple-vector value-vector)) (labels ((interpret-instruction (instruction offset index) (etypecase instruction (call-instruction (with-accessors ((number-of-values call-instruction-number-of-values) (fnrecord call-instruction-fnrecord) (inputs call-instruction-inputs)) instruction (case number-of-values (0 (values)) (1 (setf (svref value-vector offset) (apply (typo:fnrecord-function fnrecord) (mapcar #'input-value inputs)))) (otherwise (let ((values (multiple-value-list (apply (typo:fnrecord-function fnrecord) (mapcar #'input-value inputs))))) (loop for index from 0 below number-of-values do (setf (svref value-vector (+ offset index)) (pop values)))))))) (iref-instruction (with-accessors ((transformation iref-instruction-transformation)) instruction (setf (svref value-vector offset) (first (transform-sequence index transformation))))) (load-instruction (with-accessors ((transformation load-instruction-transformation) (buffer load-instruction-buffer)) instruction (let ((array (buffer-storage buffer))) (setf (svref value-vector offset) (apply #'aref array (transform-sequence index transformation)))))) (store-instruction (with-accessors ((transformation store-instruction-transformation) (buffer store-instruction-buffer) (input store-instruction-input)) instruction (let ((array (buffer-storage buffer))) (setf (apply #'aref array (transform-sequence index transformation)) (input-value input))))))) (input-value (input) (destructuring-bind (value-n . instruction) input (let ((offset (svref offset-vector (instruction-number instruction)))) (svref value-vector (+ offset value-n)))))) ;; Execute the instructions once for each point of the iteration ;; space. (map-shape (lambda (index) (loop for instruction across instruction-vector for offset across offset-vector do (interpret-instruction instruction offset index))) iteration-space)))))
null
https://raw.githubusercontent.com/marcoheisig/Petalisp/a1c85cf71da445ef9c7913cd9ddb5149373211a7/code/ir/kernel-interpreter.lisp
lisp
In this file we define a simple kernel interpreter. The interpreter can be used for testing or for executing small kernels for which compilation is not worth it. Compute the number of entries in the value vector, and have the entry of the offset vector of each instruction point to the correct place in the value vector. Introduce the value vector and functions working on it. Execute the instructions once for each point of the iteration space.
© 2016 - 2023 - license : GNU AGPLv3 -*- coding : utf-8 -*- (in-package #:petalisp.ir) (defun interpret-kernel (kernel iteration-space) (let* ((instruction-vector (kernel-instruction-vector kernel)) (offset-vector (make-array (length instruction-vector))) (value-vector-length 0)) (declare (simple-vector instruction-vector offset-vector)) (loop for instruction across instruction-vector for instruction-number from 0 for number-of-values = (instruction-number-of-values instruction) do (assert (= instruction-number (instruction-number instruction))) do (setf (svref offset-vector instruction-number) value-vector-length) do (incf value-vector-length number-of-values)) (let ((value-vector (make-array value-vector-length))) (declare (simple-vector value-vector)) (labels ((interpret-instruction (instruction offset index) (etypecase instruction (call-instruction (with-accessors ((number-of-values call-instruction-number-of-values) (fnrecord call-instruction-fnrecord) (inputs call-instruction-inputs)) instruction (case number-of-values (0 (values)) (1 (setf (svref value-vector offset) (apply (typo:fnrecord-function fnrecord) (mapcar #'input-value inputs)))) (otherwise (let ((values (multiple-value-list (apply (typo:fnrecord-function fnrecord) (mapcar #'input-value inputs))))) (loop for index from 0 below number-of-values do (setf (svref value-vector (+ offset index)) (pop values)))))))) (iref-instruction (with-accessors ((transformation iref-instruction-transformation)) instruction (setf (svref value-vector offset) (first (transform-sequence index transformation))))) (load-instruction (with-accessors ((transformation load-instruction-transformation) (buffer load-instruction-buffer)) instruction (let ((array (buffer-storage buffer))) (setf (svref value-vector offset) (apply #'aref array (transform-sequence index transformation)))))) (store-instruction (with-accessors ((transformation store-instruction-transformation) (buffer store-instruction-buffer) (input store-instruction-input)) instruction (let ((array (buffer-storage buffer))) (setf (apply #'aref array (transform-sequence index transformation)) (input-value input))))))) (input-value (input) (destructuring-bind (value-n . instruction) input (let ((offset (svref offset-vector (instruction-number instruction)))) (svref value-vector (+ offset value-n)))))) (map-shape (lambda (index) (loop for instruction across instruction-vector for offset across offset-vector do (interpret-instruction instruction offset index))) iteration-space)))))
ecc8f68bdcedd7803f81ac731b79418715c4854d1fad06ce1df8b5116653168e
DaiF1/Oditor
files.ml
file : files.ml dependencies : editor.ml colors.ml Editor file management file: files.ml dependencies: editor.ml colors.ml Editor file management *) open Editor;; open Colors;; (* Add line to text buffer param str: line to add param len: length of line *) let add_line str len = let rec loop text = match text with | [] -> let row = {chars = str; size = len; hl = []} in [row] | l::t -> l::loop t in term.text <- loop term.text;; Open file in editor param path : path to file ( string ) param path: path to file (string) *) let open_file path = let ic = try Some (open_in path) with Sys_error _ -> None in match ic with | None -> term.help <- path ^ ": no such file or directory" | Some ic -> begin term.filename <- path; term.text <- []; let read () = try Some (input_line ic) with End_of_file -> None in let rec loop () = match read () with | None -> close_in ic; 0 | Some s -> add_line s (String.length s); loop () + 1 in term.numlines <- loop () end; update_hl ();; (* Convert text buffer to string param text: erow to convert *) let rec buff_to_string text = match text with | [] -> "" | e::l -> e.chars ^ "\n" ^ buff_to_string l;; (* Write buffer to file param path: path to file *) let write_file path = term.filename <- path; term.changed <- false; let oc = open_out path in output_string oc (buff_to_string term.text); close_out oc;;
null
https://raw.githubusercontent.com/DaiF1/Oditor/9f49ce05281f3253c166475b21c282a1e36c99f7/editor/files.ml
ocaml
Add line to text buffer param str: line to add param len: length of line Convert text buffer to string param text: erow to convert Write buffer to file param path: path to file
file : files.ml dependencies : editor.ml colors.ml Editor file management file: files.ml dependencies: editor.ml colors.ml Editor file management *) open Editor;; open Colors;; let add_line str len = let rec loop text = match text with | [] -> let row = {chars = str; size = len; hl = []} in [row] | l::t -> l::loop t in term.text <- loop term.text;; Open file in editor param path : path to file ( string ) param path: path to file (string) *) let open_file path = let ic = try Some (open_in path) with Sys_error _ -> None in match ic with | None -> term.help <- path ^ ": no such file or directory" | Some ic -> begin term.filename <- path; term.text <- []; let read () = try Some (input_line ic) with End_of_file -> None in let rec loop () = match read () with | None -> close_in ic; 0 | Some s -> add_line s (String.length s); loop () + 1 in term.numlines <- loop () end; update_hl ();; let rec buff_to_string text = match text with | [] -> "" | e::l -> e.chars ^ "\n" ^ buff_to_string l;; let write_file path = term.filename <- path; term.changed <- false; let oc = open_out path in output_string oc (buff_to_string term.text); close_out oc;;
fce48104daae34b87125c2a37fd4b011ea0182e2ec67c5cdc20f7c97c56e671f
kunstmusik/score
tuning.clj
(ns score.tuning "Functions related to tunings, based on the Scala scale file format." (:require [clojure.java.io :refer :all] [clojure.string :refer [trim triml split]])) (def ^:const ^{:tag 'double} MIDDLE-C 261.6255653005986) (def TWELVE-TET { :description "Twelve-Tone Equal Temperament" :base-freq MIDDLE-C :num-scale-degrees 12 :octave 2.0 :ratios (map #(Math/pow 2.0 (/ % 12)) (range 12)) }) (defn- remove-comments [s] (first (split (triml s) #"\s+"))) (defn- convert-cents [s] (let [v (Double/parseDouble s)] (Math/pow 2 (/ v 1200.0)))) (defn- convert-ratio [s] (let [[a b] (split (trim s) #"/")] (if b (/ (Integer/parseInt a) (Integer/parseInt b)) (Integer/parseInt a)))) (defn- get-multiplier "Returns multiplier depending on if string value is ratio or cents. Cents include a . in the string, all else are considered ratios." [s] (let [v (remove-comments s)] (if (>= (.indexOf ^String v ".") 0) (convert-cents v) (convert-ratio v)))) (defn create-tuning-from-file "Creates a tuning using a Scale scale file. See -fokker.org/scala/scl_format.html for more information." [scala-scale-file-name] (with-open [rdr (reader scala-scale-file-name)] (loop [tuning {:base-freq MIDDLE-C} state 0 [x & xs] (line-seq rdr) ratios [1.0] ] (if x (cond (.startsWith ^String x "!") (recur tuning state xs ratios) (= state 0) (recur (assoc tuning :description (trim x)) (inc state) xs ratios) (= state 1) (let [pch-count (Integer/parseInt (trim x))] (recur (assoc tuning :num-scale-degrees pch-count) (inc state) xs ratios)) (= state 2) (if (= (:num-scale-degrees tuning) (count ratios)) (recur (assoc tuning :octave (get-multiplier x)) (inc state) xs ratios) (recur tuning state xs (conj ratios (get-multiplier x)))) :else (recur tuning state xs ratios) ) (assoc tuning :ratios ratios))))) (defn pch->freq "Convert a pch (i.e. [oct scale-degree]) to frequency using the given tuning. Octave of 8 is interpreted as equal to the base frequency of the tuning." [tuning [oct scale-degree]] (let [num-scale-degrees (:num-scale-degrees tuning) oct-adj (+ oct (quot scale-degree num-scale-degrees)) scale-degree-adj (rem scale-degree num-scale-degrees)] (loop [o oct-adj s scale-degree-adj] (if (neg? s) (recur (dec o) (+ num-scale-degrees s)) (let [multiplier (Math/pow (:octave tuning) (- o 8))] (* (* multiplier (:base-freq tuning)) (nth (:ratios tuning) s)))))))
null
https://raw.githubusercontent.com/kunstmusik/score/87b532ec2e3e273f077be9bdd878427a25d0534c/src/main/score/tuning.clj
clojure
(ns score.tuning "Functions related to tunings, based on the Scala scale file format." (:require [clojure.java.io :refer :all] [clojure.string :refer [trim triml split]])) (def ^:const ^{:tag 'double} MIDDLE-C 261.6255653005986) (def TWELVE-TET { :description "Twelve-Tone Equal Temperament" :base-freq MIDDLE-C :num-scale-degrees 12 :octave 2.0 :ratios (map #(Math/pow 2.0 (/ % 12)) (range 12)) }) (defn- remove-comments [s] (first (split (triml s) #"\s+"))) (defn- convert-cents [s] (let [v (Double/parseDouble s)] (Math/pow 2 (/ v 1200.0)))) (defn- convert-ratio [s] (let [[a b] (split (trim s) #"/")] (if b (/ (Integer/parseInt a) (Integer/parseInt b)) (Integer/parseInt a)))) (defn- get-multiplier "Returns multiplier depending on if string value is ratio or cents. Cents include a . in the string, all else are considered ratios." [s] (let [v (remove-comments s)] (if (>= (.indexOf ^String v ".") 0) (convert-cents v) (convert-ratio v)))) (defn create-tuning-from-file "Creates a tuning using a Scale scale file. See -fokker.org/scala/scl_format.html for more information." [scala-scale-file-name] (with-open [rdr (reader scala-scale-file-name)] (loop [tuning {:base-freq MIDDLE-C} state 0 [x & xs] (line-seq rdr) ratios [1.0] ] (if x (cond (.startsWith ^String x "!") (recur tuning state xs ratios) (= state 0) (recur (assoc tuning :description (trim x)) (inc state) xs ratios) (= state 1) (let [pch-count (Integer/parseInt (trim x))] (recur (assoc tuning :num-scale-degrees pch-count) (inc state) xs ratios)) (= state 2) (if (= (:num-scale-degrees tuning) (count ratios)) (recur (assoc tuning :octave (get-multiplier x)) (inc state) xs ratios) (recur tuning state xs (conj ratios (get-multiplier x)))) :else (recur tuning state xs ratios) ) (assoc tuning :ratios ratios))))) (defn pch->freq "Convert a pch (i.e. [oct scale-degree]) to frequency using the given tuning. Octave of 8 is interpreted as equal to the base frequency of the tuning." [tuning [oct scale-degree]] (let [num-scale-degrees (:num-scale-degrees tuning) oct-adj (+ oct (quot scale-degree num-scale-degrees)) scale-degree-adj (rem scale-degree num-scale-degrees)] (loop [o oct-adj s scale-degree-adj] (if (neg? s) (recur (dec o) (+ num-scale-degrees s)) (let [multiplier (Math/pow (:octave tuning) (- o 8))] (* (* multiplier (:base-freq tuning)) (nth (:ratios tuning) s)))))))
3f678dc67ce843afd2b52277e0748e656b70b81a2d188031e9fa60186b64cdfb
GaloisInc/saw-script
Test.hs
{-# LANGUAGE GADTs #-} # LANGUAGE LambdaCase # # LANGUAGE ImplicitParams # {-# Language OverloadedStrings #-} # OPTIONS_GHC -Wall -fno - warn - unused - top - binds # import qualified Data.ByteString as BS import qualified Data.ByteString.UTF8 as BS8 import Data.Char (isSpace) import Data.List (dropWhileEnd, isPrefixOf) import Data.Maybe (catMaybes) import System.Directory (listDirectory, doesDirectoryExist, doesFileExist, removeFile) import System.Exit (ExitCode(..)) import System.FilePath ((<.>), (</>), takeBaseName, takeExtension, replaceExtension, takeFileName, takeDirectory) import System.IO (IOMode(..), Handle, withFile, hClose, hGetContents, hGetLine, openFile) import System.IO.Temp (withSystemTempFile) import System.Environment (setEnv) import qualified System.Process as Proc import Test.Tasty (defaultMain, testGroup, TestTree) import Test.Tasty.HUnit (Assertion, testCaseSteps, assertBool, assertFailure) import Test.Tasty.Golden (findByExtension) import Test.Tasty.Golden.Advanced (goldenTest) import Test.Tasty.ExpectedFailure (expectFailBecause) import qualified Mir.Language as Mir import qualified Mir.Compositional as Mir import qualified Mir.Cryptol as Mir import qualified Crux as Crux import qualified Crux.Config.Common as Crux import qualified Data.AIG.Interface as AIG import qualified Config import qualified Config.Schema as Config type OracleTest = FilePath -> String -> (String -> IO ()) -> Assertion Do n't show any debug output when testing ( SAWInterface ) debugLevel :: Int debugLevel = 0 | Check whether an input file is expected to fail based on a comment in the first line . expectedFail :: FilePath -> IO (Maybe String) expectedFail fn = withFile fn ReadMode $ \h -> do firstLine <- hGetLine h return $ if failMarker `isPrefixOf` firstLine then Just (drop (length failMarker) firstLine) else Nothing where failMarker = "// FAIL: " TODO : remove this - copy - pasted from Crux / Options.hs for compatibility with -- old mainline crucible defaultCruxOptions :: Crux.CruxOptions defaultCruxOptions = case res of Left x -> error $ "failed to compute default crux options: " ++ show x Right x -> x where ss = Crux.cfgFile Crux.cruxOptions res = Config.loadValue (Config.sectionsSpec "crux" ss) (Config.Sections () []) data RunCruxMode = RcmConcrete | RcmSymbolic | RcmCoverage deriving (Show, Eq) runCrux :: FilePath -> Handle -> RunCruxMode -> IO () runCrux rustFile outHandle mode = Mir.withMirLogging $ do goalTimeout is bumped from 60 to 180 because scalar.rs symbolic -- verification runs close to the timeout, causing flaky results ( especially in CI ) . let quiet = True let outOpts = (Crux.outputOptions defaultCruxOptions) { Crux.simVerbose = 0 , Crux.quietMode = quiet } let options = (defaultCruxOptions { Crux.outputOptions = outOpts, Crux.inputFiles = [rustFile], Crux.globalTimeout = Just 180, Crux.goalTimeout = Just 180, Crux.solver = "z3", Crux.checkPathSat = (mode == RcmCoverage), Crux.outDir = case mode of RcmCoverage -> getOutputDir rustFile _ -> "", Crux.branchCoverage = (mode == RcmCoverage) } , Mir.defaultMirOptions { Mir.printResultOnly = (mode == RcmConcrete), Mir.defaultRlibsDir = "../deps/crucible/crux-mir/rlibs" }) let ?outputConfig = Crux.mkOutputConfig (outHandle, False) (outHandle, False) Mir.mirLoggingToSayWhat (Just $ Crux.outputOptions $ fst options) setEnv "CRYPTOLPATH" "." _exitCode <- Mir.runTestsWithExtraOverrides overrides options return () where overrides :: Mir.BindExtraOverridesFn overrides = Mir.compositionalOverrides `Mir.orOverride` Mir.cryptolOverrides getOutputDir :: FilePath -> FilePath getOutputDir rustFile = takeDirectory rustFile </> "out" cruxOracleTest :: FilePath -> String -> (String -> IO ()) -> Assertion cruxOracleTest dir name step = do step "Compiling and running oracle program" oracleOut <- compileAndRun dir name >>= \case Nothing -> assertFailure "failed to compile and run" Just out -> return out let orOut = dropWhileEnd isSpace oracleOut step ("Oracle output: " ++ orOut) let rustFile = dir </> name <.> "rs" cruxOut <- withSystemTempFile name $ \tempName h -> do runCrux rustFile h RcmConcrete hClose h h' <- openFile tempName ReadMode out <- hGetContents h' length out `seq` hClose h' return $ dropWhileEnd isSpace out step ("Crux output: " ++ cruxOut ++ "\n") assertBool "crux doesn't match oracle" (orOut == cruxOut) symbTest :: FilePath -> IO TestTree symbTest dir = do exists <- doesDirectoryExist dir rustFiles <- if exists then findByExtension [".rs"] dir else return [] return $ testGroup "Output testing" [ doGoldenTest (takeBaseName rustFile) goodFile outFile $ withFile outFile WriteMode $ \h -> runCrux rustFile h RcmSymbolic | rustFile <- rustFiles -- Skip hidden files, such as editor swap files , not $ "." `isPrefixOf` takeFileName rustFile , let goodFile = replaceExtension rustFile ".good" , let outFile = replaceExtension rustFile ".out" ] coverageTests :: FilePath -> IO TestTree coverageTests dir = do exists <- doesDirectoryExist dir rustFiles <- if exists then findByExtension [".rs"] dir else return [] return $ testGroup "Output testing" [ doGoldenTest rustFile goodFile outFile (doTest rustFile outFile) | rustFile <- rustFiles -- Skip hidden files, such as editor swap files , not $ "." `isPrefixOf` takeFileName rustFile , let goodFile = replaceExtension rustFile ".good" , let outFile = replaceExtension rustFile ".out" ] where doTest rustFile outFile = do let logFile = replaceExtension rustFile ".crux.log" withFile logFile WriteMode $ \h -> runCrux rustFile h RcmCoverage let reportDir = getOutputDir rustFile </> takeBaseName rustFile reportFiles <- findByExtension [".js"] reportDir out <- Proc.readProcess "cargo" (["run", "--manifest-path", "report-coverage/Cargo.toml", "--quiet", "--", "--no-color"] ++ reportFiles) "" writeFile outFile out doGoldenTest :: FilePath -> FilePath -> FilePath -> IO () -> TestTree doGoldenTest rustFile goodFile outFile act = goldenTest (takeBaseName rustFile) (BS.readFile goodFile) (act >> BS.readFile outFile) (\good out -> return $ if good == out then Nothing else Just $ "files " ++ goodFile ++ " and " ++ outFile ++ " differ; " ++ goodFile ++ " contains:\n" ++ BS8.toString out) (\out -> BS.writeFile goodFile out) main :: IO () main = defaultMain =<< suite suite :: IO TestTree suite = do let ?debug = 0 :: Int let ?assertFalseOnError = True let ?printCrucible = False trees <- sequence [ testGroup "crux concrete" <$> sequence [ testDir cruxOracleTest "test/conc_eval/" ] , testGroup "crux symbolic" <$> sequence [ symbTest "test/symb_eval" ] , testGroup "crux coverage" <$> sequence [ coverageTests "test/coverage" ] ] return $ testGroup "crux-mir" trees -- For newSAWCoreBackend proxy :: AIG.Proxy AIG.BasicLit AIG.BasicGraph proxy = AIG.basicProxy -- | Compile using 'rustc' and run executable compileAndRun :: FilePath -> String -> IO (Maybe String) compileAndRun dir name = do (ec, _, err) <- Proc.readProcessWithExitCode "rustc" [dir </> name <.> "rs", "--cfg", "with_main" , "--extern", "byteorder=rlibs_native/libbyteorder.rlib" , "--extern", "bytes=rlibs_native/libbytes.rlib"] "" case ec of ExitFailure _ -> do putStrLn $ "rustc compilation failed for " ++ name putStrLn "error output:" putStrLn err return Nothing ExitSuccess -> do let execFile = "." </> name (ec', out, _) <- Proc.readProcessWithExitCode execFile [] "" doesFileExist execFile >>= \case True -> removeFile execFile False -> return () case ec' of ExitFailure _ -> do putStrLn $ "non-zero exit code for test executable " ++ name return Nothing ExitSuccess -> return $ Just out testDir :: OracleTest -> FilePath -> IO TestTree testDir oracleTest dir = do let gen f | "." `isPrefixOf` takeBaseName f = return Nothing gen f | takeExtension f == ".rs" = do shouldFail <- expectedFail (dir </> f) case shouldFail of Nothing -> return (Just (testCaseSteps name (oracleTest dir name))) Just why -> return (Just (expectFailBecause why (testCaseSteps name (oracleTest dir name)))) where name = takeBaseName f gen f = doesDirectoryExist (dir </> f) >>= \case False -> return Nothing True -> Just <$> testDir oracleTest (dir </> f) exists <- doesDirectoryExist dir fs <- if exists then listDirectory dir else return [] tcs <- mapM gen fs return (testGroup (takeBaseName dir) (catMaybes tcs))
null
https://raw.githubusercontent.com/GaloisInc/saw-script/92e96208600f2ccd11b8de409e8e28d5247484ea/crux-mir-comp/test/Test.hs
haskell
# LANGUAGE GADTs # # Language OverloadedStrings # old mainline crucible verification runs close to the timeout, causing flaky results Skip hidden files, such as editor swap files Skip hidden files, such as editor swap files For newSAWCoreBackend | Compile using 'rustc' and run executable
# LANGUAGE LambdaCase # # LANGUAGE ImplicitParams # # OPTIONS_GHC -Wall -fno - warn - unused - top - binds # import qualified Data.ByteString as BS import qualified Data.ByteString.UTF8 as BS8 import Data.Char (isSpace) import Data.List (dropWhileEnd, isPrefixOf) import Data.Maybe (catMaybes) import System.Directory (listDirectory, doesDirectoryExist, doesFileExist, removeFile) import System.Exit (ExitCode(..)) import System.FilePath ((<.>), (</>), takeBaseName, takeExtension, replaceExtension, takeFileName, takeDirectory) import System.IO (IOMode(..), Handle, withFile, hClose, hGetContents, hGetLine, openFile) import System.IO.Temp (withSystemTempFile) import System.Environment (setEnv) import qualified System.Process as Proc import Test.Tasty (defaultMain, testGroup, TestTree) import Test.Tasty.HUnit (Assertion, testCaseSteps, assertBool, assertFailure) import Test.Tasty.Golden (findByExtension) import Test.Tasty.Golden.Advanced (goldenTest) import Test.Tasty.ExpectedFailure (expectFailBecause) import qualified Mir.Language as Mir import qualified Mir.Compositional as Mir import qualified Mir.Cryptol as Mir import qualified Crux as Crux import qualified Crux.Config.Common as Crux import qualified Data.AIG.Interface as AIG import qualified Config import qualified Config.Schema as Config type OracleTest = FilePath -> String -> (String -> IO ()) -> Assertion Do n't show any debug output when testing ( SAWInterface ) debugLevel :: Int debugLevel = 0 | Check whether an input file is expected to fail based on a comment in the first line . expectedFail :: FilePath -> IO (Maybe String) expectedFail fn = withFile fn ReadMode $ \h -> do firstLine <- hGetLine h return $ if failMarker `isPrefixOf` firstLine then Just (drop (length failMarker) firstLine) else Nothing where failMarker = "// FAIL: " TODO : remove this - copy - pasted from Crux / Options.hs for compatibility with defaultCruxOptions :: Crux.CruxOptions defaultCruxOptions = case res of Left x -> error $ "failed to compute default crux options: " ++ show x Right x -> x where ss = Crux.cfgFile Crux.cruxOptions res = Config.loadValue (Config.sectionsSpec "crux" ss) (Config.Sections () []) data RunCruxMode = RcmConcrete | RcmSymbolic | RcmCoverage deriving (Show, Eq) runCrux :: FilePath -> Handle -> RunCruxMode -> IO () runCrux rustFile outHandle mode = Mir.withMirLogging $ do goalTimeout is bumped from 60 to 180 because scalar.rs symbolic ( especially in CI ) . let quiet = True let outOpts = (Crux.outputOptions defaultCruxOptions) { Crux.simVerbose = 0 , Crux.quietMode = quiet } let options = (defaultCruxOptions { Crux.outputOptions = outOpts, Crux.inputFiles = [rustFile], Crux.globalTimeout = Just 180, Crux.goalTimeout = Just 180, Crux.solver = "z3", Crux.checkPathSat = (mode == RcmCoverage), Crux.outDir = case mode of RcmCoverage -> getOutputDir rustFile _ -> "", Crux.branchCoverage = (mode == RcmCoverage) } , Mir.defaultMirOptions { Mir.printResultOnly = (mode == RcmConcrete), Mir.defaultRlibsDir = "../deps/crucible/crux-mir/rlibs" }) let ?outputConfig = Crux.mkOutputConfig (outHandle, False) (outHandle, False) Mir.mirLoggingToSayWhat (Just $ Crux.outputOptions $ fst options) setEnv "CRYPTOLPATH" "." _exitCode <- Mir.runTestsWithExtraOverrides overrides options return () where overrides :: Mir.BindExtraOverridesFn overrides = Mir.compositionalOverrides `Mir.orOverride` Mir.cryptolOverrides getOutputDir :: FilePath -> FilePath getOutputDir rustFile = takeDirectory rustFile </> "out" cruxOracleTest :: FilePath -> String -> (String -> IO ()) -> Assertion cruxOracleTest dir name step = do step "Compiling and running oracle program" oracleOut <- compileAndRun dir name >>= \case Nothing -> assertFailure "failed to compile and run" Just out -> return out let orOut = dropWhileEnd isSpace oracleOut step ("Oracle output: " ++ orOut) let rustFile = dir </> name <.> "rs" cruxOut <- withSystemTempFile name $ \tempName h -> do runCrux rustFile h RcmConcrete hClose h h' <- openFile tempName ReadMode out <- hGetContents h' length out `seq` hClose h' return $ dropWhileEnd isSpace out step ("Crux output: " ++ cruxOut ++ "\n") assertBool "crux doesn't match oracle" (orOut == cruxOut) symbTest :: FilePath -> IO TestTree symbTest dir = do exists <- doesDirectoryExist dir rustFiles <- if exists then findByExtension [".rs"] dir else return [] return $ testGroup "Output testing" [ doGoldenTest (takeBaseName rustFile) goodFile outFile $ withFile outFile WriteMode $ \h -> runCrux rustFile h RcmSymbolic | rustFile <- rustFiles , not $ "." `isPrefixOf` takeFileName rustFile , let goodFile = replaceExtension rustFile ".good" , let outFile = replaceExtension rustFile ".out" ] coverageTests :: FilePath -> IO TestTree coverageTests dir = do exists <- doesDirectoryExist dir rustFiles <- if exists then findByExtension [".rs"] dir else return [] return $ testGroup "Output testing" [ doGoldenTest rustFile goodFile outFile (doTest rustFile outFile) | rustFile <- rustFiles , not $ "." `isPrefixOf` takeFileName rustFile , let goodFile = replaceExtension rustFile ".good" , let outFile = replaceExtension rustFile ".out" ] where doTest rustFile outFile = do let logFile = replaceExtension rustFile ".crux.log" withFile logFile WriteMode $ \h -> runCrux rustFile h RcmCoverage let reportDir = getOutputDir rustFile </> takeBaseName rustFile reportFiles <- findByExtension [".js"] reportDir out <- Proc.readProcess "cargo" (["run", "--manifest-path", "report-coverage/Cargo.toml", "--quiet", "--", "--no-color"] ++ reportFiles) "" writeFile outFile out doGoldenTest :: FilePath -> FilePath -> FilePath -> IO () -> TestTree doGoldenTest rustFile goodFile outFile act = goldenTest (takeBaseName rustFile) (BS.readFile goodFile) (act >> BS.readFile outFile) (\good out -> return $ if good == out then Nothing else Just $ "files " ++ goodFile ++ " and " ++ outFile ++ " differ; " ++ goodFile ++ " contains:\n" ++ BS8.toString out) (\out -> BS.writeFile goodFile out) main :: IO () main = defaultMain =<< suite suite :: IO TestTree suite = do let ?debug = 0 :: Int let ?assertFalseOnError = True let ?printCrucible = False trees <- sequence [ testGroup "crux concrete" <$> sequence [ testDir cruxOracleTest "test/conc_eval/" ] , testGroup "crux symbolic" <$> sequence [ symbTest "test/symb_eval" ] , testGroup "crux coverage" <$> sequence [ coverageTests "test/coverage" ] ] return $ testGroup "crux-mir" trees proxy :: AIG.Proxy AIG.BasicLit AIG.BasicGraph proxy = AIG.basicProxy compileAndRun :: FilePath -> String -> IO (Maybe String) compileAndRun dir name = do (ec, _, err) <- Proc.readProcessWithExitCode "rustc" [dir </> name <.> "rs", "--cfg", "with_main" , "--extern", "byteorder=rlibs_native/libbyteorder.rlib" , "--extern", "bytes=rlibs_native/libbytes.rlib"] "" case ec of ExitFailure _ -> do putStrLn $ "rustc compilation failed for " ++ name putStrLn "error output:" putStrLn err return Nothing ExitSuccess -> do let execFile = "." </> name (ec', out, _) <- Proc.readProcessWithExitCode execFile [] "" doesFileExist execFile >>= \case True -> removeFile execFile False -> return () case ec' of ExitFailure _ -> do putStrLn $ "non-zero exit code for test executable " ++ name return Nothing ExitSuccess -> return $ Just out testDir :: OracleTest -> FilePath -> IO TestTree testDir oracleTest dir = do let gen f | "." `isPrefixOf` takeBaseName f = return Nothing gen f | takeExtension f == ".rs" = do shouldFail <- expectedFail (dir </> f) case shouldFail of Nothing -> return (Just (testCaseSteps name (oracleTest dir name))) Just why -> return (Just (expectFailBecause why (testCaseSteps name (oracleTest dir name)))) where name = takeBaseName f gen f = doesDirectoryExist (dir </> f) >>= \case False -> return Nothing True -> Just <$> testDir oracleTest (dir </> f) exists <- doesDirectoryExist dir fs <- if exists then listDirectory dir else return [] tcs <- mapM gen fs return (testGroup (takeBaseName dir) (catMaybes tcs))
096fcdb464b45c704d7fad9f3e1f177dfcd345988c3a86ee1927596fbea76532
goldfirere/singletons
T450.hs
module T450 where import Data.Maybe import Data.Singletons.TH import Data.Singletons.TH.Options import Data.Text (Text) import Language.Haskell.TH (Name) import Prelude.Singletons newtype Message = MkMessage Text newtype PMessage = PMkMessage Symbol newtype Function a b = MkFunction (a -> b) newtype PFunction a b = PMkFunction (a ~> b) $(do let customPromote :: [(Name, Name)] -> Name -> Name customPromote customs n = fromMaybe n $ lookup n customs customOptions :: [(Name, Name)] -> Options customOptions customs = defaultOptions{ promotedDataTypeOrConName = \n -> promotedDataTypeOrConName defaultOptions (customPromote customs n) , defunctionalizedName = \n sat -> defunctionalizedName defaultOptions (customPromote customs n) sat } messageDecs <- withOptions (customOptions [ (''Message, ''PMessage) , ('MkMessage, 'PMkMessage) , (''Text, ''Symbol) ]) $ do messageDecs1 <- genSingletons [''Message] messageDecs2 <- singletons [d| appendMessage :: Message -> Message -> Message appendMessage (MkMessage (x :: Text)) (MkMessage (y :: Text)) = MkMessage (x <> y :: Text) |] pure $ messageDecs1 ++ messageDecs2 functionDecs <- withOptions (customOptions [ (''Function, ''PFunction) , ('MkFunction, 'PMkFunction) ]) $ do functionDecs1 <- genSingletons [''Function] functionDecs2 <- singletons [d| composeFunction :: Function b c -> Function a b -> Function a c composeFunction (MkFunction (f :: b -> c)) (MkFunction (g :: a -> b)) = MkFunction (f . g :: a -> c) |] pure $ functionDecs1 ++ functionDecs2 pure $ messageDecs ++ functionDecs)
null
https://raw.githubusercontent.com/goldfirere/singletons/ad40d2a6392d562509ba572c84f9a335e4cef5f9/singletons-base/tests/compile-and-dump/Singletons/T450.hs
haskell
module T450 where import Data.Maybe import Data.Singletons.TH import Data.Singletons.TH.Options import Data.Text (Text) import Language.Haskell.TH (Name) import Prelude.Singletons newtype Message = MkMessage Text newtype PMessage = PMkMessage Symbol newtype Function a b = MkFunction (a -> b) newtype PFunction a b = PMkFunction (a ~> b) $(do let customPromote :: [(Name, Name)] -> Name -> Name customPromote customs n = fromMaybe n $ lookup n customs customOptions :: [(Name, Name)] -> Options customOptions customs = defaultOptions{ promotedDataTypeOrConName = \n -> promotedDataTypeOrConName defaultOptions (customPromote customs n) , defunctionalizedName = \n sat -> defunctionalizedName defaultOptions (customPromote customs n) sat } messageDecs <- withOptions (customOptions [ (''Message, ''PMessage) , ('MkMessage, 'PMkMessage) , (''Text, ''Symbol) ]) $ do messageDecs1 <- genSingletons [''Message] messageDecs2 <- singletons [d| appendMessage :: Message -> Message -> Message appendMessage (MkMessage (x :: Text)) (MkMessage (y :: Text)) = MkMessage (x <> y :: Text) |] pure $ messageDecs1 ++ messageDecs2 functionDecs <- withOptions (customOptions [ (''Function, ''PFunction) , ('MkFunction, 'PMkFunction) ]) $ do functionDecs1 <- genSingletons [''Function] functionDecs2 <- singletons [d| composeFunction :: Function b c -> Function a b -> Function a c composeFunction (MkFunction (f :: b -> c)) (MkFunction (g :: a -> b)) = MkFunction (f . g :: a -> c) |] pure $ functionDecs1 ++ functionDecs2 pure $ messageDecs ++ functionDecs)
6687979b5bdfaf18de5e868ad0b4e61b95497da99bf595560425d80e159170b4
iu-parfunc/lvars
MIS.hs
| Maximum independent set algorithms in lvish # LANGUAGE CPP , ScopedTypeVariables # {-# LANGUAGE BangPatterns #-} {-# LANGUAGE GADTs #-} module Data.LVar.Graph.MIS where import Utils -- Benchmark utils: -- import PBBS.FileReader import ( wait_clocks , runAndReport ) calibrate , measureFreq , commaint , import Control.LVish import Control.Monad import Data.Word import qualified Data.Vector.Unboxed as U import qualified Data.Vector.Unboxed.Mutable as M import qualified Data.Vector.Storable as UV import qualified Data.Vector.Storable.Mutable as MV import Data.Graph.Adjacency #ifdef NEW_CONTAINERS import Control.LVish.BulkRetry #endif -- define DEBUG_CHECKS #if 1 import Data.LVar.PureSet as S #else [ 2013.07.09 ] This one still is n't terminating on 125K+ Well , maybe it 's just slow ... 5000 takes 2 seconds . Yes , it 's literally over 100 times slower currently . import Data.LVar.SLSet as S #endif import Data.LVar.IStructure as ISt import Data.LVar.NatArray as NArr ------------------------------------------------------------------------------------------ -- TODO: Define clan user-visible datatypes for dense and sparse representations of -- node sets. type DenseVertset s = NatArray s Word8 -- type SparseVertset ------------------------------------------------------------------------------------------ -- Maximal Independent Set ------------------------------------------------------------------------------------------ -- Lattice where undecided = bot, and chosen/nbrchosen are disjoint middle states flag_UNDECIDED :: Word8 flag_CHOSEN :: Word8 flag_NBRCHOSEN :: Word8 flag_UNDECIDED = 0 flag_CHOSEN = 1 flag_NBRCHOSEN = 2 data VertState = Chosen | Undecided | NbrChosen instance where Minimal complete definition : sizeOf , alignment , one of peek , peekElemOff and peekByteOff , and one of poke , pokeElemOff and pokeByteOff . type ParFor e s = (Int,Int) -> (Int -> Par e s ()) -> Par e s () # INLINE maximalIndependentSet # maximalIndependentSet : : NodeID - > Par d s ( ISet s NodeID ) -- Operate on a subgraph -- maximalIndependentSet :: AdjacencyGraph -> Par d s (ISet s NodeID) -- Operate on a whole graph. maximalIndependentSet :: (HasGet e, HasPut e) => ParFor e s -> AdjacencyGraph -> Par e s (NatArray s Word8) -- Operate on a whole graph. maximalIndependentSet parFor gr@(AdjacencyGraph vvec evec) = do For each vertex , we record whether it is CHOSEN , not chosen , or undecided : let numVerts = U.length vvec flagsArr :: NatArray s Word8 <- newNatArray numVerts let -- Here's the loop that scans through the neighbors of a node. loop !numNbrs !nbrs !selfInd !i | i == numNbrs = thisNodeWins | otherwise = do -- logDbgLn 3$ " [MIS] ... on nbr "++ show i++" of "++show numNbrs Find our Nbr 's NodeID selfInd' = fromIntegral selfInd -- If we got to the end of the neighbors below us, then we are NOT disqualified: if nbrInd > selfInd then thisNodeWins else do -- This should never block in a single-thread execution: logDbgLn 3 (" [MIS] ! Getting on nbrInd "++show nbrInd) nbrFlag <- NArr.get flagsArr (fromIntegral nbrInd) logDbgLn 3 (" [MIS] ! Get completed on nbrInd "++show nbrInd) if nbrFlag == flag_CHOSEN then NArr.put flagsArr selfInd' flag_NBRCHOSEN else loop numNbrs nbrs selfInd (i+1) where thisNodeWins = logDbgLn 3 (" [MIS] ! Node chosen: "++show selfInd) >> NArr.put flagsArr (fromIntegral selfInd) flag_CHOSEN parFor (0,numVerts) $ \ ndIx -> do let nds = nbrs gr (fromIntegral ndIx) logDbgLn 3 $ " [ MIS ] processing node " + + show ndIx++ " nbrs " + + show loop (U.length nds) nds ndIx 0 return flagsArr -- | DUPLICATE CODE: IStructure version. maximalIndependentSet2 :: (HasGet e, HasPut e) => ParFor e s -> AdjacencyGraph -> Par e s (IStructure s Word8) -- Operate on a whole graph. maximalIndependentSet2 parFor gr@(AdjacencyGraph vvec evec) = do logDbgLn 3$ " [MIS] Beginning maximalIndependentSet / Istructures" For each vertex , we record whether it is CHOSEN , not chosen , or undecided : let numVerts = U.length vvec flagsArr <- newIStructure numVerts let -- Here's the loop that scans through the neighbors of a node. loop !numNbrs !nbrs !selfInd !i | i == numNbrs = thisNodeWins | otherwise = do -- logDbgLn 3$ " [MIS] ... on nbr "++ show i++" of "++show numNbrs Find our Nbr 's NodeID selfInd' = fromIntegral selfInd -- If we got to the end of the neighbors below us, then we are NOT disqualified: if nbrInd > selfInd then thisNodeWins else do -- This should never block in a single-thread execution: logDbgLn 3 (" [MIS] ! Getting on nbrInd "++show nbrInd) nbrFlag <- ISt.get flagsArr (fromIntegral nbrInd) logDbgLn 3 (" [MIS] ! Get completed on nbrInd "++show nbrInd) if nbrFlag == flag_CHOSEN then ISt.put_ flagsArr selfInd' flag_NBRCHOSEN else loop numNbrs nbrs selfInd (i+1) where thisNodeWins = logDbgLn 3 (" [MIS] ! Node chosen: "++show selfInd) >> ISt.put_ flagsArr (fromIntegral selfInd) flag_CHOSEN parFor (0,numVerts) $ \ ndIx -> do let nds = nbrs gr (fromIntegral ndIx) logDbgLn 3 $ " [ MIS ] processing node " + + show ndIx++ " nbrs " + + show loop (U.length nds) nds ndIx 0 return flagsArr -- | Sequential version. maximalIndependentSet3 :: AdjacencyGraph -> (U.Vector Word8) maximalIndependentSet3 gr@(AdjacencyGraph vvec evec) = U.create $ do let numVerts = U.length vvec flagsArr <- M.replicate numVerts 0 let loop !numNbrs !nbrs !selfInd !i | i == numNbrs = thisNodeWins | otherwise = do Find our Nbr 's NodeID selfInd' = fromIntegral selfInd if nbrInd > selfInd then thisNodeWins else do nbrFlag <- M.read flagsArr (fromIntegral nbrInd) if nbrFlag == flag_CHOSEN then M.write flagsArr selfInd' flag_NBRCHOSEN else loop numNbrs nbrs selfInd (i+1) where thisNodeWins = M.write flagsArr (fromIntegral selfInd) flag_CHOSEN for_ (0,numVerts) $ \ ndIx -> do let nds = nbrs gr (fromIntegral ndIx) loop (U.length nds) nds ndIx 0 return flagsArr | Sequential version on NatArray ... maximalIndependentSet3B :: AdjacencyGraph -> (UV.Vector Word8) -> (UV.Vector Word8) maximalIndependentSet3B gr@(AdjacencyGraph vvec evec) vec = UV.create $ do let numVerts = U.length vvec flagsArr <- MV.replicate numVerts 0 let loop !numNbrs !nbrs !selfInd !i | i == numNbrs = thisNodeWins | otherwise = do Find our Nbr 's NodeID selfInd' = fromIntegral selfInd if nbrInd > selfInd then thisNodeWins else do nbrFlag <- MV.read flagsArr (fromIntegral nbrInd) if nbrFlag == flag_CHOSEN then MV.write flagsArr selfInd' flag_NBRCHOSEN else loop numNbrs nbrs selfInd (i+1) where thisNodeWins = MV.write flagsArr (fromIntegral selfInd) flag_CHOSEN for_ (0,numVerts) $ \ ndIx -> when (vec UV.! ndIx == 1) $ do let nds = nbrs gr (fromIntegral ndIx) loop (U.length nds) nds ndIx 0 return flagsArr -- MIS over a preexisting, filtered subgraph ------------------------------------------------------------ -- Right now this uses an IStructure because it's (temporarily) better at blocking gets: maximalIndependentSet4 :: (HasGet e, HasPut e) => AdjacencyGraph -> (NatArray s Word8) -> Par e s (IStructure s Word8) maximalIndependentSet4 gr@(AdjacencyGraph vvec evec) vertSubset = do let numVerts = U.length vvec -- Tradeoff: we use storage proportional to the ENTIRE graph. If the subset is -- very small, this is silly and we could use a sparse representation: flagsArr <- newIStructure numVerts let -- Here's the loop that scans through the neighbors of a node. loop !numNbrs !nbrs !selfInd !i | i == numNbrs = thisNodeWins | otherwise = do Find our Nbr 's NodeID selfInd' = fromIntegral selfInd -- If we got to the end of the neighbors below us, then we are NOT disqualified: if nbrInd > selfInd then thisNodeWins else do nbrFlag <- ISt.get flagsArr (fromIntegral nbrInd) if nbrFlag == flag_CHOSEN then ISt.put_ flagsArr selfInd' flag_NBRCHOSEN else loop numNbrs nbrs selfInd (i+1) where thisNodeWins = ISt.put_ flagsArr (fromIntegral selfInd) flag_CHOSEN NArr.forEach vertSubset $ \ ndIx _ -> let nds = nbrs gr (fromIntegral ndIx) in loop (U.length nds) nds ndIx 0 return flagsArr --------------------------------------------------------------------------------------------------------------- MIS using BulkRetry --------------------------------------------------------------------------------------------------------------- #ifdef NEW_CONTAINERS maximalIndependentSetBR :: AdjacencyGraph -> Par e s (NatArray s Word8) -- Operate on a whole graph. maximalIndependentSetBR gr@(AdjacencyGraph vvec _) = do For each vertex , we record whether it is CHOSEN , not chosen , or undecided : let numVerts = U.length vvec flagsArr :: NatArray s Word8 <- newNatArray numVerts let -- Here's the loop that scans through the neighbors of a node. loop retryhub !numNbrs !nbrs !selfInd !i | i == numNbrs = thisNodeWins | otherwise = do -- logDbgLn 3$ " [MIS] ... on nbr "++ show i++" of "++show numNbrs Find our Nbr 's NodeID selfInd' = fromIntegral selfInd -- If we got to the end of the neighbors below us, then we are NOT disqualified: if nbrInd > selfInd then thisNodeWins else do -- This should never block in a single-thread execution: logDbgLn 3 (" [MIS] ! Getting on nbrInd "++show nbrInd) getNB_cps retryhub flagsArr (fromIntegral nbrInd) $ \ nbrFlag -> do logDbgLn 3 (" [MIS] ! Get completed on nbrInd "++show nbrInd) if nbrFlag == flag_CHOSEN then NArr.put flagsArr selfInd' flag_NBRCHOSEN else loop retryhub numNbrs nbrs selfInd (i+1) where thisNodeWins = logDbgLn 3 (" [MIS] ! Node chosen: "++show selfInd) >> NArr.put flagsArr (fromIntegral selfInd) flag_CHOSEN forSpeculative (0,numVerts) $ \ retryhub ndIx -> do let nds = nbrs gr (fromIntegral ndIx) logDbgLn 3 $ " [ MIS ] processing node " + + show ndIx++ " nbrs " + + show loop retryhub (U.length nds) nds ndIx 0 return flagsArr #endif
null
https://raw.githubusercontent.com/iu-parfunc/lvars/78e73c96a929aa75aa4f991d42b2f677849e433a/src/lvish-graph-algorithms/src/Data/LVar/Graph/MIS.hs
haskell
# LANGUAGE BangPatterns # # LANGUAGE GADTs # Benchmark utils: import PBBS.FileReader define DEBUG_CHECKS ---------------------------------------------------------------------------------------- TODO: Define clan user-visible datatypes for dense and sparse representations of node sets. type SparseVertset ---------------------------------------------------------------------------------------- Maximal Independent Set ---------------------------------------------------------------------------------------- Lattice where undecided = bot, and chosen/nbrchosen are disjoint middle states Operate on a subgraph maximalIndependentSet :: AdjacencyGraph -> Par d s (ISet s NodeID) -- Operate on a whole graph. Operate on a whole graph. Here's the loop that scans through the neighbors of a node. logDbgLn 3$ " [MIS] ... on nbr "++ show i++" of "++show numNbrs If we got to the end of the neighbors below us, then we are NOT disqualified: This should never block in a single-thread execution: | DUPLICATE CODE: IStructure version. Operate on a whole graph. Here's the loop that scans through the neighbors of a node. logDbgLn 3$ " [MIS] ... on nbr "++ show i++" of "++show numNbrs If we got to the end of the neighbors below us, then we are NOT disqualified: This should never block in a single-thread execution: | Sequential version. MIS over a preexisting, filtered subgraph ---------------------------------------------------------- Right now this uses an IStructure because it's (temporarily) better at blocking gets: Tradeoff: we use storage proportional to the ENTIRE graph. If the subset is very small, this is silly and we could use a sparse representation: Here's the loop that scans through the neighbors of a node. If we got to the end of the neighbors below us, then we are NOT disqualified: ------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------- Operate on a whole graph. Here's the loop that scans through the neighbors of a node. logDbgLn 3$ " [MIS] ... on nbr "++ show i++" of "++show numNbrs If we got to the end of the neighbors below us, then we are NOT disqualified: This should never block in a single-thread execution:
| Maximum independent set algorithms in lvish # LANGUAGE CPP , ScopedTypeVariables # module Data.LVar.Graph.MIS where import Utils import ( wait_clocks , runAndReport ) calibrate , measureFreq , commaint , import Control.LVish import Control.Monad import Data.Word import qualified Data.Vector.Unboxed as U import qualified Data.Vector.Unboxed.Mutable as M import qualified Data.Vector.Storable as UV import qualified Data.Vector.Storable.Mutable as MV import Data.Graph.Adjacency #ifdef NEW_CONTAINERS import Control.LVish.BulkRetry #endif #if 1 import Data.LVar.PureSet as S #else [ 2013.07.09 ] This one still is n't terminating on 125K+ Well , maybe it 's just slow ... 5000 takes 2 seconds . Yes , it 's literally over 100 times slower currently . import Data.LVar.SLSet as S #endif import Data.LVar.IStructure as ISt import Data.LVar.NatArray as NArr type DenseVertset s = NatArray s Word8 flag_UNDECIDED :: Word8 flag_CHOSEN :: Word8 flag_NBRCHOSEN :: Word8 flag_UNDECIDED = 0 flag_CHOSEN = 1 flag_NBRCHOSEN = 2 data VertState = Chosen | Undecided | NbrChosen instance where Minimal complete definition : sizeOf , alignment , one of peek , peekElemOff and peekByteOff , and one of poke , pokeElemOff and pokeByteOff . type ParFor e s = (Int,Int) -> (Int -> Par e s ()) -> Par e s () # INLINE maximalIndependentSet # maximalIndependentSet parFor gr@(AdjacencyGraph vvec evec) = do For each vertex , we record whether it is CHOSEN , not chosen , or undecided : let numVerts = U.length vvec flagsArr :: NatArray s Word8 <- newNatArray numVerts let loop !numNbrs !nbrs !selfInd !i | i == numNbrs = thisNodeWins | otherwise = do Find our Nbr 's NodeID selfInd' = fromIntegral selfInd if nbrInd > selfInd then thisNodeWins else do logDbgLn 3 (" [MIS] ! Getting on nbrInd "++show nbrInd) nbrFlag <- NArr.get flagsArr (fromIntegral nbrInd) logDbgLn 3 (" [MIS] ! Get completed on nbrInd "++show nbrInd) if nbrFlag == flag_CHOSEN then NArr.put flagsArr selfInd' flag_NBRCHOSEN else loop numNbrs nbrs selfInd (i+1) where thisNodeWins = logDbgLn 3 (" [MIS] ! Node chosen: "++show selfInd) >> NArr.put flagsArr (fromIntegral selfInd) flag_CHOSEN parFor (0,numVerts) $ \ ndIx -> do let nds = nbrs gr (fromIntegral ndIx) logDbgLn 3 $ " [ MIS ] processing node " + + show ndIx++ " nbrs " + + show loop (U.length nds) nds ndIx 0 return flagsArr maximalIndependentSet2 parFor gr@(AdjacencyGraph vvec evec) = do logDbgLn 3$ " [MIS] Beginning maximalIndependentSet / Istructures" For each vertex , we record whether it is CHOSEN , not chosen , or undecided : let numVerts = U.length vvec flagsArr <- newIStructure numVerts let loop !numNbrs !nbrs !selfInd !i | i == numNbrs = thisNodeWins | otherwise = do Find our Nbr 's NodeID selfInd' = fromIntegral selfInd if nbrInd > selfInd then thisNodeWins else do logDbgLn 3 (" [MIS] ! Getting on nbrInd "++show nbrInd) nbrFlag <- ISt.get flagsArr (fromIntegral nbrInd) logDbgLn 3 (" [MIS] ! Get completed on nbrInd "++show nbrInd) if nbrFlag == flag_CHOSEN then ISt.put_ flagsArr selfInd' flag_NBRCHOSEN else loop numNbrs nbrs selfInd (i+1) where thisNodeWins = logDbgLn 3 (" [MIS] ! Node chosen: "++show selfInd) >> ISt.put_ flagsArr (fromIntegral selfInd) flag_CHOSEN parFor (0,numVerts) $ \ ndIx -> do let nds = nbrs gr (fromIntegral ndIx) logDbgLn 3 $ " [ MIS ] processing node " + + show ndIx++ " nbrs " + + show loop (U.length nds) nds ndIx 0 return flagsArr maximalIndependentSet3 :: AdjacencyGraph -> (U.Vector Word8) maximalIndependentSet3 gr@(AdjacencyGraph vvec evec) = U.create $ do let numVerts = U.length vvec flagsArr <- M.replicate numVerts 0 let loop !numNbrs !nbrs !selfInd !i | i == numNbrs = thisNodeWins | otherwise = do Find our Nbr 's NodeID selfInd' = fromIntegral selfInd if nbrInd > selfInd then thisNodeWins else do nbrFlag <- M.read flagsArr (fromIntegral nbrInd) if nbrFlag == flag_CHOSEN then M.write flagsArr selfInd' flag_NBRCHOSEN else loop numNbrs nbrs selfInd (i+1) where thisNodeWins = M.write flagsArr (fromIntegral selfInd) flag_CHOSEN for_ (0,numVerts) $ \ ndIx -> do let nds = nbrs gr (fromIntegral ndIx) loop (U.length nds) nds ndIx 0 return flagsArr | Sequential version on NatArray ... maximalIndependentSet3B :: AdjacencyGraph -> (UV.Vector Word8) -> (UV.Vector Word8) maximalIndependentSet3B gr@(AdjacencyGraph vvec evec) vec = UV.create $ do let numVerts = U.length vvec flagsArr <- MV.replicate numVerts 0 let loop !numNbrs !nbrs !selfInd !i | i == numNbrs = thisNodeWins | otherwise = do Find our Nbr 's NodeID selfInd' = fromIntegral selfInd if nbrInd > selfInd then thisNodeWins else do nbrFlag <- MV.read flagsArr (fromIntegral nbrInd) if nbrFlag == flag_CHOSEN then MV.write flagsArr selfInd' flag_NBRCHOSEN else loop numNbrs nbrs selfInd (i+1) where thisNodeWins = MV.write flagsArr (fromIntegral selfInd) flag_CHOSEN for_ (0,numVerts) $ \ ndIx -> when (vec UV.! ndIx == 1) $ do let nds = nbrs gr (fromIntegral ndIx) loop (U.length nds) nds ndIx 0 return flagsArr maximalIndependentSet4 :: (HasGet e, HasPut e) => AdjacencyGraph -> (NatArray s Word8) -> Par e s (IStructure s Word8) maximalIndependentSet4 gr@(AdjacencyGraph vvec evec) vertSubset = do let numVerts = U.length vvec flagsArr <- newIStructure numVerts let loop !numNbrs !nbrs !selfInd !i | i == numNbrs = thisNodeWins | otherwise = do Find our Nbr 's NodeID selfInd' = fromIntegral selfInd if nbrInd > selfInd then thisNodeWins else do nbrFlag <- ISt.get flagsArr (fromIntegral nbrInd) if nbrFlag == flag_CHOSEN then ISt.put_ flagsArr selfInd' flag_NBRCHOSEN else loop numNbrs nbrs selfInd (i+1) where thisNodeWins = ISt.put_ flagsArr (fromIntegral selfInd) flag_CHOSEN NArr.forEach vertSubset $ \ ndIx _ -> let nds = nbrs gr (fromIntegral ndIx) in loop (U.length nds) nds ndIx 0 return flagsArr MIS using BulkRetry #ifdef NEW_CONTAINERS maximalIndependentSetBR gr@(AdjacencyGraph vvec _) = do For each vertex , we record whether it is CHOSEN , not chosen , or undecided : let numVerts = U.length vvec flagsArr :: NatArray s Word8 <- newNatArray numVerts let loop retryhub !numNbrs !nbrs !selfInd !i | i == numNbrs = thisNodeWins | otherwise = do Find our Nbr 's NodeID selfInd' = fromIntegral selfInd if nbrInd > selfInd then thisNodeWins else do logDbgLn 3 (" [MIS] ! Getting on nbrInd "++show nbrInd) getNB_cps retryhub flagsArr (fromIntegral nbrInd) $ \ nbrFlag -> do logDbgLn 3 (" [MIS] ! Get completed on nbrInd "++show nbrInd) if nbrFlag == flag_CHOSEN then NArr.put flagsArr selfInd' flag_NBRCHOSEN else loop retryhub numNbrs nbrs selfInd (i+1) where thisNodeWins = logDbgLn 3 (" [MIS] ! Node chosen: "++show selfInd) >> NArr.put flagsArr (fromIntegral selfInd) flag_CHOSEN forSpeculative (0,numVerts) $ \ retryhub ndIx -> do let nds = nbrs gr (fromIntegral ndIx) logDbgLn 3 $ " [ MIS ] processing node " + + show ndIx++ " nbrs " + + show loop retryhub (U.length nds) nds ndIx 0 return flagsArr #endif
6b2930f45106ae0942d51a5eb93468e9f4e99089752cfd8f4d040d83c3bb82ce
Helium4Haskell/helium
SimilarNegation.hs
module SimilarNegation where test :: Float test = - (3.0 + 6.0) test' :: Int test' = - 3 dit zijn nu syntax errors : test '' : : Float - > Float test '' ( - 1.0 ) = 1.0 test '' x = x + . 1.0 test '' ' : : Int - > Bool test '' ' ( - . 1 ) = True test '' ' _ = False test'' :: Float -> Float test'' (- 1.0) = 1.0 test'' x = x +. 1.0 test''' :: Int -> Bool test''' (-. 1) = True test''' _ = False -}
null
https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/typeerrors/Heuristics/SimilarNegation.hs
haskell
module SimilarNegation where test :: Float test = - (3.0 + 6.0) test' :: Int test' = - 3 dit zijn nu syntax errors : test '' : : Float - > Float test '' ( - 1.0 ) = 1.0 test '' x = x + . 1.0 test '' ' : : Int - > Bool test '' ' ( - . 1 ) = True test '' ' _ = False test'' :: Float -> Float test'' (- 1.0) = 1.0 test'' x = x +. 1.0 test''' :: Int -> Bool test''' (-. 1) = True test''' _ = False -}
6bb3a5553ef45882350105566c417adb5eae3d38cec865e8e254dd0c91c15674
aistrate/Okasaki
PairingHeap_Test.hs
import Test.HUnit import qualified Test.QuickCheck as QC import Data.List (sort) import Text.Printf (printf) import TestHelper import PairingHeap main = do printTime $ runTestTT hunitTests printTime $ mapM_ (\(s,a) -> printf "%-25s: " s >> a) qcheckTests hunitTests = TestList [ "fromList" ~: [ testHeap "" ~? "empty", testHeap ['a'..'z'] ~? "ascending", testHeap ['z','y'..'a'] ~? "descending", testHeap (['a'..'z'] ++ ['z','y'..'a']) ~? "combined asc/desc", testHeap (['z','y'..'a'] ++ ['a'..'z']) ~? "combined desc/asc", testHeap (['a'..'z'] ++ replicate 20 'm') ~? "asc/const" ], "merge" ~: [ testMerge ("", ['a'..'z']) ~? "empty/asc", testMerge (['a'..'z'], "") ~? "asc/empty", testMerge (['a'..'z'], ['z','y'..'a']) ~? "asc/desc", testMerge (['z','y'..'a'], ['a'..'z']) ~? "desc/asc" ] ] qcheckTests = [ ("fromList", qcheck (testHeap :: [Int] -> Bool)), ("merge", qcheck (testMerge :: ([Int], [Int]) -> Bool))] qcheck :: QC.Testable a => a -> IO () qcheck = --QC.quickCheck --QC.verboseCheck QC.check $ QC.defaultConfig { QC.configMaxTest = 500 } testHeap xs = testHeap' (fromList xs) (sort xs) testHeap' :: Ord a => PairingHeap a -> [a] -> Bool testHeap' h xs = toSortedList h == xs testMerge (xs, ys) = testHeap' (merge (fromList xs) (fromList ys)) (sort (xs ++ ys))
null
https://raw.githubusercontent.com/aistrate/Okasaki/cc1473c81d053483bb5e327409346da7fda10fb4/MyCode/Ch05/PairingHeap_Test.hs
haskell
QC.quickCheck QC.verboseCheck
import Test.HUnit import qualified Test.QuickCheck as QC import Data.List (sort) import Text.Printf (printf) import TestHelper import PairingHeap main = do printTime $ runTestTT hunitTests printTime $ mapM_ (\(s,a) -> printf "%-25s: " s >> a) qcheckTests hunitTests = TestList [ "fromList" ~: [ testHeap "" ~? "empty", testHeap ['a'..'z'] ~? "ascending", testHeap ['z','y'..'a'] ~? "descending", testHeap (['a'..'z'] ++ ['z','y'..'a']) ~? "combined asc/desc", testHeap (['z','y'..'a'] ++ ['a'..'z']) ~? "combined desc/asc", testHeap (['a'..'z'] ++ replicate 20 'm') ~? "asc/const" ], "merge" ~: [ testMerge ("", ['a'..'z']) ~? "empty/asc", testMerge (['a'..'z'], "") ~? "asc/empty", testMerge (['a'..'z'], ['z','y'..'a']) ~? "asc/desc", testMerge (['z','y'..'a'], ['a'..'z']) ~? "desc/asc" ] ] qcheckTests = [ ("fromList", qcheck (testHeap :: [Int] -> Bool)), ("merge", qcheck (testMerge :: ([Int], [Int]) -> Bool))] qcheck :: QC.Testable a => a -> IO () QC.check $ QC.defaultConfig { QC.configMaxTest = 500 } testHeap xs = testHeap' (fromList xs) (sort xs) testHeap' :: Ord a => PairingHeap a -> [a] -> Bool testHeap' h xs = toSortedList h == xs testMerge (xs, ys) = testHeap' (merge (fromList xs) (fromList ys)) (sort (xs ++ ys))
fc6121f4b5aaa111fd0e2f85c645bbe3a17178e80d78c1f134fb6e2775e24d69
eugenehr/erlyconv
cp437.erl
%% THIS FILE WAS AUTOMATICALLY GENERATED BY gen_src.pl FROM mappings / MICSFT / PC / CP437.TXT AT 2016 - 08 - 19 -module(cp437). -vsn(20160819). -export([to_unicode/1, from_unicode/1]). %% Public functions to_unicode(16#80) -> 16#00c7; to_unicode(16#81) -> 16#00fc; to_unicode(16#82) -> 16#00e9; to_unicode(16#83) -> 16#00e2; to_unicode(16#84) -> 16#00e4; to_unicode(16#85) -> 16#00e0; to_unicode(16#86) -> 16#00e5; to_unicode(16#87) -> 16#00e7; to_unicode(16#88) -> 16#00ea; to_unicode(16#89) -> 16#00eb; to_unicode(16#8a) -> 16#00e8; to_unicode(16#8b) -> 16#00ef; to_unicode(16#8c) -> 16#00ee; to_unicode(16#8d) -> 16#00ec; to_unicode(16#8e) -> 16#00c4; to_unicode(16#8f) -> 16#00c5; to_unicode(16#90) -> 16#00c9; to_unicode(16#91) -> 16#00e6; to_unicode(16#92) -> 16#00c6; to_unicode(16#93) -> 16#00f4; to_unicode(16#94) -> 16#00f6; to_unicode(16#95) -> 16#00f2; to_unicode(16#96) -> 16#00fb; to_unicode(16#97) -> 16#00f9; to_unicode(16#98) -> 16#00ff; to_unicode(16#99) -> 16#00d6; to_unicode(16#9a) -> 16#00dc; to_unicode(16#9b) -> 16#00a2; to_unicode(16#9c) -> 16#00a3; to_unicode(16#9d) -> 16#00a5; to_unicode(16#9e) -> 16#20a7; to_unicode(16#9f) -> 16#0192; to_unicode(16#a0) -> 16#00e1; to_unicode(16#a1) -> 16#00ed; to_unicode(16#a2) -> 16#00f3; to_unicode(16#a3) -> 16#00fa; to_unicode(16#a4) -> 16#00f1; to_unicode(16#a5) -> 16#00d1; to_unicode(16#a6) -> 16#00aa; to_unicode(16#a7) -> 16#00ba; to_unicode(16#a8) -> 16#00bf; to_unicode(16#a9) -> 16#2310; to_unicode(16#aa) -> 16#00ac; to_unicode(16#ab) -> 16#00bd; to_unicode(16#ac) -> 16#00bc; to_unicode(16#ad) -> 16#00a1; to_unicode(16#ae) -> 16#00ab; to_unicode(16#af) -> 16#00bb; to_unicode(16#b0) -> 16#2591; to_unicode(16#b1) -> 16#2592; to_unicode(16#b2) -> 16#2593; to_unicode(16#b3) -> 16#2502; to_unicode(16#b4) -> 16#2524; to_unicode(16#b5) -> 16#2561; to_unicode(16#b6) -> 16#2562; to_unicode(16#b7) -> 16#2556; to_unicode(16#b8) -> 16#2555; to_unicode(16#b9) -> 16#2563; to_unicode(16#ba) -> 16#2551; to_unicode(16#bb) -> 16#2557; to_unicode(16#bc) -> 16#255d; to_unicode(16#bd) -> 16#255c; to_unicode(16#be) -> 16#255b; to_unicode(16#bf) -> 16#2510; to_unicode(16#c0) -> 16#2514; to_unicode(16#c1) -> 16#2534; to_unicode(16#c2) -> 16#252c; to_unicode(16#c3) -> 16#251c; to_unicode(16#c4) -> 16#2500; to_unicode(16#c5) -> 16#253c; to_unicode(16#c6) -> 16#255e; to_unicode(16#c7) -> 16#255f; to_unicode(16#c8) -> 16#255a; to_unicode(16#c9) -> 16#2554; to_unicode(16#ca) -> 16#2569; to_unicode(16#cb) -> 16#2566; to_unicode(16#cc) -> 16#2560; to_unicode(16#cd) -> 16#2550; to_unicode(16#ce) -> 16#256c; to_unicode(16#cf) -> 16#2567; to_unicode(16#d0) -> 16#2568; to_unicode(16#d1) -> 16#2564; to_unicode(16#d2) -> 16#2565; to_unicode(16#d3) -> 16#2559; to_unicode(16#d4) -> 16#2558; to_unicode(16#d5) -> 16#2552; to_unicode(16#d6) -> 16#2553; to_unicode(16#d7) -> 16#256b; to_unicode(16#d8) -> 16#256a; to_unicode(16#d9) -> 16#2518; to_unicode(16#da) -> 16#250c; to_unicode(16#db) -> 16#2588; to_unicode(16#dc) -> 16#2584; to_unicode(16#dd) -> 16#258c; to_unicode(16#de) -> 16#2590; to_unicode(16#df) -> 16#2580; to_unicode(16#e0) -> 16#03b1; to_unicode(16#e1) -> 16#00df; to_unicode(16#e2) -> 16#0393; to_unicode(16#e3) -> 16#03c0; to_unicode(16#e4) -> 16#03a3; to_unicode(16#e5) -> 16#03c3; to_unicode(16#e6) -> 16#00b5; to_unicode(16#e7) -> 16#03c4; to_unicode(16#e8) -> 16#03a6; to_unicode(16#e9) -> 16#0398; to_unicode(16#ea) -> 16#03a9; to_unicode(16#eb) -> 16#03b4; to_unicode(16#ec) -> 16#221e; to_unicode(16#ed) -> 16#03c6; to_unicode(16#ee) -> 16#03b5; to_unicode(16#ef) -> 16#2229; to_unicode(16#f0) -> 16#2261; to_unicode(16#f1) -> 16#00b1; to_unicode(16#f2) -> 16#2265; to_unicode(16#f3) -> 16#2264; to_unicode(16#f4) -> 16#2320; to_unicode(16#f5) -> 16#2321; to_unicode(16#f6) -> 16#00f7; to_unicode(16#f7) -> 16#2248; to_unicode(16#f8) -> 16#00b0; to_unicode(16#f9) -> 16#2219; to_unicode(16#fa) -> 16#00b7; to_unicode(16#fb) -> 16#221a; to_unicode(16#fc) -> 16#207f; to_unicode(16#fd) -> 16#00b2; to_unicode(16#fe) -> 16#25a0; to_unicode(16#ff) -> 16#00a0; to_unicode(List) when is_list(List) -> [to_unicode(C) || C <- List]; to_unicode(Bin) when is_binary(Bin) -> bin_to_unicode(Bin, <<>>); to_unicode(Other) -> Other. from_unicode(16#00c7) -> 16#80; from_unicode(16#00fc) -> 16#81; from_unicode(16#00e9) -> 16#82; from_unicode(16#00e2) -> 16#83; from_unicode(16#00e4) -> 16#84; from_unicode(16#00e0) -> 16#85; from_unicode(16#00e5) -> 16#86; from_unicode(16#00e7) -> 16#87; from_unicode(16#00ea) -> 16#88; from_unicode(16#00eb) -> 16#89; from_unicode(16#00e8) -> 16#8a; from_unicode(16#00ef) -> 16#8b; from_unicode(16#00ee) -> 16#8c; from_unicode(16#00ec) -> 16#8d; from_unicode(16#00c4) -> 16#8e; from_unicode(16#00c5) -> 16#8f; from_unicode(16#00c9) -> 16#90; from_unicode(16#00e6) -> 16#91; from_unicode(16#00c6) -> 16#92; from_unicode(16#00f4) -> 16#93; from_unicode(16#00f6) -> 16#94; from_unicode(16#00f2) -> 16#95; from_unicode(16#00fb) -> 16#96; from_unicode(16#00f9) -> 16#97; from_unicode(16#00ff) -> 16#98; from_unicode(16#00d6) -> 16#99; from_unicode(16#00dc) -> 16#9a; from_unicode(16#00a2) -> 16#9b; from_unicode(16#00a3) -> 16#9c; from_unicode(16#00a5) -> 16#9d; from_unicode(16#20a7) -> 16#9e; from_unicode(16#0192) -> 16#9f; from_unicode(16#00e1) -> 16#a0; from_unicode(16#00ed) -> 16#a1; from_unicode(16#00f3) -> 16#a2; from_unicode(16#00fa) -> 16#a3; from_unicode(16#00f1) -> 16#a4; from_unicode(16#00d1) -> 16#a5; from_unicode(16#00aa) -> 16#a6; from_unicode(16#00ba) -> 16#a7; from_unicode(16#00bf) -> 16#a8; from_unicode(16#2310) -> 16#a9; from_unicode(16#00ac) -> 16#aa; from_unicode(16#00bd) -> 16#ab; from_unicode(16#00bc) -> 16#ac; from_unicode(16#00a1) -> 16#ad; from_unicode(16#00ab) -> 16#ae; from_unicode(16#00bb) -> 16#af; from_unicode(16#2591) -> 16#b0; from_unicode(16#2592) -> 16#b1; from_unicode(16#2593) -> 16#b2; from_unicode(16#2502) -> 16#b3; from_unicode(16#2524) -> 16#b4; from_unicode(16#2561) -> 16#b5; from_unicode(16#2562) -> 16#b6; from_unicode(16#2556) -> 16#b7; from_unicode(16#2555) -> 16#b8; from_unicode(16#2563) -> 16#b9; from_unicode(16#2551) -> 16#ba; from_unicode(16#2557) -> 16#bb; from_unicode(16#255d) -> 16#bc; from_unicode(16#255c) -> 16#bd; from_unicode(16#255b) -> 16#be; from_unicode(16#2510) -> 16#bf; from_unicode(16#2514) -> 16#c0; from_unicode(16#2534) -> 16#c1; from_unicode(16#252c) -> 16#c2; from_unicode(16#251c) -> 16#c3; from_unicode(16#2500) -> 16#c4; from_unicode(16#253c) -> 16#c5; from_unicode(16#255e) -> 16#c6; from_unicode(16#255f) -> 16#c7; from_unicode(16#255a) -> 16#c8; from_unicode(16#2554) -> 16#c9; from_unicode(16#2569) -> 16#ca; from_unicode(16#2566) -> 16#cb; from_unicode(16#2560) -> 16#cc; from_unicode(16#2550) -> 16#cd; from_unicode(16#256c) -> 16#ce; from_unicode(16#2567) -> 16#cf; from_unicode(16#2568) -> 16#d0; from_unicode(16#2564) -> 16#d1; from_unicode(16#2565) -> 16#d2; from_unicode(16#2559) -> 16#d3; from_unicode(16#2558) -> 16#d4; from_unicode(16#2552) -> 16#d5; from_unicode(16#2553) -> 16#d6; from_unicode(16#256b) -> 16#d7; from_unicode(16#256a) -> 16#d8; from_unicode(16#2518) -> 16#d9; from_unicode(16#250c) -> 16#da; from_unicode(16#2588) -> 16#db; from_unicode(16#2584) -> 16#dc; from_unicode(16#258c) -> 16#dd; from_unicode(16#2590) -> 16#de; from_unicode(16#2580) -> 16#df; from_unicode(16#03b1) -> 16#e0; from_unicode(16#00df) -> 16#e1; from_unicode(16#0393) -> 16#e2; from_unicode(16#03c0) -> 16#e3; from_unicode(16#03a3) -> 16#e4; from_unicode(16#03c3) -> 16#e5; from_unicode(16#00b5) -> 16#e6; from_unicode(16#03c4) -> 16#e7; from_unicode(16#03a6) -> 16#e8; from_unicode(16#0398) -> 16#e9; from_unicode(16#03a9) -> 16#ea; from_unicode(16#03b4) -> 16#eb; from_unicode(16#221e) -> 16#ec; from_unicode(16#03c6) -> 16#ed; from_unicode(16#03b5) -> 16#ee; from_unicode(16#2229) -> 16#ef; from_unicode(16#2261) -> 16#f0; from_unicode(16#00b1) -> 16#f1; from_unicode(16#2265) -> 16#f2; from_unicode(16#2264) -> 16#f3; from_unicode(16#2320) -> 16#f4; from_unicode(16#2321) -> 16#f5; from_unicode(16#00f7) -> 16#f6; from_unicode(16#2248) -> 16#f7; from_unicode(16#00b0) -> 16#f8; from_unicode(16#2219) -> 16#f9; from_unicode(16#00b7) -> 16#fa; from_unicode(16#221a) -> 16#fb; from_unicode(16#207f) -> 16#fc; from_unicode(16#00b2) -> 16#fd; from_unicode(16#25a0) -> 16#fe; from_unicode(16#00a0) -> 16#ff; from_unicode(List) when is_list(List) -> [from_unicode(C) || C <- List]; from_unicode(Bin) when is_binary(Bin) -> bin_from_unicode(Bin, <<>>); from_unicode(Other) -> Other. %% Private functions bin_to_unicode(<<>>, Bin) -> Bin; bin_to_unicode(<<C, Rest/binary>>, Acc) -> U = to_unicode(C), bin_to_unicode(Rest, <<Acc/binary, U/utf8>>). bin_from_unicode(<<>>, Bin) -> Bin; bin_from_unicode(<<U/utf8, Rest/binary>>, Acc) -> C = from_unicode(U), bin_from_unicode(Rest, <<Acc/binary, C>>).
null
https://raw.githubusercontent.com/eugenehr/erlyconv/ecdcd7db8f785c9638cd1ebad37ccd426c050cdf/src/cp437.erl
erlang
THIS FILE WAS AUTOMATICALLY GENERATED BY gen_src.pl Public functions Private functions
FROM mappings / MICSFT / PC / CP437.TXT AT 2016 - 08 - 19 -module(cp437). -vsn(20160819). -export([to_unicode/1, from_unicode/1]). to_unicode(16#80) -> 16#00c7; to_unicode(16#81) -> 16#00fc; to_unicode(16#82) -> 16#00e9; to_unicode(16#83) -> 16#00e2; to_unicode(16#84) -> 16#00e4; to_unicode(16#85) -> 16#00e0; to_unicode(16#86) -> 16#00e5; to_unicode(16#87) -> 16#00e7; to_unicode(16#88) -> 16#00ea; to_unicode(16#89) -> 16#00eb; to_unicode(16#8a) -> 16#00e8; to_unicode(16#8b) -> 16#00ef; to_unicode(16#8c) -> 16#00ee; to_unicode(16#8d) -> 16#00ec; to_unicode(16#8e) -> 16#00c4; to_unicode(16#8f) -> 16#00c5; to_unicode(16#90) -> 16#00c9; to_unicode(16#91) -> 16#00e6; to_unicode(16#92) -> 16#00c6; to_unicode(16#93) -> 16#00f4; to_unicode(16#94) -> 16#00f6; to_unicode(16#95) -> 16#00f2; to_unicode(16#96) -> 16#00fb; to_unicode(16#97) -> 16#00f9; to_unicode(16#98) -> 16#00ff; to_unicode(16#99) -> 16#00d6; to_unicode(16#9a) -> 16#00dc; to_unicode(16#9b) -> 16#00a2; to_unicode(16#9c) -> 16#00a3; to_unicode(16#9d) -> 16#00a5; to_unicode(16#9e) -> 16#20a7; to_unicode(16#9f) -> 16#0192; to_unicode(16#a0) -> 16#00e1; to_unicode(16#a1) -> 16#00ed; to_unicode(16#a2) -> 16#00f3; to_unicode(16#a3) -> 16#00fa; to_unicode(16#a4) -> 16#00f1; to_unicode(16#a5) -> 16#00d1; to_unicode(16#a6) -> 16#00aa; to_unicode(16#a7) -> 16#00ba; to_unicode(16#a8) -> 16#00bf; to_unicode(16#a9) -> 16#2310; to_unicode(16#aa) -> 16#00ac; to_unicode(16#ab) -> 16#00bd; to_unicode(16#ac) -> 16#00bc; to_unicode(16#ad) -> 16#00a1; to_unicode(16#ae) -> 16#00ab; to_unicode(16#af) -> 16#00bb; to_unicode(16#b0) -> 16#2591; to_unicode(16#b1) -> 16#2592; to_unicode(16#b2) -> 16#2593; to_unicode(16#b3) -> 16#2502; to_unicode(16#b4) -> 16#2524; to_unicode(16#b5) -> 16#2561; to_unicode(16#b6) -> 16#2562; to_unicode(16#b7) -> 16#2556; to_unicode(16#b8) -> 16#2555; to_unicode(16#b9) -> 16#2563; to_unicode(16#ba) -> 16#2551; to_unicode(16#bb) -> 16#2557; to_unicode(16#bc) -> 16#255d; to_unicode(16#bd) -> 16#255c; to_unicode(16#be) -> 16#255b; to_unicode(16#bf) -> 16#2510; to_unicode(16#c0) -> 16#2514; to_unicode(16#c1) -> 16#2534; to_unicode(16#c2) -> 16#252c; to_unicode(16#c3) -> 16#251c; to_unicode(16#c4) -> 16#2500; to_unicode(16#c5) -> 16#253c; to_unicode(16#c6) -> 16#255e; to_unicode(16#c7) -> 16#255f; to_unicode(16#c8) -> 16#255a; to_unicode(16#c9) -> 16#2554; to_unicode(16#ca) -> 16#2569; to_unicode(16#cb) -> 16#2566; to_unicode(16#cc) -> 16#2560; to_unicode(16#cd) -> 16#2550; to_unicode(16#ce) -> 16#256c; to_unicode(16#cf) -> 16#2567; to_unicode(16#d0) -> 16#2568; to_unicode(16#d1) -> 16#2564; to_unicode(16#d2) -> 16#2565; to_unicode(16#d3) -> 16#2559; to_unicode(16#d4) -> 16#2558; to_unicode(16#d5) -> 16#2552; to_unicode(16#d6) -> 16#2553; to_unicode(16#d7) -> 16#256b; to_unicode(16#d8) -> 16#256a; to_unicode(16#d9) -> 16#2518; to_unicode(16#da) -> 16#250c; to_unicode(16#db) -> 16#2588; to_unicode(16#dc) -> 16#2584; to_unicode(16#dd) -> 16#258c; to_unicode(16#de) -> 16#2590; to_unicode(16#df) -> 16#2580; to_unicode(16#e0) -> 16#03b1; to_unicode(16#e1) -> 16#00df; to_unicode(16#e2) -> 16#0393; to_unicode(16#e3) -> 16#03c0; to_unicode(16#e4) -> 16#03a3; to_unicode(16#e5) -> 16#03c3; to_unicode(16#e6) -> 16#00b5; to_unicode(16#e7) -> 16#03c4; to_unicode(16#e8) -> 16#03a6; to_unicode(16#e9) -> 16#0398; to_unicode(16#ea) -> 16#03a9; to_unicode(16#eb) -> 16#03b4; to_unicode(16#ec) -> 16#221e; to_unicode(16#ed) -> 16#03c6; to_unicode(16#ee) -> 16#03b5; to_unicode(16#ef) -> 16#2229; to_unicode(16#f0) -> 16#2261; to_unicode(16#f1) -> 16#00b1; to_unicode(16#f2) -> 16#2265; to_unicode(16#f3) -> 16#2264; to_unicode(16#f4) -> 16#2320; to_unicode(16#f5) -> 16#2321; to_unicode(16#f6) -> 16#00f7; to_unicode(16#f7) -> 16#2248; to_unicode(16#f8) -> 16#00b0; to_unicode(16#f9) -> 16#2219; to_unicode(16#fa) -> 16#00b7; to_unicode(16#fb) -> 16#221a; to_unicode(16#fc) -> 16#207f; to_unicode(16#fd) -> 16#00b2; to_unicode(16#fe) -> 16#25a0; to_unicode(16#ff) -> 16#00a0; to_unicode(List) when is_list(List) -> [to_unicode(C) || C <- List]; to_unicode(Bin) when is_binary(Bin) -> bin_to_unicode(Bin, <<>>); to_unicode(Other) -> Other. from_unicode(16#00c7) -> 16#80; from_unicode(16#00fc) -> 16#81; from_unicode(16#00e9) -> 16#82; from_unicode(16#00e2) -> 16#83; from_unicode(16#00e4) -> 16#84; from_unicode(16#00e0) -> 16#85; from_unicode(16#00e5) -> 16#86; from_unicode(16#00e7) -> 16#87; from_unicode(16#00ea) -> 16#88; from_unicode(16#00eb) -> 16#89; from_unicode(16#00e8) -> 16#8a; from_unicode(16#00ef) -> 16#8b; from_unicode(16#00ee) -> 16#8c; from_unicode(16#00ec) -> 16#8d; from_unicode(16#00c4) -> 16#8e; from_unicode(16#00c5) -> 16#8f; from_unicode(16#00c9) -> 16#90; from_unicode(16#00e6) -> 16#91; from_unicode(16#00c6) -> 16#92; from_unicode(16#00f4) -> 16#93; from_unicode(16#00f6) -> 16#94; from_unicode(16#00f2) -> 16#95; from_unicode(16#00fb) -> 16#96; from_unicode(16#00f9) -> 16#97; from_unicode(16#00ff) -> 16#98; from_unicode(16#00d6) -> 16#99; from_unicode(16#00dc) -> 16#9a; from_unicode(16#00a2) -> 16#9b; from_unicode(16#00a3) -> 16#9c; from_unicode(16#00a5) -> 16#9d; from_unicode(16#20a7) -> 16#9e; from_unicode(16#0192) -> 16#9f; from_unicode(16#00e1) -> 16#a0; from_unicode(16#00ed) -> 16#a1; from_unicode(16#00f3) -> 16#a2; from_unicode(16#00fa) -> 16#a3; from_unicode(16#00f1) -> 16#a4; from_unicode(16#00d1) -> 16#a5; from_unicode(16#00aa) -> 16#a6; from_unicode(16#00ba) -> 16#a7; from_unicode(16#00bf) -> 16#a8; from_unicode(16#2310) -> 16#a9; from_unicode(16#00ac) -> 16#aa; from_unicode(16#00bd) -> 16#ab; from_unicode(16#00bc) -> 16#ac; from_unicode(16#00a1) -> 16#ad; from_unicode(16#00ab) -> 16#ae; from_unicode(16#00bb) -> 16#af; from_unicode(16#2591) -> 16#b0; from_unicode(16#2592) -> 16#b1; from_unicode(16#2593) -> 16#b2; from_unicode(16#2502) -> 16#b3; from_unicode(16#2524) -> 16#b4; from_unicode(16#2561) -> 16#b5; from_unicode(16#2562) -> 16#b6; from_unicode(16#2556) -> 16#b7; from_unicode(16#2555) -> 16#b8; from_unicode(16#2563) -> 16#b9; from_unicode(16#2551) -> 16#ba; from_unicode(16#2557) -> 16#bb; from_unicode(16#255d) -> 16#bc; from_unicode(16#255c) -> 16#bd; from_unicode(16#255b) -> 16#be; from_unicode(16#2510) -> 16#bf; from_unicode(16#2514) -> 16#c0; from_unicode(16#2534) -> 16#c1; from_unicode(16#252c) -> 16#c2; from_unicode(16#251c) -> 16#c3; from_unicode(16#2500) -> 16#c4; from_unicode(16#253c) -> 16#c5; from_unicode(16#255e) -> 16#c6; from_unicode(16#255f) -> 16#c7; from_unicode(16#255a) -> 16#c8; from_unicode(16#2554) -> 16#c9; from_unicode(16#2569) -> 16#ca; from_unicode(16#2566) -> 16#cb; from_unicode(16#2560) -> 16#cc; from_unicode(16#2550) -> 16#cd; from_unicode(16#256c) -> 16#ce; from_unicode(16#2567) -> 16#cf; from_unicode(16#2568) -> 16#d0; from_unicode(16#2564) -> 16#d1; from_unicode(16#2565) -> 16#d2; from_unicode(16#2559) -> 16#d3; from_unicode(16#2558) -> 16#d4; from_unicode(16#2552) -> 16#d5; from_unicode(16#2553) -> 16#d6; from_unicode(16#256b) -> 16#d7; from_unicode(16#256a) -> 16#d8; from_unicode(16#2518) -> 16#d9; from_unicode(16#250c) -> 16#da; from_unicode(16#2588) -> 16#db; from_unicode(16#2584) -> 16#dc; from_unicode(16#258c) -> 16#dd; from_unicode(16#2590) -> 16#de; from_unicode(16#2580) -> 16#df; from_unicode(16#03b1) -> 16#e0; from_unicode(16#00df) -> 16#e1; from_unicode(16#0393) -> 16#e2; from_unicode(16#03c0) -> 16#e3; from_unicode(16#03a3) -> 16#e4; from_unicode(16#03c3) -> 16#e5; from_unicode(16#00b5) -> 16#e6; from_unicode(16#03c4) -> 16#e7; from_unicode(16#03a6) -> 16#e8; from_unicode(16#0398) -> 16#e9; from_unicode(16#03a9) -> 16#ea; from_unicode(16#03b4) -> 16#eb; from_unicode(16#221e) -> 16#ec; from_unicode(16#03c6) -> 16#ed; from_unicode(16#03b5) -> 16#ee; from_unicode(16#2229) -> 16#ef; from_unicode(16#2261) -> 16#f0; from_unicode(16#00b1) -> 16#f1; from_unicode(16#2265) -> 16#f2; from_unicode(16#2264) -> 16#f3; from_unicode(16#2320) -> 16#f4; from_unicode(16#2321) -> 16#f5; from_unicode(16#00f7) -> 16#f6; from_unicode(16#2248) -> 16#f7; from_unicode(16#00b0) -> 16#f8; from_unicode(16#2219) -> 16#f9; from_unicode(16#00b7) -> 16#fa; from_unicode(16#221a) -> 16#fb; from_unicode(16#207f) -> 16#fc; from_unicode(16#00b2) -> 16#fd; from_unicode(16#25a0) -> 16#fe; from_unicode(16#00a0) -> 16#ff; from_unicode(List) when is_list(List) -> [from_unicode(C) || C <- List]; from_unicode(Bin) when is_binary(Bin) -> bin_from_unicode(Bin, <<>>); from_unicode(Other) -> Other. bin_to_unicode(<<>>, Bin) -> Bin; bin_to_unicode(<<C, Rest/binary>>, Acc) -> U = to_unicode(C), bin_to_unicode(Rest, <<Acc/binary, U/utf8>>). bin_from_unicode(<<>>, Bin) -> Bin; bin_from_unicode(<<U/utf8, Rest/binary>>, Acc) -> C = from_unicode(U), bin_from_unicode(Rest, <<Acc/binary, C>>).
291e75ac5623116ef644d6e7cc620034d44e2506faec1f81312a562db4a364c6
cloudant/mem3
mem3_httpd.erl
Copyright 2010 Cloudant % 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(mem3_httpd). -export([handle_membership_req/1, handle_shards_req/2]). %% includes -include("mem3.hrl"). -include_lib("couch/include/couch_db.hrl"). handle_membership_req(#httpd{method='GET', path_parts=[<<"_membership">>]} = Req) -> ClusterNodes = try mem3:nodes() catch _:_ -> {ok,[]} end, couch_httpd:send_json(Req, {[ {all_nodes, lists:sort([node()|nodes()])}, {cluster_nodes, lists:sort(ClusterNodes)} ]}). handle_shards_req(#httpd{method='GET', path_parts=[_DbName, <<"_shards">>]} = Req, Db) -> DbName = mem3:dbname(Db#db.name), Shards = mem3:shards(DbName), JsonShards = json_shards(Shards, dict:new()), couch_httpd:send_json(Req, {[ {shards, JsonShards} ]}); handle_shards_req(#httpd{method='GET', path_parts=[_DbName, <<"_shards">>, DocId]} = Req, Db) -> DbName = mem3:dbname(Db#db.name), Shards = mem3:shards(DbName, DocId), {[{Shard, Dbs}]} = json_shards(Shards, dict:new()), couch_httpd:send_json(Req, {[ {range, Shard}, {nodes, Dbs} ]}). %% %% internal %% json_shards([], AccIn) -> List = dict:to_list(AccIn), {lists:sort(List)}; json_shards([#shard{node=Node, range=[B,E]} | Rest], AccIn) -> HexBeg = couch_util:to_hex(<<B:32/integer>>), HexEnd = couch_util:to_hex(<<E:32/integer>>), Range = list_to_binary(HexBeg ++ "-" ++ HexEnd), json_shards(Rest, dict:append(Range, Node, AccIn)).
null
https://raw.githubusercontent.com/cloudant/mem3/49b41333f6acd2e9154e182cf66b67efaf58ac7b/src/mem3_httpd.erl
erlang
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 WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. includes internal
Copyright 2010 Cloudant Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not distributed under the License is distributed on an " AS IS " BASIS , WITHOUT -module(mem3_httpd). -export([handle_membership_req/1, handle_shards_req/2]). -include("mem3.hrl"). -include_lib("couch/include/couch_db.hrl"). handle_membership_req(#httpd{method='GET', path_parts=[<<"_membership">>]} = Req) -> ClusterNodes = try mem3:nodes() catch _:_ -> {ok,[]} end, couch_httpd:send_json(Req, {[ {all_nodes, lists:sort([node()|nodes()])}, {cluster_nodes, lists:sort(ClusterNodes)} ]}). handle_shards_req(#httpd{method='GET', path_parts=[_DbName, <<"_shards">>]} = Req, Db) -> DbName = mem3:dbname(Db#db.name), Shards = mem3:shards(DbName), JsonShards = json_shards(Shards, dict:new()), couch_httpd:send_json(Req, {[ {shards, JsonShards} ]}); handle_shards_req(#httpd{method='GET', path_parts=[_DbName, <<"_shards">>, DocId]} = Req, Db) -> DbName = mem3:dbname(Db#db.name), Shards = mem3:shards(DbName, DocId), {[{Shard, Dbs}]} = json_shards(Shards, dict:new()), couch_httpd:send_json(Req, {[ {range, Shard}, {nodes, Dbs} ]}). json_shards([], AccIn) -> List = dict:to_list(AccIn), {lists:sort(List)}; json_shards([#shard{node=Node, range=[B,E]} | Rest], AccIn) -> HexBeg = couch_util:to_hex(<<B:32/integer>>), HexEnd = couch_util:to_hex(<<E:32/integer>>), Range = list_to_binary(HexBeg ++ "-" ++ HexEnd), json_shards(Rest, dict:append(Range, Node, AccIn)).
739a62c26386c3774dc5f45e6a418972d6c39bad0c7e228780027f93e0b08876
xh4/web-toolkit
array.lisp
(in-package :json) (defclass array () ((value :initarg :value :initform nil :accessor value))) (defmethod initialize-instance :after ((array array) &key) (check-type (value array) list)) (defun array-form (array) (check-type array array) `(array ,@(value array))) (defmethod print-object ((array array) stream) (prin1 (array-form array) stream)) (defun array (&rest values) (make-instance 'array :value values))
null
https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/json/array.lisp
lisp
(in-package :json) (defclass array () ((value :initarg :value :initform nil :accessor value))) (defmethod initialize-instance :after ((array array) &key) (check-type (value array) list)) (defun array-form (array) (check-type array array) `(array ,@(value array))) (defmethod print-object ((array array) stream) (prin1 (array-form array) stream)) (defun array (&rest values) (make-instance 'array :value values))
0de7d4833f27b658baa503e281ac1bc904572290bee71724382dec6dfbbc6478
wireapp/wire-server
ParseExistsError.hs
module ParseExistsError where import Amazonka.Types import Gundeck.Aws import Gundeck.Aws.Arn import Gundeck.Types.Push.V2 (Transport (APNS)) import Imports import Test.Tasty import Test.Tasty.HUnit tests :: TestTree tests = testGroup "parseExistsError" [ testCase "parse error string from real world example" parseErrorTest, testCase "parse errors" parseErrors ] parseErrorTest :: Assertion parseErrorTest = let e = Just $ ErrorMessage "Invalid parameter: Token Reason: Endpoint arn:aws:sns:eu-west-1:093205192929:endpoint/APNS/staging-com.wire.dev.ent/f90c8f08-a0a1-33bc-aa43-23c94770d936 already exists with the same Token, but different attributes." expectedTopic = mkEndpointTopic (ArnEnv "staging") APNS "com.wire.dev.ent" (EndpointId "f90c8f08-a0a1-33bc-aa43-23c94770d936") expected = mkSnsArn Ireland (Account "093205192929") expectedTopic in parseExistsError e @?= Just expected parseErrors :: Assertion parseErrors = do parseExistsError Nothing @?= Nothing parseExistsError ((Just . ErrorMessage) "Invalid parameter: Token Reason: Endpoint") @?= Nothing parseExistsError ( (Just . ErrorMessage) "Invalid parameter: Token Reason: Endpoint NO_ARN already exists with the same Token, but different attributes." ) @?= Nothing parseExistsError ( (Just . ErrorMessage) "Invalid parameter: Token Reason: Endpoint arn:aws:sns:eu-west-1:093205192929:endpoint/APNS/staging-com.wire.dev.ent/f90c8f08-a0a1-33bc-aa43-23c94770d936" ) @?= Nothing
null
https://raw.githubusercontent.com/wireapp/wire-server/1c8534679d3e7f453acf7fa52df2c28590cc522b/services/gundeck/test/unit/ParseExistsError.hs
haskell
module ParseExistsError where import Amazonka.Types import Gundeck.Aws import Gundeck.Aws.Arn import Gundeck.Types.Push.V2 (Transport (APNS)) import Imports import Test.Tasty import Test.Tasty.HUnit tests :: TestTree tests = testGroup "parseExistsError" [ testCase "parse error string from real world example" parseErrorTest, testCase "parse errors" parseErrors ] parseErrorTest :: Assertion parseErrorTest = let e = Just $ ErrorMessage "Invalid parameter: Token Reason: Endpoint arn:aws:sns:eu-west-1:093205192929:endpoint/APNS/staging-com.wire.dev.ent/f90c8f08-a0a1-33bc-aa43-23c94770d936 already exists with the same Token, but different attributes." expectedTopic = mkEndpointTopic (ArnEnv "staging") APNS "com.wire.dev.ent" (EndpointId "f90c8f08-a0a1-33bc-aa43-23c94770d936") expected = mkSnsArn Ireland (Account "093205192929") expectedTopic in parseExistsError e @?= Just expected parseErrors :: Assertion parseErrors = do parseExistsError Nothing @?= Nothing parseExistsError ((Just . ErrorMessage) "Invalid parameter: Token Reason: Endpoint") @?= Nothing parseExistsError ( (Just . ErrorMessage) "Invalid parameter: Token Reason: Endpoint NO_ARN already exists with the same Token, but different attributes." ) @?= Nothing parseExistsError ( (Just . ErrorMessage) "Invalid parameter: Token Reason: Endpoint arn:aws:sns:eu-west-1:093205192929:endpoint/APNS/staging-com.wire.dev.ent/f90c8f08-a0a1-33bc-aa43-23c94770d936" ) @?= Nothing
c719fd6b4f407ead54c63cd3c7eaadcc57b75ca5fbc46988448d739f410d8721
bzg/woof
web.clj
Copyright ( c ) 2022 - 2023 Bastien Guerry < > SPDX - License - Identifier : EPL-2.0 ;; License-Filename: LICENSES/EPL-2.0.txt (ns bzg.web (:require [reitit.ring :as ring] [bzg.core :as core] [bzg.i18n :as i18n] [bzg.data :as data] [bzg.fetch :as fetch] [bzg.db :as db] [clojure.string :as string] [ring.middleware.params :as params] [reitit.ring.middleware.parameters :as parameters] [ring.middleware.cors :refer [wrap-cors]] [selmer.parser :as html] [selmer.filters :as filters] [markdown.core :as md] [clojure.java.io :as io] [datalevin.core :as d])) (filters/add-filter! :concat #(string/join "," %)) (defn- entries-format [{:keys [source-id entries sorting-by]}] (let [message-format (not-empty (core/archived-message {:source-id source-id})) linkify-maybe (cond message-format #(assoc-in % [:link] (format message-format (:message-id %))) (:archived-at (first entries)) #(assoc-in % [:link] (:archived-at %)) :else identity)] (->> entries (sort-by (condp = sorting-by "date" :date "user" :role "status" :status "priority" :priority "refs" :refs-count ;; See comment in `compute-vote` on why `read-string` "vote" #(read-string (:vote %)) "related" #(count (:related-refs %)) :priority)) reverse (remove nil?) (map linkify-maybe)))) (defn- html-defaults [& [source-id]] (let [sources (filter #(not (:hidden (val %))) (:sources db/config)) source-cfg (or (get sources source-id source-id) (and (= 1 (count sources)) (val (first sources))))] (-> (merge (:ui db/config) (:ui source-cfg) {:display (or (:pages (:ui source-cfg)) (:pages (:ui db/config)))}) (dissoc :pages)))) (defn- with-html-defaults [config-defaults {:keys [source] :as m}] (merge (html-defaults (:source-id source)) {:config (merge config-defaults {:admin-address (:admin-address db/config)})} {:sources (->> (:sources db/config) (map (fn [[k v]] (when-not (:hidden v) {:source-id k :slug (:slug v) :doc (:doc v)}))) (remove nil?))} m)) (def emails-re (re-pattern (str "(?:" core/email-re "[;,]?)+"))) (defn- parse-search-string [s] (when s (let [ ;; TODO: Could we safely use email-re as msgid-re? msgid-re #"[^\s]+" version-re #"([<>=]*)([^\s]+)" re-find-in-search (fn [s search & [re pre]] (-> (re-find (re-pattern (format "(?:^|\\s)%s(?:%s)?:(%s)" (first s) (subs s 1) (or re emails-re))) search) (as-> r (if pre (take-last 2 r) (peek r))))) from (re-find-in-search "from" s) acked (re-find-in-search "acked" s) owned (re-find-in-search "owned" s) closed (re-find-in-search "closed" s) version (re-find-in-search "version" s version-re :prefix) msg (re-find-in-search "msg" s msgid-re) raw (-> s (string/replace (re-pattern (format "(?:^|\\s)[faoc](rom|cked|wned|losed)?:%s" emails-re)) "") (string/replace #"(?:^|\s)v(ersion)?:[^\s]+" "") (string/replace #"(?:^|\s)m(sg)?:[^\s]+" "") string/trim)] {:from from :acked-by acked :owned-by owned :closed-by closed :version (not-empty (replace {"" "="} version)) :msg-id msg :raw raw}))) (defn- page-index [page source-id slug-end format-params config-defaults] (let [search (:search format-params) search-els (parse-search-string search) closed? (:closed? format-params) source (when source-id {:source-id source-id :slug (:slug (get (:sources db/config) source-id))}) ui-config (if source-id (:ui (get (:sources db/config) source-id)) (:ui db/config))] (with-html-defaults config-defaults {:source source :search search :closed? closed? :page (name page) :columns (or (:columns (page (:pages ui-config))) #{:priority :vote :from :date :related-refs :refs-count :status}) :slug-end (or (not-empty slug-end) "index") :entries (entries-format (merge {:entries (map #(assoc % :source-slug (core/source-id-to-slug (:source-id %))) (condp = page :index (fetch/index source-id search-els closed?) :news (fetch/news source-id search-els closed?) :bug (fetch/bugs source-id search-els closed?) :patch (fetch/patches source-id search-els closed?) :request (fetch/requests source-id search-els closed?)))} format-params))}))) (defn- page-sources [_ source-id _ _ config-defaults] (with-html-defaults config-defaults {:page "sources" :source {:source-id source-id :slug (:slug (get (:sources db/config) source-id))}})) (defn- page-overview [_ source-id _ _ config-defaults] (with-html-defaults config-defaults {:source (when source-id {:source-id source-id :slug (:slug (get (:sources db/config) source-id))}) :page "overview" ;; TODO: Implement overview features here })) (defn- page-404 [_ source-id _ _ config-defaults] (with-html-defaults config-defaults {:source (when source-id {:source-id source-id :slug (:slug (get (:sources db/config) source-id))}) :page "404"})) (defn- page-howto [_ source-id _ _ config-defaults] (with-html-defaults config-defaults {:page "howto" :source (when source-id (let [src-cfg (get (:sources db/config) source-id) strj (fn [m] (string/join ", " m))] {:source-id source-id :slug (:slug src-cfg) :watch (->> (or (:watch src-cfg) (:watch db/config)) (map (fn [[k v]] {:report (name k) :prefix (strj (:subject-prefix v)) :match (strj (:subject-match v)) :doc (:doc v) :triggers (strj (flatten (vals (:triggers v))))})))})) :howto (md/md-to-html-string (slurp (io/resource "md/howto.md")))})) (defn- get-patch-body [{:keys [msgid]}] (let [msg (ffirst (d/q `[:find ?e :where [?e :message-id ~msgid] [?e :patch-body]] db/db)) patch-body (not-empty (:patch-body (d/entity db/db msg)))] {:status 200 :headers {"Content-Type" "text/plain"} :body (or patch-body "Can't find a patch here")})) (defn- get-page [page {:keys [query-params path-params uri headers]}] (let [format-params {:search (or (get query-params "search") "") :closed? (or (get query-params "closed") "") :sorting-by (get query-params "sorting-by")} lang (if-let [lang (get headers "accept-language")] (subs lang 0 2) "en") config-defaults (conj (into {} (d/entity db/db [:defaults "init"])) {:i18n (get i18n/langs (keyword lang))}) html-page (condp = page :sources {:html "/sources.html" :fn page-sources} :howto {:html "/howto.html" :fn page-howto} :overview {:html "/overview.html" :fn page-overview} :404 {:html "/404.html" :fn page-404} {:html "/index.html" :fn page-index}) slug-end (or (peek (re-find #"/([^/]+)$" (or uri ""))) "") source-id (core/slug-to-source-id (:source-slug path-params)) theme (if (re-find #"Emacs" (or (get headers "user-agent") "")) "plain" (:theme db/config))] {:status 200 :headers {"Content-Type" "text/html"} :body (html/render-file (io/resource (str "themes/" theme (:html html-page))) ((:fn html-page) page source-id slug-end format-params config-defaults))})) (def handler (ring/ring-handler (ring/router [["/" ["" {:get #(get-page :index %)}] ["index:format" {:get #(data/get-all-data %)}] ["sources" {:get #(get-page :sources %)}] ["howto" {:get #(get-page :howto %)}] ["overview" {:get #(get-page :overview %)}] ["news" ["" {:get #(get-page :news %)}] [":format" {:get #(data/get-news-data %)}]] ["bugs" ["" {:get #(get-page :bug %)}] [":format" {:get #(data/get-bugs-data %)}]] ["patches" ["" {:get #(get-page :patch %)}] [":format" {:get #(data/get-patches-data %)}]] ["requests" ["" {:get #(get-page :request %)}] [":format" {:get #(data/get-requests-data %)}]] ;; Patch body ["patch/:msgid" ["" {:get #(get-patch-body %)}]] ;; List per source ["source/:source-slug/" ["" {:get #(get-page :index %)}] ["index:format" {:get #(data/get-all-data %)}] ["howto" {:get #(get-page :howto %)}] ["overview" {:get #(get-page :overview %)}] ["news" ["" {:get #(get-page :news %)}] [":format" {:get #(data/get-all-data %)}]] ["bugs" ["" {:get #(get-page :bug %)}] [":format" {:get #(data/get-bugs-data %)}]] ["patches" ["" {:get #(get-page :patch %)}] [":format" {:get #(data/get-patches-data %)}]] ["requests" ["" {:get #(get-page :request %)}] [":format" {:get #(data/get-requests-data %)}]]]]] {:data {:middleware [params/wrap-params]}}) (ring/create-default-handler {:not-found (fn [_] (get-page :404 nil))}) {:middleware [parameters/parameters-middleware #(wrap-cors % :access-control-allow-origin [#"^*$"] :access-control-allow-methods [:get])]}))
null
https://raw.githubusercontent.com/bzg/woof/d0cb841d62391122ab232fd4c241c138726120c9/src/bzg/web.clj
clojure
License-Filename: LICENSES/EPL-2.0.txt See comment in `compute-vote` on why `read-string` TODO: Could we safely use email-re as msgid-re? TODO: Implement overview features here Patch body List per source
Copyright ( c ) 2022 - 2023 Bastien Guerry < > SPDX - License - Identifier : EPL-2.0 (ns bzg.web (:require [reitit.ring :as ring] [bzg.core :as core] [bzg.i18n :as i18n] [bzg.data :as data] [bzg.fetch :as fetch] [bzg.db :as db] [clojure.string :as string] [ring.middleware.params :as params] [reitit.ring.middleware.parameters :as parameters] [ring.middleware.cors :refer [wrap-cors]] [selmer.parser :as html] [selmer.filters :as filters] [markdown.core :as md] [clojure.java.io :as io] [datalevin.core :as d])) (filters/add-filter! :concat #(string/join "," %)) (defn- entries-format [{:keys [source-id entries sorting-by]}] (let [message-format (not-empty (core/archived-message {:source-id source-id})) linkify-maybe (cond message-format #(assoc-in % [:link] (format message-format (:message-id %))) (:archived-at (first entries)) #(assoc-in % [:link] (:archived-at %)) :else identity)] (->> entries (sort-by (condp = sorting-by "date" :date "user" :role "status" :status "priority" :priority "refs" :refs-count "vote" #(read-string (:vote %)) "related" #(count (:related-refs %)) :priority)) reverse (remove nil?) (map linkify-maybe)))) (defn- html-defaults [& [source-id]] (let [sources (filter #(not (:hidden (val %))) (:sources db/config)) source-cfg (or (get sources source-id source-id) (and (= 1 (count sources)) (val (first sources))))] (-> (merge (:ui db/config) (:ui source-cfg) {:display (or (:pages (:ui source-cfg)) (:pages (:ui db/config)))}) (dissoc :pages)))) (defn- with-html-defaults [config-defaults {:keys [source] :as m}] (merge (html-defaults (:source-id source)) {:config (merge config-defaults {:admin-address (:admin-address db/config)})} {:sources (->> (:sources db/config) (map (fn [[k v]] (when-not (:hidden v) {:source-id k :slug (:slug v) :doc (:doc v)}))) (remove nil?))} m)) (def emails-re (re-pattern (str "(?:" core/email-re "[;,]?)+"))) (defn- parse-search-string [s] (when s (let [ msgid-re #"[^\s]+" version-re #"([<>=]*)([^\s]+)" re-find-in-search (fn [s search & [re pre]] (-> (re-find (re-pattern (format "(?:^|\\s)%s(?:%s)?:(%s)" (first s) (subs s 1) (or re emails-re))) search) (as-> r (if pre (take-last 2 r) (peek r))))) from (re-find-in-search "from" s) acked (re-find-in-search "acked" s) owned (re-find-in-search "owned" s) closed (re-find-in-search "closed" s) version (re-find-in-search "version" s version-re :prefix) msg (re-find-in-search "msg" s msgid-re) raw (-> s (string/replace (re-pattern (format "(?:^|\\s)[faoc](rom|cked|wned|losed)?:%s" emails-re)) "") (string/replace #"(?:^|\s)v(ersion)?:[^\s]+" "") (string/replace #"(?:^|\s)m(sg)?:[^\s]+" "") string/trim)] {:from from :acked-by acked :owned-by owned :closed-by closed :version (not-empty (replace {"" "="} version)) :msg-id msg :raw raw}))) (defn- page-index [page source-id slug-end format-params config-defaults] (let [search (:search format-params) search-els (parse-search-string search) closed? (:closed? format-params) source (when source-id {:source-id source-id :slug (:slug (get (:sources db/config) source-id))}) ui-config (if source-id (:ui (get (:sources db/config) source-id)) (:ui db/config))] (with-html-defaults config-defaults {:source source :search search :closed? closed? :page (name page) :columns (or (:columns (page (:pages ui-config))) #{:priority :vote :from :date :related-refs :refs-count :status}) :slug-end (or (not-empty slug-end) "index") :entries (entries-format (merge {:entries (map #(assoc % :source-slug (core/source-id-to-slug (:source-id %))) (condp = page :index (fetch/index source-id search-els closed?) :news (fetch/news source-id search-els closed?) :bug (fetch/bugs source-id search-els closed?) :patch (fetch/patches source-id search-els closed?) :request (fetch/requests source-id search-els closed?)))} format-params))}))) (defn- page-sources [_ source-id _ _ config-defaults] (with-html-defaults config-defaults {:page "sources" :source {:source-id source-id :slug (:slug (get (:sources db/config) source-id))}})) (defn- page-overview [_ source-id _ _ config-defaults] (with-html-defaults config-defaults {:source (when source-id {:source-id source-id :slug (:slug (get (:sources db/config) source-id))}) :page "overview" })) (defn- page-404 [_ source-id _ _ config-defaults] (with-html-defaults config-defaults {:source (when source-id {:source-id source-id :slug (:slug (get (:sources db/config) source-id))}) :page "404"})) (defn- page-howto [_ source-id _ _ config-defaults] (with-html-defaults config-defaults {:page "howto" :source (when source-id (let [src-cfg (get (:sources db/config) source-id) strj (fn [m] (string/join ", " m))] {:source-id source-id :slug (:slug src-cfg) :watch (->> (or (:watch src-cfg) (:watch db/config)) (map (fn [[k v]] {:report (name k) :prefix (strj (:subject-prefix v)) :match (strj (:subject-match v)) :doc (:doc v) :triggers (strj (flatten (vals (:triggers v))))})))})) :howto (md/md-to-html-string (slurp (io/resource "md/howto.md")))})) (defn- get-patch-body [{:keys [msgid]}] (let [msg (ffirst (d/q `[:find ?e :where [?e :message-id ~msgid] [?e :patch-body]] db/db)) patch-body (not-empty (:patch-body (d/entity db/db msg)))] {:status 200 :headers {"Content-Type" "text/plain"} :body (or patch-body "Can't find a patch here")})) (defn- get-page [page {:keys [query-params path-params uri headers]}] (let [format-params {:search (or (get query-params "search") "") :closed? (or (get query-params "closed") "") :sorting-by (get query-params "sorting-by")} lang (if-let [lang (get headers "accept-language")] (subs lang 0 2) "en") config-defaults (conj (into {} (d/entity db/db [:defaults "init"])) {:i18n (get i18n/langs (keyword lang))}) html-page (condp = page :sources {:html "/sources.html" :fn page-sources} :howto {:html "/howto.html" :fn page-howto} :overview {:html "/overview.html" :fn page-overview} :404 {:html "/404.html" :fn page-404} {:html "/index.html" :fn page-index}) slug-end (or (peek (re-find #"/([^/]+)$" (or uri ""))) "") source-id (core/slug-to-source-id (:source-slug path-params)) theme (if (re-find #"Emacs" (or (get headers "user-agent") "")) "plain" (:theme db/config))] {:status 200 :headers {"Content-Type" "text/html"} :body (html/render-file (io/resource (str "themes/" theme (:html html-page))) ((:fn html-page) page source-id slug-end format-params config-defaults))})) (def handler (ring/ring-handler (ring/router [["/" ["" {:get #(get-page :index %)}] ["index:format" {:get #(data/get-all-data %)}] ["sources" {:get #(get-page :sources %)}] ["howto" {:get #(get-page :howto %)}] ["overview" {:get #(get-page :overview %)}] ["news" ["" {:get #(get-page :news %)}] [":format" {:get #(data/get-news-data %)}]] ["bugs" ["" {:get #(get-page :bug %)}] [":format" {:get #(data/get-bugs-data %)}]] ["patches" ["" {:get #(get-page :patch %)}] [":format" {:get #(data/get-patches-data %)}]] ["requests" ["" {:get #(get-page :request %)}] [":format" {:get #(data/get-requests-data %)}]] ["patch/:msgid" ["" {:get #(get-patch-body %)}]] ["source/:source-slug/" ["" {:get #(get-page :index %)}] ["index:format" {:get #(data/get-all-data %)}] ["howto" {:get #(get-page :howto %)}] ["overview" {:get #(get-page :overview %)}] ["news" ["" {:get #(get-page :news %)}] [":format" {:get #(data/get-all-data %)}]] ["bugs" ["" {:get #(get-page :bug %)}] [":format" {:get #(data/get-bugs-data %)}]] ["patches" ["" {:get #(get-page :patch %)}] [":format" {:get #(data/get-patches-data %)}]] ["requests" ["" {:get #(get-page :request %)}] [":format" {:get #(data/get-requests-data %)}]]]]] {:data {:middleware [params/wrap-params]}}) (ring/create-default-handler {:not-found (fn [_] (get-page :404 nil))}) {:middleware [parameters/parameters-middleware #(wrap-cors % :access-control-allow-origin [#"^*$"] :access-control-allow-methods [:get])]}))
c285403b481386ea1e814041ee5f3130338a6886b1dccae2b895f1aaf35cffe8
yesodweb/serversession
TestImport.hs
module TestImport ( module TestImport , module X ) where import Application import ClassyPrelude as X hiding (delete, deleteBy, Handler) import Database.Persist as X hiding (get) import Database.Persist.Sql import Database.Persist.Sql.Types.Internal (connEscapeRawName) import Foundation as X import Model as X import Test.Hspec as X import Yesod.Default.Config2 (useEnv, loadYamlSettings) import Yesod.Test as X import Yesod.Core.Unsafe (fakeHandlerGetLogger) -- Wiping the database import Database.Persist.Sqlite (sqlDatabase, mkSqliteConnectionInfo, fkEnabled, createSqlitePoolFromInfo) import Control.Monad.Logger (runLoggingT) import Lens.Micro (set) import Settings (appDatabaseConf) import Yesod.Core (messageLoggerSource) runDB :: SqlPersistM a -> YesodExample App a runDB query = do pool <- fmap appConnPool getTestYesod liftIO $ runSqlPersistMPool query pool runHandler :: Handler a -> YesodExample App a runHandler handler = do app <- getTestYesod fakeHandlerGetLogger appLogger app handler withApp :: SpecWith (TestApp App) -> Spec withApp = before $ do settings <- loadYamlSettings ["config/test-settings.yml", "config/settings.yml"] [] useEnv foundation <- makeFoundation settings wipeDB foundation logWare <- liftIO $ makeLogWare foundation return (foundation, logWare) -- This function will truncate all of the tables in your database. -- 'withApp' calls it before each test, creating a clean environment for each -- spec to run in. wipeDB :: App -> IO () wipeDB app = do -- In order to wipe the database, we need to use a connection which has -- foreign key checks disabled. Foreign key checks are enabled or disabled -- per connection, so this won't effect queries outside this function. -- -- Aside: foreign key checks are enabled by persistent-sqlite, as of version 2.6.2 , unless they are explicitly disabled in the -- SqliteConnectionInfo. let logFunc = messageLoggerSource app (appLogger app) let dbName = sqlDatabase $ appDatabaseConf $ appSettings app connInfo = set fkEnabled False $ mkSqliteConnectionInfo dbName pool <- runLoggingT (createSqlitePoolFromInfo connInfo 1) logFunc flip runSqlPersistMPool pool $ do tables <- getTables sqlBackend <- ask let queries = map (\t -> "DELETE FROM " ++ (connEscapeRawName sqlBackend t)) tables forM_ queries (\q -> rawExecute q []) getTables :: MonadIO m => ReaderT SqlBackend m [Text] getTables = do tables <- rawSql "SELECT name FROM sqlite_master WHERE type = 'table';" [] return (fmap unSingle tables)
null
https://raw.githubusercontent.com/yesodweb/serversession/bdede5fb660890df670f103d64a5e69024b13e57/examples/serversession-example-yesod-persistent/test/TestImport.hs
haskell
Wiping the database This function will truncate all of the tables in your database. 'withApp' calls it before each test, creating a clean environment for each spec to run in. In order to wipe the database, we need to use a connection which has foreign key checks disabled. Foreign key checks are enabled or disabled per connection, so this won't effect queries outside this function. Aside: foreign key checks are enabled by persistent-sqlite, as of SqliteConnectionInfo.
module TestImport ( module TestImport , module X ) where import Application import ClassyPrelude as X hiding (delete, deleteBy, Handler) import Database.Persist as X hiding (get) import Database.Persist.Sql import Database.Persist.Sql.Types.Internal (connEscapeRawName) import Foundation as X import Model as X import Test.Hspec as X import Yesod.Default.Config2 (useEnv, loadYamlSettings) import Yesod.Test as X import Yesod.Core.Unsafe (fakeHandlerGetLogger) import Database.Persist.Sqlite (sqlDatabase, mkSqliteConnectionInfo, fkEnabled, createSqlitePoolFromInfo) import Control.Monad.Logger (runLoggingT) import Lens.Micro (set) import Settings (appDatabaseConf) import Yesod.Core (messageLoggerSource) runDB :: SqlPersistM a -> YesodExample App a runDB query = do pool <- fmap appConnPool getTestYesod liftIO $ runSqlPersistMPool query pool runHandler :: Handler a -> YesodExample App a runHandler handler = do app <- getTestYesod fakeHandlerGetLogger appLogger app handler withApp :: SpecWith (TestApp App) -> Spec withApp = before $ do settings <- loadYamlSettings ["config/test-settings.yml", "config/settings.yml"] [] useEnv foundation <- makeFoundation settings wipeDB foundation logWare <- liftIO $ makeLogWare foundation return (foundation, logWare) wipeDB :: App -> IO () wipeDB app = do version 2.6.2 , unless they are explicitly disabled in the let logFunc = messageLoggerSource app (appLogger app) let dbName = sqlDatabase $ appDatabaseConf $ appSettings app connInfo = set fkEnabled False $ mkSqliteConnectionInfo dbName pool <- runLoggingT (createSqlitePoolFromInfo connInfo 1) logFunc flip runSqlPersistMPool pool $ do tables <- getTables sqlBackend <- ask let queries = map (\t -> "DELETE FROM " ++ (connEscapeRawName sqlBackend t)) tables forM_ queries (\q -> rawExecute q []) getTables :: MonadIO m => ReaderT SqlBackend m [Text] getTables = do tables <- rawSql "SELECT name FROM sqlite_master WHERE type = 'table';" [] return (fmap unSingle tables)
0d27518f2dd67701ad3ee600d01937e73199f6770e6895f6d6671d7aca642dd1
links-lang/links
debug.ml
let debug = ref false let set_debug b = debug := b let print s = if !debug then prerr_endline s
null
https://raw.githubusercontent.com/links-lang/links/2923893c80677b67cacc6747a25b5bcd65c4c2b6/lens/debug.ml
ocaml
let debug = ref false let set_debug b = debug := b let print s = if !debug then prerr_endline s
dc86b1fa6d92fd3e705d04a84c4f988723066e84ff6882bfbd176d5d11cebad2
openmusic-project/openmusic
package.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; package.lisp --- TRIVIAL-FEATURES-TESTS package definition. ;;; Copyright ( C ) 2007 , ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies of the Software , and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . ;;; THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (in-package :cl-user) (defpackage :trivial-features-tests (:use :common-lisp :regression-test :alexandria :cffi))
null
https://raw.githubusercontent.com/openmusic-project/openmusic/9560c064512a1598cd57bcc9f0151c0815178e6f/OPENMUSIC/code/api/foreign-interface/ffi/trivial-features/tests/package.lisp
lisp
-*- Mode: lisp; indent-tabs-mode: nil -*- package.lisp --- TRIVIAL-FEATURES-TESTS package definition. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Copyright ( C ) 2007 , files ( the " Software " ) , to deal in the Software without of the Software , and to permit persons to whom the Software is included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , (in-package :cl-user) (defpackage :trivial-features-tests (:use :common-lisp :regression-test :alexandria :cffi))
62ebb2ab692bddef5b081c38074a8eee8f2410963a59b4014945b4ec7898bb10
mpickering/apply-refact
Default37.hs
yes = concat $ Data.List.intersperse " " xs
null
https://raw.githubusercontent.com/mpickering/apply-refact/a4343ea0f4f9d8c2e16d6b16b9068f321ba4f272/tests/examples/Default37.hs
haskell
yes = concat $ Data.List.intersperse " " xs
4873dc199f7017d5b8b89f75c75dffecf519bc5ea4018d5308e6707d4cca605c
andreypopp/type-systems
syntax.ml
open! Base type name = string [@@deriving sexp_of] and id = int and lvl = int type expr = | E_var of name | E_abs of name list * expr | E_app of expr * expr list | E_let of (name * expr * ty_sch option) * expr | E_lit of lit [@@deriving sexp_of] and lit = Lit_string of string | Lit_int of int and ty = | Ty_const of name | Ty_var of var | Ty_app of ty * ty list | Ty_arr of ty list * ty and var = var_data Union_find.t and var_data = { id : int; mutable lvl : lvl option; (** Levels are assigned when we enter [C_exists] or [C_let] constraints *) mutable ty : ty option; (** Types are discovered as a result of unification. *) } and ty_sch = var list * ty module Names : sig type t val make : unit -> t val alloc : t -> id -> string val lookup : t -> id -> string option end = struct type t = (Int.t, string) Hashtbl.t let make () = Hashtbl.create (module Int) let alloc names id = let i = Hashtbl.length names in let name = String.make 1 (Char.of_int_exn (97 + Int.rem i 26)) ^ if i >= 26 then Int.to_string (i / 26) else "" in Hashtbl.set names ~key:id ~data:name; name let lookup names id = Hashtbl.find names id end module MakeId () = struct let c = ref 0 let fresh () = Int.incr c; !c let reset () = c := 0 end module type SHOWABLE = sig type t val layout : t -> PPrint.document val show : t -> string val print : ?label:string -> t -> unit end module Showable (S : sig type t val layout : t -> PPrint.document end) : SHOWABLE with type t = S.t = struct type t = S.t let layout = S.layout let show v = let width = 60 in let buf = Buffer.create 100 in PPrint.ToBuffer.pretty 1. width buf (S.layout v); Buffer.contents buf let print ?label v = match label with | Some label -> Caml.print_endline (label ^ ": " ^ show v) | None -> Caml.print_endline (show v) end module type DUMPABLE = sig type t val dump : ?label:string -> t -> unit val sdump : ?label:string -> t -> string end module Dumpable (S : sig type t val sexp_of_t : t -> Sexp.t end) : DUMPABLE with type t = S.t = struct type t = S.t let dump ?label v = let s = S.sexp_of_t v in match label with | None -> Caml.Format.printf "%a@." Sexp.pp_hum s | Some label -> Caml.Format.printf "%s %a@." label Sexp.pp_hum s let sdump ?label v = let s = S.sexp_of_t v in match label with | None -> Caml.Format.asprintf "%a@." Sexp.pp_hum s | Some label -> Caml.Format.asprintf "%s %a@." label Sexp.pp_hum s end let layout_var v = let open PPrint in let lvl = Option.(v.lvl |> map ~f:Int.to_string |> value ~default:"!") in if Debug.log_levels then string (Printf.sprintf "_%i@%s" v.id lvl) else string (Printf.sprintf "_%i" v.id) let rec layout_expr' ~names = let open PPrint in function | E_var name -> string name | E_abs (args, body) -> let sep = comma ^^ blank 1 in let newline = (* Always break on let inside the body. *) match body with | E_let _ -> hardline | _ -> break 1 in let args = match args with | [ arg ] -> string arg | args -> parens (separate sep (List.map args ~f:string)) in group (group (string "fun " ^^ args ^^ string " ->") ^^ nest 2 (group (newline ^^ group (layout_expr' ~names body)))) | E_app (f, args) -> let sep = comma ^^ break 1 in group (layout_expr' ~names f ^^ parens (nest 2 (group (break 0 ^^ separate sep (List.map args ~f:(layout_expr' ~names)))))) | E_let _ as e -> let es = We do not want to print multiple nested let - expression with indents and therefore we linearize them first and print on the same indent instead . therefore we linearize them first and print on the same indent instead. *) let rec linearize es e = match e with | E_let (_, b) -> linearize (e :: es) b | e -> e :: es in List.rev (linearize [] e) in let newline = If there 's more than a single let - expression found ( checking length > 2 because the body of the last let - expression too ) we split them with a hardline . because es containts the body of the last let-expression too) we split them with a hardline. *) if List.length es > 2 then hardline else break 1 in concat (List.map es ~f:(function | E_let ((name, expr, ty_sch), _) -> let ascription = We need to layout ty_sch first as it will allocate names for use down the road . down the road. *) match ty_sch with | None -> empty | Some ty_sch -> string " :" ^^ nest 4 (break 1 ^^ layout_ty_sch' ~names ty_sch) in let expr_newline = (* If there's [let x = let y = ... in ... in ...] then we want to force break. *) match expr with | E_let _ -> hardline | _ -> break 1 in group (group (string "let " ^^ string name ^^ ascription ^^ string " =") ^^ nest 2 (expr_newline ^^ layout_expr' ~names expr) ^^ expr_newline ^^ string "in") ^^ newline | e -> layout_expr' ~names e)) | E_lit (Lit_string v) -> dquotes (string v) | E_lit (Lit_int v) -> dquotes (string (Int.to_string v)) and layout_ty' ~names ty = let open PPrint in let rec is_ty_arr = function | Ty_var var -> ( match (Union_find.value var).ty with | None -> false | Some ty -> is_ty_arr ty) | Ty_arr _ -> true | _ -> false in let rec layout_ty = function | Ty_const name -> string name | Ty_arr ([ aty ], rty) -> (* Check if we can layout this as simply as [aty -> try] in case of a single argument. *) (if is_ty_arr aty then If the single arg is the Ty_arr we need to wrap it in parens . parens (layout_ty aty) else layout_ty aty) ^^ string " -> " ^^ layout_ty rty | Ty_arr (atys, rty) -> let sep = comma ^^ blank 1 in parens (separate sep (List.map atys ~f:layout_ty)) ^^ string " -> " ^^ layout_ty rty | Ty_app (fty, atys) -> let sep = comma ^^ blank 1 in layout_ty fty ^^ brackets (separate sep (List.map atys ~f:layout_ty)) | Ty_var var -> ( let data = Union_find.value var in match data.ty with | None -> layout_con_var' ~names var | Some ty -> layout_ty ty) in layout_ty ty and layout_con_var' ~names v = let open PPrint in let v = Union_find.value v in match v.ty with | Some ty -> layout_ty' ~names ty | None -> ( match Names.lookup names v.id with | Some name -> if Debug.log_levels then string name ^^ parens (layout_var v) else string name | None -> layout_var v) and layout_ty_sch' ~names ty_sch = let open PPrint in match ty_sch with | [], ty -> layout_ty' ~names ty | vs, ty -> let vs = layout_var_prenex' ~names vs in group (vs ^^ layout_ty' ~names ty) and layout_var_prenex' ~names vs = let open PPrint in let sep = comma ^^ blank 1 in let vs = List.map vs ~f:(fun v -> let v = Union_find.value v in string (Names.alloc names v.id)) in separate sep vs ^^ string " . " module Expr = struct type t = expr include ( Showable (struct type t = expr let layout e = layout_expr' ~names:(Names.make ()) e end) : SHOWABLE with type t := t) include ( Dumpable (struct type t = expr let sexp_of_t = sexp_of_expr end) : DUMPABLE with type t := t) end module Ty = struct type t = ty let arr a b = Ty_arr (a, b) let var var = Ty_var var include ( Showable (struct type t = ty let layout ty = layout_ty' ~names:(Names.make ()) ty end) : SHOWABLE with type t := t) include ( Dumpable (struct type t = ty let sexp_of_t = sexp_of_ty end) : DUMPABLE with type t := t) end module Ty_sch = struct type t = ty_sch include ( Showable (struct type t = ty_sch let layout ty_sch = layout_ty_sch' ~names:(Names.make ()) ty_sch end) : SHOWABLE with type t := t) include ( Dumpable (struct type t = ty_sch let sexp_of_t = sexp_of_ty_sch end) : DUMPABLE with type t := t) end
null
https://raw.githubusercontent.com/andreypopp/type-systems/d379e6ebc73914189b0054549f6c0191319c443a/hmx/syntax.ml
ocaml
* Levels are assigned when we enter [C_exists] or [C_let] constraints * Types are discovered as a result of unification. Always break on let inside the body. If there's [let x = let y = ... in ... in ...] then we want to force break. Check if we can layout this as simply as [aty -> try] in case of a single argument.
open! Base type name = string [@@deriving sexp_of] and id = int and lvl = int type expr = | E_var of name | E_abs of name list * expr | E_app of expr * expr list | E_let of (name * expr * ty_sch option) * expr | E_lit of lit [@@deriving sexp_of] and lit = Lit_string of string | Lit_int of int and ty = | Ty_const of name | Ty_var of var | Ty_app of ty * ty list | Ty_arr of ty list * ty and var = var_data Union_find.t and var_data = { id : int; mutable lvl : lvl option; mutable ty : ty option; } and ty_sch = var list * ty module Names : sig type t val make : unit -> t val alloc : t -> id -> string val lookup : t -> id -> string option end = struct type t = (Int.t, string) Hashtbl.t let make () = Hashtbl.create (module Int) let alloc names id = let i = Hashtbl.length names in let name = String.make 1 (Char.of_int_exn (97 + Int.rem i 26)) ^ if i >= 26 then Int.to_string (i / 26) else "" in Hashtbl.set names ~key:id ~data:name; name let lookup names id = Hashtbl.find names id end module MakeId () = struct let c = ref 0 let fresh () = Int.incr c; !c let reset () = c := 0 end module type SHOWABLE = sig type t val layout : t -> PPrint.document val show : t -> string val print : ?label:string -> t -> unit end module Showable (S : sig type t val layout : t -> PPrint.document end) : SHOWABLE with type t = S.t = struct type t = S.t let layout = S.layout let show v = let width = 60 in let buf = Buffer.create 100 in PPrint.ToBuffer.pretty 1. width buf (S.layout v); Buffer.contents buf let print ?label v = match label with | Some label -> Caml.print_endline (label ^ ": " ^ show v) | None -> Caml.print_endline (show v) end module type DUMPABLE = sig type t val dump : ?label:string -> t -> unit val sdump : ?label:string -> t -> string end module Dumpable (S : sig type t val sexp_of_t : t -> Sexp.t end) : DUMPABLE with type t = S.t = struct type t = S.t let dump ?label v = let s = S.sexp_of_t v in match label with | None -> Caml.Format.printf "%a@." Sexp.pp_hum s | Some label -> Caml.Format.printf "%s %a@." label Sexp.pp_hum s let sdump ?label v = let s = S.sexp_of_t v in match label with | None -> Caml.Format.asprintf "%a@." Sexp.pp_hum s | Some label -> Caml.Format.asprintf "%s %a@." label Sexp.pp_hum s end let layout_var v = let open PPrint in let lvl = Option.(v.lvl |> map ~f:Int.to_string |> value ~default:"!") in if Debug.log_levels then string (Printf.sprintf "_%i@%s" v.id lvl) else string (Printf.sprintf "_%i" v.id) let rec layout_expr' ~names = let open PPrint in function | E_var name -> string name | E_abs (args, body) -> let sep = comma ^^ blank 1 in let newline = match body with | E_let _ -> hardline | _ -> break 1 in let args = match args with | [ arg ] -> string arg | args -> parens (separate sep (List.map args ~f:string)) in group (group (string "fun " ^^ args ^^ string " ->") ^^ nest 2 (group (newline ^^ group (layout_expr' ~names body)))) | E_app (f, args) -> let sep = comma ^^ break 1 in group (layout_expr' ~names f ^^ parens (nest 2 (group (break 0 ^^ separate sep (List.map args ~f:(layout_expr' ~names)))))) | E_let _ as e -> let es = We do not want to print multiple nested let - expression with indents and therefore we linearize them first and print on the same indent instead . therefore we linearize them first and print on the same indent instead. *) let rec linearize es e = match e with | E_let (_, b) -> linearize (e :: es) b | e -> e :: es in List.rev (linearize [] e) in let newline = If there 's more than a single let - expression found ( checking length > 2 because the body of the last let - expression too ) we split them with a hardline . because es containts the body of the last let-expression too) we split them with a hardline. *) if List.length es > 2 then hardline else break 1 in concat (List.map es ~f:(function | E_let ((name, expr, ty_sch), _) -> let ascription = We need to layout ty_sch first as it will allocate names for use down the road . down the road. *) match ty_sch with | None -> empty | Some ty_sch -> string " :" ^^ nest 4 (break 1 ^^ layout_ty_sch' ~names ty_sch) in let expr_newline = match expr with | E_let _ -> hardline | _ -> break 1 in group (group (string "let " ^^ string name ^^ ascription ^^ string " =") ^^ nest 2 (expr_newline ^^ layout_expr' ~names expr) ^^ expr_newline ^^ string "in") ^^ newline | e -> layout_expr' ~names e)) | E_lit (Lit_string v) -> dquotes (string v) | E_lit (Lit_int v) -> dquotes (string (Int.to_string v)) and layout_ty' ~names ty = let open PPrint in let rec is_ty_arr = function | Ty_var var -> ( match (Union_find.value var).ty with | None -> false | Some ty -> is_ty_arr ty) | Ty_arr _ -> true | _ -> false in let rec layout_ty = function | Ty_const name -> string name | Ty_arr ([ aty ], rty) -> (if is_ty_arr aty then If the single arg is the Ty_arr we need to wrap it in parens . parens (layout_ty aty) else layout_ty aty) ^^ string " -> " ^^ layout_ty rty | Ty_arr (atys, rty) -> let sep = comma ^^ blank 1 in parens (separate sep (List.map atys ~f:layout_ty)) ^^ string " -> " ^^ layout_ty rty | Ty_app (fty, atys) -> let sep = comma ^^ blank 1 in layout_ty fty ^^ brackets (separate sep (List.map atys ~f:layout_ty)) | Ty_var var -> ( let data = Union_find.value var in match data.ty with | None -> layout_con_var' ~names var | Some ty -> layout_ty ty) in layout_ty ty and layout_con_var' ~names v = let open PPrint in let v = Union_find.value v in match v.ty with | Some ty -> layout_ty' ~names ty | None -> ( match Names.lookup names v.id with | Some name -> if Debug.log_levels then string name ^^ parens (layout_var v) else string name | None -> layout_var v) and layout_ty_sch' ~names ty_sch = let open PPrint in match ty_sch with | [], ty -> layout_ty' ~names ty | vs, ty -> let vs = layout_var_prenex' ~names vs in group (vs ^^ layout_ty' ~names ty) and layout_var_prenex' ~names vs = let open PPrint in let sep = comma ^^ blank 1 in let vs = List.map vs ~f:(fun v -> let v = Union_find.value v in string (Names.alloc names v.id)) in separate sep vs ^^ string " . " module Expr = struct type t = expr include ( Showable (struct type t = expr let layout e = layout_expr' ~names:(Names.make ()) e end) : SHOWABLE with type t := t) include ( Dumpable (struct type t = expr let sexp_of_t = sexp_of_expr end) : DUMPABLE with type t := t) end module Ty = struct type t = ty let arr a b = Ty_arr (a, b) let var var = Ty_var var include ( Showable (struct type t = ty let layout ty = layout_ty' ~names:(Names.make ()) ty end) : SHOWABLE with type t := t) include ( Dumpable (struct type t = ty let sexp_of_t = sexp_of_ty end) : DUMPABLE with type t := t) end module Ty_sch = struct type t = ty_sch include ( Showable (struct type t = ty_sch let layout ty_sch = layout_ty_sch' ~names:(Names.make ()) ty_sch end) : SHOWABLE with type t := t) include ( Dumpable (struct type t = ty_sch let sexp_of_t = sexp_of_ty_sch end) : DUMPABLE with type t := t) end
979640f7168a88b163c73c9568ac8bc66af56a45b6c4bbce23fdd2625c369a9d
abakst/Brisk
Extract.hs
# LANGUAGE ScopedTypeVariables # # LANGUAGE FlexibleInstances # # LANGUAGE UndecidableInstances # module Brisk.Model.Extract where import GHC (GhcMonad) import GhcPlugins hiding ((<+>), pp, text, Subst, Id, mkTyVar, tyVarName) import qualified GhcPlugins as Ghc import Type as Ty import TyCoRep as Tr import Name import Control.Monad.Trans.State import Control.Monad.State hiding (get, gets, modify) import Data.Function import Data.List import Data.Maybe import PrelNames import Text.Show.Pretty (ppShow) import qualified Data.Set as Set import qualified Brisk.Model.Env as Env import Brisk.Transform.ANF (anormalize) import Brisk.Model.GhcInterface import Brisk.Model.Types import Brisk.Model.Builtins import Brisk.Model.Prolog hiding (BriskAnnot(..)) -- import Brisk.Model.Promela import Brisk.Model.IceT (runIceT, HasType(..)) import Brisk.Pretty import Text.PrettyPrint.HughesPJ as PP type MGen a = StateT MGState IO a data MGState = MGS { hscEnv :: !HscEnv , modGuts :: !ModGuts , impureTys :: ![Id] , procTy :: !Id , cnt :: !Int , srcSpans :: ![SrcSpan] } initialEState : : HscEnv - > ModGuts - > Var - > MGState initialEState henv mg p t = MGS { hscEnv = henv , modGuts = mg , impureTys = t , procTy = p , cnt = 0 , srcSpans = [noSrcSpan] } type EffMap = Env.Env Id AbsEff instance Annot TyAnnot where dummyAnnot = (Nothing, noSrcSpan) instance HasType TyAnnot where getType = fst setType t (_,l) = (t,l) pushSpan :: RealSrcSpan -> MGen () pushSpan ss = modify $ \s -> s { srcSpans = RealSrcSpan ss : srcSpans s } currentSpan :: MGen SrcSpan currentSpan = head <$> gets srcSpans popSpan :: MGen SrcSpan popSpan = do span:spans <- gets srcSpans modify $ \s -> s { srcSpans = spans } return span noAnnot :: Functor f => f a -> f TyAnnot noAnnot = fmap (const dummyAnnot) specAnnot :: Maybe Ty.Type -> TyAnnot specAnnot t = (idOfType <$> t, noSrcSpan) annotType :: CoreExpr -> AbsEff -> AbsEff annotType e t = t { annot = a } where a | isTypeArg e = annot t | otherwise = (Just (exprEType e), snd (annot t)) idOfType = ofType tyConId (tyVarName . nameId) exprEType = idOfType . exprType liftAnnot t = (t, noSrcSpan) specTableEnv :: SpecTableIn -> EffMap specTableEnv (SpecTable tab) = Env.addsEnv Env.empty [ (x, liftAnnot <$> t) | x :<=: t <- tab ] impureTypes = [ ("Control.Distributed.Process.Internal.Types", "Process") , ("Control.Distributed.Static", "Closure") ] runMGen :: [String] -> HscEnv -> ModGuts -> SpecTableIn -> CoreProgram -> IO SpecTableOut runMGen bs hsenv mg specs@(SpecTable speccies) prog = do -- initBinds <- resolve hsenv (specTuple <$> specs) -- let g0 = Env.addsEnv Env.empty [ (nameId x, specAnnot <$> b) | (x,b) <- initBinds ] prog' <- liftIO $ anormalize hsenv mg prog builtin ' < - do forM ( let SpecTable ts = builtin in ts ) $ \(x : < = : t ) - > do let ( m , n ) = nm < - ghcVarName hsenv m n -- return (nameId nm :<=: t) putStrLn ( briskShowPpr prog ' ) binfix binfix = SpecTable builtin ' impureTys <- forM impureTypes $ fmap nameId . uncurry (ghcTyName hsenv) procTy <- nameId <$> ghcTyName hsenv "Control.Distributed.Process.Internal.Types" "Process" g <- evalStateT (go g0 prog') (initialEState hsenv mg procTy impureTys) ns <- forM bs findModuleNameId let all = Env.toList g brisk = filter ((`elem` ns) . fst) all -- dumpBinds all dumpBinds brisk forM_ brisk (putStrLn . render . PP.vcat . fmap pp . snd . runIceT . snd) forM_ brisk (putStrLn . toBriskString . snd) return $ SpecTable [ x :<=: e | (x,e) <- all ] where go :: EffMap -> CoreProgram -> MGen EffMap go = foldM mGenBind findModuleNameId b = nameId <$> lookupName hsenv (mg_module mg) b isPure :: Ty.Type -> MGen Bool isPure t = do ty <- gets impureTys return $ go ty t where go :: [Id] -> Ty.Type -> Bool go ts (Tr.TyVarTy t') = True go ts (Tr.LitTy _) = True go ts (Tr.AppTy t1 t2) = True go ts (Tr.TyConApp tc [_,t']) {- FunTy _ t') -} | isFunTyCon tc = go ts t' go ts (Tr.TyConApp tc _) = nameId (getName tc) `notElem` ts go ts (Tr.ForAllTy _ t') = go ts t' cmp t t' = nameId (getName t) /= nameId (getName t') dumpBinds :: [(Id, AbsEff)] -> IO () dumpBinds binds = forM_ binds $ \(k,v) -> putStrLn (render (pp k <+> text ":=" <+> PP.vcat [ pp v -- , text (ppShow v) ])) bindId :: NamedThing a => a -> Id bindId = nameId . getName annotOfBind x = (Just . idOfType $ idType x, getSrcSpan x) mGenBind :: EffMap -> CoreBind -> MGen EffMap mGenBind g (NonRec x b) | isDictId x = return g | otherwise = do a <- mGenExpr g b return (Env.insert g (bindId x) a) mGenBind g (Rec [(f,e)]) = do let g' = Env.insert g n guess a <- mGenExpr g' e return (Env.insert g n (etaExp $ ERec n a (annotOfBind f))) where (bs,_) = collectBinders e bes = [ EVar (bindId x) (annotOfBind x) | x <- bs, not (isDictId x) ] -- guess = foldr go (foldl go' (var n (annotOfBind f)) bes) bes guess = etaExp $ var n (annotOfBind f) etaExp e = foldr go (foldl go' e bes) bes n = bindId f go (EVar x l) a = ELam x a l go' a x = EApp a x (annotOfBind f) mGenBind g (Rec bs) = do liftIO $ putStrLn "Skipping binding group!" return g mGenExpr :: EffMap -> CoreExpr -> MGen AbsEff mGenExpr g e = annotType e <$> mGenExpr' g e mGenExpr' g (Tick (SourceNote ss _) e) = do pushSpan ss a <- mGenExpr g e popSpan return a mGenExpr' g (Tick _ e) = mGenExpr g e mGenExpr' g (Type t) = do s <- currentSpan return (EType (idOfType t) (Nothing, s)) mGenExpr' g exp@(Cast e _) = mGenExpr g e mGenExpr' g (Lit l) = do s <- currentSpan return (litEffect s l) mGenExpr' g e@(Var x) | Just dc <- isDataConId_maybe x = return $ conEffExpr (annotOfBind x) (dataConOrigResTy dc) dc mGenExpr' g v@(Var x) | Just a <- Env.lookup g (bindId x) = return (annotType (Var x) a) | otherwise = do pure <- isPure (idType x) s <- currentSpan when pure $ liftIO $ do let t = defaultEffExpr ( Nothing , s ) ( idType x ) ( " pure " + + showSDoc unsafeGlobalDynFlags ( ppr v ) ) ( " ghc ty : " + + showSDoc unsafeGlobalDynFlags ( ppr ( idType x ) ) ) ( " ty : " + + render ( pp t ) ) when pure $ liftIO $ do let t = defaultEffExpr (Nothing, s) (idType x) putStrLn ("pure " ++ showSDoc unsafeGlobalDynFlags (ppr v)) putStrLn ("ghc ty: " ++ showSDoc unsafeGlobalDynFlags (ppr (idType x))) putStrLn ("ty: " ++ render (pp t)) -} return $ if pure then defaultEffExpr (Nothing, s) (idType x) else var (bindId x) (annotOfBind x) mGenExpr' g exp@(Let bnd@(NonRec b e) e') | isDictId b = mGenExpr' g e' | otherwise = do pure <- isPure (idType b) a <- mGenExpr g e go a pure where go a pure | pure && not (isVal a || isFun a) = do s <- currentSpan let x = bindId b a' <- mGenExpr (Env.insert g x (var x $ annotOfBind b)) e' if x `elem` fv a' then return $ ELet x a a' (Just (exprEType exp), s) else return a' | otherwise = mGenExpr (Env.insert g (bindId b) a) e' mGenExpr' g (Let b e) = do g' <- mGenBind g b mGenExpr g' e mGenExpr' g abs@(Lam b e) = do a <- mGenExpr (Env.insert g n (var n $ annotOfBind b)) e s <- currentSpan if isDictId b then return a else return (lam n a (Just (exprEType abs), s)) where n | isTyVar b = tyVarName (bindId b) | otherwise = bindId b mGenExpr' g exp@(App e e') | not (isTypeArg e') && isDictTy (exprType e') = mGenExpr g e mGenExpr' g e@(App (Var i) l) | Just dc <- isDataConWorkId_maybe i, dc == intDataCon = mGenExpr' g l mGenExpr' g e@(App e1@(Var f) _) | getName f == failMName = error "AHA!!!!" mGenExpr' g e@(App e1@(Var f) e2@(Type t)) | isMonadOp f, Just tc <- tyConAppTyCon_maybe t = do a <- mGenMonadOp f tc annotType e <$> maybe defApp return a where defApp = do eff1 <- mGenExpr g e1 eff2 <- mGenExpr g e2 mGenApp g eff1 eff2 mGenExpr' g e@(App e1 e2) = do ef1 <- mGenExpr g e1 ef2 <- mGenExpr g e2 simplify . annotType e <$> mGenApp g ef1 ef2 mGenExpr' g e@(Case e' _ t alts) = do a <- mGenExpr g e' defA <- mapM (mGenExpr g) def as <- mGenCaseAlts g alts' s <- currentSpan let tCase = exprEType e' tExp = exprEType e return . simplify $ ECase tCase a as defA (Just tExp, s) where (alts', def) = findDefault alts mGenExpr' g e = exprError "Unhandled Expression" e mGenMonadOp :: NamedThing a => a -> TyCon -> MGen (Maybe AbsEff) mGenMonadOp f tc = do tc' <- gets procTy if nameId (getName tc) == tc' then return (noAnnot <$> monadOp f) else return Nothing mGenApp :: EffMap -> AbsEff -> AbsEff -> MGen AbsEff mGenApp g e@ECon {} (EType _ _) = return e mGenApp g e@ECon {} a = return $ simplify (e `apConEff` a) mGenApp g a@(ELam x m _) a2 = return . simplify $ subst [(x, a2)] m = do x a1 _ < - alphaRename ( fv a2 ) a -- return . simplify . subst x a2 $ a1 mGenApp _ a1@(ERec f _ l) a2 = return $ EApp a1 a2 l mGenApp _ a1@(EApp _ _ l) a2 = return $ EApp a1 a2 l mGenApp g e@(EVar x l) a2 = return $ EApp e a2 l mGenApp _ e@(EVal _ _) _ = return e mGenApp _ e1 e2 = error ("App:\n" ++ render (pp e1 PP.$$ pp e2)) substIf :: Id -> Set.Set Id -> AbsEff -> AbsEff -> AbsEff substIf x xs a | x `Set.member` xs = subst [(x, a)] | otherwise = id var :: Id -> a -> EffExpr Id a var = EVar lam = ELam mGenCaseAlts :: EffMap -> [CoreAlt] -> MGen [(Id, [Id], AbsEff)] mGenCaseAlts g = mapM go where go (DataAlt c, bs, e) = do let g' = Env.addsEnv g [ (bindId b, var (bindId b) (annotOfBind b)) | b <- bs ] a <- mGenExpr g' e return (dataConId c, bindId <$> bs, a) go (LitAlt l, [], e) = do ae <- mGenExpr g e return (vv, [], ae) go (DEFAULT, [], e) = error "unhandled DEFAULT case" litEffect :: SrcSpan -> Literal -> AbsEff litEffect l (LitInteger i _) = litInt i (Nothing, l) litEffect l (MachInt i) = litInt i (Nothing, l) litEffect l (MachInt64 i) = litInt i (Nothing, l) litEffect l _ = litInt 0 (Nothing, l) instance Pretty Name where ppPrec _ i = text $ showSDoc unsafeGlobalDynFlags (ppr i) instance Pretty CoreExpr where ppPrec _ i = text $ showSDoc unsafeGlobalDynFlags (ppr i) exprError :: String -> CoreExpr -> a exprError s e = errorFmt s $ showPpr unsafeGlobalDynFlags e nameError :: NamedThing n => String -> n -> a nameError s x = errorFmt s $ showSDocDebug unsafeGlobalDynFlags (ppr (getName x)) errorFmt s e = error ("[BRISK] " ++ s ++ ": " ++ e)
null
https://raw.githubusercontent.com/abakst/Brisk/3e4ce790a742d3e3b786dba45d36f715ea0e61ef/src/Brisk/Model/Extract.hs
haskell
import Brisk.Model.Promela initBinds <- resolve hsenv (specTuple <$> specs) let g0 = Env.addsEnv Env.empty [ (nameId x, specAnnot <$> b) | (x,b) <- initBinds ] return (nameId nm :<=: t) dumpBinds all FunTy _ t') , text (ppShow v) guess = foldr go (foldl go' (var n (annotOfBind f)) bes) bes return . simplify . subst x a2 $ a1
# LANGUAGE ScopedTypeVariables # # LANGUAGE FlexibleInstances # # LANGUAGE UndecidableInstances # module Brisk.Model.Extract where import GHC (GhcMonad) import GhcPlugins hiding ((<+>), pp, text, Subst, Id, mkTyVar, tyVarName) import qualified GhcPlugins as Ghc import Type as Ty import TyCoRep as Tr import Name import Control.Monad.Trans.State import Control.Monad.State hiding (get, gets, modify) import Data.Function import Data.List import Data.Maybe import PrelNames import Text.Show.Pretty (ppShow) import qualified Data.Set as Set import qualified Brisk.Model.Env as Env import Brisk.Transform.ANF (anormalize) import Brisk.Model.GhcInterface import Brisk.Model.Types import Brisk.Model.Builtins import Brisk.Model.Prolog hiding (BriskAnnot(..)) import Brisk.Model.IceT (runIceT, HasType(..)) import Brisk.Pretty import Text.PrettyPrint.HughesPJ as PP type MGen a = StateT MGState IO a data MGState = MGS { hscEnv :: !HscEnv , modGuts :: !ModGuts , impureTys :: ![Id] , procTy :: !Id , cnt :: !Int , srcSpans :: ![SrcSpan] } initialEState : : HscEnv - > ModGuts - > Var - > MGState initialEState henv mg p t = MGS { hscEnv = henv , modGuts = mg , impureTys = t , procTy = p , cnt = 0 , srcSpans = [noSrcSpan] } type EffMap = Env.Env Id AbsEff instance Annot TyAnnot where dummyAnnot = (Nothing, noSrcSpan) instance HasType TyAnnot where getType = fst setType t (_,l) = (t,l) pushSpan :: RealSrcSpan -> MGen () pushSpan ss = modify $ \s -> s { srcSpans = RealSrcSpan ss : srcSpans s } currentSpan :: MGen SrcSpan currentSpan = head <$> gets srcSpans popSpan :: MGen SrcSpan popSpan = do span:spans <- gets srcSpans modify $ \s -> s { srcSpans = spans } return span noAnnot :: Functor f => f a -> f TyAnnot noAnnot = fmap (const dummyAnnot) specAnnot :: Maybe Ty.Type -> TyAnnot specAnnot t = (idOfType <$> t, noSrcSpan) annotType :: CoreExpr -> AbsEff -> AbsEff annotType e t = t { annot = a } where a | isTypeArg e = annot t | otherwise = (Just (exprEType e), snd (annot t)) idOfType = ofType tyConId (tyVarName . nameId) exprEType = idOfType . exprType liftAnnot t = (t, noSrcSpan) specTableEnv :: SpecTableIn -> EffMap specTableEnv (SpecTable tab) = Env.addsEnv Env.empty [ (x, liftAnnot <$> t) | x :<=: t <- tab ] impureTypes = [ ("Control.Distributed.Process.Internal.Types", "Process") , ("Control.Distributed.Static", "Closure") ] runMGen :: [String] -> HscEnv -> ModGuts -> SpecTableIn -> CoreProgram -> IO SpecTableOut runMGen bs hsenv mg specs@(SpecTable speccies) prog prog' <- liftIO $ anormalize hsenv mg prog builtin ' < - do forM ( let SpecTable ts = builtin in ts ) $ \(x : < = : t ) - > do let ( m , n ) = nm < - ghcVarName hsenv m n putStrLn ( briskShowPpr prog ' ) binfix binfix = SpecTable builtin ' impureTys <- forM impureTypes $ fmap nameId . uncurry (ghcTyName hsenv) procTy <- nameId <$> ghcTyName hsenv "Control.Distributed.Process.Internal.Types" "Process" g <- evalStateT (go g0 prog') (initialEState hsenv mg procTy impureTys) ns <- forM bs findModuleNameId let all = Env.toList g brisk = filter ((`elem` ns) . fst) all dumpBinds brisk forM_ brisk (putStrLn . render . PP.vcat . fmap pp . snd . runIceT . snd) forM_ brisk (putStrLn . toBriskString . snd) return $ SpecTable [ x :<=: e | (x,e) <- all ] where go :: EffMap -> CoreProgram -> MGen EffMap go = foldM mGenBind findModuleNameId b = nameId <$> lookupName hsenv (mg_module mg) b isPure :: Ty.Type -> MGen Bool isPure t = do ty <- gets impureTys return $ go ty t where go :: [Id] -> Ty.Type -> Bool go ts (Tr.TyVarTy t') = True go ts (Tr.LitTy _) = True go ts (Tr.AppTy t1 t2) = True | isFunTyCon tc = go ts t' go ts (Tr.TyConApp tc _) = nameId (getName tc) `notElem` ts go ts (Tr.ForAllTy _ t') = go ts t' cmp t t' = nameId (getName t) /= nameId (getName t') dumpBinds :: [(Id, AbsEff)] -> IO () dumpBinds binds = forM_ binds $ \(k,v) -> putStrLn (render (pp k <+> text ":=" <+> PP.vcat [ pp v ])) bindId :: NamedThing a => a -> Id bindId = nameId . getName annotOfBind x = (Just . idOfType $ idType x, getSrcSpan x) mGenBind :: EffMap -> CoreBind -> MGen EffMap mGenBind g (NonRec x b) | isDictId x = return g | otherwise = do a <- mGenExpr g b return (Env.insert g (bindId x) a) mGenBind g (Rec [(f,e)]) = do let g' = Env.insert g n guess a <- mGenExpr g' e return (Env.insert g n (etaExp $ ERec n a (annotOfBind f))) where (bs,_) = collectBinders e bes = [ EVar (bindId x) (annotOfBind x) | x <- bs, not (isDictId x) ] guess = etaExp $ var n (annotOfBind f) etaExp e = foldr go (foldl go' e bes) bes n = bindId f go (EVar x l) a = ELam x a l go' a x = EApp a x (annotOfBind f) mGenBind g (Rec bs) = do liftIO $ putStrLn "Skipping binding group!" return g mGenExpr :: EffMap -> CoreExpr -> MGen AbsEff mGenExpr g e = annotType e <$> mGenExpr' g e mGenExpr' g (Tick (SourceNote ss _) e) = do pushSpan ss a <- mGenExpr g e popSpan return a mGenExpr' g (Tick _ e) = mGenExpr g e mGenExpr' g (Type t) = do s <- currentSpan return (EType (idOfType t) (Nothing, s)) mGenExpr' g exp@(Cast e _) = mGenExpr g e mGenExpr' g (Lit l) = do s <- currentSpan return (litEffect s l) mGenExpr' g e@(Var x) | Just dc <- isDataConId_maybe x = return $ conEffExpr (annotOfBind x) (dataConOrigResTy dc) dc mGenExpr' g v@(Var x) | Just a <- Env.lookup g (bindId x) = return (annotType (Var x) a) | otherwise = do pure <- isPure (idType x) s <- currentSpan when pure $ liftIO $ do let t = defaultEffExpr ( Nothing , s ) ( idType x ) ( " pure " + + showSDoc unsafeGlobalDynFlags ( ppr v ) ) ( " ghc ty : " + + showSDoc unsafeGlobalDynFlags ( ppr ( idType x ) ) ) ( " ty : " + + render ( pp t ) ) when pure $ liftIO $ do let t = defaultEffExpr (Nothing, s) (idType x) putStrLn ("pure " ++ showSDoc unsafeGlobalDynFlags (ppr v)) putStrLn ("ghc ty: " ++ showSDoc unsafeGlobalDynFlags (ppr (idType x))) putStrLn ("ty: " ++ render (pp t)) -} return $ if pure then defaultEffExpr (Nothing, s) (idType x) else var (bindId x) (annotOfBind x) mGenExpr' g exp@(Let bnd@(NonRec b e) e') | isDictId b = mGenExpr' g e' | otherwise = do pure <- isPure (idType b) a <- mGenExpr g e go a pure where go a pure | pure && not (isVal a || isFun a) = do s <- currentSpan let x = bindId b a' <- mGenExpr (Env.insert g x (var x $ annotOfBind b)) e' if x `elem` fv a' then return $ ELet x a a' (Just (exprEType exp), s) else return a' | otherwise = mGenExpr (Env.insert g (bindId b) a) e' mGenExpr' g (Let b e) = do g' <- mGenBind g b mGenExpr g' e mGenExpr' g abs@(Lam b e) = do a <- mGenExpr (Env.insert g n (var n $ annotOfBind b)) e s <- currentSpan if isDictId b then return a else return (lam n a (Just (exprEType abs), s)) where n | isTyVar b = tyVarName (bindId b) | otherwise = bindId b mGenExpr' g exp@(App e e') | not (isTypeArg e') && isDictTy (exprType e') = mGenExpr g e mGenExpr' g e@(App (Var i) l) | Just dc <- isDataConWorkId_maybe i, dc == intDataCon = mGenExpr' g l mGenExpr' g e@(App e1@(Var f) _) | getName f == failMName = error "AHA!!!!" mGenExpr' g e@(App e1@(Var f) e2@(Type t)) | isMonadOp f, Just tc <- tyConAppTyCon_maybe t = do a <- mGenMonadOp f tc annotType e <$> maybe defApp return a where defApp = do eff1 <- mGenExpr g e1 eff2 <- mGenExpr g e2 mGenApp g eff1 eff2 mGenExpr' g e@(App e1 e2) = do ef1 <- mGenExpr g e1 ef2 <- mGenExpr g e2 simplify . annotType e <$> mGenApp g ef1 ef2 mGenExpr' g e@(Case e' _ t alts) = do a <- mGenExpr g e' defA <- mapM (mGenExpr g) def as <- mGenCaseAlts g alts' s <- currentSpan let tCase = exprEType e' tExp = exprEType e return . simplify $ ECase tCase a as defA (Just tExp, s) where (alts', def) = findDefault alts mGenExpr' g e = exprError "Unhandled Expression" e mGenMonadOp :: NamedThing a => a -> TyCon -> MGen (Maybe AbsEff) mGenMonadOp f tc = do tc' <- gets procTy if nameId (getName tc) == tc' then return (noAnnot <$> monadOp f) else return Nothing mGenApp :: EffMap -> AbsEff -> AbsEff -> MGen AbsEff mGenApp g e@ECon {} (EType _ _) = return e mGenApp g e@ECon {} a = return $ simplify (e `apConEff` a) mGenApp g a@(ELam x m _) a2 = return . simplify $ subst [(x, a2)] m = do x a1 _ < - alphaRename ( fv a2 ) a mGenApp _ a1@(ERec f _ l) a2 = return $ EApp a1 a2 l mGenApp _ a1@(EApp _ _ l) a2 = return $ EApp a1 a2 l mGenApp g e@(EVar x l) a2 = return $ EApp e a2 l mGenApp _ e@(EVal _ _) _ = return e mGenApp _ e1 e2 = error ("App:\n" ++ render (pp e1 PP.$$ pp e2)) substIf :: Id -> Set.Set Id -> AbsEff -> AbsEff -> AbsEff substIf x xs a | x `Set.member` xs = subst [(x, a)] | otherwise = id var :: Id -> a -> EffExpr Id a var = EVar lam = ELam mGenCaseAlts :: EffMap -> [CoreAlt] -> MGen [(Id, [Id], AbsEff)] mGenCaseAlts g = mapM go where go (DataAlt c, bs, e) = do let g' = Env.addsEnv g [ (bindId b, var (bindId b) (annotOfBind b)) | b <- bs ] a <- mGenExpr g' e return (dataConId c, bindId <$> bs, a) go (LitAlt l, [], e) = do ae <- mGenExpr g e return (vv, [], ae) go (DEFAULT, [], e) = error "unhandled DEFAULT case" litEffect :: SrcSpan -> Literal -> AbsEff litEffect l (LitInteger i _) = litInt i (Nothing, l) litEffect l (MachInt i) = litInt i (Nothing, l) litEffect l (MachInt64 i) = litInt i (Nothing, l) litEffect l _ = litInt 0 (Nothing, l) instance Pretty Name where ppPrec _ i = text $ showSDoc unsafeGlobalDynFlags (ppr i) instance Pretty CoreExpr where ppPrec _ i = text $ showSDoc unsafeGlobalDynFlags (ppr i) exprError :: String -> CoreExpr -> a exprError s e = errorFmt s $ showPpr unsafeGlobalDynFlags e nameError :: NamedThing n => String -> n -> a nameError s x = errorFmt s $ showSDocDebug unsafeGlobalDynFlags (ppr (getName x)) errorFmt s e = error ("[BRISK] " ++ s ++ ": " ++ e)
74c1404c92705c0217f2a23d66fa9ed465b2163e8c41c42992f773143d13d179
clojure/data.xml
prxml.clj
Copyright ( c ) . All rights reserved . ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns clojure.data.xml.prxml (:require [clojure.data.xml.protocols :refer [AsElements as-elements]] [clojure.data.xml.node :refer [cdata xml-comment element* element]])) (defn sexp-element [tag attrs child] (cond (= :-cdata tag) (cdata (first child)) (= :-comment tag) (xml-comment (first child)) :else (element* tag attrs (mapcat as-elements child)))) (extend-protocol AsElements clojure.lang.IPersistentVector (as-elements [v] (let [[tag & [attrs & after-attrs :as content]] v [attrs content] (if (map? attrs) [(into {} (for [[k v] attrs] [k (str v)])) after-attrs] [{} content])] [(sexp-element tag attrs content)])) clojure.lang.ISeq (as-elements [s] (mapcat as-elements s)) clojure.lang.Keyword (as-elements [k] [(element k)]) java.lang.String (as-elements [s] [s]) nil (as-elements [_] nil) java.lang.Object (as-elements [o] [(str o)])) (defn sexps-as-fragment "Convert a compact prxml/hiccup-style data structure into the more formal tag/attrs/content format. A seq of elements will be returned, which may not be suitable for immediate use as there is no root element. See also sexp-as-element. The format is [:tag-name attr-map? content*]. Each vector opens a new tag; seqs do not open new tags, and are just used for inserting groups of elements into the parent tag. A bare keyword not in a vector creates an empty element. To provide XML conversion for your own data types, extend the AsElements protocol to them." ([] nil) ([sexp] (as-elements sexp)) ([sexp & sexps] (mapcat as-elements (cons sexp sexps)))) (defn sexp-as-element "Convert a single sexp into an Element" [sexp] (let [[root & more] (sexps-as-fragment sexp)] (when more (throw (IllegalArgumentException. "Cannot have multiple root elements; try creating a fragment instead"))) root))
null
https://raw.githubusercontent.com/clojure/data.xml/12cc9934607de6cb4d75eddb1fcae30829fa4156/src/main/clojure/clojure/data/xml/prxml.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software.
Copyright ( c ) . All rights reserved . (ns clojure.data.xml.prxml (:require [clojure.data.xml.protocols :refer [AsElements as-elements]] [clojure.data.xml.node :refer [cdata xml-comment element* element]])) (defn sexp-element [tag attrs child] (cond (= :-cdata tag) (cdata (first child)) (= :-comment tag) (xml-comment (first child)) :else (element* tag attrs (mapcat as-elements child)))) (extend-protocol AsElements clojure.lang.IPersistentVector (as-elements [v] (let [[tag & [attrs & after-attrs :as content]] v [attrs content] (if (map? attrs) [(into {} (for [[k v] attrs] [k (str v)])) after-attrs] [{} content])] [(sexp-element tag attrs content)])) clojure.lang.ISeq (as-elements [s] (mapcat as-elements s)) clojure.lang.Keyword (as-elements [k] [(element k)]) java.lang.String (as-elements [s] [s]) nil (as-elements [_] nil) java.lang.Object (as-elements [o] [(str o)])) (defn sexps-as-fragment "Convert a compact prxml/hiccup-style data structure into the more formal tag/attrs/content format. A seq of elements will be returned, which may not be suitable for immediate use as there is no root element. See also sexp-as-element. seqs do not open new tags, and are just used for inserting groups of elements into the parent tag. A bare keyword not in a vector creates an empty element. To provide XML conversion for your own data types, extend the AsElements protocol to them." ([] nil) ([sexp] (as-elements sexp)) ([sexp & sexps] (mapcat as-elements (cons sexp sexps)))) (defn sexp-as-element "Convert a single sexp into an Element" [sexp] (let [[root & more] (sexps-as-fragment sexp)] (when more (throw (IllegalArgumentException. "Cannot have multiple root elements; try creating a fragment instead"))) root))
23b0926c3c29d7b3a98e9fe0ea9327a6e38b42719b8ee3ba219aa142deace422
argp/bap
batDeque.ml
* Deque -- functional double - ended queues * Copyright ( C ) 2011 Batteries Included Development Team * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation ; either * version 2.1 of the License , or ( at your option ) any later version , * with the special exception on linking described in file LICENSE . * * This library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this library ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * Deque -- functional double-ended queues * Copyright (C) 2011 Batteries Included Development Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version, * with the special exception on linking described in file LICENSE. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) type 'a dq = { front : 'a list ; flen : int ; rear : 'a list ; rlen : int } let invariants t = assert (List.length t.front = t.flen); assert (List.length t.rear = t.rlen) type 'a t = 'a dq type 'a enumerable = 'a t type 'a mappable = 'a t let empty = { front = [ ] ; flen = 0 ; rear = [ ] ; rlen = 0 } let size q = q.flen + q.rlen let cons x q = { q with front = x :: q.front ; flen = q.flen + 1 } $ T cons size ( cons 1 empty ) = 1 to_list(cons 1 empty ) < > to_list(cons 2 empty ) size (cons 1 empty) = 1 to_list(cons 1 empty) <> to_list(cons 2 empty) *) $ Q cons ( Q.list Q.pos_int ) ~count:10 \ ( fun l - > List.fold_left ( fun q x - > cons x q ) empty l | > to_list = List.rev l ) (Q.list Q.pos_int) ~count:10 \ (fun l -> List.fold_left (fun q x -> cons x q) empty l |> to_list = List.rev l) *) let snoc q x = { q with rear = x :: q.rear ; rlen = q.rlen + 1 } $ T cons ; snoc to_list(cons 1 empty ) = to_list(snoc empty 1 ) to_list(cons 1 ( cons 2 empty ) ) = ( to_list ( snoc ( snoc empty 2 ) 1 ) | > List.rev ) to_list(cons 1 empty) = to_list(snoc empty 1) to_list(cons 1 (cons 2 empty)) = (to_list (snoc (snoc empty 2) 1) |> List.rev) *) $ Q snoc ( Q.list Q.int ) ( fun l - > List.fold_left snoc empty l | > to_list = l ) (Q.list Q.int) (fun l -> List.fold_left snoc empty l |> to_list = l) *) let front q = match q with | {front = h :: front; flen = flen; _} -> Some (h, { q with front = front ; flen = flen - 1 }) | {rear = []; _} -> None | {rear = rear; rlen = rlen; _} -> beware : when rlen = 1 , we must put the only element of * the deque at the front ( ie new_flen = 1 , new_rlen = 0 ) * the deque at the front (ie new_flen = 1, new_rlen = 0) *) let new_flen = (rlen + 1) / 2 in let new_rlen = rlen / 2 in we split the non empty list in half because if we transfer * everything to the front , then a call to rear would also * transfer everything to the rear etc . - > no amortization * ( but we could transfer 3/4 instead of 1/2 of the list for instance ) * everything to the front, then a call to rear would also * transfer everything to the rear etc. -> no amortization * (but we could transfer 3/4 instead of 1/2 of the list for instance) *) let rear, rev_front = BatList.split_at new_rlen rear in let front = List.rev rev_front in Some (List.hd front, { front = List.tl front ; flen = new_flen - 1 ; rear = rear ; rlen = new_rlen }) $ T front front(cons 1 empty ) = Some(1,empty ) front(snoc empty 1 ) = Some(1,empty ) front(cons 1 empty) = Some(1,empty) front(snoc empty 1) = Some(1,empty) *) let rear q = match q with | {rear = t :: rear; rlen = rlen; _} -> Some ({ q with rear = rear ; rlen = rlen - 1 }, t) | {front = []; _} -> None | {front = front; flen = flen; _} -> let new_rlen = (flen + 1) / 2 in let new_flen = flen / 2 in let front, rev_rear = BatList.split_at new_flen front in let rear = List.rev rev_rear in Some ({ front = front ; flen = new_flen ; rear = List.tl rear ; rlen = new_rlen - 1 }, List.hd rear) $ T rear match rear(empty | > cons 1 | > cons 2 ) with | Some ( _ , 1 ) - > true | _ - > false match rear(empty |> cons 1 |> cons 2) with | Some(_, 1) -> true | _ -> false *) let rev q = { front = q.rear ; flen = q.rlen ; rear = q.front ; rlen = q.flen } $ Q rev ( Q.list Q.pos_int ) ( fun l - > let q = of_list l in rev q | > to_list = List.rev l ) (Q.list Q.pos_int) (fun l -> let q = of_list l in rev q |> to_list = List.rev l) *) let of_list l = { front = l ; flen = List.length l ; rear = [] ; rlen = 0 } let is_empty q = size q = 0 let append q r = if size q > size r then { q with rlen = q.rlen + size r ; rear = BatList.append r.rear (List.rev_append r.front q.rear) } else { r with flen = r.flen + size q ; front = BatList.append q.front (List.rev_append q.rear r.front) } let append_list q l = let n = List.length l in { q with rear = List.rev_append l q.rear; rlen = q.rlen + n } let prepend_list l q = let n = List.length l in { q with front = BatList.append l q.front ; flen = q.flen + n } let at ?(backwards=false) q n = let size_front = q.flen in let size_rear = q.rlen in if n < 0 || n >= size_rear + size_front then None else Some ( if backwards then if n < size_rear then BatList.at q.rear n else BatList.at q.front (size_front - 1 - (n - size_rear)) else if n < size_front then BatList.at q.front n else BatList.at q.rear (size_rear - 1 - (n - size_front)) ) let map f q = let rec go q r = match front q with | None -> r | Some (x, q) -> go q (snoc r (f x)) in go q empty let mapi f q = let rec go n q r = match front q with | None -> r | Some (x, q) -> go (n + 1) q (snoc r (f n x)) in go 0 q empty let iter f q = let rec go q = match front q with | None -> () | Some (x, q) -> f x ; go q in go q let iteri f q = let rec go n q = match front q with | None -> () | Some (x, q) -> f n x ; go (n + 1) q in go 0 q let rec fold_left fn acc q = match front q with | None -> acc | Some (f, q) -> fold_left fn (fn acc f) q let rec fold_right fn q acc = match rear q with | None -> acc | Some (q, r) -> fold_right fn q (fn r acc) let to_list q = BatList.append q.front (BatList.rev q.rear) let find ?(backwards=false) test q = let rec spin k f r = match f with | [] -> begin match r with | [] -> None | _ -> spin k (List.rev r) [] end | x :: f -> if test x then Some (k, x) else spin (k + 1) f r in if backwards then spin 0 q.rear q.front else spin 0 q.front q.rear let rec enum q = let cur = ref q in let next () = match front !cur with | None -> raise BatEnum.No_more_elements | Some (x, q) -> cur := q ; x in let count () = size !cur in let clone () = enum !cur in BatEnum.make ~next ~count ~clone let of_enum e = BatEnum.fold snoc empty e $ Q enum ( Q.list Q.int ) ( fun l - > List.of_enum ( enum ( List.fold_left snoc empty l ) ) = l ) (Q.list Q.int) (fun l -> List.of_enum (enum (List.fold_left snoc empty l)) = l) $ Q of_enum ( Q.list Q.int ) ( fun l - > to_list ( of_enum ( l ) ) = l ) (Q.list Q.int) (fun l -> to_list (of_enum (List.enum l)) = l) *) let print ?(first="[") ?(last="]") ?(sep="; ") elepr out dq = let rec spin dq = match front dq with | None -> () | Some (a, dq) when size dq = 0 -> elepr out a | Some (a, dq) -> elepr out a ; BatInnerIO.nwrite out sep ; spin dq in BatInnerIO.nwrite out first ; spin dq ; BatInnerIO.nwrite out last $ Q print ( Q.list Q.int ) ( fun l - > \ BatIO.to_string ( print ~first : " < " ~last : " > " ~sep : " , " Int.print ) ( of_list l ) \ = BatIO.to_string ( List.print ~first : " < " ~last : " > " ~sep : " , " Int.print ) l ) (Q.list Q.int) (fun l -> \ BatIO.to_string (print ~first:"<" ~last:">" ~sep:"," Int.print) (of_list l) \ = BatIO.to_string (List.print ~first:"<" ~last:">" ~sep:"," Int.print) l) *)
null
https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/batteries/src/batDeque.ml
ocaml
* Deque -- functional double - ended queues * Copyright ( C ) 2011 Batteries Included Development Team * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation ; either * version 2.1 of the License , or ( at your option ) any later version , * with the special exception on linking described in file LICENSE . * * This library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this library ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * Deque -- functional double-ended queues * Copyright (C) 2011 Batteries Included Development Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version, * with the special exception on linking described in file LICENSE. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) type 'a dq = { front : 'a list ; flen : int ; rear : 'a list ; rlen : int } let invariants t = assert (List.length t.front = t.flen); assert (List.length t.rear = t.rlen) type 'a t = 'a dq type 'a enumerable = 'a t type 'a mappable = 'a t let empty = { front = [ ] ; flen = 0 ; rear = [ ] ; rlen = 0 } let size q = q.flen + q.rlen let cons x q = { q with front = x :: q.front ; flen = q.flen + 1 } $ T cons size ( cons 1 empty ) = 1 to_list(cons 1 empty ) < > to_list(cons 2 empty ) size (cons 1 empty) = 1 to_list(cons 1 empty) <> to_list(cons 2 empty) *) $ Q cons ( Q.list Q.pos_int ) ~count:10 \ ( fun l - > List.fold_left ( fun q x - > cons x q ) empty l | > to_list = List.rev l ) (Q.list Q.pos_int) ~count:10 \ (fun l -> List.fold_left (fun q x -> cons x q) empty l |> to_list = List.rev l) *) let snoc q x = { q with rear = x :: q.rear ; rlen = q.rlen + 1 } $ T cons ; snoc to_list(cons 1 empty ) = to_list(snoc empty 1 ) to_list(cons 1 ( cons 2 empty ) ) = ( to_list ( snoc ( snoc empty 2 ) 1 ) | > List.rev ) to_list(cons 1 empty) = to_list(snoc empty 1) to_list(cons 1 (cons 2 empty)) = (to_list (snoc (snoc empty 2) 1) |> List.rev) *) $ Q snoc ( Q.list Q.int ) ( fun l - > List.fold_left snoc empty l | > to_list = l ) (Q.list Q.int) (fun l -> List.fold_left snoc empty l |> to_list = l) *) let front q = match q with | {front = h :: front; flen = flen; _} -> Some (h, { q with front = front ; flen = flen - 1 }) | {rear = []; _} -> None | {rear = rear; rlen = rlen; _} -> beware : when rlen = 1 , we must put the only element of * the deque at the front ( ie new_flen = 1 , new_rlen = 0 ) * the deque at the front (ie new_flen = 1, new_rlen = 0) *) let new_flen = (rlen + 1) / 2 in let new_rlen = rlen / 2 in we split the non empty list in half because if we transfer * everything to the front , then a call to rear would also * transfer everything to the rear etc . - > no amortization * ( but we could transfer 3/4 instead of 1/2 of the list for instance ) * everything to the front, then a call to rear would also * transfer everything to the rear etc. -> no amortization * (but we could transfer 3/4 instead of 1/2 of the list for instance) *) let rear, rev_front = BatList.split_at new_rlen rear in let front = List.rev rev_front in Some (List.hd front, { front = List.tl front ; flen = new_flen - 1 ; rear = rear ; rlen = new_rlen }) $ T front front(cons 1 empty ) = Some(1,empty ) front(snoc empty 1 ) = Some(1,empty ) front(cons 1 empty) = Some(1,empty) front(snoc empty 1) = Some(1,empty) *) let rear q = match q with | {rear = t :: rear; rlen = rlen; _} -> Some ({ q with rear = rear ; rlen = rlen - 1 }, t) | {front = []; _} -> None | {front = front; flen = flen; _} -> let new_rlen = (flen + 1) / 2 in let new_flen = flen / 2 in let front, rev_rear = BatList.split_at new_flen front in let rear = List.rev rev_rear in Some ({ front = front ; flen = new_flen ; rear = List.tl rear ; rlen = new_rlen - 1 }, List.hd rear) $ T rear match rear(empty | > cons 1 | > cons 2 ) with | Some ( _ , 1 ) - > true | _ - > false match rear(empty |> cons 1 |> cons 2) with | Some(_, 1) -> true | _ -> false *) let rev q = { front = q.rear ; flen = q.rlen ; rear = q.front ; rlen = q.flen } $ Q rev ( Q.list Q.pos_int ) ( fun l - > let q = of_list l in rev q | > to_list = List.rev l ) (Q.list Q.pos_int) (fun l -> let q = of_list l in rev q |> to_list = List.rev l) *) let of_list l = { front = l ; flen = List.length l ; rear = [] ; rlen = 0 } let is_empty q = size q = 0 let append q r = if size q > size r then { q with rlen = q.rlen + size r ; rear = BatList.append r.rear (List.rev_append r.front q.rear) } else { r with flen = r.flen + size q ; front = BatList.append q.front (List.rev_append q.rear r.front) } let append_list q l = let n = List.length l in { q with rear = List.rev_append l q.rear; rlen = q.rlen + n } let prepend_list l q = let n = List.length l in { q with front = BatList.append l q.front ; flen = q.flen + n } let at ?(backwards=false) q n = let size_front = q.flen in let size_rear = q.rlen in if n < 0 || n >= size_rear + size_front then None else Some ( if backwards then if n < size_rear then BatList.at q.rear n else BatList.at q.front (size_front - 1 - (n - size_rear)) else if n < size_front then BatList.at q.front n else BatList.at q.rear (size_rear - 1 - (n - size_front)) ) let map f q = let rec go q r = match front q with | None -> r | Some (x, q) -> go q (snoc r (f x)) in go q empty let mapi f q = let rec go n q r = match front q with | None -> r | Some (x, q) -> go (n + 1) q (snoc r (f n x)) in go 0 q empty let iter f q = let rec go q = match front q with | None -> () | Some (x, q) -> f x ; go q in go q let iteri f q = let rec go n q = match front q with | None -> () | Some (x, q) -> f n x ; go (n + 1) q in go 0 q let rec fold_left fn acc q = match front q with | None -> acc | Some (f, q) -> fold_left fn (fn acc f) q let rec fold_right fn q acc = match rear q with | None -> acc | Some (q, r) -> fold_right fn q (fn r acc) let to_list q = BatList.append q.front (BatList.rev q.rear) let find ?(backwards=false) test q = let rec spin k f r = match f with | [] -> begin match r with | [] -> None | _ -> spin k (List.rev r) [] end | x :: f -> if test x then Some (k, x) else spin (k + 1) f r in if backwards then spin 0 q.rear q.front else spin 0 q.front q.rear let rec enum q = let cur = ref q in let next () = match front !cur with | None -> raise BatEnum.No_more_elements | Some (x, q) -> cur := q ; x in let count () = size !cur in let clone () = enum !cur in BatEnum.make ~next ~count ~clone let of_enum e = BatEnum.fold snoc empty e $ Q enum ( Q.list Q.int ) ( fun l - > List.of_enum ( enum ( List.fold_left snoc empty l ) ) = l ) (Q.list Q.int) (fun l -> List.of_enum (enum (List.fold_left snoc empty l)) = l) $ Q of_enum ( Q.list Q.int ) ( fun l - > to_list ( of_enum ( l ) ) = l ) (Q.list Q.int) (fun l -> to_list (of_enum (List.enum l)) = l) *) let print ?(first="[") ?(last="]") ?(sep="; ") elepr out dq = let rec spin dq = match front dq with | None -> () | Some (a, dq) when size dq = 0 -> elepr out a | Some (a, dq) -> elepr out a ; BatInnerIO.nwrite out sep ; spin dq in BatInnerIO.nwrite out first ; spin dq ; BatInnerIO.nwrite out last $ Q print ( Q.list Q.int ) ( fun l - > \ BatIO.to_string ( print ~first : " < " ~last : " > " ~sep : " , " Int.print ) ( of_list l ) \ = BatIO.to_string ( List.print ~first : " < " ~last : " > " ~sep : " , " Int.print ) l ) (Q.list Q.int) (fun l -> \ BatIO.to_string (print ~first:"<" ~last:">" ~sep:"," Int.print) (of_list l) \ = BatIO.to_string (List.print ~first:"<" ~last:">" ~sep:"," Int.print) l) *)
04fa73b64660244d3586568563199d3c1af6a987705ddedef2d24876558b883c
mirage/ocaml-cohttp
bytebuffer.ml
module Bytes = BytesLabels Bytebuffer is split into three regions using two separate indices that are used to support read and write operations . + --------------------+---------------------------+----------------------------+ | Consumed Bytes | Bytes available to read | Empty space for writing | + --------------------+---------------------------+----------------------------+ | 0 < = pos_read < = pos_fill < = capacity Consumed Bytes : This is content that 's already consumed via a get / read operation . This space can be safely reclaimed . Bytes available to read : This is the actual content that will be surfaced to users via get / read operations on the bytebuffer . Empty space for writing : This is space that will be filled by any set / write operations on the bytebuffer . to support read and write operations. +--------------------+---------------------------+----------------------------+ | Consumed Bytes | Bytes available to read | Empty space for writing | +--------------------+---------------------------+----------------------------+ | 0 <= pos_read <= pos_fill <= capacity Consumed Bytes: This is content that's already consumed via a get/read operation. This space can be safely reclaimed. Bytes available to read: This is the actual content that will be surfaced to users via get/read operations on the bytebuffer. Empty space for writing: This is space that will be filled by any set/write operations on the bytebuffer. *) type t = { mutable buf : Bytes.t; mutable pos_read : int; mutable pos_fill : int; } let create size = let buf = Bytes.create size in { buf; pos_read = 0; pos_fill = 0 } let unsafe_buf t = t.buf let pos t = t.pos_read let compact t = if t.pos_read > 0 then ( let len = t.pos_fill - t.pos_read in Bytes.blit ~src:t.buf ~dst:t.buf ~src_pos:t.pos_read ~dst_pos:0 ~len; t.pos_read <- 0; t.pos_fill <- len) let length t = t.pos_fill - t.pos_read let drop t len = if len < 0 || len > length t then invalid_arg "Bytebuffer.drop: Index out of bounds"; t.pos_read <- t.pos_read + len let rec index_rec t ch idx len = if idx = len then -1 else if Char.equal (Bytes.unsafe_get t.buf (t.pos_read + idx)) ch then idx + t.pos_read else index_rec t ch (idx + 1) len let index t ch = index_rec t ch 0 (length t) let to_string t = Bytes.sub_string t.buf ~pos:t.pos_read ~len:(length t) module Make (IO : sig type 'a t val ( >>| ) : 'a t -> ('a -> 'b) -> 'b t val ( >>= ) : 'a t -> ('a -> 'b t) -> 'b t val return : 'a -> 'a t end) (Refill : sig type src val refill : src -> bytes -> pos:int -> len:int -> [ `Ok of int | `Eof ] IO.t end) = struct open IO let refill t src = compact t; Refill.refill src t.buf ~pos:t.pos_fill ~len:(Bytes.length t.buf - t.pos_fill) >>| function | `Eof -> `Eof | `Ok count -> t.pos_fill <- t.pos_fill + count; `Ok let get_line t idx = let len = idx - t.pos_read in if len >= 1 && Char.equal (Bytes.unsafe_get t.buf (idx - 1)) '\r' then ( let res = let len = len - 1 in Bytes.sub_string t.buf ~pos:t.pos_read ~len in drop t (len + 1); Some res) else None let get_line_buf t buf idx = let len = idx - t.pos_read in Buffer.add_subbytes buf t.buf t.pos_read len; drop t (len + 1) let rec read_line_slow t reader buf = if length t = 0 then refill t reader >>= function | `Ok -> read_line_slow t reader buf | `Eof -> IO.return `Eof else let idx = index t '\n' in if idx > -1 then ( get_line_buf t buf idx; IO.return `Ok) else let len = length t in Buffer.add_subbytes buf t.buf t.pos_read len; drop t len; read_line_slow t reader buf let read_line t reader = let idx = index t '\n' in if idx = -1 then let buf = Buffer.create (length t + 1) in read_line_slow t reader buf >>| function | `Eof -> None | `Ok -> let len = Buffer.length buf in if len = 0 then None else if len >= 2 && Buffer.nth buf (len - 1) = '\r' then Some (Buffer.sub buf 0 (len - 1)) else None else let line = get_line t idx in IO.return line let rec read t reader len = let length = length t in if length > 0 then ( let to_read = min length len in let buf = Bytes.sub_string t.buf ~pos:t.pos_read ~len:to_read in drop t to_read; IO.return buf) else refill t reader >>= function | `Ok -> read t reader len | `Eof -> IO.return "" end
null
https://raw.githubusercontent.com/mirage/ocaml-cohttp/5ee84489cf6755711d0e7c0f1365685a15cae468/http/src/bytebuffer/bytebuffer.ml
ocaml
module Bytes = BytesLabels Bytebuffer is split into three regions using two separate indices that are used to support read and write operations . + --------------------+---------------------------+----------------------------+ | Consumed Bytes | Bytes available to read | Empty space for writing | + --------------------+---------------------------+----------------------------+ | 0 < = pos_read < = pos_fill < = capacity Consumed Bytes : This is content that 's already consumed via a get / read operation . This space can be safely reclaimed . Bytes available to read : This is the actual content that will be surfaced to users via get / read operations on the bytebuffer . Empty space for writing : This is space that will be filled by any set / write operations on the bytebuffer . to support read and write operations. +--------------------+---------------------------+----------------------------+ | Consumed Bytes | Bytes available to read | Empty space for writing | +--------------------+---------------------------+----------------------------+ | 0 <= pos_read <= pos_fill <= capacity Consumed Bytes: This is content that's already consumed via a get/read operation. This space can be safely reclaimed. Bytes available to read: This is the actual content that will be surfaced to users via get/read operations on the bytebuffer. Empty space for writing: This is space that will be filled by any set/write operations on the bytebuffer. *) type t = { mutable buf : Bytes.t; mutable pos_read : int; mutable pos_fill : int; } let create size = let buf = Bytes.create size in { buf; pos_read = 0; pos_fill = 0 } let unsafe_buf t = t.buf let pos t = t.pos_read let compact t = if t.pos_read > 0 then ( let len = t.pos_fill - t.pos_read in Bytes.blit ~src:t.buf ~dst:t.buf ~src_pos:t.pos_read ~dst_pos:0 ~len; t.pos_read <- 0; t.pos_fill <- len) let length t = t.pos_fill - t.pos_read let drop t len = if len < 0 || len > length t then invalid_arg "Bytebuffer.drop: Index out of bounds"; t.pos_read <- t.pos_read + len let rec index_rec t ch idx len = if idx = len then -1 else if Char.equal (Bytes.unsafe_get t.buf (t.pos_read + idx)) ch then idx + t.pos_read else index_rec t ch (idx + 1) len let index t ch = index_rec t ch 0 (length t) let to_string t = Bytes.sub_string t.buf ~pos:t.pos_read ~len:(length t) module Make (IO : sig type 'a t val ( >>| ) : 'a t -> ('a -> 'b) -> 'b t val ( >>= ) : 'a t -> ('a -> 'b t) -> 'b t val return : 'a -> 'a t end) (Refill : sig type src val refill : src -> bytes -> pos:int -> len:int -> [ `Ok of int | `Eof ] IO.t end) = struct open IO let refill t src = compact t; Refill.refill src t.buf ~pos:t.pos_fill ~len:(Bytes.length t.buf - t.pos_fill) >>| function | `Eof -> `Eof | `Ok count -> t.pos_fill <- t.pos_fill + count; `Ok let get_line t idx = let len = idx - t.pos_read in if len >= 1 && Char.equal (Bytes.unsafe_get t.buf (idx - 1)) '\r' then ( let res = let len = len - 1 in Bytes.sub_string t.buf ~pos:t.pos_read ~len in drop t (len + 1); Some res) else None let get_line_buf t buf idx = let len = idx - t.pos_read in Buffer.add_subbytes buf t.buf t.pos_read len; drop t (len + 1) let rec read_line_slow t reader buf = if length t = 0 then refill t reader >>= function | `Ok -> read_line_slow t reader buf | `Eof -> IO.return `Eof else let idx = index t '\n' in if idx > -1 then ( get_line_buf t buf idx; IO.return `Ok) else let len = length t in Buffer.add_subbytes buf t.buf t.pos_read len; drop t len; read_line_slow t reader buf let read_line t reader = let idx = index t '\n' in if idx = -1 then let buf = Buffer.create (length t + 1) in read_line_slow t reader buf >>| function | `Eof -> None | `Ok -> let len = Buffer.length buf in if len = 0 then None else if len >= 2 && Buffer.nth buf (len - 1) = '\r' then Some (Buffer.sub buf 0 (len - 1)) else None else let line = get_line t idx in IO.return line let rec read t reader len = let length = length t in if length > 0 then ( let to_read = min length len in let buf = Bytes.sub_string t.buf ~pos:t.pos_read ~len:to_read in drop t to_read; IO.return buf) else refill t reader >>= function | `Ok -> read t reader len | `Eof -> IO.return "" end
b6c92ec66975f3d155e189efb4cf8ed34147fc488d1204159dd8845c60889fbf
pirapira/coq2rust
genprint.mli
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) (** Entry point for generic printers *) open Pp open Genarg val raw_print : ('raw, 'glb, 'top) genarg_type -> 'raw -> std_ppcmds (** Printer for raw level generic arguments. *) val glb_print : ('raw, 'glb, 'top) genarg_type -> 'glb -> std_ppcmds (** Printer for glob level generic arguments. *) val top_print : ('raw, 'glb, 'top) genarg_type -> 'top -> std_ppcmds (** Printer for top level generic arguments. *) val generic_raw_print : rlevel generic_argument -> std_ppcmds val generic_glb_print : glevel generic_argument -> std_ppcmds val generic_top_print : tlevel generic_argument -> std_ppcmds val register_print0 : ('raw, 'glb, 'top) genarg_type -> ('raw -> std_ppcmds) -> ('glb -> std_ppcmds) -> ('top -> std_ppcmds) -> unit
null
https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/printing/genprint.mli
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** * Entry point for generic printers * Printer for raw level generic arguments. * Printer for glob level generic arguments. * Printer for top level generic arguments.
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Pp open Genarg val raw_print : ('raw, 'glb, 'top) genarg_type -> 'raw -> std_ppcmds val glb_print : ('raw, 'glb, 'top) genarg_type -> 'glb -> std_ppcmds val top_print : ('raw, 'glb, 'top) genarg_type -> 'top -> std_ppcmds val generic_raw_print : rlevel generic_argument -> std_ppcmds val generic_glb_print : glevel generic_argument -> std_ppcmds val generic_top_print : tlevel generic_argument -> std_ppcmds val register_print0 : ('raw, 'glb, 'top) genarg_type -> ('raw -> std_ppcmds) -> ('glb -> std_ppcmds) -> ('top -> std_ppcmds) -> unit
52c63ff45c67a60749d1118c37248353bc3d29a69e241f8256cec66bb74cd38c
clash-lang/clash-compiler
Signals.hs
{-# LANGUAGE RankNTypes #-} | Functions to generate signals for SPI devices . The function used to -- generate a signal determines if the signal is lawful or not (with regards -- to respecting busy and acknowledgement signals). -- module Test.Cores.Internal.Signals ( GenMaster , GenSlave , masterLawfulSignal , masterLawlessSignal , slaveLawfulSignal , slaveLawlessSignal ) where import qualified Data.List as List (cycle, head, tail) import qualified Clash.Explicit.Prelude as E (moore, mooreB) import Clash.Prelude -- import Clash.Cores.SPI type GenMaster n = forall dom . ( KnownDomain dom , KnownNat n ) => Clock dom -> Reset dom -> [BitVector n] -> Signal dom Bool -> Signal dom Bool -> Signal dom (Maybe (BitVector n)) type GenSlave n = forall dom . ( KnownDomain dom , KnownNat n ) => Clock dom -> Reset dom -> [BitVector n] -> Signal dom Bool -> Signal dom (BitVector n) | A device which gives data to the SPI master , while respecting -- busy and acknowledgement signals from the device. -- masterLawfulSignal :: GenMaster n masterLawfulSignal clk rst vals ack busy = E.mooreB clk rst enableGen go out (List.head vals, List.tail (List.cycle vals), True) (ack, busy) where go (x, xs, _) (isAck, isBusy) | isAck = (List.head xs, List.tail xs, isBusy) | otherwise = (x, xs, isBusy) out (x, _, b) = if b then Nothing else Just x | A device which gives data to the SPI master . This function does not -- wait for the acknowledgement signal before changing the input, which -- should result in incorrect data transfer. -- masterLawlessSignal :: GenMaster n masterLawlessSignal clk rst vals _ = E.mooreB clk rst enableGen go out (List.head vals, List.tail (List.cycle vals), True) where go (_, xs, _) isBusy = (List.head xs, List.tail xs, isBusy) out (x, _, b) = if b then Nothing else Just x | A device which gives data to an SPI slave , while respecting -- acknowledgement signals from the device. -- slaveLawfulSignal :: GenSlave n slaveLawfulSignal clk rst vals = E.moore clk rst enableGen go fst (List.head vals, List.tail (List.cycle vals)) where go (x, xs) isAck = if isAck then (List.head xs, List.tail xs) else (x, xs) | A device which gives data to an SPI slave . This function does not -- wait for the acknowledgement signal before changing the input, which -- should result in incorrect data transfer. -- slaveLawlessSignal :: GenSlave n slaveLawlessSignal clk rst vals = E.moore clk rst enableGen go fst (List.head vals, List.tail (List.cycle vals)) where go (_, xs) _ = (List.head xs, List.tail xs)
null
https://raw.githubusercontent.com/clash-lang/clash-compiler/8e461a910f2f37c900705a0847a9b533bce4d2ea/clash-cores/test/Test/Cores/Internal/Signals.hs
haskell
# LANGUAGE RankNTypes # generate a signal determines if the signal is lawful or not (with regards to respecting busy and acknowledgement signals). import Clash.Cores.SPI busy and acknowledgement signals from the device. wait for the acknowledgement signal before changing the input, which should result in incorrect data transfer. acknowledgement signals from the device. wait for the acknowledgement signal before changing the input, which should result in incorrect data transfer.
| Functions to generate signals for SPI devices . The function used to module Test.Cores.Internal.Signals ( GenMaster , GenSlave , masterLawfulSignal , masterLawlessSignal , slaveLawfulSignal , slaveLawlessSignal ) where import qualified Data.List as List (cycle, head, tail) import qualified Clash.Explicit.Prelude as E (moore, mooreB) import Clash.Prelude type GenMaster n = forall dom . ( KnownDomain dom , KnownNat n ) => Clock dom -> Reset dom -> [BitVector n] -> Signal dom Bool -> Signal dom Bool -> Signal dom (Maybe (BitVector n)) type GenSlave n = forall dom . ( KnownDomain dom , KnownNat n ) => Clock dom -> Reset dom -> [BitVector n] -> Signal dom Bool -> Signal dom (BitVector n) | A device which gives data to the SPI master , while respecting masterLawfulSignal :: GenMaster n masterLawfulSignal clk rst vals ack busy = E.mooreB clk rst enableGen go out (List.head vals, List.tail (List.cycle vals), True) (ack, busy) where go (x, xs, _) (isAck, isBusy) | isAck = (List.head xs, List.tail xs, isBusy) | otherwise = (x, xs, isBusy) out (x, _, b) = if b then Nothing else Just x | A device which gives data to the SPI master . This function does not masterLawlessSignal :: GenMaster n masterLawlessSignal clk rst vals _ = E.mooreB clk rst enableGen go out (List.head vals, List.tail (List.cycle vals), True) where go (_, xs, _) isBusy = (List.head xs, List.tail xs, isBusy) out (x, _, b) = if b then Nothing else Just x | A device which gives data to an SPI slave , while respecting slaveLawfulSignal :: GenSlave n slaveLawfulSignal clk rst vals = E.moore clk rst enableGen go fst (List.head vals, List.tail (List.cycle vals)) where go (x, xs) isAck = if isAck then (List.head xs, List.tail xs) else (x, xs) | A device which gives data to an SPI slave . This function does not slaveLawlessSignal :: GenSlave n slaveLawlessSignal clk rst vals = E.moore clk rst enableGen go fst (List.head vals, List.tail (List.cycle vals)) where go (_, xs) _ = (List.head xs, List.tail xs)
744b39fee221e30f4c708cc051b07ee2ae12b16ccc0b6fa3d880ea1206572e1c
initc3/SaUCy
Main.hs
module Main where import qualified Language.ILC.Repl as Repl ( main ) main :: IO () main = Repl.main
null
https://raw.githubusercontent.com/initc3/SaUCy/199154c1f488af4561e4bf1f7f5f3ef8876dfa6b/app/Main.hs
haskell
module Main where import qualified Language.ILC.Repl as Repl ( main ) main :: IO () main = Repl.main
1d2215252918648b79255185f386504ab9630af8013b7d43e1aebb6b17dbdd20
mtgred/netrunner
pages.clj
(ns web.pages (:require [cheshire.core :as json] [cljc.java-time.instant :as inst] [hiccup.page :as hiccup] [monger.collection :as mc] [monger.operators :refer :all] [ring.middleware.anti-forgery :as anti-forgery] [web.utils :refer [response html-response]] [web.versions :refer [frontend-version]])) (defn index-page ([request] (index-page request nil nil)) ([{user :user server-mode :system/server-mode} og replay-id] (html-response 200 (hiccup/html5 [:head [:meta {:charset "utf-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=0.6, minimal-ui"}] [:meta {:name "apple-mobile-web-app-capable" :content "yes"}] [:meta {:property "og:type" :content (:type og "website")}] [:meta {:property "og:url" :content (:url og "")}] [:meta {:property "og:image" :content (:image og "")}] [:meta {:property "og:title" :content (:title og "Play Netrunner in your browser")}] [:meta {:property "og:site_name" :content (:site_name og "jinteki.net")}] [:meta {:property "og:description" :content (:description og "Build Netrunner decks and test them online against other players.")}] [:link {:rel "apple-touch-icon" :href "/img/icons/jinteki_167.png"}] [:title "Jinteki"] (hiccup/include-css "/lib/css/toastr.min.css") (if (= "dev" server-mode) (hiccup/include-css "/css/netrunner.css") (hiccup/include-css (str "/css/netrunner.css?v=" @frontend-version)))] [:body [:div#sente-csrf-token {:style {:display "hidden"} :data-csrf-token (force anti-forgery/*anti-forgery-token*)}] [:div {:style {:display "hidden"} :id "server-originated-data" :data-version @frontend-version :data-replay-id replay-id}] [:div#main-content] [:audio#ting [:source {:src "/sound/ting.mp3" :type "audio/mp3"}] [:source {:src "/sound/ting.ogg" :type "audio/ogg"}]] (hiccup/include-js "-2.1.1.min.js") (hiccup/include-js "-ui.min.js") (hiccup/include-js "") (hiccup/include-js "/lib/js/toastr.min.js") [:script {:type "text/javascript"} (str "var user=" (json/generate-string user) ";")] (if (= "dev" server-mode) (list (hiccup/include-js "/js/cljs-runtime/goog.base.js") (hiccup/include-js "/js/main.js")) (list (hiccup/include-js (str "/js/main.js?v=" @frontend-version))))])))) (defn reset-password-page [{db :system/db {:keys [token]} :path-params}] (if (mc/find-one-as-map db "users" {:resetPasswordToken token :resetPasswordExpires {"$gt" (inst/now)}}) (html-response 200 (hiccup/html5 [:head [:title "Jinteki"] (hiccup/include-css "/css/netrunner.css")] [:body [:div.reset-bg] [:form.panel.blue-shade.reset-form {:method "POST"} [:h3 "Password Reset"] [:p [:input.form-control {:type "password" :name "password" :value "" :placeholder "New password" :autofocus true :required "required"}]] [:p [:input.form-control {:type "password" :name "confirm" :value "" :placeholder "Confirm password" :required "required"}]] [:p [:button.btn.btn-primary {:type "submit"} "Update Password"]]]])) (response 404 {:message "Sorry, but that reset token is invalid or has expired."})))
null
https://raw.githubusercontent.com/mtgred/netrunner/5245a4cbcda4b789addd2b8b9213276422718f23/src/clj/web/pages.clj
clojure
(ns web.pages (:require [cheshire.core :as json] [cljc.java-time.instant :as inst] [hiccup.page :as hiccup] [monger.collection :as mc] [monger.operators :refer :all] [ring.middleware.anti-forgery :as anti-forgery] [web.utils :refer [response html-response]] [web.versions :refer [frontend-version]])) (defn index-page ([request] (index-page request nil nil)) ([{user :user server-mode :system/server-mode} og replay-id] (html-response 200 (hiccup/html5 [:head [:meta {:charset "utf-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=0.6, minimal-ui"}] [:meta {:name "apple-mobile-web-app-capable" :content "yes"}] [:meta {:property "og:type" :content (:type og "website")}] [:meta {:property "og:url" :content (:url og "")}] [:meta {:property "og:image" :content (:image og "")}] [:meta {:property "og:title" :content (:title og "Play Netrunner in your browser")}] [:meta {:property "og:site_name" :content (:site_name og "jinteki.net")}] [:meta {:property "og:description" :content (:description og "Build Netrunner decks and test them online against other players.")}] [:link {:rel "apple-touch-icon" :href "/img/icons/jinteki_167.png"}] [:title "Jinteki"] (hiccup/include-css "/lib/css/toastr.min.css") (if (= "dev" server-mode) (hiccup/include-css "/css/netrunner.css") (hiccup/include-css (str "/css/netrunner.css?v=" @frontend-version)))] [:body [:div#sente-csrf-token {:style {:display "hidden"} :data-csrf-token (force anti-forgery/*anti-forgery-token*)}] [:div {:style {:display "hidden"} :id "server-originated-data" :data-version @frontend-version :data-replay-id replay-id}] [:div#main-content] [:audio#ting [:source {:src "/sound/ting.mp3" :type "audio/mp3"}] [:source {:src "/sound/ting.ogg" :type "audio/ogg"}]] (hiccup/include-js "-2.1.1.min.js") (hiccup/include-js "-ui.min.js") (hiccup/include-js "") (hiccup/include-js "/lib/js/toastr.min.js") [:script {:type "text/javascript"} (str "var user=" (json/generate-string user) ";")] (if (= "dev" server-mode) (list (hiccup/include-js "/js/cljs-runtime/goog.base.js") (hiccup/include-js "/js/main.js")) (list (hiccup/include-js (str "/js/main.js?v=" @frontend-version))))])))) (defn reset-password-page [{db :system/db {:keys [token]} :path-params}] (if (mc/find-one-as-map db "users" {:resetPasswordToken token :resetPasswordExpires {"$gt" (inst/now)}}) (html-response 200 (hiccup/html5 [:head [:title "Jinteki"] (hiccup/include-css "/css/netrunner.css")] [:body [:div.reset-bg] [:form.panel.blue-shade.reset-form {:method "POST"} [:h3 "Password Reset"] [:p [:input.form-control {:type "password" :name "password" :value "" :placeholder "New password" :autofocus true :required "required"}]] [:p [:input.form-control {:type "password" :name "confirm" :value "" :placeholder "Confirm password" :required "required"}]] [:p [:button.btn.btn-primary {:type "submit"} "Update Password"]]]])) (response 404 {:message "Sorry, but that reset token is invalid or has expired."})))
b30990fd1ed3c02e0ebead12d1b17772ae848878be7098e190e1136d9c317e7a
tnelson/Forge
sample-wheat.rkt
#lang forge/core (sig Node) (relation edges (Node Node)) (pred (isSource n) (= Node (join n edges))) (pred hasSink (some ([n Node]) (= Node (join edges n))))
null
https://raw.githubusercontent.com/tnelson/Forge/1687cba0ebdb598c29c51845d43c98a459d0588f/forge/check-ex-spec/examples/sample-ta/sample/wheats/sample-wheat.rkt
racket
#lang forge/core (sig Node) (relation edges (Node Node)) (pred (isSource n) (= Node (join n edges))) (pred hasSink (some ([n Node]) (= Node (join edges n))))
87f7a282b387358da48c7f3e82f39d488749be96aa6253ef8ee8c289b78e30ec
kupl/FixML
localize.ml
open Lang open Util open Label_lang open Print open Labeling (* set of execution traces *) type trace_set = int BatSet.t let empty_set = BatSet.empty let extend_set = BatSet.add (* set of execution traces *) let trace_set = ref empty_set let init_set () = (trace_set := empty_set) let start_time = ref 0.0 (* Find counter exampels *) let rec is_counter_example : prog -> example -> bool = fun pgm (input, output) -> let res_var = "__res__" in let pgm = pgm@(External.grading_prog) in let pgm' = pgm @ [(DLet (BindOne res_var,false,[],fresh_tvar(),(Lang.appify (EVar !Options.opt_entry_func) input)))] in try let env = Eval.run pgm' in let result = Lang.lookup_env res_var env in not (Eval.value_equality result output) with _ -> true let rec find_counter_examples : prog -> examples -> examples * examples = fun pgm examples -> List.partition (is_counter_example pgm) examples (*****************************************************************) labeled exp evaluation - > should merge it with non - labeld ver (*****************************************************************) (* Block task *) let rec is_fun : labeled_value -> bool = fun v -> match v with | VList vs -> List.exists is_fun vs | VTuple vs -> List.exists is_fun vs | VCtor (x, vs) -> List.exists is_fun vs | VFun (x, e, closure) -> true | VFunRec (f, x, e, closure) -> true | VBlock (f, vs) -> true | _ -> false let rec update_closure : labeled_env -> labeled_value -> labeled_value = fun env v -> match v with | VList vs -> VList (List.map (update_closure env) vs) | VTuple vs -> VTuple (List.map (update_closure env) vs) | VCtor (x, vs) -> VCtor (x, List.map (update_closure env) vs) | VFun (x, e, closure) -> VFun (x, e, env) | VFunRec (f, x, e, closure) -> VFunRec (f, x, e, env) | VBlock (f, vs) -> let (xs, vs) = List.split vs in let vs = List.map (update_closure env) vs in VBlock (f, List.combine xs vs) | _ -> v let rec find_callee : id -> (id * labeled_value) list -> labeled_value = fun x vs -> match vs with | [] -> raise (Failure "not found") | (y, v)::tl -> if x = y then v else find_callee x tl let bind_block : labeled_env -> (id * labeled_value) list -> labeled_env = fun env vs -> let (xs, _) = List.split vs in List.fold_left (fun env x -> update_env x (VBlock (x, vs)) env) env xs (* Argument binding *) let rec arg_binding : labeled_env -> arg -> labeled_value -> labeled_env = fun env arg v -> match (arg, v) with | ArgUnder t, _ -> env | ArgOne (x, t), _ -> update_env x v env | ArgTuple xs, VTuple vs -> ( try List.fold_left2 arg_binding env xs vs with | Invalid_argument _ -> raise (Failure "argument binding failure - tuples are not compatible") | _ -> raise (StackOverflow "Stack overflow during evaluation (looping recursion?)") ) | _ -> raise (Failure "argument binding failure") let rec let_binding : labeled_env -> let_bind -> labeled_value -> labeled_env = fun env x v -> match (x, v) with | BindUnder, _ -> env | BindOne x, _ -> update_env x v env | BindTuple xs, VTuple vs -> ( try List.fold_left2 let_binding env xs vs with | Invalid_argument _ -> raise (Failure "argument binding failure - tuples are not compatible") | _ -> raise (StackOverflow "Stack overflow during evaluation (looping recursion?)") ) | _ -> raise (Failure "let binding failure") (* Pattern Matching *) let rec find_first_branch : labeled_value -> labeled_branch list -> (pat * labeled_exp) = fun v bs -> match bs with | [] -> raise (Failure "Pattern matching failure") | (p, e)::tl -> if (pattern_match v p) then (p, e) else find_first_branch v tl and pattern_match : labeled_value -> pat -> bool = fun v p -> match (v, p) with | VInt n1, PInt n2 -> n1 = n2 | VBool b1, PBool b2 -> b1 = b2 | VList l1, PList l2 -> pattern_match_list l1 l2 | VTuple l1, PTuple l2 -> pattern_match_list l1 l2 | VCtor (x1, l1), PCtor (x2, l2) -> (x1 = x2) && pattern_match_list l1 l2 | VList [], PCons (phd::ptl) -> if ptl = [] then (pattern_match v phd) else false | VList (vhd::vtl), PCons (phd::ptl) -> if ptl = [] then (pattern_match v phd) else (pattern_match vhd phd) && (pattern_match (VList vtl) (PCons ptl)) | _, PVar x -> true | _, PUnder -> true | _, Pats pl -> (try List.exists (pattern_match v) pl with _ -> false) | _ -> false and pattern_match_list : labeled_value list -> pat list -> bool = fun vs ps -> try List.for_all2 pattern_match vs ps with _ -> false let rec check_patterns : pat list -> bool = fun ps -> let var_set_list = List.map (gather_vars BatSet.empty) ps in let base = List.hd var_set_list in List.for_all (fun set -> BatSet.equal set base) var_set_list and gather_vars : id BatSet.t -> pat -> id BatSet.t = fun set p -> match p with | PVar x -> BatSet.add x set | PList ps | PTuple ps | PCtor (_, ps) | PCons ps | Pats ps -> List.fold_left gather_vars set ps | _ -> set let rec bind_pat : labeled_env -> labeled_value -> pat -> labeled_env = fun env v p -> match (v, p) with | _, PInt n2 -> env | _, PBool b2 -> env | _, PUnder -> env | _, PVar x -> update_env x v env | _, Pats ps -> if check_patterns ps then bind_pat env v (List.find (pattern_match v) ps) else raise (Failure "Invalid pattern list") | VList l1, PList l2 -> bind_pat_list env l1 l2 | VTuple l1, PTuple l2 -> bind_pat_list env l1 l2 | VCtor (x1, l1), PCtor (x2, l2) -> bind_pat_list env l1 l2 | VList [], PCons (phd::ptl) -> if ptl = [] then (bind_pat env v phd) else raise (Failure "Pattern binding failure") | VList (vhd::vtl), PCons (phd::ptl) -> if ptl = [] then bind_pat env v phd else bind_pat (bind_pat env vhd phd) (VList vtl) (PCons ptl) | _ -> raise (Failure "Pattern binding failure") and bind_pat_list : labeled_env -> labeled_value list -> pat list -> labeled_env = fun env vs ps -> List.fold_left2 bind_pat env vs ps let rec value_equality : labeled_value -> labeled_value -> bool = fun v1 v2 -> match v1,v2 with | VBool b1,VBool b2 -> b1=b2 | VInt n1,VInt n2 -> n1=n2 | VString id1,VString id2 -> id1=id2 | VList l1, VList l2 | VTuple l1, VTuple l2 -> (try List.for_all2 value_equality l1 l2 with _ -> false) | VCtor (x1,l1), VCtor(x2,l2) -> (try ((x1=x2) && List.for_all2 value_equality l1 l2) with _ -> false) | _ -> false (* exp evaluation *) let rec eval : labeled_env -> labeled_exp -> labeled_value = fun env (label, e) -> (trace_set := extend_set label !trace_set); (* gather execution traces *) if (Unix.gettimeofday() -. !start_time >0.2) then raise (Failure "Timeout") else match e with | EUnit -> VUnit | Const n -> VInt n | TRUE -> VBool true | FALSE -> VBool false | String id -> VString id | EVar x -> lookup_env x env | EList es -> VList (List.map (eval env) es) | ETuple es -> VTuple (List.map (eval env) es) | ECtor (c, es) -> VCtor (c, List.map (eval env) es) (* aop *) | ADD (e1, e2) -> (eval_abop env e1 e2 (+)) | SUB (e1, e2) -> (eval_abop env e1 e2 (-)) | MUL (e1, e2) -> (eval_abop env e1 e2 ( * )) | DIV (e1, e2) -> (eval_abop env e1 e2 (/)) | MOD (e1, e2) -> (eval_abop env e1 e2 (mod)) | MINUS e -> begin match (eval env e) with | VInt n -> VInt (-n) | _ -> raise (Failure "arithmetic_operation error") end | NOT e -> begin match (eval env e) with | VBool b -> VBool (not b) | _ -> raise (Failure "boolean_operation error") end | OR (e1, e2) -> (eval_bbop env e1 e2 (||)) | AND (e1, e2) -> (eval_bbop env e1 e2 (&&)) | LESS (e1, e2) -> (eval_abbop env e1 e2 (<)) | LARGER (e1, e2) -> (eval_abbop env e1 e2 (>)) | LESSEQ (e1, e2) -> (eval_abbop env e1 e2 (<=)) | LARGEREQ (e1, e2) -> (eval_abbop env e1 e2 (>=)) | EQUAL (e1, e2) -> VBool (eval_equality env e1 e2) | NOTEQ (e1, e2) -> VBool (not (eval_equality env e1 e2)) (* lop *) | AT (e1, e2) -> begin match (eval env e1, eval env e2) with | VList vs1, VList vs2 -> VList (vs1 @ vs2) | _ -> raise (Failure "list_operation error") end | DOUBLECOLON (e1, e2) -> begin match (eval env e2) with | VList vs -> VList ((eval env e1)::vs) | _ -> raise (Failure "list_operation error") end | STRCON (e1,e2) -> let (v1,v2) = (eval env e1,eval env e2) in begin match v1,v2 with | VString str1,VString str2 -> VString (str1 ^ str2) | _ -> raise (Failure "string_operation error") end (* else *) | IF (e1, e2, e3) -> begin match (eval env e1) with | VBool true -> eval env e2 | VBool false -> eval env e3 | _ -> raise (Failure "if_type error") end | ELet (f, is_rec, args, typ, e1, e2) -> begin match args with | [] -> (* Value binding *) if is_rec then let v1 = eval env e1 in begin match v1 with | VFun (x, e, closure) -> begin match f with | BindOne f -> eval (update_env f (VFunRec (f, x, e, closure)) env) e2 | _ -> raise (Failure "Only variables are allowed as left-hand side of `let rec'") end | _ -> eval (let_binding env f v1) e2 end else eval (let_binding env f (eval env e1)) e2 | _ -> (* Function binding *) let rec binding : arg list -> labeled_exp -> labeled_exp = fun xs e -> begin match xs with | [] -> e | hd::tl -> (dummy_label, EFun (hd, binding tl e)) end in let x = List.hd args in let vf = if is_rec then begin match f with | BindOne f -> VFunRec (f, x, (binding (List.tl args) e1), env) | _ -> raise (Failure "Only variables are allowed as left-hand side of `let rec'") end else VFun (x, (binding (List.tl args) e1), env) in eval (let_binding env f vf) e2 end | EBlock (is_rec, bindings, e2) -> let env = begin match is_rec with | true -> let (func_map, const_map) = List.fold_left ( fun (func_map, const_map) (f, is_rec, args, typ, exp) -> begin match f with | BindOne x -> let v = eval env (dummy_label, ELet (BindOne x, is_rec, args, typ, exp, let_to_lexp f)) in if is_fun v then ((x, v)::func_map, const_map) else (func_map, (x, v)::const_map) | _ -> raise (Failure "l-value cannot be a tupple") end ) ([], []) bindings in (* constant mapping *) let init_env = List.fold_left (fun env (x, c) -> update_env x c env) env const_map in (* update each function's closure *) let func_map = List.map (fun (x, v) -> (x, update_closure init_env v)) func_map in (* block mapping *) List.fold_left (fun env (x, v) -> update_env x (VBlock (x, func_map)) env) init_env func_map | false -> let vs = List.map (fun (f, is_rec, args, typ, e) -> eval env (dummy_label, ELet (f, is_rec, args, typ, e, let_to_lexp f))) bindings in List.fold_left2 (fun env (f, is_rec, args, typ, e) v -> let_binding env f v) env bindings vs end in eval env e2 | EMatch (e, bs) -> let v = eval env e in let (p, ex) = find_first_branch v bs in eval (bind_pat env v p) ex | EFun (arg, e) -> VFun (arg, e, env) | EApp (e1, e2) -> let (v1, v2) = (eval env e1, eval env e2) in begin match v1 with | VFun (x, e, closure) -> eval (arg_binding closure x v2) e | VFunRec (f, x, e, closure) -> eval (update_env f v1 (arg_binding closure x v2)) e | VBlock (f, vs) -> let v = find_callee f vs in begin match v with | VFunRec (f, x, e, closure) -> let block_env = bind_block closure vs in eval (arg_binding block_env x v2) e | _ -> raise (Failure "mutually recursive function call error") end | _ -> raise (Failure "function_call error") end | Hole n -> VHole n | Raise e -> let e = eval env e in raise (LExcept e) and eval_abop : labeled_env -> labeled_exp -> labeled_exp -> (int -> int -> int) -> labeled_value = fun env e1 e2 op -> match (eval env e1, eval env e2) with | VInt n1, VInt n2 -> VInt (op n1 n2) | _ -> raise (Failure "arithmetic_operation error") and eval_abbop : labeled_env -> labeled_exp -> labeled_exp -> (int -> int -> bool) -> labeled_value = fun env e1 e2 op -> match (eval env e1, eval env e2) with | VInt n1, VInt n2 -> VBool (op n1 n2) | _ -> raise (Failure "int_relation error") and eval_bbop : labeled_env -> labeled_exp -> labeled_exp -> (bool -> bool -> bool) -> labeled_value = fun env e1 e2 op -> match (eval env e1, eval env e2) with | VBool b1, VBool b2 -> VBool (op b1 b2) | _ -> raise (Failure "boolean_operation error") and eval_equality : labeled_env -> labeled_exp -> labeled_exp -> bool = fun env e1 e2-> let (x,y) = (eval env e1, eval env e2) in (value_equality x y) let check_entry f entry_func = match f with |BindOne x -> (x=entry_func) |_ -> false let rec eval_decl : labeled_env -> labeled_decl -> labeled_env = fun env decl -> match decl with | DLet (f, is_rec, args, typ, e) -> let e = (dummy_label, ELet (f, is_rec, args, typ, e, (let_to_lexp f))) in let_binding env f (eval env e) | DBlock (is_rec, bindings) -> begin match is_rec with | true -> let (func_map, const_map) = List.fold_left ( fun (func_map, const_map) (f, is_rec, args, typ, exp) -> begin match f with | BindOne x -> let v = eval env (dummy_label, ELet (BindOne x, is_rec, args, typ, exp, let_to_lexp f)) in if is_fun v then ((x, v)::func_map, const_map) else (func_map, (x, v)::const_map) | _ -> raise (Failure "l-value cannot be a tupple") end ) ([], []) bindings in (* constant mapping *) let init_env = List.fold_left (fun env (x, c) -> update_env x c env) env const_map in (* update each function's closure *) let func_map = List.map (fun (x, v) -> (x, update_closure init_env v)) func_map in (* block mapping *) List.fold_left (fun env (x, v) -> update_env x (VBlock (x, func_map)) env) init_env func_map | false -> let envs = List.map (fun binding -> eval_decl env (DLet binding)) bindings in List.fold_left (fun env new_env -> BatMap.union env new_env) env envs end | _ -> env let run : labeled_prog -> labeled_env = fun decls -> start_time:=Unix.gettimeofday(); let init_env = List.fold_left eval_decl empty_env (Labeling.labeling_prog (External.init_prog)) in init_set (); start_time := Unix.gettimeofday(); let decls = decls@(Labeling.labeling_prog (External.grading_prog)) in List.fold_left eval_decl init_env decls let rec collect_execution_trace : labeled_prog -> example -> trace_set = fun pgm (input, output) -> let pgm = pgm @ labeling_prog (External.grading_prog) in let res_var = "__res__" in let pgm' = pgm @ labeling_prog [(DLet (BindOne res_var, false, [], fresh_tvar(), (Lang.appify (EVar !Options.opt_entry_func) input)))] in try let _ = run pgm' in !trace_set with _ -> !trace_set let gen_label_map (ex : examples) (pgm : labeled_prog) : (int, int) BatMap.t = List.fold_left (fun map example -> let label_set = collect_execution_trace pgm example in BatSet.fold (fun label m -> if BatMap.mem label m then BatMap.add label ((BatMap.find label m)+1) m else BatMap.add label 1 m ) label_set map ) BatMap.empty ex let weight : labeled_prog -> examples -> examples -> (int, float) BatMap.t = fun l_pgm pos neg -> let counter_map = gen_label_map neg l_pgm in let pass_map = gen_label_map pos l_pgm in let counter_num = List.length neg in let pass_num = List.length pos in let weight_function = BatMap.foldi (fun label n result -> if(BatMap.mem label pass_map) then let w = (float_of_int (BatMap.find label pass_map)) /. float_of_int(counter_num+pass_num) in BatMap.add label w result else BatMap.add label 0.0 result ) counter_map BatMap.empty in weight_function let cost_avg : (int, float) BatMap.t -> labeled_prog -> float = fun w l_pgm-> let pgm_set = BatMap.foldi (fun l _ acc -> let hole_pgm = gen_hole_pgm l l_pgm in BatSet.add (unlabeling_prog hole_pgm) acc ) w BatSet.empty in let sum = BatSet.fold (fun pgm acc-> let rank = (cost (unlabeling_prog l_pgm)) - (cost pgm) in acc +. (float_of_int rank) ) pgm_set 0.0 in sum /. (float_of_int (BatSet.cardinal pgm_set)) let rec naive_exp :labeled_exp -> int BatSet.t -> int BatSet.t = fun (label,e) env -> let env = BatSet.add label env in match e with | EUnit | Const _ | TRUE | FALSE | String _ | EVar _ | Hole _ -> env | EList es | ETuple es | ECtor (_,es)-> list_fold (fun e r -> naive_exp e r) es env (* aop *) | ADD (e1, e2) | SUB (e1,e2) | MUL (e1,e2) | DIV (e1,e2) | MOD (e1,e2) |STRCON (e1,e2) |OR (e1,e2) | AND (e1,e2) | LESS (e1,e2) | LARGER (e1,e2) | LESSEQ (e1,e2) | LARGEREQ (e1,e2) | EQUAL (e1,e2) | NOTEQ (e1,e2) | AT (e1,e2) | DOUBLECOLON (e1,e2) | EApp (e1,e2) | ELet (_,_,_,_,e1,e2)-> let env = naive_exp e1 env in naive_exp e2 env | MINUS e | NOT e | EFun (_,e) | Raise e-> naive_exp e env (* else *) | IF (e1, e2, e3) -> let env = naive_exp e1 env in let env = naive_exp e2 env in naive_exp e3 env | EBlock (is_rec, bindings, e2) -> let env = naive_exp e2 env in list_fold (fun (_,_,_,_,e) env -> naive_exp e env) bindings env | EMatch (e, bs) -> let env = naive_exp e env in list_fold (fun (_,e) env -> naive_exp e env) bs env let rec naive_decl : labeled_decl -> int BatSet.t -> int BatSet.t = fun decl env -> match decl with | DLet (f, is_rec, args, typ, e) -> naive_exp e env | DBlock (is_rec, bindings) -> list_fold (fun (_,_,_,_,e) env -> naive_exp e env) bindings env | _ -> env let rec naive : labeled_prog -> int BatSet.t = fun l_pgm -> list_fold naive_decl l_pgm BatSet.empty (* Find inital candidates *) let localization : prog -> examples -> (int * prog) BatSet.t = fun pgm examples -> let (counter_examples,pass_examples) = find_counter_examples pgm examples in let l_pgm = Labeling.labeling_prog pgm in let weight_function = weight l_pgm pass_examples counter_examples in let avg = cost_avg weight_function l_pgm in let candidate_set = BatMap.foldi (fun label weight set -> let hole_pgm = gen_hole_pgm label l_pgm in let candidate_pgm = unlabeling_prog hole_pgm in let rank = ((cost pgm) - (cost candidate_pgm)) in let rank = int_of_float ((float_of_int rank) +. (weight *. avg)) in if (Synthesize.is_closed candidate_pgm) then set else extend_set (rank, candidate_pgm) set ) weight_function empty_set in candidate_set
null
https://raw.githubusercontent.com/kupl/FixML/0a032a733d68cd8ccc8b1034d2908cd43b241fce/engine/localize.ml
ocaml
set of execution traces set of execution traces Find counter exampels *************************************************************** *************************************************************** Block task Argument binding Pattern Matching exp evaluation gather execution traces aop lop else Value binding Function binding constant mapping update each function's closure block mapping constant mapping update each function's closure block mapping aop else Find inital candidates
open Lang open Util open Label_lang open Print open Labeling type trace_set = int BatSet.t let empty_set = BatSet.empty let extend_set = BatSet.add let trace_set = ref empty_set let init_set () = (trace_set := empty_set) let start_time = ref 0.0 let rec is_counter_example : prog -> example -> bool = fun pgm (input, output) -> let res_var = "__res__" in let pgm = pgm@(External.grading_prog) in let pgm' = pgm @ [(DLet (BindOne res_var,false,[],fresh_tvar(),(Lang.appify (EVar !Options.opt_entry_func) input)))] in try let env = Eval.run pgm' in let result = Lang.lookup_env res_var env in not (Eval.value_equality result output) with _ -> true let rec find_counter_examples : prog -> examples -> examples * examples = fun pgm examples -> List.partition (is_counter_example pgm) examples labeled exp evaluation - > should merge it with non - labeld ver let rec is_fun : labeled_value -> bool = fun v -> match v with | VList vs -> List.exists is_fun vs | VTuple vs -> List.exists is_fun vs | VCtor (x, vs) -> List.exists is_fun vs | VFun (x, e, closure) -> true | VFunRec (f, x, e, closure) -> true | VBlock (f, vs) -> true | _ -> false let rec update_closure : labeled_env -> labeled_value -> labeled_value = fun env v -> match v with | VList vs -> VList (List.map (update_closure env) vs) | VTuple vs -> VTuple (List.map (update_closure env) vs) | VCtor (x, vs) -> VCtor (x, List.map (update_closure env) vs) | VFun (x, e, closure) -> VFun (x, e, env) | VFunRec (f, x, e, closure) -> VFunRec (f, x, e, env) | VBlock (f, vs) -> let (xs, vs) = List.split vs in let vs = List.map (update_closure env) vs in VBlock (f, List.combine xs vs) | _ -> v let rec find_callee : id -> (id * labeled_value) list -> labeled_value = fun x vs -> match vs with | [] -> raise (Failure "not found") | (y, v)::tl -> if x = y then v else find_callee x tl let bind_block : labeled_env -> (id * labeled_value) list -> labeled_env = fun env vs -> let (xs, _) = List.split vs in List.fold_left (fun env x -> update_env x (VBlock (x, vs)) env) env xs let rec arg_binding : labeled_env -> arg -> labeled_value -> labeled_env = fun env arg v -> match (arg, v) with | ArgUnder t, _ -> env | ArgOne (x, t), _ -> update_env x v env | ArgTuple xs, VTuple vs -> ( try List.fold_left2 arg_binding env xs vs with | Invalid_argument _ -> raise (Failure "argument binding failure - tuples are not compatible") | _ -> raise (StackOverflow "Stack overflow during evaluation (looping recursion?)") ) | _ -> raise (Failure "argument binding failure") let rec let_binding : labeled_env -> let_bind -> labeled_value -> labeled_env = fun env x v -> match (x, v) with | BindUnder, _ -> env | BindOne x, _ -> update_env x v env | BindTuple xs, VTuple vs -> ( try List.fold_left2 let_binding env xs vs with | Invalid_argument _ -> raise (Failure "argument binding failure - tuples are not compatible") | _ -> raise (StackOverflow "Stack overflow during evaluation (looping recursion?)") ) | _ -> raise (Failure "let binding failure") let rec find_first_branch : labeled_value -> labeled_branch list -> (pat * labeled_exp) = fun v bs -> match bs with | [] -> raise (Failure "Pattern matching failure") | (p, e)::tl -> if (pattern_match v p) then (p, e) else find_first_branch v tl and pattern_match : labeled_value -> pat -> bool = fun v p -> match (v, p) with | VInt n1, PInt n2 -> n1 = n2 | VBool b1, PBool b2 -> b1 = b2 | VList l1, PList l2 -> pattern_match_list l1 l2 | VTuple l1, PTuple l2 -> pattern_match_list l1 l2 | VCtor (x1, l1), PCtor (x2, l2) -> (x1 = x2) && pattern_match_list l1 l2 | VList [], PCons (phd::ptl) -> if ptl = [] then (pattern_match v phd) else false | VList (vhd::vtl), PCons (phd::ptl) -> if ptl = [] then (pattern_match v phd) else (pattern_match vhd phd) && (pattern_match (VList vtl) (PCons ptl)) | _, PVar x -> true | _, PUnder -> true | _, Pats pl -> (try List.exists (pattern_match v) pl with _ -> false) | _ -> false and pattern_match_list : labeled_value list -> pat list -> bool = fun vs ps -> try List.for_all2 pattern_match vs ps with _ -> false let rec check_patterns : pat list -> bool = fun ps -> let var_set_list = List.map (gather_vars BatSet.empty) ps in let base = List.hd var_set_list in List.for_all (fun set -> BatSet.equal set base) var_set_list and gather_vars : id BatSet.t -> pat -> id BatSet.t = fun set p -> match p with | PVar x -> BatSet.add x set | PList ps | PTuple ps | PCtor (_, ps) | PCons ps | Pats ps -> List.fold_left gather_vars set ps | _ -> set let rec bind_pat : labeled_env -> labeled_value -> pat -> labeled_env = fun env v p -> match (v, p) with | _, PInt n2 -> env | _, PBool b2 -> env | _, PUnder -> env | _, PVar x -> update_env x v env | _, Pats ps -> if check_patterns ps then bind_pat env v (List.find (pattern_match v) ps) else raise (Failure "Invalid pattern list") | VList l1, PList l2 -> bind_pat_list env l1 l2 | VTuple l1, PTuple l2 -> bind_pat_list env l1 l2 | VCtor (x1, l1), PCtor (x2, l2) -> bind_pat_list env l1 l2 | VList [], PCons (phd::ptl) -> if ptl = [] then (bind_pat env v phd) else raise (Failure "Pattern binding failure") | VList (vhd::vtl), PCons (phd::ptl) -> if ptl = [] then bind_pat env v phd else bind_pat (bind_pat env vhd phd) (VList vtl) (PCons ptl) | _ -> raise (Failure "Pattern binding failure") and bind_pat_list : labeled_env -> labeled_value list -> pat list -> labeled_env = fun env vs ps -> List.fold_left2 bind_pat env vs ps let rec value_equality : labeled_value -> labeled_value -> bool = fun v1 v2 -> match v1,v2 with | VBool b1,VBool b2 -> b1=b2 | VInt n1,VInt n2 -> n1=n2 | VString id1,VString id2 -> id1=id2 | VList l1, VList l2 | VTuple l1, VTuple l2 -> (try List.for_all2 value_equality l1 l2 with _ -> false) | VCtor (x1,l1), VCtor(x2,l2) -> (try ((x1=x2) && List.for_all2 value_equality l1 l2) with _ -> false) | _ -> false let rec eval : labeled_env -> labeled_exp -> labeled_value = fun env (label, e) -> if (Unix.gettimeofday() -. !start_time >0.2) then raise (Failure "Timeout") else match e with | EUnit -> VUnit | Const n -> VInt n | TRUE -> VBool true | FALSE -> VBool false | String id -> VString id | EVar x -> lookup_env x env | EList es -> VList (List.map (eval env) es) | ETuple es -> VTuple (List.map (eval env) es) | ECtor (c, es) -> VCtor (c, List.map (eval env) es) | ADD (e1, e2) -> (eval_abop env e1 e2 (+)) | SUB (e1, e2) -> (eval_abop env e1 e2 (-)) | MUL (e1, e2) -> (eval_abop env e1 e2 ( * )) | DIV (e1, e2) -> (eval_abop env e1 e2 (/)) | MOD (e1, e2) -> (eval_abop env e1 e2 (mod)) | MINUS e -> begin match (eval env e) with | VInt n -> VInt (-n) | _ -> raise (Failure "arithmetic_operation error") end | NOT e -> begin match (eval env e) with | VBool b -> VBool (not b) | _ -> raise (Failure "boolean_operation error") end | OR (e1, e2) -> (eval_bbop env e1 e2 (||)) | AND (e1, e2) -> (eval_bbop env e1 e2 (&&)) | LESS (e1, e2) -> (eval_abbop env e1 e2 (<)) | LARGER (e1, e2) -> (eval_abbop env e1 e2 (>)) | LESSEQ (e1, e2) -> (eval_abbop env e1 e2 (<=)) | LARGEREQ (e1, e2) -> (eval_abbop env e1 e2 (>=)) | EQUAL (e1, e2) -> VBool (eval_equality env e1 e2) | NOTEQ (e1, e2) -> VBool (not (eval_equality env e1 e2)) | AT (e1, e2) -> begin match (eval env e1, eval env e2) with | VList vs1, VList vs2 -> VList (vs1 @ vs2) | _ -> raise (Failure "list_operation error") end | DOUBLECOLON (e1, e2) -> begin match (eval env e2) with | VList vs -> VList ((eval env e1)::vs) | _ -> raise (Failure "list_operation error") end | STRCON (e1,e2) -> let (v1,v2) = (eval env e1,eval env e2) in begin match v1,v2 with | VString str1,VString str2 -> VString (str1 ^ str2) | _ -> raise (Failure "string_operation error") end | IF (e1, e2, e3) -> begin match (eval env e1) with | VBool true -> eval env e2 | VBool false -> eval env e3 | _ -> raise (Failure "if_type error") end | ELet (f, is_rec, args, typ, e1, e2) -> begin match args with | [] -> if is_rec then let v1 = eval env e1 in begin match v1 with | VFun (x, e, closure) -> begin match f with | BindOne f -> eval (update_env f (VFunRec (f, x, e, closure)) env) e2 | _ -> raise (Failure "Only variables are allowed as left-hand side of `let rec'") end | _ -> eval (let_binding env f v1) e2 end else eval (let_binding env f (eval env e1)) e2 | _ -> let rec binding : arg list -> labeled_exp -> labeled_exp = fun xs e -> begin match xs with | [] -> e | hd::tl -> (dummy_label, EFun (hd, binding tl e)) end in let x = List.hd args in let vf = if is_rec then begin match f with | BindOne f -> VFunRec (f, x, (binding (List.tl args) e1), env) | _ -> raise (Failure "Only variables are allowed as left-hand side of `let rec'") end else VFun (x, (binding (List.tl args) e1), env) in eval (let_binding env f vf) e2 end | EBlock (is_rec, bindings, e2) -> let env = begin match is_rec with | true -> let (func_map, const_map) = List.fold_left ( fun (func_map, const_map) (f, is_rec, args, typ, exp) -> begin match f with | BindOne x -> let v = eval env (dummy_label, ELet (BindOne x, is_rec, args, typ, exp, let_to_lexp f)) in if is_fun v then ((x, v)::func_map, const_map) else (func_map, (x, v)::const_map) | _ -> raise (Failure "l-value cannot be a tupple") end ) ([], []) bindings in let init_env = List.fold_left (fun env (x, c) -> update_env x c env) env const_map in let func_map = List.map (fun (x, v) -> (x, update_closure init_env v)) func_map in List.fold_left (fun env (x, v) -> update_env x (VBlock (x, func_map)) env) init_env func_map | false -> let vs = List.map (fun (f, is_rec, args, typ, e) -> eval env (dummy_label, ELet (f, is_rec, args, typ, e, let_to_lexp f))) bindings in List.fold_left2 (fun env (f, is_rec, args, typ, e) v -> let_binding env f v) env bindings vs end in eval env e2 | EMatch (e, bs) -> let v = eval env e in let (p, ex) = find_first_branch v bs in eval (bind_pat env v p) ex | EFun (arg, e) -> VFun (arg, e, env) | EApp (e1, e2) -> let (v1, v2) = (eval env e1, eval env e2) in begin match v1 with | VFun (x, e, closure) -> eval (arg_binding closure x v2) e | VFunRec (f, x, e, closure) -> eval (update_env f v1 (arg_binding closure x v2)) e | VBlock (f, vs) -> let v = find_callee f vs in begin match v with | VFunRec (f, x, e, closure) -> let block_env = bind_block closure vs in eval (arg_binding block_env x v2) e | _ -> raise (Failure "mutually recursive function call error") end | _ -> raise (Failure "function_call error") end | Hole n -> VHole n | Raise e -> let e = eval env e in raise (LExcept e) and eval_abop : labeled_env -> labeled_exp -> labeled_exp -> (int -> int -> int) -> labeled_value = fun env e1 e2 op -> match (eval env e1, eval env e2) with | VInt n1, VInt n2 -> VInt (op n1 n2) | _ -> raise (Failure "arithmetic_operation error") and eval_abbop : labeled_env -> labeled_exp -> labeled_exp -> (int -> int -> bool) -> labeled_value = fun env e1 e2 op -> match (eval env e1, eval env e2) with | VInt n1, VInt n2 -> VBool (op n1 n2) | _ -> raise (Failure "int_relation error") and eval_bbop : labeled_env -> labeled_exp -> labeled_exp -> (bool -> bool -> bool) -> labeled_value = fun env e1 e2 op -> match (eval env e1, eval env e2) with | VBool b1, VBool b2 -> VBool (op b1 b2) | _ -> raise (Failure "boolean_operation error") and eval_equality : labeled_env -> labeled_exp -> labeled_exp -> bool = fun env e1 e2-> let (x,y) = (eval env e1, eval env e2) in (value_equality x y) let check_entry f entry_func = match f with |BindOne x -> (x=entry_func) |_ -> false let rec eval_decl : labeled_env -> labeled_decl -> labeled_env = fun env decl -> match decl with | DLet (f, is_rec, args, typ, e) -> let e = (dummy_label, ELet (f, is_rec, args, typ, e, (let_to_lexp f))) in let_binding env f (eval env e) | DBlock (is_rec, bindings) -> begin match is_rec with | true -> let (func_map, const_map) = List.fold_left ( fun (func_map, const_map) (f, is_rec, args, typ, exp) -> begin match f with | BindOne x -> let v = eval env (dummy_label, ELet (BindOne x, is_rec, args, typ, exp, let_to_lexp f)) in if is_fun v then ((x, v)::func_map, const_map) else (func_map, (x, v)::const_map) | _ -> raise (Failure "l-value cannot be a tupple") end ) ([], []) bindings in let init_env = List.fold_left (fun env (x, c) -> update_env x c env) env const_map in let func_map = List.map (fun (x, v) -> (x, update_closure init_env v)) func_map in List.fold_left (fun env (x, v) -> update_env x (VBlock (x, func_map)) env) init_env func_map | false -> let envs = List.map (fun binding -> eval_decl env (DLet binding)) bindings in List.fold_left (fun env new_env -> BatMap.union env new_env) env envs end | _ -> env let run : labeled_prog -> labeled_env = fun decls -> start_time:=Unix.gettimeofday(); let init_env = List.fold_left eval_decl empty_env (Labeling.labeling_prog (External.init_prog)) in init_set (); start_time := Unix.gettimeofday(); let decls = decls@(Labeling.labeling_prog (External.grading_prog)) in List.fold_left eval_decl init_env decls let rec collect_execution_trace : labeled_prog -> example -> trace_set = fun pgm (input, output) -> let pgm = pgm @ labeling_prog (External.grading_prog) in let res_var = "__res__" in let pgm' = pgm @ labeling_prog [(DLet (BindOne res_var, false, [], fresh_tvar(), (Lang.appify (EVar !Options.opt_entry_func) input)))] in try let _ = run pgm' in !trace_set with _ -> !trace_set let gen_label_map (ex : examples) (pgm : labeled_prog) : (int, int) BatMap.t = List.fold_left (fun map example -> let label_set = collect_execution_trace pgm example in BatSet.fold (fun label m -> if BatMap.mem label m then BatMap.add label ((BatMap.find label m)+1) m else BatMap.add label 1 m ) label_set map ) BatMap.empty ex let weight : labeled_prog -> examples -> examples -> (int, float) BatMap.t = fun l_pgm pos neg -> let counter_map = gen_label_map neg l_pgm in let pass_map = gen_label_map pos l_pgm in let counter_num = List.length neg in let pass_num = List.length pos in let weight_function = BatMap.foldi (fun label n result -> if(BatMap.mem label pass_map) then let w = (float_of_int (BatMap.find label pass_map)) /. float_of_int(counter_num+pass_num) in BatMap.add label w result else BatMap.add label 0.0 result ) counter_map BatMap.empty in weight_function let cost_avg : (int, float) BatMap.t -> labeled_prog -> float = fun w l_pgm-> let pgm_set = BatMap.foldi (fun l _ acc -> let hole_pgm = gen_hole_pgm l l_pgm in BatSet.add (unlabeling_prog hole_pgm) acc ) w BatSet.empty in let sum = BatSet.fold (fun pgm acc-> let rank = (cost (unlabeling_prog l_pgm)) - (cost pgm) in acc +. (float_of_int rank) ) pgm_set 0.0 in sum /. (float_of_int (BatSet.cardinal pgm_set)) let rec naive_exp :labeled_exp -> int BatSet.t -> int BatSet.t = fun (label,e) env -> let env = BatSet.add label env in match e with | EUnit | Const _ | TRUE | FALSE | String _ | EVar _ | Hole _ -> env | EList es | ETuple es | ECtor (_,es)-> list_fold (fun e r -> naive_exp e r) es env | ADD (e1, e2) | SUB (e1,e2) | MUL (e1,e2) | DIV (e1,e2) | MOD (e1,e2) |STRCON (e1,e2) |OR (e1,e2) | AND (e1,e2) | LESS (e1,e2) | LARGER (e1,e2) | LESSEQ (e1,e2) | LARGEREQ (e1,e2) | EQUAL (e1,e2) | NOTEQ (e1,e2) | AT (e1,e2) | DOUBLECOLON (e1,e2) | EApp (e1,e2) | ELet (_,_,_,_,e1,e2)-> let env = naive_exp e1 env in naive_exp e2 env | MINUS e | NOT e | EFun (_,e) | Raise e-> naive_exp e env | IF (e1, e2, e3) -> let env = naive_exp e1 env in let env = naive_exp e2 env in naive_exp e3 env | EBlock (is_rec, bindings, e2) -> let env = naive_exp e2 env in list_fold (fun (_,_,_,_,e) env -> naive_exp e env) bindings env | EMatch (e, bs) -> let env = naive_exp e env in list_fold (fun (_,e) env -> naive_exp e env) bs env let rec naive_decl : labeled_decl -> int BatSet.t -> int BatSet.t = fun decl env -> match decl with | DLet (f, is_rec, args, typ, e) -> naive_exp e env | DBlock (is_rec, bindings) -> list_fold (fun (_,_,_,_,e) env -> naive_exp e env) bindings env | _ -> env let rec naive : labeled_prog -> int BatSet.t = fun l_pgm -> list_fold naive_decl l_pgm BatSet.empty let localization : prog -> examples -> (int * prog) BatSet.t = fun pgm examples -> let (counter_examples,pass_examples) = find_counter_examples pgm examples in let l_pgm = Labeling.labeling_prog pgm in let weight_function = weight l_pgm pass_examples counter_examples in let avg = cost_avg weight_function l_pgm in let candidate_set = BatMap.foldi (fun label weight set -> let hole_pgm = gen_hole_pgm label l_pgm in let candidate_pgm = unlabeling_prog hole_pgm in let rank = ((cost pgm) - (cost candidate_pgm)) in let rank = int_of_float ((float_of_int rank) +. (weight *. avg)) in if (Synthesize.is_closed candidate_pgm) then set else extend_set (rank, candidate_pgm) set ) weight_function empty_set in candidate_set
8aaa0003ee4520eee4549cd601634040fca5660242a50930c0673bdeac7b3e23
mzp/coq-ide-for-ios
coqinit.ml
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) $ I d : coqinit.ml 13323 2010 - 07 - 24 15:57:30Z herbelin $ open Pp open System open Toplevel let (/) = Filename.concat let set_debug () = Flags.debug := true Loading of the ressource file . rcfile is either $ HOME/.coqrc . VERSION , or $ HOME/.coqrc if the first one does not exist . rcfile is either $HOME/.coqrc.VERSION, or $HOME/.coqrc if the first one does not exist. *) let rcfile = ref (home/".coqrc") let rcfile_specified = ref false let set_rcfile s = rcfile := s; rcfile_specified := true let set_rcuser s = rcfile := ("~"^s)/".coqrc" let load_rc = ref true let no_load_rc () = load_rc := false let load_rcfile() = if !load_rc then try if !rcfile_specified then if file_readable_p !rcfile then Vernac.load_vernac false !rcfile else raise (Sys_error ("Cannot read rcfile: "^ !rcfile)) else if file_readable_p (!rcfile^"."^Coq_config.version) then Vernac.load_vernac false (!rcfile^"."^Coq_config.version) else if file_readable_p !rcfile then Vernac.load_vernac false !rcfile else () Flags.if_verbose ( ( " No .coqrc or .coqrc . "^Coq_config.version^ " found . Skipping rcfile loading . " ) ) Flags.if_verbose mSGNL (str ("No .coqrc or .coqrc."^Coq_config.version^ " found. Skipping rcfile loading.")) *) with e -> (msgnl (str"Load of rcfile failed."); raise e) else Flags.if_verbose msgnl (str"Skipping rcfile loading.") Puts dir in the path of ML and in the LoadPath let coq_add_path d s = Mltop.add_path d (Names.make_dirpath [Nameops.coq_root;Names.id_of_string s]) let coq_add_rec_path s = Mltop.add_rec_path s (Names.make_dirpath [Nameops.coq_root]) (* By the option -include -I or -R of the command line *) let includes = ref [] let push_include (s, alias) = includes := (s,alias,false) :: !includes let push_rec_include (s, alias) = includes := (s,alias,true) :: !includes (* The list of all theories in the standard library /!\ order does matter *) let theories_dirs_map = [ "theories/Unicode", "Unicode" ; "theories/Classes", "Classes" ; "theories/Program", "Program" ; "theories/MSets", "MSets" ; "theories/FSets", "FSets" ; "theories/Reals", "Reals" ; "theories/Strings", "Strings" ; "theories/Sorting", "Sorting" ; "theories/Setoids", "Setoids" ; "theories/Sets", "Sets" ; "theories/Structures", "Structures" ; "theories/Lists", "Lists" ; "theories/Wellfounded", "Wellfounded" ; "theories/Relations", "Relations" ; "theories/Numbers", "Numbers" ; "theories/QArith", "QArith" ; "theories/NArith", "NArith" ; "theories/ZArith", "ZArith" ; "theories/Arith", "Arith" ; "theories/Bool", "Bool" ; "theories/Logic", "Logic" ; "theories/Init", "Init" ] (* Initializes the LoadPath *) let init_load_path () = let coqlib = Envars.coqlib () in let user_contrib = coqlib/"user-contrib" in let dirs = ["states";"plugins"] in (* first user-contrib *) if Sys.file_exists user_contrib then Mltop.add_rec_path user_contrib Nameops.default_root_prefix; (* then states, theories and dev *) List.iter (fun s -> coq_add_rec_path (coqlib/s)) dirs; (* developer specific directory to open *) if Coq_config.local then coq_add_path (coqlib/"dev") "dev"; (* then standard library *) List.iter (fun (s,alias) -> Mltop.add_rec_path (coqlib/s) (Names.make_dirpath [Names.id_of_string alias; Nameops.coq_root])) theories_dirs_map; (* then current directory *) Mltop.add_path "." Nameops.default_root_prefix; (* additional loadpath, given with -I -include -R options *) List.iter (fun (s,alias,reci) -> if reci then Mltop.add_rec_path s alias else Mltop.add_path s alias) (List.rev !includes) let init_library_roots () = includes := [] (* Initialises the Ocaml toplevel before launching it, so that it can find the "include" file in the *source* directory *) let init_ocaml_path () = let coqsrc = Coq_config.coqsrc in let add_subdir dl = Mltop.add_ml_dir (List.fold_left (/) coqsrc dl) in Mltop.add_ml_dir (Envars.coqlib ()); List.iter add_subdir [ [ "config" ]; [ "dev" ]; [ "lib" ]; [ "kernel" ]; [ "library" ]; [ "pretyping" ]; [ "interp" ]; [ "parsing" ]; [ "proofs" ]; [ "tactics" ]; [ "toplevel" ]; [ "translate" ]; [ "ide" ] ]
null
https://raw.githubusercontent.com/mzp/coq-ide-for-ios/4cdb389bbecd7cdd114666a8450ecf5b5f0391d3/coqlib/toplevel/coqinit.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** By the option -include -I or -R of the command line The list of all theories in the standard library /!\ order does matter Initializes the LoadPath first user-contrib then states, theories and dev developer specific directory to open then standard library then current directory additional loadpath, given with -I -include -R options Initialises the Ocaml toplevel before launching it, so that it can find the "include" file in the *source* directory
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * $ I d : coqinit.ml 13323 2010 - 07 - 24 15:57:30Z herbelin $ open Pp open System open Toplevel let (/) = Filename.concat let set_debug () = Flags.debug := true Loading of the ressource file . rcfile is either $ HOME/.coqrc . VERSION , or $ HOME/.coqrc if the first one does not exist . rcfile is either $HOME/.coqrc.VERSION, or $HOME/.coqrc if the first one does not exist. *) let rcfile = ref (home/".coqrc") let rcfile_specified = ref false let set_rcfile s = rcfile := s; rcfile_specified := true let set_rcuser s = rcfile := ("~"^s)/".coqrc" let load_rc = ref true let no_load_rc () = load_rc := false let load_rcfile() = if !load_rc then try if !rcfile_specified then if file_readable_p !rcfile then Vernac.load_vernac false !rcfile else raise (Sys_error ("Cannot read rcfile: "^ !rcfile)) else if file_readable_p (!rcfile^"."^Coq_config.version) then Vernac.load_vernac false (!rcfile^"."^Coq_config.version) else if file_readable_p !rcfile then Vernac.load_vernac false !rcfile else () Flags.if_verbose ( ( " No .coqrc or .coqrc . "^Coq_config.version^ " found . Skipping rcfile loading . " ) ) Flags.if_verbose mSGNL (str ("No .coqrc or .coqrc."^Coq_config.version^ " found. Skipping rcfile loading.")) *) with e -> (msgnl (str"Load of rcfile failed."); raise e) else Flags.if_verbose msgnl (str"Skipping rcfile loading.") Puts dir in the path of ML and in the LoadPath let coq_add_path d s = Mltop.add_path d (Names.make_dirpath [Nameops.coq_root;Names.id_of_string s]) let coq_add_rec_path s = Mltop.add_rec_path s (Names.make_dirpath [Nameops.coq_root]) let includes = ref [] let push_include (s, alias) = includes := (s,alias,false) :: !includes let push_rec_include (s, alias) = includes := (s,alias,true) :: !includes let theories_dirs_map = [ "theories/Unicode", "Unicode" ; "theories/Classes", "Classes" ; "theories/Program", "Program" ; "theories/MSets", "MSets" ; "theories/FSets", "FSets" ; "theories/Reals", "Reals" ; "theories/Strings", "Strings" ; "theories/Sorting", "Sorting" ; "theories/Setoids", "Setoids" ; "theories/Sets", "Sets" ; "theories/Structures", "Structures" ; "theories/Lists", "Lists" ; "theories/Wellfounded", "Wellfounded" ; "theories/Relations", "Relations" ; "theories/Numbers", "Numbers" ; "theories/QArith", "QArith" ; "theories/NArith", "NArith" ; "theories/ZArith", "ZArith" ; "theories/Arith", "Arith" ; "theories/Bool", "Bool" ; "theories/Logic", "Logic" ; "theories/Init", "Init" ] let init_load_path () = let coqlib = Envars.coqlib () in let user_contrib = coqlib/"user-contrib" in let dirs = ["states";"plugins"] in if Sys.file_exists user_contrib then Mltop.add_rec_path user_contrib Nameops.default_root_prefix; List.iter (fun s -> coq_add_rec_path (coqlib/s)) dirs; if Coq_config.local then coq_add_path (coqlib/"dev") "dev"; List.iter (fun (s,alias) -> Mltop.add_rec_path (coqlib/s) (Names.make_dirpath [Names.id_of_string alias; Nameops.coq_root])) theories_dirs_map; Mltop.add_path "." Nameops.default_root_prefix; List.iter (fun (s,alias,reci) -> if reci then Mltop.add_rec_path s alias else Mltop.add_path s alias) (List.rev !includes) let init_library_roots () = includes := [] let init_ocaml_path () = let coqsrc = Coq_config.coqsrc in let add_subdir dl = Mltop.add_ml_dir (List.fold_left (/) coqsrc dl) in Mltop.add_ml_dir (Envars.coqlib ()); List.iter add_subdir [ [ "config" ]; [ "dev" ]; [ "lib" ]; [ "kernel" ]; [ "library" ]; [ "pretyping" ]; [ "interp" ]; [ "parsing" ]; [ "proofs" ]; [ "tactics" ]; [ "toplevel" ]; [ "translate" ]; [ "ide" ] ]