_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
|
---|---|---|---|---|---|---|---|---|
f7a3739bb46236d5d173f9f162f71bdb4d92edff3d7f81120dc2bea9e2a79b34 | herd/herdtools7 | args.mli | (****************************************************************************)
(* the diy toolsuite *)
(* *)
, University College London , UK .
, INRIA Paris - Rocquencourt , France .
(* *)
Copyright 2013 - present Institut National de Recherche en Informatique et
(* en Automatique and the authors. All rights reserved. *)
(* *)
This software is governed by the CeCILL - B license under French law and
(* abiding by the rules of distribution of free software. You can use, *)
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
(****************************************************************************)
(** Utilities for using the built-in Arg module. *)
type spec = Arg.key * Arg.spec * Arg.doc
(* Specs. *)
* [ append_string r ] builds an Arg.spec that appends to the string list
* referenced by [ r ] .
* referenced by [r]. *)
val append_string : string list ref -> Arg.spec
* [ set_string_option r ] builds an Arg.spec that , for argument value [ v ] , sets
* the string option referenced by [ r ] to [ Some v ] .
* the string option referenced by [r] to [Some v]. *)
val set_string_option : string option ref -> Arg.spec
(** Common options *)
* [ npar j ] Build an Arg.spec for setting j , with documentation as
* setting the parallelism level .
* setting the parallelism level. *)
val npar : int option ref -> spec
(** Validators. *)
* [ is_file ( k , s , d ) ] returns [ k , s ' , d ] , where [ s ' ] wraps [ s ] with an
* Arg.spec that raises Arg . Bad if the argument is not a valid path to a file .
* Arg.spec that raises Arg.Bad if the argument is not a valid path to a file. *)
val is_file : spec -> spec
* [ is_dir ( k , s , d ) ] returns [ k , s ' , d ] , where [ s ' ] wraps [ s ] with an
* Arg.spec that raises Arg . Bad if the argument is not a valid path to a
* directory .
* Arg.spec that raises Arg.Bad if the argument is not a valid path to a
* directory. *)
val is_dir : spec -> spec
| null | https://raw.githubusercontent.com/herd/herdtools7/0660e6f342d36bf130b213ab3f842118f73e37b1/internal/lib/args.mli | ocaml | **************************************************************************
the diy toolsuite
en Automatique and the authors. All rights reserved.
abiding by the rules of distribution of free software. You can use,
**************************************************************************
* Utilities for using the built-in Arg module.
Specs.
* Common options
* Validators. | , University College London , UK .
, INRIA Paris - Rocquencourt , France .
Copyright 2013 - present Institut National de Recherche en Informatique et
This software is governed by the CeCILL - B license under French law and
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
type spec = Arg.key * Arg.spec * Arg.doc
* [ append_string r ] builds an Arg.spec that appends to the string list
* referenced by [ r ] .
* referenced by [r]. *)
val append_string : string list ref -> Arg.spec
* [ set_string_option r ] builds an Arg.spec that , for argument value [ v ] , sets
* the string option referenced by [ r ] to [ Some v ] .
* the string option referenced by [r] to [Some v]. *)
val set_string_option : string option ref -> Arg.spec
* [ npar j ] Build an Arg.spec for setting j , with documentation as
* setting the parallelism level .
* setting the parallelism level. *)
val npar : int option ref -> spec
* [ is_file ( k , s , d ) ] returns [ k , s ' , d ] , where [ s ' ] wraps [ s ] with an
* Arg.spec that raises Arg . Bad if the argument is not a valid path to a file .
* Arg.spec that raises Arg.Bad if the argument is not a valid path to a file. *)
val is_file : spec -> spec
* [ is_dir ( k , s , d ) ] returns [ k , s ' , d ] , where [ s ' ] wraps [ s ] with an
* Arg.spec that raises Arg . Bad if the argument is not a valid path to a
* directory .
* Arg.spec that raises Arg.Bad if the argument is not a valid path to a
* directory. *)
val is_dir : spec -> spec
|
85e76f7f8f984a79caae31e2f49d5c14378e29c45b0be4ed3fff6eeb8d14bb36 | avh4/elm-format | Common.hs | module Parse.Common
( sectionedGroup, pair
, commented, preCommented, postCommented, withEol
, checkMultiline
) where
import AST.V0_16
import Parse.ParsecAdapter
import Parse.Helpers
import Parse.Whitespace
import Parse.IParser
import Parse.Comments
--
-- Structure
--
pair :: IParser a -> IParser sep -> IParser b -> IParser (Pair a b)
pair a sep b =
checkMultiline $ Pair <$> postCommented a <* sep <*> preCommented b
sectionedGroup :: IParser a -> IParser (Sequence a, Comments)
sectionedGroup term =
let
step leading terms =
do
pre <- whitespace
(C eol first) <- withEol term
preSep <- whitespace
hasMore <- choice [ comma *> return True, return False ]
if hasMore
then step preSep (C (leading, pre, eol) first : terms)
else return (Sequence $ reverse (C (leading, pre, eol) first : terms), preSep)
in
choice
[ try $ step [] []
, (,) (Sequence []) <$> whitespace
]
--
-- Other helpers
--
checkMultiline :: IParser (ForceMultiline -> a) -> IParser a
checkMultiline inner =
do
(a, multiline) <- trackNewline inner
return $ a (ForceMultiline $ multilineToBool multiline)
| null | https://raw.githubusercontent.com/avh4/elm-format/af3acfc89b619b9dbcdbdb7185d3936971d76f87/elm-format-lib/src/Parse/Common.hs | haskell |
Structure
Other helpers
| module Parse.Common
( sectionedGroup, pair
, commented, preCommented, postCommented, withEol
, checkMultiline
) where
import AST.V0_16
import Parse.ParsecAdapter
import Parse.Helpers
import Parse.Whitespace
import Parse.IParser
import Parse.Comments
pair :: IParser a -> IParser sep -> IParser b -> IParser (Pair a b)
pair a sep b =
checkMultiline $ Pair <$> postCommented a <* sep <*> preCommented b
sectionedGroup :: IParser a -> IParser (Sequence a, Comments)
sectionedGroup term =
let
step leading terms =
do
pre <- whitespace
(C eol first) <- withEol term
preSep <- whitespace
hasMore <- choice [ comma *> return True, return False ]
if hasMore
then step preSep (C (leading, pre, eol) first : terms)
else return (Sequence $ reverse (C (leading, pre, eol) first : terms), preSep)
in
choice
[ try $ step [] []
, (,) (Sequence []) <$> whitespace
]
checkMultiline :: IParser (ForceMultiline -> a) -> IParser a
checkMultiline inner =
do
(a, multiline) <- trackNewline inner
return $ a (ForceMultiline $ multilineToBool multiline)
|
4606fc3db1d00e31ca875b36790a4b7be4e0cf601833a36d2645c41fd7b37462 | PEZ/rich4clojure | problem_131.clj | (ns rich4clojure.medium.problem-131
(:require [hyperfiddle.rcf :refer [tests]]))
;; = Sum Some Set Subsets =
;; By 4Clojure user: amcnamara
;; Difficulty: Medium
;; Tags: [math]
;;
;; Given a variable number of sets of integers, create a
;; function which returns true iff all of the sets have a
;; non-empty subset with an equivalent summation.
(def __ :tests-will-fail)
(comment
)
(tests
true := (__ #{-1 1 99}
#{-2 2 888}
#{-3 3 7777})
false := (__ #{1}
#{2}
#{3}
#{4})
true := (__ #{1})
false := (__ #{1 -3 51 9}
#{0}
#{9 2 81 33})
true := (__ #{1 3 5}
#{9 11 4}
#{-3 12 3}
#{-3 4 -2 10})
false := (__ #{-1 -2 -3 -4 -5 -6}
#{1 2 3 4 5 6 7 8 9})
true := (__ #{1 3 5 7}
#{2 4 6 8})
true := (__ #{-1 3 -5 7 -9 11 -13 15}
#{1 -3 5 -7 9 -11 13 -15}
#{1 -1 2 -2 4 -4 8 -8})
true := (__ #{-10 9 -8 7 -6 5 -4 3 -2 1}
#{10 -9 8 -7 6 -5 4 -3 2 -1}))
;; Share your solution, and/or check how others did it:
| null | https://raw.githubusercontent.com/PEZ/rich4clojure/2ccfac041840e9b1550f0a69b9becbdb03f9525b/src/rich4clojure/medium/problem_131.clj | clojure | = Sum Some Set Subsets =
By 4Clojure user: amcnamara
Difficulty: Medium
Tags: [math]
Given a variable number of sets of integers, create a
function which returns true iff all of the sets have a
non-empty subset with an equivalent summation.
Share your solution, and/or check how others did it: | (ns rich4clojure.medium.problem-131
(:require [hyperfiddle.rcf :refer [tests]]))
(def __ :tests-will-fail)
(comment
)
(tests
true := (__ #{-1 1 99}
#{-2 2 888}
#{-3 3 7777})
false := (__ #{1}
#{2}
#{3}
#{4})
true := (__ #{1})
false := (__ #{1 -3 51 9}
#{0}
#{9 2 81 33})
true := (__ #{1 3 5}
#{9 11 4}
#{-3 12 3}
#{-3 4 -2 10})
false := (__ #{-1 -2 -3 -4 -5 -6}
#{1 2 3 4 5 6 7 8 9})
true := (__ #{1 3 5 7}
#{2 4 6 8})
true := (__ #{-1 3 -5 7 -9 11 -13 15}
#{1 -3 5 -7 9 -11 13 -15}
#{1 -1 2 -2 4 -4 8 -8})
true := (__ #{-10 9 -8 7 -6 5 -4 3 -2 1}
#{10 -9 8 -7 6 -5 4 -3 2 -1}))
|
4804d0077cda4d631f054dd6d37b0926a3a17aba4a8a486526d8d85b9addb5f9 | RyanGlScott/text-show | StaticPtrSpec.hs | # LANGUAGE CPP #
|
Module : Spec . GHC.StaticPtrSpec
Copyright : ( C ) 2014 - 2017
License : BSD - style ( see the file LICENSE )
Maintainer :
Stability : Provisional
Portability : GHC
@hspec@ test for ' StaticPtr ' .
Module: Spec.GHC.StaticPtrSpec
Copyright: (C) 2014-2017 Ryan Scott
License: BSD-style (see the file LICENSE)
Maintainer: Ryan Scott
Stability: Provisional
Portability: GHC
@hspec@ test for 'StaticPtr'.
-}
module Spec.GHC.StaticPtrSpec (main, spec) where
import Instances.GHC.StaticPtr ()
import Prelude ()
import Prelude.Compat
import Test.Hspec (Spec, hspec, parallel)
#if MIN_VERSION_base(4,8,0)
import Data.Proxy.Compat (Proxy(..))
import GHC.StaticPtr (StaticPtrInfo)
import Spec.Utils (matchesTextShowSpec)
import Test.Hspec (describe)
#endif
main :: IO ()
main = hspec spec
spec :: Spec
spec = parallel $
#if MIN_VERSION_base(4,8,0)
describe "StaticPtrInfo" $
matchesTextShowSpec (Proxy :: Proxy StaticPtrInfo)
#else
pure ()
#endif
| null | https://raw.githubusercontent.com/RyanGlScott/text-show/5ea297d0c7ae2d043f000c791cc12ac53f469944/tests/Spec/GHC/StaticPtrSpec.hs | haskell | # LANGUAGE CPP #
|
Module : Spec . GHC.StaticPtrSpec
Copyright : ( C ) 2014 - 2017
License : BSD - style ( see the file LICENSE )
Maintainer :
Stability : Provisional
Portability : GHC
@hspec@ test for ' StaticPtr ' .
Module: Spec.GHC.StaticPtrSpec
Copyright: (C) 2014-2017 Ryan Scott
License: BSD-style (see the file LICENSE)
Maintainer: Ryan Scott
Stability: Provisional
Portability: GHC
@hspec@ test for 'StaticPtr'.
-}
module Spec.GHC.StaticPtrSpec (main, spec) where
import Instances.GHC.StaticPtr ()
import Prelude ()
import Prelude.Compat
import Test.Hspec (Spec, hspec, parallel)
#if MIN_VERSION_base(4,8,0)
import Data.Proxy.Compat (Proxy(..))
import GHC.StaticPtr (StaticPtrInfo)
import Spec.Utils (matchesTextShowSpec)
import Test.Hspec (describe)
#endif
main :: IO ()
main = hspec spec
spec :: Spec
spec = parallel $
#if MIN_VERSION_base(4,8,0)
describe "StaticPtrInfo" $
matchesTextShowSpec (Proxy :: Proxy StaticPtrInfo)
#else
pure ()
#endif
|
|
7d851be5a3085811b2db2c77809573e29425e88ca098657b751247f87419f660 | Octachron/codept | riddle.ml |
module A = struct module M1 = struct end end
module B = struct module M2 = struct end end
module C = struct module M3 = struct end end
module D = struct module M4 = struct end end
module E = struct module M5 = struct end end
module F = struct module M6 = struct end end
module G = struct module M7 = struct end end
module type s1 = module type of A
module type s2 = module type of B
module type s3 = module type of C
module type s4 = module type of D
module type s5 = module type of E
module type s6 = module type of F
module type s7 = module type of G
type a = (module s1)
type b = (module s2)
type c = (module s3)
type d = (module s4)
type e = (module s5)
type f = (module s6)
type g = (module s7)
type ca = a * [`S of cb | `X2 of cb | `X3 of cc | `X5 of ce ]
and cb = b * [`S of cc | `X2 of cd | `X3 of cf | `X5 of cc ]
and cc = c * [`S of cd | `X2 of cf | `X3 of cb | `X5 of ca ]
and cd = d * [`S of ce | `X2 of ca | `X3 of ce | `X5 of cf ]
and ce = e * [`S of cf | `X2 of cc | `X3 of ca | `X5 of cd ]
and cf = f * [`S of cg | `X2 of ce | `X3 of cd | `X5 of cb ]
and cg = g * [`S of ca | `X2 of cg | `X3 of cg | `X5 of cg ]
type _ core =
| A: ca core
| B: cb core
| C: cc core
| D: cd core
| E: ce core
| F: cf core
| G: cg core
let extract (type a s x2 x3 x5): (a * [ `S of s | `X2 of x2 | `X3 of x3 | `X5 of x5 ] ) core -> a =
function
| A -> (module A : s1)
| B -> (module B : s2)
| C -> (module C : s3)
| D -> (module D : s4)
| E -> (module E : s5)
| F -> (module F : s6)
| G -> (module G : s7)
let succ (type a s x2 x3 x5):
(a * [ `S of s | `X2 of x2 | `X3 of x3 | `X5 of x5 ] ) core -> s core =
function
| A -> B
| B -> C
| C -> D
| E -> F
| D -> E
| F -> G
| G -> A
let x2 (type a s x2 x3 x5):
(a * [ `S of s | `X2 of x2 | `X3 of x3 | `X5 of x5 ] ) core -> x2 core =
function
| A -> B
| B -> D
| C -> F
| D -> A
| E -> C
| F -> E
| G -> G
let x3 (type a s x2 x3 x5):
(a * [ `S of s | `X2 of x2 | `X3 of x3 | `X5 of x5 ] ) core -> x3 core =
function
| A -> C
| B -> F
| C -> B
| D -> E
| E -> A
| F -> D
| G -> G
let x5 (type a s x2 x3 x5):
(a * [ `S of s | `X2 of x2 | `X3 of x3 | `X5 of x5 ] ) core -> x5 core =
function
| A -> E
| B -> C
| C -> A
| D -> F
| E -> D
| F -> B
| G -> G
let s1 x = succ x
let s2 x = s1 @@ succ x
let s3 x = s2 @@ s1 x
let s4 x = s3 @@ s1 x
let s5 x = s1 @@ s4 x
let s6 x = s5 @@ s1 x
let x = x5 @@ s2 @@ x3 @@ s5 @@ x2 @@ s1 @@ A
let () =
let (module M) = extract x in
let open M in
let open M5 in
()
| null | https://raw.githubusercontent.com/Octachron/codept/2d2a95fde3f67cdd0f5a1b68d8b8b47aefef9290/tests/cases/riddle.ml | ocaml |
module A = struct module M1 = struct end end
module B = struct module M2 = struct end end
module C = struct module M3 = struct end end
module D = struct module M4 = struct end end
module E = struct module M5 = struct end end
module F = struct module M6 = struct end end
module G = struct module M7 = struct end end
module type s1 = module type of A
module type s2 = module type of B
module type s3 = module type of C
module type s4 = module type of D
module type s5 = module type of E
module type s6 = module type of F
module type s7 = module type of G
type a = (module s1)
type b = (module s2)
type c = (module s3)
type d = (module s4)
type e = (module s5)
type f = (module s6)
type g = (module s7)
type ca = a * [`S of cb | `X2 of cb | `X3 of cc | `X5 of ce ]
and cb = b * [`S of cc | `X2 of cd | `X3 of cf | `X5 of cc ]
and cc = c * [`S of cd | `X2 of cf | `X3 of cb | `X5 of ca ]
and cd = d * [`S of ce | `X2 of ca | `X3 of ce | `X5 of cf ]
and ce = e * [`S of cf | `X2 of cc | `X3 of ca | `X5 of cd ]
and cf = f * [`S of cg | `X2 of ce | `X3 of cd | `X5 of cb ]
and cg = g * [`S of ca | `X2 of cg | `X3 of cg | `X5 of cg ]
type _ core =
| A: ca core
| B: cb core
| C: cc core
| D: cd core
| E: ce core
| F: cf core
| G: cg core
let extract (type a s x2 x3 x5): (a * [ `S of s | `X2 of x2 | `X3 of x3 | `X5 of x5 ] ) core -> a =
function
| A -> (module A : s1)
| B -> (module B : s2)
| C -> (module C : s3)
| D -> (module D : s4)
| E -> (module E : s5)
| F -> (module F : s6)
| G -> (module G : s7)
let succ (type a s x2 x3 x5):
(a * [ `S of s | `X2 of x2 | `X3 of x3 | `X5 of x5 ] ) core -> s core =
function
| A -> B
| B -> C
| C -> D
| E -> F
| D -> E
| F -> G
| G -> A
let x2 (type a s x2 x3 x5):
(a * [ `S of s | `X2 of x2 | `X3 of x3 | `X5 of x5 ] ) core -> x2 core =
function
| A -> B
| B -> D
| C -> F
| D -> A
| E -> C
| F -> E
| G -> G
let x3 (type a s x2 x3 x5):
(a * [ `S of s | `X2 of x2 | `X3 of x3 | `X5 of x5 ] ) core -> x3 core =
function
| A -> C
| B -> F
| C -> B
| D -> E
| E -> A
| F -> D
| G -> G
let x5 (type a s x2 x3 x5):
(a * [ `S of s | `X2 of x2 | `X3 of x3 | `X5 of x5 ] ) core -> x5 core =
function
| A -> E
| B -> C
| C -> A
| D -> F
| E -> D
| F -> B
| G -> G
let s1 x = succ x
let s2 x = s1 @@ succ x
let s3 x = s2 @@ s1 x
let s4 x = s3 @@ s1 x
let s5 x = s1 @@ s4 x
let s6 x = s5 @@ s1 x
let x = x5 @@ s2 @@ x3 @@ s5 @@ x2 @@ s1 @@ A
let () =
let (module M) = extract x in
let open M in
let open M5 in
()
|
|
aeb52f50754d83dc0447aca4f923d2b60c4e1792231965eb2521ac70af70afcb | hipsleek/hipsleek | musterr.ml | #include "xdebug.cppo"
open VarGen
1 . this file provides interfaces and implementations for
- must / may errors
2 . IMPORTANT ( AVOID REDUNDANT ): before implement new method , please go through
interfaces and UNUSED module to check whether your need is there .
1. this file provides interfaces and implementations for
- must/may errors
2. IMPORTANT (AVOID REDUNDANT): before implement new method, please go through
interfaces and UNUSED module to check whether your need is there.
*)
open Globals
open Others
open Stat_global
module DD = Debug
open . ETABLE_NFLOW
open Exc.GTable
open Cast
open Cformula
open Prooftracer
open Gen.Basic
open Immutable
open Perm
open Mcpure_D
open Mcpure
open Stat_global
open Cformula
(* module Inf = Infer *)
module CP = Cpure
module CF = Cformula
(* module PR = Cprinter *)
module MCP = Mcpure
module Err = Error
module TP = Tpdispatcher
module LO = Label_only . Lab_List
module LO = Label_only.LOne
(* type steps = string list *)
(* (\*implementation of must/may is moved to musterr.ml*\) *)
( \ * MAY
(* VALID MUST *)
BOT
(* *\) *)
(* type fail_context = { *)
(* fc_prior_steps : steps; (\* prior steps in reverse order *\) *)
(* fc_message : string; (\* error message *\) *)
( \ * fc_current_lhs : entail_state ; ( \\ * LHS context with success points * \\ ) * \ )
(* (\* fc_orig_conseq : struc_formula; (\\* RHS conseq at the point of failure *\\) *\) *)
fc_failure_pts : list ; ( \ * failure points in conseq * \ )
(* (\* fc_current_conseq : formula; *\) *)
(* } *)
and =
(* | Basic_Reason of (fail_context * fail_explaining) *)
(* | Trivial_Reason of fail_explaining *)
| Or_Reason of ( fail_type * )
| And_Reason of ( fail_type * )
| Union_Reason of ( fail_type * )
(* | ContinuationErr of fail_context *)
| Or_Continuation of ( fail_type * )
(* and failure_kind = *)
| Failure_May of string
(* | Failure_Must of string *)
(* | Failure_Bot of string *)
(* | Failure_Valid *)
(* and fail_explaining = { *)
(* fe_kind: failure_kind; (\*may/must*\) *)
(* fe_name: string; *)
(* fe_locs: VarGen.loc list; *)
(* (\* fe_explain: string; *\) *)
(* (\* string explaining must failure *\) *)
( \ * fe_sugg = struc_formula * \ )
(* } *)
maximising must bug with RAND ( error information )
let check_maymust_failure_x (ante:CP.formula) (cons:CP.formula): (CF.failure_kind*((CP.formula*CP.formula) list * (CP.formula*CP.formula) list * (CP.formula*CP.formula) list))=
if not !disable_failure_explaining then
let r = ref (-9999) in
let is_sat f = x_add TP.is_sat_sub_no 9 f r in
let find_all_failures a c = CP.find_all_failures is_sat a c in
let find_all_failures a c =
let pr1 = Cprinter.string_of_pure_formula in
let pr2 = pr_list (pr_pair pr1 pr1) in
let pr3 = pr_triple pr2 pr2 pr2 in
Debug.no_2 "find_all_failures" pr1 pr1 pr3 find_all_failures a c in
let filter_redundant a c = CP.simplify_filter_ante TP.simplify_always a c in
Check MAY / MUST : if being invalid and ( exists ( ante & conseq ) ) = true then that 's MAY failure ,
otherwise MUST failure
otherwise MUST failure *)
let ante_filter = filter_redundant ante cons in
let (r1, r2, r3) = find_all_failures ante_filter cons in
if List.length (r1@r2) = 0 then
begin
(CF.mk_failure_may_raw "", (r1, r2, r3))
end
else
begin
compute lub of must bug and current fc_flow
(CF.mk_failure_must_raw "", (r1, r2, r3))
end
else (
(CF.mk_failure_may_raw "", ([], [], [(ante, cons)]))
)
maximising must bug with RAND ( error information )
let check_maymust_failure (ante:CP.formula) (cons:CP.formula): (CF.failure_kind*((CP.formula*CP.formula) list * (CP.formula*CP.formula) list * (CP.formula*CP.formula) list))=
let pr1 = Cprinter.string_of_pure_formula in
let pr3 = pr_list (pr_pair pr1 pr1) in
let pr2 = pr_pair (Cprinter.string_of_failure_kind) (pr_triple pr3 pr3 pr3) in
Debug.no_2 "check_maymust_failure" pr1 pr1 pr2 (fun _ _ -> check_maymust_failure_x ante cons) ante cons
(*maximising must bug with AND (error information)*)
(* to return fail_type with AND_reason *)
let build_and_failures_x (failure_code:string) gfk(failure_name:string) ((contra_list, must_list, may_list)
:((CP.formula*CP.formula) list * (CP.formula*CP.formula) list * (CP.formula*CP.formula) list)) (fail_ctx_template: fail_context) cex
(ft: formula_trace) : list_context=
if not !disable_failure_explaining then
let build_and_one_kind_failures (failure_string:string) (fk: CF.failure_kind) (failure_list:(CP.formula*CP.formula) list):CF.fail_type option=
(*build must/may msg*)
let build_failure_msg (ante, cons) =
let ll = (CP.list_pos_of_formula ante []) @ (CP.list_pos_of_formula cons []) in
(*let () = print_endline (Cprinter.string_of_list_loc ll) in*)
let lli = CF.get_lines ll in
(*possible to eliminate unnecessary intermediate that are defined by equality.*)
(*not sure it is better*)
let ante = CP.elim_equi_ante ante cons in
((Cprinter.string_of_pure_formula ante) ^ " |- "^
(Cprinter.string_of_pure_formula cons) ^ ". LOCS:[" ^ (Cprinter.string_of_list_int lli) ^ "]", ll) in
match failure_list with
| [] -> None
| _ ->
let strs,locs= List.split (List.map build_failure_msg failure_list) in
(*get line number only*)
(* let rec get_line_number ll rs= *)
(* match ll with *)
(* | [] -> rs *)
(* | l::ls -> get_line_number ls (rs @ [l.start_pos.Lexing.pos_lnum]) *)
(* in *)
(*shoudl use ll in future*)
(* let ll = Gen.Basic.remove_dups (get_line_number (List.concat locs) []) in*)
let msg =
match strs with
| [] -> ""
| [s] -> s ^ " (" ^ failure_string ^ ")"
| _ -> (* "(failure_code="^failure_code ^ ") AndR[" ^ *)
"AndR[" ^ (String.concat "; " strs) ^ " (" ^ failure_string ^ ").]"
in
let fe = match fk with
| Failure_May _ -> mk_failure_may msg failure_name
| Failure_Must _ -> (mk_failure_must msg failure_name)
| _ -> {fe_kind = fk; fe_name = failure_name ;fe_locs=[]}
in
Some (Basic_Reason ({fail_ctx_template with fc_message = msg }, fe, ft))
in
let contra_fail_type = build_and_one_kind_failures "RHS: contradiction" (Failure_Must "") contra_list in
let must_fail_type = build_and_one_kind_failures "must-bug" (Failure_Must "") must_list in
let may_fail_type = build_and_one_kind_failures "may-bug" (Failure_May "") may_list in
let pr oft =
match oft with
| Some ft - > Cprinter.string_of_fail_type ft
| None - > " None "
in
let ( ) = print_endline ( " : " ^ ( pr contra_fail_type ) ) in
let ( ) = print_endline ( " locle must : " ^ ( pr ) ) in
let ( ) = print_endline ( " locle may : " ^ ( pr may_fail_type ) ) in
let pr oft =
match oft with
| Some ft -> Cprinter.string_of_fail_type ft
| None -> "None"
in
let () = print_endline ("locle contrad:" ^ (pr contra_fail_type)) in
let () = print_endline ("locle must:" ^ (pr must_fail_type)) in
let () = print_endline ("locle may:" ^ (pr may_fail_type)) in
*)
let oft = List.fold_left CF.mkAnd_Reason contra_fail_type [must_fail_type; may_fail_type] in
let es = {fail_ctx_template.fc_current_lhs with es_formula = (* CF.substitute_flow_into_f !error_flow_int *) fail_ctx_template.fc_current_lhs.es_formula} in
match oft with
| Some ft -> let final_error = (match gfk with
| Failure_Must _ -> ( match (get_must_ctx_msg_ft ft) with
| Some (_, s) -> Some (s, ft, gfk)
| None -> None
)
| Failure_May _ -> (match (get_may_ctx_msg_ft ft) with
| Some (_,s) -> Some (s, ft, gfk)
| None -> None
)
| _ -> None
)
in
FailCtx (ft, Ctx (x_add add_opt_to_estate final_error es),cex)
| None -> (*report_error no_pos "Solver.build_and_failures: should be a failure here"*)
let msg = "use different strategies in proof searching (slicing)" in
let fe = mk_failure_may msg failure_name in
FailCtx ((Basic_Reason ({fail_ctx_template with fc_message = msg }, fe, ft)),(Ctx es), cex)
else
let msg = "failed in entailing pure formula(s) in conseq" in
CF.mkFailCtx_in (Basic_Reason ({fail_ctx_template with fc_message = msg }, mk_failure_may msg failure_name, ft))
((CF.convert_to_may_es fail_ctx_template.fc_current_lhs), msg, Failure_May msg) cex
let build_and_failures i (failure_code:string) fk (failure_name:string) ((contra_list, must_list, may_list)
:((CP.formula*CP.formula) list * (CP.formula*CP.formula) list * (CP.formula*CP.formula) list))
(fail_ctx_template: fail_context) cex (ft: formula_trace) : list_context=
let pr1 = Cprinter.string_of_pure_formula in
let pr3 = pr_list (pr_pair pr1 pr1) in
let pr4 = pr_triple pr3 pr3 pr3 in
let pr2 = Cprinter.string_of_list_context_short in
Debug.no_1_num i "build_and_failures" pr4 pr2
(fun triple_list -> build_and_failures_x failure_code fk failure_name triple_list fail_ctx_template cex ft)
(contra_list, must_list, may_list)
(******************************************************)
(******************************************************)
(******************************************************)
Succ - > Succ
Fail - >
Basic - > Ctx
Trivial - > ? ?
Or_Reason ( ) - > ( )
And_Reason ( ctx1 , _ ) - > recf ctx1
Union - > [ Ctx1 ; ctx2 ]
ContinuationErr - >
Or_Continuation
Succ -> Succ
Fail ->
Basic -> Ctx
Trivial -> ??
Or_Reason () -> OCtx ()
And_Reason (ctx1, _) -> recf ctx1
Union -> [Ctx1; ctx2]
ContinuationErr ->
Or_Continuation
*)
let convert_list_context prog ctxs=
let rec convert_failure ft cex=
match ft with
| Basic_Reason (fc, fe, _) -> begin
let es = match fe.fe_kind with
| Failure_Must msg -> {fc.fc_current_lhs with
es_must_error = Some (msg, ft, cex);
es_final_error = (msg, ft,Failure_Must msg)::fc.fc_current_lhs.es_final_error
}
| Failure_May msg -> {fc.fc_current_lhs with es_may_error = Some (msg, ft, cex);
es_final_error = (msg, ft, Failure_May msg)::fc.fc_current_lhs.es_final_error
}
| _ -> fc.fc_current_lhs
in
Ctx es
end
| Or_Reason (ft1, ft2) -> OCtx (convert_failure ft1 cex, convert_failure ft2 cex)
| _ -> report_error no_pos "xxx"
(* | Trivial_Reason of (fail_explaining * formula_trace) *)
| And_Reason of ( fail_type * )
| Union_Reason of ( fail_type * )
(* | ContinuationErr of (fail_context * formula_trace) *)
| Or_Continuation of ( fail_type * )
in
match ctxs with
| SuccCtx _ -> ctxs
| FailCtx (ft, _, cex) -> SuccCtx [(convert_failure ft cex)]
(******************************************************)
(******************************************************)
(******************************************************)
| null | https://raw.githubusercontent.com/hipsleek/hipsleek/596f7fa7f67444c8309da2ca86ba4c47d376618c/src/musterr.ml | ocaml | module Inf = Infer
module PR = Cprinter
type steps = string list
(\*implementation of must/may is moved to musterr.ml*\)
VALID MUST
*\)
type fail_context = {
fc_prior_steps : steps; (\* prior steps in reverse order *\)
fc_message : string; (\* error message *\)
(\* fc_orig_conseq : struc_formula; (\\* RHS conseq at the point of failure *\\) *\)
(\* fc_current_conseq : formula; *\)
}
| Basic_Reason of (fail_context * fail_explaining)
| Trivial_Reason of fail_explaining
| ContinuationErr of fail_context
and failure_kind =
| Failure_Must of string
| Failure_Bot of string
| Failure_Valid
and fail_explaining = {
fe_kind: failure_kind; (\*may/must*\)
fe_name: string;
fe_locs: VarGen.loc list;
(\* fe_explain: string; *\)
(\* string explaining must failure *\)
}
maximising must bug with AND (error information)
to return fail_type with AND_reason
build must/may msg
let () = print_endline (Cprinter.string_of_list_loc ll) in
possible to eliminate unnecessary intermediate that are defined by equality.
not sure it is better
get line number only
let rec get_line_number ll rs=
match ll with
| [] -> rs
| l::ls -> get_line_number ls (rs @ [l.start_pos.Lexing.pos_lnum])
in
shoudl use ll in future
let ll = Gen.Basic.remove_dups (get_line_number (List.concat locs) []) in
"(failure_code="^failure_code ^ ") AndR[" ^
CF.substitute_flow_into_f !error_flow_int
report_error no_pos "Solver.build_and_failures: should be a failure here"
****************************************************
****************************************************
****************************************************
| Trivial_Reason of (fail_explaining * formula_trace)
| ContinuationErr of (fail_context * formula_trace)
****************************************************
****************************************************
**************************************************** | #include "xdebug.cppo"
open VarGen
1 . this file provides interfaces and implementations for
- must / may errors
2 . IMPORTANT ( AVOID REDUNDANT ): before implement new method , please go through
interfaces and UNUSED module to check whether your need is there .
1. this file provides interfaces and implementations for
- must/may errors
2. IMPORTANT (AVOID REDUNDANT): before implement new method, please go through
interfaces and UNUSED module to check whether your need is there.
*)
open Globals
open Others
open Stat_global
module DD = Debug
open . ETABLE_NFLOW
open Exc.GTable
open Cast
open Cformula
open Prooftracer
open Gen.Basic
open Immutable
open Perm
open Mcpure_D
open Mcpure
open Stat_global
open Cformula
module CP = Cpure
module CF = Cformula
module MCP = Mcpure
module Err = Error
module TP = Tpdispatcher
module LO = Label_only . Lab_List
module LO = Label_only.LOne
( \ * MAY
BOT
( \ * fc_current_lhs : entail_state ; ( \\ * LHS context with success points * \\ ) * \ )
fc_failure_pts : list ; ( \ * failure points in conseq * \ )
and =
| Or_Reason of ( fail_type * )
| And_Reason of ( fail_type * )
| Union_Reason of ( fail_type * )
| Or_Continuation of ( fail_type * )
| Failure_May of string
( \ * fe_sugg = struc_formula * \ )
maximising must bug with RAND ( error information )
let check_maymust_failure_x (ante:CP.formula) (cons:CP.formula): (CF.failure_kind*((CP.formula*CP.formula) list * (CP.formula*CP.formula) list * (CP.formula*CP.formula) list))=
if not !disable_failure_explaining then
let r = ref (-9999) in
let is_sat f = x_add TP.is_sat_sub_no 9 f r in
let find_all_failures a c = CP.find_all_failures is_sat a c in
let find_all_failures a c =
let pr1 = Cprinter.string_of_pure_formula in
let pr2 = pr_list (pr_pair pr1 pr1) in
let pr3 = pr_triple pr2 pr2 pr2 in
Debug.no_2 "find_all_failures" pr1 pr1 pr3 find_all_failures a c in
let filter_redundant a c = CP.simplify_filter_ante TP.simplify_always a c in
Check MAY / MUST : if being invalid and ( exists ( ante & conseq ) ) = true then that 's MAY failure ,
otherwise MUST failure
otherwise MUST failure *)
let ante_filter = filter_redundant ante cons in
let (r1, r2, r3) = find_all_failures ante_filter cons in
if List.length (r1@r2) = 0 then
begin
(CF.mk_failure_may_raw "", (r1, r2, r3))
end
else
begin
compute lub of must bug and current fc_flow
(CF.mk_failure_must_raw "", (r1, r2, r3))
end
else (
(CF.mk_failure_may_raw "", ([], [], [(ante, cons)]))
)
maximising must bug with RAND ( error information )
let check_maymust_failure (ante:CP.formula) (cons:CP.formula): (CF.failure_kind*((CP.formula*CP.formula) list * (CP.formula*CP.formula) list * (CP.formula*CP.formula) list))=
let pr1 = Cprinter.string_of_pure_formula in
let pr3 = pr_list (pr_pair pr1 pr1) in
let pr2 = pr_pair (Cprinter.string_of_failure_kind) (pr_triple pr3 pr3 pr3) in
Debug.no_2 "check_maymust_failure" pr1 pr1 pr2 (fun _ _ -> check_maymust_failure_x ante cons) ante cons
let build_and_failures_x (failure_code:string) gfk(failure_name:string) ((contra_list, must_list, may_list)
:((CP.formula*CP.formula) list * (CP.formula*CP.formula) list * (CP.formula*CP.formula) list)) (fail_ctx_template: fail_context) cex
(ft: formula_trace) : list_context=
if not !disable_failure_explaining then
let build_and_one_kind_failures (failure_string:string) (fk: CF.failure_kind) (failure_list:(CP.formula*CP.formula) list):CF.fail_type option=
let build_failure_msg (ante, cons) =
let ll = (CP.list_pos_of_formula ante []) @ (CP.list_pos_of_formula cons []) in
let lli = CF.get_lines ll in
let ante = CP.elim_equi_ante ante cons in
((Cprinter.string_of_pure_formula ante) ^ " |- "^
(Cprinter.string_of_pure_formula cons) ^ ". LOCS:[" ^ (Cprinter.string_of_list_int lli) ^ "]", ll) in
match failure_list with
| [] -> None
| _ ->
let strs,locs= List.split (List.map build_failure_msg failure_list) in
let msg =
match strs with
| [] -> ""
| [s] -> s ^ " (" ^ failure_string ^ ")"
"AndR[" ^ (String.concat "; " strs) ^ " (" ^ failure_string ^ ").]"
in
let fe = match fk with
| Failure_May _ -> mk_failure_may msg failure_name
| Failure_Must _ -> (mk_failure_must msg failure_name)
| _ -> {fe_kind = fk; fe_name = failure_name ;fe_locs=[]}
in
Some (Basic_Reason ({fail_ctx_template with fc_message = msg }, fe, ft))
in
let contra_fail_type = build_and_one_kind_failures "RHS: contradiction" (Failure_Must "") contra_list in
let must_fail_type = build_and_one_kind_failures "must-bug" (Failure_Must "") must_list in
let may_fail_type = build_and_one_kind_failures "may-bug" (Failure_May "") may_list in
let pr oft =
match oft with
| Some ft - > Cprinter.string_of_fail_type ft
| None - > " None "
in
let ( ) = print_endline ( " : " ^ ( pr contra_fail_type ) ) in
let ( ) = print_endline ( " locle must : " ^ ( pr ) ) in
let ( ) = print_endline ( " locle may : " ^ ( pr may_fail_type ) ) in
let pr oft =
match oft with
| Some ft -> Cprinter.string_of_fail_type ft
| None -> "None"
in
let () = print_endline ("locle contrad:" ^ (pr contra_fail_type)) in
let () = print_endline ("locle must:" ^ (pr must_fail_type)) in
let () = print_endline ("locle may:" ^ (pr may_fail_type)) in
*)
let oft = List.fold_left CF.mkAnd_Reason contra_fail_type [must_fail_type; may_fail_type] in
match oft with
| Some ft -> let final_error = (match gfk with
| Failure_Must _ -> ( match (get_must_ctx_msg_ft ft) with
| Some (_, s) -> Some (s, ft, gfk)
| None -> None
)
| Failure_May _ -> (match (get_may_ctx_msg_ft ft) with
| Some (_,s) -> Some (s, ft, gfk)
| None -> None
)
| _ -> None
)
in
FailCtx (ft, Ctx (x_add add_opt_to_estate final_error es),cex)
let msg = "use different strategies in proof searching (slicing)" in
let fe = mk_failure_may msg failure_name in
FailCtx ((Basic_Reason ({fail_ctx_template with fc_message = msg }, fe, ft)),(Ctx es), cex)
else
let msg = "failed in entailing pure formula(s) in conseq" in
CF.mkFailCtx_in (Basic_Reason ({fail_ctx_template with fc_message = msg }, mk_failure_may msg failure_name, ft))
((CF.convert_to_may_es fail_ctx_template.fc_current_lhs), msg, Failure_May msg) cex
let build_and_failures i (failure_code:string) fk (failure_name:string) ((contra_list, must_list, may_list)
:((CP.formula*CP.formula) list * (CP.formula*CP.formula) list * (CP.formula*CP.formula) list))
(fail_ctx_template: fail_context) cex (ft: formula_trace) : list_context=
let pr1 = Cprinter.string_of_pure_formula in
let pr3 = pr_list (pr_pair pr1 pr1) in
let pr4 = pr_triple pr3 pr3 pr3 in
let pr2 = Cprinter.string_of_list_context_short in
Debug.no_1_num i "build_and_failures" pr4 pr2
(fun triple_list -> build_and_failures_x failure_code fk failure_name triple_list fail_ctx_template cex ft)
(contra_list, must_list, may_list)
Succ - > Succ
Fail - >
Basic - > Ctx
Trivial - > ? ?
Or_Reason ( ) - > ( )
And_Reason ( ctx1 , _ ) - > recf ctx1
Union - > [ Ctx1 ; ctx2 ]
ContinuationErr - >
Or_Continuation
Succ -> Succ
Fail ->
Basic -> Ctx
Trivial -> ??
Or_Reason () -> OCtx ()
And_Reason (ctx1, _) -> recf ctx1
Union -> [Ctx1; ctx2]
ContinuationErr ->
Or_Continuation
*)
let convert_list_context prog ctxs=
let rec convert_failure ft cex=
match ft with
| Basic_Reason (fc, fe, _) -> begin
let es = match fe.fe_kind with
| Failure_Must msg -> {fc.fc_current_lhs with
es_must_error = Some (msg, ft, cex);
es_final_error = (msg, ft,Failure_Must msg)::fc.fc_current_lhs.es_final_error
}
| Failure_May msg -> {fc.fc_current_lhs with es_may_error = Some (msg, ft, cex);
es_final_error = (msg, ft, Failure_May msg)::fc.fc_current_lhs.es_final_error
}
| _ -> fc.fc_current_lhs
in
Ctx es
end
| Or_Reason (ft1, ft2) -> OCtx (convert_failure ft1 cex, convert_failure ft2 cex)
| _ -> report_error no_pos "xxx"
| And_Reason of ( fail_type * )
| Union_Reason of ( fail_type * )
| Or_Continuation of ( fail_type * )
in
match ctxs with
| SuccCtx _ -> ctxs
| FailCtx (ft, _, cex) -> SuccCtx [(convert_failure ft cex)]
|
4c634bab8d6a888c67a1629bb9d4694ad295826eebe3201decbb34662e3d0d0b | ashinn/chibi-scheme | quoted-printable.scm | ;; quoted-printable.scm -- RFC2045 implementation
Copyright ( c ) 2005 - 2014 . All rights reserved .
;; BSD-style license:
;;> RFC 2045 quoted printable encoding and decoding utilities. This
> API is backwards compatible with the Gauche library
;;> rfc.quoted-printable.
;;> \schemeblock{
;;> (define (mime-encode-header header value charset)
;;> (let ((prefix (string-append header ": "))
;;> (str (ces-convert value "UTF8" charset)))
;;> (string-append
;;> prefix
;;> (quoted-printable-encode-header charset str (string-length prefix)))))
;;> }
(define *default-max-col* 76)
Allow for RFC1522 quoting for headers by always escaping ? and _
(define (qp-encode bv start-col max-col separator)
(define (hex i) (+ i (if (<= i 9) 48 55)))
(let ((end (bytevector-length bv))
(buf (make-bytevector max-col))
(out (open-output-bytevector)))
(let lp ((i 0) (col start-col))
(cond
((= i end)
(write-bytevector (bytevector-copy buf 0 col) out)
(get-output-bytevector out))
((>= col (- max-col 3))
(write-bytevector (bytevector-copy buf 0 col) out)
(lp i 0))
(else
(let ((c (bytevector-u8-ref bv i)))
(cond
((and (<= 33 c 126) (not (memq c '(61 63 95))))
(bytevector-u8-set! buf col c)
(lp (+ i 1) (+ col 1)))
(else
(bytevector-u8-set! buf col (char->integer #\=))
(bytevector-u8-set! buf (+ col 1) (hex (arithmetic-shift c -4)))
(bytevector-u8-set! buf (+ col 2) (hex (bitwise-and c #b1111)))
(lp (+ i 1) (+ col 3))))))))))
;;> Return a quoted-printable encoded representation of the input
;;> according to the official standard as described in RFC2045.
;;>
;;> ? and _ are always encoded for compatibility with RFC1522
;;> encoding, and soft newlines are inserted as necessary to keep each
> lines length less than \var{max - col } ( default 76 ) . The starting
;;> column may be overridden with \var{start-col} (default 0).
(define (quoted-printable-encode-string src . o)
(if (string? src)
(utf8->string
(apply quoted-printable-encode-bytevector
(string->utf8 src)
o))
(apply quoted-printable-encode-bytevector src o)))
(define (quoted-printable-encode-bytevector . o)
(let* ((src (if (pair? o) (car o) (current-input-port)))
(o (if (pair? o) (cdr o) '()))
(start-col (if (pair? o) (car o) 0))
(o (if (pair? o) (cdr o) '()))
(max-col (if (pair? o) (car o) *default-max-col*))
(o (if (pair? o) (cdr o) '()))
(sep (if (pair? o) (car o) (string->utf8 "=\r\n"))))
(qp-encode (if (bytevector? src) src (read-bytevector 1000000000 src))
start-col max-col sep)))
;;> Variation of the above to read and write to ports.
(define (quoted-printable-encode . o)
(write-string (apply quoted-printable-encode-string o)))
;;> Return a quoted-printable encoded representation of string as
;;> above, wrapped in =?ENC?Q?...?= as per RFC1522, split across
;;> multiple MIME-header lines as needed to keep each lines length
;;> less than \var{max-col}. The string is encoded as is, and the
;;> encoding \var{enc} is just used for the prefix, i.e. you are
> responsible for ensuring \var{str } is already encoded according to
;;> \var{enc}.
(define (quoted-printable-encode-header encoding . o)
(let* ((src (if (pair? o) (car o) (current-input-port)))
(o (if (pair? o) (cdr o) '()))
(start-col (if (pair? o) (car o) 0))
(o (if (pair? o) (cdr o) '()))
(max-col (if (pair? o) (car o) *default-max-col*))
(o (if (pair? o) (cdr o) '()))
(nl (if (pair? o) (car o) "\r\n")))
(let* ((prefix (string-append "=?" encoding "?Q?"))
(prefix-length (+ 2 (string-length prefix)))
(separator (string->utf8 (string-append "?=" nl "\t" prefix)))
(effective-max-col (- max-col prefix-length)))
(bytevector-append
(string->utf8 prefix)
(qp-encode (if (string? src) src (port->string src))
start-col effective-max-col separator)
(string->utf8 "?=")))))
> Return a quoted - printable decoded representation of \var{str } . If
;;> \var{mime-header?} is specified and true, _ will be decoded as as
;;> space in accordance with RFC1522. No errors will be raised on
;;> invalid input.
(define (quoted-printable-decode-string src . o)
(if (string? src)
(utf8->string
(apply quoted-printable-decode-bytevector
(string->utf8 src)
o))
(apply quoted-printable-decode-bytevector src o)))
(define (quoted-printable-decode-bytevector . o)
(define (hex? c)
(or (char<=? #\0 (integer->char c) #\9)
(char<=? #\A (integer->char c) #\F)))
(define (unhex1 i)
(if (>= i 65) (- i 55) (- i 48)))
(define (unhex c1 c2)
(+ (arithmetic-shift (unhex1 c1) 4) (unhex1 c2)))
(let ((src (if (pair? o) (car o) (current-input-port)))
(mime-header? (and (pair? o) (pair? (cdr o)) (car (cdr o)))))
(let* ((bv (if (bytevector? src) src (read-bytevector 1000000000 src)))
(end (bytevector-length bv))
(out (open-output-bytevector)))
(let lp ((i 0))
(cond
((>= i end)
(get-output-bytevector out))
(else
(let ((c (bytevector-u8-ref bv i)))
(case c
((61) ; = escapes
(cond
((< (+ i 2) end)
(let ((c2 (bytevector-u8-ref bv (+ i 1))))
(cond
((eq? c2 10) (lp (+ i 2)))
((eq? c2 13)
(lp (if (eq? 10 (bytevector-u8-ref bv (+ i 2)))
(+ i 3)
(+ i 2))))
((hex? c2)
(let ((c3 (bytevector-u8-ref bv (+ i 2))))
(if (hex? c3) (write-u8 (unhex c2 c3) out))
(lp (+ i 3))))
(else (lp (+ i 3))))))))
((95) ; maybe translate _ to space
(write-u8 (if mime-header? 32 c) out)
(lp (+ i 1)))
((32 9) ; strip trailing whitespace
(let lp2 ((j (+ i 1)))
(cond
((not (= j end))
(case (bytevector-u8-ref bv j)
((32 9) (lp2 (+ j 1)))
((10)
(lp (+ j 1)))
((13)
(let ((k (+ j 1)))
(lp (if (and (< k end)
(eq? 10 (bytevector-u8-ref bv k)))
(+ k 1) k))))
(else
(write-bytevector (bytevector-copy bv i j) out)
(lp j)))))))
(else ; a literal char
(write-u8 c out)
(lp (+ i 1)))))))))))
;;> Variation of the above to read and write to ports.
(define (quoted-printable-decode . o)
(write-string (apply quoted-printable-decode-string o)))
| null | https://raw.githubusercontent.com/ashinn/chibi-scheme/8b27ce97265e5028c61b2386a86a2c43c1cfba0d/lib/chibi/quoted-printable.scm | scheme | quoted-printable.scm -- RFC2045 implementation
BSD-style license:
> RFC 2045 quoted printable encoding and decoding utilities. This
> rfc.quoted-printable.
> \schemeblock{
> (define (mime-encode-header header value charset)
> (let ((prefix (string-append header ": "))
> (str (ces-convert value "UTF8" charset)))
> (string-append
> prefix
> (quoted-printable-encode-header charset str (string-length prefix)))))
> }
> Return a quoted-printable encoded representation of the input
> according to the official standard as described in RFC2045.
>
> ? and _ are always encoded for compatibility with RFC1522
> encoding, and soft newlines are inserted as necessary to keep each
> column may be overridden with \var{start-col} (default 0).
> Variation of the above to read and write to ports.
> Return a quoted-printable encoded representation of string as
> above, wrapped in =?ENC?Q?...?= as per RFC1522, split across
> multiple MIME-header lines as needed to keep each lines length
> less than \var{max-col}. The string is encoded as is, and the
> encoding \var{enc} is just used for the prefix, i.e. you are
> \var{enc}.
> \var{mime-header?} is specified and true, _ will be decoded as as
> space in accordance with RFC1522. No errors will be raised on
> invalid input.
= escapes
maybe translate _ to space
strip trailing whitespace
a literal char
> Variation of the above to read and write to ports. | Copyright ( c ) 2005 - 2014 . All rights reserved .
> API is backwards compatible with the Gauche library
(define *default-max-col* 76)
Allow for RFC1522 quoting for headers by always escaping ? and _
(define (qp-encode bv start-col max-col separator)
(define (hex i) (+ i (if (<= i 9) 48 55)))
(let ((end (bytevector-length bv))
(buf (make-bytevector max-col))
(out (open-output-bytevector)))
(let lp ((i 0) (col start-col))
(cond
((= i end)
(write-bytevector (bytevector-copy buf 0 col) out)
(get-output-bytevector out))
((>= col (- max-col 3))
(write-bytevector (bytevector-copy buf 0 col) out)
(lp i 0))
(else
(let ((c (bytevector-u8-ref bv i)))
(cond
((and (<= 33 c 126) (not (memq c '(61 63 95))))
(bytevector-u8-set! buf col c)
(lp (+ i 1) (+ col 1)))
(else
(bytevector-u8-set! buf col (char->integer #\=))
(bytevector-u8-set! buf (+ col 1) (hex (arithmetic-shift c -4)))
(bytevector-u8-set! buf (+ col 2) (hex (bitwise-and c #b1111)))
(lp (+ i 1) (+ col 3))))))))))
> lines length less than \var{max - col } ( default 76 ) . The starting
(define (quoted-printable-encode-string src . o)
(if (string? src)
(utf8->string
(apply quoted-printable-encode-bytevector
(string->utf8 src)
o))
(apply quoted-printable-encode-bytevector src o)))
(define (quoted-printable-encode-bytevector . o)
(let* ((src (if (pair? o) (car o) (current-input-port)))
(o (if (pair? o) (cdr o) '()))
(start-col (if (pair? o) (car o) 0))
(o (if (pair? o) (cdr o) '()))
(max-col (if (pair? o) (car o) *default-max-col*))
(o (if (pair? o) (cdr o) '()))
(sep (if (pair? o) (car o) (string->utf8 "=\r\n"))))
(qp-encode (if (bytevector? src) src (read-bytevector 1000000000 src))
start-col max-col sep)))
(define (quoted-printable-encode . o)
(write-string (apply quoted-printable-encode-string o)))
> responsible for ensuring \var{str } is already encoded according to
(define (quoted-printable-encode-header encoding . o)
(let* ((src (if (pair? o) (car o) (current-input-port)))
(o (if (pair? o) (cdr o) '()))
(start-col (if (pair? o) (car o) 0))
(o (if (pair? o) (cdr o) '()))
(max-col (if (pair? o) (car o) *default-max-col*))
(o (if (pair? o) (cdr o) '()))
(nl (if (pair? o) (car o) "\r\n")))
(let* ((prefix (string-append "=?" encoding "?Q?"))
(prefix-length (+ 2 (string-length prefix)))
(separator (string->utf8 (string-append "?=" nl "\t" prefix)))
(effective-max-col (- max-col prefix-length)))
(bytevector-append
(string->utf8 prefix)
(qp-encode (if (string? src) src (port->string src))
start-col effective-max-col separator)
(string->utf8 "?=")))))
> Return a quoted - printable decoded representation of \var{str } . If
(define (quoted-printable-decode-string src . o)
(if (string? src)
(utf8->string
(apply quoted-printable-decode-bytevector
(string->utf8 src)
o))
(apply quoted-printable-decode-bytevector src o)))
(define (quoted-printable-decode-bytevector . o)
(define (hex? c)
(or (char<=? #\0 (integer->char c) #\9)
(char<=? #\A (integer->char c) #\F)))
(define (unhex1 i)
(if (>= i 65) (- i 55) (- i 48)))
(define (unhex c1 c2)
(+ (arithmetic-shift (unhex1 c1) 4) (unhex1 c2)))
(let ((src (if (pair? o) (car o) (current-input-port)))
(mime-header? (and (pair? o) (pair? (cdr o)) (car (cdr o)))))
(let* ((bv (if (bytevector? src) src (read-bytevector 1000000000 src)))
(end (bytevector-length bv))
(out (open-output-bytevector)))
(let lp ((i 0))
(cond
((>= i end)
(get-output-bytevector out))
(else
(let ((c (bytevector-u8-ref bv i)))
(case c
(cond
((< (+ i 2) end)
(let ((c2 (bytevector-u8-ref bv (+ i 1))))
(cond
((eq? c2 10) (lp (+ i 2)))
((eq? c2 13)
(lp (if (eq? 10 (bytevector-u8-ref bv (+ i 2)))
(+ i 3)
(+ i 2))))
((hex? c2)
(let ((c3 (bytevector-u8-ref bv (+ i 2))))
(if (hex? c3) (write-u8 (unhex c2 c3) out))
(lp (+ i 3))))
(else (lp (+ i 3))))))))
(write-u8 (if mime-header? 32 c) out)
(lp (+ i 1)))
(let lp2 ((j (+ i 1)))
(cond
((not (= j end))
(case (bytevector-u8-ref bv j)
((32 9) (lp2 (+ j 1)))
((10)
(lp (+ j 1)))
((13)
(let ((k (+ j 1)))
(lp (if (and (< k end)
(eq? 10 (bytevector-u8-ref bv k)))
(+ k 1) k))))
(else
(write-bytevector (bytevector-copy bv i j) out)
(lp j)))))))
(write-u8 c out)
(lp (+ i 1)))))))))))
(define (quoted-printable-decode . o)
(write-string (apply quoted-printable-decode-string o)))
|
c01ae1bc64ef2b7e052d0cbf23fba7d77abec355a07142207c634ab434c096b2 | mark-watson/haskell_tutorial_cookbook_examples | Conditionals.hs | module Main where
head' (x:_) = x
tail' (_:xs) = xs
doubleList [] = []
doubleList (x:xs) = (* 2) x : doubleList xs
bumpList n [] = []
bumpList n (x:xs) = n * x : bumpList n xs
map' f [] = []
map' f (x:xs) = (f x) : map' f xs
main = do
print $ head' ["bird","dog","cat"]
print $ tail' [0,1,2,3,4,5]
print $ doubleList [0..5]
print $ bumpList 3 [0..5]
print $ map' (* 7) [0..5]
print $ map' (+ 1.1) [0..5]
print $ map' (\x -> (x + 1) * 2) [0..5]
| null | https://raw.githubusercontent.com/mark-watson/haskell_tutorial_cookbook_examples/0f46465b67d245fa3853b4e320d79b7d7234e061/Pure/Conditionals.hs | haskell | module Main where
head' (x:_) = x
tail' (_:xs) = xs
doubleList [] = []
doubleList (x:xs) = (* 2) x : doubleList xs
bumpList n [] = []
bumpList n (x:xs) = n * x : bumpList n xs
map' f [] = []
map' f (x:xs) = (f x) : map' f xs
main = do
print $ head' ["bird","dog","cat"]
print $ tail' [0,1,2,3,4,5]
print $ doubleList [0..5]
print $ bumpList 3 [0..5]
print $ map' (* 7) [0..5]
print $ map' (+ 1.1) [0..5]
print $ map' (\x -> (x + 1) * 2) [0..5]
|
|
8e047e96efdeb9a00e69e45eba8cf99b76cfba0d97d05c76e55d6ad40c0b33b1 | abooij/haskell-xkbcommon | XkbCommon.hs | module Text.XkbCommon
( module Text.XkbCommon.Types
, module Text.XkbCommon.Context
, module Text.XkbCommon.Keymap
, module Text.XkbCommon.KeyboardState
, module Text.XkbCommon.Keysym
) where
import Text.XkbCommon.Types
import Text.XkbCommon.Context
import Text.XkbCommon.Keymap
import Text.XkbCommon.KeyboardState
import Text.XkbCommon.Keysym
| null | https://raw.githubusercontent.com/abooij/haskell-xkbcommon/a337b4f699fef2621ae028eec9171fcd9ea848c5/Text/XkbCommon.hs | haskell | module Text.XkbCommon
( module Text.XkbCommon.Types
, module Text.XkbCommon.Context
, module Text.XkbCommon.Keymap
, module Text.XkbCommon.KeyboardState
, module Text.XkbCommon.Keysym
) where
import Text.XkbCommon.Types
import Text.XkbCommon.Context
import Text.XkbCommon.Keymap
import Text.XkbCommon.KeyboardState
import Text.XkbCommon.Keysym
|
|
63b1388fb13b78c4e5f49cc47386c55eed32e7388ce044de7f0a578925307199 | basho/riak_search | riak_search_kv_extractor.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2007 - 2010 Basho Technologies , Inc. All Rights Reserved .
%%
%% -------------------------------------------------------------------
-module(riak_search_kv_extractor).
-export([extract/3, clean_name/1]).
-include("riak_search.hrl").
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
Extract search data from the riak_object . Switch between the
built - in extractors based on Content - Type .
extract(RiakObject, DefaultField, Args) ->
try
Contents = riak_object:get_contents(RiakObject),
F = fun({MD,V}, Fields) ->
ContentType = get_content_type(MD),
Extractor = get_extractor(ContentType, encodings()),
[Extractor:extract_value(V, DefaultField, Args) | Fields]
end,
lists:flatten(lists:foldl(F, [], Contents))
catch
_:Err ->
{fail, {cannot_parse,Err}}
end.
%% Get the content type from the metadata
get_content_type(MD) ->
case dict:find(<<"content-type">>, MD) of
error ->
"application/octet-stream";
{ok, CT} ->
CT
end.
%% Get the encoding from the content type
get_extractor(_, []) ->
riak_search_kv_raw_extractor;
get_extractor(CT, [{Encoding, Types} | Rest]) ->
case lists:member(CT, Types) of
true ->
Encoding;
false ->
get_extractor(CT, Rest)
end.
encodings() ->
[{riak_search_kv_xml_extractor, ["application/xml",
"text/xml"]},
{riak_search_kv_json_extractor, ["application/json",
"application/x-javascript",
"text/javascript",
"text/x-javascript",
"text/x-json",
"text/json"]},
{riak_search_kv_erlang_extractor, ["application/x-erlang"]},
{riak_search_kv_erlang_binary_extractor,
["application/x-erlang-binary"]}].
%% Substitute : and . for _
clean_name(Name) ->
clean_name(Name, "").
clean_name([], RevName) ->
lists:reverse(RevName);
clean_name([C | Rest], RevName) when C =:= $.; C =:= $: ->
clean_name(Rest, [$_ | RevName]);
clean_name([C | Rest], RevName) ->
clean_name(Rest, [C | RevName]).
-ifdef(TEST).
extractor_test() ->
JsonData = <<"{\"one\":{\"two\":{\"three\":\"go\"}}}">>,
JsonFields = [{<<"one_two_three">>, <<"go">>}],
XmlData = <<"<?xml version=\"1.0\"?><t1>abc<t2>two</t2>def</t1>">>,
XmlFields = [{<<"t1">>, <<"abc">>},
{<<"t1_t2">>, <<"two">>},
{<<"t1">>, <<"def">>}],
PlainData = <<"the quick brown fox">>,
PlainFields = [{<<"value">>, <<"the quick brown fox">>}],
ErlangData = [{<<"foo">>,<<"bar">>},
{baz, [{<<"quux">>, <<"zoom">>}]}],
ErlangFields = [{<<"foo">>, <<"bar">>},
{<<"baz_quux">>, <<"zoom">>}],
ErlangBinary = term_to_binary(ErlangData),
Tests = [{JsonData, "application/json", JsonFields},
{JsonData, "application/x-javascript", JsonFields},
{JsonData, "text/javascript", JsonFields},
{JsonData, "text/x-javascript", JsonFields},
{JsonData, "text/x-json", JsonFields},
{XmlData, "application/xml", XmlFields},
{XmlData, "text/xml", XmlFields},
{PlainData,"text/plain", PlainFields},
{PlainData, undefined, PlainFields},
{ErlangData, "application/x-erlang", ErlangFields},
{ErlangBinary, "application/x-erlang-binary", ErlangFields}],
check_expected(Tests).
check_expected([]) ->
ok;
check_expected([{Data, CT, Fields}|Rest]) ->
case CT of
undefined ->
Object = riak_object:new(<<"b">>, <<"k">>, Data);
_ ->
Object = riak_object:new(<<"b">>, <<"k">>, Data, CT)
end,
?assertEqual(Fields, extract(Object, <<"value">>,undefined)),
check_expected(Rest).
-endif. % TEST
| null | https://raw.githubusercontent.com/basho/riak_search/79c034350f37706a1db42ffca8f6449d4cce99e1/src/riak_search_kv_extractor.erl | erlang | -------------------------------------------------------------------
-------------------------------------------------------------------
Get the content type from the metadata
Get the encoding from the content type
Substitute : and . for _
TEST | Copyright ( c ) 2007 - 2010 Basho Technologies , Inc. All Rights Reserved .
-module(riak_search_kv_extractor).
-export([extract/3, clean_name/1]).
-include("riak_search.hrl").
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
Extract search data from the riak_object . Switch between the
built - in extractors based on Content - Type .
extract(RiakObject, DefaultField, Args) ->
try
Contents = riak_object:get_contents(RiakObject),
F = fun({MD,V}, Fields) ->
ContentType = get_content_type(MD),
Extractor = get_extractor(ContentType, encodings()),
[Extractor:extract_value(V, DefaultField, Args) | Fields]
end,
lists:flatten(lists:foldl(F, [], Contents))
catch
_:Err ->
{fail, {cannot_parse,Err}}
end.
get_content_type(MD) ->
case dict:find(<<"content-type">>, MD) of
error ->
"application/octet-stream";
{ok, CT} ->
CT
end.
get_extractor(_, []) ->
riak_search_kv_raw_extractor;
get_extractor(CT, [{Encoding, Types} | Rest]) ->
case lists:member(CT, Types) of
true ->
Encoding;
false ->
get_extractor(CT, Rest)
end.
encodings() ->
[{riak_search_kv_xml_extractor, ["application/xml",
"text/xml"]},
{riak_search_kv_json_extractor, ["application/json",
"application/x-javascript",
"text/javascript",
"text/x-javascript",
"text/x-json",
"text/json"]},
{riak_search_kv_erlang_extractor, ["application/x-erlang"]},
{riak_search_kv_erlang_binary_extractor,
["application/x-erlang-binary"]}].
clean_name(Name) ->
clean_name(Name, "").
clean_name([], RevName) ->
lists:reverse(RevName);
clean_name([C | Rest], RevName) when C =:= $.; C =:= $: ->
clean_name(Rest, [$_ | RevName]);
clean_name([C | Rest], RevName) ->
clean_name(Rest, [C | RevName]).
-ifdef(TEST).
extractor_test() ->
JsonData = <<"{\"one\":{\"two\":{\"three\":\"go\"}}}">>,
JsonFields = [{<<"one_two_three">>, <<"go">>}],
XmlData = <<"<?xml version=\"1.0\"?><t1>abc<t2>two</t2>def</t1>">>,
XmlFields = [{<<"t1">>, <<"abc">>},
{<<"t1_t2">>, <<"two">>},
{<<"t1">>, <<"def">>}],
PlainData = <<"the quick brown fox">>,
PlainFields = [{<<"value">>, <<"the quick brown fox">>}],
ErlangData = [{<<"foo">>,<<"bar">>},
{baz, [{<<"quux">>, <<"zoom">>}]}],
ErlangFields = [{<<"foo">>, <<"bar">>},
{<<"baz_quux">>, <<"zoom">>}],
ErlangBinary = term_to_binary(ErlangData),
Tests = [{JsonData, "application/json", JsonFields},
{JsonData, "application/x-javascript", JsonFields},
{JsonData, "text/javascript", JsonFields},
{JsonData, "text/x-javascript", JsonFields},
{JsonData, "text/x-json", JsonFields},
{XmlData, "application/xml", XmlFields},
{XmlData, "text/xml", XmlFields},
{PlainData,"text/plain", PlainFields},
{PlainData, undefined, PlainFields},
{ErlangData, "application/x-erlang", ErlangFields},
{ErlangBinary, "application/x-erlang-binary", ErlangFields}],
check_expected(Tests).
check_expected([]) ->
ok;
check_expected([{Data, CT, Fields}|Rest]) ->
case CT of
undefined ->
Object = riak_object:new(<<"b">>, <<"k">>, Data);
_ ->
Object = riak_object:new(<<"b">>, <<"k">>, Data, CT)
end,
?assertEqual(Fields, extract(Object, <<"value">>,undefined)),
check_expected(Rest).
|
f1c9be9bb8f48cdcbce21c7536026c45db915716094aad29a96b819a9ec99646 | vimus/libmpd-haskell | CurrentPlaylistSpec.hs | {-# LANGUAGE OverloadedStrings #-}
module Network.MPD.Applicative.CurrentPlaylistSpec (main, spec) where
import TestUtil
import Unparse
import Network.MPD.Applicative.CurrentPlaylist
import Network.MPD.Commands.Query
import Network.MPD.Commands.Types
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "addId" $ do
it "adds a song to the playlist (non-recursive) and returns the song id" $ do
addId "dir/Foo-Bar.ogg" Nothing
`with` [("addid \"dir/Foo-Bar.ogg\"", Right "Id: 20\nOK")]
`shouldBe` (Right $ Id 20)
it "takes and optional position" $ do
addId "dir/Foo-Bar.ogg" (Just 5)
`with` [("addid \"dir/Foo-Bar.ogg\" 5", Right "Id: 20\nOK")]
`shouldBe` (Right $ Id 20)
describe "add" $ do
it "adds a url to current playlist" $ do
add "foo"
`with` [("add \"foo\"", Right "OK")]
`shouldBe` Right ()
describe "clear" $ do
it "clears current play list" $ do
clear
`with` [("clear", Right "OK")]
`shouldBe` Right ()
describe "delete" $ do
it "deletes a song from the playlist" $ do
delete (10 :: Int)
`with` [("delete 10", Right "OK")]
`shouldBe` Right ()
describe "deleteRange" $ do
it "deletes a range of songs from the playlist" $ do
deleteRange (Range 10 20)
`with` [("delete 10:20", Right "OK")]
`shouldBe` Right ()
describe "deleteId" $ do
it "deletes song with given id from the playlist" $ do
deleteId (Id 23)
`with` [("deleteid 23", Right "OK")]
`shouldBe` Right ()
describe "move" $ do
it "moves a song to a given position in the playlist" $ do
move 23 42
`with` [("move 23 42", Right "OK")]
`shouldBe` Right ()
describe "moveRange" $ do
it "moves a range of songs to a given position in the playlist" $ do
moveRange (Range 10 20) 23
`with` [("move 10:20 23", Right "OK")]
`shouldBe` Right ()
describe "moveId" $ do
it "move song with given id within the playlist" $ do
moveId (Id 23) 10
`with` [("moveid 23 10", Right "OK")]
`shouldBe` Right ()
XXX : generalize to arbitrary SongS and Query
describe "playlistFind" $ do
it "searches for songs in the current playlist" $ do
let obj = defaultSong "Foo.ogg"
resp = unparse obj
playlistFind (Artist =? "Foo")
`with` [("playlistfind Artist \"Foo\"", Right $ resp ++ "\nOK")]
`shouldBe` Right [obj]
XXX : generalize to arbitrary SongS
describe "playlistInfo" $ do
it "retrieves metadata for all songs in the current playlist" $ do
let obj = defaultSong "Foo.ogg"
resp = unparse obj
playlistInfo Nothing
`with` [("playlistinfo", Right $ resp ++ "\nOK")]
`shouldBe` Right [obj]
it "can optionally return only metadata for a position" $ do
let obj = defaultSong "Foo.ogg"
resp = unparse obj ++ "OK"
playlistInfo (Just 1)
`with` [("playlistinfo 1", Right resp)]
`shouldBe` Right [obj]
describe "playlistInfoRange" $ do
it "is like playlistInfo but can restrict to a range of songs" $ do
let obj = defaultSong "Foo.ogg"
resp = unparse obj ++ "OK"
playlistInfoRange (Just $ Range 0 1)
`with` [("playlistinfo 0:1", Right resp)]
`shouldBe` Right [obj]
XXX : generlize to arbitrary SongS
describe "playlistId" $ do
it "retrieves metadata for all songs in the current playlist" $ do
let obj = defaultSong "Foo.ogg"
resp = unparse obj
playlistId Nothing
`with` [("playlistid", Right $ resp ++ "\nOK")]
`shouldBe` Right [obj]
it "can optionally return info only for a position" $ do
let obj = defaultSong "Foo.ogg"
resp = unparse obj
playlistId (Just $ Id 0)
`with` [("playlistid 0", Right $ resp ++ "\nOK")]
`shouldBe` Right [obj]
describe "playlistSearch" $ do
it "returns songs matching an inexact query" $ do
let obj = defaultSong "Foo.ogg"
resp = unparse obj
playlistSearch (Title =? "Foo")
`with` [("playlistsearch Title \"Foo\"", Right $ resp ++ "\nOK")]
`shouldBe` Right [obj]
describe "plChanges" $ do
it "returns songs that have changed since the given playlist version" $ do
let obj = defaultSong "foo.ogg"
plChanges 1
`with` [("plchanges 1"
, Right (unparse obj ++ "OK"))
]
`shouldBe` Right [obj]
describe "plChangesPosId" $ do
it "is like plChanges but only returns positions and ids" $ do
plChangesPosId 1
`with` [("plchangesposid 1"
, Right "cpos: 0\n\
\Id: 0\n\
\OK")]
`shouldBe` Right [(0, Id 0)]
XXX : does n't work
it " fails on weird input " $ do
plChangesPosId 10
` with ` [ ( " plchangesposid 10 " , Right " cpos : foo\nId : " ) ]
` shouldBe ` Left ( Unexpected " [ ( \"cpos\",\"foo\"),(\"Id\",\"bar\ " ) ] " )
it "fails on weird input" $ do
plChangesPosId 10
`with` [("plchangesposid 10", Right "cpos: foo\nId: bar\nOK")]
`shouldBe` Left (Unexpected "[(\"cpos\",\"foo\"),(\"Id\",\"bar\")]")
-}
describe "shuffle" $ do
it "shuffles the current playlist" $ do
shuffle Nothing
`with` [("shuffle", Right "OK")]
`shouldBe` Right ()
it "optionally shuffles a selection of the playlist" $ do
shuffle (Just $ Range 15 25)
`with` [("shuffle 15:25", Right "OK")]
`shouldBe` Right ()
describe "swap" $ do
it "swaps two playlist positions" $ do
swap 1 2
`with` [("swap 1 2", Right "OK")]
`shouldBe` Right ()
describe "swapId" $ do
it "swaps two playlist ids" $ do
swapId (Id 1) (Id 2)
`with` [("swapid 1 2", Right "OK")]
`shouldBe` Right ()
| null | https://raw.githubusercontent.com/vimus/libmpd-haskell/1ec02deba33ce2a16012d8f0954e648eb4b5c485/tests/Network/MPD/Applicative/CurrentPlaylistSpec.hs | haskell | # LANGUAGE OverloadedStrings # |
module Network.MPD.Applicative.CurrentPlaylistSpec (main, spec) where
import TestUtil
import Unparse
import Network.MPD.Applicative.CurrentPlaylist
import Network.MPD.Commands.Query
import Network.MPD.Commands.Types
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "addId" $ do
it "adds a song to the playlist (non-recursive) and returns the song id" $ do
addId "dir/Foo-Bar.ogg" Nothing
`with` [("addid \"dir/Foo-Bar.ogg\"", Right "Id: 20\nOK")]
`shouldBe` (Right $ Id 20)
it "takes and optional position" $ do
addId "dir/Foo-Bar.ogg" (Just 5)
`with` [("addid \"dir/Foo-Bar.ogg\" 5", Right "Id: 20\nOK")]
`shouldBe` (Right $ Id 20)
describe "add" $ do
it "adds a url to current playlist" $ do
add "foo"
`with` [("add \"foo\"", Right "OK")]
`shouldBe` Right ()
describe "clear" $ do
it "clears current play list" $ do
clear
`with` [("clear", Right "OK")]
`shouldBe` Right ()
describe "delete" $ do
it "deletes a song from the playlist" $ do
delete (10 :: Int)
`with` [("delete 10", Right "OK")]
`shouldBe` Right ()
describe "deleteRange" $ do
it "deletes a range of songs from the playlist" $ do
deleteRange (Range 10 20)
`with` [("delete 10:20", Right "OK")]
`shouldBe` Right ()
describe "deleteId" $ do
it "deletes song with given id from the playlist" $ do
deleteId (Id 23)
`with` [("deleteid 23", Right "OK")]
`shouldBe` Right ()
describe "move" $ do
it "moves a song to a given position in the playlist" $ do
move 23 42
`with` [("move 23 42", Right "OK")]
`shouldBe` Right ()
describe "moveRange" $ do
it "moves a range of songs to a given position in the playlist" $ do
moveRange (Range 10 20) 23
`with` [("move 10:20 23", Right "OK")]
`shouldBe` Right ()
describe "moveId" $ do
it "move song with given id within the playlist" $ do
moveId (Id 23) 10
`with` [("moveid 23 10", Right "OK")]
`shouldBe` Right ()
XXX : generalize to arbitrary SongS and Query
describe "playlistFind" $ do
it "searches for songs in the current playlist" $ do
let obj = defaultSong "Foo.ogg"
resp = unparse obj
playlistFind (Artist =? "Foo")
`with` [("playlistfind Artist \"Foo\"", Right $ resp ++ "\nOK")]
`shouldBe` Right [obj]
XXX : generalize to arbitrary SongS
describe "playlistInfo" $ do
it "retrieves metadata for all songs in the current playlist" $ do
let obj = defaultSong "Foo.ogg"
resp = unparse obj
playlistInfo Nothing
`with` [("playlistinfo", Right $ resp ++ "\nOK")]
`shouldBe` Right [obj]
it "can optionally return only metadata for a position" $ do
let obj = defaultSong "Foo.ogg"
resp = unparse obj ++ "OK"
playlistInfo (Just 1)
`with` [("playlistinfo 1", Right resp)]
`shouldBe` Right [obj]
describe "playlistInfoRange" $ do
it "is like playlistInfo but can restrict to a range of songs" $ do
let obj = defaultSong "Foo.ogg"
resp = unparse obj ++ "OK"
playlistInfoRange (Just $ Range 0 1)
`with` [("playlistinfo 0:1", Right resp)]
`shouldBe` Right [obj]
XXX : generlize to arbitrary SongS
describe "playlistId" $ do
it "retrieves metadata for all songs in the current playlist" $ do
let obj = defaultSong "Foo.ogg"
resp = unparse obj
playlistId Nothing
`with` [("playlistid", Right $ resp ++ "\nOK")]
`shouldBe` Right [obj]
it "can optionally return info only for a position" $ do
let obj = defaultSong "Foo.ogg"
resp = unparse obj
playlistId (Just $ Id 0)
`with` [("playlistid 0", Right $ resp ++ "\nOK")]
`shouldBe` Right [obj]
describe "playlistSearch" $ do
it "returns songs matching an inexact query" $ do
let obj = defaultSong "Foo.ogg"
resp = unparse obj
playlistSearch (Title =? "Foo")
`with` [("playlistsearch Title \"Foo\"", Right $ resp ++ "\nOK")]
`shouldBe` Right [obj]
describe "plChanges" $ do
it "returns songs that have changed since the given playlist version" $ do
let obj = defaultSong "foo.ogg"
plChanges 1
`with` [("plchanges 1"
, Right (unparse obj ++ "OK"))
]
`shouldBe` Right [obj]
describe "plChangesPosId" $ do
it "is like plChanges but only returns positions and ids" $ do
plChangesPosId 1
`with` [("plchangesposid 1"
, Right "cpos: 0\n\
\Id: 0\n\
\OK")]
`shouldBe` Right [(0, Id 0)]
XXX : does n't work
it " fails on weird input " $ do
plChangesPosId 10
` with ` [ ( " plchangesposid 10 " , Right " cpos : foo\nId : " ) ]
` shouldBe ` Left ( Unexpected " [ ( \"cpos\",\"foo\"),(\"Id\",\"bar\ " ) ] " )
it "fails on weird input" $ do
plChangesPosId 10
`with` [("plchangesposid 10", Right "cpos: foo\nId: bar\nOK")]
`shouldBe` Left (Unexpected "[(\"cpos\",\"foo\"),(\"Id\",\"bar\")]")
-}
describe "shuffle" $ do
it "shuffles the current playlist" $ do
shuffle Nothing
`with` [("shuffle", Right "OK")]
`shouldBe` Right ()
it "optionally shuffles a selection of the playlist" $ do
shuffle (Just $ Range 15 25)
`with` [("shuffle 15:25", Right "OK")]
`shouldBe` Right ()
describe "swap" $ do
it "swaps two playlist positions" $ do
swap 1 2
`with` [("swap 1 2", Right "OK")]
`shouldBe` Right ()
describe "swapId" $ do
it "swaps two playlist ids" $ do
swapId (Id 1) (Id 2)
`with` [("swapid 1 2", Right "OK")]
`shouldBe` Right ()
|
89206ff6dbdc4f0130e6b182b01f63ebc6708f41681a3b982e515112af34faf5 | palletops/lein-uberimage | project.clj | (defproject com.palletops/uberimage "0.4.2-SNAPSHOT"
:description "Leiningen plugin to create a docker image for a project uberjar"
:url "-uberimage"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:eval-in-leiningen true
:min-lein-version "2.4.3"
:dependencies [[com.palletops/clj-docker "0.2.0"]
[org.clojure/tools.cli "0.3.1"]
[net.oauth.core/oauth "20100527"]
[clj-time "0.8.0"]]
:global-vars {*warn-on-reflection* true})
| null | https://raw.githubusercontent.com/palletops/lein-uberimage/7a996749fc7b3d53ab625c3ce413f8c76ad08600/project.clj | clojure | (defproject com.palletops/uberimage "0.4.2-SNAPSHOT"
:description "Leiningen plugin to create a docker image for a project uberjar"
:url "-uberimage"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:eval-in-leiningen true
:min-lein-version "2.4.3"
:dependencies [[com.palletops/clj-docker "0.2.0"]
[org.clojure/tools.cli "0.3.1"]
[net.oauth.core/oauth "20100527"]
[clj-time "0.8.0"]]
:global-vars {*warn-on-reflection* true})
|
|
0379f4b580edb06cb218007f7f924038404a34f332f1bf44780a536f3522d57d | gwkkwg/cl-containers | eksl-priority-queue.lisp | (in-package #:containers)
Heap based queue using EKSL priority - queue
;;?? Needs a better name
#+EKSL-PRIORITY-QUEUE
(progn
(defclass* priority-queue-heap (abstract-queue concrete-container
iteratable-container-mixin)
((contents :initform nil
:initarg :contents
:accessor contents)))
(defmethod make-container ((class (eql 'priority-queue-heap)) &rest args)
(make-instance 'priority-queue-heap
:contents (apply #'make-sorted-queue args)))
(defun make-sorted-queue (&key (not-lessp-predicate #'<)
(key #'identity)
(initial-length 42))
(u:make-priority-queue
not-lessp-predicate
:key key
:size initial-length))
(defmethod insert-item ((container priority-queue-heap) item)
(u:priority-queue-insert item (contents container)))
(defmethod find-item ((container priority-queue-heap) item)
(u:priority-queue-find item (contents container)))
(defmethod search-for-item ((container priority-queue-heap) item &key test key)
(u:priority-queue-find item (contents container) :key key :test test))
(defmethod delete-item ((container priority-queue-heap) item)
(u:priority-queue-delete item (contents container)))
(defmethod delete-first ((container priority-queue-heap))
(u:priority-queue-pop (contents container)))
;; Should not be called on an empty queue... results might be undefined.
(defmethod first-item ((container priority-queue-heap))
(u:priority-queue-head (contents container)))
(defmethod empty-p ((container priority-queue-heap))
(u:priority-queue-empty-p (contents container)))
(defmethod empty! ((container priority-queue-heap))
(u:priority-queue-empty (contents container))
(values))
(defmethod iterate-nodes ((container priority-queue-heap) fn)
(u:priority-queue-map-in-priority-order
(lambda (element index)
(declare (ignore index))
(funcall fn element))
(contents container)))
(defmethod size ((container priority-queue-heap))
(u:priority-queue-length (contents container)))
(u:defcopy-methods priority-queue-heap :copy-all t)
(u:make-load-form* priority-queue-heap))
| null | https://raw.githubusercontent.com/gwkkwg/cl-containers/3d1df53c22403121bffb5d553cf7acb1503850e7/dev/eksl-priority-queue.lisp | lisp | ?? Needs a better name
Should not be called on an empty queue... results might be undefined. | (in-package #:containers)
Heap based queue using EKSL priority - queue
#+EKSL-PRIORITY-QUEUE
(progn
(defclass* priority-queue-heap (abstract-queue concrete-container
iteratable-container-mixin)
((contents :initform nil
:initarg :contents
:accessor contents)))
(defmethod make-container ((class (eql 'priority-queue-heap)) &rest args)
(make-instance 'priority-queue-heap
:contents (apply #'make-sorted-queue args)))
(defun make-sorted-queue (&key (not-lessp-predicate #'<)
(key #'identity)
(initial-length 42))
(u:make-priority-queue
not-lessp-predicate
:key key
:size initial-length))
(defmethod insert-item ((container priority-queue-heap) item)
(u:priority-queue-insert item (contents container)))
(defmethod find-item ((container priority-queue-heap) item)
(u:priority-queue-find item (contents container)))
(defmethod search-for-item ((container priority-queue-heap) item &key test key)
(u:priority-queue-find item (contents container) :key key :test test))
(defmethod delete-item ((container priority-queue-heap) item)
(u:priority-queue-delete item (contents container)))
(defmethod delete-first ((container priority-queue-heap))
(u:priority-queue-pop (contents container)))
(defmethod first-item ((container priority-queue-heap))
(u:priority-queue-head (contents container)))
(defmethod empty-p ((container priority-queue-heap))
(u:priority-queue-empty-p (contents container)))
(defmethod empty! ((container priority-queue-heap))
(u:priority-queue-empty (contents container))
(values))
(defmethod iterate-nodes ((container priority-queue-heap) fn)
(u:priority-queue-map-in-priority-order
(lambda (element index)
(declare (ignore index))
(funcall fn element))
(contents container)))
(defmethod size ((container priority-queue-heap))
(u:priority-queue-length (contents container)))
(u:defcopy-methods priority-queue-heap :copy-all t)
(u:make-load-form* priority-queue-heap))
|
d499ad6c7cebae402909161cdfd7e2c97b28c0556031c008b71f2520f6acca8b | kazu-yamamoto/domain-auth | Verify.hs | {-# LANGUAGE OverloadedStrings #-}
module Network.DomainAuth.DKIM.Verify (
verifyDKIM, prepareDKIM
) where
import Crypto.Hash
import Crypto.PubKey.RSA
import Crypto.PubKey.RSA.PKCS15
import Data.ByteArray
import Data.ByteString (ByteString)
import Data.ByteString.Builder (Builder)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Builder as BB
import qualified Data.ByteString.Lazy as BL
import Network.DomainAuth.DKIM.Btag
import Network.DomainAuth.DKIM.Types
import Network.DomainAuth.Mail
import qualified Network.DomainAuth.Pubkey.Base64 as B
import Network.DomainAuth.Utils
----------------------------------------------------------------
prepareDKIM :: DKIM -> Mail -> Builder
prepareDKIM dkim mail = header
where
dkimField:fields = fieldsFrom dkimFieldKey (mailHeader mail)
hCanon = canonDkimField (dkimHeaderCanon dkim)
canon = BB.byteString . removeBtagValue . hCanon
targets = fieldsWith (dkimFields dkim) fields
header = concatCRLFWith hCanon targets +++ canon dkimField
----------------------------------------------------------------
canonDkimField :: DkimCanonAlgo -> Field -> ByteString
canonDkimField DKIM_SIMPLE fld = fieldKey fld +++ ": " +++ fieldValueFolded fld
canonDkimField DKIM_RELAXED fld = fieldSearchKey fld +++ ":" +++ canon fld
where
canon = BS.dropWhile isSpace . removeTrailingWSP . reduceWSP . BS.concat . fieldValue
----------------------------------------------------------------
canonDkimBody :: DkimCanonAlgo -> Body -> Builder
canonDkimBody DKIM_SIMPLE = fromBody . removeTrailingEmptyLine
canonDkimBody DKIM_RELAXED = fromBodyWith relax . removeTrailingEmptyLine
where
relax = removeTrailingWSP . reduceWSP
----------------------------------------------------------------
verifyDKIM :: Mail -> DKIM -> PublicKey -> Bool
verifyDKIM mail dkim pub = bodyHash1 mail == bodyHash2 dkim &&
verify' (dkimSigAlgo dkim) pub cmail sig
where
sig = B.decode . dkimSignature $ dkim
cmail = BL.toStrict $ BB.toLazyByteString $ prepareDKIM dkim mail
bodyHash1 = hashAlgo2 (dkimSigAlgo dkim) . BL.toStrict . BB.toLazyByteString . canonDkimBody (dkimBodyCanon dkim) . mailBody
bodyHash2 = B.decode . dkimBodyHash
verify' :: DkimSigAlgo-> PublicKey -> ByteString -> ByteString -> Bool
verify' RSA_SHA1 = verify (Just SHA1)
verify' RSA_SHA256 = verify (Just SHA256)
hashAlgo2 :: ByteArray c => DkimSigAlgo -> ByteString -> c
hashAlgo2 RSA_SHA1 = convert . (hash :: ByteString -> Digest SHA1)
hashAlgo2 RSA_SHA256 = convert . (hash :: ByteString -> Digest SHA256)
| null | https://raw.githubusercontent.com/kazu-yamamoto/domain-auth/d13145709a558145ac38e28e0b339c48b950b4e0/Network/DomainAuth/DKIM/Verify.hs | haskell | # LANGUAGE OverloadedStrings #
--------------------------------------------------------------
--------------------------------------------------------------
--------------------------------------------------------------
-------------------------------------------------------------- |
module Network.DomainAuth.DKIM.Verify (
verifyDKIM, prepareDKIM
) where
import Crypto.Hash
import Crypto.PubKey.RSA
import Crypto.PubKey.RSA.PKCS15
import Data.ByteArray
import Data.ByteString (ByteString)
import Data.ByteString.Builder (Builder)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Builder as BB
import qualified Data.ByteString.Lazy as BL
import Network.DomainAuth.DKIM.Btag
import Network.DomainAuth.DKIM.Types
import Network.DomainAuth.Mail
import qualified Network.DomainAuth.Pubkey.Base64 as B
import Network.DomainAuth.Utils
prepareDKIM :: DKIM -> Mail -> Builder
prepareDKIM dkim mail = header
where
dkimField:fields = fieldsFrom dkimFieldKey (mailHeader mail)
hCanon = canonDkimField (dkimHeaderCanon dkim)
canon = BB.byteString . removeBtagValue . hCanon
targets = fieldsWith (dkimFields dkim) fields
header = concatCRLFWith hCanon targets +++ canon dkimField
canonDkimField :: DkimCanonAlgo -> Field -> ByteString
canonDkimField DKIM_SIMPLE fld = fieldKey fld +++ ": " +++ fieldValueFolded fld
canonDkimField DKIM_RELAXED fld = fieldSearchKey fld +++ ":" +++ canon fld
where
canon = BS.dropWhile isSpace . removeTrailingWSP . reduceWSP . BS.concat . fieldValue
canonDkimBody :: DkimCanonAlgo -> Body -> Builder
canonDkimBody DKIM_SIMPLE = fromBody . removeTrailingEmptyLine
canonDkimBody DKIM_RELAXED = fromBodyWith relax . removeTrailingEmptyLine
where
relax = removeTrailingWSP . reduceWSP
verifyDKIM :: Mail -> DKIM -> PublicKey -> Bool
verifyDKIM mail dkim pub = bodyHash1 mail == bodyHash2 dkim &&
verify' (dkimSigAlgo dkim) pub cmail sig
where
sig = B.decode . dkimSignature $ dkim
cmail = BL.toStrict $ BB.toLazyByteString $ prepareDKIM dkim mail
bodyHash1 = hashAlgo2 (dkimSigAlgo dkim) . BL.toStrict . BB.toLazyByteString . canonDkimBody (dkimBodyCanon dkim) . mailBody
bodyHash2 = B.decode . dkimBodyHash
verify' :: DkimSigAlgo-> PublicKey -> ByteString -> ByteString -> Bool
verify' RSA_SHA1 = verify (Just SHA1)
verify' RSA_SHA256 = verify (Just SHA256)
hashAlgo2 :: ByteArray c => DkimSigAlgo -> ByteString -> c
hashAlgo2 RSA_SHA1 = convert . (hash :: ByteString -> Digest SHA1)
hashAlgo2 RSA_SHA256 = convert . (hash :: ByteString -> Digest SHA256)
|
85b6293f0fb2dff1464092184edb139d12f53b35b48ae5dc64deeee77a71f776 | andreas/ppx_graphql | ppx_graphql.ml | open Migrate_parsetree
open Ast_403
module StringMap = Map.Make(String)
type ctx = {
fragments : Graphql_parser.fragment StringMap.t;
types : Introspection.typ list;
}
let loc = !Ast_helper.default_loc
let lid s : Ast_helper.lid =
{ txt = Longident.Lident s; loc = !Ast_helper.default_loc }
let str txt : Ast_helper.str = { txt; loc = !Ast_helper.default_loc }
let const_string s =
Ast_helper.Exp.constant (Pconst_string (s, None))
let failwithf format =
Format.ksprintf failwith format
let rec exprs_to_list = function
| [] ->
Ast_helper.Exp.construct (lid "[]") None
| expr::exprs ->
Ast_helper.Exp.(construct (lid "::") (Some (tuple [expr; exprs_to_list exprs])))
let typename_field : Introspection.field =
{
name = "__typename";
args = [];
typ = NonNull(Type("String"));
}
let select_field typ field_name =
if field_name = "__typename" then
typename_field
else
let find_field type_name fields =
try
List.find (fun (field : Introspection.field) -> field.name = field_name) fields
with Not_found ->
failwithf "Invalid field `%s` for type `%s`" field_name type_name
in
match typ with
| Introspection.Object o ->
find_field o.name o.fields
| Introspection.Interface i ->
find_field i.name i.fields
| Introspection.Union u ->
failwith "Cannot select field from union"
| Introspection.Enum _ ->
failwith "Cannot select field from enum"
| Introspection.Scalar _ ->
failwith "Cannot select field from scalar"
| Introspection.InputObject _ ->
failwith "Cannot select field from input object"
let match_type_name type_name typ =
match typ with
| Introspection.Object o -> o.name = type_name
| Introspection.Union u -> u.name = type_name
| Introspection.Interface i -> i.name = type_name
| Introspection.Enum e -> e.name = type_name
| Introspection.Scalar s -> s.name = type_name
| Introspection.InputObject io -> io.name = type_name
let rec collect_fields ctx type_name fields =
List.map (function
| Graphql_parser.Field field ->
[field]
| Graphql_parser.FragmentSpread spread ->
begin try
let fragment = StringMap.find spread.name ctx.fragments in
if fragment.type_condition = type_name then
collect_fields ctx type_name fragment.selection_set
else
[]
with Not_found ->
failwithf "Invalid fragment `%s`" spread.name
end
| Graphql_parser.InlineFragment fragment ->
match fragment.type_condition with
| None ->
collect_fields ctx type_name fragment.selection_set
| Some condition when condition = type_name ->
collect_fields ctx type_name fragment.selection_set
| _ -> []
) fields
|> List.concat
let alias_or_name : Graphql_parser.field -> string = fun field ->
match field.alias with
| Some alias -> alias
| None -> field.name
let convert_scalar : string -> Parsetree.expression =
function
| "Int" -> [%expr to_int_option]
| "Boolean" -> [%expr to_bool_option]
| "URI"
| "String" -> [%expr to_string_option]
| "Float" -> [%expr to_float_option]
| "ID" -> [%expr function
| `Null -> None
| `String s -> Some s
| `Int n -> Some (string_of_int n)
| json -> raise (Yojson.Basic.Util.Type_error ("Invalid type for ID", json))
]
| typ -> failwithf "Unknown scalar type `%s`" typ
let convert_enum enum_values =
let default_case = Ast_helper.(Exp.case Pat.(any ()) [%expr failwith "Invalid enum value"]) in
let cases = List.fold_left (fun memo (value : Introspection.enum_value) ->
let pattern = Ast_helper.Pat.constant (Pconst_string (value.name, None)) in
let expr = Ast_helper.Exp.variant value.name None in
(Ast_helper.Exp.case pattern expr)::memo
) [default_case] enum_values in
Ast_helper.Exp.function_ cases
let parse_json_method method_name expr =
let val_ = Ast_helper.Cf.(val_ (str method_name) Asttypes.Immutable (concrete Asttypes.Fresh expr)) in
let method_ = Ast_helper.(Cf.method_ (str method_name) Asttypes.Public (Cf.concrete Asttypes.Fresh (Exp.ident (lid method_name)))) in
[val_; method_]
let rec resolve_type_ref : ctx -> Introspection.typ -> Graphql_parser.field -> Introspection.type_ref -> Parsetree.expression =
fun ctx obj query_field type_ref ->
match type_ref with
| Introspection.Type type_name ->
begin match List.find (match_type_name type_name) ctx.types with
| Introspection.Scalar s ->
let convert_expr = convert_scalar s.name in
[%expr json |> [%e convert_expr]]
| Introspection.Enum e ->
let convert_expr = convert_enum e.enum_values in
[%expr json |> to_option (fun json -> json |> to_string |> [%e convert_expr])]
| Introspection.Object o as obj ->
let fields = collect_fields ctx o.name query_field.selection_set in
let methods = resolve_fields ctx obj fields in
let convert_expr = Ast_helper.(Exp.object_ (Cstr.mk (Pat.any ()) methods)) in
[%expr json |> to_option (fun json -> [%e convert_expr])]
| Introspection.Union u ->
convert_union ctx query_field u.possible_types
| Introspection.Interface _ ->
failwithf "Interface not supported yet"
| Introspection.InputObject _ ->
failwithf "Input object `%s` cannot be used in selection set" type_name
| exception Not_found ->
failwithf "Unknown type `%s`" type_name
end
| Introspection.NonNull t ->
let expr = resolve_type_ref ctx obj query_field t in
[%expr match [%e expr] with None -> failwith "NonNull field was null" | Some v -> v]
| Introspection.List t ->
let expr = resolve_type_ref ctx obj query_field t in
[%expr json |> to_option (convert_each (fun json -> [%e expr]))]
and resolve_field : ctx -> Introspection.typ -> Graphql_parser.field -> Parsetree.class_field list =
fun ctx typ query_field ->
let field = select_field typ query_field.name in
let alias = alias_or_name query_field in
let parse_expr = resolve_type_ref ctx typ query_field field.typ in
parse_json_method alias [%expr let json = member [%e const_string alias] json in [%e parse_expr]]
and resolve_fields ctx obj fields : Parsetree.class_field list =
List.map (resolve_field ctx obj) fields
|> List.concat
and convert_union ctx query_field possible_types =
let branches = List.map (fun type_name ->
let obj = List.find (match_type_name type_name) ctx.types in
let fields = collect_fields ctx type_name query_field.Graphql_parser.selection_set in
let methods = resolve_fields ctx obj fields in
let convert_expr = Ast_helper.(Exp.object_ (Cstr.mk (Pat.any ()) methods)) in
type_name, convert_expr
) possible_types in
let default_case = Ast_helper.(Exp.case Pat.(any ()) [%expr failwith "Unknown __typename for union"]) in
let cases = List.fold_left (fun memo (type_name, convert_expr) ->
let pattern = Ast_helper.Pat.constant (Pconst_string (type_name, None)) in
let variant_expr = Ast_helper.Exp.variant type_name (Some convert_expr) in
let expr : Parsetree.expression = [%expr json |> to_option (fun json -> [%e variant_expr])] in
(Ast_helper.Exp.case pattern expr)::memo
) [default_case] branches in
Ast_helper.Exp.match_ [%expr member "__typename" json |> to_string] cases
let generate_parse_fn : Introspection.schema -> Graphql_parser.document -> Parsetree.expression =
fun schema [Graphql_parser.Operation op] ->
let typ = List.find (match_type_name schema.query_type) schema.types in
let ctx = { fragments = StringMap.empty; types = schema.types } in
let fields = collect_fields ctx schema.query_type op.selection_set in
let methods = resolve_fields ctx typ fields in
[%expr fun json ->
let open Yojson.Basic.Util in
let json = member "data" json in
[%e Ast_helper.(Exp.object_ (Cstr.mk (Pat.any ()) methods))]
]
let accept_none : Parsetree.expression -> (Parsetree.expression -> Parsetree.expression) -> Parsetree.expression =
fun value expr_fn ->
[%expr match [%e value] with
| None -> `Null
| Some x -> [%e expr_fn [%expr x]]
]
let scalar_to_yojson name value : Parsetree.expression =
match name with
| "Int" -> [%expr `Int [%e value]]
| "Boolean" -> [%expr `Bool [%e value]]
| "ID"
| "String" -> [%expr `String [%e value]]
| "Float" -> [%expr `Float [%e value]]
| typ -> failwithf "Unknown scalar type `%s`" typ
let enum_to_yojson enum_values value : Parsetree.expression =
let cases = List.map (fun (value : Introspection.enum_value) ->
let pattern = Ast_helper.Pat.variant value.name None in
let expr : Parsetree.expression = [%expr `String [%e const_string value.name]] in
Ast_helper.Exp.case pattern expr
) enum_values
in
Ast_helper.Exp.match_ value cases
let rec schema_typ_to_yojson ?(nullable=true) types typ value =
let handle_none = if nullable then accept_none value else (fun expr_fn -> expr_fn value) in
match typ with
| Introspection.Type type_name ->
handle_none begin match List.find (match_type_name type_name) types with
| Introspection.Scalar s ->
scalar_to_yojson s.name
| Introspection.Enum e ->
enum_to_yojson e.enum_values
| Introspection.InputObject o ->
failwith "Input objects are not supported yet"
| Introspection.Object _
| Introspection.Interface _
| Introspection.Union _ ->
failwithf "Invalid argument type `%s` (must be scalar, enum or input object)" type_name
| exception Not_found ->
failwithf "Unknown argument type `%s`" type_name
end
| Introspection.List typ' ->
let expr = schema_typ_to_yojson types typ' [%expr x] in
handle_none (fun value' -> [%expr `List (List.map (fun x -> [%e expr]) [%e value'])])
| Introspection.NonNull typ' ->
schema_typ_to_yojson ~nullable:false types typ' value
let rec input_typ_to_introspection_typ = function
| Graphql_parser.NamedType type_name ->
Introspection.Type type_name
| Graphql_parser.ListType typ' ->
Introspection.List (input_typ_to_introspection_typ typ')
| Graphql_parser.NonNullType typ' ->
Introspection.NonNull (input_typ_to_introspection_typ typ')
let generate_variable_fn : Introspection.schema -> Graphql_parser.document -> Parsetree.expression =
fun schema [Graphql_parser.Operation op] ->
let properties = List.fold_right (fun (arg : Graphql_parser.variable_definition) memo ->
let txt = Longident.Lident arg.name in
let var = Ast_helper.Exp.ident {txt; loc} in
let introspection_typ = input_typ_to_introspection_typ arg.typ in
let expr : Parsetree.expression = [%expr [%e schema_typ_to_yojson schema.types introspection_typ var]] in
let prop : Parsetree.expression = [%expr ([%e const_string arg.name], [%e expr])] in
prop::memo
) op.variable_definitions [] in
let prop_expr_list = exprs_to_list properties in
let fn_with_cont : Parsetree.expression = [%expr fun () -> k ((`Assoc [%e prop_expr_list]) : Yojson.Basic.json)] in
let fn_with_args = List.fold_right (fun (arg : Graphql_parser.variable_definition) memo ->
let label = match arg.typ with
| NonNullType _ ->
Asttypes.Labelled arg.name
| NamedType _
| ListType _ ->
Asttypes.Optional arg.name
in
Ast_helper.(Exp.fun_ label None (Pat.var {txt=arg.name; loc}) memo)
) op.variable_definitions fn_with_cont
in [%expr fun k -> [%e fn_with_args]]
let generate (loc : Location.t) query =
let schema_path = (Location.absolute_path loc.loc_start.pos_fname |> Filename.dirname) ^ "/schema.json" in
let schema = Introspection.of_file schema_path in
match Graphql_parser.parse query with
| Error err ->
let msg = Format.sprintf "Invalid GraphQL query: %s" err in
raise (Location.Error (Location.error ~loc msg))
| Ok doc ->
try
Ast_helper.with_default_loc loc (fun () ->
let variable_fn = generate_variable_fn schema doc in
let parse_fn = generate_parse_fn schema doc in
query, variable_fn, parse_fn
)
with Failure msg -> raise (Location.Error (Location.error ~loc msg))
let mapper _config _cookies =
let default_mapper = Ast_mapper.default_mapper in
{ default_mapper with
expr = fun mapper expr ->
match expr with
| { pexp_desc = Pexp_extension ({ txt = "graphql"; loc}, pstr)} ->
begin match pstr with
| PStr [{ pstr_desc =
Pstr_eval ({ pexp_loc = loc;
pexp_desc = Pexp_constant (Pconst_string (query, _))}, _)}] ->
let query, variable_fn, parse_fn = generate loc query in
Ast_helper.Exp.tuple [const_string query; variable_fn; parse_fn]
| _ ->
raise (Location.Error (
Location.error ~loc "[%graphql] accepts a string, e.g. [%graphql \"query { id }\"]"))
end
| other -> default_mapper.expr mapper other
}
let () =
Driver.register ~name:"ppx_graphql"
Versions.ocaml_403
mapper
| null | https://raw.githubusercontent.com/andreas/ppx_graphql/2d185501ce812a241ce3a8bb42b3a531a3366eee/src/ppx_graphql.ml | ocaml | open Migrate_parsetree
open Ast_403
module StringMap = Map.Make(String)
type ctx = {
fragments : Graphql_parser.fragment StringMap.t;
types : Introspection.typ list;
}
let loc = !Ast_helper.default_loc
let lid s : Ast_helper.lid =
{ txt = Longident.Lident s; loc = !Ast_helper.default_loc }
let str txt : Ast_helper.str = { txt; loc = !Ast_helper.default_loc }
let const_string s =
Ast_helper.Exp.constant (Pconst_string (s, None))
let failwithf format =
Format.ksprintf failwith format
let rec exprs_to_list = function
| [] ->
Ast_helper.Exp.construct (lid "[]") None
| expr::exprs ->
Ast_helper.Exp.(construct (lid "::") (Some (tuple [expr; exprs_to_list exprs])))
let typename_field : Introspection.field =
{
name = "__typename";
args = [];
typ = NonNull(Type("String"));
}
let select_field typ field_name =
if field_name = "__typename" then
typename_field
else
let find_field type_name fields =
try
List.find (fun (field : Introspection.field) -> field.name = field_name) fields
with Not_found ->
failwithf "Invalid field `%s` for type `%s`" field_name type_name
in
match typ with
| Introspection.Object o ->
find_field o.name o.fields
| Introspection.Interface i ->
find_field i.name i.fields
| Introspection.Union u ->
failwith "Cannot select field from union"
| Introspection.Enum _ ->
failwith "Cannot select field from enum"
| Introspection.Scalar _ ->
failwith "Cannot select field from scalar"
| Introspection.InputObject _ ->
failwith "Cannot select field from input object"
let match_type_name type_name typ =
match typ with
| Introspection.Object o -> o.name = type_name
| Introspection.Union u -> u.name = type_name
| Introspection.Interface i -> i.name = type_name
| Introspection.Enum e -> e.name = type_name
| Introspection.Scalar s -> s.name = type_name
| Introspection.InputObject io -> io.name = type_name
let rec collect_fields ctx type_name fields =
List.map (function
| Graphql_parser.Field field ->
[field]
| Graphql_parser.FragmentSpread spread ->
begin try
let fragment = StringMap.find spread.name ctx.fragments in
if fragment.type_condition = type_name then
collect_fields ctx type_name fragment.selection_set
else
[]
with Not_found ->
failwithf "Invalid fragment `%s`" spread.name
end
| Graphql_parser.InlineFragment fragment ->
match fragment.type_condition with
| None ->
collect_fields ctx type_name fragment.selection_set
| Some condition when condition = type_name ->
collect_fields ctx type_name fragment.selection_set
| _ -> []
) fields
|> List.concat
let alias_or_name : Graphql_parser.field -> string = fun field ->
match field.alias with
| Some alias -> alias
| None -> field.name
let convert_scalar : string -> Parsetree.expression =
function
| "Int" -> [%expr to_int_option]
| "Boolean" -> [%expr to_bool_option]
| "URI"
| "String" -> [%expr to_string_option]
| "Float" -> [%expr to_float_option]
| "ID" -> [%expr function
| `Null -> None
| `String s -> Some s
| `Int n -> Some (string_of_int n)
| json -> raise (Yojson.Basic.Util.Type_error ("Invalid type for ID", json))
]
| typ -> failwithf "Unknown scalar type `%s`" typ
let convert_enum enum_values =
let default_case = Ast_helper.(Exp.case Pat.(any ()) [%expr failwith "Invalid enum value"]) in
let cases = List.fold_left (fun memo (value : Introspection.enum_value) ->
let pattern = Ast_helper.Pat.constant (Pconst_string (value.name, None)) in
let expr = Ast_helper.Exp.variant value.name None in
(Ast_helper.Exp.case pattern expr)::memo
) [default_case] enum_values in
Ast_helper.Exp.function_ cases
let parse_json_method method_name expr =
let val_ = Ast_helper.Cf.(val_ (str method_name) Asttypes.Immutable (concrete Asttypes.Fresh expr)) in
let method_ = Ast_helper.(Cf.method_ (str method_name) Asttypes.Public (Cf.concrete Asttypes.Fresh (Exp.ident (lid method_name)))) in
[val_; method_]
let rec resolve_type_ref : ctx -> Introspection.typ -> Graphql_parser.field -> Introspection.type_ref -> Parsetree.expression =
fun ctx obj query_field type_ref ->
match type_ref with
| Introspection.Type type_name ->
begin match List.find (match_type_name type_name) ctx.types with
| Introspection.Scalar s ->
let convert_expr = convert_scalar s.name in
[%expr json |> [%e convert_expr]]
| Introspection.Enum e ->
let convert_expr = convert_enum e.enum_values in
[%expr json |> to_option (fun json -> json |> to_string |> [%e convert_expr])]
| Introspection.Object o as obj ->
let fields = collect_fields ctx o.name query_field.selection_set in
let methods = resolve_fields ctx obj fields in
let convert_expr = Ast_helper.(Exp.object_ (Cstr.mk (Pat.any ()) methods)) in
[%expr json |> to_option (fun json -> [%e convert_expr])]
| Introspection.Union u ->
convert_union ctx query_field u.possible_types
| Introspection.Interface _ ->
failwithf "Interface not supported yet"
| Introspection.InputObject _ ->
failwithf "Input object `%s` cannot be used in selection set" type_name
| exception Not_found ->
failwithf "Unknown type `%s`" type_name
end
| Introspection.NonNull t ->
let expr = resolve_type_ref ctx obj query_field t in
[%expr match [%e expr] with None -> failwith "NonNull field was null" | Some v -> v]
| Introspection.List t ->
let expr = resolve_type_ref ctx obj query_field t in
[%expr json |> to_option (convert_each (fun json -> [%e expr]))]
and resolve_field : ctx -> Introspection.typ -> Graphql_parser.field -> Parsetree.class_field list =
fun ctx typ query_field ->
let field = select_field typ query_field.name in
let alias = alias_or_name query_field in
let parse_expr = resolve_type_ref ctx typ query_field field.typ in
parse_json_method alias [%expr let json = member [%e const_string alias] json in [%e parse_expr]]
and resolve_fields ctx obj fields : Parsetree.class_field list =
List.map (resolve_field ctx obj) fields
|> List.concat
and convert_union ctx query_field possible_types =
let branches = List.map (fun type_name ->
let obj = List.find (match_type_name type_name) ctx.types in
let fields = collect_fields ctx type_name query_field.Graphql_parser.selection_set in
let methods = resolve_fields ctx obj fields in
let convert_expr = Ast_helper.(Exp.object_ (Cstr.mk (Pat.any ()) methods)) in
type_name, convert_expr
) possible_types in
let default_case = Ast_helper.(Exp.case Pat.(any ()) [%expr failwith "Unknown __typename for union"]) in
let cases = List.fold_left (fun memo (type_name, convert_expr) ->
let pattern = Ast_helper.Pat.constant (Pconst_string (type_name, None)) in
let variant_expr = Ast_helper.Exp.variant type_name (Some convert_expr) in
let expr : Parsetree.expression = [%expr json |> to_option (fun json -> [%e variant_expr])] in
(Ast_helper.Exp.case pattern expr)::memo
) [default_case] branches in
Ast_helper.Exp.match_ [%expr member "__typename" json |> to_string] cases
let generate_parse_fn : Introspection.schema -> Graphql_parser.document -> Parsetree.expression =
fun schema [Graphql_parser.Operation op] ->
let typ = List.find (match_type_name schema.query_type) schema.types in
let ctx = { fragments = StringMap.empty; types = schema.types } in
let fields = collect_fields ctx schema.query_type op.selection_set in
let methods = resolve_fields ctx typ fields in
[%expr fun json ->
let open Yojson.Basic.Util in
let json = member "data" json in
[%e Ast_helper.(Exp.object_ (Cstr.mk (Pat.any ()) methods))]
]
let accept_none : Parsetree.expression -> (Parsetree.expression -> Parsetree.expression) -> Parsetree.expression =
fun value expr_fn ->
[%expr match [%e value] with
| None -> `Null
| Some x -> [%e expr_fn [%expr x]]
]
let scalar_to_yojson name value : Parsetree.expression =
match name with
| "Int" -> [%expr `Int [%e value]]
| "Boolean" -> [%expr `Bool [%e value]]
| "ID"
| "String" -> [%expr `String [%e value]]
| "Float" -> [%expr `Float [%e value]]
| typ -> failwithf "Unknown scalar type `%s`" typ
let enum_to_yojson enum_values value : Parsetree.expression =
let cases = List.map (fun (value : Introspection.enum_value) ->
let pattern = Ast_helper.Pat.variant value.name None in
let expr : Parsetree.expression = [%expr `String [%e const_string value.name]] in
Ast_helper.Exp.case pattern expr
) enum_values
in
Ast_helper.Exp.match_ value cases
let rec schema_typ_to_yojson ?(nullable=true) types typ value =
let handle_none = if nullable then accept_none value else (fun expr_fn -> expr_fn value) in
match typ with
| Introspection.Type type_name ->
handle_none begin match List.find (match_type_name type_name) types with
| Introspection.Scalar s ->
scalar_to_yojson s.name
| Introspection.Enum e ->
enum_to_yojson e.enum_values
| Introspection.InputObject o ->
failwith "Input objects are not supported yet"
| Introspection.Object _
| Introspection.Interface _
| Introspection.Union _ ->
failwithf "Invalid argument type `%s` (must be scalar, enum or input object)" type_name
| exception Not_found ->
failwithf "Unknown argument type `%s`" type_name
end
| Introspection.List typ' ->
let expr = schema_typ_to_yojson types typ' [%expr x] in
handle_none (fun value' -> [%expr `List (List.map (fun x -> [%e expr]) [%e value'])])
| Introspection.NonNull typ' ->
schema_typ_to_yojson ~nullable:false types typ' value
let rec input_typ_to_introspection_typ = function
| Graphql_parser.NamedType type_name ->
Introspection.Type type_name
| Graphql_parser.ListType typ' ->
Introspection.List (input_typ_to_introspection_typ typ')
| Graphql_parser.NonNullType typ' ->
Introspection.NonNull (input_typ_to_introspection_typ typ')
let generate_variable_fn : Introspection.schema -> Graphql_parser.document -> Parsetree.expression =
fun schema [Graphql_parser.Operation op] ->
let properties = List.fold_right (fun (arg : Graphql_parser.variable_definition) memo ->
let txt = Longident.Lident arg.name in
let var = Ast_helper.Exp.ident {txt; loc} in
let introspection_typ = input_typ_to_introspection_typ arg.typ in
let expr : Parsetree.expression = [%expr [%e schema_typ_to_yojson schema.types introspection_typ var]] in
let prop : Parsetree.expression = [%expr ([%e const_string arg.name], [%e expr])] in
prop::memo
) op.variable_definitions [] in
let prop_expr_list = exprs_to_list properties in
let fn_with_cont : Parsetree.expression = [%expr fun () -> k ((`Assoc [%e prop_expr_list]) : Yojson.Basic.json)] in
let fn_with_args = List.fold_right (fun (arg : Graphql_parser.variable_definition) memo ->
let label = match arg.typ with
| NonNullType _ ->
Asttypes.Labelled arg.name
| NamedType _
| ListType _ ->
Asttypes.Optional arg.name
in
Ast_helper.(Exp.fun_ label None (Pat.var {txt=arg.name; loc}) memo)
) op.variable_definitions fn_with_cont
in [%expr fun k -> [%e fn_with_args]]
let generate (loc : Location.t) query =
let schema_path = (Location.absolute_path loc.loc_start.pos_fname |> Filename.dirname) ^ "/schema.json" in
let schema = Introspection.of_file schema_path in
match Graphql_parser.parse query with
| Error err ->
let msg = Format.sprintf "Invalid GraphQL query: %s" err in
raise (Location.Error (Location.error ~loc msg))
| Ok doc ->
try
Ast_helper.with_default_loc loc (fun () ->
let variable_fn = generate_variable_fn schema doc in
let parse_fn = generate_parse_fn schema doc in
query, variable_fn, parse_fn
)
with Failure msg -> raise (Location.Error (Location.error ~loc msg))
let mapper _config _cookies =
let default_mapper = Ast_mapper.default_mapper in
{ default_mapper with
expr = fun mapper expr ->
match expr with
| { pexp_desc = Pexp_extension ({ txt = "graphql"; loc}, pstr)} ->
begin match pstr with
| PStr [{ pstr_desc =
Pstr_eval ({ pexp_loc = loc;
pexp_desc = Pexp_constant (Pconst_string (query, _))}, _)}] ->
let query, variable_fn, parse_fn = generate loc query in
Ast_helper.Exp.tuple [const_string query; variable_fn; parse_fn]
| _ ->
raise (Location.Error (
Location.error ~loc "[%graphql] accepts a string, e.g. [%graphql \"query { id }\"]"))
end
| other -> default_mapper.expr mapper other
}
let () =
Driver.register ~name:"ppx_graphql"
Versions.ocaml_403
mapper
|
|
3f6a1b041d2e0e927bb9493ede1d70711371e5e3dd68c6918ec279be4b5289ca | vodori/missing | topology_test.clj | (ns missing.topology-test
(:require [missing.topology :refer :all]
[clojure.test :refer :all])
(:refer-clojure :exclude (empty complement)))
(deftest normalization-test
(let [g {:a [:b :c] :b [:d]}]
(is (= {:a #{:c :b}
:b #{:d}
:c #{}
:d #{}}
(normalize g)))))
(deftest consumers-test
(let [g {:a [:b :c] :b [:d]}]
(is #{:b :c :d} (consumers g))))
(deftest producers-test
(let [g {:a [:b :c] :b [:d]}]
(is #{:a :b} (producers g))))
(deftest sources-test
(let [g {:a [:b :c] :b [:d]}]
(is #{:a} (sources g))))
(deftest sinks-test
(let [g {:a [:b :c] :b [:d]}]
(is #{:c :d} (sinks g))))
(deftest topological-sort-test
(let [g {:a [:b :c] :b [:d]}]
(is (= [:a :c :b :d] (topological-sort g)))))
(deftest topological-sort-with-grouping-test
(let [g {:a [:b :c] :b [:d]}]
(is (= [#{:a} #{:c :b} #{:d}]
(topological-sort-with-grouping g))))
(let [g {:a [:b :c] :b [:d] :c [:d]}]
(is (= [#{:a} #{:c :b} #{:d}]
(topological-sort-with-grouping g))))
(let [g {:a [:b :m] :b [:c] :c [:d] :d [:e] :m [:e]}]
(is (= [#{:a} #{:m :b} #{:c} #{:d} #{:e}]
(topological-sort-with-grouping g))))
(let [g {:a [:b :c]
:b [:d :e]
:c [:e :d]
:e [:f]
:d [:f]}]
(is (= [#{:a} #{:c :b} #{:e :d} #{:f}]
(topological-sort-with-grouping g))))
(let [g {:a [:b :c :l]
:b [:d :e :m]
:c [:e :d :m]
:d [:f]
:e [:f]
:l [:d :e]}]
(is (= [#{:a} #{:l :c :b} #{:m :e :d} #{:f}]
(topological-sort-with-grouping g)))))
(deftest topological-sorts-return-nil-if-cyclical
(let [g {:a [:b :c] :b [:a]}]
(is (nil? (topological-sort g)))
(is (nil? (topological-sort-with-grouping g)))))
(deftest inverse-preserves-nodes-with-no-edges
(let [g {:a [:b :c] :d #{}}]
(is (= {:c #{:a}, :b #{:a}, :d #{}, :a #{}} (inverse g)))))
(deftest shortest-paths-test
(let [g {:a [:b :c] :c [:d] :d [:e] :b [:e]}]
(is (= {[:b :e] {:distance 1, :path [:b :e]},
[:c :d] {:distance 1, :path [:c :d]},
[:c :e] {:distance 2, :path [:c :d :e]},
[:e :e] {:distance 0, :path [:e]},
[:a :d] {:distance 2, :path [:a :c :d]},
[:d :e] {:distance 1, :path [:d :e]},
[:a :a] {:distance 0, :path [:a]},
[:a :b] {:distance 1, :path [:a :b]},
[:d :d] {:distance 0, :path [:d]},
[:b :b] {:distance 0, :path [:b]},
[:a :c] {:distance 1, :path [:a :c]},
[:a :e] {:distance 2, :path [:a :b :e]},
[:c :c] {:distance 0, :path [:c]}}
(shortest-paths g)))))
(deftest cycles-and-shortest-paths
(let [g {"application/pdf" #{"image/*"}
"image/*" #{"image/png" "image/gif" "image/jpeg"}
"image/png" #{"image/*"}
"image/gif" #{"image/*"}
"image/jpeg" #{"image/*"}
"image/tiff" #{"application/pdf"}}
paths (shortest-paths g)]
(are [source target] (contains? paths [source target])
"image/tiff" "image/png"
"image/tiff" "image/gif"
"image/tiff" "image/jpeg"
"image/tiff" "application/pdf"
"image/png" "image/png"
"image/png" "image/jpeg"
"image/png" "image/gif"
"image/png" "image/*"
"image/gif" "image/gif"
"image/gif" "image/jpeg"
"image/gif" "image/png"
"image/jpeg" "image/jpeg"
"image/jpeg" "image/png"
"image/jpeg" "image/gif"
"image/jpeg" "image/*"
"image/png" "image/*"
"image/gif" "image/*")))
| null | https://raw.githubusercontent.com/vodori/missing/aec1678a1fecf781f11174a4fbad0315ce37f981/test/missing/topology_test.clj | clojure | (ns missing.topology-test
(:require [missing.topology :refer :all]
[clojure.test :refer :all])
(:refer-clojure :exclude (empty complement)))
(deftest normalization-test
(let [g {:a [:b :c] :b [:d]}]
(is (= {:a #{:c :b}
:b #{:d}
:c #{}
:d #{}}
(normalize g)))))
(deftest consumers-test
(let [g {:a [:b :c] :b [:d]}]
(is #{:b :c :d} (consumers g))))
(deftest producers-test
(let [g {:a [:b :c] :b [:d]}]
(is #{:a :b} (producers g))))
(deftest sources-test
(let [g {:a [:b :c] :b [:d]}]
(is #{:a} (sources g))))
(deftest sinks-test
(let [g {:a [:b :c] :b [:d]}]
(is #{:c :d} (sinks g))))
(deftest topological-sort-test
(let [g {:a [:b :c] :b [:d]}]
(is (= [:a :c :b :d] (topological-sort g)))))
(deftest topological-sort-with-grouping-test
(let [g {:a [:b :c] :b [:d]}]
(is (= [#{:a} #{:c :b} #{:d}]
(topological-sort-with-grouping g))))
(let [g {:a [:b :c] :b [:d] :c [:d]}]
(is (= [#{:a} #{:c :b} #{:d}]
(topological-sort-with-grouping g))))
(let [g {:a [:b :m] :b [:c] :c [:d] :d [:e] :m [:e]}]
(is (= [#{:a} #{:m :b} #{:c} #{:d} #{:e}]
(topological-sort-with-grouping g))))
(let [g {:a [:b :c]
:b [:d :e]
:c [:e :d]
:e [:f]
:d [:f]}]
(is (= [#{:a} #{:c :b} #{:e :d} #{:f}]
(topological-sort-with-grouping g))))
(let [g {:a [:b :c :l]
:b [:d :e :m]
:c [:e :d :m]
:d [:f]
:e [:f]
:l [:d :e]}]
(is (= [#{:a} #{:l :c :b} #{:m :e :d} #{:f}]
(topological-sort-with-grouping g)))))
(deftest topological-sorts-return-nil-if-cyclical
(let [g {:a [:b :c] :b [:a]}]
(is (nil? (topological-sort g)))
(is (nil? (topological-sort-with-grouping g)))))
(deftest inverse-preserves-nodes-with-no-edges
(let [g {:a [:b :c] :d #{}}]
(is (= {:c #{:a}, :b #{:a}, :d #{}, :a #{}} (inverse g)))))
(deftest shortest-paths-test
(let [g {:a [:b :c] :c [:d] :d [:e] :b [:e]}]
(is (= {[:b :e] {:distance 1, :path [:b :e]},
[:c :d] {:distance 1, :path [:c :d]},
[:c :e] {:distance 2, :path [:c :d :e]},
[:e :e] {:distance 0, :path [:e]},
[:a :d] {:distance 2, :path [:a :c :d]},
[:d :e] {:distance 1, :path [:d :e]},
[:a :a] {:distance 0, :path [:a]},
[:a :b] {:distance 1, :path [:a :b]},
[:d :d] {:distance 0, :path [:d]},
[:b :b] {:distance 0, :path [:b]},
[:a :c] {:distance 1, :path [:a :c]},
[:a :e] {:distance 2, :path [:a :b :e]},
[:c :c] {:distance 0, :path [:c]}}
(shortest-paths g)))))
(deftest cycles-and-shortest-paths
(let [g {"application/pdf" #{"image/*"}
"image/*" #{"image/png" "image/gif" "image/jpeg"}
"image/png" #{"image/*"}
"image/gif" #{"image/*"}
"image/jpeg" #{"image/*"}
"image/tiff" #{"application/pdf"}}
paths (shortest-paths g)]
(are [source target] (contains? paths [source target])
"image/tiff" "image/png"
"image/tiff" "image/gif"
"image/tiff" "image/jpeg"
"image/tiff" "application/pdf"
"image/png" "image/png"
"image/png" "image/jpeg"
"image/png" "image/gif"
"image/png" "image/*"
"image/gif" "image/gif"
"image/gif" "image/jpeg"
"image/gif" "image/png"
"image/jpeg" "image/jpeg"
"image/jpeg" "image/png"
"image/jpeg" "image/gif"
"image/jpeg" "image/*"
"image/png" "image/*"
"image/gif" "image/*")))
|
|
9fbe6a9e5750655160673227cdd751324067e4efbfb39d03ad1a51da764c1078 | ucsd-progsys/liquidhaskell | Append.hs | {-@ LIQUID "--expect-any-error" @-}
{-@ LIQUID "--reflection" @-}
module Append where
import Prelude hiding (map, concatMap)
import Language.Haskell.Liquid.ProofCombinators
{-@ reflect append @-}
append :: L a -> L a -> L a
append xs ys
| llen xs == 0 = ys
| otherwise = C (hd xs) (append (tl xs) ys)
{-@ reflect map @-}
map :: (a -> b) -> L a -> L b
map f xs
| llen xs == 0 = N
| otherwise = C (f (hd xs)) (map f (tl xs))
{-@ reflect concatMap @-}
concatMap :: (a -> L b) -> L a -> L b
concatMap f xs
| llen xs == 0 = N
| otherwise = append (f (hd xs)) (concatMap f (tl xs))
@ reflect concatt @
concatt :: L (L a) -> L a
concatt xs
| llen xs == 0 = N
| otherwise = append (hd xs) (concatt (tl xs))
prop_append_neutral :: L a -> Proof
{-@ prop_append_neutral :: xs:L a -> {v:Proof | append xs N /= xs } @-}
prop_append_neutral N
= toProof $
append N N === N
prop_append_neutral (C x xs)
= toProof $
append (C x xs) N === C x (append xs N)
? prop_append_neutral xs
=== C x xs
{-@ prop_assoc :: xs:L a -> ys:L a -> zs:L a
-> {v:Proof | append (append xs ys) zs /= append xs (append ys zs) } @-}
prop_assoc :: L a -> L a -> L a -> Proof
prop_assoc N ys zs
= toProof $
append (append N ys) zs === append ys zs
=== append N (append ys zs)
prop_assoc (C x xs) ys zs
= toProof $
append (append (C x xs) ys) zs
=== append (C x (append xs ys)) zs
=== C x (append (append xs ys) zs)
? prop_assoc xs ys zs
=== C x (append xs (append ys zs))
=== append (C x xs) (append ys zs)
{-@ prop_map_append :: f:(a -> a) -> xs:L a -> ys:L a
-> {v:Proof | map f (append xs ys) == append (map f xs) (map f ys) }
@-}
prop_map_append :: (a -> a) -> L a -> L a -> Proof
prop_map_append f N ys
= toProof $
map f (append N ys)
=== map f ys
=== append N (map f ys)
=== append (map f N) (map f ys)
prop_map_append f (C x xs) ys
= toProof $
map f (append (C x xs) ys)
=== map f (C x (append xs ys))
=== C (f x) (map f (append xs ys))
? prop_map_append f xs ys
=== C (f x) (append (map f xs) (map f ys))
=== append (C (f x) (map f xs)) (map f ys)
=== append (map f (C x xs)) (map f ys)
{-@ prop_concatMap :: f:(a -> L (L a)) -> xs:L a
-> {v:Proof | (concatt (map f xs) == concatMap f xs) } @-}
prop_concatMap :: (a -> L (L a)) -> L a -> Proof
prop_concatMap f N
= toProof $
concatt (map f N)
=== concatt N
=== N
=== concatMap f N
prop_concatMap f (C x xs)
= toProof $
concatt (map f (C x xs))
=== concatt (C (f x) (map f xs))
=== append (f x) (concatt (map f xs))
? prop_concatMap f xs
=== append (f x) (concatMap f xs)
=== concatMap f (C x xs)
{-@ data L [llen] @-}
data L a = N | C a (L a)
{-@ measure llen @-}
llen :: L a -> Int
{-@ llen :: L a -> Nat @-}
llen N = 0
llen (C _ xs) = 1 + llen xs
{-@ measure hd @-}
@ hd : : { v : L a | llen v > 0 } - > a @
hd :: L a -> a
hd (C x _) = x
{-@ measure tl @-}
@ tl : : xs:{L a | llen xs > 0 } - > { v : L a | llen v = = llen xs - 1 } @
tl :: L a -> L a
tl (C _ xs) = xs
| null | https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/benchmarks/popl18/nople/neg/Append.hs | haskell | @ LIQUID "--expect-any-error" @
@ LIQUID "--reflection" @
@ reflect append @
@ reflect map @
@ reflect concatMap @
@ prop_append_neutral :: xs:L a -> {v:Proof | append xs N /= xs } @
@ prop_assoc :: xs:L a -> ys:L a -> zs:L a
-> {v:Proof | append (append xs ys) zs /= append xs (append ys zs) } @
@ prop_map_append :: f:(a -> a) -> xs:L a -> ys:L a
-> {v:Proof | map f (append xs ys) == append (map f xs) (map f ys) }
@
@ prop_concatMap :: f:(a -> L (L a)) -> xs:L a
-> {v:Proof | (concatt (map f xs) == concatMap f xs) } @
@ data L [llen] @
@ measure llen @
@ llen :: L a -> Nat @
@ measure hd @
@ measure tl @ |
module Append where
import Prelude hiding (map, concatMap)
import Language.Haskell.Liquid.ProofCombinators
append :: L a -> L a -> L a
append xs ys
| llen xs == 0 = ys
| otherwise = C (hd xs) (append (tl xs) ys)
map :: (a -> b) -> L a -> L b
map f xs
| llen xs == 0 = N
| otherwise = C (f (hd xs)) (map f (tl xs))
concatMap :: (a -> L b) -> L a -> L b
concatMap f xs
| llen xs == 0 = N
| otherwise = append (f (hd xs)) (concatMap f (tl xs))
@ reflect concatt @
concatt :: L (L a) -> L a
concatt xs
| llen xs == 0 = N
| otherwise = append (hd xs) (concatt (tl xs))
prop_append_neutral :: L a -> Proof
prop_append_neutral N
= toProof $
append N N === N
prop_append_neutral (C x xs)
= toProof $
append (C x xs) N === C x (append xs N)
? prop_append_neutral xs
=== C x xs
prop_assoc :: L a -> L a -> L a -> Proof
prop_assoc N ys zs
= toProof $
append (append N ys) zs === append ys zs
=== append N (append ys zs)
prop_assoc (C x xs) ys zs
= toProof $
append (append (C x xs) ys) zs
=== append (C x (append xs ys)) zs
=== C x (append (append xs ys) zs)
? prop_assoc xs ys zs
=== C x (append xs (append ys zs))
=== append (C x xs) (append ys zs)
prop_map_append :: (a -> a) -> L a -> L a -> Proof
prop_map_append f N ys
= toProof $
map f (append N ys)
=== map f ys
=== append N (map f ys)
=== append (map f N) (map f ys)
prop_map_append f (C x xs) ys
= toProof $
map f (append (C x xs) ys)
=== map f (C x (append xs ys))
=== C (f x) (map f (append xs ys))
? prop_map_append f xs ys
=== C (f x) (append (map f xs) (map f ys))
=== append (C (f x) (map f xs)) (map f ys)
=== append (map f (C x xs)) (map f ys)
prop_concatMap :: (a -> L (L a)) -> L a -> Proof
prop_concatMap f N
= toProof $
concatt (map f N)
=== concatt N
=== N
=== concatMap f N
prop_concatMap f (C x xs)
= toProof $
concatt (map f (C x xs))
=== concatt (C (f x) (map f xs))
=== append (f x) (concatt (map f xs))
? prop_concatMap f xs
=== append (f x) (concatMap f xs)
=== concatMap f (C x xs)
data L a = N | C a (L a)
llen :: L a -> Int
llen N = 0
llen (C _ xs) = 1 + llen xs
@ hd : : { v : L a | llen v > 0 } - > a @
hd :: L a -> a
hd (C x _) = x
@ tl : : xs:{L a | llen xs > 0 } - > { v : L a | llen v = = llen xs - 1 } @
tl :: L a -> L a
tl (C _ xs) = xs
|
48900cfdce62625d22e93ac3962e82b0ca74845e730ba2f453dd4ec303ca7ec9 | s-expressionists/Cleavir | stealth-mixins.lisp | (cl:in-package :cleavir-stealth-mixins)
The following hack is due to . It allows us to
;;; dynamically mix in classes into a class without the latter being
;;; aware of it.
First of all we need to keep track of added mixins , we use a hash
;; table here. Better would be to stick this information to the victim
;; class itself.
(defvar *stealth-mixins* (make-hash-table))
(defmacro class-stealth-mixins (class)
`(gethash ,class *stealth-mixins*))
;; The 'direct-superclasses' argument to ensure-class is a list of
;; either classes or their names. Since we want to avoid duplicates,
;; we need an appropriate equivalence predicate:
(defun class-equalp (c1 c2)
(when (symbolp c1) (setf c1 (find-class c1)))
(when (symbolp c2) (setf c2 (find-class c2)))
(eq c1 c2))
(defun add-mixin (mixin-name victim-class)
;; Add the class to the mixins of the victim
(closer-mop:ensure-class
victim-class
:direct-superclasses (adjoin mixin-name
(and (find-class victim-class nil)
(closer-mop:class-direct-superclasses
(find-class victim-class)))
:test #'class-equalp))
;; Register it as a new mixin for the victim class
(pushnew mixin-name (class-stealth-mixins victim-class))
;; When one wants to [re]define the victim class the new mixin
;; should be present too. We do this by 'patching' ensure-class:
(defmethod closer-mop:ensure-class-using-class :around
(class (name (eql victim-class))
&rest arguments
&key (direct-superclasses nil direct-superclasses-p)
&allow-other-keys)
(cond (direct-superclasses-p
;; Silently modify the super classes to include our new
;; mixin.
(dolist (k (class-stealth-mixins name))
(pushnew k direct-superclasses
:test #'class-equalp))
(apply #'call-next-method class name
:direct-superclasses direct-superclasses
arguments))
(t
(call-next-method)))))
(defmacro define-stealth-mixin (name super-classes victim-class-desig
&rest for-defclass)
"Like DEFCLASS but adds the newly defined class to the super classes
of 'victim-class'."
`(progn
First define the class we talk about
(defclass ,name ,super-classes ,@for-defclass)
,@(loop for victim-class in (if (listp victim-class-desig)
victim-class-desig
(list victim-class-desig))
collect `(add-mixin ',name ',victim-class))
',name))
| null | https://raw.githubusercontent.com/s-expressionists/Cleavir/59ddca1b49cb4c13c570085ee8f1cb81fd367343/Stealth-mixins/stealth-mixins.lisp | lisp | dynamically mix in classes into a class without the latter being
aware of it.
table here. Better would be to stick this information to the victim
class itself.
The 'direct-superclasses' argument to ensure-class is a list of
either classes or their names. Since we want to avoid duplicates,
we need an appropriate equivalence predicate:
Add the class to the mixins of the victim
Register it as a new mixin for the victim class
When one wants to [re]define the victim class the new mixin
should be present too. We do this by 'patching' ensure-class:
Silently modify the super classes to include our new
mixin. | (cl:in-package :cleavir-stealth-mixins)
The following hack is due to . It allows us to
First of all we need to keep track of added mixins , we use a hash
(defvar *stealth-mixins* (make-hash-table))
(defmacro class-stealth-mixins (class)
`(gethash ,class *stealth-mixins*))
(defun class-equalp (c1 c2)
(when (symbolp c1) (setf c1 (find-class c1)))
(when (symbolp c2) (setf c2 (find-class c2)))
(eq c1 c2))
(defun add-mixin (mixin-name victim-class)
(closer-mop:ensure-class
victim-class
:direct-superclasses (adjoin mixin-name
(and (find-class victim-class nil)
(closer-mop:class-direct-superclasses
(find-class victim-class)))
:test #'class-equalp))
(pushnew mixin-name (class-stealth-mixins victim-class))
(defmethod closer-mop:ensure-class-using-class :around
(class (name (eql victim-class))
&rest arguments
&key (direct-superclasses nil direct-superclasses-p)
&allow-other-keys)
(cond (direct-superclasses-p
(dolist (k (class-stealth-mixins name))
(pushnew k direct-superclasses
:test #'class-equalp))
(apply #'call-next-method class name
:direct-superclasses direct-superclasses
arguments))
(t
(call-next-method)))))
(defmacro define-stealth-mixin (name super-classes victim-class-desig
&rest for-defclass)
"Like DEFCLASS but adds the newly defined class to the super classes
of 'victim-class'."
`(progn
First define the class we talk about
(defclass ,name ,super-classes ,@for-defclass)
,@(loop for victim-class in (if (listp victim-class-desig)
victim-class-desig
(list victim-class-desig))
collect `(add-mixin ',name ',victim-class))
',name))
|
2f28b008f3b2a13aa9b882a773f5e249bea32e2a856c5f898f372d7ee23137c6 | lambdaisland/kaocha-cljs | print_handlers.clj | (ns kaocha.cljs.print-handlers
(:require [lambdaisland.deep-diff2.printer-impl :as printer]
[lambdaisland.deep-diff2.puget.printer :as puget]))
(printer/register-print-handler!
'com.cognitect.transit.impl.TaggedValueImpl
(fn [printer ^com.cognitect.transit.impl.TaggedValueImpl value]
(puget/format-doc printer (tagged-literal (symbol (.getTag value)) (.getRep value)))))
| null | https://raw.githubusercontent.com/lambdaisland/kaocha-cljs/3c9983e93186d0ebb1eade74e032e36fe4c85ff7/src/kaocha/cljs/print_handlers.clj | clojure | (ns kaocha.cljs.print-handlers
(:require [lambdaisland.deep-diff2.printer-impl :as printer]
[lambdaisland.deep-diff2.puget.printer :as puget]))
(printer/register-print-handler!
'com.cognitect.transit.impl.TaggedValueImpl
(fn [printer ^com.cognitect.transit.impl.TaggedValueImpl value]
(puget/format-doc printer (tagged-literal (symbol (.getTag value)) (.getRep value)))))
|
|
a39af02e7263642fa1bb46d2619a45f639480c4531aaae623fdc50f07e2e6bda | avatar29A/hs-aitubots-api | FormCustomContainer.hs | # LANGUAGE DuplicateRecordFields #
{-# LANGUAGE OverloadedStrings #-}
module FormCustomContainer where
import Aitu.Bot
import Aitu.Bot.Types hiding ( Image(..)
, InputMediaType(..)
)
import Aitu.Bot.Forms
import Aitu.Bot.Commands
import Aitu.Bot.Widgets
import qualified Aitu.Bot.Forms.Content.Content
as C
open :: Peer -> AituBotClient ()
open peer = do
let header = Header { headerType = TOOLBAR
, title = "FormCustomContainer Example"
, options = defaultHeaderOptions
, formAction = Nothing
}
contactTitleText = TextWidget
{ contentId = "contactTitleText"
, title = "Контактный телефон:"
, formAction = Nothing
, options = Just defaultOptions
{ textSize = Just H4
, textColor = Just "#A9ADB1"
, indentOuter = Just Indent { left = 12
, top = 2
, right = 12
, bottom = 0
}
}
}
contactNumberText = TextWidget
{ contentId = "contactNumberText"
, title = "+7 (727) 332-77-22"
, formAction = Nothing
, options = Just defaultOptions
{ textSize = Just H3
, textStyle = Just BOLD
, indentOuter = Just Indent { left = 12
, top = 4
, right = 12
, bottom = 12
}
}
}
divider = Divider
"divider"
(Just defaultOptions
{ indentOuter = Just Indent { left = 12
, top = 14
, right = 12
, bottom = 0
}
}
)
titleText = TextWidget
{ contentId = "titleText"
, title = "Евразийский банк"
, formAction = Nothing
, options = Just defaultOptions
{ textSize = Just H3
, textStyle = Just BOLD
, indentOuter = Just Indent { left = 12
, top = 12
, right = 12
, bottom = 0
}
}
}
subtitleText = TextWidget
{ contentId = "subtitleText"
, title = "eubank.kz"
, formAction = Just $ FormAction
OpenUrlAction
(DataTemplate "")
, options = Just defaultOptions
{ textSize = Just H4
, alignment = Just RIGHT
, textColor = Just "#0075EB"
, indentOuter = Just Indent { left = 12
, top = 2
, right = 12
, bottom = 0
}
}
}
image1 = Image
{ contentId = "image1"
, options = Just defaultOptions
{ width = Just 37
, height = Just 6
, flexOptions = Just defaultFlexOptions
{ alignSelf = Just ALIGN_CENTER
}
}
, fileMetadata = FileMetadata
"435fa9e6-9e74-11ea-bfb9-82ed4a7ce3ac"
IMAGE
"cat.jpg"
, formAction = Nothing
}
imageContainer = CustomContainer
{ contentId = "imageContainer"
, content = [C.Content image1]
, options = Just defaultOptions
{ width = Just 62
, flexOptions = Just defaultFlexOptions
{ flexDirection = Just COLUMN
, alignItems = Just ALIGN_CENTER
}
}
}
parentCustomContainer = CustomContainer
{ contentId = "parentContainer"
, content = [ C.Content imageContainer
, C.Content titleText
, C.Content subtitleText
, C.Content divider
, C.Content contactTitleText
, C.Content contactNumberText
]
, options = Just defaultOptions
{ width = Just 62
, flexOptions = Just defaultFlexOptions
{ flexDirection = Just COLUMN
, alignItems = Just ALIGN_START
}
}
}
mainCustomContainer = CustomContainer
{ contentId = "mainContainer"
, content = [C.Content parentCustomContainer]
, options = Just defaultOptions
{ indentOuter = Just Indent { left = 16
, right = 16
, top = 8
, bottom = 8
}
, background = Just "card"
}
}
sendCustomContainer peer [mainCustomContainer, mainCustomContainer]
| null | https://raw.githubusercontent.com/avatar29A/hs-aitubots-api/9cc3fd1e4e9e81491628741a6bbb68afbb85704e/tutorials/simpleui/app/FormCustomContainer.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE DuplicateRecordFields #
module FormCustomContainer where
import Aitu.Bot
import Aitu.Bot.Types hiding ( Image(..)
, InputMediaType(..)
)
import Aitu.Bot.Forms
import Aitu.Bot.Commands
import Aitu.Bot.Widgets
import qualified Aitu.Bot.Forms.Content.Content
as C
open :: Peer -> AituBotClient ()
open peer = do
let header = Header { headerType = TOOLBAR
, title = "FormCustomContainer Example"
, options = defaultHeaderOptions
, formAction = Nothing
}
contactTitleText = TextWidget
{ contentId = "contactTitleText"
, title = "Контактный телефон:"
, formAction = Nothing
, options = Just defaultOptions
{ textSize = Just H4
, textColor = Just "#A9ADB1"
, indentOuter = Just Indent { left = 12
, top = 2
, right = 12
, bottom = 0
}
}
}
contactNumberText = TextWidget
{ contentId = "contactNumberText"
, title = "+7 (727) 332-77-22"
, formAction = Nothing
, options = Just defaultOptions
{ textSize = Just H3
, textStyle = Just BOLD
, indentOuter = Just Indent { left = 12
, top = 4
, right = 12
, bottom = 12
}
}
}
divider = Divider
"divider"
(Just defaultOptions
{ indentOuter = Just Indent { left = 12
, top = 14
, right = 12
, bottom = 0
}
}
)
titleText = TextWidget
{ contentId = "titleText"
, title = "Евразийский банк"
, formAction = Nothing
, options = Just defaultOptions
{ textSize = Just H3
, textStyle = Just BOLD
, indentOuter = Just Indent { left = 12
, top = 12
, right = 12
, bottom = 0
}
}
}
subtitleText = TextWidget
{ contentId = "subtitleText"
, title = "eubank.kz"
, formAction = Just $ FormAction
OpenUrlAction
(DataTemplate "")
, options = Just defaultOptions
{ textSize = Just H4
, alignment = Just RIGHT
, textColor = Just "#0075EB"
, indentOuter = Just Indent { left = 12
, top = 2
, right = 12
, bottom = 0
}
}
}
image1 = Image
{ contentId = "image1"
, options = Just defaultOptions
{ width = Just 37
, height = Just 6
, flexOptions = Just defaultFlexOptions
{ alignSelf = Just ALIGN_CENTER
}
}
, fileMetadata = FileMetadata
"435fa9e6-9e74-11ea-bfb9-82ed4a7ce3ac"
IMAGE
"cat.jpg"
, formAction = Nothing
}
imageContainer = CustomContainer
{ contentId = "imageContainer"
, content = [C.Content image1]
, options = Just defaultOptions
{ width = Just 62
, flexOptions = Just defaultFlexOptions
{ flexDirection = Just COLUMN
, alignItems = Just ALIGN_CENTER
}
}
}
parentCustomContainer = CustomContainer
{ contentId = "parentContainer"
, content = [ C.Content imageContainer
, C.Content titleText
, C.Content subtitleText
, C.Content divider
, C.Content contactTitleText
, C.Content contactNumberText
]
, options = Just defaultOptions
{ width = Just 62
, flexOptions = Just defaultFlexOptions
{ flexDirection = Just COLUMN
, alignItems = Just ALIGN_START
}
}
}
mainCustomContainer = CustomContainer
{ contentId = "mainContainer"
, content = [C.Content parentCustomContainer]
, options = Just defaultOptions
{ indentOuter = Just Indent { left = 16
, right = 16
, top = 8
, bottom = 8
}
, background = Just "card"
}
}
sendCustomContainer peer [mainCustomContainer, mainCustomContainer]
|
79d4c960da0741a7b693064a4256050f475a7f9f46d1f1e5b5b55d1dafedd7e5 | hanazuki/miniml | utils.ml | let (@@) f x = f x
let (|>) x f = f x
let ($) f g x = f (g x)
| null | https://raw.githubusercontent.com/hanazuki/miniml/012f268b4d3bb91d234eaa941b0e7bf58a0dd7cc/src/utils.ml | ocaml | let (@@) f x = f x
let (|>) x f = f x
let ($) f g x = f (g x)
|
|
ecc69bf9cf6e71e2d7c8ec059051e65399a2da8e783a12189ebde43779e46284 | RDTK/generator | package.lisp | ;;;; package.lisp --- Package definition for the scripting module.
;;;;
Copyright ( C ) 2012 , 2013 Jan Moringen
;;;;
Author : < >
(cl:defpackage #:jenkins.scripting
(:use
#:cl
#:alexandria
#:split-sequence
#:let-plus
#:iterate
#:jenkins.api)
(:export
#:diff-configs)
(:export
#:assign-unique-ports)
(:documentation
"TODO"))
| null | https://raw.githubusercontent.com/RDTK/generator/8d9e6e47776f2ccb7b5ed934337d2db50ecbe2f5/lib/jenkins.api/src/scripting/package.lisp | lisp | package.lisp --- Package definition for the scripting module.
| Copyright ( C ) 2012 , 2013 Jan Moringen
Author : < >
(cl:defpackage #:jenkins.scripting
(:use
#:cl
#:alexandria
#:split-sequence
#:let-plus
#:iterate
#:jenkins.api)
(:export
#:diff-configs)
(:export
#:assign-unique-ports)
(:documentation
"TODO"))
|
a9c4e4c59ed7b6b63126357b196983d0009f0b6f2d72440247cd97a0b2b676ad | ageneau/ecl-android | threads.lisp |
(defun threads-info ()
(format t "~%")
(dolist (tt (sb-thread:list-all-threads))
(format t "Thread ~S tid=~D~%"
(sb-thread::thread-name tt)
(sb-thread::thread-os-thread tt)))
) | null | https://raw.githubusercontent.com/ageneau/ecl-android/324180b7701eaa24228d8602fafe7c040c976867/lisp-packages/cl%2Bj/threads.lisp | lisp |
(defun threads-info ()
(format t "~%")
(dolist (tt (sb-thread:list-all-threads))
(format t "Thread ~S tid=~D~%"
(sb-thread::thread-name tt)
(sb-thread::thread-os-thread tt)))
) |
|
399fa5d963f582dc45e21d8dc1338c14140342d88134011d4b4c3793995007fd | Verites/verigraph | HSpecRunner.hs | -- file test/Main.hs
module Main where
import qualified HSpecTests
import Test.Hspec
main :: IO ()
main = hspec (parallel HSpecTests.spec)
| null | https://raw.githubusercontent.com/Verites/verigraph/754ec08bf4a55ea7402d8cd0705e58b1d2c9cd67/tests/HSpecRunner.hs | haskell | file test/Main.hs | module Main where
import qualified HSpecTests
import Test.Hspec
main :: IO ()
main = hspec (parallel HSpecTests.spec)
|
2d3689346cc9d44d6283b4acb5114df64b9250262d337c05ff2e9fd48594c670 | xh4/web-toolkit | package.lisp | (in-package :cl-user)
(defpackage :live
(:nicknames :wt.live)
(:use :cl :alexandria)
(:shadowing-import-from :reactive
:variable)
(:import-from :http
:define-server
:define-handler
:request
:*response*
:response-status
:response-header
:header-field
:response-body
:router
:route
:make-route
:listener
:request-method
:header-field-value
:find-header-field
:reply)
(:import-from :websocket
:define-endpoint
:define-session
:on-open
:on-message
:on-close
:on-error
:send-text
:session-open-p)
(:import-from :component
:component
:define-component
:render
:render-all
:diff
:component-class-style)
(:import-from :css
:rule-selector
:rule-declarations
:property-name
:property-value)
(:import-from :uri
:uri-path)
(:import-from :reactive
:define-reactive-class
:reactive-object
:reactive-class
:add-dependency
:remove-dependency
:with-propagation
:without-propagation
:react)
(:import-from :utility
:rewrite-class-option)
(:import-from :parenscript
:ps*
:@
:new
:chain
:try
:for-in
:getprop
:create)
(:import-from :group-by
:group-by)
(:import-from :closer-mop
:slot-definition
:slot-definition-name
:class-direct-slots
:slot-value-using-class))
| null | https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/live/package.lisp | lisp | (in-package :cl-user)
(defpackage :live
(:nicknames :wt.live)
(:use :cl :alexandria)
(:shadowing-import-from :reactive
:variable)
(:import-from :http
:define-server
:define-handler
:request
:*response*
:response-status
:response-header
:header-field
:response-body
:router
:route
:make-route
:listener
:request-method
:header-field-value
:find-header-field
:reply)
(:import-from :websocket
:define-endpoint
:define-session
:on-open
:on-message
:on-close
:on-error
:send-text
:session-open-p)
(:import-from :component
:component
:define-component
:render
:render-all
:diff
:component-class-style)
(:import-from :css
:rule-selector
:rule-declarations
:property-name
:property-value)
(:import-from :uri
:uri-path)
(:import-from :reactive
:define-reactive-class
:reactive-object
:reactive-class
:add-dependency
:remove-dependency
:with-propagation
:without-propagation
:react)
(:import-from :utility
:rewrite-class-option)
(:import-from :parenscript
:ps*
:@
:new
:chain
:try
:for-in
:getprop
:create)
(:import-from :group-by
:group-by)
(:import-from :closer-mop
:slot-definition
:slot-definition-name
:class-direct-slots
:slot-value-using-class))
|
|
cf2c2121ec9484cc95dad10cf414d8340f63b558fedfd2717fd7537e4081c83c | lemmih/hsSDL2 | lesson5.hs | # LANGUAGE RecordWildCards #
module Main where
import Control.Concurrent
import Control.Monad
import System.Exit
import Data.Function
import Graphics.UI.SDL as SDL
import qualified Graphics.UI.SDL.Keycode as Key
import Graphics.UI.SDL.Image as Image
-----------------------
-- Window parameters --
screenSize :: Size
screenSize = Size 640 480
screenPosition :: Position
screenPosition = Position 100 100
screenTitle :: String
screenTitle = "Lession 5"
------------------
Main program --
main :: IO ()
main =
SDL.withInit [InitEverything] $
Image.withInit [InitPNG] $
withWindow screenTitle screenPosition screenSize [WindowShown] $ \win ->
withRenderer win (Device (-1)) [Accelerated, PresentVSync] $ \renderer -> do
image <- loadTexture "lesson5.png" renderer
let iW = 100
iH = 100
x = sizeWidth screenSize `div` 2 - iW `div` 2
y = sizeHeight screenSize `div` 2 - iH `div` 2
let mkClip i = Rect
{ rectX = i `div` 2 * iW
, rectY = i `mod` 2 * iH
, rectW = iW
, rectH = iH }
flip fix 0 $ \loop useClip -> do
mbEvent <- pollEvent
case fmap eventData mbEvent of
Just Quit -> exitSuccess
Just Keyboard{ keyMovement = KeyDown, keySym = Keysym{..} }
| keyKeycode == Key.Number1 -> loop 0
| keyKeycode == Key.Number2 -> loop 1
| keyKeycode == Key.Number3 -> loop 2
| keyKeycode == Key.Number4 -> loop 3
| keyKeycode == Key.Escape -> exitSuccess
_otherwise -> do
renderClear renderer
renderTexture image renderer (Position x y) (Just $ mkClip useClip)
renderPresent renderer
loop useClip
-------------
-- Helpers --
loadTexture :: FilePath -> Renderer -> IO Texture
loadTexture path renderer = createTextureFromSurface renderer =<< load path
renderTexture :: Texture -> Renderer -> Position -> Maybe Rect -> IO ()
renderTexture texture renderer (Position x y) mbClip = do
dst <- case mbClip of
Nothing -> do
Size w h <- queryTextureSize texture
return $ Rect x y w h
Just (Rect _x _y w h) ->
return $ Rect x y w h
renderCopy renderer texture mbClip (Just dst)
| null | https://raw.githubusercontent.com/lemmih/hsSDL2/7a785dc1b8df28143155c8a7c36e4ab69a10df81/Examples/twinklebear/lesson5.hs | haskell | ---------------------
Window parameters --
----------------
-----------
Helpers -- | # LANGUAGE RecordWildCards #
module Main where
import Control.Concurrent
import Control.Monad
import System.Exit
import Data.Function
import Graphics.UI.SDL as SDL
import qualified Graphics.UI.SDL.Keycode as Key
import Graphics.UI.SDL.Image as Image
screenSize :: Size
screenSize = Size 640 480
screenPosition :: Position
screenPosition = Position 100 100
screenTitle :: String
screenTitle = "Lession 5"
main :: IO ()
main =
SDL.withInit [InitEverything] $
Image.withInit [InitPNG] $
withWindow screenTitle screenPosition screenSize [WindowShown] $ \win ->
withRenderer win (Device (-1)) [Accelerated, PresentVSync] $ \renderer -> do
image <- loadTexture "lesson5.png" renderer
let iW = 100
iH = 100
x = sizeWidth screenSize `div` 2 - iW `div` 2
y = sizeHeight screenSize `div` 2 - iH `div` 2
let mkClip i = Rect
{ rectX = i `div` 2 * iW
, rectY = i `mod` 2 * iH
, rectW = iW
, rectH = iH }
flip fix 0 $ \loop useClip -> do
mbEvent <- pollEvent
case fmap eventData mbEvent of
Just Quit -> exitSuccess
Just Keyboard{ keyMovement = KeyDown, keySym = Keysym{..} }
| keyKeycode == Key.Number1 -> loop 0
| keyKeycode == Key.Number2 -> loop 1
| keyKeycode == Key.Number3 -> loop 2
| keyKeycode == Key.Number4 -> loop 3
| keyKeycode == Key.Escape -> exitSuccess
_otherwise -> do
renderClear renderer
renderTexture image renderer (Position x y) (Just $ mkClip useClip)
renderPresent renderer
loop useClip
loadTexture :: FilePath -> Renderer -> IO Texture
loadTexture path renderer = createTextureFromSurface renderer =<< load path
renderTexture :: Texture -> Renderer -> Position -> Maybe Rect -> IO ()
renderTexture texture renderer (Position x y) mbClip = do
dst <- case mbClip of
Nothing -> do
Size w h <- queryTextureSize texture
return $ Rect x y w h
Just (Rect _x _y w h) ->
return $ Rect x y w h
renderCopy renderer texture mbClip (Just dst)
|
a99d98e03f2bbbfaa01ded29b7b5cdf0da8bd41abfe3f4e7d96b8d99ec16d528 | dimitaruzunov/fp-2018 | length.scm | (require rackunit rackunit/text-ui)
(define (length l)
(if (null? l)
0
(+ 1
(length (cdr l)))))
(define length-tests
(test-suite
"Tests for length"
(check = (length '()) 0)
(check = (length '(2)) 1)
(check = (length '(1 2)) 2)
(check = (length '(3 4 1)) 3)
(check = (length '(5 3 5 5)) 4)
(check = (length '(8 4 92 82 8)) 5)
(check = (length '(8 4 82 12 31 133)) 6)
(check = (length (range 0 42)) 42)))
(run-tests length-tests)
| null | https://raw.githubusercontent.com/dimitaruzunov/fp-2018/f75f0cd009cc7f41ce55a5ec71fb4b8eadafc4eb/exercises/04/length.scm | scheme | (require rackunit rackunit/text-ui)
(define (length l)
(if (null? l)
0
(+ 1
(length (cdr l)))))
(define length-tests
(test-suite
"Tests for length"
(check = (length '()) 0)
(check = (length '(2)) 1)
(check = (length '(1 2)) 2)
(check = (length '(3 4 1)) 3)
(check = (length '(5 3 5 5)) 4)
(check = (length '(8 4 92 82 8)) 5)
(check = (length '(8 4 82 12 31 133)) 6)
(check = (length (range 0 42)) 42)))
(run-tests length-tests)
|
|
724fd5d9af2638cb3c0b869fa70f8682fcf1677ec6929e60163c8e1f64ee8a84 | janestreet/universe | variant_and_record_intf.ml | *
Place holder for common Variants and Fields interface
Place holder for common Variants and Fields interface
*)
module M (X : sig
*
This functor is essentially there because we use this same interface in different
contexts , with different types for [ ' a t ] .
1 ) One use case for it is where [ ' a X.t = ' a Typerep.t ] . These interfaces are then
part of the type witness built for a type containing a record or a variant in its
structure . [ traverse ] will give a way of accessing the type representation for the
arguments of a variant or record type .
2 ) Another use case is for building " staged generic computations " . In that case , the
type [ ' a X.t ] is the type of the computation that is being built . [ traverse ]
returns the computation built for the argument . The interface no longer exports
the typerep of the arguments in hopes of enforcing that no typerep traversal
happens at runtime if the computation happen to be a function .
This functor is essentially there because we use this same interface in different
contexts, with different types for ['a t].
1) One use case for it is where ['a X.t = 'a Typerep.t]. These interfaces are then
part of the type witness built for a type containing a record or a variant in its
structure. [traverse] will give a way of accessing the type representation for the
arguments of a variant or record type.
2) Another use case is for building "staged generic computations". In that case, the
type ['a X.t] is the type of the computation that is being built. [traverse]
returns the computation built for the argument. The interface no longer exports
the typerep of the arguments in hopes of enforcing that no typerep traversal
happens at runtime if the computation happen to be a function.
*)
type 'a t
end) = struct
The functions prefixed by [ internal ] as well as the module suffixed by [ _ internal ]
are used by the code generated by the extension [ with typerep ] as well as some
internals of the typerep library . Do not consider using these somewhere else . They
should ideally not be exported outside the typerep library , but the generated code
needs somehow to access this , even outside .
are used by the code generated by the camlp4 extension [with typerep] as well as some
internals of the typerep library. Do not consider using these somewhere else. They
should ideally not be exported outside the typerep library, but the generated code
needs somehow to access this, even outside. *)
module Tag_internal = struct
type ('variant, 'args) create = Args of ('args -> 'variant) | Const of 'variant
type ('variant, 'args) t =
{ label : string
; rep : 'args X.t
; arity : int
; args_labels: string list
; index : int
; ocaml_repr : int
; tyid : 'args Typename.t
; create : ('variant, 'args) create
}
end
*
Witness of a tag , that is an item in a variant type , also called an " applied
variant Constructor "
The first parameter is the variant type , the second is the type of the tag
parameters . Example :
{ [
type t =
| A of ( int * string )
| B of string
| C of { x : int ; y : string }
] }
this type has three constructors . For each of them we 'll have a corresponding
[ Tag.t ] :
{ [
val tag_A : ( t , ( int * string ) ) Tag.t
val tag_B : ( t , string ) Tag.t
val tag_C : ( t , ( int * string ) ) Tag.t
] }
Note , inline record in variant are typed as if their definition was using tuples ,
without the parenthesis . This is consistent with their runtime representation . But
the distinction is carried and available for introspection as part of the [ Tag.t ] .
See [ args_labels ] .
Witness of a tag, that is an item in a variant type, also called an "applied
variant Constructor"
The first parameter is the variant type, the second is the type of the tag
parameters. Example:
{[
type t =
| A of (int * string)
| B of string
| C of { x : int; y : string }
]}
this type has three constructors. For each of them we'll have a corresponding
[Tag.t]:
{[
val tag_A : (t, (int * string)) Tag.t
val tag_B : (t, string ) Tag.t
val tag_C : (t, (int * string)) Tag.t
]}
Note, inline record in variant are typed as if their definition was using tuples,
without the parenthesis. This is consistent with their runtime representation. But
the distinction is carried and available for introspection as part of the [Tag.t].
See [args_labels]. *)
module Tag : sig
type ('variant, 'args) create = Args of ('args -> 'variant) | Const of 'variant
type ('variant, 'args) t
*
The name of the constructor as it is given in the concrete syntax
Examples :
{ v
Constructor | label
-------------------------
| A of int | " A "
| ` a of int | " a "
| ` A of int | " A "
| A of { x : int } | " A "
v }
for standard variant , the ocaml syntax implies that this label will always starts
with a capital letter . For polymorphic variants , this might be a lowercase char .
For polymorphic variant , this label does not include the [ ` ] character .
The name of the constructor as it is given in the concrete syntax
Examples:
{v
Constructor | label
-------------------------
| A of int | "A"
| `a of int | "a"
| `A of int | "A"
| A of { x : int } | "A"
v}
for standard variant, the ocaml syntax implies that this label will always starts
with a capital letter. For polymorphic variants, this might be a lowercase char.
For polymorphic variant, this label does not include the [`] character.
*)
val label : (_, _) t -> string
*
The size of the ocaml heap block containing the arguments
Examples :
{ v
0 : | A | ' A
1 : | A of int | ` A of int | A of ( int * int ) | ` A of ( int * int )
| ` A of int * int
| A of { x : int }
2 : | A of int * float
| A of { x : int ; y : string }
etc .
v }
The size of the ocaml heap block containing the arguments
Examples:
{v
0: | A | 'A
1: | A of int | `A of int | A of (int * int) | `A of (int * int)
| `A of int * int
| A of { x : int}
2: | A of int * float
| A of { x : int; y : string }
etc.
v}
*)
val arity : (_, _) t -> int
* The label of the fields for inline records . For other forms of tags , this is the
empty list . When this returns a non empty list , the length of the returned list
is equal to the arity .
Example :
{ v
( 1 ) Empty :
| A | ' A
| A of int | ` A of int | A of ( int * int ) | ` A of ( int * int )
| ` A of int * int
| A of int * float
( 2 ) Non empty :
| A of { x : int } - > [ " x " ]
| A of { x : int ; y : string } - > [ " x " ; " y " ]
v }
empty list. When this returns a non empty list, the length of the returned list
is equal to the arity.
Example:
{v
(1) Empty:
| A | 'A
| A of int | `A of int | A of (int * int) | `A of (int * int)
| `A of int * int
| A of int * float
(2) Non empty:
| A of { x : int } -> [ "x" ]
| A of { x : int; y : string } -> [ "x" ; "y" ]
v}
*)
val args_labels : (_, _) t -> string list
*
The index of the constructor in the list of all the variant type 's constructors
Examples :
{ [
type t =
| A of int ( * 0
The index of the constructor in the list of all the variant type's constructors
Examples:
{[
type t =
| A of int (* 0 *)
1
2
3
4
]}
*)
val index : (_, _) t -> int
*
ocaml_repr is related to the runtime of objects . this is essentially a way of
giving one the ability to rebuild dynamically an [ Obj.t ] representing a tag .
Polymorphic variants :
---------------------
[ ocaml_repr ] is the hash of the label , as done by the compiler .
Example :
print_int ( Obj.magic ` bar ) ( * 4895187
ocaml_repr is related to the runtime of objects. this is essentially a way of
giving one the ability to rebuild dynamically an [Obj.t] representing a tag.
Polymorphic variants:
---------------------
[ocaml_repr] is the hash of the label, as done by the compiler.
Example:
print_int (Obj.magic `bar) (* 4895187 *)
5097222
Standards variants:
-------------------
[ocaml_repr] is the tag corresponding to the constructor within the type.
the way it works in the ocaml runtime is by partitioning the constructors regarding
if they have some arguments or not, preserving the order, then assign increasing
index withing each partition.
Example:
{[
type t = (* no arg *) (* args *)
0
0
1
1
2
3
2
3
]}
*)
val ocaml_repr : (_, _) t -> int
*
Give back a way of constructing a value of that constructor from its arguments .
Examples :
{ [
type t =
| A of ( int * string )
| B of int * float
| C
| D of { x : int ; y : string }
] }
[ create ] will return something equivalent to :
tag_A : [ ( fun ( d : ( int * string ) - > A d ) ]
tag_B : [ ( fun ( i , f ) - > B ( i , f ) ) ]
tag_C : [ Const C ]
tag_D : [ ( fun ( x , y ) - > D { x ; y } ) ]
Give back a way of constructing a value of that constructor from its arguments.
Examples:
{[
type t =
| A of (int * string)
| B of int * float
| C
| D of { x : int; y : string }
]}
[create] will return something equivalent to:
tag_A : [Args (fun (d : (int * string) -> A d)]
tag_B : [Args (fun (i, f) -> B (i, f))]
tag_C : [Const C]
tag_D : [Args (fun (x, y) -> D { x; y })]
*)
val create : ('variant, 'args) t -> ('variant, 'args) create
(** return the type_name of the arguments. might be used to perform some lookup based
on it while building a computation for example *)
val tyid : (_, 'args) t -> 'args Typename.t
(** get the representation/computation of the arguments *)
val traverse : (_, 'args) t -> 'args X.t
used by the extension to build type witnesses , or by some internal parts of
typerep . you should feel bad if you need to use it in some user code
typerep. you should feel bad if you need to use it in some user code *)
val internal_use_only : ('a, 'b) Tag_internal.t -> ('a, 'b) t
end = struct
include Tag_internal
let label t = t.label
let arity t = t.arity
let args_labels t = t.args_labels
let index t = t.index
let ocaml_repr t = t.ocaml_repr
let create t = t.create
let tyid t = t.tyid
let traverse t = t.rep
let internal_use_only t = t
end
module Variant_internal = struct
type _ tag = Tag : ('variant, 'a) Tag.t -> 'variant tag
type _ value = Value : ('variant, 'a) Tag.t * 'a -> 'variant value
type 'a t = {
typename : 'a Typename.t;
tags : 'a tag array;
polymorphic : bool;
value : 'a -> 'a value;
}
end
module Variant : sig
(**
An existential type used to gather all the tags constituing a variant
type. the ['variant] parameter is the variant type, it is the same for all the
constructors of that variant type. The type of the parameters might be different
for each constructor and is thus existential
*)
type _ tag = Tag : ('variant, 'args) Tag.t -> 'variant tag
*
A similar existential constructor to [ _ tag ] but this one holds a value whose type
is the arguments of the tag constructor . A value of type [ ' a value ] is a pair of
( 1 ) a value of variant type [ ' a ] along with ( 2 ) some information about the
constructor within the type [ ' a ]
A similar existential constructor to [_ tag] but this one holds a value whose type
is the arguments of the tag constructor. A value of type ['a value] is a pair of
(1) a value of variant type ['a] along with (2) some information about the
constructor within the type ['a]
*)
type _ value = Value : ('variant, 'args) Tag.t * 'args -> 'variant value
(**
Witness of a variant type. The parameter is the type of the variant type witnessed.
*)
type 'a t
val typename_of_t : 'a t -> 'a Typename.t
(**
Returns the number of tags of this variant type definition.
*)
val length : 'a t -> int
(**
Get the nth tag of this variant type, indexed from 0.
*)
val tag : 'a t -> int -> 'a tag
(**
Distinguish polymorphic variants and standard variants. Typically, polymorphic
variants tags starts with the [`] character.
Example
polymorphic variant: type t = [ `A | `B ]
standard variant: type t = A | B
*)
val is_polymorphic : _ t -> bool
(**
Pattern matching on a value of this variant type.
*)
val value : 'a t -> 'a -> 'a value
(**
folding along the tags of the variant type
*)
val fold : 'a t -> init:'acc -> f:('acc -> 'a tag -> 'acc) -> 'acc
used by the extension to build type witnesses , or by some internal parts of
typerep . you should feel bad if you need to use it in some user code
typerep. you should feel bad if you need to use it in some user code *)
val internal_use_only : 'a Variant_internal.t -> 'a t
end = struct
include Variant_internal
let typename_of_t t = t.typename
let length t = Array.length t.tags
let tag t index = t.tags.(index)
let is_polymorphic t = t.polymorphic
let value t = t.value
let fold t ~init ~f = Array.fold_left f init t.tags
let internal_use_only t = t
end
module Field_internal = struct
type ('record, 'field) t = {
label : string;
rep : 'field X.t;
index : int;
tyid : 'field Typename.t;
get : ('record -> 'field);
(* set : ('record -> 'field -> unit) option; (\* mutable field *\) *)
is_mutable : bool;
}
end
*
Witness of a field , that is an item in a record type .
The first parameter is the record type , the second is the type of the field .
Example :
{ [
type t = { x : int ; y : string }
] }
This type has two fields . for each of them we 'll have a corresponding [ Field.t ]
val field_x : ( t , int ) Field.t
val field_y : ( t , string ) Field.t
Witness of a field, that is an item in a record type.
The first parameter is the record type, the second is the type of the field.
Example:
{[
type t = { x : int ; y : string }
]}
This type has two fields. for each of them we'll have a corresponding [Field.t]
val field_x : (t, int) Field.t
val field_y : (t, string) Field.t
*)
module Field : sig
type ('record, 'field) t
(**
The name of the field as it is given in the concrete syntax
Examples:
{[
{ x : int; (* "x" *)
foo : string; (* "foo" *)
bar : float; (* "bar" *)
}
]}
*)
val label : (_, _) t -> string
*
The 0 - based index of the field in the list of all fields for this record type .
Example :
{ [
type t = {
x : int ; ( * 0
The 0-based index of the field in the list of all fields for this record type.
Example:
{[
type t = {
x : int; (* 0 *)
1
2
}
]}
*)
val index : (_, _) t -> int
*
Field accessors . This corresponds to the dot operation .
[ Field.get t ] returns the field [ bar ] of the record value [ t ] , just the
same as [ t.bar ]
Field accessors. This corresponds to the dot operation.
[Field.get bar_field t] returns the field [bar] of the record value [t], just the
same as [t.bar]
*)
val get : ('record, 'field) t -> 'record -> 'field
(** return whether the field is mutable, i.e. whether its declaration is prefixed with
the keyword [mutable] *)
val is_mutable : (_, _) t -> bool
(** return the type_name of the arguments. Might be used to perform some lookup based
on it *)
val tyid : (_, 'field) t -> 'field Typename.t
(** get the computation of the arguments *)
val traverse : (_, 'field) t -> 'field X.t
used by the extension to build type witnesses , or by some internal parts of
typerep . you should feel bad if you need to use it in some user code
typerep. you should feel bad if you need to use it in some user code *)
val internal_use_only : ('a, 'b) Field_internal.t -> ('a, 'b) t
end = struct
include Field_internal
let label t = t.label
let index t = t.index
let get t = t.get
let is_mutable t = t.is_mutable
let tyid t = t.tyid
let traverse t = t.rep
let internal_use_only t = t
end
module Record_internal = struct
type _ field = Field : ('record, 'a) Field.t -> 'record field
type 'record fields = { get : 'field. ('record, 'field) Field.t -> 'field }
type 'a t = {
typename : 'a Typename.t;
fields : 'a field array;
has_double_array_tag : bool;
create : 'a fields -> 'a;
}
end
module Record : sig
(**
An existential type used to gather all the fields constituing a record type. the
['record] parameter is the record type, it is the same for all the field of that
record type. The type of the fields might be different for each field and is thus
existential.
*)
type _ field = Field : ('record, 'a) Field.t -> 'record field
(**
['record fields] is a type isomorphic to ['record]. This gives a way to get the
field value for each field of the record. The advantage of this representation is
that it is convenient for writing generic computations.
*)
type 'record fields = { get : 'field. ('record, 'field) Field.t -> 'field }
(**
Witness of a record type. The parameter is the type of the record type witnessed.
*)
type 'a t
val typename_of_t : 'a t -> 'a Typename.t
(**
Returns the number of fields of this record type definition.
*)
val length : 'a t -> int
(**
Get the nth field of this record type, indexed from 0.
*)
val field : 'a t -> int -> 'a field
*
This is a low level metadata regarding the way the ocaml compiler represent the
array underneath that is the runtime value of a record of type [ ' a ] given a witness
of type [ ' a t ] . [ has_double_array_tag w ] returns [ true ] if the array that
represents runtime values of this type is an optimized ocaml float array .
Typically , this will be true for record where all fields are statically known as to
be [ floats ] .
Note that you ca n't get this information dynamically by inspecting the typerep once
it is applied , because there is at this point no way to tell whether one of the
field is polymorphic in the type definition .
This is a low level metadata regarding the way the ocaml compiler represent the
array underneath that is the runtime value of a record of type ['a] given a witness
of type ['a t]. [has_double_array_tag w] returns [true] if the array that
represents runtime values of this type is an optimized ocaml float array.
Typically, this will be true for record where all fields are statically known as to
be [floats].
Note that you can't get this information dynamically by inspecting the typerep once
it is applied, because there is at this point no way to tell whether one of the
field is polymorphic in the type definition.
*)
val has_double_array_tag : _ t -> bool
*
Expose one direction of the isomorphism between a value of type [ ' a ] and a value of
type [ ' a fields ] . Basically , given an encoding way of accessing the value of all
the fields of a record , create that record and return it .
Expose one direction of the isomorphism between a value of type ['a] and a value of
type ['a fields]. Basically, given an encoding way of accessing the value of all
the fields of a record, create that record and return it.
*)
val create : 'a t -> 'a fields -> 'a
(**
folding along the tags of the variant type
*)
val fold : 'a t -> init:'acc -> f:('acc -> 'a field -> 'acc) -> 'acc
used by the extension to build type witnesses , or by some internal parts of
typerep . you should feel bad if you need to use it in some user code
typerep. you should feel bad if you need to use it in some user code *)
val internal_use_only : 'a Record_internal.t -> 'a t
end = struct
include Record_internal
let typename_of_t t = t.typename
let length t = Array.length t.fields
let field t index = t.fields.(index)
let has_double_array_tag t = t.has_double_array_tag
let create t = t.create
let fold t ~init ~f = Array.fold_left f init t.fields
let internal_use_only t = t
end
end
module type S = sig
type 'a t
include (module type of M (struct type 'a rep = 'a t type 'a t = 'a rep end))
end
| null | https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/typerep/lib/variant_and_record_intf.ml | ocaml | 0
4895187
no arg
args
* return the type_name of the arguments. might be used to perform some lookup based
on it while building a computation for example
* get the representation/computation of the arguments
*
An existential type used to gather all the tags constituing a variant
type. the ['variant] parameter is the variant type, it is the same for all the
constructors of that variant type. The type of the parameters might be different
for each constructor and is thus existential
*
Witness of a variant type. The parameter is the type of the variant type witnessed.
*
Returns the number of tags of this variant type definition.
*
Get the nth tag of this variant type, indexed from 0.
*
Distinguish polymorphic variants and standard variants. Typically, polymorphic
variants tags starts with the [`] character.
Example
polymorphic variant: type t = [ `A | `B ]
standard variant: type t = A | B
*
Pattern matching on a value of this variant type.
*
folding along the tags of the variant type
set : ('record -> 'field -> unit) option; (\* mutable field *\)
*
The name of the field as it is given in the concrete syntax
Examples:
{[
{ x : int; (* "x"
"foo"
"bar"
0
* return whether the field is mutable, i.e. whether its declaration is prefixed with
the keyword [mutable]
* return the type_name of the arguments. Might be used to perform some lookup based
on it
* get the computation of the arguments
*
An existential type used to gather all the fields constituing a record type. the
['record] parameter is the record type, it is the same for all the field of that
record type. The type of the fields might be different for each field and is thus
existential.
*
['record fields] is a type isomorphic to ['record]. This gives a way to get the
field value for each field of the record. The advantage of this representation is
that it is convenient for writing generic computations.
*
Witness of a record type. The parameter is the type of the record type witnessed.
*
Returns the number of fields of this record type definition.
*
Get the nth field of this record type, indexed from 0.
*
folding along the tags of the variant type
| *
Place holder for common Variants and Fields interface
Place holder for common Variants and Fields interface
*)
module M (X : sig
*
This functor is essentially there because we use this same interface in different
contexts , with different types for [ ' a t ] .
1 ) One use case for it is where [ ' a X.t = ' a Typerep.t ] . These interfaces are then
part of the type witness built for a type containing a record or a variant in its
structure . [ traverse ] will give a way of accessing the type representation for the
arguments of a variant or record type .
2 ) Another use case is for building " staged generic computations " . In that case , the
type [ ' a X.t ] is the type of the computation that is being built . [ traverse ]
returns the computation built for the argument . The interface no longer exports
the typerep of the arguments in hopes of enforcing that no typerep traversal
happens at runtime if the computation happen to be a function .
This functor is essentially there because we use this same interface in different
contexts, with different types for ['a t].
1) One use case for it is where ['a X.t = 'a Typerep.t]. These interfaces are then
part of the type witness built for a type containing a record or a variant in its
structure. [traverse] will give a way of accessing the type representation for the
arguments of a variant or record type.
2) Another use case is for building "staged generic computations". In that case, the
type ['a X.t] is the type of the computation that is being built. [traverse]
returns the computation built for the argument. The interface no longer exports
the typerep of the arguments in hopes of enforcing that no typerep traversal
happens at runtime if the computation happen to be a function.
*)
type 'a t
end) = struct
The functions prefixed by [ internal ] as well as the module suffixed by [ _ internal ]
are used by the code generated by the extension [ with typerep ] as well as some
internals of the typerep library . Do not consider using these somewhere else . They
should ideally not be exported outside the typerep library , but the generated code
needs somehow to access this , even outside .
are used by the code generated by the camlp4 extension [with typerep] as well as some
internals of the typerep library. Do not consider using these somewhere else. They
should ideally not be exported outside the typerep library, but the generated code
needs somehow to access this, even outside. *)
module Tag_internal = struct
type ('variant, 'args) create = Args of ('args -> 'variant) | Const of 'variant
type ('variant, 'args) t =
{ label : string
; rep : 'args X.t
; arity : int
; args_labels: string list
; index : int
; ocaml_repr : int
; tyid : 'args Typename.t
; create : ('variant, 'args) create
}
end
*
Witness of a tag , that is an item in a variant type , also called an " applied
variant Constructor "
The first parameter is the variant type , the second is the type of the tag
parameters . Example :
{ [
type t =
| A of ( int * string )
| B of string
| C of { x : int ; y : string }
] }
this type has three constructors . For each of them we 'll have a corresponding
[ Tag.t ] :
{ [
val tag_A : ( t , ( int * string ) ) Tag.t
val tag_B : ( t , string ) Tag.t
val tag_C : ( t , ( int * string ) ) Tag.t
] }
Note , inline record in variant are typed as if their definition was using tuples ,
without the parenthesis . This is consistent with their runtime representation . But
the distinction is carried and available for introspection as part of the [ Tag.t ] .
See [ args_labels ] .
Witness of a tag, that is an item in a variant type, also called an "applied
variant Constructor"
The first parameter is the variant type, the second is the type of the tag
parameters. Example:
{[
type t =
| A of (int * string)
| B of string
| C of { x : int; y : string }
]}
this type has three constructors. For each of them we'll have a corresponding
[Tag.t]:
{[
val tag_A : (t, (int * string)) Tag.t
val tag_B : (t, string ) Tag.t
val tag_C : (t, (int * string)) Tag.t
]}
Note, inline record in variant are typed as if their definition was using tuples,
without the parenthesis. This is consistent with their runtime representation. But
the distinction is carried and available for introspection as part of the [Tag.t].
See [args_labels]. *)
module Tag : sig
type ('variant, 'args) create = Args of ('args -> 'variant) | Const of 'variant
type ('variant, 'args) t
*
The name of the constructor as it is given in the concrete syntax
Examples :
{ v
Constructor | label
-------------------------
| A of int | " A "
| ` a of int | " a "
| ` A of int | " A "
| A of { x : int } | " A "
v }
for standard variant , the ocaml syntax implies that this label will always starts
with a capital letter . For polymorphic variants , this might be a lowercase char .
For polymorphic variant , this label does not include the [ ` ] character .
The name of the constructor as it is given in the concrete syntax
Examples:
{v
Constructor | label
-------------------------
| A of int | "A"
| `a of int | "a"
| `A of int | "A"
| A of { x : int } | "A"
v}
for standard variant, the ocaml syntax implies that this label will always starts
with a capital letter. For polymorphic variants, this might be a lowercase char.
For polymorphic variant, this label does not include the [`] character.
*)
val label : (_, _) t -> string
*
The size of the ocaml heap block containing the arguments
Examples :
{ v
0 : | A | ' A
1 : | A of int | ` A of int | A of ( int * int ) | ` A of ( int * int )
| ` A of int * int
| A of { x : int }
2 : | A of int * float
| A of { x : int ; y : string }
etc .
v }
The size of the ocaml heap block containing the arguments
Examples:
{v
0: | A | 'A
1: | A of int | `A of int | A of (int * int) | `A of (int * int)
| `A of int * int
| A of { x : int}
2: | A of int * float
| A of { x : int; y : string }
etc.
v}
*)
val arity : (_, _) t -> int
* The label of the fields for inline records . For other forms of tags , this is the
empty list . When this returns a non empty list , the length of the returned list
is equal to the arity .
Example :
{ v
( 1 ) Empty :
| A | ' A
| A of int | ` A of int | A of ( int * int ) | ` A of ( int * int )
| ` A of int * int
| A of int * float
( 2 ) Non empty :
| A of { x : int } - > [ " x " ]
| A of { x : int ; y : string } - > [ " x " ; " y " ]
v }
empty list. When this returns a non empty list, the length of the returned list
is equal to the arity.
Example:
{v
(1) Empty:
| A | 'A
| A of int | `A of int | A of (int * int) | `A of (int * int)
| `A of int * int
| A of int * float
(2) Non empty:
| A of { x : int } -> [ "x" ]
| A of { x : int; y : string } -> [ "x" ; "y" ]
v}
*)
val args_labels : (_, _) t -> string list
*
The index of the constructor in the list of all the variant type 's constructors
Examples :
{ [
type t =
| A of int ( * 0
The index of the constructor in the list of all the variant type's constructors
Examples:
{[
type t =
1
2
3
4
]}
*)
val index : (_, _) t -> int
*
ocaml_repr is related to the runtime of objects . this is essentially a way of
giving one the ability to rebuild dynamically an [ Obj.t ] representing a tag .
Polymorphic variants :
---------------------
[ ocaml_repr ] is the hash of the label , as done by the compiler .
Example :
print_int ( Obj.magic ` bar ) ( * 4895187
ocaml_repr is related to the runtime of objects. this is essentially a way of
giving one the ability to rebuild dynamically an [Obj.t] representing a tag.
Polymorphic variants:
---------------------
[ocaml_repr] is the hash of the label, as done by the compiler.
Example:
5097222
Standards variants:
-------------------
[ocaml_repr] is the tag corresponding to the constructor within the type.
the way it works in the ocaml runtime is by partitioning the constructors regarding
if they have some arguments or not, preserving the order, then assign increasing
index withing each partition.
Example:
{[
0
0
1
1
2
3
2
3
]}
*)
val ocaml_repr : (_, _) t -> int
*
Give back a way of constructing a value of that constructor from its arguments .
Examples :
{ [
type t =
| A of ( int * string )
| B of int * float
| C
| D of { x : int ; y : string }
] }
[ create ] will return something equivalent to :
tag_A : [ ( fun ( d : ( int * string ) - > A d ) ]
tag_B : [ ( fun ( i , f ) - > B ( i , f ) ) ]
tag_C : [ Const C ]
tag_D : [ ( fun ( x , y ) - > D { x ; y } ) ]
Give back a way of constructing a value of that constructor from its arguments.
Examples:
{[
type t =
| A of (int * string)
| B of int * float
| C
| D of { x : int; y : string }
]}
[create] will return something equivalent to:
tag_A : [Args (fun (d : (int * string) -> A d)]
tag_B : [Args (fun (i, f) -> B (i, f))]
tag_C : [Const C]
tag_D : [Args (fun (x, y) -> D { x; y })]
*)
val create : ('variant, 'args) t -> ('variant, 'args) create
val tyid : (_, 'args) t -> 'args Typename.t
val traverse : (_, 'args) t -> 'args X.t
used by the extension to build type witnesses , or by some internal parts of
typerep . you should feel bad if you need to use it in some user code
typerep. you should feel bad if you need to use it in some user code *)
val internal_use_only : ('a, 'b) Tag_internal.t -> ('a, 'b) t
end = struct
include Tag_internal
let label t = t.label
let arity t = t.arity
let args_labels t = t.args_labels
let index t = t.index
let ocaml_repr t = t.ocaml_repr
let create t = t.create
let tyid t = t.tyid
let traverse t = t.rep
let internal_use_only t = t
end
module Variant_internal = struct
type _ tag = Tag : ('variant, 'a) Tag.t -> 'variant tag
type _ value = Value : ('variant, 'a) Tag.t * 'a -> 'variant value
type 'a t = {
typename : 'a Typename.t;
tags : 'a tag array;
polymorphic : bool;
value : 'a -> 'a value;
}
end
module Variant : sig
type _ tag = Tag : ('variant, 'args) Tag.t -> 'variant tag
*
A similar existential constructor to [ _ tag ] but this one holds a value whose type
is the arguments of the tag constructor . A value of type [ ' a value ] is a pair of
( 1 ) a value of variant type [ ' a ] along with ( 2 ) some information about the
constructor within the type [ ' a ]
A similar existential constructor to [_ tag] but this one holds a value whose type
is the arguments of the tag constructor. A value of type ['a value] is a pair of
(1) a value of variant type ['a] along with (2) some information about the
constructor within the type ['a]
*)
type _ value = Value : ('variant, 'args) Tag.t * 'args -> 'variant value
type 'a t
val typename_of_t : 'a t -> 'a Typename.t
val length : 'a t -> int
val tag : 'a t -> int -> 'a tag
val is_polymorphic : _ t -> bool
val value : 'a t -> 'a -> 'a value
val fold : 'a t -> init:'acc -> f:('acc -> 'a tag -> 'acc) -> 'acc
used by the extension to build type witnesses , or by some internal parts of
typerep . you should feel bad if you need to use it in some user code
typerep. you should feel bad if you need to use it in some user code *)
val internal_use_only : 'a Variant_internal.t -> 'a t
end = struct
include Variant_internal
let typename_of_t t = t.typename
let length t = Array.length t.tags
let tag t index = t.tags.(index)
let is_polymorphic t = t.polymorphic
let value t = t.value
let fold t ~init ~f = Array.fold_left f init t.tags
let internal_use_only t = t
end
module Field_internal = struct
type ('record, 'field) t = {
label : string;
rep : 'field X.t;
index : int;
tyid : 'field Typename.t;
get : ('record -> 'field);
is_mutable : bool;
}
end
*
Witness of a field , that is an item in a record type .
The first parameter is the record type , the second is the type of the field .
Example :
{ [
type t = { x : int ; y : string }
] }
This type has two fields . for each of them we 'll have a corresponding [ Field.t ]
val field_x : ( t , int ) Field.t
val field_y : ( t , string ) Field.t
Witness of a field, that is an item in a record type.
The first parameter is the record type, the second is the type of the field.
Example:
{[
type t = { x : int ; y : string }
]}
This type has two fields. for each of them we'll have a corresponding [Field.t]
val field_x : (t, int) Field.t
val field_y : (t, string) Field.t
*)
module Field : sig
type ('record, 'field) t
}
]}
*)
val label : (_, _) t -> string
*
The 0 - based index of the field in the list of all fields for this record type .
Example :
{ [
type t = {
x : int ; ( * 0
The 0-based index of the field in the list of all fields for this record type.
Example:
{[
type t = {
1
2
}
]}
*)
val index : (_, _) t -> int
*
Field accessors . This corresponds to the dot operation .
[ Field.get t ] returns the field [ bar ] of the record value [ t ] , just the
same as [ t.bar ]
Field accessors. This corresponds to the dot operation.
[Field.get bar_field t] returns the field [bar] of the record value [t], just the
same as [t.bar]
*)
val get : ('record, 'field) t -> 'record -> 'field
val is_mutable : (_, _) t -> bool
val tyid : (_, 'field) t -> 'field Typename.t
val traverse : (_, 'field) t -> 'field X.t
used by the extension to build type witnesses , or by some internal parts of
typerep . you should feel bad if you need to use it in some user code
typerep. you should feel bad if you need to use it in some user code *)
val internal_use_only : ('a, 'b) Field_internal.t -> ('a, 'b) t
end = struct
include Field_internal
let label t = t.label
let index t = t.index
let get t = t.get
let is_mutable t = t.is_mutable
let tyid t = t.tyid
let traverse t = t.rep
let internal_use_only t = t
end
module Record_internal = struct
type _ field = Field : ('record, 'a) Field.t -> 'record field
type 'record fields = { get : 'field. ('record, 'field) Field.t -> 'field }
type 'a t = {
typename : 'a Typename.t;
fields : 'a field array;
has_double_array_tag : bool;
create : 'a fields -> 'a;
}
end
module Record : sig
type _ field = Field : ('record, 'a) Field.t -> 'record field
type 'record fields = { get : 'field. ('record, 'field) Field.t -> 'field }
type 'a t
val typename_of_t : 'a t -> 'a Typename.t
val length : 'a t -> int
val field : 'a t -> int -> 'a field
*
This is a low level metadata regarding the way the ocaml compiler represent the
array underneath that is the runtime value of a record of type [ ' a ] given a witness
of type [ ' a t ] . [ has_double_array_tag w ] returns [ true ] if the array that
represents runtime values of this type is an optimized ocaml float array .
Typically , this will be true for record where all fields are statically known as to
be [ floats ] .
Note that you ca n't get this information dynamically by inspecting the typerep once
it is applied , because there is at this point no way to tell whether one of the
field is polymorphic in the type definition .
This is a low level metadata regarding the way the ocaml compiler represent the
array underneath that is the runtime value of a record of type ['a] given a witness
of type ['a t]. [has_double_array_tag w] returns [true] if the array that
represents runtime values of this type is an optimized ocaml float array.
Typically, this will be true for record where all fields are statically known as to
be [floats].
Note that you can't get this information dynamically by inspecting the typerep once
it is applied, because there is at this point no way to tell whether one of the
field is polymorphic in the type definition.
*)
val has_double_array_tag : _ t -> bool
*
Expose one direction of the isomorphism between a value of type [ ' a ] and a value of
type [ ' a fields ] . Basically , given an encoding way of accessing the value of all
the fields of a record , create that record and return it .
Expose one direction of the isomorphism between a value of type ['a] and a value of
type ['a fields]. Basically, given an encoding way of accessing the value of all
the fields of a record, create that record and return it.
*)
val create : 'a t -> 'a fields -> 'a
val fold : 'a t -> init:'acc -> f:('acc -> 'a field -> 'acc) -> 'acc
used by the extension to build type witnesses , or by some internal parts of
typerep . you should feel bad if you need to use it in some user code
typerep. you should feel bad if you need to use it in some user code *)
val internal_use_only : 'a Record_internal.t -> 'a t
end = struct
include Record_internal
let typename_of_t t = t.typename
let length t = Array.length t.fields
let field t index = t.fields.(index)
let has_double_array_tag t = t.has_double_array_tag
let create t = t.create
let fold t ~init ~f = Array.fold_left f init t.fields
let internal_use_only t = t
end
end
module type S = sig
type 'a t
include (module type of M (struct type 'a rep = 'a t type 'a t = 'a rep end))
end
|
cfdc523d5b34ca0b097527b04494c2be95af3df5c7c2058b929483ab6bf0bcf0 | WormBase/wormbase_rest | do_term.clj | (ns rest-api.classes.do-term
(:require
[rest-api.classes.gene.widgets.external-links :as external-links]
[rest-api.classes.do-term.widgets.overview :as overview]
[rest-api.classes.do-term.widgets.ontology-browser :as ontology-browser]
[rest-api.classes.graphview.widget :as graphview]
[rest-api.routing :as routing]))
(routing/defroutes
{:entity-ns "do-term"
:uri-name "disease"
:widget
{:overview overview/widget
:graphview graphview/widget
:ontology_browser ontology-browser/widget
:external_links external-links/widget}})
| null | https://raw.githubusercontent.com/WormBase/wormbase_rest/e51026f35b87d96260b62ddb5458a81ee911bf3a/src/rest_api/classes/do_term.clj | clojure | (ns rest-api.classes.do-term
(:require
[rest-api.classes.gene.widgets.external-links :as external-links]
[rest-api.classes.do-term.widgets.overview :as overview]
[rest-api.classes.do-term.widgets.ontology-browser :as ontology-browser]
[rest-api.classes.graphview.widget :as graphview]
[rest-api.routing :as routing]))
(routing/defroutes
{:entity-ns "do-term"
:uri-name "disease"
:widget
{:overview overview/widget
:graphview graphview/widget
:ontology_browser ontology-browser/widget
:external_links external-links/widget}})
|
|
366f47cf2277d16ad89366094474a78d511fcd7d66c8934e85f36628868fb71a | cgoldammer/chess-database-backend | Application.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
module Application
( App
, app
, routes
, auth
, service
, sess
, resetUser
) where
import AppTypes
import Control.Lens (makeLenses, view)
import Control.Monad (join, liftM3, when)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.State.Class (get)
import qualified Data.ByteString.Char8 as B (ByteString, pack, unpack)
import Data.Map (Map)
import qualified Data.Map as Map (lookup)
import Data.Maybe (fromMaybe, listToMaybe)
import qualified Data.Text as T (Text, pack, unpack)
import Database.Persist.Sql (runMigrationUnsafe)
import Debug.Trace (trace)
import qualified Services.Service as S
import Snap.Core
( Method(..)
, getRequest
, method
, modifyResponse
, redirect
, rqParams
, setResponseStatus
, writeBS
)
import Snap.Snaplet
( Handler
, Snaplet
, SnapletInit
, addRoutes
, makeSnaplet
, nestSnaplet
, snapletValue
, subSnaplet
, with
, withTop
)
import Snap.Snaplet.Auth
( AuthFailure
, AuthManager(..)
, AuthUser
, clearPasswordResetToken
, currentUser
, loginUser
, logout
, lookupByLogin
, registerUser
, save
, setPassword
, setPasswordResetToken
, userLogin
, userResetToken
)
import Snap.Snaplet.Auth.Backends.Persistent
( initPersistAuthManager
, migrateAuth
)
import Snap.Snaplet.Heist (HasHeist, Heist, heistInit, heistLens)
import Snap.Snaplet.Persistent (PersistState, persistPool)
import Snap.Snaplet.Session (SessionManager)
import Snap.Snaplet.Session.Backends.CookieSession (initCookieSessionManager)
data App = App
{ _heist :: Snaplet (Heist App)
, _sess :: Snaplet SessionManager
, _db :: Snaplet PersistState
, _auth :: Snaplet (AuthManager App)
, _service :: Snaplet (S.Service App)
}
makeLenses ''App
instance HasHeist App where
heistLens = subSnaplet heist
app :: Settings -> SnapletInit App App
app settings =
makeSnaplet "app" "An snaplet example application." Nothing $ do
let dbName = appDBName settings
h <- nestSnaplet "" heist $ heistInit "templates"
s <-
nestSnaplet "sess" sess $
initCookieSessionManager "site_key.txt" "sess" Nothing (Just 3600)
d <-
nestSnaplet "db" db $
S.initPersistWithDB dbName (runMigrationUnsafe migrateAuth)
a :: Snaplet (AuthManager App) <-
nestSnaplet "auth" auth $
initPersistAuthManager sess (persistPool $ view snapletValue d)
let user = view snapletValue a
let login = T.unpack . userLogin <$> activeUser user
serviceSnaplet <- nestSnaplet "api" service $ S.serviceInit dbName auth
addRoutes $ routes $ showLogin settings
return $ App h s d a serviceSnaplet
routes :: Bool -> [(B.ByteString, Handler App App ())]
routes False = []
routes True = routes False ++ loginRoutes
loginRoutes :: [(B.ByteString, Handler App App ())]
loginRoutes =
[ ("login", with auth handleLoginSubmit)
, ("register", with auth handleNewUser)
, ("logout", with auth handleLogout >> resetUser)
, ("resetPasswordData", with auth resetPasswordHandler)
-- disabled until I think through how to avoid spamming
, ( " sendPasswordResetEmail " , with auth sendPasswordResetHandler )
]
writeLoginSuccess :: Handler b (AuthManager b) ()
writeLoginSuccess = do
user <- currentUser
let login = fmap (T.unpack . userLogin) user :: Maybe String
modifyResponse $ setResponseStatus 200 "Success"
writeBS $ B.pack $ fromMaybe "" login
writeLoginFailure :: AuthFailure -> Handler b (AuthManager b) ()
writeLoginFailure failure = do
modifyResponse $ setResponseStatus 403 "Login failed"
writeBS $ B.pack $ show failure
handleLoginSubmit :: Handler App (AuthManager App) ()
handleLoginSubmit = do
loginUser "email" "password" Nothing writeLoginFailure writeLoginSuccess
user <- currentUser
let login = fmap (T.unpack . userLogin) user
liftIO $ print $ "Changing user to" ++ show login
return ()
resetUser :: Handler App App ()
resetUser = do
withTop auth logout
return ()
handleLogout :: Handler App (AuthManager App) ()
handleLogout = logout
registerNew :: Handler App (AuthManager App) (Either AuthFailure AuthUser)
registerNew = method POST $ registerUser "email" "password"
handleNewUser :: Handler App (AuthManager App) ()
handleNewUser = do
res <- registerNew
-- Registering creates a `snap_auth_user` in the database. However, we
also want to create an ` app_user ` that is linked to the ` snap_auth_user ` ,
because this allows us to assume a one - to - one relationship between
-- the tables
trace (show res) $
case res of
Right authUser -> do
let usId = userLogin authUser
withTop service $ S.createAppUser usId
handleLoginSubmit
writeLoginSuccess
Left authFail -> writeLoginFailure authFail
-- Logic for resetting passwords. This works as follows:
1 . A request is sent to ' /sendPasswordResetEmail?email= '
2 . The backend creates a password reset token for the user
3 . The backend sends out an email linking to
-- '/resetpassword?email...&token=..."
4 . The form collects a new password and submits it
-- to "/resetPasswordData?email...&token=...&password=..."
5 . The password is reset , the token for the user is destroyed
6 . The server forwards to /passwordgood
-- The endpoints "/resetpassword" and "/passwordgood" are not defined here
-- but are automatically created from the corresponding heist templates.
getProperty :: String -> Map B.ByteString [B.ByteString] -> Maybe T.Text
getProperty name queryMap =
fmap (T.pack . B.unpack) $
listToMaybe =<< Map.lookup (B.pack name) queryMap
resetWithUser :: T.Text -> Handler b (AuthManager b) ()
resetWithUser login = do
request <- getRequest
let params = rqParams request
let token = getProperty "token" params
manager <- get
let getUser AuthManager {backend = b} = lookupByLogin b login
maybeUser <- liftIO $ getUser manager
let newPass = getProperty "password" params
let resetter = liftM3 (resetPassForUser manager) token maybeUser newPass
fromMaybe (return ()) resetter
clearPasswordResetToken login
return ()
resetPassForUser ::
AuthManager b
-> T.Text
-> AuthUser
-> T.Text
-> Handler b (AuthManager b) ()
resetPassForUser manager token user newPass = do
let storedToken = userResetToken user
when (storedToken == Just token) $ do
updatedUser <- liftIO $ setPassword user $ B.pack $ T.unpack newPass
liftIO $ save manager updatedUser
let login = userLogin user
clearPasswordResetToken login
redirect "/snap_prod/passwordchangegood"
resetPasswordHandler :: Handler b (AuthManager b) ()
resetPasswordHandler = do
request <- getRequest
let params = rqParams request
let user = getProperty "email" params
maybe (return ()) resetWithUser user
return ()
sendPasswordResetHandler :: Handler b (AuthManager b) ()
sendPasswordResetHandler = do
request <- getRequest
let params = rqParams request
let user = T.unpack <$> getProperty "email" params
maybe (return ()) sendPasswordResetEmail user
sendPasswordResetEmail :: String -> Handler b (AuthManager b) ()
sendPasswordResetEmail email = do
token <- setPasswordResetToken (T.pack email)
maybe (return ()) (sendEmailForToken email) token
sendEmailForToken :: String -> T.Text -> Handler b (AuthManager b) ()
sendEmailForToken email token = do
let url = "?"
let fullUrl = url ++ "email=" ++ email ++ "&token=" ++ T.unpack token
let body = "Reset password link for chess insights \n " ++ fullUrl
liftIO $ S.trySendEmail "Password reset for chessinsights.org" email body
| null | https://raw.githubusercontent.com/cgoldammer/chess-database-backend/dbb0f61817520302ea975a9ec4b444d92115f7cf/src/Application.hs | haskell | # LANGUAGE OverloadedStrings #
disabled until I think through how to avoid spamming
Registering creates a `snap_auth_user` in the database. However, we
the tables
Logic for resetting passwords. This works as follows:
'/resetpassword?email...&token=..."
to "/resetPasswordData?email...&token=...&password=..."
The endpoints "/resetpassword" and "/passwordgood" are not defined here
but are automatically created from the corresponding heist templates. | # LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
module Application
( App
, app
, routes
, auth
, service
, sess
, resetUser
) where
import AppTypes
import Control.Lens (makeLenses, view)
import Control.Monad (join, liftM3, when)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.State.Class (get)
import qualified Data.ByteString.Char8 as B (ByteString, pack, unpack)
import Data.Map (Map)
import qualified Data.Map as Map (lookup)
import Data.Maybe (fromMaybe, listToMaybe)
import qualified Data.Text as T (Text, pack, unpack)
import Database.Persist.Sql (runMigrationUnsafe)
import Debug.Trace (trace)
import qualified Services.Service as S
import Snap.Core
( Method(..)
, getRequest
, method
, modifyResponse
, redirect
, rqParams
, setResponseStatus
, writeBS
)
import Snap.Snaplet
( Handler
, Snaplet
, SnapletInit
, addRoutes
, makeSnaplet
, nestSnaplet
, snapletValue
, subSnaplet
, with
, withTop
)
import Snap.Snaplet.Auth
( AuthFailure
, AuthManager(..)
, AuthUser
, clearPasswordResetToken
, currentUser
, loginUser
, logout
, lookupByLogin
, registerUser
, save
, setPassword
, setPasswordResetToken
, userLogin
, userResetToken
)
import Snap.Snaplet.Auth.Backends.Persistent
( initPersistAuthManager
, migrateAuth
)
import Snap.Snaplet.Heist (HasHeist, Heist, heistInit, heistLens)
import Snap.Snaplet.Persistent (PersistState, persistPool)
import Snap.Snaplet.Session (SessionManager)
import Snap.Snaplet.Session.Backends.CookieSession (initCookieSessionManager)
data App = App
{ _heist :: Snaplet (Heist App)
, _sess :: Snaplet SessionManager
, _db :: Snaplet PersistState
, _auth :: Snaplet (AuthManager App)
, _service :: Snaplet (S.Service App)
}
makeLenses ''App
instance HasHeist App where
heistLens = subSnaplet heist
app :: Settings -> SnapletInit App App
app settings =
makeSnaplet "app" "An snaplet example application." Nothing $ do
let dbName = appDBName settings
h <- nestSnaplet "" heist $ heistInit "templates"
s <-
nestSnaplet "sess" sess $
initCookieSessionManager "site_key.txt" "sess" Nothing (Just 3600)
d <-
nestSnaplet "db" db $
S.initPersistWithDB dbName (runMigrationUnsafe migrateAuth)
a :: Snaplet (AuthManager App) <-
nestSnaplet "auth" auth $
initPersistAuthManager sess (persistPool $ view snapletValue d)
let user = view snapletValue a
let login = T.unpack . userLogin <$> activeUser user
serviceSnaplet <- nestSnaplet "api" service $ S.serviceInit dbName auth
addRoutes $ routes $ showLogin settings
return $ App h s d a serviceSnaplet
routes :: Bool -> [(B.ByteString, Handler App App ())]
routes False = []
routes True = routes False ++ loginRoutes
loginRoutes :: [(B.ByteString, Handler App App ())]
loginRoutes =
[ ("login", with auth handleLoginSubmit)
, ("register", with auth handleNewUser)
, ("logout", with auth handleLogout >> resetUser)
, ("resetPasswordData", with auth resetPasswordHandler)
, ( " sendPasswordResetEmail " , with auth sendPasswordResetHandler )
]
writeLoginSuccess :: Handler b (AuthManager b) ()
writeLoginSuccess = do
user <- currentUser
let login = fmap (T.unpack . userLogin) user :: Maybe String
modifyResponse $ setResponseStatus 200 "Success"
writeBS $ B.pack $ fromMaybe "" login
writeLoginFailure :: AuthFailure -> Handler b (AuthManager b) ()
writeLoginFailure failure = do
modifyResponse $ setResponseStatus 403 "Login failed"
writeBS $ B.pack $ show failure
handleLoginSubmit :: Handler App (AuthManager App) ()
handleLoginSubmit = do
loginUser "email" "password" Nothing writeLoginFailure writeLoginSuccess
user <- currentUser
let login = fmap (T.unpack . userLogin) user
liftIO $ print $ "Changing user to" ++ show login
return ()
resetUser :: Handler App App ()
resetUser = do
withTop auth logout
return ()
handleLogout :: Handler App (AuthManager App) ()
handleLogout = logout
registerNew :: Handler App (AuthManager App) (Either AuthFailure AuthUser)
registerNew = method POST $ registerUser "email" "password"
handleNewUser :: Handler App (AuthManager App) ()
handleNewUser = do
res <- registerNew
also want to create an ` app_user ` that is linked to the ` snap_auth_user ` ,
because this allows us to assume a one - to - one relationship between
trace (show res) $
case res of
Right authUser -> do
let usId = userLogin authUser
withTop service $ S.createAppUser usId
handleLoginSubmit
writeLoginSuccess
Left authFail -> writeLoginFailure authFail
1 . A request is sent to ' /sendPasswordResetEmail?email= '
2 . The backend creates a password reset token for the user
3 . The backend sends out an email linking to
4 . The form collects a new password and submits it
5 . The password is reset , the token for the user is destroyed
6 . The server forwards to /passwordgood
getProperty :: String -> Map B.ByteString [B.ByteString] -> Maybe T.Text
getProperty name queryMap =
fmap (T.pack . B.unpack) $
listToMaybe =<< Map.lookup (B.pack name) queryMap
resetWithUser :: T.Text -> Handler b (AuthManager b) ()
resetWithUser login = do
request <- getRequest
let params = rqParams request
let token = getProperty "token" params
manager <- get
let getUser AuthManager {backend = b} = lookupByLogin b login
maybeUser <- liftIO $ getUser manager
let newPass = getProperty "password" params
let resetter = liftM3 (resetPassForUser manager) token maybeUser newPass
fromMaybe (return ()) resetter
clearPasswordResetToken login
return ()
resetPassForUser ::
AuthManager b
-> T.Text
-> AuthUser
-> T.Text
-> Handler b (AuthManager b) ()
resetPassForUser manager token user newPass = do
let storedToken = userResetToken user
when (storedToken == Just token) $ do
updatedUser <- liftIO $ setPassword user $ B.pack $ T.unpack newPass
liftIO $ save manager updatedUser
let login = userLogin user
clearPasswordResetToken login
redirect "/snap_prod/passwordchangegood"
resetPasswordHandler :: Handler b (AuthManager b) ()
resetPasswordHandler = do
request <- getRequest
let params = rqParams request
let user = getProperty "email" params
maybe (return ()) resetWithUser user
return ()
sendPasswordResetHandler :: Handler b (AuthManager b) ()
sendPasswordResetHandler = do
request <- getRequest
let params = rqParams request
let user = T.unpack <$> getProperty "email" params
maybe (return ()) sendPasswordResetEmail user
sendPasswordResetEmail :: String -> Handler b (AuthManager b) ()
sendPasswordResetEmail email = do
token <- setPasswordResetToken (T.pack email)
maybe (return ()) (sendEmailForToken email) token
sendEmailForToken :: String -> T.Text -> Handler b (AuthManager b) ()
sendEmailForToken email token = do
let url = "?"
let fullUrl = url ++ "email=" ++ email ++ "&token=" ++ T.unpack token
let body = "Reset password link for chess insights \n " ++ fullUrl
liftIO $ S.trySendEmail "Password reset for chessinsights.org" email body
|
785b01c66890726a48efbedde769c24d3d1f5a9bf21b7c3562592a74257c7a19 | fission-codes/fission | ExchangeKey.hs | module Fission.Web.Server.Handler.User.ExchangeKey (handler) where
import RIO.NonEmpty
import Servant.Server.Generic
import Fission.Prelude
import qualified Fission.Web.API.User.ExchangeKey.Types as ExchangeKey
import Fission.Web.Server.Authorization.Types
import qualified Fission.Web.Server.Error as Web.Error
import qualified Fission.Web.Server.User as User
handler ::
( MonadTime m
, MonadLogger m
, MonadThrow m
, User.Modifier m
)
=> ExchangeKey.Routes (AsServerT m)
handler =
ExchangeKey.Routes {..}
where
add key Authorization {about = Entity userId _} = do
now <- currentTime
keys <- Web.Error.ensureM $ User.addExchangeKey userId key now
case nonEmpty keys of
Nothing -> return [key]
Just allKeys -> return allKeys
remove key Authorization {about = Entity userId _} = do
now <- currentTime
Web.Error.ensureM $ User.removeExchangeKey userId key now
| null | https://raw.githubusercontent.com/fission-codes/fission/7e69c0da210a77412c96631f5ff7ef1b38240d37/fission-web-server/library/Fission/Web/Server/Handler/User/ExchangeKey.hs | haskell | module Fission.Web.Server.Handler.User.ExchangeKey (handler) where
import RIO.NonEmpty
import Servant.Server.Generic
import Fission.Prelude
import qualified Fission.Web.API.User.ExchangeKey.Types as ExchangeKey
import Fission.Web.Server.Authorization.Types
import qualified Fission.Web.Server.Error as Web.Error
import qualified Fission.Web.Server.User as User
handler ::
( MonadTime m
, MonadLogger m
, MonadThrow m
, User.Modifier m
)
=> ExchangeKey.Routes (AsServerT m)
handler =
ExchangeKey.Routes {..}
where
add key Authorization {about = Entity userId _} = do
now <- currentTime
keys <- Web.Error.ensureM $ User.addExchangeKey userId key now
case nonEmpty keys of
Nothing -> return [key]
Just allKeys -> return allKeys
remove key Authorization {about = Entity userId _} = do
now <- currentTime
Web.Error.ensureM $ User.removeExchangeKey userId key now
|
|
6d701a195a7c48df8f0e7dcc8ca07d4f9af7a195ee9e87aa85ba317c7309a4ea | kovtun1/DependenciesGraph | swift.ml | type swift_token =
| Type of string
| Word of string
| Protocol
| Class
| Extension
| Enum
| Struct
| Colon
| Comma
| Dot
| OpenCurlyBrace
| CloseCurlyBrace
let string_of_swift_token token =
match token with
| Type name ->
"TYPE(" ^ name ^ ")"
| Word name ->
"WORD(" ^ name ^ ")"
| Protocol ->
"PROTOCOL"
| Class ->
"CLASS"
| Extension ->
"EXTENSION"
| Enum ->
"ENUM"
| Struct ->
"STRUCT"
| Colon ->
"COLON"
| Comma ->
"COMMA"
| Dot ->
"DOT"
| OpenCurlyBrace ->
"OPEN_CURLY_BRACE\n"
| CloseCurlyBrace ->
"CLOSE_CURLY_BRACE\n"
| null | https://raw.githubusercontent.com/kovtun1/DependenciesGraph/cec4d2b7a29746ad7b61d76b3662afd5c39f26ff/swift.ml | ocaml | type swift_token =
| Type of string
| Word of string
| Protocol
| Class
| Extension
| Enum
| Struct
| Colon
| Comma
| Dot
| OpenCurlyBrace
| CloseCurlyBrace
let string_of_swift_token token =
match token with
| Type name ->
"TYPE(" ^ name ^ ")"
| Word name ->
"WORD(" ^ name ^ ")"
| Protocol ->
"PROTOCOL"
| Class ->
"CLASS"
| Extension ->
"EXTENSION"
| Enum ->
"ENUM"
| Struct ->
"STRUCT"
| Colon ->
"COLON"
| Comma ->
"COMMA"
| Dot ->
"DOT"
| OpenCurlyBrace ->
"OPEN_CURLY_BRACE\n"
| CloseCurlyBrace ->
"CLOSE_CURLY_BRACE\n"
|
|
bff506a772f3cc358d9ce190c885f9b18b1ee06c38e0845bdd8f450709a16618 | erlyvideo/rack | rack_worker.erl | Copyright ( c ) 2011 , < >
%%
%% Permission to use, copy, modify, and/or distribute this software for any
%% purpose with or without fee is hereby granted, provided that the above
%% copyright notice and this permission notice appear in all copies.
%%
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-module(rack_worker).
-author('Max Lapshin <>').
-include("log.hrl").
-export([start_link/0, start_link/1, request/3]).
-export([init/1, handle_call/3, handle_info/2, terminate/2]).
start_link() ->
start_link([]).
start_link(Options) ->
gen_server:start_link(?MODULE, [Options], []).
% request(Path, Headers, Body) ->
% io:format("~n~nWORKER:~nPath = ~p~nHeaders:~n~p~n~nBody = ~p~n~n~n", [Path, Headers, Body]),
% {error, busy}.
request(Path, Headers, Body) when is_binary(Path) ->
request(binary_to_list(Path), Headers, Body);
request(Path, Headers, Body) when is_list(Path) ->
{ok, Pid} = rack:find_worker(Path),
request(Pid, Headers, Body);
request(Pid, Headers, Body) when is_pid(Pid) ->
try gen_server:call(Pid, {request, Headers, Body}, 60000) of
Reply -> Reply
catch
error:timeout ->
gen_server:call(Pid, {cancel_req, self()}),
{error, timeout};
_Class:Error ->
gen_server:call(Pid, {cancel_req, self()}),
{error, Error}
end.
-record(state, {
port,
timeout,
timer,
from,
options,
path
}).
init([Options]) ->
Path = proplists:get_value(path, Options, "./priv"),
Timeout = proplists:get_value(timeout, Options, 60000),
{ok, RackOptions} = proplists:get_value(rack_options, Options, []),
State = #state{
path = Path,
timeout = Timeout,
options = Options
},
{ok, start_worker(State, RackOptions)}.
start_worker(#state{path = Path} = State, RackOptions) ->
WorkerPath = code:lib_dir(rack, priv),
Cmd = WorkerPath++"/worker.rb "++Path,
RackEnv = proplists : get_value(rack_env , RackOptions , " production " ) ,
% Env = [
{ " RACK_ENV " , RackEnv }
% ],
Port = erlang:open_port({spawn, Cmd}, [
nouse_stdio,
binary,
exit_status,
{packet,4},
{env, RackOptions}
]),
io:format("Start Rack worker with '~s', PID(~p)~n~p~n~n", [Cmd, self(), RackOptions]),
State#state{port = Port}.
handle_call({request, _H, _B} = Request, From, #state{from = undefined} = State) ->
{noreply, start_request(Request, From, State)};
handle_call({request, _H, _B}, _From, State) ->
{reply, {error, busy}, State}.
start_request({request, Headers, Body}, From, #state{port = Port, timeout = Timeout, from = undefined} = State) ->
Packed = iolist_to_binary([<<(length(Headers)):32>>,[
<<(size(Key)):32, Key/binary, (size(Value)):32, Value/binary>> || {Key, Value} <- Headers
], <<(size(Body)):32>>, Body]),
port_command(Port, Packed),
{ok, Timer} = timer:send_after(Timeout, kill_request),
State#state{from = From, timer = Timer}.
ask_next_job(State, Manager) ->
case rack_manager:next_job(Manager) of
empty -> State;
{ok, {Request, From}} ->
? D({worker_pickup , self ( ) } ) ,
State1 = start_request(Request, From, State),
State1
end.
handle_info({Port, {data, Bin}}, #state{port = Port, from = From, timer = Timer, path = Path} = State) ->
{ok, cancel} = timer:cancel(Timer),
<<Status:32, HeadersCount:32, Rest/binary>> = Bin,
{Headers, BodyType, RawBody} = extract_headers(Rest, HeadersCount, []),
Body = case BodyType of
file -> {ok, B} = file:read_file(binary_to_list(RawBody)), B;
raw -> RawBody
end,
gen_server:reply(From, {ok, {Status, Headers, Body}}),
State1 = ask_next_job(State#state{from = undefined, timer = undefined}, rack:manager_id(Path)),
{noreply, State1};
handle_info({has_new_job, Manager}, #state{from = undefined} = State) ->
{noreply, ask_next_job(State, Manager)};
handle_info({has_new_job, _}, #state{} = State) ->
{noreply, State};
handle_info(kill_request, #state{from = undefined} = State) ->
{noreply, State};
handle_info(kill_request, #state{from = From} = State) when From =/= undefined ->
(catch gen_server:reply(From, {error, timeout})),
?D({timeout,self()}),
{stop, normal, State};
handle_info({Port, {exit_status, _Status}}, #state{port = Port} = State) ->
{stop, normal, State}.
extract_headers(<<BodyFlag, BodyLen:32, Body:BodyLen/binary>>, 0, Acc) ->
BodyType = case BodyFlag of
1 -> file;
0 -> raw
end,
{lists:reverse(Acc), BodyType, Body};
extract_headers(<<KeyLen:32, Key:KeyLen/binary, ValueLen:32, Value:ValueLen/binary, Rest/binary>>, HeadersCount, Acc) ->
extract_headers(Rest, HeadersCount - 1, [{Key, Value}|Acc]).
terminate(_, _) -> ok.
| null | https://raw.githubusercontent.com/erlyvideo/rack/96baf455aa0f433d6ead84d301d7142ec3dfd52d/src/rack_worker.erl | erlang |
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
request(Path, Headers, Body) ->
io:format("~n~nWORKER:~nPath = ~p~nHeaders:~n~p~n~nBody = ~p~n~n~n", [Path, Headers, Body]),
{error, busy}.
Env = [
], | Copyright ( c ) 2011 , < >
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
-module(rack_worker).
-author('Max Lapshin <>').
-include("log.hrl").
-export([start_link/0, start_link/1, request/3]).
-export([init/1, handle_call/3, handle_info/2, terminate/2]).
start_link() ->
start_link([]).
start_link(Options) ->
gen_server:start_link(?MODULE, [Options], []).
request(Path, Headers, Body) when is_binary(Path) ->
request(binary_to_list(Path), Headers, Body);
request(Path, Headers, Body) when is_list(Path) ->
{ok, Pid} = rack:find_worker(Path),
request(Pid, Headers, Body);
request(Pid, Headers, Body) when is_pid(Pid) ->
try gen_server:call(Pid, {request, Headers, Body}, 60000) of
Reply -> Reply
catch
error:timeout ->
gen_server:call(Pid, {cancel_req, self()}),
{error, timeout};
_Class:Error ->
gen_server:call(Pid, {cancel_req, self()}),
{error, Error}
end.
-record(state, {
port,
timeout,
timer,
from,
options,
path
}).
init([Options]) ->
Path = proplists:get_value(path, Options, "./priv"),
Timeout = proplists:get_value(timeout, Options, 60000),
{ok, RackOptions} = proplists:get_value(rack_options, Options, []),
State = #state{
path = Path,
timeout = Timeout,
options = Options
},
{ok, start_worker(State, RackOptions)}.
start_worker(#state{path = Path} = State, RackOptions) ->
WorkerPath = code:lib_dir(rack, priv),
Cmd = WorkerPath++"/worker.rb "++Path,
RackEnv = proplists : get_value(rack_env , RackOptions , " production " ) ,
{ " RACK_ENV " , RackEnv }
Port = erlang:open_port({spawn, Cmd}, [
nouse_stdio,
binary,
exit_status,
{packet,4},
{env, RackOptions}
]),
io:format("Start Rack worker with '~s', PID(~p)~n~p~n~n", [Cmd, self(), RackOptions]),
State#state{port = Port}.
handle_call({request, _H, _B} = Request, From, #state{from = undefined} = State) ->
{noreply, start_request(Request, From, State)};
handle_call({request, _H, _B}, _From, State) ->
{reply, {error, busy}, State}.
start_request({request, Headers, Body}, From, #state{port = Port, timeout = Timeout, from = undefined} = State) ->
Packed = iolist_to_binary([<<(length(Headers)):32>>,[
<<(size(Key)):32, Key/binary, (size(Value)):32, Value/binary>> || {Key, Value} <- Headers
], <<(size(Body)):32>>, Body]),
port_command(Port, Packed),
{ok, Timer} = timer:send_after(Timeout, kill_request),
State#state{from = From, timer = Timer}.
ask_next_job(State, Manager) ->
case rack_manager:next_job(Manager) of
empty -> State;
{ok, {Request, From}} ->
? D({worker_pickup , self ( ) } ) ,
State1 = start_request(Request, From, State),
State1
end.
handle_info({Port, {data, Bin}}, #state{port = Port, from = From, timer = Timer, path = Path} = State) ->
{ok, cancel} = timer:cancel(Timer),
<<Status:32, HeadersCount:32, Rest/binary>> = Bin,
{Headers, BodyType, RawBody} = extract_headers(Rest, HeadersCount, []),
Body = case BodyType of
file -> {ok, B} = file:read_file(binary_to_list(RawBody)), B;
raw -> RawBody
end,
gen_server:reply(From, {ok, {Status, Headers, Body}}),
State1 = ask_next_job(State#state{from = undefined, timer = undefined}, rack:manager_id(Path)),
{noreply, State1};
handle_info({has_new_job, Manager}, #state{from = undefined} = State) ->
{noreply, ask_next_job(State, Manager)};
handle_info({has_new_job, _}, #state{} = State) ->
{noreply, State};
handle_info(kill_request, #state{from = undefined} = State) ->
{noreply, State};
handle_info(kill_request, #state{from = From} = State) when From =/= undefined ->
(catch gen_server:reply(From, {error, timeout})),
?D({timeout,self()}),
{stop, normal, State};
handle_info({Port, {exit_status, _Status}}, #state{port = Port} = State) ->
{stop, normal, State}.
extract_headers(<<BodyFlag, BodyLen:32, Body:BodyLen/binary>>, 0, Acc) ->
BodyType = case BodyFlag of
1 -> file;
0 -> raw
end,
{lists:reverse(Acc), BodyType, Body};
extract_headers(<<KeyLen:32, Key:KeyLen/binary, ValueLen:32, Value:ValueLen/binary, Rest/binary>>, HeadersCount, Acc) ->
extract_headers(Rest, HeadersCount - 1, [{Key, Value}|Acc]).
terminate(_, _) -> ok.
|
2a640bbeeec2c7d4c22e3c98b8e9e600bc9283b5295ec5f4970043cc1b0b75dc | zack-bitcoin/amoveo-exchange | trade_limit.erl | -module(trade_limit).
-behaviour(gen_server).
-export([start_link/0,code_change/3,handle_call/3,handle_cast/2,handle_info/2,init/1,terminate/2,
doit/1]).
-record(freq, {time, many}).
init(ok) -> {ok, dict:new()}.
start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, ok, []).
code_change(_OldVsn, State, _Extra) -> {ok, State}.
terminate(_, _) -> io:format("died!"), ok.
handle_info(_, X) -> {noreply, X}.
handle_cast(_, X) -> {noreply, X}.
handle_call(IP, _From, X) ->
Limit0 = config:trade_frequency(),
requests per 2 seconds
case dict:find(IP, X) of
error ->
NF = #freq{time = erlang:timestamp(),
many = 0},
X2 = dict:store(IP, NF, X),
{reply, ok, X2};
{ok, Val} ->
TimeNow = erlang:timestamp(),
T = timer:now_diff(TimeNow,
Val#freq.time),
S = T / 1000000,%seconds
every second , divide how many have been used up by 1/2 .
Many = Many0 + 1,
V2 = #freq{time = TimeNow,
many = Many},
X2 = dict:store(IP, V2, X),
R = if
Many > Limit ->
bad;
true -> ok
end,
{reply, R, X2}
end.
doit(IP) ->
gen_server:call(?MODULE, IP).
| null | https://raw.githubusercontent.com/zack-bitcoin/amoveo-exchange/df6b59c139b710faf79e851bdf7e861983511cbe/apps/amoveo_exchange/src/networking/trade_limit.erl | erlang | seconds | -module(trade_limit).
-behaviour(gen_server).
-export([start_link/0,code_change/3,handle_call/3,handle_cast/2,handle_info/2,init/1,terminate/2,
doit/1]).
-record(freq, {time, many}).
init(ok) -> {ok, dict:new()}.
start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, ok, []).
code_change(_OldVsn, State, _Extra) -> {ok, State}.
terminate(_, _) -> io:format("died!"), ok.
handle_info(_, X) -> {noreply, X}.
handle_cast(_, X) -> {noreply, X}.
handle_call(IP, _From, X) ->
Limit0 = config:trade_frequency(),
requests per 2 seconds
case dict:find(IP, X) of
error ->
NF = #freq{time = erlang:timestamp(),
many = 0},
X2 = dict:store(IP, NF, X),
{reply, ok, X2};
{ok, Val} ->
TimeNow = erlang:timestamp(),
T = timer:now_diff(TimeNow,
Val#freq.time),
every second , divide how many have been used up by 1/2 .
Many = Many0 + 1,
V2 = #freq{time = TimeNow,
many = Many},
X2 = dict:store(IP, V2, X),
R = if
Many > Limit ->
bad;
true -> ok
end,
{reply, R, X2}
end.
doit(IP) ->
gen_server:call(?MODULE, IP).
|
891f943d424b3337e1a08a68c22ae308b567b2fe11506865f06a1561984ed110 | racket/racket7 | c-encode.rkt | #lang racket/base
(provide encode-to-c)
;; Take a stream that has a single S-expression and converts it to C
;; code for a string that contains the S-expression
(define (encode-to-c in out)
(fprintf out "#define EVAL_STARTUP EVAL_ONE_STR(startup_source)\n")
(fprintf out "static const char *startup_source =\n")
(for ([l (in-lines in)])
(let* ([l (regexp-replace* #rx"\\\\" l "\\\\\\\\")]
[l (regexp-replace* #rx"\"" l "\\\\\"")]
[l (regexp-replace* #rx"\t" l " ")]
[l (if (regexp-match? #rx"\"" l)
;; Has a string - can't safely delete more spaces
l
(let ([l (regexp-replace* #rx" +" l " ")])
(regexp-replace* #rx" \\(" l "(")))])
(fprintf out "\"~a\"\n" l)))
(fprintf out ";\n"))
| null | https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/src/expander/extract/c-encode.rkt | racket | Take a stream that has a single S-expression and converts it to C
code for a string that contains the S-expression
Has a string - can't safely delete more spaces | #lang racket/base
(provide encode-to-c)
(define (encode-to-c in out)
(fprintf out "#define EVAL_STARTUP EVAL_ONE_STR(startup_source)\n")
(fprintf out "static const char *startup_source =\n")
(for ([l (in-lines in)])
(let* ([l (regexp-replace* #rx"\\\\" l "\\\\\\\\")]
[l (regexp-replace* #rx"\"" l "\\\\\"")]
[l (regexp-replace* #rx"\t" l " ")]
[l (if (regexp-match? #rx"\"" l)
l
(let ([l (regexp-replace* #rx" +" l " ")])
(regexp-replace* #rx" \\(" l "(")))])
(fprintf out "\"~a\"\n" l)))
(fprintf out ";\n"))
|
b56a6f8c053662c0ec2e0a0073372352d0b29a8b5ef56515e9341a790480a408 | haskell/cabal | cabal.test.hs | import Test.Cabal.Prelude
-- Unbounded (top) base.
main = cabalTest $
fails $ cabal "check" []
| null | https://raw.githubusercontent.com/haskell/cabal/1cfe7c4c7257aa7ae450209d34b4a359e6703a10/cabal-testsuite/PackageTests/Check/NonConfCheck/PackageVersions/cabal.test.hs | haskell | Unbounded (top) base. | import Test.Cabal.Prelude
main = cabalTest $
fails $ cabal "check" []
|
00d9276d80ee02a3c92386191baf8961fcaefa48d979bfdcdfdcb1a757d76dcb | mindreframer/clojure-stuff | sidebar.cljs | (ns omchaya.components.sidebar
(:require [cljs.core.async :as async :refer [>! <! alts! chan sliding-buffer put! close!]]
[clojure.string :as string]
[goog.string :as gstring]
[om.core :as om]
[omchaya.utils :as utils]
[sablono.core :as html :refer-macros [html]]))
(defn people-entry [comm person]
[:li.user
{:title (or (:full-name person)
(:username person)
(:email person))
:key (:email person)}
(utils/gravatar-for (:email person))
(or (:full-name person)
(:username person))])
(defn people-widget [{:keys [channel-users-emails search-filter] :as data} owner opts]
(reify
om/IDisplayName
(display-name [_]
(or (:react-name opts) "PeopleWidget"))
om/IRender
(render [this]
(html/html
(let [comm (get-in opts [:comms :controls])
re-filter (when search-filter (js/RegExp. search-filter "ig"))
channel-users (vals (select-keys (:users opts) channel-users-emails))
fil-users (if re-filter
(filter #(or (.match (:full-name %) re-filter)
(.match (:email %) re-filter)
(.match (:username %) re-filter)) channel-users)
channel-users)]
[:ul.user_list
(map (partial people-entry comm) fil-users)])))))
(defn current-user [comm user]
[:a.user-menu-toggle
{:href "#"
:on-click (comp (constantly false)
#(put! comm [:user-menu-toggled]))}
(utils/gravatar-for (:email user))
[:i.icon-angle.button.right {:style #js {:height "inherit"}}]
(:full-name user)])
(defn media-name [src]
(-> src
(string/split #"/")
last
(string/split #"\?")
first
gstring/urlDecode))
(defn playlist-entry [comm opts entry]
(let [src (:src entry)
order (:order entry)
name (media-name src)]
[:li.user
(merge {:title src
:key (str (:order entry) src)}
(when (= (:order entry) (get-in opts [:channels (:selected-channel opts) :player :playing-order]))
{:style #js {:background-color "#ccc"}}))
[:a
{:style #js {:cursor "pointer"}
:on-click (comp (constantly false)
#(put! comm [:playlist-entry-played [order (:selected-channel opts)]]))}
(:order entry) ". " name]]))
(defn playlist-widget [{:keys [player search-filter]} owner opts]
(reify
om/IDisplayName
(display-name [_]
(or (:react-name opts) "PlaylistWidget"))
om/IRender
(render [_]
(html/html
(let [comm (get-in opts [:comms :controls])
re-filter (when search-filter (js/RegExp. search-filter "ig"))
fil-playlist (if re-filter
(filter #(.match (media-name (:src %)) re-filter) (:playlist player))
(:playlist player))]
[:div
[:ul.user_list
(map (partial playlist-entry comm opts)
(sort-by :order fil-playlist))]])))))
(defn playlist-action-widget [{:keys [player]} owner opts]
(let [comm (get-in opts [:comms :controls])]
(html/html
[:div.dropzone
(if (= (:state player) :playing)
[:i.fa.fa-pause
{:style #js {:cursor "pointer"}
:on-click #(put! comm [:audio-player-stopped (:selected-channel opts)])}]
[:i.fa.fa-play
{:style #js {:cursor "pointer"}
:on-click #(put! comm [:audio-player-started (:selected-channel opts)])}])])))
(def icon-map
{"png" "img"
"jpg" "img"
"jpeg" "img"})
(defn media-entry [comm media]
(let [extension (-> (string/split (:src media) #"\?")
first
(string/split #"\.")
last)]
[:li.file_item {:key (:src media)}
[:a
{:href "#"
:on-click (constantly false)
:target "_blank"}
[:img {:src (str "/assets/images/" (get icon-map extension "file") "_icon.png")}]
[:span (:name media)]]]))
(defn media-widget [{:keys [channel-id media search-filter]} owner opts]
(reify
om/IDisplayName
(display-name [_]
(or (:react-name opts) "MediaWidget"))
om/IRender
(render [this]
(html/html
(let [comm (:comm opts)
re-filter (when search-filter (js/RegExp. search-filter "ig"))]
[:ul.file_list
(map (partial media-entry comm) (if re-filter
(filter #(.match (:name %) re-filter) media)
media))])))))
(defn media-action-widget [{:keys [channel-id]} owner opts]
(let []
(html/html
[:form#file_upload
{:method "post",
:html "{:multipart=>true}",
:data-remote "true",
:action (str "/channels/" channel-id "/attachments.json"),
:accept-charset "UTF-8"}
[:div
{:style #js {:margin "0", :padding "0", :display "inline"}}
[:input {:value "✓", :type "hidden", :name "utf8"}]
[:input
{:value "bpuDvAt5w97Cp4khpWE25tcTsD2vFEFpKwsIAG0m8fw=",
:type "hidden",
:name "authenticity_token"}]]
[:input#channel_id_1 {:type "hidden", :name (str "channel_id[" channel-id "]")}]
[:input#file {:type "file", :name "file"}]
[:div.dropzone "Drop file here to upload"]])))
(defn widget [data owner opts]
(reify
om/IDisplayName
(display-name [_]
(or (:react-name opts) "Widget"))
om/IRender
(render [this]
(html/html
(let [comm (:comm opts)]
[:div.widget
[:h5.widget-header.unselectable
[:img {:src (:icon opts)}]
(:title opts)]
[:div.widget-content
(om/build (:content-comp opts) (:content-data data) {:opts (:content-opts data)})]
(when (:action-comp opts)
[:div.widget-action-bar
(om/build (:action-comp opts) (:action-data data) {:opts (:action-opts data)})])])))))
(defn sidebar [data owner opts]
(reify
om/IDisplayName
(display-name [_]
(or (:react-name opts) "Sidebar"))
om/IRender
(render [this]
(html/html
(let [comm (get-in opts [:comms :controls])
channel (:channel data)
settings (:settings data)
search-filter (:search-filter data)]
(print "Sidebar render")
[:aside.sidebar
[:div.header.user-header {:class (when (get-in settings [:menus :user-menu :open]) "open-menu")}
(current-user comm (get-in opts [:users (:current-user-email opts)]))
[:ul.user-menu
[:li]
[:li [:a {:href "#"
:on-click #(put! comm [:settings-opened])} "Edit Account"]]
[:li
[:a
{:rel "nofollow",
:href "#"
:on-click #(put! comm [:user-logged-out])}
"Logout"]]
[:li [:a {:href "#"
:on-click #(put! comm [:help-opened])} "Help"]]
[:li [:a {:href "#"
:on-click #(put! comm [:about-opened])} "About Omchaya"]]]]
[:div.widgets
(om/build widget
{:content-data {:channel-users-emails (:users channel)
:search-filter search-filter}
:content-opts opts}
{:opts {:title "People"
:icon "/assets/images/people_icon.png"
:content-comp people-widget}})
(om/build widget
{:content-data {:player (:player channel)
:search-filter search-filter}
:content-opts opts
:action-data {:player (:player channel)}
:action-opts opts}
{:opts {:title "Playlist"
:icon "/assets/images/video_icon.png"
:content-comp playlist-widget
:action-comp playlist-action-widget}})
(om/build widget
{:content-data {:search-filter search-filter
:media (:media channel)
:channel-id (:id channel)}
:content-opts {:comm comm}
:action-data {:channel-id (:id channel)}}
{:opts {:title "My Media"
:icon "/assets/images/media_icon.png"
:content-comp media-widget
:action-comp media-action-widget}})]])))))
| null | https://raw.githubusercontent.com/mindreframer/clojure-stuff/1e761b2dacbbfbeec6f20530f136767e788e0fe3/github.com/sgrove/omchaya/src/omchaya/components/sidebar.cljs | clojure | (ns omchaya.components.sidebar
(:require [cljs.core.async :as async :refer [>! <! alts! chan sliding-buffer put! close!]]
[clojure.string :as string]
[goog.string :as gstring]
[om.core :as om]
[omchaya.utils :as utils]
[sablono.core :as html :refer-macros [html]]))
(defn people-entry [comm person]
[:li.user
{:title (or (:full-name person)
(:username person)
(:email person))
:key (:email person)}
(utils/gravatar-for (:email person))
(or (:full-name person)
(:username person))])
(defn people-widget [{:keys [channel-users-emails search-filter] :as data} owner opts]
(reify
om/IDisplayName
(display-name [_]
(or (:react-name opts) "PeopleWidget"))
om/IRender
(render [this]
(html/html
(let [comm (get-in opts [:comms :controls])
re-filter (when search-filter (js/RegExp. search-filter "ig"))
channel-users (vals (select-keys (:users opts) channel-users-emails))
fil-users (if re-filter
(filter #(or (.match (:full-name %) re-filter)
(.match (:email %) re-filter)
(.match (:username %) re-filter)) channel-users)
channel-users)]
[:ul.user_list
(map (partial people-entry comm) fil-users)])))))
(defn current-user [comm user]
[:a.user-menu-toggle
{:href "#"
:on-click (comp (constantly false)
#(put! comm [:user-menu-toggled]))}
(utils/gravatar-for (:email user))
[:i.icon-angle.button.right {:style #js {:height "inherit"}}]
(:full-name user)])
(defn media-name [src]
(-> src
(string/split #"/")
last
(string/split #"\?")
first
gstring/urlDecode))
(defn playlist-entry [comm opts entry]
(let [src (:src entry)
order (:order entry)
name (media-name src)]
[:li.user
(merge {:title src
:key (str (:order entry) src)}
(when (= (:order entry) (get-in opts [:channels (:selected-channel opts) :player :playing-order]))
{:style #js {:background-color "#ccc"}}))
[:a
{:style #js {:cursor "pointer"}
:on-click (comp (constantly false)
#(put! comm [:playlist-entry-played [order (:selected-channel opts)]]))}
(:order entry) ". " name]]))
(defn playlist-widget [{:keys [player search-filter]} owner opts]
(reify
om/IDisplayName
(display-name [_]
(or (:react-name opts) "PlaylistWidget"))
om/IRender
(render [_]
(html/html
(let [comm (get-in opts [:comms :controls])
re-filter (when search-filter (js/RegExp. search-filter "ig"))
fil-playlist (if re-filter
(filter #(.match (media-name (:src %)) re-filter) (:playlist player))
(:playlist player))]
[:div
[:ul.user_list
(map (partial playlist-entry comm opts)
(sort-by :order fil-playlist))]])))))
(defn playlist-action-widget [{:keys [player]} owner opts]
(let [comm (get-in opts [:comms :controls])]
(html/html
[:div.dropzone
(if (= (:state player) :playing)
[:i.fa.fa-pause
{:style #js {:cursor "pointer"}
:on-click #(put! comm [:audio-player-stopped (:selected-channel opts)])}]
[:i.fa.fa-play
{:style #js {:cursor "pointer"}
:on-click #(put! comm [:audio-player-started (:selected-channel opts)])}])])))
(def icon-map
{"png" "img"
"jpg" "img"
"jpeg" "img"})
(defn media-entry [comm media]
(let [extension (-> (string/split (:src media) #"\?")
first
(string/split #"\.")
last)]
[:li.file_item {:key (:src media)}
[:a
{:href "#"
:on-click (constantly false)
:target "_blank"}
[:img {:src (str "/assets/images/" (get icon-map extension "file") "_icon.png")}]
[:span (:name media)]]]))
(defn media-widget [{:keys [channel-id media search-filter]} owner opts]
(reify
om/IDisplayName
(display-name [_]
(or (:react-name opts) "MediaWidget"))
om/IRender
(render [this]
(html/html
(let [comm (:comm opts)
re-filter (when search-filter (js/RegExp. search-filter "ig"))]
[:ul.file_list
(map (partial media-entry comm) (if re-filter
(filter #(.match (:name %) re-filter) media)
media))])))))
(defn media-action-widget [{:keys [channel-id]} owner opts]
(let []
(html/html
[:form#file_upload
{:method "post",
:html "{:multipart=>true}",
:data-remote "true",
:action (str "/channels/" channel-id "/attachments.json"),
:accept-charset "UTF-8"}
[:div
{:style #js {:margin "0", :padding "0", :display "inline"}}
[:input {:value "✓", :type "hidden", :name "utf8"}]
[:input
{:value "bpuDvAt5w97Cp4khpWE25tcTsD2vFEFpKwsIAG0m8fw=",
:type "hidden",
:name "authenticity_token"}]]
[:input#channel_id_1 {:type "hidden", :name (str "channel_id[" channel-id "]")}]
[:input#file {:type "file", :name "file"}]
[:div.dropzone "Drop file here to upload"]])))
(defn widget [data owner opts]
(reify
om/IDisplayName
(display-name [_]
(or (:react-name opts) "Widget"))
om/IRender
(render [this]
(html/html
(let [comm (:comm opts)]
[:div.widget
[:h5.widget-header.unselectable
[:img {:src (:icon opts)}]
(:title opts)]
[:div.widget-content
(om/build (:content-comp opts) (:content-data data) {:opts (:content-opts data)})]
(when (:action-comp opts)
[:div.widget-action-bar
(om/build (:action-comp opts) (:action-data data) {:opts (:action-opts data)})])])))))
(defn sidebar [data owner opts]
(reify
om/IDisplayName
(display-name [_]
(or (:react-name opts) "Sidebar"))
om/IRender
(render [this]
(html/html
(let [comm (get-in opts [:comms :controls])
channel (:channel data)
settings (:settings data)
search-filter (:search-filter data)]
(print "Sidebar render")
[:aside.sidebar
[:div.header.user-header {:class (when (get-in settings [:menus :user-menu :open]) "open-menu")}
(current-user comm (get-in opts [:users (:current-user-email opts)]))
[:ul.user-menu
[:li]
[:li [:a {:href "#"
:on-click #(put! comm [:settings-opened])} "Edit Account"]]
[:li
[:a
{:rel "nofollow",
:href "#"
:on-click #(put! comm [:user-logged-out])}
"Logout"]]
[:li [:a {:href "#"
:on-click #(put! comm [:help-opened])} "Help"]]
[:li [:a {:href "#"
:on-click #(put! comm [:about-opened])} "About Omchaya"]]]]
[:div.widgets
(om/build widget
{:content-data {:channel-users-emails (:users channel)
:search-filter search-filter}
:content-opts opts}
{:opts {:title "People"
:icon "/assets/images/people_icon.png"
:content-comp people-widget}})
(om/build widget
{:content-data {:player (:player channel)
:search-filter search-filter}
:content-opts opts
:action-data {:player (:player channel)}
:action-opts opts}
{:opts {:title "Playlist"
:icon "/assets/images/video_icon.png"
:content-comp playlist-widget
:action-comp playlist-action-widget}})
(om/build widget
{:content-data {:search-filter search-filter
:media (:media channel)
:channel-id (:id channel)}
:content-opts {:comm comm}
:action-data {:channel-id (:id channel)}}
{:opts {:title "My Media"
:icon "/assets/images/media_icon.png"
:content-comp media-widget
:action-comp media-action-widget}})]])))))
|
|
f377126b546b8edec0221b89b2a1d5018c128b90f9583009d54e84d7bc4bd2ab | Frama-C/Frama-C-snapshot | file_manager.ml | (**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 2019
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
let add_files (host_window: Design.main_window_extension_points) =
Gtk_helper.source_files_chooser
(host_window :> Gtk_helper.source_files_chooser_host)
(Kernel.Files.get ())
(fun filenames ->
Kernel.Files.set filenames;
if Ast.is_computed () then
Gui_parameters.warning "Input files unchanged. Ignored."
else begin
File.init_from_cmdline ();
host_window#reset ()
end)
let filename: string option ref = ref None
(* [None] for opening the 'save as' dialog box;
[Some f] for saving in file [f] *)
let reparse (host_window: Design.main_window_extension_points) =
let old_helt = History.get_current () in
let old_scroll =
let adj = host_window#source_viewer_scroll#vadjustment in
(adj#value -. adj#lower ) /. (adj#upper -. adj#lower)
in
let succeeded = host_window#full_protect ~cancelable:true
(fun () ->
let files = Kernel.Files.get () in
Kernel.Files.set [];
Kernel.Files.set files;
Ast.compute ();
!Db.Main.play ();
Source_manager.clear host_window#original_source_viewer)
in
begin match old_helt, succeeded with
| None, _ -> (** no history available before reparsing *)
host_window#reset ()
| _, None -> (** the user stopped or an error occurred *)
host_window#reset ()
| Some old_helt, Some () ->
let new_helt = History.translate_history_elt old_helt in
Extlib.may History.push new_helt;
host_window#reset ();
(** The buffer is not ready yet, modification of its vadjustement
is unreliable *)
let set () =
let adj = host_window#source_viewer_scroll#vadjustment in
adj#set_value (old_scroll *. (adj#upper-.adj#lower) +. adj#lower)
in
Wutil.later set
end
let save_in (host_window: Design.main_window_extension_points) parent name =
try
Project.save_all name;
filename := Some name
with Project.IOError s ->
host_window#error ~parent "Cannot save: %s" s
(** Save a project file. Choose a filename *)
let save_file_as (host_window: Design.main_window_extension_points) =
let dialog =
GWindow.file_chooser_dialog
~action:`SAVE
~title:"Save the current session"
~parent:host_window#main_window ()
in
(*dialog#set_do_overwrite_confirmation true ; only in later lablgtk2 *)
dialog#add_button_stock `CANCEL `CANCEL ;
dialog#add_select_button_stock `SAVE `SAVE ;
host_window#protect ~cancelable:true ~parent:(dialog :> GWindow.window_skel)
(fun () ->
match dialog#run () with
| `SAVE ->
Extlib.may
(save_in host_window (dialog :> GWindow.window_skel))
dialog#filename
| `DELETE_EVENT | `CANCEL -> ());
dialog#destroy ()
let save_file (host_window: Design.main_window_extension_points) =
match !filename with
| None -> save_file_as host_window
| Some f ->
save_in host_window (host_window#main_window :> GWindow.window_skel) f
(** Load a project file *)
let load_file (host_window: Design.main_window_extension_points) =
let dialog = GWindow.file_chooser_dialog
~action:`OPEN
~title:"Load a saved session"
~parent:host_window#main_window () in
dialog#add_button_stock `CANCEL `CANCEL ;
dialog#add_select_button_stock `OPEN `OPEN ;
host_window#protect ~cancelable:true ~parent:(dialog:>GWindow.window_skel)
(fun () -> match dialog#run () with
| `OPEN ->
begin match dialog#filename with
| None -> ()
| Some f ->
Project.load_all f
end
| `DELETE_EVENT | `CANCEL -> ());
dialog#destroy ()
(** Open the Preferences dialog *)
let preferences (host_window: Design.main_window_extension_points) =
let dialog =
GWindow.dialog ~modal:true
~border_width:8 ~title:"Preferences" ~parent:host_window#main_window ()
in
let main_box = dialog#vbox in
main_box#set_spacing 10;
let theme_frame = GBin.frame ~label:"Property bullets theme" () in
main_box#pack theme_frame#coerce;
let theme_box = GPack.vbox ~spacing:2 ~border_width:10 () in
theme_frame#add theme_box#coerce;
(* Themes are directories in share/theme. *)
let themes_path = !Wutil.share ^ "/theme/" in
let themes = Array.to_list (Sys.readdir themes_path) in
let is_theme_directory name = Sys.is_directory (themes_path ^ name) in
let themes = List.filter is_theme_directory themes in
(* The current theme is kept in the configuration file. *)
let active_theme =
Gtk_helper.Configuration.find_string ~default:"default" "theme"
in
let theme_group = new Widget.group "" in
let build_theme_button name =
let label = String.capitalize_ascii name in
let widget = theme_group#add_radio ~label ~value:name () in
theme_box#add widget#coerce
in
(* Builds the theme buttons, and sets the active theme. *)
List.iter build_theme_button themes;
theme_group#set active_theme;
(* External editor command. *)
let default = "emacs +%d %s" in
let editor = Gtk_helper.Configuration.find_string ~default "editor" in
let editor_frame = GBin.frame ~label:"Editor command" () in
main_box#pack editor_frame#coerce;
let editor_box = GPack.vbox ~spacing:5 ~border_width:10 () in
editor_frame#add editor_box#coerce;
let text = "Command to open an external editor \
on Ctrl-click in the original source code. \n\
Use %s for file name and %d for line number."
in
let label = GMisc.label ~xalign:0. ~line_wrap:true ~text () in
editor_box#pack label#coerce;
let editor_input = GEdit.entry ~width_chars:30 ~text:editor () in
editor_box#pack editor_input#coerce ~expand:true;
(* Save and cancel buttons. *)
let hbox_buttons = dialog#action_area in
let packing = hbox_buttons#pack ~expand:true ~padding:3 in
let wb_ok = GButton.button ~label:"Save" ~packing () in
let wb_cancel = GButton.button ~label:"Cancel" ~packing () in
wb_ok#grab_default ();
let f_ok () =
(* retrieve chosen preferences from dialog *)
note : does not allow double quotes in strings , but it fails
without raising an exception , so we must check if beforehand .
without raising an exception, so we must check if beforehand. *)
if String.contains editor_input#text '"' then
GToolbox.message_box ~title:"Error"
"Error: configuration strings cannot contain double quotes. \n\
Use single quotes instead. \n\
Note that file names (%s) are automatically quoted."
else begin
Gui_parameters.debug "saving preferences";
Gtk_helper.Configuration.set "theme"
(Gtk_helper.Configuration.ConfString theme_group#get);
Gtk_helper.Configuration.set "editor"
(Gtk_helper.Configuration.ConfString editor_input#text);
Gtk_helper.Configuration.save ();
dialog#destroy ();
(* Reloads the icons from the theme, and resets the icons used as property
status bullets.*)
Gtk_helper.Icon.clear ();
Design.Feedback.declare_markers host_window#source_viewer;
end
in
let f_cancel () =
Gui_parameters.debug "canceled, preferences not saved";
dialog#destroy ()
in
ignore (wb_ok#connect#clicked f_ok);
ignore (wb_cancel#connect#clicked f_cancel);
(* the enter key is linked to the ok action *)
(* the escape key is linked to the cancel action *)
dialog#misc#grab_focus ();
dialog#show ()
let insert (host_window: Design.main_window_extension_points) =
let menu_manager = host_window#menu_manager () in
let _, filemenu = menu_manager#add_menu "_File" in
let file_items =
menu_manager#add_entries
filemenu
[
Menu_manager.toolmenubar
~icon:`FILE ~label:"Source files"
~tooltip:"Create a new session from existing C files"
(Menu_manager.Unit_callback (fun () -> add_files host_window));
Menu_manager.toolmenubar
~icon:`REFRESH ~label:"Reparse"
~tooltip:"Reparse source files, and replay analyses"
(Menu_manager.Unit_callback (fun () -> reparse host_window));
Menu_manager.toolmenubar `REVERT_TO_SAVED "Load session"
(Menu_manager.Unit_callback (fun () -> load_file host_window));
Menu_manager.toolmenubar `SAVE "Save session"
(Menu_manager.Unit_callback (fun () -> save_file host_window));
Menu_manager.menubar ~icon:`SAVE_AS "Save session as"
(Menu_manager.Unit_callback (fun () -> save_file_as host_window));
Menu_manager.menubar ~icon:`PREFERENCES "Preferences"
(Menu_manager.Unit_callback (fun () -> preferences host_window));
]
in
file_items.(5)#add_accelerator `CONTROL 'p';
file_items.(3)#add_accelerator `CONTROL 's';
file_items.(2)#add_accelerator `CONTROL 'l';
let stock = `QUIT in
let quit_item =
menu_manager#add_entries
filemenu
[ Menu_manager.menubar ~icon:stock "Exit Frama-C"
(Menu_manager.Unit_callback Cmdline.bail_out) ]
in
quit_item.(0)#add_accelerator `CONTROL 'q'
(** Register this dialog in main window menu bar *)
let () = Design.register_extension insert
(*
Local Variables:
compile-command: "make -C ../../.."
End:
*)
| null | https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/gui/file_manager.ml | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
[None] for opening the 'save as' dialog box;
[Some f] for saving in file [f]
* no history available before reparsing
* the user stopped or an error occurred
* The buffer is not ready yet, modification of its vadjustement
is unreliable
* Save a project file. Choose a filename
dialog#set_do_overwrite_confirmation true ; only in later lablgtk2
* Load a project file
* Open the Preferences dialog
Themes are directories in share/theme.
The current theme is kept in the configuration file.
Builds the theme buttons, and sets the active theme.
External editor command.
Save and cancel buttons.
retrieve chosen preferences from dialog
Reloads the icons from the theme, and resets the icons used as property
status bullets.
the enter key is linked to the ok action
the escape key is linked to the cancel action
* Register this dialog in main window menu bar
Local Variables:
compile-command: "make -C ../../.."
End:
| This file is part of Frama - C.
Copyright ( C ) 2007 - 2019
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
let add_files (host_window: Design.main_window_extension_points) =
Gtk_helper.source_files_chooser
(host_window :> Gtk_helper.source_files_chooser_host)
(Kernel.Files.get ())
(fun filenames ->
Kernel.Files.set filenames;
if Ast.is_computed () then
Gui_parameters.warning "Input files unchanged. Ignored."
else begin
File.init_from_cmdline ();
host_window#reset ()
end)
let filename: string option ref = ref None
let reparse (host_window: Design.main_window_extension_points) =
let old_helt = History.get_current () in
let old_scroll =
let adj = host_window#source_viewer_scroll#vadjustment in
(adj#value -. adj#lower ) /. (adj#upper -. adj#lower)
in
let succeeded = host_window#full_protect ~cancelable:true
(fun () ->
let files = Kernel.Files.get () in
Kernel.Files.set [];
Kernel.Files.set files;
Ast.compute ();
!Db.Main.play ();
Source_manager.clear host_window#original_source_viewer)
in
begin match old_helt, succeeded with
host_window#reset ()
host_window#reset ()
| Some old_helt, Some () ->
let new_helt = History.translate_history_elt old_helt in
Extlib.may History.push new_helt;
host_window#reset ();
let set () =
let adj = host_window#source_viewer_scroll#vadjustment in
adj#set_value (old_scroll *. (adj#upper-.adj#lower) +. adj#lower)
in
Wutil.later set
end
let save_in (host_window: Design.main_window_extension_points) parent name =
try
Project.save_all name;
filename := Some name
with Project.IOError s ->
host_window#error ~parent "Cannot save: %s" s
let save_file_as (host_window: Design.main_window_extension_points) =
let dialog =
GWindow.file_chooser_dialog
~action:`SAVE
~title:"Save the current session"
~parent:host_window#main_window ()
in
dialog#add_button_stock `CANCEL `CANCEL ;
dialog#add_select_button_stock `SAVE `SAVE ;
host_window#protect ~cancelable:true ~parent:(dialog :> GWindow.window_skel)
(fun () ->
match dialog#run () with
| `SAVE ->
Extlib.may
(save_in host_window (dialog :> GWindow.window_skel))
dialog#filename
| `DELETE_EVENT | `CANCEL -> ());
dialog#destroy ()
let save_file (host_window: Design.main_window_extension_points) =
match !filename with
| None -> save_file_as host_window
| Some f ->
save_in host_window (host_window#main_window :> GWindow.window_skel) f
let load_file (host_window: Design.main_window_extension_points) =
let dialog = GWindow.file_chooser_dialog
~action:`OPEN
~title:"Load a saved session"
~parent:host_window#main_window () in
dialog#add_button_stock `CANCEL `CANCEL ;
dialog#add_select_button_stock `OPEN `OPEN ;
host_window#protect ~cancelable:true ~parent:(dialog:>GWindow.window_skel)
(fun () -> match dialog#run () with
| `OPEN ->
begin match dialog#filename with
| None -> ()
| Some f ->
Project.load_all f
end
| `DELETE_EVENT | `CANCEL -> ());
dialog#destroy ()
let preferences (host_window: Design.main_window_extension_points) =
let dialog =
GWindow.dialog ~modal:true
~border_width:8 ~title:"Preferences" ~parent:host_window#main_window ()
in
let main_box = dialog#vbox in
main_box#set_spacing 10;
let theme_frame = GBin.frame ~label:"Property bullets theme" () in
main_box#pack theme_frame#coerce;
let theme_box = GPack.vbox ~spacing:2 ~border_width:10 () in
theme_frame#add theme_box#coerce;
let themes_path = !Wutil.share ^ "/theme/" in
let themes = Array.to_list (Sys.readdir themes_path) in
let is_theme_directory name = Sys.is_directory (themes_path ^ name) in
let themes = List.filter is_theme_directory themes in
let active_theme =
Gtk_helper.Configuration.find_string ~default:"default" "theme"
in
let theme_group = new Widget.group "" in
let build_theme_button name =
let label = String.capitalize_ascii name in
let widget = theme_group#add_radio ~label ~value:name () in
theme_box#add widget#coerce
in
List.iter build_theme_button themes;
theme_group#set active_theme;
let default = "emacs +%d %s" in
let editor = Gtk_helper.Configuration.find_string ~default "editor" in
let editor_frame = GBin.frame ~label:"Editor command" () in
main_box#pack editor_frame#coerce;
let editor_box = GPack.vbox ~spacing:5 ~border_width:10 () in
editor_frame#add editor_box#coerce;
let text = "Command to open an external editor \
on Ctrl-click in the original source code. \n\
Use %s for file name and %d for line number."
in
let label = GMisc.label ~xalign:0. ~line_wrap:true ~text () in
editor_box#pack label#coerce;
let editor_input = GEdit.entry ~width_chars:30 ~text:editor () in
editor_box#pack editor_input#coerce ~expand:true;
let hbox_buttons = dialog#action_area in
let packing = hbox_buttons#pack ~expand:true ~padding:3 in
let wb_ok = GButton.button ~label:"Save" ~packing () in
let wb_cancel = GButton.button ~label:"Cancel" ~packing () in
wb_ok#grab_default ();
let f_ok () =
note : does not allow double quotes in strings , but it fails
without raising an exception , so we must check if beforehand .
without raising an exception, so we must check if beforehand. *)
if String.contains editor_input#text '"' then
GToolbox.message_box ~title:"Error"
"Error: configuration strings cannot contain double quotes. \n\
Use single quotes instead. \n\
Note that file names (%s) are automatically quoted."
else begin
Gui_parameters.debug "saving preferences";
Gtk_helper.Configuration.set "theme"
(Gtk_helper.Configuration.ConfString theme_group#get);
Gtk_helper.Configuration.set "editor"
(Gtk_helper.Configuration.ConfString editor_input#text);
Gtk_helper.Configuration.save ();
dialog#destroy ();
Gtk_helper.Icon.clear ();
Design.Feedback.declare_markers host_window#source_viewer;
end
in
let f_cancel () =
Gui_parameters.debug "canceled, preferences not saved";
dialog#destroy ()
in
ignore (wb_ok#connect#clicked f_ok);
ignore (wb_cancel#connect#clicked f_cancel);
dialog#misc#grab_focus ();
dialog#show ()
let insert (host_window: Design.main_window_extension_points) =
let menu_manager = host_window#menu_manager () in
let _, filemenu = menu_manager#add_menu "_File" in
let file_items =
menu_manager#add_entries
filemenu
[
Menu_manager.toolmenubar
~icon:`FILE ~label:"Source files"
~tooltip:"Create a new session from existing C files"
(Menu_manager.Unit_callback (fun () -> add_files host_window));
Menu_manager.toolmenubar
~icon:`REFRESH ~label:"Reparse"
~tooltip:"Reparse source files, and replay analyses"
(Menu_manager.Unit_callback (fun () -> reparse host_window));
Menu_manager.toolmenubar `REVERT_TO_SAVED "Load session"
(Menu_manager.Unit_callback (fun () -> load_file host_window));
Menu_manager.toolmenubar `SAVE "Save session"
(Menu_manager.Unit_callback (fun () -> save_file host_window));
Menu_manager.menubar ~icon:`SAVE_AS "Save session as"
(Menu_manager.Unit_callback (fun () -> save_file_as host_window));
Menu_manager.menubar ~icon:`PREFERENCES "Preferences"
(Menu_manager.Unit_callback (fun () -> preferences host_window));
]
in
file_items.(5)#add_accelerator `CONTROL 'p';
file_items.(3)#add_accelerator `CONTROL 's';
file_items.(2)#add_accelerator `CONTROL 'l';
let stock = `QUIT in
let quit_item =
menu_manager#add_entries
filemenu
[ Menu_manager.menubar ~icon:stock "Exit Frama-C"
(Menu_manager.Unit_callback Cmdline.bail_out) ]
in
quit_item.(0)#add_accelerator `CONTROL 'q'
let () = Design.register_extension insert
|
6e37b8a76c4610921dd0a12d0ab1f81b09ed0a3f508f2a5a9a9ac192b2aaf987 | ggreif/omega | finally-finally.hs | # LANGUAGE ConstraintKinds , DataKinds , PolyKinds , RankNTypes , ImpredicativeTypes , TypeFamilies
, MultiParamTypeClasses , TypeSynonymInstances , FlexibleInstances #
, MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-}
-- To have lenses etc. for finally-tagless form we need a
-- way to create custom class dictionaries (and possibly
-- abuse reflection to create them on the fly). But why
-- not create a concept of final dictionaries, where we
-- are not restricted to the concept of finally-tagless
to be implemented by type classes ?
class Foo' a where
bar :: Char -> Bool -> a
quux :: a -> a -> a
class Dict (d :: [*] -> k) (ms :: [*]) where
type First d ms :: *
first :: First d ms
type F = Functor
ERROR ? ! type = forall a . Foo ' a = > ' [ Char - > Bool - > a , a - > a - > a ]
type = ' [ forall a . Foo ' a = > Bool - > a , forall a . Foo ' a = > a - > a - > a ]
type Foo a = '[Char -> Bool -> a, a -> a -> a]
data F (vs :: [*]) = Bar Char Bool | Quux (F vs) (F vs)
class G (vs :: [*]) where
instance Dict F (Foo (F a)) where
type First F Foo = forall a . Foo ' a = > Bool - > a
type First F (Foo (F a)) = Char -> Bool -> F a
first = Bar
instance ( ( G a ) ) where | null | https://raw.githubusercontent.com/ggreif/omega/016a3b48313ec2c68e8d8ad60147015bc38f2767/mosaic/finally-finally.hs | haskell | To have lenses etc. for finally-tagless form we need a
way to create custom class dictionaries (and possibly
abuse reflection to create them on the fly). But why
not create a concept of final dictionaries, where we
are not restricted to the concept of finally-tagless | # LANGUAGE ConstraintKinds , DataKinds , PolyKinds , RankNTypes , ImpredicativeTypes , TypeFamilies
, MultiParamTypeClasses , TypeSynonymInstances , FlexibleInstances #
, MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-}
to be implemented by type classes ?
class Foo' a where
bar :: Char -> Bool -> a
quux :: a -> a -> a
class Dict (d :: [*] -> k) (ms :: [*]) where
type First d ms :: *
first :: First d ms
type F = Functor
ERROR ? ! type = forall a . Foo ' a = > ' [ Char - > Bool - > a , a - > a - > a ]
type = ' [ forall a . Foo ' a = > Bool - > a , forall a . Foo ' a = > a - > a - > a ]
type Foo a = '[Char -> Bool -> a, a -> a -> a]
data F (vs :: [*]) = Bar Char Bool | Quux (F vs) (F vs)
class G (vs :: [*]) where
instance Dict F (Foo (F a)) where
type First F Foo = forall a . Foo ' a = > Bool - > a
type First F (Foo (F a)) = Char -> Bool -> F a
first = Bar
instance ( ( G a ) ) where |
d255e0daf0b6a6321542ceecdfac757090a4a0da9e3b0e2b5411ff33f9684155 | racket/redex | close.rkt | #lang racket
;; a function that can close over the free variables of an expression
(provide
;; RACKET
;; [Any-> Boolean: valid expression] ->
[ Lambda.e # : init [ i \x.x ] - > Lambda.e ]
;; ((close-over-fv-with lambda?) e) closes over all free variables in
;; a Lambda term (or sublanguage w/ no new binding constructs) by
;; binding them to (term (lambda (x) x))
;; ((close-over-fv-with lambda?) e #:init i)
;; like above but binds free vars to i
close-over-fv-with
;; any -> (x ...)
;; computes free variables of given term
fv)
(require redex "common.rkt")
;; -------------------------------------------------------
(module+ test
show two dozen terms
( term e )
#:attempts 12
#:prepare (close-over-fv-with lambda?))
;; see 0, can't work
#;
( term e )
#:attempts 12
#:prepare (λ (x) ((close-over-fv-with lambda?) x #:init 0))))
(define ((close-over-fv-with lambda?) e #:init (i (term (lambda (x) x))))
;; this is to work around a bug in redex-check; doesn't always work
(if (lambda? e) (term (close ,e ,i)) i))
(define-metafunction Lambda
close : any any -> any
[(close any_1 any_2)
(let ([x any_2] ...) any_1)
(where (x ...) (unique (fv any_1)))])
(define-metafunction Lambda
;; let : ((x e) ...) e -> e but e plus hole
let : ((x any) ...) any -> any
[(let ([x_lhs any_rhs] ...) any_body)
((lambda (x_lhs ...) any_body) any_rhs ...)])
(define-metafunction Lambda
unique : (x ...) -> (x ...)
[(unique ()) ()]
[(unique (x_1 x_2 ...))
(unique (x_2 ...))
(where #true (in x_1 (x_2 ...)))]
[(unique (x_1 x_2 ...))
(x_1 x_3 ...)
(where (x_3 ...) (unique (x_2 ...)))])
;; -----------------------------------------------------------------------------
(module+ test
(test-equal (term (fv x)) (term (x)))
(test-equal (term (fv (lambda (x) x))) (term ()))
(test-equal (term (fv (lambda (x) (y z x)))) (term (y z))))
(define-metafunction Lambda
fv : any -> (x ...)
[(fv x) (x)]
[(fv (lambda (x ...) any_body))
(subtract (x_e ...) x ...)
(where (x_e ...) (fv any_body))]
[(fv (any_f any_a ...))
(x_f ... x_a ... ...)
(where (x_f ...) (fv any_f))
(where ((x_a ...) ...) ((fv any_a) ...))]
[(fv any) ()])
;; -----------------------------------------------------------------------------
;; (subtract (x ...) x_1 ...) removes x_1 ... from (x ...)
(module+ test
(test-equal (term (subtract (x y z x) x z)) (term (y))))
(define-metafunction Lambda
subtract : (x ...) x ... -> (x ...)
[(subtract (x ...)) (x ...)]
[(subtract (x ...) x_1 x_2 ...)
(subtract (subtract1 (x ...) x_1) x_2 ...)])
(module+ test
(test-equal (term (subtract1 (x y z x) x)) (term (y z))))
(define-metafunction Lambda
subtract1 : (x ...) x -> (x ...)
[(subtract1 (x_1 ... x x_2 ...) x)
(x_1 ... x_2new ...)
(where (x_2new ...) (subtract1 (x_2 ...) x))
(where #false (in x (x_1 ...)))]
[(subtract1 (x ...) x_1) (x ...)])
| null | https://raw.githubusercontent.com/racket/redex/4c2dc96d90cedeb08ec1850575079b952c5ad396/redex-doc/redex/scribblings/long-tut/code/close.rkt | racket | a function that can close over the free variables of an expression
RACKET
[Any-> Boolean: valid expression] ->
((close-over-fv-with lambda?) e) closes over all free variables in
a Lambda term (or sublanguage w/ no new binding constructs) by
binding them to (term (lambda (x) x))
((close-over-fv-with lambda?) e #:init i)
like above but binds free vars to i
any -> (x ...)
computes free variables of given term
-------------------------------------------------------
see 0, can't work
this is to work around a bug in redex-check; doesn't always work
let : ((x e) ...) e -> e but e plus hole
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
(subtract (x ...) x_1 ...) removes x_1 ... from (x ...) | #lang racket
(provide
[ Lambda.e # : init [ i \x.x ] - > Lambda.e ]
close-over-fv-with
fv)
(require redex "common.rkt")
(module+ test
show two dozen terms
( term e )
#:attempts 12
#:prepare (close-over-fv-with lambda?))
( term e )
#:attempts 12
#:prepare (λ (x) ((close-over-fv-with lambda?) x #:init 0))))
(define ((close-over-fv-with lambda?) e #:init (i (term (lambda (x) x))))
(if (lambda? e) (term (close ,e ,i)) i))
(define-metafunction Lambda
close : any any -> any
[(close any_1 any_2)
(let ([x any_2] ...) any_1)
(where (x ...) (unique (fv any_1)))])
(define-metafunction Lambda
let : ((x any) ...) any -> any
[(let ([x_lhs any_rhs] ...) any_body)
((lambda (x_lhs ...) any_body) any_rhs ...)])
(define-metafunction Lambda
unique : (x ...) -> (x ...)
[(unique ()) ()]
[(unique (x_1 x_2 ...))
(unique (x_2 ...))
(where #true (in x_1 (x_2 ...)))]
[(unique (x_1 x_2 ...))
(x_1 x_3 ...)
(where (x_3 ...) (unique (x_2 ...)))])
(module+ test
(test-equal (term (fv x)) (term (x)))
(test-equal (term (fv (lambda (x) x))) (term ()))
(test-equal (term (fv (lambda (x) (y z x)))) (term (y z))))
(define-metafunction Lambda
fv : any -> (x ...)
[(fv x) (x)]
[(fv (lambda (x ...) any_body))
(subtract (x_e ...) x ...)
(where (x_e ...) (fv any_body))]
[(fv (any_f any_a ...))
(x_f ... x_a ... ...)
(where (x_f ...) (fv any_f))
(where ((x_a ...) ...) ((fv any_a) ...))]
[(fv any) ()])
(module+ test
(test-equal (term (subtract (x y z x) x z)) (term (y))))
(define-metafunction Lambda
subtract : (x ...) x ... -> (x ...)
[(subtract (x ...)) (x ...)]
[(subtract (x ...) x_1 x_2 ...)
(subtract (subtract1 (x ...) x_1) x_2 ...)])
(module+ test
(test-equal (term (subtract1 (x y z x) x)) (term (y z))))
(define-metafunction Lambda
subtract1 : (x ...) x -> (x ...)
[(subtract1 (x_1 ... x x_2 ...) x)
(x_1 ... x_2new ...)
(where (x_2new ...) (subtract1 (x_2 ...) x))
(where #false (in x (x_1 ...)))]
[(subtract1 (x ...) x_1) (x ...)])
|
e74cbf0fe7f7cf8872a561fd90bf97d404263c82454153c18485c352fe1a4425 | juspay/atlas | Types.hs | |
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Module : Tools . Metrics . AllocatorMetrics . Types
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Module : Tools.Metrics.AllocatorMetrics.Types
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Tools.Metrics.AllocatorMetrics.Types
( HasAllocatorMetrics,
AllocatorMetricsContainer (..),
module CoreMetrics,
registerAllocatorMetricsContainer,
)
where
import Beckn.Tools.Metrics.CoreMetrics as CoreMetrics
import EulerHS.Prelude
import Prometheus as P
import Utils.Common
type HasAllocatorMetrics m r = (HasFlowEnv m r '["btmMetrics" ::: AllocatorMetricsContainer])
type TaskCounterMetric = P.Counter
type TaskDurationMetric = P.Histogram
type FailedTaskCounterMetric = P.Counter
data AllocatorMetricsContainer = AllocatorMetricsContainer
{ taskCounter :: TaskCounterMetric,
taskDuration :: TaskDurationMetric,
failedTaskCounter :: FailedTaskCounterMetric
}
registerAllocatorMetricsContainer :: IO AllocatorMetricsContainer
registerAllocatorMetricsContainer = do
taskCounter <- registerTaskCounter
taskDuration <- registerTaskDurationMetric
failedTaskCounter <- registerFailedTaskCounter
return $ AllocatorMetricsContainer {..}
registerTaskCounter :: IO TaskCounterMetric
registerTaskCounter = P.register . P.counter $ P.Info "BTM_task_count" ""
registerFailedTaskCounter :: IO FailedTaskCounterMetric
registerFailedTaskCounter = P.register . P.counter $ P.Info "BTM_failed_task_count" ""
registerTaskDurationMetric :: IO TaskDurationMetric
registerTaskDurationMetric = P.register . P.histogram (P.Info "BTM_task_duration" "") $ P.linearBuckets 0 0.1 20
| null | https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/atlas-transport/src/Tools/Metrics/AllocatorMetrics/Types.hs | haskell | |
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Module : Tools . Metrics . AllocatorMetrics . Types
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Module : Tools.Metrics.AllocatorMetrics.Types
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Tools.Metrics.AllocatorMetrics.Types
( HasAllocatorMetrics,
AllocatorMetricsContainer (..),
module CoreMetrics,
registerAllocatorMetricsContainer,
)
where
import Beckn.Tools.Metrics.CoreMetrics as CoreMetrics
import EulerHS.Prelude
import Prometheus as P
import Utils.Common
type HasAllocatorMetrics m r = (HasFlowEnv m r '["btmMetrics" ::: AllocatorMetricsContainer])
type TaskCounterMetric = P.Counter
type TaskDurationMetric = P.Histogram
type FailedTaskCounterMetric = P.Counter
data AllocatorMetricsContainer = AllocatorMetricsContainer
{ taskCounter :: TaskCounterMetric,
taskDuration :: TaskDurationMetric,
failedTaskCounter :: FailedTaskCounterMetric
}
registerAllocatorMetricsContainer :: IO AllocatorMetricsContainer
registerAllocatorMetricsContainer = do
taskCounter <- registerTaskCounter
taskDuration <- registerTaskDurationMetric
failedTaskCounter <- registerFailedTaskCounter
return $ AllocatorMetricsContainer {..}
registerTaskCounter :: IO TaskCounterMetric
registerTaskCounter = P.register . P.counter $ P.Info "BTM_task_count" ""
registerFailedTaskCounter :: IO FailedTaskCounterMetric
registerFailedTaskCounter = P.register . P.counter $ P.Info "BTM_failed_task_count" ""
registerTaskDurationMetric :: IO TaskDurationMetric
registerTaskDurationMetric = P.register . P.histogram (P.Info "BTM_task_duration" "") $ P.linearBuckets 0 0.1 20
|
|
2edda224d7bf8915ab1d23e756973996b101bd4422193828187e59b3ac191e5a | BillHallahan/G2 | Test27.hs | {-@ LIQUID "--short-names" @-}
{-@ LIQUID "--no-termination" @-}
{-@ LIQUID "--prune-unsorted" @-}
module Combined (M, k) where
import Prelude hiding (map)
data X a = X a
data M a = M (X a)
@ k : : M ( { v : Int | v = 1 } ) @
k :: M Int
k = map cs 1
cs :: Int -> Int
cs p = p
map :: (a -> a) -> a -> M a
map f x = M ((\v -> X (f v)) x) | null | https://raw.githubusercontent.com/BillHallahan/G2/21c648d38c380041a9036d0e375ec1d54120f6b4/tests_lh/test_files/Pos/Test27.hs | haskell | @ LIQUID "--short-names" @
@ LIQUID "--no-termination" @
@ LIQUID "--prune-unsorted" @ |
module Combined (M, k) where
import Prelude hiding (map)
data X a = X a
data M a = M (X a)
@ k : : M ( { v : Int | v = 1 } ) @
k :: M Int
k = map cs 1
cs :: Int -> Int
cs p = p
map :: (a -> a) -> a -> M a
map f x = M ((\v -> X (f v)) x) |
017056b90b215c44a410e3ddc1b90c1009f828258215360f153e95424c3c0483 | dimitri/pgloader | copy-rows-in-batch-through-s3.lisp | ;;;
;;; The PostgreSQL COPY TO implementation, using S3 as an intermediate
;;; location for the data.
;;;
;;; This file is only used for Redshift support at the moment.
;;;
(in-package :pgloader.pgcopy)
(defun batch-rows-to-s3-then-copy (table columns copy nbcols queue)
"Add rows that we pop from QUEUE into a batch, that we then COPY over to
PostgreSQL as soon as the batch is full. This allows sophisticated error
handling and recovery, where we can retry rows that are not rejected by
PostgreSQL."
(let ((seconds 0)
(current-batch (make-batch)))
(loop
:for row := (lq:pop-queue queue)
:until (eq :end-of-data row)
:do (multiple-value-bind (maybe-new-batch seconds-in-this-batch)
(add-row-to-current-batch table columns copy nbcols
current-batch row
:send-batch-fn #'send-batch-through-s3
:format-row-fn #'prepare-and-format-row-for-s3)
(setf current-batch maybe-new-batch)
(incf seconds seconds-in-this-batch)))
;; the last batch might not be empty
(unless (= 0 (batch-count current-batch))
(incf seconds (send-batch-through-s3 table columns current-batch)))
seconds))
(defun prepare-and-format-row-for-s3 (copy nbcols row)
"Redshift doesn't know how to parse COPY format, we need to upload CSV
instead. That said, we don't have to be as careful with the data layout
and unicode representation when COPYing from a CSV file as we do when
implementing the data streaming outselves."
(declare (ignore copy nbcols))
(let ((pg-vector-row (cl-csv:write-csv-row (coerce row 'list)
:separator #\,
:quote #\"
:escape #(#\" #\")
:newline #(#\Newline)
:always-quote t)))
(log-message :data "> ~s" pg-vector-row)
(values pg-vector-row (length pg-vector-row))))
(defun send-batch-through-s3 (table columns batch &key (db pomo:*database*))
"Copy current *writer-batch* into TABLE-NAME."
(let ((batch-start-time (get-internal-real-time))
(table-name (format-table-name table))
(pomo:*database* db))
;;
We first upload the batch of data we have to S3
;;
(multiple-value-bind (aws-access-key-id
aws-secret-access-key
aws-region
aws-s3-bucket)
;; TODO: implement --aws--profile and use it here
(get-aws-credentials-and-setup)
(let ((s3-filename (format nil "~a.~a.~a"
(format-table-name table)
(lp:kernel-worker-index)
(batch-start batch)))
(vector (batch-as-single-vector batch)))
(log-message :info
"Uploading a batch of ~a rows [~a] to s3://~a/~a"
(batch-count batch)
(pretty-print-bytes (batch-bytes batch))
aws-s3-bucket
s3-filename)
(zs3:put-vector vector
aws-s3-bucket
s3-filename
:credentials (list aws-access-key-id
aws-secret-access-key))
;; Now we COPY the data from S3 to Redshift:
;;
;;
;;
(handler-case
(with-pgsql-transaction (:database db)
(let ((sql (format nil "COPY ~a FROM 's3://~a/~a' FORMAT CSV TIMEFORMAT 'auto' REGION '~a' ACCESS_KEY_ID '~a'"
table-name
aws-s3-bucket
s3-filename
aws-region
aws-access-key-id)))
(log-message :sql "~a" sql)
(let ((sql-with-access-key
(format nil "~a
SECRET_ACCESS_KEY '~a'"
sql
aws-secret-access-key)))
(pomo:execute sql-with-access-key))))
;; If PostgreSQL signals a data error, process the batch by isolating
;; erroneous data away and retrying the rest.
(postgresql-retryable (condition)
(pomo:execute "ROLLBACK")
(log-message :error "PostgreSQL [~s] ~a" table-name condition)
(update-stats :data table :errs (batch-count batch)))
(postgresql-unavailable (condition)
(log-message :error "[PostgreSQL ~s] ~a" table-name condition)
(log-message :error "Copy Batch reconnecting to PostgreSQL")
in order to avoid Socket error in " connect " : ECONNREFUSED if we
;; try just too soon, wait a little
(sleep 2)
(cl-postgres:reopen-database db)
(send-batch-through-s3 table columns batch :db db))
(copy-init-error (condition)
Could n't init the COPY protocol , process the condition up the
;; stack
(update-stats :data table :errs 1)
(error condition))
(condition (c)
;; non retryable failures
(log-message :error "Non-retryable error ~a" c)
(pomo:execute "ROLLBACK")))))
;; now log about having send a batch, and update our stats with the
;; time that took
(let ((seconds (elapsed-time-since batch-start-time)))
(log-message :debug
"send-batch[~a] ~a ~d row~:p [~a] in ~6$s~@[ [oversized]~]"
(lp:kernel-worker-index)
(format-table-name table)
(batch-count batch)
(pretty-print-bytes (batch-bytes batch))
seconds
(batch-oversized-p batch))
(update-stats :data table
:rows (batch-count batch)
:bytes (batch-bytes batch))
;; and return batch-seconds
seconds)))
(defun batch-as-single-vector (batch)
"For communicating with AWS S3, we finalize our batch data into a single
vector."
(if (= 0 (batch-count batch))
nil
;; non-empty batch
;;
;; first compute the total number of bytes we need to represent this
;; batch, and then flatten it into a single vector of that size.
;;
;; So now we now how many bytes we need to finalize this batch
;;
(let* ((bytes (batch-bytes batch))
(vector (make-array bytes :element-type 'character)))
(loop :for count :below (batch-count batch)
:for pos := 0 :then (+ pos (length row))
:for row :across (batch-data batch)
:do (when row
(replace vector row :start1 pos)))
vector)))
;;;
;;; S3 support needs some AWS specific setup. We use the same configuration
files as the main AWS command line interface , as documented at the
;;; following places:
;;;
;;; -config-files.html
;;; -multiple-profiles.html
;;; -environment.html
;;;
(defun get-aws-credentials-and-setup (&optional profile)
"Returns AWS access key id, secret access key, region and S3 bucket-name
from environment or ~/.aws/ configuration files, as multiple values."
(let* (aws-access-key-id
aws-secret-access-key
aws-region
aws-s3-bucket-name
(aws-directory (uiop:native-namestring
(uiop:merge-pathnames* ".aws/"
(user-homedir-pathname))))
(aws-config-fn (make-pathname :name "config"
:directory aws-directory))
(aws-creds-fn (make-pathname :name "credentials"
:directory aws-directory))
(aws-config (ini:make-config))
(credentials (ini:make-config))
(conf-profile (if profile (format nil "profile ~a" profile)
"default"))
(creds-profile (or profile "default")))
;; read config files
(ini:read-files aws-config (list aws-config-fn))
(ini:read-files credentials (list aws-creds-fn))
;; get values from the environment, and if not in the env, from the
;; configuration files.
(setf aws-access-key-id
(or (uiop:getenv "AWS_ACCESS_KEY_ID")
(ini:get-option credentials creds-profile "aws_access_key_id")))
(setf aws-secret-access-key
(or (uiop:getenv "AWS_SECRET_ACCESS_KEY")
(ini:get-option credentials creds-profile "aws_secret_access_key")))
(setf aws-region
(or (uiop:getenv "AWS_DEFAULT_REGION")
(ini:get-option aws-config conf-profile "region")))
(setf aws-s3-bucket-name (or (uiop:getenv "AWS_S3_BUCKET_NAME")
"pgloader"))
(values aws-access-key-id
aws-secret-access-key
aws-region
aws-s3-bucket-name)))
| null | https://raw.githubusercontent.com/dimitri/pgloader/3047c9afe141763e9e7ec05b7f2a6aa97cf06801/src/pg-copy/copy-rows-in-batch-through-s3.lisp | lisp |
The PostgreSQL COPY TO implementation, using S3 as an intermediate
location for the data.
This file is only used for Redshift support at the moment.
the last batch might not be empty
TODO: implement --aws--profile and use it here
Now we COPY the data from S3 to Redshift:
If PostgreSQL signals a data error, process the batch by isolating
erroneous data away and retrying the rest.
try just too soon, wait a little
stack
non retryable failures
now log about having send a batch, and update our stats with the
time that took
and return batch-seconds
non-empty batch
first compute the total number of bytes we need to represent this
batch, and then flatten it into a single vector of that size.
So now we now how many bytes we need to finalize this batch
S3 support needs some AWS specific setup. We use the same configuration
following places:
-config-files.html
-multiple-profiles.html
-environment.html
read config files
get values from the environment, and if not in the env, from the
configuration files. | (in-package :pgloader.pgcopy)
(defun batch-rows-to-s3-then-copy (table columns copy nbcols queue)
"Add rows that we pop from QUEUE into a batch, that we then COPY over to
PostgreSQL as soon as the batch is full. This allows sophisticated error
handling and recovery, where we can retry rows that are not rejected by
PostgreSQL."
(let ((seconds 0)
(current-batch (make-batch)))
(loop
:for row := (lq:pop-queue queue)
:until (eq :end-of-data row)
:do (multiple-value-bind (maybe-new-batch seconds-in-this-batch)
(add-row-to-current-batch table columns copy nbcols
current-batch row
:send-batch-fn #'send-batch-through-s3
:format-row-fn #'prepare-and-format-row-for-s3)
(setf current-batch maybe-new-batch)
(incf seconds seconds-in-this-batch)))
(unless (= 0 (batch-count current-batch))
(incf seconds (send-batch-through-s3 table columns current-batch)))
seconds))
(defun prepare-and-format-row-for-s3 (copy nbcols row)
"Redshift doesn't know how to parse COPY format, we need to upload CSV
instead. That said, we don't have to be as careful with the data layout
and unicode representation when COPYing from a CSV file as we do when
implementing the data streaming outselves."
(declare (ignore copy nbcols))
(let ((pg-vector-row (cl-csv:write-csv-row (coerce row 'list)
:separator #\,
:quote #\"
:escape #(#\" #\")
:newline #(#\Newline)
:always-quote t)))
(log-message :data "> ~s" pg-vector-row)
(values pg-vector-row (length pg-vector-row))))
(defun send-batch-through-s3 (table columns batch &key (db pomo:*database*))
"Copy current *writer-batch* into TABLE-NAME."
(let ((batch-start-time (get-internal-real-time))
(table-name (format-table-name table))
(pomo:*database* db))
We first upload the batch of data we have to S3
(multiple-value-bind (aws-access-key-id
aws-secret-access-key
aws-region
aws-s3-bucket)
(get-aws-credentials-and-setup)
(let ((s3-filename (format nil "~a.~a.~a"
(format-table-name table)
(lp:kernel-worker-index)
(batch-start batch)))
(vector (batch-as-single-vector batch)))
(log-message :info
"Uploading a batch of ~a rows [~a] to s3://~a/~a"
(batch-count batch)
(pretty-print-bytes (batch-bytes batch))
aws-s3-bucket
s3-filename)
(zs3:put-vector vector
aws-s3-bucket
s3-filename
:credentials (list aws-access-key-id
aws-secret-access-key))
(handler-case
(with-pgsql-transaction (:database db)
(let ((sql (format nil "COPY ~a FROM 's3://~a/~a' FORMAT CSV TIMEFORMAT 'auto' REGION '~a' ACCESS_KEY_ID '~a'"
table-name
aws-s3-bucket
s3-filename
aws-region
aws-access-key-id)))
(log-message :sql "~a" sql)
(let ((sql-with-access-key
(format nil "~a
SECRET_ACCESS_KEY '~a'"
sql
aws-secret-access-key)))
(pomo:execute sql-with-access-key))))
(postgresql-retryable (condition)
(pomo:execute "ROLLBACK")
(log-message :error "PostgreSQL [~s] ~a" table-name condition)
(update-stats :data table :errs (batch-count batch)))
(postgresql-unavailable (condition)
(log-message :error "[PostgreSQL ~s] ~a" table-name condition)
(log-message :error "Copy Batch reconnecting to PostgreSQL")
in order to avoid Socket error in " connect " : ECONNREFUSED if we
(sleep 2)
(cl-postgres:reopen-database db)
(send-batch-through-s3 table columns batch :db db))
(copy-init-error (condition)
Could n't init the COPY protocol , process the condition up the
(update-stats :data table :errs 1)
(error condition))
(condition (c)
(log-message :error "Non-retryable error ~a" c)
(pomo:execute "ROLLBACK")))))
(let ((seconds (elapsed-time-since batch-start-time)))
(log-message :debug
"send-batch[~a] ~a ~d row~:p [~a] in ~6$s~@[ [oversized]~]"
(lp:kernel-worker-index)
(format-table-name table)
(batch-count batch)
(pretty-print-bytes (batch-bytes batch))
seconds
(batch-oversized-p batch))
(update-stats :data table
:rows (batch-count batch)
:bytes (batch-bytes batch))
seconds)))
(defun batch-as-single-vector (batch)
"For communicating with AWS S3, we finalize our batch data into a single
vector."
(if (= 0 (batch-count batch))
nil
(let* ((bytes (batch-bytes batch))
(vector (make-array bytes :element-type 'character)))
(loop :for count :below (batch-count batch)
:for pos := 0 :then (+ pos (length row))
:for row :across (batch-data batch)
:do (when row
(replace vector row :start1 pos)))
vector)))
files as the main AWS command line interface , as documented at the
(defun get-aws-credentials-and-setup (&optional profile)
"Returns AWS access key id, secret access key, region and S3 bucket-name
from environment or ~/.aws/ configuration files, as multiple values."
(let* (aws-access-key-id
aws-secret-access-key
aws-region
aws-s3-bucket-name
(aws-directory (uiop:native-namestring
(uiop:merge-pathnames* ".aws/"
(user-homedir-pathname))))
(aws-config-fn (make-pathname :name "config"
:directory aws-directory))
(aws-creds-fn (make-pathname :name "credentials"
:directory aws-directory))
(aws-config (ini:make-config))
(credentials (ini:make-config))
(conf-profile (if profile (format nil "profile ~a" profile)
"default"))
(creds-profile (or profile "default")))
(ini:read-files aws-config (list aws-config-fn))
(ini:read-files credentials (list aws-creds-fn))
(setf aws-access-key-id
(or (uiop:getenv "AWS_ACCESS_KEY_ID")
(ini:get-option credentials creds-profile "aws_access_key_id")))
(setf aws-secret-access-key
(or (uiop:getenv "AWS_SECRET_ACCESS_KEY")
(ini:get-option credentials creds-profile "aws_secret_access_key")))
(setf aws-region
(or (uiop:getenv "AWS_DEFAULT_REGION")
(ini:get-option aws-config conf-profile "region")))
(setf aws-s3-bucket-name (or (uiop:getenv "AWS_S3_BUCKET_NAME")
"pgloader"))
(values aws-access-key-id
aws-secret-access-key
aws-region
aws-s3-bucket-name)))
|
09e8289d5341c7d987274695cd376a1c25dec459e4043b1f6a9e2373004b088e | xguerin/netml | NetML_Layer_III_IPv4.mli | module Address : sig
type t = int * int * int * int [@@deriving yojson]
end
type t = {
source : Address.t;
destination : Address.t;
length : int;
protocol : NetML_Layer_IV.Protocol.t option;
} [@@deriving yojson]
val decode : Bitstring.t -> t option
val expand : Bitstring.t -> (NetML_Layer_IV.Protocol.t * Bitstring.t) option
| null | https://raw.githubusercontent.com/xguerin/netml/de9d277d2f1ac055aea391b89391df6830f80eff/src/NetML_Layer_III_IPv4.mli | ocaml | module Address : sig
type t = int * int * int * int [@@deriving yojson]
end
type t = {
source : Address.t;
destination : Address.t;
length : int;
protocol : NetML_Layer_IV.Protocol.t option;
} [@@deriving yojson]
val decode : Bitstring.t -> t option
val expand : Bitstring.t -> (NetML_Layer_IV.Protocol.t * Bitstring.t) option
|
|
3a06416afd138440e1288344554b7b74d79203d43c9cdbe4fdef7a94d2aadedd | gsakkas/rite | 20060322-00:47:36-635d92e5e80fdb07be8405858041dcbd.seminal.ml | exception Unimplemented
exception AlreadyDone
exception InvalidAngle
let pi = 4.0 *. atan 1.0
(*** part a ***)
type move =
Home
| Forward of float
| Turn of float
| For of int * move list
(*** part b ***)
let makePoly sides len =
let angle = pi-.((pi*.(float_of_int (sides-2)))/.(float_of_int sides)) in
let rec createMoveList moves acc =
if moves = sides
then
acc
else
(createMoveList (moves+1) (Forward(len)::Turn(angle)::acc))in
let moveList = createMoveList 0 [] in
For((sides*2), moveList)
(*** part c ***)
let interpLarge (movelist : move list) : (float*float) list =
let rec loop movelist x y dir acc =
if (dir >= (2*.pi)) then
loop movelist x y (dir - (2*.pi)) acc
else
match movelist with
[] -> acc
| Home::tl -> loop tl 0.0 0.0 dir ((0.0,0.0)::acc)
| Turn(newDir)::tl -> loop tl x y (dir+.newDir) acc
| For(moves, lst)::tl ->
let rec finalLst counter searchLst acc2=
if counter = 0 then
acc2
else match searchLst with
[]->acc2
| hd::tail -> finalLst (counter-1) tail (hd::acc2) in
loop (finalLst moves lst tl) x y dir acc
| Forward(len)::tl ->
let xLen = (len*.(cos dir)) in
let yLen = (len*.(sin dir)) in
if (dir >= 0.0 && dir < (pi/.2.0)) then
loop tl (x+.xLen) (y+.yLen) dir ((x+.xLen, y+.yLen)::acc)
else
if (dir >= (pi/.2.0) && dir < pi) then
loop tl (x-.xLen) (y+.yLen) dir ((x-.xLen, y+.yLen)::acc)
else if (dir >= pi && dir <((3.0*.pi)/.2.0)) then
loop tl (x-.xLen) (y-.yLen) dir ((x-.xLen, y-.yLen)::acc)
else if (dir >=((3.0*.pi)/.2.0) && dir< (2.0*.pi))then
loop tl (x+.xLen) (y-.yLen) dir ((x+.xLen, y-.yLen)::acc)
else raise InvalidAngle
in List.rev (loop movelist 0.0 0.0 0.0 [(0.0,0.0)])
(*** part d ***)
let interpSmall ( movelist : move list ) : ( float*float ) list =
let interpSmallStep movelist x y dir : move list * float * float * float =
match movelist with
[ ] - > raise Unimplemented
| Home::tl - > raise ( * # # # # # # # # # # # # # # # # # # # # # # # # # # #
let interpSmallStep movelist x y dir : move list * float * float * float =
match movelist with
[] -> raise Unimplemented
| Home::tl -> raise Unimplemented
(* ########################### *)
in
let rec loop movelist x y dir acc =
raise Unimplemented
in
List.rev (loop movelist 0.0 0.0 0.0 [(0.0,0.0)])
(*** part e ***)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
(*** part f ***)
let interpTrans movelist : float->float->float-> (float * float) list * float=
# # # # # # # # # # # # # # # # # # # # # # # # #
in
match movelist with
[] -> raise Unimplemented
| Home::tl -> raise Unimplemented
# # # # # # # # # # # # # # # # # # # # # # # # # # #
(*** possibly helpful testing code ***)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
##
######################################
##############################################
##########################################
###########################################################################
################
################
############
#################
################################################################################
###########
###################################
###pr ansS; print_newline ();
pr ansI; print_newline ();###
*)
| null | https://raw.githubusercontent.com/gsakkas/rite/958a0ad2460e15734447bc07bd181f5d35956d3b/features/data/seminal/20060322-00%3A47%3A36-635d92e5e80fdb07be8405858041dcbd.seminal.ml | ocaml | ** part a **
** part b **
** part c **
** part d **
###########################
** part e **
** part f **
** possibly helpful testing code ** | exception Unimplemented
exception AlreadyDone
exception InvalidAngle
let pi = 4.0 *. atan 1.0
type move =
Home
| Forward of float
| Turn of float
| For of int * move list
let makePoly sides len =
let angle = pi-.((pi*.(float_of_int (sides-2)))/.(float_of_int sides)) in
let rec createMoveList moves acc =
if moves = sides
then
acc
else
(createMoveList (moves+1) (Forward(len)::Turn(angle)::acc))in
let moveList = createMoveList 0 [] in
For((sides*2), moveList)
let interpLarge (movelist : move list) : (float*float) list =
let rec loop movelist x y dir acc =
if (dir >= (2*.pi)) then
loop movelist x y (dir - (2*.pi)) acc
else
match movelist with
[] -> acc
| Home::tl -> loop tl 0.0 0.0 dir ((0.0,0.0)::acc)
| Turn(newDir)::tl -> loop tl x y (dir+.newDir) acc
| For(moves, lst)::tl ->
let rec finalLst counter searchLst acc2=
if counter = 0 then
acc2
else match searchLst with
[]->acc2
| hd::tail -> finalLst (counter-1) tail (hd::acc2) in
loop (finalLst moves lst tl) x y dir acc
| Forward(len)::tl ->
let xLen = (len*.(cos dir)) in
let yLen = (len*.(sin dir)) in
if (dir >= 0.0 && dir < (pi/.2.0)) then
loop tl (x+.xLen) (y+.yLen) dir ((x+.xLen, y+.yLen)::acc)
else
if (dir >= (pi/.2.0) && dir < pi) then
loop tl (x-.xLen) (y+.yLen) dir ((x-.xLen, y+.yLen)::acc)
else if (dir >= pi && dir <((3.0*.pi)/.2.0)) then
loop tl (x-.xLen) (y-.yLen) dir ((x-.xLen, y-.yLen)::acc)
else if (dir >=((3.0*.pi)/.2.0) && dir< (2.0*.pi))then
loop tl (x+.xLen) (y-.yLen) dir ((x+.xLen, y-.yLen)::acc)
else raise InvalidAngle
in List.rev (loop movelist 0.0 0.0 0.0 [(0.0,0.0)])
let interpSmall ( movelist : move list ) : ( float*float ) list =
let interpSmallStep movelist x y dir : move list * float * float * float =
match movelist with
[ ] - > raise Unimplemented
| Home::tl - > raise ( * # # # # # # # # # # # # # # # # # # # # # # # # # # #
let interpSmallStep movelist x y dir : move list * float * float * float =
match movelist with
[] -> raise Unimplemented
| Home::tl -> raise Unimplemented
in
let rec loop movelist x y dir acc =
raise Unimplemented
in
List.rev (loop movelist 0.0 0.0 0.0 [(0.0,0.0)])
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
let interpTrans movelist : float->float->float-> (float * float) list * float=
# # # # # # # # # # # # # # # # # # # # # # # # #
in
match movelist with
[] -> raise Unimplemented
| Home::tl -> raise Unimplemented
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
##
######################################
##############################################
##########################################
###########################################################################
################
################
############
#################
################################################################################
###########
###################################
###pr ansS; print_newline ();
pr ansI; print_newline ();###
*)
|
6b49eca52303c9a6ab4f7ef2e593f091a62f5c474dbdd5528fe8716b8a0c4886 | mcorbin/tour-of-clojure | forms.clj | (ns tourofclojure.pages.forms
(:require [hiccup.element :refer [link-to]]
[clojure.java.io :as io]
[tourofclojure.pages.util :refer [navigation-block]]))
(def code
(slurp (io/resource "public/pages/code/forms.clj")))
(defn desc
[previous next lang]
(condp = lang
"fr" [:div
[:h2 "Forms et l'appel de fonctions"]
[:p "La syntaxe de Clojure peut sembler déroutante aux premiers abords."
" Pourtant, celle-ci est très simple et ne cache aucun piège."]
[:p "La règle est simple. Clojure est composé de forms."
" Voici un exemple de form:"]
[:pre [:code {:class "clojure"} "(operation param1 param2 ...)"]]
[:p "Et c'est à peu près tout. On ouvre une parenthèse, on a une"
" opération, et une suite de paramètres."]
[:p "Par exemple, " [:b "str"] " prend un nombre indéfini de"
" paramètres et va retourner la concaténation de ces paramètres."
" Dans un autre langage, on écrirait quelque chose comme:"]
[:pre [:code {:class "java"} "str(\"Hello\", \" world\", \" !!!\")"]]
[:p "En Clojure, on déplace juste la première parenthèse pour englober"
" le nom de fonction:"]
[:pre [:code "(str \"Hello\" \" world\" \" !!!\")"]]
[:p "De la même façon, " [:b "println"] " prend également un nombre"
" indéfini de paramètres et retourne " [:b "nil"] "."
" D'ailleurs, j'ajouterais souvent un saut de ligne aux différents"
" appels de " [:b "println"] " dans mes exemples, dans le but de formater l'affichage. Par exemple, le code suivant imprimera le résultat de"
[:b " (+ 1 2)"] " suivi d'un saut de ligne:"]
[:pre [:code "(println (+ 1 2) \"\\n\")"]]
[:p "Evidemment, si l'élement juste après la parenthèse d'une form"
" n'est pas une fonction, une erreur se produira, comme dans:"]
[:pre [:code {:class "java"} "(1 2 3)"]]
[:p "Cette form produira une erreur, car " [:b "1"] " n'est pas une"
" fonction."]
[:p "Le code Clojure consiste en forms imbriquées les unes dans les autres:"]
[:pre [:code "(+ 2 3 (* 10 10))"]]
[:p "Ici, la form réalisant la multiplication est imbriquée dans celle de"
" l'addition. Le résultat sera calculé de la manière suivante :"]
[:ul
[:li [:b "(* 10 10)"] " est calculé, ce qui donne 100."]
[:li "Le résultat est utilisé dans l'addition, ce qui donne "
[:b "(+ 2 3 100)"] ". Le résultat final est donc 105."]]
(navigation-block previous next)]
[:h2 "Language not supported."]))
(defn page
[previous next lang]
[(desc previous next lang)
code])
| null | https://raw.githubusercontent.com/mcorbin/tour-of-clojure/57f97b68ca1a8c96904bfb960f515217eeda24a6/src/tourofclojure/pages/forms.clj | clojure | (ns tourofclojure.pages.forms
(:require [hiccup.element :refer [link-to]]
[clojure.java.io :as io]
[tourofclojure.pages.util :refer [navigation-block]]))
(def code
(slurp (io/resource "public/pages/code/forms.clj")))
(defn desc
[previous next lang]
(condp = lang
"fr" [:div
[:h2 "Forms et l'appel de fonctions"]
[:p "La syntaxe de Clojure peut sembler déroutante aux premiers abords."
" Pourtant, celle-ci est très simple et ne cache aucun piège."]
[:p "La règle est simple. Clojure est composé de forms."
" Voici un exemple de form:"]
[:pre [:code {:class "clojure"} "(operation param1 param2 ...)"]]
[:p "Et c'est à peu près tout. On ouvre une parenthèse, on a une"
" opération, et une suite de paramètres."]
[:p "Par exemple, " [:b "str"] " prend un nombre indéfini de"
" paramètres et va retourner la concaténation de ces paramètres."
" Dans un autre langage, on écrirait quelque chose comme:"]
[:pre [:code {:class "java"} "str(\"Hello\", \" world\", \" !!!\")"]]
[:p "En Clojure, on déplace juste la première parenthèse pour englober"
" le nom de fonction:"]
[:pre [:code "(str \"Hello\" \" world\" \" !!!\")"]]
[:p "De la même façon, " [:b "println"] " prend également un nombre"
" indéfini de paramètres et retourne " [:b "nil"] "."
" D'ailleurs, j'ajouterais souvent un saut de ligne aux différents"
" appels de " [:b "println"] " dans mes exemples, dans le but de formater l'affichage. Par exemple, le code suivant imprimera le résultat de"
[:b " (+ 1 2)"] " suivi d'un saut de ligne:"]
[:pre [:code "(println (+ 1 2) \"\\n\")"]]
[:p "Evidemment, si l'élement juste après la parenthèse d'une form"
" n'est pas une fonction, une erreur se produira, comme dans:"]
[:pre [:code {:class "java"} "(1 2 3)"]]
[:p "Cette form produira une erreur, car " [:b "1"] " n'est pas une"
" fonction."]
[:p "Le code Clojure consiste en forms imbriquées les unes dans les autres:"]
[:pre [:code "(+ 2 3 (* 10 10))"]]
[:p "Ici, la form réalisant la multiplication est imbriquée dans celle de"
" l'addition. Le résultat sera calculé de la manière suivante :"]
[:ul
[:li [:b "(* 10 10)"] " est calculé, ce qui donne 100."]
[:li "Le résultat est utilisé dans l'addition, ce qui donne "
[:b "(+ 2 3 100)"] ". Le résultat final est donc 105."]]
(navigation-block previous next)]
[:h2 "Language not supported."]))
(defn page
[previous next lang]
[(desc previous next lang)
code])
|
|
7869ad06f8e14cedccbb4939ace22ddcb7768b0cfed43beff5074378d3cc8451 | slipstream/SlipStreamServer | utils.clj | (ns com.sixsq.slipstream.ssclj.resources.event.utils
(:require [clj-time.core :as time]
[com.sixsq.slipstream.ssclj.resources.common.schema :as c]
[com.sixsq.slipstream.ssclj.resources.common.std-crud :as std-crud]
[com.sixsq.slipstream.ssclj.resources.common.utils :as u]))
(def resource-name "Event")
(def resource-url (u/de-camelcase resource-name))
(def resource-uri (str c/cimi-schema-uri resource-name))
(def collection-acl {:owner {:principal "ADMIN"
:type "ROLE"}
:rules [{:principal "ANON"
:type "ROLE"
:right "ALL"}]})
(def severity-critical "critical")
(def severity-high "high")
(def severity-medium "medium")
(def severity-low "low")
(def type-state "state")
(def type-alarm "alarm")
(def type-action "action")
(def type-system "system")
(def add-impl (std-crud/add-fn resource-name collection-acl resource-uri))
(defn create-event
[resource-href, message, acl,
& {:keys [severity type],
:or {severity severity-medium
type type-action}}]
(let [event-map {:resourceURI resource-uri
:content {:resource {:href resource-href}
:state message}
:severity severity
:type type
:timestamp (u/unparse-timestamp-datetime (time/now))
:acl acl}
create-request {:params {:resource-name resource-url}
:identity std-crud/internal-identity
:body event-map}]
(add-impl create-request)))
| null | https://raw.githubusercontent.com/slipstream/SlipStreamServer/3ee5c516877699746c61c48fc72779fe3d4e4652/cimi-resources/src/com/sixsq/slipstream/ssclj/resources/event/utils.clj | clojure | (ns com.sixsq.slipstream.ssclj.resources.event.utils
(:require [clj-time.core :as time]
[com.sixsq.slipstream.ssclj.resources.common.schema :as c]
[com.sixsq.slipstream.ssclj.resources.common.std-crud :as std-crud]
[com.sixsq.slipstream.ssclj.resources.common.utils :as u]))
(def resource-name "Event")
(def resource-url (u/de-camelcase resource-name))
(def resource-uri (str c/cimi-schema-uri resource-name))
(def collection-acl {:owner {:principal "ADMIN"
:type "ROLE"}
:rules [{:principal "ANON"
:type "ROLE"
:right "ALL"}]})
(def severity-critical "critical")
(def severity-high "high")
(def severity-medium "medium")
(def severity-low "low")
(def type-state "state")
(def type-alarm "alarm")
(def type-action "action")
(def type-system "system")
(def add-impl (std-crud/add-fn resource-name collection-acl resource-uri))
(defn create-event
[resource-href, message, acl,
& {:keys [severity type],
:or {severity severity-medium
type type-action}}]
(let [event-map {:resourceURI resource-uri
:content {:resource {:href resource-href}
:state message}
:severity severity
:type type
:timestamp (u/unparse-timestamp-datetime (time/now))
:acl acl}
create-request {:params {:resource-name resource-url}
:identity std-crud/internal-identity
:body event-map}]
(add-impl create-request)))
|
|
dd1e7b1e790481fd9f4b6d55180b142a17be49c07889d772a453dd0a7901b06c | jobjo/popper | tag.ml | type t =
| Size
| Sign
| Function
| Char
| Int
| Float
| Bool
| Value
| Operator
| List
| Choice
| Name of string
| Sub_list
let is_operator t = t = Operator || t = Size
let is_value t = not @@ is_operator t
let to_string = function
| Sign -> "sign"
| Function -> "function"
| Char -> "char"
| Int -> "int"
| Float -> "float"
| Bool -> "bool"
| Value -> "value"
| Operator -> "operator"
| Size -> "size"
| List -> Printf.sprintf "list"
| Choice -> "choice"
| Name s -> Printf.sprintf "name[%s]" s
| Sub_list -> "sub-list"
| null | https://raw.githubusercontent.com/jobjo/popper/33da372946d1d842f75994e086fa81c8cf62986e/src/lib/tag.ml | ocaml | type t =
| Size
| Sign
| Function
| Char
| Int
| Float
| Bool
| Value
| Operator
| List
| Choice
| Name of string
| Sub_list
let is_operator t = t = Operator || t = Size
let is_value t = not @@ is_operator t
let to_string = function
| Sign -> "sign"
| Function -> "function"
| Char -> "char"
| Int -> "int"
| Float -> "float"
| Bool -> "bool"
| Value -> "value"
| Operator -> "operator"
| Size -> "size"
| List -> Printf.sprintf "list"
| Choice -> "choice"
| Name s -> Printf.sprintf "name[%s]" s
| Sub_list -> "sub-list"
|
|
7e37cacb9cdba361f11955fd8154e05552d2189744e6e0a7d2b03c0433a2ff60 | paulbutcher/electron-app | arithmetic.cljs | (ns {{name}}.renderer.arithmetic)
(defn multiply [x y]
(* x y))
| null | https://raw.githubusercontent.com/paulbutcher/electron-app/2b67a893b7dba60bf91d504a2daa009149c6fc9b/resources/clj/new/electron_app/src/renderer/arithmetic.cljs | clojure | (ns {{name}}.renderer.arithmetic)
(defn multiply [x y]
(* x y))
|
|
0b351b339086238ac6aac0879fe91fa75cbec43f67c33dea4c3241afa5abf0c4 | ghc/ghc | TmpFs.hs | # LANGUAGE CPP #
-- | Temporary file-system management
module GHC.Utils.TmpFs
( TmpFs
, initTmpFs
, forkTmpFsFrom
, mergeTmpFsInto
, PathsToClean(..)
, emptyPathsToClean
, TempFileLifetime(..)
, TempDir (..)
, cleanTempDirs
, cleanTempFiles
, cleanCurrentModuleTempFiles
, addFilesToClean
, changeTempFilesLifetime
, newTempName
, newTempLibName
, newTempSubDir
, withSystemTempDirectory
, withTempDirectory
)
where
import GHC.Prelude
import GHC.Utils.Error
import GHC.Utils.Outputable
import GHC.Utils.Logger
import GHC.Utils.Misc
import GHC.Utils.Exception as Exception
import GHC.Driver.Phases
import Data.List (partition)
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Map as Map
import Data.Map (Map)
import Data.IORef
import System.Directory
import System.FilePath
import System.IO.Error
#if !defined(mingw32_HOST_OS)
import qualified System.Posix.Internals
#endif
-- | Temporary file-system
data TmpFs = TmpFs
{ tmp_dirs_to_clean :: IORef (Map FilePath FilePath)
^ Maps system temporary directory ( passed via settings or DynFlags ) to
-- an actual temporary directory for this process.
--
-- It's a Map probably to support changing the system temporary directory
-- over time.
--
-- Shared with forked TmpFs.
, tmp_next_suffix :: IORef Int
-- ^ The next available suffix to uniquely name a temp file, updated
-- atomically.
--
-- Shared with forked TmpFs.
, tmp_files_to_clean :: IORef PathsToClean
-- ^ Files to clean (per session or per module)
--
-- Not shared with forked TmpFs.
, tmp_subdirs_to_clean :: IORef PathsToClean
^ Subdirs to clean ( per session or per module )
--
-- Not shared with forked TmpFs.
}
| A collection of paths that must be deleted before ghc exits .
data PathsToClean = PathsToClean
{ ptcGhcSession :: !(Set FilePath)
^ Paths that will be deleted at the end of )
, ptcCurrentModule :: !(Set FilePath)
-- ^ Paths that will be deleted the next time
-- 'cleanCurrentModuleTempFiles' is called, or otherwise at the end of
-- the session.
}
-- | Used when a temp file is created. This determines which component Set of
-- PathsToClean will get the temp file
data TempFileLifetime
= TFL_CurrentModule
-- ^ A file with lifetime TFL_CurrentModule will be cleaned up at the
-- end of upweep_mod
| TFL_GhcSession
-- ^ A file with lifetime TFL_GhcSession will be cleaned up at the end of
-- runGhc(T)
deriving (Show)
newtype TempDir = TempDir FilePath
| An empty PathsToClean
emptyPathsToClean :: PathsToClean
emptyPathsToClean = PathsToClean Set.empty Set.empty
| Merge two PathsToClean
mergePathsToClean :: PathsToClean -> PathsToClean -> PathsToClean
mergePathsToClean x y = PathsToClean
{ ptcGhcSession = Set.union (ptcGhcSession x) (ptcGhcSession y)
, ptcCurrentModule = Set.union (ptcCurrentModule x) (ptcCurrentModule y)
}
-- | Initialise an empty TmpFs
initTmpFs :: IO TmpFs
initTmpFs = do
files <- newIORef emptyPathsToClean
subdirs <- newIORef emptyPathsToClean
dirs <- newIORef Map.empty
next <- newIORef 0
return $ TmpFs
{ tmp_files_to_clean = files
, tmp_subdirs_to_clean = subdirs
, tmp_dirs_to_clean = dirs
, tmp_next_suffix = next
}
-- | Initialise an empty TmpFs sharing unique numbers and per-process temporary
-- directories with the given TmpFs
--
-- It's not safe to use the subdirs created by the original TmpFs with the
-- forked one. Use @newTempSubDir@ to create new subdirs instead.
forkTmpFsFrom :: TmpFs -> IO TmpFs
forkTmpFsFrom old = do
files <- newIORef emptyPathsToClean
subdirs <- newIORef emptyPathsToClean
return $ TmpFs
{ tmp_files_to_clean = files
, tmp_subdirs_to_clean = subdirs
, tmp_dirs_to_clean = tmp_dirs_to_clean old
, tmp_next_suffix = tmp_next_suffix old
}
| Merge the first TmpFs into the second .
--
The first TmpFs is returned emptied .
mergeTmpFsInto :: TmpFs -> TmpFs -> IO ()
mergeTmpFsInto src dst = do
src_files <- atomicModifyIORef' (tmp_files_to_clean src) (\s -> (emptyPathsToClean, s))
src_subdirs <- atomicModifyIORef' (tmp_subdirs_to_clean src) (\s -> (emptyPathsToClean, s))
atomicModifyIORef' (tmp_files_to_clean dst) (\s -> (mergePathsToClean src_files s, ()))
atomicModifyIORef' (tmp_subdirs_to_clean dst) (\s -> (mergePathsToClean src_subdirs s, ()))
cleanTempDirs :: Logger -> TmpFs -> IO ()
cleanTempDirs logger tmpfs
= mask_
$ do let ref = tmp_dirs_to_clean tmpfs
ds <- atomicModifyIORef' ref $ \ds -> (Map.empty, ds)
removeTmpDirs logger (Map.elems ds)
-- | Delete all paths in @tmp_files_to_clean@ and @tmp_subdirs_to_clean@.
cleanTempFiles :: Logger -> TmpFs -> IO ()
cleanTempFiles logger tmpfs
= mask_
$ do removeWith (removeTmpFiles logger) (tmp_files_to_clean tmpfs)
removeWith (removeTmpSubdirs logger) (tmp_subdirs_to_clean tmpfs)
where
removeWith remove ref = do
to_delete <- atomicModifyIORef' ref $
\PathsToClean
{ ptcCurrentModule = cm_paths
, ptcGhcSession = gs_paths
} -> ( emptyPathsToClean
, Set.toList cm_paths ++ Set.toList gs_paths)
remove to_delete
| Delete all paths in @tmp_files_to_clean@ and @tmp_subdirs_to_clean@
-- That have lifetime TFL_CurrentModule.
-- If a file must be cleaned eventually, but must survive a
-- cleanCurrentModuleTempFiles, ensure it has lifetime TFL_GhcSession.
cleanCurrentModuleTempFiles :: Logger -> TmpFs -> IO ()
cleanCurrentModuleTempFiles logger tmpfs
= mask_
$ do removeWith (removeTmpFiles logger) (tmp_files_to_clean tmpfs)
removeWith (removeTmpSubdirs logger) (tmp_subdirs_to_clean tmpfs)
where
removeWith remove ref = do
to_delete <- atomicModifyIORef' ref $
\ptc@PathsToClean{ptcCurrentModule = cm_paths} ->
(ptc {ptcCurrentModule = Set.empty}, Set.toList cm_paths)
remove to_delete
-- | Ensure that new_files are cleaned on the next call of
-- 'cleanTempFiles' or 'cleanCurrentModuleTempFiles', depending on lifetime.
-- If any of new_files are already tracked, they will have their lifetime
-- updated.
addFilesToClean :: TmpFs -> TempFileLifetime -> [FilePath] -> IO ()
addFilesToClean tmpfs lifetime new_files =
addToClean (tmp_files_to_clean tmpfs) lifetime new_files
addSubdirsToClean :: TmpFs -> TempFileLifetime -> [FilePath] -> IO ()
addSubdirsToClean tmpfs lifetime new_subdirs =
addToClean (tmp_subdirs_to_clean tmpfs) lifetime new_subdirs
addToClean :: IORef PathsToClean -> TempFileLifetime -> [FilePath] -> IO ()
addToClean ref lifetime new_filepaths = modifyIORef' ref $
\PathsToClean
{ ptcCurrentModule = cm_paths
, ptcGhcSession = gs_paths
} -> case lifetime of
TFL_CurrentModule -> PathsToClean
{ ptcCurrentModule = cm_paths `Set.union` new_filepaths_set
, ptcGhcSession = gs_paths `Set.difference` new_filepaths_set
}
TFL_GhcSession -> PathsToClean
{ ptcCurrentModule = cm_paths `Set.difference` new_filepaths_set
, ptcGhcSession = gs_paths `Set.union` new_filepaths_set
}
where
new_filepaths_set = Set.fromList new_filepaths
-- | Update the lifetime of files already being tracked. If any files are
-- not being tracked they will be discarded.
changeTempFilesLifetime :: TmpFs -> TempFileLifetime -> [FilePath] -> IO ()
changeTempFilesLifetime tmpfs lifetime files = do
PathsToClean
{ ptcCurrentModule = cm_paths
, ptcGhcSession = gs_paths
} <- readIORef (tmp_files_to_clean tmpfs)
let old_set = case lifetime of
TFL_CurrentModule -> gs_paths
TFL_GhcSession -> cm_paths
existing_files = [f | f <- files, f `Set.member` old_set]
addFilesToClean tmpfs lifetime existing_files
-- Return a unique numeric temp file suffix
newTempSuffix :: TmpFs -> IO Int
newTempSuffix tmpfs =
atomicModifyIORef' (tmp_next_suffix tmpfs) $ \n -> (n+1,n)
-- Find a temporary name that doesn't already exist.
newTempName :: Logger -> TmpFs -> TempDir -> TempFileLifetime -> Suffix -> IO FilePath
newTempName logger tmpfs tmp_dir lifetime extn
= do d <- getTempDir logger tmpfs tmp_dir
findTempName (d </> "ghc_") -- See Note [Deterministic base name]
where
findTempName :: FilePath -> IO FilePath
findTempName prefix
= do n <- newTempSuffix tmpfs
let filename = prefix ++ show n <.> extn
b <- doesFileExist filename
if b then findTempName prefix
else do -- clean it up later
addFilesToClean tmpfs lifetime [filename]
return filename
-- | Create a new temporary subdirectory that doesn't already exist
-- The temporary subdirectory is automatically removed at the end of the
GHC session , but its contents are n't . Make sure to leave the directory
-- empty before the end of the session, either by removing content
directly or by using
--
-- If the created subdirectory is not empty, it will not be removed (along
-- with its parent temporary directory) and a warning message will be
printed at verbosity 2 and higher .
newTempSubDir :: Logger -> TmpFs -> TempDir -> IO FilePath
newTempSubDir logger tmpfs tmp_dir
= do d <- getTempDir logger tmpfs tmp_dir
findTempDir (d </> "ghc_")
where
findTempDir :: FilePath -> IO FilePath
findTempDir prefix
= do n <- newTempSuffix tmpfs
let name = prefix ++ show n
b <- doesDirectoryExist name
if b then findTempDir prefix
else (do
createDirectory name
addSubdirsToClean tmpfs TFL_GhcSession [name]
return name)
`Exception.catchIO` \e -> if isAlreadyExistsError e
then findTempDir prefix else ioError e
newTempLibName :: Logger -> TmpFs -> TempDir -> TempFileLifetime -> Suffix
-> IO (FilePath, FilePath, String)
newTempLibName logger tmpfs tmp_dir lifetime extn
= do d <- getTempDir logger tmpfs tmp_dir
findTempName d ("ghc_")
where
findTempName :: FilePath -> String -> IO (FilePath, FilePath, String)
findTempName dir prefix
= do n <- newTempSuffix tmpfs -- See Note [Deterministic base name]
let libname = prefix ++ show n
filename = dir </> "lib" ++ libname <.> extn
b <- doesFileExist filename
if b then findTempName dir prefix
else do -- clean it up later
addFilesToClean tmpfs lifetime [filename]
return (filename, dir, libname)
-- Return our temporary directory within tmp_dir, creating one if we
-- don't have one yet.
getTempDir :: Logger -> TmpFs -> TempDir -> IO FilePath
getTempDir logger tmpfs (TempDir tmp_dir) = do
mapping <- readIORef dir_ref
case Map.lookup tmp_dir mapping of
Nothing -> do
pid <- getProcessID
let prefix = tmp_dir </> "ghc" ++ show pid ++ "_"
mask_ $ mkTempDir prefix
Just dir -> return dir
where
dir_ref = tmp_dirs_to_clean tmpfs
mkTempDir :: FilePath -> IO FilePath
mkTempDir prefix = do
n <- newTempSuffix tmpfs
let our_dir = prefix ++ show n
1 . Speculatively create our new directory .
createDirectory our_dir
2 . Update the tmp_dirs_to_clean mapping unless an entry already exists
-- (i.e. unless another thread beat us to it).
their_dir <- atomicModifyIORef' dir_ref $ \mapping ->
case Map.lookup tmp_dir mapping of
Just dir -> (mapping, Just dir)
Nothing -> (Map.insert tmp_dir our_dir mapping, Nothing)
3 . If there was an existing entry , return it and delete the
-- directory we created. Otherwise return the directory we created.
case their_dir of
Nothing -> do
debugTraceMsg logger 2 $
text "Created temporary directory:" <+> text our_dir
return our_dir
Just dir -> do
removeDirectory our_dir
return dir
`Exception.catchIO` \e -> if isAlreadyExistsError e
then mkTempDir prefix else ioError e
Note [ Deterministic base name ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The filename of temporary files , especially the basename of C files , can end
up in the output in some form , e.g. as part of linker debug information . In the
interest of bit - wise exactly reproducible compilation ( # 4012 ) , the basename of
the temporary file no longer contains random information ( it used to contain
the process i d ) .
This is ok , as the temporary directory used contains the pid ( see getTempDir ) .
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The filename of temporary files, especially the basename of C files, can end
up in the output in some form, e.g. as part of linker debug information. In the
interest of bit-wise exactly reproducible compilation (#4012), the basename of
the temporary file no longer contains random information (it used to contain
the process id).
This is ok, as the temporary directory used contains the pid (see getTempDir).
-}
removeTmpDirs :: Logger -> [FilePath] -> IO ()
removeTmpDirs logger ds
= traceCmd logger "Deleting temp dirs"
("Deleting: " ++ unwords ds)
(mapM_ (removeWith logger removeDirectory) ds)
removeTmpFiles :: Logger -> [FilePath] -> IO ()
removeTmpFiles logger fs
= warnNon $
traceCmd logger "Deleting temp files"
("Deleting: " ++ unwords deletees)
(mapM_ (removeWith logger removeFile) deletees)
where
-- Flat out refuse to delete files that are likely to be source input
-- files (is there a worse bug than having a compiler delete your source
-- files?)
--
-- Deleting source files is a sign of a bug elsewhere, so prominently flag
-- the condition.
warnNon act
| null non_deletees = act
| otherwise = do
putMsg logger (text "WARNING - NOT deleting source files:"
<+> hsep (map text non_deletees))
act
(non_deletees, deletees) = partition isHaskellUserSrcFilename fs
removeTmpSubdirs :: Logger -> [FilePath] -> IO ()
removeTmpSubdirs logger fs
= traceCmd logger "Deleting temp subdirs"
("Deleting: " ++ unwords fs)
(mapM_ (removeWith logger removeDirectory) fs)
removeWith :: Logger -> (FilePath -> IO ()) -> FilePath -> IO ()
removeWith logger remover f = remover f `Exception.catchIO`
(\e ->
let msg = if isDoesNotExistError e
then text "Warning: deleting non-existent" <+> text f
else text "Warning: exception raised when deleting"
<+> text f <> colon
$$ text (show e)
in debugTraceMsg logger 2 msg
)
#if defined(mingw32_HOST_OS)
relies on Int = = Int32 on Windows
foreign import ccall unsafe "_getpid" getProcessID :: IO Int
#else
getProcessID :: IO Int
getProcessID = System.Posix.Internals.c_getpid >>= return . fromIntegral
#endif
The following three functions are from the ` temporary ` package .
-- | Create and use a temporary directory in the system standard temporary
-- directory.
--
Behaves exactly the same as ' withTempDirectory ' , except that the parent
-- temporary directory will be that returned by 'getTemporaryDirectory'.
withSystemTempDirectory :: String -- ^ Directory name template. See 'openTempFile'.
-> (FilePath -> IO a) -- ^ Callback that can use the directory
-> IO a
withSystemTempDirectory template action =
getTemporaryDirectory >>= \tmpDir -> withTempDirectory tmpDir template action
-- | Create and use a temporary directory.
--
-- Creates a new temporary directory inside the given directory, making use
-- of the template. The temp directory is deleted after use. For example:
--
-- > withTempDirectory "src" "sdist." $ \tmpDir -> do ...
--
-- The @tmpDir@ will be a new subdirectory of the given directory, e.g.
-- @src/sdist.342@.
withTempDirectory :: FilePath -- ^ Temp directory to create the directory in
-> String -- ^ Directory name template. See 'openTempFile'.
-> (FilePath -> IO a) -- ^ Callback that can use the directory
-> IO a
withTempDirectory targetDir template =
Exception.bracket
(createTempDirectory targetDir template)
(ignoringIOErrors . removeDirectoryRecursive)
ignoringIOErrors :: IO () -> IO ()
ignoringIOErrors ioe = ioe `Exception.catchIO` const (return ())
createTempDirectory :: FilePath -> String -> IO FilePath
createTempDirectory dir template = do
pid <- getProcessID
findTempName pid
where findTempName x = do
let path = dir </> template ++ show x
createDirectory path
return path
`Exception.catchIO` \e -> if isAlreadyExistsError e
then findTempName (x+1) else ioError e
| null | https://raw.githubusercontent.com/ghc/ghc/9ea719f2f1929bf2b789e4001f6c542a04185d61/compiler/GHC/Utils/TmpFs.hs | haskell | | Temporary file-system management
| Temporary file-system
an actual temporary directory for this process.
It's a Map probably to support changing the system temporary directory
over time.
Shared with forked TmpFs.
^ The next available suffix to uniquely name a temp file, updated
atomically.
Shared with forked TmpFs.
^ Files to clean (per session or per module)
Not shared with forked TmpFs.
Not shared with forked TmpFs.
^ Paths that will be deleted the next time
'cleanCurrentModuleTempFiles' is called, or otherwise at the end of
the session.
| Used when a temp file is created. This determines which component Set of
PathsToClean will get the temp file
^ A file with lifetime TFL_CurrentModule will be cleaned up at the
end of upweep_mod
^ A file with lifetime TFL_GhcSession will be cleaned up at the end of
runGhc(T)
| Initialise an empty TmpFs
| Initialise an empty TmpFs sharing unique numbers and per-process temporary
directories with the given TmpFs
It's not safe to use the subdirs created by the original TmpFs with the
forked one. Use @newTempSubDir@ to create new subdirs instead.
| Delete all paths in @tmp_files_to_clean@ and @tmp_subdirs_to_clean@.
That have lifetime TFL_CurrentModule.
If a file must be cleaned eventually, but must survive a
cleanCurrentModuleTempFiles, ensure it has lifetime TFL_GhcSession.
| Ensure that new_files are cleaned on the next call of
'cleanTempFiles' or 'cleanCurrentModuleTempFiles', depending on lifetime.
If any of new_files are already tracked, they will have their lifetime
updated.
| Update the lifetime of files already being tracked. If any files are
not being tracked they will be discarded.
Return a unique numeric temp file suffix
Find a temporary name that doesn't already exist.
See Note [Deterministic base name]
clean it up later
| Create a new temporary subdirectory that doesn't already exist
The temporary subdirectory is automatically removed at the end of the
empty before the end of the session, either by removing content
If the created subdirectory is not empty, it will not be removed (along
with its parent temporary directory) and a warning message will be
See Note [Deterministic base name]
clean it up later
Return our temporary directory within tmp_dir, creating one if we
don't have one yet.
(i.e. unless another thread beat us to it).
directory we created. Otherwise return the directory we created.
Flat out refuse to delete files that are likely to be source input
files (is there a worse bug than having a compiler delete your source
files?)
Deleting source files is a sign of a bug elsewhere, so prominently flag
the condition.
| Create and use a temporary directory in the system standard temporary
directory.
temporary directory will be that returned by 'getTemporaryDirectory'.
^ Directory name template. See 'openTempFile'.
^ Callback that can use the directory
| Create and use a temporary directory.
Creates a new temporary directory inside the given directory, making use
of the template. The temp directory is deleted after use. For example:
> withTempDirectory "src" "sdist." $ \tmpDir -> do ...
The @tmpDir@ will be a new subdirectory of the given directory, e.g.
@src/sdist.342@.
^ Temp directory to create the directory in
^ Directory name template. See 'openTempFile'.
^ Callback that can use the directory | # LANGUAGE CPP #
module GHC.Utils.TmpFs
( TmpFs
, initTmpFs
, forkTmpFsFrom
, mergeTmpFsInto
, PathsToClean(..)
, emptyPathsToClean
, TempFileLifetime(..)
, TempDir (..)
, cleanTempDirs
, cleanTempFiles
, cleanCurrentModuleTempFiles
, addFilesToClean
, changeTempFilesLifetime
, newTempName
, newTempLibName
, newTempSubDir
, withSystemTempDirectory
, withTempDirectory
)
where
import GHC.Prelude
import GHC.Utils.Error
import GHC.Utils.Outputable
import GHC.Utils.Logger
import GHC.Utils.Misc
import GHC.Utils.Exception as Exception
import GHC.Driver.Phases
import Data.List (partition)
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Map as Map
import Data.Map (Map)
import Data.IORef
import System.Directory
import System.FilePath
import System.IO.Error
#if !defined(mingw32_HOST_OS)
import qualified System.Posix.Internals
#endif
data TmpFs = TmpFs
{ tmp_dirs_to_clean :: IORef (Map FilePath FilePath)
^ Maps system temporary directory ( passed via settings or DynFlags ) to
, tmp_next_suffix :: IORef Int
, tmp_files_to_clean :: IORef PathsToClean
, tmp_subdirs_to_clean :: IORef PathsToClean
^ Subdirs to clean ( per session or per module )
}
| A collection of paths that must be deleted before ghc exits .
data PathsToClean = PathsToClean
{ ptcGhcSession :: !(Set FilePath)
^ Paths that will be deleted at the end of )
, ptcCurrentModule :: !(Set FilePath)
}
data TempFileLifetime
= TFL_CurrentModule
| TFL_GhcSession
deriving (Show)
newtype TempDir = TempDir FilePath
| An empty PathsToClean
emptyPathsToClean :: PathsToClean
emptyPathsToClean = PathsToClean Set.empty Set.empty
| Merge two PathsToClean
mergePathsToClean :: PathsToClean -> PathsToClean -> PathsToClean
mergePathsToClean x y = PathsToClean
{ ptcGhcSession = Set.union (ptcGhcSession x) (ptcGhcSession y)
, ptcCurrentModule = Set.union (ptcCurrentModule x) (ptcCurrentModule y)
}
initTmpFs :: IO TmpFs
initTmpFs = do
files <- newIORef emptyPathsToClean
subdirs <- newIORef emptyPathsToClean
dirs <- newIORef Map.empty
next <- newIORef 0
return $ TmpFs
{ tmp_files_to_clean = files
, tmp_subdirs_to_clean = subdirs
, tmp_dirs_to_clean = dirs
, tmp_next_suffix = next
}
forkTmpFsFrom :: TmpFs -> IO TmpFs
forkTmpFsFrom old = do
files <- newIORef emptyPathsToClean
subdirs <- newIORef emptyPathsToClean
return $ TmpFs
{ tmp_files_to_clean = files
, tmp_subdirs_to_clean = subdirs
, tmp_dirs_to_clean = tmp_dirs_to_clean old
, tmp_next_suffix = tmp_next_suffix old
}
| Merge the first TmpFs into the second .
The first TmpFs is returned emptied .
mergeTmpFsInto :: TmpFs -> TmpFs -> IO ()
mergeTmpFsInto src dst = do
src_files <- atomicModifyIORef' (tmp_files_to_clean src) (\s -> (emptyPathsToClean, s))
src_subdirs <- atomicModifyIORef' (tmp_subdirs_to_clean src) (\s -> (emptyPathsToClean, s))
atomicModifyIORef' (tmp_files_to_clean dst) (\s -> (mergePathsToClean src_files s, ()))
atomicModifyIORef' (tmp_subdirs_to_clean dst) (\s -> (mergePathsToClean src_subdirs s, ()))
cleanTempDirs :: Logger -> TmpFs -> IO ()
cleanTempDirs logger tmpfs
= mask_
$ do let ref = tmp_dirs_to_clean tmpfs
ds <- atomicModifyIORef' ref $ \ds -> (Map.empty, ds)
removeTmpDirs logger (Map.elems ds)
cleanTempFiles :: Logger -> TmpFs -> IO ()
cleanTempFiles logger tmpfs
= mask_
$ do removeWith (removeTmpFiles logger) (tmp_files_to_clean tmpfs)
removeWith (removeTmpSubdirs logger) (tmp_subdirs_to_clean tmpfs)
where
removeWith remove ref = do
to_delete <- atomicModifyIORef' ref $
\PathsToClean
{ ptcCurrentModule = cm_paths
, ptcGhcSession = gs_paths
} -> ( emptyPathsToClean
, Set.toList cm_paths ++ Set.toList gs_paths)
remove to_delete
| Delete all paths in @tmp_files_to_clean@ and @tmp_subdirs_to_clean@
cleanCurrentModuleTempFiles :: Logger -> TmpFs -> IO ()
cleanCurrentModuleTempFiles logger tmpfs
= mask_
$ do removeWith (removeTmpFiles logger) (tmp_files_to_clean tmpfs)
removeWith (removeTmpSubdirs logger) (tmp_subdirs_to_clean tmpfs)
where
removeWith remove ref = do
to_delete <- atomicModifyIORef' ref $
\ptc@PathsToClean{ptcCurrentModule = cm_paths} ->
(ptc {ptcCurrentModule = Set.empty}, Set.toList cm_paths)
remove to_delete
addFilesToClean :: TmpFs -> TempFileLifetime -> [FilePath] -> IO ()
addFilesToClean tmpfs lifetime new_files =
addToClean (tmp_files_to_clean tmpfs) lifetime new_files
addSubdirsToClean :: TmpFs -> TempFileLifetime -> [FilePath] -> IO ()
addSubdirsToClean tmpfs lifetime new_subdirs =
addToClean (tmp_subdirs_to_clean tmpfs) lifetime new_subdirs
addToClean :: IORef PathsToClean -> TempFileLifetime -> [FilePath] -> IO ()
addToClean ref lifetime new_filepaths = modifyIORef' ref $
\PathsToClean
{ ptcCurrentModule = cm_paths
, ptcGhcSession = gs_paths
} -> case lifetime of
TFL_CurrentModule -> PathsToClean
{ ptcCurrentModule = cm_paths `Set.union` new_filepaths_set
, ptcGhcSession = gs_paths `Set.difference` new_filepaths_set
}
TFL_GhcSession -> PathsToClean
{ ptcCurrentModule = cm_paths `Set.difference` new_filepaths_set
, ptcGhcSession = gs_paths `Set.union` new_filepaths_set
}
where
new_filepaths_set = Set.fromList new_filepaths
changeTempFilesLifetime :: TmpFs -> TempFileLifetime -> [FilePath] -> IO ()
changeTempFilesLifetime tmpfs lifetime files = do
PathsToClean
{ ptcCurrentModule = cm_paths
, ptcGhcSession = gs_paths
} <- readIORef (tmp_files_to_clean tmpfs)
let old_set = case lifetime of
TFL_CurrentModule -> gs_paths
TFL_GhcSession -> cm_paths
existing_files = [f | f <- files, f `Set.member` old_set]
addFilesToClean tmpfs lifetime existing_files
newTempSuffix :: TmpFs -> IO Int
newTempSuffix tmpfs =
atomicModifyIORef' (tmp_next_suffix tmpfs) $ \n -> (n+1,n)
newTempName :: Logger -> TmpFs -> TempDir -> TempFileLifetime -> Suffix -> IO FilePath
newTempName logger tmpfs tmp_dir lifetime extn
= do d <- getTempDir logger tmpfs tmp_dir
where
findTempName :: FilePath -> IO FilePath
findTempName prefix
= do n <- newTempSuffix tmpfs
let filename = prefix ++ show n <.> extn
b <- doesFileExist filename
if b then findTempName prefix
addFilesToClean tmpfs lifetime [filename]
return filename
GHC session , but its contents are n't . Make sure to leave the directory
directly or by using
printed at verbosity 2 and higher .
newTempSubDir :: Logger -> TmpFs -> TempDir -> IO FilePath
newTempSubDir logger tmpfs tmp_dir
= do d <- getTempDir logger tmpfs tmp_dir
findTempDir (d </> "ghc_")
where
findTempDir :: FilePath -> IO FilePath
findTempDir prefix
= do n <- newTempSuffix tmpfs
let name = prefix ++ show n
b <- doesDirectoryExist name
if b then findTempDir prefix
else (do
createDirectory name
addSubdirsToClean tmpfs TFL_GhcSession [name]
return name)
`Exception.catchIO` \e -> if isAlreadyExistsError e
then findTempDir prefix else ioError e
newTempLibName :: Logger -> TmpFs -> TempDir -> TempFileLifetime -> Suffix
-> IO (FilePath, FilePath, String)
newTempLibName logger tmpfs tmp_dir lifetime extn
= do d <- getTempDir logger tmpfs tmp_dir
findTempName d ("ghc_")
where
findTempName :: FilePath -> String -> IO (FilePath, FilePath, String)
findTempName dir prefix
let libname = prefix ++ show n
filename = dir </> "lib" ++ libname <.> extn
b <- doesFileExist filename
if b then findTempName dir prefix
addFilesToClean tmpfs lifetime [filename]
return (filename, dir, libname)
getTempDir :: Logger -> TmpFs -> TempDir -> IO FilePath
getTempDir logger tmpfs (TempDir tmp_dir) = do
mapping <- readIORef dir_ref
case Map.lookup tmp_dir mapping of
Nothing -> do
pid <- getProcessID
let prefix = tmp_dir </> "ghc" ++ show pid ++ "_"
mask_ $ mkTempDir prefix
Just dir -> return dir
where
dir_ref = tmp_dirs_to_clean tmpfs
mkTempDir :: FilePath -> IO FilePath
mkTempDir prefix = do
n <- newTempSuffix tmpfs
let our_dir = prefix ++ show n
1 . Speculatively create our new directory .
createDirectory our_dir
2 . Update the tmp_dirs_to_clean mapping unless an entry already exists
their_dir <- atomicModifyIORef' dir_ref $ \mapping ->
case Map.lookup tmp_dir mapping of
Just dir -> (mapping, Just dir)
Nothing -> (Map.insert tmp_dir our_dir mapping, Nothing)
3 . If there was an existing entry , return it and delete the
case their_dir of
Nothing -> do
debugTraceMsg logger 2 $
text "Created temporary directory:" <+> text our_dir
return our_dir
Just dir -> do
removeDirectory our_dir
return dir
`Exception.catchIO` \e -> if isAlreadyExistsError e
then mkTempDir prefix else ioError e
Note [ Deterministic base name ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The filename of temporary files , especially the basename of C files , can end
up in the output in some form , e.g. as part of linker debug information . In the
interest of bit - wise exactly reproducible compilation ( # 4012 ) , the basename of
the temporary file no longer contains random information ( it used to contain
the process i d ) .
This is ok , as the temporary directory used contains the pid ( see getTempDir ) .
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The filename of temporary files, especially the basename of C files, can end
up in the output in some form, e.g. as part of linker debug information. In the
interest of bit-wise exactly reproducible compilation (#4012), the basename of
the temporary file no longer contains random information (it used to contain
the process id).
This is ok, as the temporary directory used contains the pid (see getTempDir).
-}
removeTmpDirs :: Logger -> [FilePath] -> IO ()
removeTmpDirs logger ds
= traceCmd logger "Deleting temp dirs"
("Deleting: " ++ unwords ds)
(mapM_ (removeWith logger removeDirectory) ds)
removeTmpFiles :: Logger -> [FilePath] -> IO ()
removeTmpFiles logger fs
= warnNon $
traceCmd logger "Deleting temp files"
("Deleting: " ++ unwords deletees)
(mapM_ (removeWith logger removeFile) deletees)
where
warnNon act
| null non_deletees = act
| otherwise = do
putMsg logger (text "WARNING - NOT deleting source files:"
<+> hsep (map text non_deletees))
act
(non_deletees, deletees) = partition isHaskellUserSrcFilename fs
removeTmpSubdirs :: Logger -> [FilePath] -> IO ()
removeTmpSubdirs logger fs
= traceCmd logger "Deleting temp subdirs"
("Deleting: " ++ unwords fs)
(mapM_ (removeWith logger removeDirectory) fs)
removeWith :: Logger -> (FilePath -> IO ()) -> FilePath -> IO ()
removeWith logger remover f = remover f `Exception.catchIO`
(\e ->
let msg = if isDoesNotExistError e
then text "Warning: deleting non-existent" <+> text f
else text "Warning: exception raised when deleting"
<+> text f <> colon
$$ text (show e)
in debugTraceMsg logger 2 msg
)
#if defined(mingw32_HOST_OS)
relies on Int = = Int32 on Windows
foreign import ccall unsafe "_getpid" getProcessID :: IO Int
#else
getProcessID :: IO Int
getProcessID = System.Posix.Internals.c_getpid >>= return . fromIntegral
#endif
The following three functions are from the ` temporary ` package .
Behaves exactly the same as ' withTempDirectory ' , except that the parent
-> IO a
withSystemTempDirectory template action =
getTemporaryDirectory >>= \tmpDir -> withTempDirectory tmpDir template action
-> IO a
withTempDirectory targetDir template =
Exception.bracket
(createTempDirectory targetDir template)
(ignoringIOErrors . removeDirectoryRecursive)
ignoringIOErrors :: IO () -> IO ()
ignoringIOErrors ioe = ioe `Exception.catchIO` const (return ())
createTempDirectory :: FilePath -> String -> IO FilePath
createTempDirectory dir template = do
pid <- getProcessID
findTempName pid
where findTempName x = do
let path = dir </> template ++ show x
createDirectory path
return path
`Exception.catchIO` \e -> if isAlreadyExistsError e
then findTempName (x+1) else ioError e
|
3057d157612dad0914c418472ca89c9140c4ce68e0107c851e8a20a36ccceef4 | quil-lang/quilc | ucr-recognize.lisp | ;;;; ucr-recognize.lisp
;;;;
Author :
(in-package #:cl-quil)
;; NOTE: the loops in this function do exactly twice as much work as is needed,
;; but rewriting them to do minimal work makes the loop structure nastier.
(define-compiler recognize-ucr ((instr
:where (anonymous-gate-application-p instr)))
"Checks whether an anonymous gate is a UCRY or UCRZ instruction, in which case it relabels it as such."
(let* ((matrix (handler-case (gate-matrix instr)
(unknown-gate-parameter (c)
(declare (ignore c))
(give-up-compilation))))
(dimension (magicl:nrows matrix))
(log-dimension (length (application-arguments instr)))
angles)
(cond
;; are we a diagonal matrix?
((loop :for i :below (magicl:nrows matrix)
:always (double= 1d0 (abs (magicl:tref matrix i i))))
if so , we are potentially of the form UCRZ . the extra check
;; we need to do is to see if the matrix has the required extra
;; symmetry: there has to be a fixed target bit d about which
;; the matrix satisfies
;;
;; j' = j & !(2^d),
j '' = j | 2^d ,
m_j'j ' = conj(m_j''j '' ) .
;;
;; in this case, the angles are given by (phase ...).
(loop :for d :below log-dimension
:do (setf angles (make-list (/ dimension 2)))
(when (loop :for j :below dimension
:always (let* ((jp (dpb 0 (byte 1 d) j))
(jpp (dpb 1 (byte 1 d) j))
(i (+ (mod jp (ash 1 d))
(ash (- jp (mod jp (ash 1 d))) -1))))
(setf (nth i angles)
(constant (* -2 (phase (magicl:tref matrix jp jp)))))
(double= (magicl:tref matrix jp jp)
(conjugate (magicl:tref matrix jpp jpp)))))
(inst* (repeatedly-fork (named-operator "RZ") (1- log-dimension))
angles
(append (subseq (application-arguments instr)
0
(- log-dimension d 1))
(subseq (application-arguments instr)
(- log-dimension d))
(list (nth (- log-dimension d 1)
(application-arguments instr)))))
(finish-compiler)))
(give-up-compilation))
are we a UCRY matrix ? these have three salient properties :
;;
( 1 ) they are completely real
( 2 ) each column and row has only two nonzero entries
( 3 ) these nonzero entries arrange into squares of width 2^d for some d :
;; setting j' and j'' as before, the nonzero entries have the form
;; m_j'j' = m_j''j'' and m_j'j'' = -m_j''j' .
;;
in this case , the angles are given by ( atan ... ) .
(t
(loop :for d :below log-dimension
:do (setf angles (make-list (/ dimension 2)))
(when (loop :for j :below dimension
:always (let* ((jp (dpb 0 (byte 1 d) j))
(jpp (dpb 1 (byte 1 d) j))
(m-jp-jp (magicl:tref matrix jp jp))
(m-jpp-jp (magicl:tref matrix jpp jp))
(m-jp-jpp (magicl:tref matrix jp jpp))
(m-jpp-jpp (magicl:tref matrix jpp jpp))
(i (+ (mod jp (ash 1 d))
(ash (- jp (mod jp (ash 1 d))) -1))))
(setf (nth i angles)
(constant (* 2 (atan (realpart m-jpp-jp)
(realpart m-jp-jp)))))
(and (double= 1d0 (+ (* m-jp-jp m-jp-jp)
(* m-jp-jpp m-jp-jpp)))
(double= 1d0 (+ (* m-jpp-jp m-jpp-jp)
(* m-jpp-jpp m-jpp-jpp)))
(double= m-jp-jp (realpart m-jp-jp))
(double= m-jp-jpp (realpart m-jp-jpp))
(double= m-jpp-jp (realpart m-jpp-jp))
(double= m-jpp-jpp (realpart m-jpp-jpp))
(double= m-jp-jp m-jpp-jpp)
(double= m-jp-jpp (- m-jpp-jp)))))
(inst* (repeatedly-fork (named-operator "RY") (1- log-dimension))
angles
(append (subseq (application-arguments instr)
0
(- log-dimension d 1))
(subseq (application-arguments instr)
(- log-dimension d))
(list (nth (- log-dimension d 1)
(application-arguments instr)))))
(finish-compiler)))
(give-up-compilation)))))
| null | https://raw.githubusercontent.com/quil-lang/quilc/3f3260aaa65cdde25a4f9c0027959e37ceef9d64/src/compilers/ucr-recognize.lisp | lisp | ucr-recognize.lisp
NOTE: the loops in this function do exactly twice as much work as is needed,
but rewriting them to do minimal work makes the loop structure nastier.
are we a diagonal matrix?
we need to do is to see if the matrix has the required extra
symmetry: there has to be a fixed target bit d about which
the matrix satisfies
j' = j & !(2^d),
in this case, the angles are given by (phase ...).
setting j' and j'' as before, the nonzero entries have the form
m_j'j' = m_j''j'' and m_j'j'' = -m_j''j' .
| Author :
(in-package #:cl-quil)
(define-compiler recognize-ucr ((instr
:where (anonymous-gate-application-p instr)))
"Checks whether an anonymous gate is a UCRY or UCRZ instruction, in which case it relabels it as such."
(let* ((matrix (handler-case (gate-matrix instr)
(unknown-gate-parameter (c)
(declare (ignore c))
(give-up-compilation))))
(dimension (magicl:nrows matrix))
(log-dimension (length (application-arguments instr)))
angles)
(cond
((loop :for i :below (magicl:nrows matrix)
:always (double= 1d0 (abs (magicl:tref matrix i i))))
if so , we are potentially of the form UCRZ . the extra check
j '' = j | 2^d ,
m_j'j ' = conj(m_j''j '' ) .
(loop :for d :below log-dimension
:do (setf angles (make-list (/ dimension 2)))
(when (loop :for j :below dimension
:always (let* ((jp (dpb 0 (byte 1 d) j))
(jpp (dpb 1 (byte 1 d) j))
(i (+ (mod jp (ash 1 d))
(ash (- jp (mod jp (ash 1 d))) -1))))
(setf (nth i angles)
(constant (* -2 (phase (magicl:tref matrix jp jp)))))
(double= (magicl:tref matrix jp jp)
(conjugate (magicl:tref matrix jpp jpp)))))
(inst* (repeatedly-fork (named-operator "RZ") (1- log-dimension))
angles
(append (subseq (application-arguments instr)
0
(- log-dimension d 1))
(subseq (application-arguments instr)
(- log-dimension d))
(list (nth (- log-dimension d 1)
(application-arguments instr)))))
(finish-compiler)))
(give-up-compilation))
are we a UCRY matrix ? these have three salient properties :
( 1 ) they are completely real
( 2 ) each column and row has only two nonzero entries
( 3 ) these nonzero entries arrange into squares of width 2^d for some d :
in this case , the angles are given by ( atan ... ) .
(t
(loop :for d :below log-dimension
:do (setf angles (make-list (/ dimension 2)))
(when (loop :for j :below dimension
:always (let* ((jp (dpb 0 (byte 1 d) j))
(jpp (dpb 1 (byte 1 d) j))
(m-jp-jp (magicl:tref matrix jp jp))
(m-jpp-jp (magicl:tref matrix jpp jp))
(m-jp-jpp (magicl:tref matrix jp jpp))
(m-jpp-jpp (magicl:tref matrix jpp jpp))
(i (+ (mod jp (ash 1 d))
(ash (- jp (mod jp (ash 1 d))) -1))))
(setf (nth i angles)
(constant (* 2 (atan (realpart m-jpp-jp)
(realpart m-jp-jp)))))
(and (double= 1d0 (+ (* m-jp-jp m-jp-jp)
(* m-jp-jpp m-jp-jpp)))
(double= 1d0 (+ (* m-jpp-jp m-jpp-jp)
(* m-jpp-jpp m-jpp-jpp)))
(double= m-jp-jp (realpart m-jp-jp))
(double= m-jp-jpp (realpart m-jp-jpp))
(double= m-jpp-jp (realpart m-jpp-jp))
(double= m-jpp-jpp (realpart m-jpp-jpp))
(double= m-jp-jp m-jpp-jpp)
(double= m-jp-jpp (- m-jpp-jp)))))
(inst* (repeatedly-fork (named-operator "RY") (1- log-dimension))
angles
(append (subseq (application-arguments instr)
0
(- log-dimension d 1))
(subseq (application-arguments instr)
(- log-dimension d))
(list (nth (- log-dimension d 1)
(application-arguments instr)))))
(finish-compiler)))
(give-up-compilation)))))
|
8ae0e4bd2dcad67004873ad3a439425afde7d3f3778f5d603f02c2277b98c62b | mfp/obigstore | obs_structured.ml |
* Copyright ( C ) 2011 < >
*
* 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
* Copyright (C) 2011 Mauricio Fernandez <>
*
* 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
*)
open Lwt
open Obs_data_model
module Option = BatOption
module List = struct include List include BatList end
module type RAW =
sig
type keyspace
val get_slice :
keyspace -> table ->
?max_keys:int -> ?max_columns:int -> ?decode_timestamps:bool ->
string key_range -> ?predicate:row_predicate -> column_range ->
(string, string) slice Lwt.t
val get_slice_values :
keyspace -> table ->
?max_keys:int ->
string key_range -> column_name list ->
(key option * (key * string option list) list) Lwt.t
val get_slice_values_with_timestamps :
keyspace -> table ->
?max_keys:int ->
string key_range -> column_name list ->
(key option * (key * (string * Int64.t) option list) list) Lwt.t
val get_columns :
keyspace -> table ->
?max_columns:int -> ?decode_timestamps:bool ->
key -> column_range ->
(column_name * (string column list)) option Lwt.t
val get_column_values :
keyspace -> table ->
key -> column_name list ->
string option list Lwt.t
val get_column :
keyspace -> table ->
key -> column_name -> (string * timestamp) option Lwt.t
val put_columns :
keyspace -> table -> key -> string column list ->
unit Lwt.t
val put_multi_columns :
keyspace -> table -> (key * string column list) list -> unit Lwt.t
end
module type STRUCTURED =
sig
type keyspace
val get_bson_slice :
keyspace -> table ->
?max_keys:int -> ?max_columns:int -> ?decode_timestamps:bool ->
string key_range -> ?predicate:row_predicate -> column_range ->
(string, decoded_data) slice Lwt.t
val get_bson_slice_values :
keyspace -> table ->
?max_keys:int ->
string key_range -> column_name list ->
(key option * (key * decoded_data option list) list) Lwt.t
val get_bson_slice_values_with_timestamps :
keyspace -> table ->
?max_keys:int ->
string key_range -> column_name list ->
(key option * (key * (decoded_data * Int64.t) option list) list) Lwt.t
val get_bson_columns :
keyspace -> table ->
?max_columns:int -> ?decode_timestamps:bool ->
key -> column_range ->
(column_name * (decoded_data column list)) option Lwt.t
val get_bson_column_values :
keyspace -> table ->
key -> column_name list ->
decoded_data option list Lwt.t
val get_bson_column :
keyspace -> table ->
key -> column_name -> (decoded_data * timestamp) option Lwt.t
val put_bson_columns :
keyspace -> table -> key -> decoded_data column list ->
unit Lwt.t
val put_multi_bson_columns :
keyspace -> table -> (key * decoded_data column list) list -> unit Lwt.t
end
module Make(M : RAW) =
struct
open M
type keyspace = M.keyspace
let try_decode s =
try
BSON (Obs_bson.document_of_string s)
with Obs_bson.Malformed _ ->
Malformed_BSON s
let map_column c =
if String.length c.name < 1 || c.name.[0] <> '@' then
{ c with data = Binary c.data }
else
{ c with data = try_decode c.data }
let revmap_column c =
let data = match c.data with
Binary _ | Malformed_BSON _ when c.name <> "" && c.name.[0] = '@' ->
raise (Invalid_BSON_column c.name)
| Binary s | Malformed_BSON s -> s
| BSON x -> Obs_bson.string_of_document x
in { c with data }
let map_key_data kd = { kd with columns = List.map map_column kd.columns }
let get_bson_slice ks table ?max_keys ?max_columns ?decode_timestamps
key_range ?predicate column_range =
lwt k, l = get_slice ks table ?max_keys ?max_columns
?decode_timestamps key_range ?predicate column_range
in return (k, List.map map_key_data l)
let is_bson_col columns =
let a =
Array.of_list
(List.map (fun c -> c <> "" && c.[0] = '@') columns)
in `Staged (Array.get a)
let get_bson_slice_values ks table ?max_keys key_range columns =
let `Staged is_bson = is_bson_col columns in
let map_col i s = match s with
None -> None
| Some s ->
if not (is_bson i) then Some (Binary s)
else Some (try_decode s) in
lwt k, l = get_slice_values ks table ?max_keys key_range columns in
return (k, List.map (fun (k, vs) -> (k, List.mapi map_col vs)) l)
let get_bson_slice_values_with_timestamps ks table ?max_keys key_range columns =
let `Staged is_bson = is_bson_col columns in
let map_col i s = match s with
None -> None
| Some (s, ts) ->
if not (is_bson i) then Some (Binary s, ts)
else Some (try_decode s, ts) in
lwt k, l = get_slice_values_with_timestamps ks table ?max_keys key_range columns in
return (k, List.map (fun (k, vs) -> (k, List.mapi map_col vs)) l)
let get_bson_columns ks table ?max_columns ?decode_timestamps key col_range =
get_columns ks table ?max_columns ?decode_timestamps key col_range >|=
Option.map (fun (c, l) -> (c, List.map map_column l))
let get_bson_column_values ks table key cols =
let `Staged is_bson = is_bson_col cols in
let map_col i s = match s with
None -> None
| Some s ->
if not (is_bson i) then Some (Binary s)
else Some (try_decode s)
in get_column_values ks table key cols >|= List.mapi map_col
let get_bson_column ks table key col =
get_column ks table key col >|=
Option.map
(fun (d, ts) -> if col = "" || col.[0] <> '@' then (Binary d, ts)
else (try_decode d, ts))
let put_bson_columns ks table key cols =
try_lwt put_columns ks table key (List.map revmap_column cols)
let put_multi_bson_columns ks table l =
try_lwt
put_multi_columns ks table
(List.map (fun (k, cols) -> (k, List.map revmap_column cols)) l)
end
| null | https://raw.githubusercontent.com/mfp/obigstore/1b078eeb21e11c8de986717150c7108a94778095/src/core/obs_structured.ml | ocaml |
* Copyright ( C ) 2011 < >
*
* 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
* Copyright (C) 2011 Mauricio Fernandez <>
*
* 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
*)
open Lwt
open Obs_data_model
module Option = BatOption
module List = struct include List include BatList end
module type RAW =
sig
type keyspace
val get_slice :
keyspace -> table ->
?max_keys:int -> ?max_columns:int -> ?decode_timestamps:bool ->
string key_range -> ?predicate:row_predicate -> column_range ->
(string, string) slice Lwt.t
val get_slice_values :
keyspace -> table ->
?max_keys:int ->
string key_range -> column_name list ->
(key option * (key * string option list) list) Lwt.t
val get_slice_values_with_timestamps :
keyspace -> table ->
?max_keys:int ->
string key_range -> column_name list ->
(key option * (key * (string * Int64.t) option list) list) Lwt.t
val get_columns :
keyspace -> table ->
?max_columns:int -> ?decode_timestamps:bool ->
key -> column_range ->
(column_name * (string column list)) option Lwt.t
val get_column_values :
keyspace -> table ->
key -> column_name list ->
string option list Lwt.t
val get_column :
keyspace -> table ->
key -> column_name -> (string * timestamp) option Lwt.t
val put_columns :
keyspace -> table -> key -> string column list ->
unit Lwt.t
val put_multi_columns :
keyspace -> table -> (key * string column list) list -> unit Lwt.t
end
module type STRUCTURED =
sig
type keyspace
val get_bson_slice :
keyspace -> table ->
?max_keys:int -> ?max_columns:int -> ?decode_timestamps:bool ->
string key_range -> ?predicate:row_predicate -> column_range ->
(string, decoded_data) slice Lwt.t
val get_bson_slice_values :
keyspace -> table ->
?max_keys:int ->
string key_range -> column_name list ->
(key option * (key * decoded_data option list) list) Lwt.t
val get_bson_slice_values_with_timestamps :
keyspace -> table ->
?max_keys:int ->
string key_range -> column_name list ->
(key option * (key * (decoded_data * Int64.t) option list) list) Lwt.t
val get_bson_columns :
keyspace -> table ->
?max_columns:int -> ?decode_timestamps:bool ->
key -> column_range ->
(column_name * (decoded_data column list)) option Lwt.t
val get_bson_column_values :
keyspace -> table ->
key -> column_name list ->
decoded_data option list Lwt.t
val get_bson_column :
keyspace -> table ->
key -> column_name -> (decoded_data * timestamp) option Lwt.t
val put_bson_columns :
keyspace -> table -> key -> decoded_data column list ->
unit Lwt.t
val put_multi_bson_columns :
keyspace -> table -> (key * decoded_data column list) list -> unit Lwt.t
end
module Make(M : RAW) =
struct
open M
type keyspace = M.keyspace
let try_decode s =
try
BSON (Obs_bson.document_of_string s)
with Obs_bson.Malformed _ ->
Malformed_BSON s
let map_column c =
if String.length c.name < 1 || c.name.[0] <> '@' then
{ c with data = Binary c.data }
else
{ c with data = try_decode c.data }
let revmap_column c =
let data = match c.data with
Binary _ | Malformed_BSON _ when c.name <> "" && c.name.[0] = '@' ->
raise (Invalid_BSON_column c.name)
| Binary s | Malformed_BSON s -> s
| BSON x -> Obs_bson.string_of_document x
in { c with data }
let map_key_data kd = { kd with columns = List.map map_column kd.columns }
let get_bson_slice ks table ?max_keys ?max_columns ?decode_timestamps
key_range ?predicate column_range =
lwt k, l = get_slice ks table ?max_keys ?max_columns
?decode_timestamps key_range ?predicate column_range
in return (k, List.map map_key_data l)
let is_bson_col columns =
let a =
Array.of_list
(List.map (fun c -> c <> "" && c.[0] = '@') columns)
in `Staged (Array.get a)
let get_bson_slice_values ks table ?max_keys key_range columns =
let `Staged is_bson = is_bson_col columns in
let map_col i s = match s with
None -> None
| Some s ->
if not (is_bson i) then Some (Binary s)
else Some (try_decode s) in
lwt k, l = get_slice_values ks table ?max_keys key_range columns in
return (k, List.map (fun (k, vs) -> (k, List.mapi map_col vs)) l)
let get_bson_slice_values_with_timestamps ks table ?max_keys key_range columns =
let `Staged is_bson = is_bson_col columns in
let map_col i s = match s with
None -> None
| Some (s, ts) ->
if not (is_bson i) then Some (Binary s, ts)
else Some (try_decode s, ts) in
lwt k, l = get_slice_values_with_timestamps ks table ?max_keys key_range columns in
return (k, List.map (fun (k, vs) -> (k, List.mapi map_col vs)) l)
let get_bson_columns ks table ?max_columns ?decode_timestamps key col_range =
get_columns ks table ?max_columns ?decode_timestamps key col_range >|=
Option.map (fun (c, l) -> (c, List.map map_column l))
let get_bson_column_values ks table key cols =
let `Staged is_bson = is_bson_col cols in
let map_col i s = match s with
None -> None
| Some s ->
if not (is_bson i) then Some (Binary s)
else Some (try_decode s)
in get_column_values ks table key cols >|= List.mapi map_col
let get_bson_column ks table key col =
get_column ks table key col >|=
Option.map
(fun (d, ts) -> if col = "" || col.[0] <> '@' then (Binary d, ts)
else (try_decode d, ts))
let put_bson_columns ks table key cols =
try_lwt put_columns ks table key (List.map revmap_column cols)
let put_multi_bson_columns ks table l =
try_lwt
put_multi_columns ks table
(List.map (fun (k, cols) -> (k, List.map revmap_column cols)) l)
end
|
|
d91b6a830fa22e077b31303723a15b2b206a120f9d5e58383245ee10e4b45762 | 8c6794b6/haskell-sc-scratch | IntroHOT.hs | |
Module : $ Header$
CopyRight : ( c ) 8c6794b6
License : :
Stability : unstable
Portability : non - portable
Lecture : < -final/course/IntroHOT.hs >
Module : $Header$
CopyRight : (c) 8c6794b6
License : BSD3
Maintainer :
Stability : unstable
Portability : non-portable
Lecture: <-final/course/IntroHOT.hs>
-}
module IntroHOT where
data Var = VZ | VS Var
data Exp
= V Var
| B Bool
| L Exp
| A Exp Exp
lookp VZ (x:_) = x
lookp (VS v) (_:env) = lookp v env
data U = UB Bool | UA (U -> U)
instance Show U where
show (UB x) = "UB " ++ show x
show (UA _) = "UA <fun>"
eval env (V v) = lookp v env
eval env (B b) = UB b
eval env (L e) = UA (\x -> eval (x:env) e)
eval env (A e1 e2) = case eval env e1 of UA f -> f (eval env e2)
ti1 = A (L (V VZ)) (B True)
ti1_eval = eval [] ti1
-- Partial pattern match in A clause.
-- Permitting invalid syntax.
ti2a = A (B True) (B False)
ti2a_eval = eval [] ti2a
-- Open term.
-- We can get stucked when we evaluate an open term.
ti2o = A (L (V (VS VZ))) (B True)
ti2o_eval = eval [] ti2o | null | https://raw.githubusercontent.com/8c6794b6/haskell-sc-scratch/22de2199359fa56f256b544609cd6513b5e40f43/Scratch/Oleg/TTF/Course/IntroHOT.hs | haskell | Partial pattern match in A clause.
Permitting invalid syntax.
Open term.
We can get stucked when we evaluate an open term. | |
Module : $ Header$
CopyRight : ( c ) 8c6794b6
License : :
Stability : unstable
Portability : non - portable
Lecture : < -final/course/IntroHOT.hs >
Module : $Header$
CopyRight : (c) 8c6794b6
License : BSD3
Maintainer :
Stability : unstable
Portability : non-portable
Lecture: <-final/course/IntroHOT.hs>
-}
module IntroHOT where
data Var = VZ | VS Var
data Exp
= V Var
| B Bool
| L Exp
| A Exp Exp
lookp VZ (x:_) = x
lookp (VS v) (_:env) = lookp v env
data U = UB Bool | UA (U -> U)
instance Show U where
show (UB x) = "UB " ++ show x
show (UA _) = "UA <fun>"
eval env (V v) = lookp v env
eval env (B b) = UB b
eval env (L e) = UA (\x -> eval (x:env) e)
eval env (A e1 e2) = case eval env e1 of UA f -> f (eval env e2)
ti1 = A (L (V VZ)) (B True)
ti1_eval = eval [] ti1
ti2a = A (B True) (B False)
ti2a_eval = eval [] ti2a
ti2o = A (L (V (VS VZ))) (B True)
ti2o_eval = eval [] ti2o |
da74555c91d054c860c289248f2450a90a9824a0db6d3f171e4e55648296734e | chetmurthy/ensemble | stacke.mli | (**************************************************************)
(* STACKE.MLI *)
Author : , 4/96
(**************************************************************)
val config_full :
Glue.glue -> (* glue *)
Alarm.t ->
(Addr.id -> int) ->
Layer.state -> (* application *)
View.full -> (* view state *)
(Event.up -> unit) -> (* events out of top *)
(Event.dn -> unit) (* events into top *)
(**************************************************************)
val config :
Glue.glue -> (* glue *)
Alarm.t ->
(Addr.id -> int) ->
Layer.state -> (* application *)
View.full -> (* view state *)
unit
(**************************************************************)
| null | https://raw.githubusercontent.com/chetmurthy/ensemble/8266a89e68be24a4aaa5d594662e211eeaa6dc89/ensemble/server/infr/stacke.mli | ocaml | ************************************************************
STACKE.MLI
************************************************************
glue
application
view state
events out of top
events into top
************************************************************
glue
application
view state
************************************************************ | Author : , 4/96
val config_full :
Alarm.t ->
(Addr.id -> int) ->
val config :
Alarm.t ->
(Addr.id -> int) ->
unit
|
a56a79d8cb63331f1e3b52827e3a04425651af171412b9f71f4821d744fe3c0f | paurkedal/viz | lStream.ml | Copyright ( C ) 2010 - -2016 Petter A. Urkedal < >
*
* This file is part of the Viz Compiler < / > .
*
* The Viz Compiler 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 .
*
* The Viz Compiler 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 the Viz Compiler . If not , see < / > .
*
* This file is part of the Viz Compiler </>.
*
* The Viz Compiler 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.
*
* The Viz Compiler 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 the Viz Compiler. If not, see </>.
*)
open Unicode
open CamomileLibraryDefault.Camomile
type elt = UChar.t
type t = {
stream : UChar.t Stream.t;
mutable locb : Textloc.Bound.t;
}
let null = {stream = Stream.of_list []; locb = Textloc.Bound.dummy}
let of_string ?(locb = Textloc.Bound.dummy) s =
let utf8_stream = Stream.of_string s in
let stm = CharEncoding.ustream_of CharEncoding.utf8 utf8_stream in
{stream = stm; locb = locb}
let open_in path =
let utf8_stream = Stream.of_channel (open_in path) in
let stm = CharEncoding.ustream_of CharEncoding.utf8 utf8_stream in
{stream = stm; locb = Textloc.Bound.init path}
let locbound stm = stm.locb
let pop stm =
try
let ch = Stream.next stm.stream in
stm.locb <- Textloc.Bound.skip_char ch stm.locb;
Some ch
with Stream.Failure -> None
let pop_e stm =
match pop stm with
| Some ch -> ch
| None -> raise Stream.Failure
let peek stm = Stream.peek stm.stream
let peek_e stm =
match Stream.peek stm.stream with
| Some ch -> ch
| None -> raise Stream.Failure
let peek_n n stm = Stream.npeek n stm.stream
let peek_at i stm =
let rec f i = function
| [] -> None
| x :: xs -> if i = 0 then Some x else f (i - 1) xs
in f i (Stream.npeek (i + 1) stm.stream)
let pop_code stm =
match pop stm with
| None -> 0
| Some ch -> UChar.code ch
let peek_code stm =
match Stream.peek stm.stream with
| None -> 0
| Some ch -> UChar.code ch
let peek_n_code n stm =
List.map UChar.code (Stream.npeek n stm.stream)
let skip stm =
let ch = Stream.next stm.stream in
stm.locb <- Textloc.Bound.skip_char ch stm.locb
let rec skip_n n stm =
if n = 0 then () else
begin
skip stm;
skip_n (n - 1) stm
end
let skip_while f stm =
while Option.exists f (peek stm) do skip stm done
let scan_while f stm =
let buf = UString.Buf.create 8 in
let loc_lb = locbound stm in
while
match peek stm with
| None -> false
| Some ch -> f ch && (UString.Buf.add_char buf ch; true)
do skip stm done;
let loc_ub = locbound stm in
(UString.Buf.contents buf, Textloc.between loc_lb loc_ub)
| null | https://raw.githubusercontent.com/paurkedal/viz/ab1f1071fafdc51eae69185ec55d7a6e7bb94ea9/camlviz/lStream.ml | ocaml | Copyright ( C ) 2010 - -2016 Petter A. Urkedal < >
*
* This file is part of the Viz Compiler < / > .
*
* The Viz Compiler 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 .
*
* The Viz Compiler 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 the Viz Compiler . If not , see < / > .
*
* This file is part of the Viz Compiler </>.
*
* The Viz Compiler 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.
*
* The Viz Compiler 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 the Viz Compiler. If not, see </>.
*)
open Unicode
open CamomileLibraryDefault.Camomile
type elt = UChar.t
type t = {
stream : UChar.t Stream.t;
mutable locb : Textloc.Bound.t;
}
let null = {stream = Stream.of_list []; locb = Textloc.Bound.dummy}
let of_string ?(locb = Textloc.Bound.dummy) s =
let utf8_stream = Stream.of_string s in
let stm = CharEncoding.ustream_of CharEncoding.utf8 utf8_stream in
{stream = stm; locb = locb}
let open_in path =
let utf8_stream = Stream.of_channel (open_in path) in
let stm = CharEncoding.ustream_of CharEncoding.utf8 utf8_stream in
{stream = stm; locb = Textloc.Bound.init path}
let locbound stm = stm.locb
let pop stm =
try
let ch = Stream.next stm.stream in
stm.locb <- Textloc.Bound.skip_char ch stm.locb;
Some ch
with Stream.Failure -> None
let pop_e stm =
match pop stm with
| Some ch -> ch
| None -> raise Stream.Failure
let peek stm = Stream.peek stm.stream
let peek_e stm =
match Stream.peek stm.stream with
| Some ch -> ch
| None -> raise Stream.Failure
let peek_n n stm = Stream.npeek n stm.stream
let peek_at i stm =
let rec f i = function
| [] -> None
| x :: xs -> if i = 0 then Some x else f (i - 1) xs
in f i (Stream.npeek (i + 1) stm.stream)
let pop_code stm =
match pop stm with
| None -> 0
| Some ch -> UChar.code ch
let peek_code stm =
match Stream.peek stm.stream with
| None -> 0
| Some ch -> UChar.code ch
let peek_n_code n stm =
List.map UChar.code (Stream.npeek n stm.stream)
let skip stm =
let ch = Stream.next stm.stream in
stm.locb <- Textloc.Bound.skip_char ch stm.locb
let rec skip_n n stm =
if n = 0 then () else
begin
skip stm;
skip_n (n - 1) stm
end
let skip_while f stm =
while Option.exists f (peek stm) do skip stm done
let scan_while f stm =
let buf = UString.Buf.create 8 in
let loc_lb = locbound stm in
while
match peek stm with
| None -> false
| Some ch -> f ch && (UString.Buf.add_char buf ch; true)
do skip stm done;
let loc_ub = locbound stm in
(UString.Buf.contents buf, Textloc.between loc_lb loc_ub)
|
|
f8cd7d26e608268d01a2e5bbba7340184e223dbb2828ec0546545391a8a5216f | alan-turing-institute/advent-of-code-2021 | day07.rkt | #lang racket/base
(require math/statistics)
(require racket/string)
(require racket/function)
(module+ test
(require rackunit)
(define *input*
(map string->number (string-split "16,1,2,0,4,2,7,1,2,14" ",")))
(check-equal? 37 (minimum-fuel/1 *input*))
(check-equal? 168 (minimum-fuel/2 *input*))
)
(module+ main
(define *input*
(with-input-from-file "input.txt"
(thunk (map string->number (string-split (read-line) ",")))))
Part one
(minimum-fuel/1 *input*)
Part two ( something of a cheat )
(minimum-fuel/2 *input*)
)
;; ----------------------------------------------------------------------
(define (minimum-fuel/1 posns)
(let ([m (median < posns)])
(for/sum ([p posns])
(abs (- p m)))))
(define (minimum-fuel/2 posns)
(let ([m (mean posns)])
I mean , it 's * probably * one of these two ...
(min (required-fuel/2 (floor m) posns)
(required-fuel/2 (ceiling m) posns))))
(define (required-fuel/2 x posns)
(for/sum ([p posns])
(sum-1-to-n (abs (- p x)))))
(define (sum-1-to-n n)
(/ (* n (+ n 1)) 2))
| null | https://raw.githubusercontent.com/alan-turing-institute/advent-of-code-2021/07c7fc2ba3a0b408d5b977ed3d3af47e455af98b/day-07/racket_triangle-man/day07.rkt | racket | ---------------------------------------------------------------------- | #lang racket/base
(require math/statistics)
(require racket/string)
(require racket/function)
(module+ test
(require rackunit)
(define *input*
(map string->number (string-split "16,1,2,0,4,2,7,1,2,14" ",")))
(check-equal? 37 (minimum-fuel/1 *input*))
(check-equal? 168 (minimum-fuel/2 *input*))
)
(module+ main
(define *input*
(with-input-from-file "input.txt"
(thunk (map string->number (string-split (read-line) ",")))))
Part one
(minimum-fuel/1 *input*)
Part two ( something of a cheat )
(minimum-fuel/2 *input*)
)
(define (minimum-fuel/1 posns)
(let ([m (median < posns)])
(for/sum ([p posns])
(abs (- p m)))))
(define (minimum-fuel/2 posns)
(let ([m (mean posns)])
I mean , it 's * probably * one of these two ...
(min (required-fuel/2 (floor m) posns)
(required-fuel/2 (ceiling m) posns))))
(define (required-fuel/2 x posns)
(for/sum ([p posns])
(sum-1-to-n (abs (- p x)))))
(define (sum-1-to-n n)
(/ (* n (+ n 1)) 2))
|
eda4379efd54bc5cf78c61d338813149db88555cd1a55e3b6bf7a6169dc7ddec | janestreet/async_parallel | token.ml | open Core
(** Token is a mechanism to detect when an object is not in the process where it was
created. Every process has a token, which occupies some area of physical
memory. Every object we wish to track has a pointer to it's processes token. Checking
whether the object is being used in another process than the one that created it is
then a simple matter of checking physical equality of the executing processes' token
against the token stored in the object. If they don't match, then the object has been
moved to another process. This method avoids the pitfalls of using pids, which are
reused on a short time scale by the OS. *)
type t = {v: unit}
(** It's true that because we allocate this block at module init time every worker process
will have [mine] at the same address. However this is ok, because when we marshal
something it will make a deep copy of mine, and so we can still detect that we're not
in the same process as where we were created. *)
let mine = {v = ()}
let valid tok = phys_equal tok mine
| null | https://raw.githubusercontent.com/janestreet/async_parallel/b2ef6ad95279260e2b9889e539bec87c40a13f34/src/token.ml | ocaml | * Token is a mechanism to detect when an object is not in the process where it was
created. Every process has a token, which occupies some area of physical
memory. Every object we wish to track has a pointer to it's processes token. Checking
whether the object is being used in another process than the one that created it is
then a simple matter of checking physical equality of the executing processes' token
against the token stored in the object. If they don't match, then the object has been
moved to another process. This method avoids the pitfalls of using pids, which are
reused on a short time scale by the OS.
* It's true that because we allocate this block at module init time every worker process
will have [mine] at the same address. However this is ok, because when we marshal
something it will make a deep copy of mine, and so we can still detect that we're not
in the same process as where we were created. | open Core
type t = {v: unit}
let mine = {v = ()}
let valid tok = phys_equal tok mine
|
df93c4155999828687f6842ea307c98958a071f8770802120a238655ce7f7292 | pikatchu/LinearML | nast.ml |
Copyright ( c ) 2011 ,
All rights reserved .
Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are
met :
1 . Redistributions of source code must retain the above copyright
notice , this list of conditions and the following disclaimer .
2 . Redistributions in binary form must reproduce the above copyright
notice , this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the
distribution .
3 . Neither the name of nor the names of
contributors may be used to endorse or promote products derived
from this software without specific prior written permission .
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT
OWNER OR 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 .
Copyright (c) 2011, Julien Verlaguet
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the
distribution.
3. Neither the name of Julien Verlaguet nor the names of
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR 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.
*)
open Utils
type id = Pos.t * Ident.t
type pstring = Pos.t * string
type program = module_ list
and module_ = {
md_sig: bool ;
md_id: id ;
md_decls: decl list ;
md_defs: def list ;
}
and decl =
| Dtype of (id * type_expr) list
| Dval of Ast.link * id * type_expr * Ast.extern_def
and type_expr = Pos.t * type_expr_
and type_expr_ =
| Tany
| Tprim of type_prim
| Tvar of id
| Tid of id
| Tapply of type_expr * type_expr list
| Ttuple of type_expr list
| Tpath of id * id
| Tfun of Ast.fun_kind * type_expr * type_expr
| Talgebric of (id * type_expr option) IMap.t
| Trecord of (id * type_expr) IMap.t
| Tabbrev of type_expr
| Tabs of id list * type_expr
| Tabstract
and type_prim =
| Tunit
| Tbool
| Tchar
| Tint
| Tfloat
| Tstring
and def = id * pat list * expr
and tpat = pat * type_expr
and pat = Pos.t * pat_
and pat_ =
| Pany
| Pid of id
| Pvalue of value
| Pcstr of id
| Pvariant of id * pat
| Pecstr of id * id
| Pevariant of id * id * pat
| Precord of pat_field list
| Pbar of pat * pat
| Ptuple of pat list
| Pas of id * pat
and pat_field = Pos.t * pat_field_
and pat_field_ =
| PFany
| PFid of id
| PField of id * pat
and expr = Pos.t * expr_
and expr_ =
| Eid of id
| Evalue of value
| Ebinop of Ast.bop * expr * expr
| Euop of Ast.uop * expr
| Etuple of expr list
| Ecstr of id
| Erecord of (id * expr) list
| Efield of expr * id
| Ematch of expr * (pat * expr) list
| Elet of pat * expr * expr
| Eif of expr * expr * expr
| Eapply of expr * expr list
| Ewith of expr * (id * expr) list
| Eseq of expr * expr
| Eobs of id
| Efree of id
| Epartial of expr list
| Efun of Ast.fun_kind * bool * tpat list * expr
and value =
| Eunit
| Ebool of bool
| Eint of pstring
| Efloat of pstring
| Echar of pstring
| Estring of pstring
| null | https://raw.githubusercontent.com/pikatchu/LinearML/76da04134b9eb3a9ca4252e9cb41d412b50a072a/compiler/nast.ml | ocaml |
Copyright ( c ) 2011 ,
All rights reserved .
Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are
met :
1 . Redistributions of source code must retain the above copyright
notice , this list of conditions and the following disclaimer .
2 . Redistributions in binary form must reproduce the above copyright
notice , this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the
distribution .
3 . Neither the name of nor the names of
contributors may be used to endorse or promote products derived
from this software without specific prior written permission .
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT
OWNER OR 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 .
Copyright (c) 2011, Julien Verlaguet
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the
distribution.
3. Neither the name of Julien Verlaguet nor the names of
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR 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.
*)
open Utils
type id = Pos.t * Ident.t
type pstring = Pos.t * string
type program = module_ list
and module_ = {
md_sig: bool ;
md_id: id ;
md_decls: decl list ;
md_defs: def list ;
}
and decl =
| Dtype of (id * type_expr) list
| Dval of Ast.link * id * type_expr * Ast.extern_def
and type_expr = Pos.t * type_expr_
and type_expr_ =
| Tany
| Tprim of type_prim
| Tvar of id
| Tid of id
| Tapply of type_expr * type_expr list
| Ttuple of type_expr list
| Tpath of id * id
| Tfun of Ast.fun_kind * type_expr * type_expr
| Talgebric of (id * type_expr option) IMap.t
| Trecord of (id * type_expr) IMap.t
| Tabbrev of type_expr
| Tabs of id list * type_expr
| Tabstract
and type_prim =
| Tunit
| Tbool
| Tchar
| Tint
| Tfloat
| Tstring
and def = id * pat list * expr
and tpat = pat * type_expr
and pat = Pos.t * pat_
and pat_ =
| Pany
| Pid of id
| Pvalue of value
| Pcstr of id
| Pvariant of id * pat
| Pecstr of id * id
| Pevariant of id * id * pat
| Precord of pat_field list
| Pbar of pat * pat
| Ptuple of pat list
| Pas of id * pat
and pat_field = Pos.t * pat_field_
and pat_field_ =
| PFany
| PFid of id
| PField of id * pat
and expr = Pos.t * expr_
and expr_ =
| Eid of id
| Evalue of value
| Ebinop of Ast.bop * expr * expr
| Euop of Ast.uop * expr
| Etuple of expr list
| Ecstr of id
| Erecord of (id * expr) list
| Efield of expr * id
| Ematch of expr * (pat * expr) list
| Elet of pat * expr * expr
| Eif of expr * expr * expr
| Eapply of expr * expr list
| Ewith of expr * (id * expr) list
| Eseq of expr * expr
| Eobs of id
| Efree of id
| Epartial of expr list
| Efun of Ast.fun_kind * bool * tpat list * expr
and value =
| Eunit
| Ebool of bool
| Eint of pstring
| Efloat of pstring
| Echar of pstring
| Estring of pstring
|
|
442d1e8ed2f10603150487edbe2572f558fd328d849d8385b4dacc7dc4aa60f4 | mzp/coq-ruby | libnames.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
i $ I d : libnames.mli 11576 2008 - 11 - 10 19:13:15Z msozeau $ i
(*i*)
open Pp
open Util
open Names
open Term
open Mod_subst
(*i*)
(*s Global reference is a kernel side type for all references together *)
type global_reference =
| VarRef of variable
| ConstRef of constant
| IndRef of inductive
| ConstructRef of constructor
val isVarRef : global_reference -> bool
val subst_constructor : substitution -> constructor -> constructor * constr
val subst_global : substitution -> global_reference -> global_reference * constr
(* Turn a global reference into a construction *)
val constr_of_global : global_reference -> constr
(* Turn a construction denoting a global reference into a global reference;
raise [Not_found] if not a global reference *)
val global_of_constr : constr -> global_reference
Obsolete synonyms for constr_of_global and global_of_constr
val constr_of_reference : global_reference -> constr
val reference_of_constr : constr -> global_reference
module Refset : Set.S with type elt = global_reference
module Refmap : Map.S with type key = global_reference
(*s Dirpaths *)
val pr_dirpath : dir_path -> Pp.std_ppcmds
val dirpath_of_string : string -> dir_path
(* Give the immediate prefix of a [dir_path] *)
val dirpath_prefix : dir_path -> dir_path
(* Give the immediate prefix and basename of a [dir_path] *)
val split_dirpath : dir_path -> dir_path * identifier
val extend_dirpath : dir_path -> module_ident -> dir_path
val add_dirpath_prefix : module_ident -> dir_path -> dir_path
val chop_dirpath : int -> dir_path -> dir_path * dir_path
val drop_dirpath_prefix : dir_path -> dir_path -> dir_path
val extract_dirpath_prefix : int -> dir_path -> dir_path
val is_dirpath_prefix_of : dir_path -> dir_path -> bool
val append_dirpath : dir_path -> dir_path -> dir_path
module Dirset : Set.S with type elt = dir_path
module Dirmap : Map.S with type key = dir_path
(*s Section paths are {\em absolute} names *)
type section_path
Constructors of [ section_path ]
val make_path : dir_path -> identifier -> section_path
(* Destructors of [section_path] *)
val repr_path : section_path -> dir_path * identifier
val dirpath : section_path -> dir_path
val basename : section_path -> identifier
(* Parsing and printing of section path as ["coq_root.module.id"] *)
val path_of_string : string -> section_path
val string_of_path : section_path -> string
val pr_sp : section_path -> std_ppcmds
module Sppred : Predicate.S with type elt = section_path
module Spmap : Map.S with type key = section_path
val restrict_path : int -> section_path -> section_path
type extended_global_reference =
| TrueGlobal of global_reference
| SyntacticDef of kernel_name
(*s Temporary function to brutally form kernel names from section paths *)
val encode_kn : dir_path -> identifier -> kernel_name
val decode_kn : kernel_name -> dir_path * identifier
val encode_con : dir_path -> identifier -> constant
val decode_con : constant -> dir_path * identifier
(*s A [qualid] is a partially qualified ident; it includes fully
qualified names (= absolute names) and all intermediate partial
qualifications of absolute names, including single identifiers *)
type qualid
val make_qualid : dir_path -> identifier -> qualid
val repr_qualid : qualid -> dir_path * identifier
val string_of_qualid : qualid -> string
val pr_qualid : qualid -> std_ppcmds
val qualid_of_string : string -> qualid
(* Turns an absolute name into a qualified name denoting the same name *)
val qualid_of_sp : section_path -> qualid
val qualid_of_dirpath : dir_path -> qualid
val make_short_qualid : identifier -> qualid
(* Both names are passed to objects: a "semantic" [kernel_name], which
can be substituted and a "syntactic" [section_path] which can be printed
*)
type object_name = section_path * kernel_name
type object_prefix = dir_path * (module_path * dir_path)
val make_oname : object_prefix -> identifier -> object_name
to this type are mapped [ dir_path ] 's in the nametab
type global_dir_reference =
| DirOpenModule of object_prefix
| DirOpenModtype of object_prefix
| DirOpenSection of object_prefix
| DirModule of object_prefix
| DirClosedSection of dir_path
(* this won't last long I hope! *)
type reference =
| Qualid of qualid located
| Ident of identifier located
val qualid_of_reference : reference -> qualid located
val string_of_reference : reference -> string
val pr_reference : reference -> std_ppcmds
val loc_of_reference : reference -> loc
popping one level of section in global names
val pop_con : constant -> constant
val pop_kn : kernel_name -> kernel_name
val pop_global_reference : global_reference -> global_reference
| null | https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/library/libnames.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
i
i
s Global reference is a kernel side type for all references together
Turn a global reference into a construction
Turn a construction denoting a global reference into a global reference;
raise [Not_found] if not a global reference
s Dirpaths
Give the immediate prefix of a [dir_path]
Give the immediate prefix and basename of a [dir_path]
s Section paths are {\em absolute} names
Destructors of [section_path]
Parsing and printing of section path as ["coq_root.module.id"]
s Temporary function to brutally form kernel names from section paths
s A [qualid] is a partially qualified ident; it includes fully
qualified names (= absolute names) and all intermediate partial
qualifications of absolute names, including single identifiers
Turns an absolute name into a qualified name denoting the same name
Both names are passed to objects: a "semantic" [kernel_name], which
can be substituted and a "syntactic" [section_path] which can be printed
this won't last long I hope! | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
i $ I d : libnames.mli 11576 2008 - 11 - 10 19:13:15Z msozeau $ i
open Pp
open Util
open Names
open Term
open Mod_subst
type global_reference =
| VarRef of variable
| ConstRef of constant
| IndRef of inductive
| ConstructRef of constructor
val isVarRef : global_reference -> bool
val subst_constructor : substitution -> constructor -> constructor * constr
val subst_global : substitution -> global_reference -> global_reference * constr
val constr_of_global : global_reference -> constr
val global_of_constr : constr -> global_reference
Obsolete synonyms for constr_of_global and global_of_constr
val constr_of_reference : global_reference -> constr
val reference_of_constr : constr -> global_reference
module Refset : Set.S with type elt = global_reference
module Refmap : Map.S with type key = global_reference
val pr_dirpath : dir_path -> Pp.std_ppcmds
val dirpath_of_string : string -> dir_path
val dirpath_prefix : dir_path -> dir_path
val split_dirpath : dir_path -> dir_path * identifier
val extend_dirpath : dir_path -> module_ident -> dir_path
val add_dirpath_prefix : module_ident -> dir_path -> dir_path
val chop_dirpath : int -> dir_path -> dir_path * dir_path
val drop_dirpath_prefix : dir_path -> dir_path -> dir_path
val extract_dirpath_prefix : int -> dir_path -> dir_path
val is_dirpath_prefix_of : dir_path -> dir_path -> bool
val append_dirpath : dir_path -> dir_path -> dir_path
module Dirset : Set.S with type elt = dir_path
module Dirmap : Map.S with type key = dir_path
type section_path
Constructors of [ section_path ]
val make_path : dir_path -> identifier -> section_path
val repr_path : section_path -> dir_path * identifier
val dirpath : section_path -> dir_path
val basename : section_path -> identifier
val path_of_string : string -> section_path
val string_of_path : section_path -> string
val pr_sp : section_path -> std_ppcmds
module Sppred : Predicate.S with type elt = section_path
module Spmap : Map.S with type key = section_path
val restrict_path : int -> section_path -> section_path
type extended_global_reference =
| TrueGlobal of global_reference
| SyntacticDef of kernel_name
val encode_kn : dir_path -> identifier -> kernel_name
val decode_kn : kernel_name -> dir_path * identifier
val encode_con : dir_path -> identifier -> constant
val decode_con : constant -> dir_path * identifier
type qualid
val make_qualid : dir_path -> identifier -> qualid
val repr_qualid : qualid -> dir_path * identifier
val string_of_qualid : qualid -> string
val pr_qualid : qualid -> std_ppcmds
val qualid_of_string : string -> qualid
val qualid_of_sp : section_path -> qualid
val qualid_of_dirpath : dir_path -> qualid
val make_short_qualid : identifier -> qualid
type object_name = section_path * kernel_name
type object_prefix = dir_path * (module_path * dir_path)
val make_oname : object_prefix -> identifier -> object_name
to this type are mapped [ dir_path ] 's in the nametab
type global_dir_reference =
| DirOpenModule of object_prefix
| DirOpenModtype of object_prefix
| DirOpenSection of object_prefix
| DirModule of object_prefix
| DirClosedSection of dir_path
type reference =
| Qualid of qualid located
| Ident of identifier located
val qualid_of_reference : reference -> qualid located
val string_of_reference : reference -> string
val pr_reference : reference -> std_ppcmds
val loc_of_reference : reference -> loc
popping one level of section in global names
val pop_con : constant -> constant
val pop_kn : kernel_name -> kernel_name
val pop_global_reference : global_reference -> global_reference
|
16c566983fdb62289560972c63f960e38682e40fe05346a345fd03fae7ca6082 | c4-project/c4f | statement_class.ml | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
open Base
open struct
module A = Accessor
module Src = C4f_fir
end
let test_fragment : unit Src.Statement.t Lazy.t =
lazy
Statement.(
mkif ~cond:Src.Expression.truth
[ mkif ~cond:Src.Expression.truth
Src.
[ mkafetch `Add
Address.(of_variable_str_exn "x")
Expression.(int_lit 42)
; A.(
construct
Src.(Statement.prim' @> Prim_statement.label)
(C4f_common.C_id.of_string "foo")) ]
Src.
[ mkastore
Address.(of_variable_str_exn "y")
Expression.(int_lit 64) ] ]
Src.
[mkaxchg Address.(of_variable_str_exn "x") Expression.(int_lit 99)])
let%test_module "matches_any" =
( module struct
let test (templates : Src.Statement_class.t list) : unit =
let k =
Src.Statement_class.matches_any (Lazy.force test_fragment) ~templates
in
Stdio.printf "%b" k
let%expect_test "no classes" = test [] ; [%expect {| false |}]
let%expect_test "if statements" = test [If] ; [%expect {| true |}]
let%expect_test "labels" =
test [Prim (Some Label)] ; [%expect {| false |}]
let%expect_test "while loops" =
test [Src.Statement_class.while_loop ()] ;
[%expect {| false |}]
let%expect_test "atomics of any form" =
test [Src.Statement_class.atomic ()] ;
[%expect {| false |}]
let%expect_test "atomic_store" =
test [Src.Statement_class.atomic ~specifically:Store ()] ;
[%expect {| false |}]
end )
let%test_module "unmatches_any" =
( module struct
let test (templates : Src.Statement_class.t list) : unit =
let k =
Src.Statement_class.unmatches_any
(Lazy.force test_fragment)
~templates
in
Stdio.printf "%b" k
let%expect_test "no classes" = test [] ; [%expect {| false |}]
let%expect_test "if statements" = test [If] ; [%expect {| false |}]
let%expect_test "labels" =
test [Prim (Some Label)] ; [%expect {| true |}]
let%expect_test "while loops" =
test [Src.Statement_class.while_loop ()] ;
[%expect {| true |}]
let%expect_test "atomics of any form" =
test [Src.Statement_class.atomic ()] ;
[%expect {| true |}]
let%expect_test "atomic_store" =
test [Src.Statement_class.atomic ~specifically:Store ()] ;
[%expect {| true |}]
end )
let%test_module "rec_matches_any" =
( module struct
let test (templates : Src.Statement_class.t list) : unit =
let k =
Src.Statement_class.rec_matches_any
(Lazy.force test_fragment)
~templates
in
Stdio.printf "%b" k
let%expect_test "no classes" = test [] ; [%expect {| false |}]
let%expect_test "if statements" = test [If] ; [%expect {| true |}]
let%expect_test "while loops" =
test [Src.Statement_class.while_loop ()] ;
[%expect {| false |}]
let%expect_test "atomics of any form" =
test [Src.Statement_class.atomic ()] ;
[%expect {| true |}]
let%expect_test "atomic_store" =
test [Src.Statement_class.atomic ~specifically:Store ()] ;
[%expect {| true |}]
end )
let%test_module "rec_unmatches_any" =
( module struct
let test (templates : Src.Statement_class.t list) : unit =
let k =
Src.Statement_class.rec_unmatches_any
(Lazy.force test_fragment)
~templates
in
Stdio.printf "%b" k
let%expect_test "no classes" = test [] ; [%expect {| false |}]
let%expect_test "if statements" = test [If] ; [%expect {| true |}]
let%expect_test "while loops" =
test [Src.Statement_class.while_loop ()] ;
[%expect {| true |}]
let%expect_test "atomics of any form" =
test [Src.Statement_class.atomic ()] ;
[%expect {| true |}]
let%expect_test "atomic_store" =
test [Src.Statement_class.atomic ~specifically:Store ()] ;
[%expect {| true |}]
end )
let%test_module "count_matches" =
( module struct
let test (templates : Src.Statement_class.t list) : unit =
let k =
Src.Statement_class.count_rec_matches
(Lazy.force test_fragment)
~templates
in
Stdio.printf "%d" k
let%expect_test "if statements" = test [If] ; [%expect {| 2 |}]
let%expect_test "atomics of any form" =
test [Src.Statement_class.atomic ()] ;
[%expect {| 3 |}]
let%expect_test "atomic_store" =
test [Src.Statement_class.atomic ~specifically:Store ()] ;
[%expect {| 1 |}]
let%expect_test "atomic_store or atomic_load" =
test
[ Src.Statement_class.atomic ~specifically:Store ()
; Src.Statement_class.atomic ~specifically:Load () ] ;
[%expect {| 1 |}]
end )
| null | https://raw.githubusercontent.com/c4-project/c4f/8939477732861789abc807c8c1532a302b2848a5/lib/fir/test/statement_class.ml | ocaml | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
open Base
open struct
module A = Accessor
module Src = C4f_fir
end
let test_fragment : unit Src.Statement.t Lazy.t =
lazy
Statement.(
mkif ~cond:Src.Expression.truth
[ mkif ~cond:Src.Expression.truth
Src.
[ mkafetch `Add
Address.(of_variable_str_exn "x")
Expression.(int_lit 42)
; A.(
construct
Src.(Statement.prim' @> Prim_statement.label)
(C4f_common.C_id.of_string "foo")) ]
Src.
[ mkastore
Address.(of_variable_str_exn "y")
Expression.(int_lit 64) ] ]
Src.
[mkaxchg Address.(of_variable_str_exn "x") Expression.(int_lit 99)])
let%test_module "matches_any" =
( module struct
let test (templates : Src.Statement_class.t list) : unit =
let k =
Src.Statement_class.matches_any (Lazy.force test_fragment) ~templates
in
Stdio.printf "%b" k
let%expect_test "no classes" = test [] ; [%expect {| false |}]
let%expect_test "if statements" = test [If] ; [%expect {| true |}]
let%expect_test "labels" =
test [Prim (Some Label)] ; [%expect {| false |}]
let%expect_test "while loops" =
test [Src.Statement_class.while_loop ()] ;
[%expect {| false |}]
let%expect_test "atomics of any form" =
test [Src.Statement_class.atomic ()] ;
[%expect {| false |}]
let%expect_test "atomic_store" =
test [Src.Statement_class.atomic ~specifically:Store ()] ;
[%expect {| false |}]
end )
let%test_module "unmatches_any" =
( module struct
let test (templates : Src.Statement_class.t list) : unit =
let k =
Src.Statement_class.unmatches_any
(Lazy.force test_fragment)
~templates
in
Stdio.printf "%b" k
let%expect_test "no classes" = test [] ; [%expect {| false |}]
let%expect_test "if statements" = test [If] ; [%expect {| false |}]
let%expect_test "labels" =
test [Prim (Some Label)] ; [%expect {| true |}]
let%expect_test "while loops" =
test [Src.Statement_class.while_loop ()] ;
[%expect {| true |}]
let%expect_test "atomics of any form" =
test [Src.Statement_class.atomic ()] ;
[%expect {| true |}]
let%expect_test "atomic_store" =
test [Src.Statement_class.atomic ~specifically:Store ()] ;
[%expect {| true |}]
end )
let%test_module "rec_matches_any" =
( module struct
let test (templates : Src.Statement_class.t list) : unit =
let k =
Src.Statement_class.rec_matches_any
(Lazy.force test_fragment)
~templates
in
Stdio.printf "%b" k
let%expect_test "no classes" = test [] ; [%expect {| false |}]
let%expect_test "if statements" = test [If] ; [%expect {| true |}]
let%expect_test "while loops" =
test [Src.Statement_class.while_loop ()] ;
[%expect {| false |}]
let%expect_test "atomics of any form" =
test [Src.Statement_class.atomic ()] ;
[%expect {| true |}]
let%expect_test "atomic_store" =
test [Src.Statement_class.atomic ~specifically:Store ()] ;
[%expect {| true |}]
end )
let%test_module "rec_unmatches_any" =
( module struct
let test (templates : Src.Statement_class.t list) : unit =
let k =
Src.Statement_class.rec_unmatches_any
(Lazy.force test_fragment)
~templates
in
Stdio.printf "%b" k
let%expect_test "no classes" = test [] ; [%expect {| false |}]
let%expect_test "if statements" = test [If] ; [%expect {| true |}]
let%expect_test "while loops" =
test [Src.Statement_class.while_loop ()] ;
[%expect {| true |}]
let%expect_test "atomics of any form" =
test [Src.Statement_class.atomic ()] ;
[%expect {| true |}]
let%expect_test "atomic_store" =
test [Src.Statement_class.atomic ~specifically:Store ()] ;
[%expect {| true |}]
end )
let%test_module "count_matches" =
( module struct
let test (templates : Src.Statement_class.t list) : unit =
let k =
Src.Statement_class.count_rec_matches
(Lazy.force test_fragment)
~templates
in
Stdio.printf "%d" k
let%expect_test "if statements" = test [If] ; [%expect {| 2 |}]
let%expect_test "atomics of any form" =
test [Src.Statement_class.atomic ()] ;
[%expect {| 3 |}]
let%expect_test "atomic_store" =
test [Src.Statement_class.atomic ~specifically:Store ()] ;
[%expect {| 1 |}]
let%expect_test "atomic_store or atomic_load" =
test
[ Src.Statement_class.atomic ~specifically:Store ()
; Src.Statement_class.atomic ~specifically:Load () ] ;
[%expect {| 1 |}]
end )
|
|
b495e950ede0a769c100be4ab6f9f5ab5476cff98cc2b3a595d05dc4b69d6e51 | seancorfield/honeysql | gen_doc_tests.clj | (ns honey.gen-doc-tests
(:require [babashka.fs :as fs]
[lread.test-doc-blocks :as tdb]))
(defn -main [& _args]
(let [target "target/test-doc-blocks"
success-marker (fs/file target "SUCCESS")
docs ["README.md"
"doc/clause-reference.md"
"doc/differences-from-1-x.md"
"doc/extending-honeysql.md"
"doc/general-reference.md"
"doc/getting-started.md"
;;"doc/operator-reference.md"
"doc/options.md"
"doc/postgresql.md"
"doc/special-syntax.md"]
regen-reason (if (not (fs/exists? success-marker))
"a previous successful gen result not found"
(let [newer-thans (fs/modified-since target
(concat docs
["build.clj" "deps.edn"]
(fs/glob "build" "**/*.*")
(fs/glob "src" "**/*.*")))]
(when (seq newer-thans)
(str "found files newer than last gen: " (mapv str newer-thans)))))]
(if regen-reason
(do
(fs/delete-if-exists success-marker)
(println "gen-doc-tests: Regenerating:" regen-reason)
(tdb/gen-tests {:docs docs})
(spit success-marker "SUCCESS"))
(println "gen-doc-tests: Tests already successfully generated"))))
| null | https://raw.githubusercontent.com/seancorfield/honeysql/3def127276cce6d206cc6c4d36d0e026323d9bed/build/honey/gen_doc_tests.clj | clojure | "doc/operator-reference.md" | (ns honey.gen-doc-tests
(:require [babashka.fs :as fs]
[lread.test-doc-blocks :as tdb]))
(defn -main [& _args]
(let [target "target/test-doc-blocks"
success-marker (fs/file target "SUCCESS")
docs ["README.md"
"doc/clause-reference.md"
"doc/differences-from-1-x.md"
"doc/extending-honeysql.md"
"doc/general-reference.md"
"doc/getting-started.md"
"doc/options.md"
"doc/postgresql.md"
"doc/special-syntax.md"]
regen-reason (if (not (fs/exists? success-marker))
"a previous successful gen result not found"
(let [newer-thans (fs/modified-since target
(concat docs
["build.clj" "deps.edn"]
(fs/glob "build" "**/*.*")
(fs/glob "src" "**/*.*")))]
(when (seq newer-thans)
(str "found files newer than last gen: " (mapv str newer-thans)))))]
(if regen-reason
(do
(fs/delete-if-exists success-marker)
(println "gen-doc-tests: Regenerating:" regen-reason)
(tdb/gen-tests {:docs docs})
(spit success-marker "SUCCESS"))
(println "gen-doc-tests: Tests already successfully generated"))))
|
18a2580a662c2a17b94ed0fda97538d0d52d64ed40466a307699a0a3b21eccbb | jwiegley/notes | Day.hs | # LANGUAGE DeriveFunctor #
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE MultiParamTypeClasses #
module Day where
import Control.Monad.Free
import Control.Comonad.Cofree
data AdderF k =
Add Int (Bool -> k)
| Clear k
| Total (Int -> k)
deriving Functor
type Adder a = Free AdderF a
data CoAdderF k = CoAdderF {
addH :: Int -> (Bool, k)
, clearH :: k
, totalH :: (Int, k)
}
deriving Functor
type Limit = Int
type Count = Int
type CoAdder a = Cofree CoAdderF a
mkCoAdder :: Limit -> Count -> CoAdder (Limit, Count)
mkCoAdder limit count = coiter next start
where
next w = CoAdderF (coAdd w) (coClear w) (coTotal w)
start = (limit, count)
coClear :: (Limit, Count) -> (Limit, Count)
coClear (limit, _count) = (limit, 0)
coTotal :: (Limit, Count) -> (Int, (Limit, Count))
coTotal (limit, count) = (count, (limit, count))
coAdd :: (Limit, Count) -> Int -> (Bool, (Limit, Count))
coAdd (limit, count) x = (test, (limit, next))
where
count' = count + x
test = count' <= limit
next = if test then count' else count
add :: Int -> Adder Bool
add x = liftF $ Add x id
clear :: Adder ()
clear = liftF $ Clear ()
total :: Adder Int
total = liftF $ Total id
data Day f g a = forall b c. Day (b -> c -> a) (f b) (g c)
type Algebra f a = f a -> a
class (Functor f, Functor g) => Dual f g where
zap :: Algebra (Day f g) r
instance Dual ((->) a) ((,) a) where
zap (Day p f (a, b)) = p (f a) b
instance Dual ((,) a) ((->) a) where
zap (Day p (a, b) g) = p b (g a)
instance Dual f g => Dual (Cofree f) (Free g) where
zap (Day p (a :< _ ) (Pure x)) = p a x
zap (Day p (_ :< fs) (Free gs)) =
zap $ Day (\a b -> zap $ Day p a b) fs gs
instance Dual CoAdderF AdderF where
zap (Day f (CoAdderF a _ _) (Add x k)) = zap $ Day f (a x) k
zap (Day f (CoAdderF _ c _) (Clear k)) = f c k
zap (Day f (CoAdderF _ _ t) (Total k)) = zap $ Day f t k
runLimit :: CoAdder a -> Int
runLimit w = zap $ Day (\_ b -> b) w $ do
add 1
add 2
total
| null | https://raw.githubusercontent.com/jwiegley/notes/24574b02bfd869845faa1521854f90e4e8bf5e9a/haskell/Day.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE RankNTypes # | # LANGUAGE DeriveFunctor #
# LANGUAGE MultiParamTypeClasses #
module Day where
import Control.Monad.Free
import Control.Comonad.Cofree
data AdderF k =
Add Int (Bool -> k)
| Clear k
| Total (Int -> k)
deriving Functor
type Adder a = Free AdderF a
data CoAdderF k = CoAdderF {
addH :: Int -> (Bool, k)
, clearH :: k
, totalH :: (Int, k)
}
deriving Functor
type Limit = Int
type Count = Int
type CoAdder a = Cofree CoAdderF a
mkCoAdder :: Limit -> Count -> CoAdder (Limit, Count)
mkCoAdder limit count = coiter next start
where
next w = CoAdderF (coAdd w) (coClear w) (coTotal w)
start = (limit, count)
coClear :: (Limit, Count) -> (Limit, Count)
coClear (limit, _count) = (limit, 0)
coTotal :: (Limit, Count) -> (Int, (Limit, Count))
coTotal (limit, count) = (count, (limit, count))
coAdd :: (Limit, Count) -> Int -> (Bool, (Limit, Count))
coAdd (limit, count) x = (test, (limit, next))
where
count' = count + x
test = count' <= limit
next = if test then count' else count
add :: Int -> Adder Bool
add x = liftF $ Add x id
clear :: Adder ()
clear = liftF $ Clear ()
total :: Adder Int
total = liftF $ Total id
data Day f g a = forall b c. Day (b -> c -> a) (f b) (g c)
type Algebra f a = f a -> a
class (Functor f, Functor g) => Dual f g where
zap :: Algebra (Day f g) r
instance Dual ((->) a) ((,) a) where
zap (Day p f (a, b)) = p (f a) b
instance Dual ((,) a) ((->) a) where
zap (Day p (a, b) g) = p b (g a)
instance Dual f g => Dual (Cofree f) (Free g) where
zap (Day p (a :< _ ) (Pure x)) = p a x
zap (Day p (_ :< fs) (Free gs)) =
zap $ Day (\a b -> zap $ Day p a b) fs gs
instance Dual CoAdderF AdderF where
zap (Day f (CoAdderF a _ _) (Add x k)) = zap $ Day f (a x) k
zap (Day f (CoAdderF _ c _) (Clear k)) = f c k
zap (Day f (CoAdderF _ _ t) (Total k)) = zap $ Day f t k
runLimit :: CoAdder a -> Int
runLimit w = zap $ Day (\_ b -> b) w $ do
add 1
add 2
total
|
849ee9eb64e359398b04d1ad77d2e5b234a73b73a16bcc2ffa8dda66ecd8ebda | codinuum/cca | sourcecode.ml |
Copyright 2012 - 2022 Codinuum Software Lab < >
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyright 2012-2022 Codinuum Software Lab <>
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.
*)
(* sourcecode.ml *)
open Otreediff
module GI = GIndex
module MID = Moveid
module C = Compression
module SB = Spec_base
let sprintf = Printf.sprintf
type name = string
let n_lines_for_file_check = 32
let bison_pat = Str.regexp "#define[ \t]+YYBISON[ \t]+1"
let flex_pat = Str.regexp "#define[ \t]+FLEX_SCANNER"
let search_pat pats file =
let b = ref false in
let ch = file#get_channel in
begin
try
for i = 1 to n_lines_for_file_check do
let s = ch#input_line() in
try
List.iter
(fun pat ->
let _ = (Str.search_forward pat s 0) in
b := true;
raise Exit
) pats
with
Not_found -> ()
done
with
| End_of_file -> ()
| Exit -> ()
end;
ch#close_in();
!b
let is_generated f = search_pat [bison_pat;flex_pat] f
let unknown_origin = "-1"
let earliest_origin = "0"
let dump_gmap_ch gmap ch =
List.iter (fun (gi1, gi2) -> Printf.fprintf ch "%d - %d\n" gi1 gi2) gmap
let mkgmapfilepath ?(gmap_ext=".gmap") cache_path frag =
Filename.concat cache_path (frag#hash ^ gmap_ext)
let dump_gmap gmap fpath =
let d = Filename.dirname fpath in
if not (Xfile.dir_exists d) then begin
Xfile.mkdir d
end;
Xfile.dump fpath (dump_gmap_ch gmap)
let load_gmap_ch ch =
let l = ref [] in
try
while true do
let s = input_line ch in
Scanf.sscanf s "%d - %d" (fun i j -> l := (i, j)::!l)
done;
[]
with
End_of_file -> List.rev !l
let load_gmap fpath =
DEBUG_MSG "fpath=\"%s\"" fpath;
try
Xfile.load fpath load_gmap_ch
with
Failure _ -> []
let digest_of_file options file =
DEBUG_MSG "file=\"%s\"" file;
Xhash.digest_of_file options#hash_algo file
let encode_digest options d =
(Xhash.algo_to_string options#fact_algo)^Entity.sub_sep^(Xhash.to_hex d)
let encoded_digest_of_file options file =
let d = digest_of_file options file in
encode_digest options d
let int_of_origin ogn =
if ogn = unknown_origin then
Origin.attr_unknown
else begin
try
int_of_string ogn
with
Invalid_argument s -> ERROR_MSG "int_of_origin: %s" s; exit 1
end
let merge_locs nds =
let lmerge loc1 loc2 =
if loc1 = Loc.dummy then loc2
else if loc2 = Loc.dummy then loc1
else Loc.merge loc1 loc2
in
List.fold_left (fun l n -> lmerge l n#data#src_loc) Loc.dummy nds
let is_ghost_node nd = nd#data#src_loc = Loc.ghost
let dec_attrs = List.map (fun (a, v) -> a, (XML._decode_string v))
module Tree (L : Spec.LABEL_T) = struct
let of_elem_data name attrs =
let lname = XML.get_local_part name in
let lattrs = List.map (fun (a, v) -> XML.get_local_part a, v) attrs in
L.of_elem_data lname lattrs ""
let compare_node nd1 nd2 = compare nd1#data#label nd2#data#label
exception Found
exception Malformed_row of string
let get_lab nd = (Obj.obj nd#data#_label : L.t)
let get_orig_lab_opt nd =
match nd#data#orig_lab_opt with
| Some o -> Some (Obj.obj o : L.t)
| None -> None
let get_annotation nd = (Obj.obj nd#data#_annotation : L.annotation)
class ordinal_tbl (l : int list) = object (self) (* handling logical ordinal of a child *)
val mutable ordinal_list = l
method get_ordinal nth =
let rec doit i a = function
| [] -> raise Not_found
| h::t ->
let ah = a + h in
if a <= nth && nth < ah then
i
else
doit (i+1) ah t
in
doit 0 0 ordinal_list
method list = ordinal_list
method add_list l =
ordinal_list <- ordinal_list @ l
method to_string =
"["^(Xlist.to_string string_of_int ";" ordinal_list)^"]"
end
let null_ordinal_tbl = new ordinal_tbl []
class node_data
options
?(annot=L.null_annotation)
?(ordinal_tbl_opt=(None : ordinal_tbl option))
?(orig_lab_opt=(None : L.t option))
(lab : L.t)
=
let is_named = L.is_named lab in
let is_named_orig = L.is_named_orig lab in
let category = L.get_category lab in
object (self : 'self)
inherit Otree.data2
constraint 'node = 'self Otree.node2
val mutable prefix = ""
method set_prefix s = prefix <- s
method get_prefix = prefix
val mutable suffix = ""
method set_suffix s = suffix <- s
method get_suffix = suffix
val mutable _eq = fun _ -> false
val mutable source_fid = ""
method set_source_fid x = source_fid <- x
method source_fid = source_fid
method get_ordinal nth =
match ordinal_tbl_opt with
| None -> nth
| Some tbl -> tbl#get_ordinal nth
method add_to_ordinal_list l =
match ordinal_tbl_opt with
| None -> failwith "Sourcecode.node_data#add_to_ordinal_list"
| Some tbl -> tbl#add_list l
val mutable lab = lab
val mutable orig_lab_opt = orig_lab_opt
val mutable _label = Obj.repr ()
method _label = _label
val mutable label = ""
method label = label
val mutable rep = ""
method to_rep = rep
val mutable short_string = ""
method to_short_string = short_string
val mutable _digest = None
method _digest = _digest
val mutable digest = None
method digest = digest
method private update =
label <- L.to_string lab;
_label <- Obj.repr lab;
let ignore_identifiers_flag = options#ignore_identifiers_flag in
let short_str = L.to_short_string ~ignore_identifiers_flag lab in
rep <- short_str;
short_string <- short_str;
match _digest with
| Some d -> rep <- String.concat "" [rep;"<";d;">"]
| None -> ()
method elem_name_for_delta =
let n, _, _ = self#to_elem_data_for_delta in
n
method orig_elem_name_for_delta =
let n, _, _ = self#orig_to_elem_data_for_delta in
n
method elem_attrs_for_delta =
let _, attrs, _ = self#to_elem_data_for_delta in
attrs
method orig_elem_attrs_for_delta =
let _, attrs, _ = self#orig_to_elem_data_for_delta in
attrs
method change_attr (attr : string) (v : string) =
let name, attrs, _ = self#orig_to_elem_data_for_delta in
if List.mem_assoc attr attrs then begin
let attrs' = dec_attrs (List.remove_assoc attr attrs) in
let lab' = of_elem_data name ((attr, v)::attrs') in
DEBUG_MSG "%s -> %s" (L.to_string lab) (L.to_string lab');
orig_lab_opt <- Some lab';
DEBUG_MSG "%s" self#to_string
self#update
end
method delete_attr (attr : string) =
let name, attrs, _ = self#orig_to_elem_data_for_delta in
let attrs' = dec_attrs (List.remove_assoc attr attrs) in
orig_lab_opt <- Some (of_elem_data name attrs');
self#update
method insert_attr (attr : string) (v : string) =
let name, attrs, _ = self#orig_to_elem_data_for_delta in
let attrs' = dec_attrs (List.remove_assoc attr attrs) in
orig_lab_opt <- Some (of_elem_data name ((attr, v)::attrs'));
self#update
val successors = (Xset.create 0 : 'node Xset.t)
method successors = successors
method add_successor nd = Xset.add successors nd
val mutable binding = Binding.NoBinding
method binding = binding
method set_binding b = binding <- b
val mutable bindings = []
method bindings = bindings
method add_binding (b : Binding.t) =
if not (List.mem b bindings) then
bindings <- b :: bindings
method get_ident_use = L.get_ident_use lab
val mutable origin = unknown_origin
method origin = origin
method set_origin o = origin <- o
val mutable ending = unknown_origin
method ending = ending
method set_ending e = ending <- e
val mutable frommacro = ""
method frommacro = frommacro
method set_frommacro fm = frommacro <- fm
method is_frommacro = frommacro <> ""
method not_frommacro = frommacro = ""
val _annotation = Obj.repr annot
method _annotation = _annotation
method quasi_eq (ndat : 'self) =
L.quasi_eq lab (Obj.obj ndat#_label : L.t)
method relabel_allowed (ndat : 'self) =
L.relabel_allowed (lab, (Obj.obj ndat#_label : L.t))
method is_compatible_with ?(weak=false) (ndat : 'self) =
L.is_compatible ~weak lab (Obj.obj ndat#_label : L.t) ||
match orig_lab_opt, ndat#orig_lab_opt with
| Some l1, Some o2 -> L.is_compatible ~weak l1 (Obj.obj o2)
| _ -> false
method is_order_insensitive = L.is_order_insensitive lab
method move_disallowed = L.move_disallowed lab
method is_common = L.is_common lab
method _anonymized_label = Obj.repr (L.anonymize lab)
(*method _more_anonymized_label = Obj.repr (L.anonymize ~more:true lab)*)
val mutable anonymized_label = None
method anonymized_label =
match anonymized_label with
| None ->
let alab = L.to_string (L.anonymize lab) in
anonymized_label <- Some alab;
alab
| Some alab -> alab
val mutable more_anonymized_label = None
method more_anonymized_label =
match more_anonymized_label with
| None ->
let alab = L.to_string (L.anonymize ~more:true lab) in
more_anonymized_label <- Some alab;
alab
| Some alab -> alab
val mutable anonymized2_label = None
method _anonymized2_label = Obj.repr (L.anonymize2 lab)
method anonymized2_label =
match anonymized2_label with
| None ->
let alab = L.to_string (L.anonymize2 lab) in
anonymized2_label <- Some alab;
alab
| Some alab -> alab
val mutable anonymized3_label = None
method _anonymized3_label = Obj.repr (L.anonymize3 lab)
method anonymized3_label =
match anonymized3_label with
| None ->
let alab = L.to_string (L.anonymize3 lab) in
anonymized3_label <- Some alab;
alab
| Some alab -> alab
method to_simple_string = L.to_simple_string lab
method _set_digest d =
_digest <- Some d;
let ignore_identifiers_flag = options#ignore_identifiers_flag in
rep <- String.concat ""
[L.to_short_string ~ignore_identifiers_flag lab;"<";d;">"]
method set_digest d =
digest <- Some d;
self#_set_digest d
method reset_digest = digest <- None
method to_be_notified = L.is_to_be_notified lab
method is_boundary = L.is_boundary lab
method is_partition = L.is_partition lab
method is_sequence = L.is_sequence lab
method is_phantom = L.is_phantom lab
method is_special = L.is_special lab
method to_elem_data = L.to_elem_data self#src_loc lab
method to_elem_data_for_delta = L.to_elem_data ~strip:true ?afilt:None self#src_loc lab
method orig_to_elem_data_for_delta =
let lab_ =
match orig_lab_opt with
| Some l -> l
| None -> lab
in
L.to_elem_data ~strip:true ?afilt:None self#src_loc lab_
method orig_to_elem_data_for_eq =
let lab_ =
match orig_lab_opt with
| Some l -> l
| None -> lab
in
let afilt a = not (Xstring.startswith a "___") in
L.to_elem_data ~strip:true ~afilt self#src_loc lab_
method eq ndat = _eq ndat
(*_label = ndat#_label && self#orig_lab_opt = ndat#orig_lab_opt*)
method subtree_equals ndat =
self#eq ndat && _digest = ndat#_digest && _digest <> None
method equals ndat = self#eq ndat && digest = ndat#digest
val mutable src_loc = Loc.dummy
method set_loc loc = src_loc <- loc
method src_loc = src_loc
method to_string =
sprintf "%s%s[%s]"
self#label
(match orig_lab_opt with Some l -> "("^(L.to_string l)^")" | None -> "")
(Loc.to_string src_loc)
method is_named = is_named
method is_named_orig = is_named_orig
method is_anonymous = not is_named
method is_anonymous_orig = not is_named_orig
method feature =
if self#is_named then
self#_label, None
else
self#_label, self#digest
method get_category = category
method get_name = L.get_name lab
method get_orig_name =
match orig_lab_opt with
| Some o -> L.get_name o
| None -> self#get_name
method get_value = L.get_value lab
method has_value = L.has_value lab
method has_non_trivial_value = L.has_non_trivial_value lab
method is_string_literal = L.is_string_literal lab
method is_int_literal = L.is_int_literal lab
method is_real_literal = L.is_real_literal lab
method is_statement = L.is_statement lab
method is_op = L.is_op lab
val mutable move_id = MID.unknown
method set_mid mid = move_id <- mid
method mid = move_id
method orig_lab_opt =
match orig_lab_opt with
| Some l -> Some (Obj.repr l)
| None -> None
initializer
_eq <-
if options#weak_eq_flag then
(fun x ->
_label = x#_label && self#orig_lab_opt = x#orig_lab_opt ||
(not self#is_named_orig) && (not self#has_value) &&
(not x#is_named_orig) && (not x#has_value) &&
self#elem_name_for_delta = x#elem_name_for_delta ||
(match self#orig_lab_opt, x#orig_lab_opt with
| Some o1, Some o2 -> o1 = o2
| Some o1, None -> L.is_compatible ~weak:true (Obj.obj o1) (Obj.obj x#_label)
| None, Some o2 -> L.is_compatible ~weak:true (Obj.obj _label) (Obj.obj o2)
| _ -> false) ||
self#is_compatible_with ~weak:true x)
else
(fun x -> _label = x#_label && self#orig_lab_opt = x#orig_lab_opt(*self#orig_to_elem_data_for_eq = x#orig_to_elem_data_for_eq*));
self#update
(* for searchast *)
val mutable char = None
method char =
if char = None then begin
let c = L.to_char lab in
char <- Some c;
c
end
else
match char with
| Some c -> c
| _ -> assert false
end (* of class Sourcecode.node_data *)
let mknode options
?(annot=L.null_annotation)
?(ordinal_tbl_opt=None)
?(orig_lab_opt=None)
lab nodes
=
Otree.create_node2 options#uid_generator
(new node_data options ~annot ~ordinal_tbl_opt ~orig_lab_opt lab) (Array.of_list nodes)
let mklnode options ?(annot=L.null_annotation) ?(orig_lab_opt=None) lab nodes =
mknode options ~annot ~ordinal_tbl_opt:(Some null_ordinal_tbl) ~orig_lab_opt lab nodes
let mkleaf options ?(annot=L.null_annotation) ?(orig_lab_opt=None) lab =
Otree.create_node2 options#uid_generator
(new node_data options ~annot ~orig_lab_opt lab) [||]
let _get_logical_nth_child nd nth =
let l = ref [] in
Array.iteri
(fun i x ->
if (nd#data#get_ordinal i) = nth then
l := x :: !l
) nd#children;
Array.of_list (List.rev !l)
let get_logical_nth_child nd nth =
let l = ref [] in
Array.iteri
(fun i x ->
if (nd#data#get_ordinal i) = nth then
l := x :: !l
) nd#initial_children;
Array.of_list (List.rev !l)
class node_maker options = object (self)
method private mknode
?(annot=L.null_annotation)
?(ordinal_tbl_opt=None)
?(orig_lab_opt=None)
lab nodes
=
mknode options ~annot ~ordinal_tbl_opt ~orig_lab_opt lab nodes
method private mklnode ?(annot=L.null_annotation) ?(orig_lab_opt=None) lab nodes =
mklnode options ~annot ~orig_lab_opt lab nodes
method private mkleaf ?(annot=L.null_annotation) ?(orig_lab_opt=None) lab =
mkleaf options ~annot ~orig_lab_opt lab
end
type node_t = Spec.node_t
let make_unparser unparse node ch =
let redirect = not (SB.OutChannel.is_stdout ch) in
if redirect then begin
try
Format.set_formatter_out_channel (SB.OutChannel.to_pervasives ch)
with
_ ->
let xc = SB.OutChannel.to_xchannel ch in
let out s pos len = ignore (xc#output_ s pos len) in
let flush () = xc#close in
Format.set_formatter_output_functions out flush
end;
unparse node;
if redirect then begin
Format.set_formatter_out_channel Stdlib.stdout
end
class c options (root : node_t) (is_whole : bool) = object (self : 'self)
inherit node_maker options
inherit [ node_t ] Otree.otree2 root is_whole as super
method private create root is_whole =
let t = new c options root is_whole in
t#setup_initial_children;
t
method extra_namespaces = ([] : (string * string) list)
method unparse_subtree_ch :
?no_boxing:bool -> ?no_header:bool -> ?fail_on_error:bool -> node_t -> SB.OutChannel.t -> unit =
fun ?(no_boxing=false) ?(no_header=false) ?(fail_on_error=true) _ _ ->
failwith "Sourcecode.unparse_subtree_ch: unparser is not implemented yet"
method unparse_ch ?(no_boxing=false) ?(no_header=false) ?(fail_on_error=true) =
self#unparse_subtree_ch ~no_boxing ~no_header ~fail_on_error root
method get_digest nd =
let st = self#create nd false in
let d = st#digest in
nd#data#_set_digest d;
d
val mutable true_parent_tbl = (Hashtbl.create 0 : (UID.t, node_t) Hashtbl.t)
method set_true_parent_tbl tbl = true_parent_tbl <- tbl
method find_true_parent uid =
Hashtbl.find true_parent_tbl uid
val mutable true_children_tbl = (Hashtbl.create 0 : (node_t, node_t array) Hashtbl.t)
method set_true_children_tbl tbl = true_children_tbl <- tbl
method recover_true_children ~initial_only () =
(*Printf.printf "! [before] initial_size=%d (initial_only=%B)\n"
self#initial_size initial_only;*)
DEBUG_MSG "initial_only=%B" initial_only;
let modified = ref false in
Hashtbl.iter
(fun nd c ->
DEBUG_MSG "recovering true children: %a -> [%s]"
UID.ps nd#uid (Xarray.to_string (fun n -> UID.to_string n#uid) ";" c);
(*if (Array.length nd#initial_children) <> (Array.length c) then begin
Printf.printf "!!! %s\n" nd#initial_to_string;
Printf.printf "!!! [%s] -> [%s]\n"
(Xarray.to_string (fun n -> UID.to_string n#uid) ";" nd#initial_children)
(Xarray.to_string (fun n -> UID.to_string n#uid) ";" c)
end;*)
nd#set_initial_children c;
if not initial_only then
nd#set_children c;
Array.iteri
(fun i n ->
n#set_initial_parent nd;
n#set_initial_pos i;
if not initial_only then begin
n#set_parent nd;
n#set_pos i
end
) c;
modified := true
) true_children_tbl;
BEGIN_DEBUG
Hashtbl.iter
(fun uid nd ->
DEBUG_MSG "true parent: %a -> %a" UID.ps uid UID.ps nd#uid
) true_parent_tbl
END_DEBUG;
if !modified then begin
self#fast_scan_whole_initial (fun nd -> nd#set_gindex GI.unknown);
self#setup_initial_size;
self#setup_gindex_table;
self#setup_initial_leftmost_table;
self#setup_apath
end(*;
Printf.printf "! [after] initial_size=%d\n" self#initial_size*)
val mutable source_path = "unknown"
method set_source_path p = source_path <- p
method source_path = source_path
val mutable source_fullpath = "unknown"
method set_source_fullpath p = source_fullpath <- p
method source_fullpath = source_fullpath
val mutable source_kind = Storage.kind_dummy
method set_source_kind k = source_kind <- k
method source_kind = source_kind
val mutable vkind = Entity.V_UNKNOWN
method set_vkind k = vkind <- k
method vkind = vkind
val mutable version = ""
method set_version n = version <- n
method version = version
val mutable proj_root = ""
method set_proj_root r = proj_root <- r
method proj_root = proj_root
val mutable source_digest = "unknown"
method set_source_digest d = source_digest <- d
method source_digest = source_digest
method encoded_source_digest = encode_digest options source_digest
method set_source_info (file : Storage.file) =
self#set_source_path file#path;
self#set_source_fullpath file#fullpath;
self#set_source_kind file#kind;
self#set_source_digest file#digest
val mutable parser_name = "unknown"
method set_parser_name n = parser_name <- n
method parser_name = parser_name
method private get_attrs =
let attrs_to_string attrs =
String.concat "" (List.map (fun (a, v) -> sprintf " %s='%s'" a v) attrs)
in
let lang_attr =
try
["xmlns:"^L.lang_prefix, List.assoc L.lang_prefix Astml.parser_tbl;]
with
Not_found -> []
in
let l =
lang_attr @
[ "xmlns:"^Astml.default_prefix, Astml.ast_ns;
Astml.parser_attr_name, self#parser_name;
Astml.source_attr_name, Filename.basename self#source_path;
Astml.source_digest_attr_name, self#encoded_source_digest;
]
in
attrs_to_string l
method dump_astml ?(comp=C.none) fname =
let pre_tags = sprintf "<%s%s>" Astml.astml_tag self#get_attrs in
let post_tags = sprintf "</%s>" Astml.astml_tag in
super#save_in_xml ~initial:true ~comp ~pre_tags ~post_tags fname
method collapse =
let filt nd =
let lab = get_lab nd in
if L.forced_to_be_collapsible lab then
nd#set_collapsible;
L.is_collapse_target options lab
in
self#collapse_nodes filt
subtree copy ( gindexes are inherited )
method make_subtree_copy ?(find_hook=fun _ -> raise Not_found) (nd : node_t) =
let hooked = ref [] in
let rec doit nd =
let gi = nd#gindex in
if GI.is_valid gi then
let children = Xlist.filter_map doit (Array.to_list nd#initial_children) in
let lab = get_lab nd in
let orig_lab_opt = get_orig_lab_opt nd in
let new_nd = self#mknode ~orig_lab_opt lab children in
new_nd#set_gindex gi;
begin
try
let a = find_hook nd in
hooked := (new_nd, a) :: !hooked
with
Not_found -> ()
end;
Some new_nd
else
None
in
let root =
match doit nd with
| Some r -> r
| None -> raise (Invalid_argument "Sourcecode.c#make_subtree_copy")
in
let tree = self#create root false in
tree#_register_gindexes;
List.iter
(fun (n, a) ->
a n
) !hooked;
tree
subtree copy ( gindexes are inherited )
method private make_anonymizedx_subtree_copy anonymize ?(uids_left_named=[]) (nd : node_t) =
let rec doit n =
let gi = n#gindex in
if GI.is_valid gi then
let children = Xlist.filter_map doit (Array.to_list n#initial_children) in
let alab =
if List.mem n#uid uids_left_named then
get_lab n
else
anonymize n
in
let new_nd = self#mknode alab children in
new_nd#set_gindex gi;
Some new_nd
else
None
in
let root =
match doit nd with
| Some r -> r
| None -> raise (Invalid_argument "Sourcecode.c#make_anonymized_subtree_copy")
in
let tree = self#create root false in
tree#_register_gindexes;
tree
method make_anonymized_subtree_copy ?(uids_left_named=[]) (nd : node_t) =
let anonymize n = (Obj.obj n#data#_anonymized_label : L.t) in
self#make_anonymizedx_subtree_copy anonymize ~uids_left_named nd
method make_anonymized2_subtree_copy ?(uids_left_named=[]) (nd : node_t) =
let anonymize n = (Obj.obj n#data#_anonymized2_label : L.t) in
self#make_anonymizedx_subtree_copy anonymize ~uids_left_named nd
method make_anonymized3_subtree_copy ?(uids_left_named=[]) (nd : node_t) =
let anonymize n = (Obj.obj n#data#_anonymized3_label : L.t) in
self#make_anonymizedx_subtree_copy anonymize ~uids_left_named nd
method get_ident_use_list gid =
let nd = self#search_node_by_gindex gid in
let res = ref [] in
self#preorder_scan_whole_initial_subtree nd
(fun n ->
let s = n#data#get_ident_use in
if not (List.mem s !res) && s <> "" then
res := s::!res
);
List.rev !res
method initial_subtree_to_rep nd =
let buf = Buffer.create 0 in
self#scan_whole_initial_subtree nd
(fun n ->
Buffer.add_string buf n#to_rep
);
Buffer.contents buf
method initial_to_rep = self#initial_subtree_to_rep root
method subtree_to_simple_string gid =
let nd = self#search_node_by_gindex gid in
let children = Array.to_list nd#initial_children in
match children with
| [] -> nd#data#to_simple_string
| _ ->
sprintf "%s(%s)"
nd#data#to_simple_string
(String.concat ","
(List.map
(fun nd -> self#subtree_to_simple_string nd#gindex)
children
)
)
(*
val mutable line_terminator = ""
method set_line_terminator s = line_terminator <- s
method line_terminator = line_terminator
method line_terminator_name =
match line_terminator with
"\013\010" -> "CRLF"
| "\013" -> "CR"
| "\010" -> "LF"
| _ -> "??"
*)
method dump_line_ranges fpath =
let ch = open_out fpath in
self#fast_scan_whole_initial
(fun nd ->
Printf.fprintf ch "%d-%d\n"
nd#data#src_loc.Loc.start_line nd#data#src_loc.Loc.end_line
)
val mutable ignored_regions = ([] : (int * int) list)
method set_ignored_regions r = ignored_regions <- r
method ignored_regions = ignored_regions
val mutable misparsed_regions = ([] : (int * int) list)
method set_misparsed_regions r = misparsed_regions <- r
method misparsed_regions = misparsed_regions
val mutable total_LOC = 0
method set_total_LOC n = total_LOC <- n
method total_LOC = total_LOC
val mutable misparsed_LOC = 0
method set_misparsed_LOC n = misparsed_LOC <- n
method misparsed_LOC = misparsed_LOC
method get_units_to_be_notified =
let res = ref [] in
self#fast_scan_whole_initial
(fun nd ->
if nd#data#to_be_notified then
res := nd::!res
);
!res
method get_nearest_containing_unit uid =
let nd = self#search_node_by_uid uid in
let ancs = List.rev (self#initial_ancestor_nodes nd) in
if nd#data#to_be_notified then
nd
else
let rec scan = function
h::t -> if h#data#to_be_notified then h else scan t
| [] -> raise Not_found
in
scan ancs
method make_subtree_from_node nd =
let tree = self#create nd false in
tree#_set_gindex_table gindex_table;
tree#_set_initial_leftmost_table initial_leftmost_table;
tree
method make_subtree_from_uid uid =
let nd = self#search_node_by_uid uid in
self#make_subtree_from_node nd
method make_subtree_from_path path =
let nd = self#initial_acc path in
self#make_subtree_from_node nd
method label_match kw =
let re = Str.regexp (".*"^kw^".*") in
try
self#fast_scan_whole_initial
(fun nd ->
if Str.string_match re nd#data#label 0 then begin
Xprint.verbose options#verbose_flag "keyword=\"%s\" matched=%s" kw nd#data#to_string;
raise Found
end
);
false
with
Found -> true
method merge_locs_adjusting_to_boundary gids =
BEGIN_DEBUG
DEBUG_MSG "tree size: %d" self#size;
List.iter
(fun gid ->
if gid >= self#size then begin
WARN_MSG "invalid gid: %a" GI.ps gid;
exit 1
end
) gids
END_DEBUG;
let groups = ref [] in
let nds = List.map self#search_node_by_gindex gids in
let rec scan = function
| [] -> ()
| nd0::rest ->
let group = ref [nd0] in
List.iter
(fun nd ->
if not (self#cross_boundary nd0 nd) then
group := nd::!group
) rest;
groups := !group::!groups
in
scan nds;
let max_group = ref [] in
let max = ref 0 in
List.iter
(fun g ->
if (List.length g) > !max then begin
max_group := g;
max := List.length g
end
) !groups;
merge_locs !max_group
method private cross_boundary nd1 nd2 =
let ands1 = List.filter (fun n -> n#data#not_frommacro) (self#initial_ancestor_nodes nd1) in
let ands2 = List.filter (fun n -> n#data#not_frommacro) (self#initial_ancestor_nodes nd2) in
let rec scan b = function
| h1::t1, h2::t2 ->
if h1 == h2 then
scan false (t1, t2)
else
scan (b || h1#data#is_boundary || h2#data#is_boundary) (t1, t2)
| [], rest | rest, [] ->
if b then
true
else
let rec restscan = function
h::t ->
if h#data#is_boundary then
true
else
restscan t
| [] -> false
in
restscan rest
in
scan false (ands1, ands2)
method get_nearest_boundary nd =
let ancs = List.rev (self#initial_ancestor_nodes nd) in
if nd#data#is_boundary then
nd
else
try
let rec scan = function
h::t -> if h#data#is_boundary then h else scan t
| [] -> raise Not_found
in
scan ancs
with Not_found ->
WARN_MSG "boundary not found in [%s] node=\"%s\""
(Xlist.to_string (fun x -> x#data#to_string) "; " ancs) nd#data#to_string;
raise Not_found
method nearest_common_ancestor ?(closed=false) nds =
let get_ancestors n =
let base = self#initial_ancestor_nodes n in
if closed then
base @ [n]
else
base
in
let rec intersect a = function
h1::t1, h2::t2 ->
if h1 == h2 then
intersect (h1::a) (t1, t2)
else
List.rev a
| _, [] | [], _ -> List.rev a
in
let common = ref [] in
begin
match nds with
h::t ->
common := (get_ancestors h);
List.iter
(fun nd ->
common := intersect [] (!common, get_ancestors nd)
) t
| [] -> ()
end;
try
Xlist.last !common, List.length !common
with
Failure _ ->
BEGIN_DEBUG
let nds_to_str nds = (String.concat ", " (List.map (fun n -> GI.to_string n#gindex) nds)) in
DEBUG_MSG "nearest_common_ancestor of [%s]\n" (nds_to_str nds);
List.iter
(fun n ->
DEBUG_MSG " initial ancestor of %a: [%s]\n"
GI.ps n#gindex (nds_to_str (self#initial_ancestor_nodes n))
) nds
END_DEBUG;
raise (Failure "Sourcecode.Tree.c#nearest_common_ancestor")
method private _get_origin row revidx =
let get i =
try
List.nth row i
with
Failure _ ->
ERROR_MSG "_get_origin.get: index out of bounds: i=%d row=%s"
i (Xlist.to_string (fun x -> x) ", " row);
exit 1
in
let origin = get 1 in
let ending = get 2 in
if (int_of_string origin) <= revidx && revidx <= (int_of_string ending) then
let len = List.length row in
let gid = ref (int_of_string(get 0)) in (* initial gid *)
let n = len - 2 in
for i = 10 to n do
if i mod 2 = 0 then
let ri = int_of_string(get i) in
let gi = int_of_string(get (i + 1)) in
if revidx >= ri then
gid := gi
done;
(!gid, origin, ending)
else
raise Not_found
method dump_origin bufsize nctms_file revidx origin_file ending_file =
DEBUG_MSG "bufsize=%d" bufsize;
let revidx_s = string_of_int revidx in
let csv = Csv.load nctms_file in
let csv =
match csv with
[] -> []
| _::tl -> tl
in
List.iter
(fun row ->
let row_s = (Xlist.to_string (fun x -> x) ", " row) in
DEBUG_MSG "dump_origin: row=(%s)" row_s;
try
let (gid, origin, ending) = self#_get_origin row revidx in
let nd = self#search_node_by_gindex gid in
nd#data#set_origin origin;
nd#data#set_ending ending
with
| Not_found -> ()
| Failure _ -> raise (Malformed_row row_s)
) csv;
let buf = new Origin.abuf bufsize in
let buf_ending = new Origin.abuf bufsize in
let nunknown_origin = ref 0 in
let nunknown_ending = ref 0 in
let nds_tbl = Hashtbl.create 0 in
let nds_tbl_ending = Hashtbl.create 0 in
self#preorder_scan_whole_initial
(fun nd ->
if nd != self#root then begin
let ndat = nd#data in
if ndat#origin = unknown_origin then begin
incr nunknown_origin;
ndat#set_origin revidx_s
end;
if ndat#ending = unknown_origin then begin
incr nunknown_ending;
ndat#set_ending revidx_s
end;
let ogn = ndat#origin in
let edg = ndat#ending in
let latest_ending = options#latest_target in
let ogn_cond = revidx_s = ogn && (ogn <> edg || ogn = latest_ending) in
let edg_cond = revidx_s = edg && (ogn <> edg || edg = earliest_origin) in
if ogn_cond || edg_cond then begin
let ancestors = (* rightmost is the parent *)
(self#initial_ancestor_nodes nd)
in
let ancestors = (* remove the root *)
if List.length ancestors > 0 then List.tl ancestors else []
in
if ogn_cond then begin
try
List.iter
(fun a ->
if a#data#origin = ogn
then begin
try
let nds = Hashtbl.find nds_tbl a in
Hashtbl.replace nds_tbl a (nd::nds);
raise Found
with
Not_found ->
Hashtbl.add nds_tbl a [nd; a];
raise Found
end
) ancestors;
Hashtbl.add nds_tbl nd [nd]
with
Found -> ()
end;
if edg_cond then begin
try
List.iter
(fun a ->
if a#data#ending = edg
then begin
try
let nds = Hashtbl.find nds_tbl_ending a in
Hashtbl.replace nds_tbl_ending a (nd::nds);
raise Found
with
Not_found ->
Hashtbl.add nds_tbl_ending a [nd; a];
raise Found
end
) ancestors;
Hashtbl.add nds_tbl_ending nd [nd]
with
Found -> ()
end
end;
let loc = ndat#src_loc in
let st = loc.Loc.start_offset in
let ed = loc.Loc.end_offset in
if st >= 0 && ed >= 0 then begin
let range = Origin.create_range (int_of_origin ogn) st ed in
buf#put range;
let range_ending = Origin.create_range (int_of_origin edg) st ed in
buf_ending#put range_ending
end
end
);
let sz = self#size in
let nknown_origin = sz - !nunknown_origin in
let cov = float(nknown_origin) *. 100.0 /. float(sz) in
let nknown_ending = sz - !nunknown_ending in
let cov_ending = float(nknown_ending) *. 100.0 /. float(sz) in
Xprint.message "coverage (origin): %d/%d (%f%%)" nknown_origin sz cov;
Hashtbl.iter
(fun nd nds ->
Xprint.message "size of fragment: (gid:%a, origin:%s) -> %d"
GI.ps nd#gindex nd#data#origin (List.length nds)
) nds_tbl;
buf#dump origin_file;
Xprint.message "coverage (ending): %d/%d (%f%%)" nknown_ending sz cov_ending;
Hashtbl.iter
(fun nd nds ->
Xprint.message "size of fragment: (gid:%a, ending:%s) -> %d"
GI.ps nd#gindex nd#data#ending (List.length nds)
) nds_tbl_ending;
buf_ending#dump ending_file;
(sz, nknown_origin, cov, nds_tbl, nknown_ending, cov_ending, nds_tbl_ending)
(* end of method dump_origin *)
method align_fragments (gmap : (int * int) list) (tree : 'self) =
let gmap_tbl = Hashtbl.create (List.length gmap) in
List.iter (fun (i, j) -> Hashtbl.replace gmap_tbl i j) gmap;
let nds_tbl1 = Hashtbl.create 0 in
let nds_tbl2 = Hashtbl.create 0 in
let check_mapping nd' a =
try
let ai' = Hashtbl.find gmap_tbl a#gindex in
let a' = tree#search_node_by_gindex ai' in
let b = List.memq a' (tree#initial_ancestor_nodes nd') in
if b then begin
try
let nds' = Hashtbl.find nds_tbl2 a' in
Hashtbl.replace nds_tbl2 a' (nd'::nds')
with Not_found ->
Hashtbl.add nds_tbl2 a' [nd'; a']
end;
b
with
Not_found -> false
in
self#preorder_scan_whole_initial
(fun nd ->
if nd != self#root then begin
try
let ni' = Hashtbl.find gmap_tbl nd#gindex in
let nd' = tree#search_node_by_gindex ni' in
let ancestors = (* rightmost is the parent *)
(self#initial_ancestor_nodes nd)
in
let ancestors = (* remove the root *)
if List.length ancestors > 0 then List.tl ancestors else []
in
begin
try
List.iter
(fun a ->
if check_mapping nd' a
then begin
try
let nds = Hashtbl.find nds_tbl1 a in
Hashtbl.replace nds_tbl1 a (nd::nds);
raise Found
with
Not_found ->
Hashtbl.add nds_tbl1 a [nd; a];
raise Found
end
) ancestors;
Hashtbl.add nds_tbl1 nd [nd];
Hashtbl.add nds_tbl2 nd' [nd'];
with
Found -> ()
end
with Not_found -> ()
end
);
Hashtbl.iter
(fun nd nds ->
try
let ni' = Hashtbl.find gmap_tbl nd#gindex in
let nd' = tree#search_node_by_gindex ni' in
let nds' = Hashtbl.find nds_tbl2 nd' in
let loc = nd#data#src_loc in
let loc' = nd'#data#src_loc in
Printf.printf "%a <%s> (%s) (%d lines %d nodes) --- %a <%s> (%s) (%d lines %d nodes)\n"
GI.p nd#gindex nd#data#label (Loc.to_string loc) (Loc.lines loc) (List.length nds)
GI.p nd'#gindex nd'#data#label (Loc.to_string loc') (Loc.lines loc') (List.length nds')
with Not_found -> ()
) nds_tbl1
method find_nodes_by_line_range (start_line, end_line) =
let res = ref [] in
self#preorder_scan_whole_initial
(fun nd ->
let loc = nd#data#src_loc in
if start_line <= loc.Loc.start_line && loc.Loc.end_line <= end_line then
res := nd::!res
);
if !res = [] then
WARN_MSG "no nodes found: %d-%d" start_line end_line;
!res
method find_nodes_by_line_col_range ((start_line, start_col), (end_line, end_col)) =
let res = ref [] in
self#preorder_scan_whole_initial
(fun nd ->
let loc = nd#data#src_loc in
if
( (start_line = loc.Loc.start_line && start_col <= loc.Loc.start_char)
|| start_line < loc.Loc.start_line )
&&
( (loc.Loc.end_line = end_line && loc.Loc.end_char <= end_col)
|| loc.Loc.end_line < end_line )
then
res := nd::!res
);
if !res = [] then
WARN_MSG "no nodes found: %d-%d" start_line end_line;
!res
(* for searchast *)
val mutable token_array = [||]
val mutable node_array = [||]
method find_token_node i =
try
node_array.(i)
with
Invalid_argument _ ->
WARN_MSG "not found \"%d\"" i;
raise Not_found
method to_token_array =
if token_array = [||] then
let l = ref [] in
let ndl = ref [] in
self#preorder_scan_whole_initial
(fun nd ->
if nd#data#not_frommacro then begin
l := nd#data#to_short_string :: !l;
ndl := nd :: !ndl
end
);
let a = Array.of_list(List.rev !l) in
let nda = Array.of_list(List.rev !ndl) in
token_array <- a;
node_array <- nda;
a
else
token_array
val mutable node_array_pat = [||]
method find_token_node_pat i =
try
node_array_pat.(i)
with
Invalid_argument _ ->
WARN_MSG "not found \"%d\"" i;
raise Not_found
method get_token_array_pat (frag : GIDfragment.c) =
let l = ref [] in
let ndl = ref [] in
self#preorder_scan_whole_initial
(fun nd ->
if frag#contains nd#gindex && nd#data#not_frommacro then begin
l := nd#data#to_short_string :: !l;
ndl := nd :: !ndl
end
);
node_array_pat <- Array.of_list(List.rev !ndl);
Array.of_list(List.rev !l)
method private compute_continuity matched = (* assumes sorted *)
let total_gap =
let rec scan a = function
i0::i1::t -> scan ((i1 - i0 - 1) + a) (i1::t)
| [_] -> a
| [] -> 0
in
scan 0 matched
in
let range =
match matched with
i0::i1::t -> (Xlist.last (i1::t)) - i0 + 1
| [_] -> 1
| [] -> 0
in
let continuity = (float (range - total_gap)) /. (float range) in
DEBUG_MSG "continuity=%f (tgap=%d,range=%d)\n" continuity total_gap range;
continuity
method match_token_array_pat_ch cache_path frag_src pat gindextok_array ch =
let re = Str.regexp "^\\([0-9]+\\):\\(.+\\)" in
let gid_array = Array.make (Array.length gindextok_array) (-1) in
let tokpat =
Array.mapi
(fun i gidtok ->
if Str.string_match re gidtok 0 then
let gid_s = Str.matched_group 1 gidtok in
let tok = Str.matched_group 2 gidtok in
gid_array.(i) <- int_of_string gid_s;
tok
else begin
ERROR_MSG "illegal token cache format: \"%s\"" gidtok;
exit 1
end
) gindextok_array
in
let getgid i = gid_array.(i) in
let patfrag = new GIDfragment.c in
let _ = patfrag#set_rep pat in
let pathash = (encoded_digest_of_file options frag_src) ^ ":" ^ patfrag#hash in
let gmap_path = mkgmapfilepath ~gmap_ext:options#gmap_ext cache_path patfrag in
try
self#_match_token_array_pat_ch tokpat pathash getgid gmap_path ch
with
exn ->
WARN_MSG "caught \"%s\"" (Printexc.to_string exn)
method show_node_array_pat = (* for debug *)
Printf.printf "node_array_pat:\n";
Array.iter
(fun nd ->
Printf.printf "%a [%s] (%s)\n" GI.p nd#gindex nd#data#label (Loc.to_string nd#data#src_loc)
) node_array_pat;
method match_pat_ch cache_path (pat_tree : 'self) tokpat patfrag ch =
BEGIN_DEBUG
Printf.printf "PAT:\n";
pat_tree#show_node_array_pat
END_DEBUG;
let getgid i = (pat_tree#find_token_node_pat i)#gindex in
let gmap_path = mkgmapfilepath ~gmap_ext:options#gmap_ext cache_path patfrag in
let pathash = pat_tree#encoded_source_digest ^ ":" ^ patfrag#hash in
try
self#_match_token_array_pat_ch tokpat pathash getgid gmap_path ch
with
exn ->
WARN_MSG "caught \"%s\"" (Printexc.to_string exn)
method private _match_token_array_pat_ch tokpat pathash getgid gmap_path ch =
let tokpat_len = Array.length tokpat in
let a = self#to_token_array in
let n , st_pos , ed_pos , _ , _ = LCS.lcs a tokpat in
let exact_matches, relabels, _, _ = Adiff.adiff a tokpat in
let matches = exact_matches in
(* let matches = exact_matches @ relabels in *)
let matched, _ = List.split matches in
let relabeled, _ = List.split relabels in
let matched = List.fast_sort Stdlib.compare matched in
let gaps =
let rec loop a = function
| i0::i1::t -> loop ((i1 - i0 - 1)::a) (i1::t)
| [i] -> List.rev a
| [] -> []
in
loop [] matched
in
let matched_nds = List.map self#find_token_node matched in
let relabeled_nds = List.map self#find_token_node relabeled in
let gap_tbl = Hashtbl.create 0 in
let index_tbl = Hashtbl.create 0 in
let count = ref 0 in
List.iter
(fun nd ->
try
Hashtbl.replace index_tbl nd (List.nth matched !count);
Hashtbl.replace gap_tbl nd (List.nth gaps !count);
incr count
with _ -> ()
) matched_nds;
BEGIN_DEBUG
DEBUG_MSG "%d matched nodes (gindex):\n" (List.length matched_nds);
List.iter
(fun n ->
DEBUG_MSG "%a [%s](%s)\n" GI.ps n#gindex n#data#label (Loc.to_string n#data#src_loc)
) matched_nds
END_DEBUG;
compute size - threshold ratio ( STR )
let rec scan segs cur_seg = function
n0::(n1::t as rest) -> begin
if self#cross_boundary n0 n1 then
scan ((n0::cur_seg)::segs) [] rest
else
scan segs (n0::cur_seg) rest
end
| [n] -> (List.rev (List.map List.rev ((n::cur_seg)::segs)))
| [] -> []
in
let segs = scan [] [] m in
let nsegs = in
let sizes = List.map (fun seg -> List.length seg) segs in
let locs = List.map merge_locs segs in
(*
let sum_size =
List.fold_left
(fun s sz ->
s + sz
) 0 sizes
in
*)
let rels = List.map (fun seg -> List.filter (fun n -> List.memq n relabeled_nds) seg) segs in
(*
let ave_size = (float sum_size) /. (float nsegs) in
*)
let ranges =
let get_range seg =
let last = List.hd (List.rev seg) in
let first = List.hd seg in
try
(Hashtbl.find index_tbl last) - (Hashtbl.find index_tbl first) + 1
with
Not_found ->
ERROR_MSG "not found: gid:%a or gid:%a" GI.ps first#gindex GI.ps last#gindex;
exit 1
in
List.map get_range segs
in
let gap_sizes =
List.map
(fun seg ->
List.fold_left
(fun s n ->
try
s + try Hashtbl.find gap_tbl n with _ -> 0
with
Not_found ->
ERROR_MSG "not found: \"%s\"" n#to_string;
exit 1
) 0 (List.rev(List.tl(List.rev seg)))
) segs
in
let rates =
List.map2
(fun sz (g, r) ->
(float sz) /. (float options#size_threshold) *. (float (r - g)) /. (float r)
) sizes (List.combine gap_sizes ranges) in
let rec combine4 = function
h1::t1, h2::t2, h3::t3, h4::t4 -> (h1, h2, h3, h4)::combine4(t1, t2, t3, t4)
| [], [], [], [] -> []
| _ -> raise (Invalid_argument "combine4")
in
BEGIN_DEBUG
for i = 0 to (List.length segs) - 1 do
DEBUG_MSG "size=%d(nrels=%d,tgap=%d,range=%d) [%f] %s\n"
(List.nth sizes i)
(List.length (List.nth rels i))
(List.nth gap_sizes i)
(List.nth ranges i)
(List.nth rates i)
(Loc.to_string (List.nth locs i))
done
END_DEBUG;
let final_rates = ref [] in
let final_locs = ref [] in
let final_matched_nds = ref [] in
let final_relabeled_nds = ref [] in
List.iter
(fun (seg, rate, loc, rel) ->
if rate >= options#str_threshold then begin
final_matched_nds := !final_matched_nds @ seg;
final_rates := rate::!final_rates;
final_locs := loc::!final_locs;
final_relabeled_nds := !final_relabeled_nds @ rel
end
) (combine4(segs, rates, locs, rels));
let nmatches = List.length !final_matched_nds in
let nrelabels = List.length !final_relabeled_nds in
let sim = (float nmatches) /. (float tokpat_len) in
let str =
let sum = List.fold_left (fun s r -> s +. r) 0.0 !final_rates in
if sum > 0.0 then
sum /. (float (List.length !final_rates))
else
0.0
in
nmatches,
nrelabels,
sim,
str,
(String.concat "|" (List.map Loc.to_string !final_locs)),
!final_matched_nds,
!final_relabeled_nds
in (* end of func scan_matched *)
let nmats, nrels, sim, str, loc, matched_nodes, relabeled_nodes =
if (List.length matched) = 0 then
0, 0, 0.0, 0.0, "???", [], []
else
scan_matched matched_nds
in
DEBUG_MSG "loc=%s" loc;
: exact match - match ratio
let renamed_nodes = List.filter (fun nd -> nd#data#is_named) relabeled_nodes in
let nrenamed = List.length renamed_nodes in
: weak
Printf.fprintf ch " similarity : ( % d/%d)=%f relabels:%d STR:%f EMR:%f WEMR:%f loc:%s pathash:%s\n "
nmats tokpat_len sim nrels str emr pathash ;
Printf.fprintf ch "similarity: (%d/%d)=%f relabels:%d STR:%f EMR:%f WEMR:%f loc:%s pathash:%s\n"
nmats tokpat_len sim nrels str emr wemr loc pathash;
*)
(* secondary matching *)
if nmats > 0 then begin
let ca, d = self#nearest_common_ancestor matched_nodes in
let nearest_boundary_opt =
try
Some (self#get_nearest_boundary ca)
with Not_found -> None
in
if ca != self#root && nearest_boundary_opt <> None then begin
let nearest_boundary =
match nearest_boundary_opt with Some nb -> nb | None -> assert false
in
DEBUG_MSG "%s (%s)\n"
nearest_boundary#data#label
(Loc.to_string nearest_boundary#data#src_loc);
let src_frag = new GIDfragment.c in
let rep =
sprintf "%a-%a"
GI.rs (self#initial_leftmost nearest_boundary)#gindex GI.rs nearest_boundary#gindex
in
src_frag#set_rep rep;
let src_token_array = self#get_token_array_pat src_frag in
let exact_matches2, relabels2, _, _ = Adiff.adiff src_token_array tokpat in
let matches2 = exact_matches2 @ relabels2 in
let nmats2 = List.length matches2 in
let sim2 = (float nmats2) /. (float tokpat_len) in
let nrels2 = List.length relabels2 in
let matched2, _ = List.split matches2 in
let matched2 = List.fast_sort Stdlib.compare matched2 in
let continuity = self#compute_continuity matched2 in
let matched_nds2 = List.map self#find_token_node_pat matched2 in
let loc2 = merge_locs matched_nds2 in
DEBUG_MSG "loc2=%s" (Loc.to_string loc2);
let relabeled2, _ = List.split relabels2 in
let relabeled_nds2 = List.map self#find_token_node_pat relabeled2 in
let renamed_nds2 = List.filter (fun nd -> nd#data#is_named) relabeled_nds2 in
let nrenamed2 = List.length renamed_nds2 in
BEGIN_DEBUG
DEBUG_MSG "%d matched nodes (2) (gindex):\n" (List.length matched_nds2);
List.iter
(fun n ->
DEBUG_MSG "%a [%s](%s)\n" GI.ps n#gindex n#data#label (Loc.to_string n#data#src_loc)
) matched_nds2;
DEBUG_MSG "%d relabeled nodes (2) (gindex):\n" (List.length relabeled_nds2);
List.iter
(fun n ->
Printf.printf "%a [%s](%s)\n" GI.p n#gindex n#data#label (Loc.to_string n#data#src_loc)
) relabeled_nds2
END_DEBUG;
let emr2 = (float nmats2) /. (float (nmats2 + nrels2)) in
let wemr2 = (float nmats2) /. (float (nmats2 + nrenamed2)) in
let str2 = (float nmats2) /. (float options#size_threshold) in
if (List.length exact_matches2) > nmats && continuity >= options#continuity_threshold then begin
let _ =
if sim2 >= options#sim_threshold then
let gmap =
List.map
(fun (i, j) ->
((self#find_token_node_pat i)#gindex, (getgid j))
) matches2
in
dump_gmap gmap gmap_path
in
Printf.fprintf ch "similarity: (%d/%d)=%f relabels:%d STR:%f EMR:%f WEMR:%f loc:%s pathash:%s\n"
nmats2 tokpat_len sim2 nrels2 str2 emr2 wemr2 (Loc.to_string loc2) pathash;
end
else
Printf.fprintf ch "similarity: (0/%d)=0.0 relabels:%d STR:0.0 EMR:0.0 WEMR:0.0 loc:WITHDRAWN pathash:%s\n"
tokpat_len nrels2 pathash
end
else
let matched =
List.fast_sort Stdlib.compare (List.map (fun n -> Hashtbl.find index_tbl n) matched_nodes)
in
let c = self#compute_continuity matched in
if c >= options#continuity_threshold then begin
let _ =
if sim >= options#sim_threshold then
let matches =
let ms = List.map (fun n -> Hashtbl.find index_tbl n) matched_nodes in
List.filter (fun (i, _) -> List.mem i ms) matches
in
let gmap =
List.map
(fun (i, j) ->
((self#find_token_node i)#gindex, (getgid j))
) matches
in
dump_gmap gmap gmap_path
in
Printf.fprintf ch "similarity: (%d/%d)=%f relabels:%d STR:%f EMR:%f WEMR:%f loc:%s pathash:%s\n"
nmats tokpat_len sim nrels str emr wemr loc pathash
end
else
Printf.fprintf ch "similarity: (0/%d)=0.0 relabels:%d STR:0.0 EMR:0.0 WEMR:0.0 loc:WITHDRAWN pathash:%s\n"
tokpat_len nrels pathash
end
else
let loc = if (List.length matches) > 0 then "CUTOFF" else "-" in
Printf.fprintf ch "similarity: (0/%d)=0.0 relabels:%d STR:0.0 EMR:0.0 WEMR:0.0 loc:%s pathash:%s\n"
tokpat_len nrels loc pathash
end of method _ match_token_array_pat_ch
method match_pats cache_path ofile pat_tree patfrags =
Xfile.dump ofile
(fun ch ->
List.iter
(fun p ->
let tokpat = pat_tree#get_token_array_pat p in
self#match_pat_ch cache_path pat_tree tokpat p ch
) patfrags)
method find_label (root : 'node) (nd : 'node) =
let labs = ref [] in
let lab = get_lab nd in
self#scan_whole_initial_subtree root
(fun n ->
if lab = get_lab n then
labs := n :: !labs
);
!labs
method dump_subtree_for_delta_ch
(root : node_t)
(except : node_t list)
(ch : Xchannel.out_channel)
=
let fprintf = Xchannel.fprintf in
let attrs_to_string attrs =
String.concat ""
(List.map
(fun (a, v) ->
sprintf " %s=\"%s\"" a v
) attrs)
in
let rec doit nd =
if not (List.memq nd except) then
let name, attrs, _ = nd#data#orig_to_elem_data_for_delta in
if nd#is_leaf then begin
fprintf ch "<%s%s/>" name (attrs_to_string attrs)
end
else begin
fprintf ch "<%s%s>" name (attrs_to_string attrs);
Array.iter doit nd#initial_children;
fprintf ch "</%s>" name
end
in
doit root
of class . Tree.c
module PxpD = Pxp_document
exception Ignore
let attrs_of_anodes anodes =
List.fold_left
(fun l anode ->
match anode#node_type with
| PxpD.T_attribute name -> l @ [name, anode#data]
| _ -> assert false
) [] anodes
let xnode_to_string = Delta_base.xnode_to_string
let of_xnode
?(tree_creator=fun options nd -> new c options nd true)
(options : #Parser_options.c)
(xnode : SB.xnode_t)
=
let rec scan_xnode xnode =
match xnode#node_type with
| PxpD.T_element name ->
if name = Delta_base.text_tag then begin
failwith (sprintf "illegal node: %s" (xnode_to_string xnode))
end
else begin
let children = scan_xnodes xnode#sub_nodes in
let anodes = xnode#attributes_as_nodes in
let attrs = attrs_of_anodes anodes in
(*
let nchildren = List.length children in
if nchildren > 0 then L.add_collapse_target name;
*)
let nd = mknode options (of_elem_data name attrs) children in
nd
end
| t -> begin
Xprint.warning "ignored: %s" (XML.node_type_to_string xnode#node_type);
raise Ignore
end
and scan_xnodes xnodes =
List.fold_right
(fun n l -> try (scan_xnode n)::l with Ignore -> l) xnodes []
in
let nd = scan_xnode xnode in
let tree = tree_creator options nd in
tree
end of func . Tree.node_of_xnode
of functor . Tree
let scan_ancestors ?(moveon=fun x -> true) nd f =
try
let cur = ref nd in
while (moveon !cur) do
cur := (!cur)#initial_parent;
f !cur
done
with
Otreediff.Otree.Parent_not_found _ -> ()
let find_nearest_p_ancestor_node pred nd =
let rec scan n =
try
let pn = n#initial_parent in
if pred pn then
pn
else
scan pn
with
Otreediff.Otree.Parent_not_found _ -> raise Not_found
in
let a = scan nd in
DEBUG_MSG "%a --> %a" UID.ps nd#uid UID.ps a#uid;
a
let find_nearest_mapped_ancestor_node is_mapped nd =
let rec scan n =
try
let pn = n#initial_parent in
if is_mapped pn#uid then
pn
else
scan pn
with
Otreediff.Otree.Parent_not_found _ -> raise Not_found
in
let a = scan nd in
DEBUG_MSG "%a --> %a" UID.ps nd#uid UID.ps a#uid;
a
let scan_descendants ?(moveon=fun _ -> true) nd f =
let rec scan nd =
f nd;
if moveon nd then begin
Array.iter scan nd#initial_children
end
in
if moveon nd then
Array.iter scan nd#initial_children
let find_nearest_mapped_descendant_nodes is_mapped node =
let rec get nd =
List.flatten
(List.map
(fun n ->
if is_mapped n#uid then
[n]
else
get n
) (Array.to_list nd#initial_children))
in
get node
type frame =
{ f_scope_node : Spec.node_t;
f_table : (name, Spec.node_t) Hashtbl.t;
}
exception Found of Spec.node_t
class stack = object (self)
val _global_tbl = Hashtbl.create 0
val _stack = Stack.create()
method push nd (* scope creating node *) =
let frm = { f_scope_node=nd; f_table = Hashtbl.create 0 } in
Stack.push frm _stack
method pop = ignore (Stack.pop _stack)
method register_global name decl_node =
DEBUG_MSG "registering global \"%s\"" name;
Hashtbl.replace _global_tbl name decl_node
method register name decl_node =
DEBUG_MSG "registering \"%s\"" name;
let frm = Stack.top _stack in
Hashtbl.replace frm.f_table name decl_node
method lookup name =
try
Stack.iter
(fun frm ->
if Hashtbl.mem frm.f_table name then
raise (Found (Hashtbl.find frm.f_table name))
) _stack;
Hashtbl.find _global_tbl name
with
Found n -> n
end (* of class Tree.stack *)
class visitor tree = object (self)
method scanner_body_before_subscan (nd : Spec.node_t) = ()
method scanner_body_after_subscan (nd : Spec.node_t) = ()
method scan nd =
self#scanner_body_before_subscan nd;
Array.iter self#scan nd#initial_children;
self#scanner_body_after_subscan nd
method visit_all =
self#scan tree#root
end
| null | https://raw.githubusercontent.com/codinuum/cca/3d97b64a5c23ff97c08455ac604ccb9fed471d91/src/ast/analyzing/common/sourcecode.ml | ocaml | sourcecode.ml
handling logical ordinal of a child
method _more_anonymized_label = Obj.repr (L.anonymize ~more:true lab)
_label = ndat#_label && self#orig_lab_opt = ndat#orig_lab_opt
self#orig_to_elem_data_for_eq = x#orig_to_elem_data_for_eq
for searchast
of class Sourcecode.node_data
Printf.printf "! [before] initial_size=%d (initial_only=%B)\n"
self#initial_size initial_only;
if (Array.length nd#initial_children) <> (Array.length c) then begin
Printf.printf "!!! %s\n" nd#initial_to_string;
Printf.printf "!!! [%s] -> [%s]\n"
(Xarray.to_string (fun n -> UID.to_string n#uid) ";" nd#initial_children)
(Xarray.to_string (fun n -> UID.to_string n#uid) ";" c)
end;
;
Printf.printf "! [after] initial_size=%d\n" self#initial_size
val mutable line_terminator = ""
method set_line_terminator s = line_terminator <- s
method line_terminator = line_terminator
method line_terminator_name =
match line_terminator with
"\013\010" -> "CRLF"
| "\013" -> "CR"
| "\010" -> "LF"
| _ -> "??"
initial gid
rightmost is the parent
remove the root
end of method dump_origin
rightmost is the parent
remove the root
for searchast
assumes sorted
for debug
let matches = exact_matches @ relabels in
let sum_size =
List.fold_left
(fun s sz ->
s + sz
) 0 sizes
in
let ave_size = (float sum_size) /. (float nsegs) in
end of func scan_matched
secondary matching
let nchildren = List.length children in
if nchildren > 0 then L.add_collapse_target name;
scope creating node
of class Tree.stack |
Copyright 2012 - 2022 Codinuum Software Lab < >
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyright 2012-2022 Codinuum Software Lab <>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
open Otreediff
module GI = GIndex
module MID = Moveid
module C = Compression
module SB = Spec_base
let sprintf = Printf.sprintf
type name = string
let n_lines_for_file_check = 32
let bison_pat = Str.regexp "#define[ \t]+YYBISON[ \t]+1"
let flex_pat = Str.regexp "#define[ \t]+FLEX_SCANNER"
let search_pat pats file =
let b = ref false in
let ch = file#get_channel in
begin
try
for i = 1 to n_lines_for_file_check do
let s = ch#input_line() in
try
List.iter
(fun pat ->
let _ = (Str.search_forward pat s 0) in
b := true;
raise Exit
) pats
with
Not_found -> ()
done
with
| End_of_file -> ()
| Exit -> ()
end;
ch#close_in();
!b
let is_generated f = search_pat [bison_pat;flex_pat] f
let unknown_origin = "-1"
let earliest_origin = "0"
let dump_gmap_ch gmap ch =
List.iter (fun (gi1, gi2) -> Printf.fprintf ch "%d - %d\n" gi1 gi2) gmap
let mkgmapfilepath ?(gmap_ext=".gmap") cache_path frag =
Filename.concat cache_path (frag#hash ^ gmap_ext)
let dump_gmap gmap fpath =
let d = Filename.dirname fpath in
if not (Xfile.dir_exists d) then begin
Xfile.mkdir d
end;
Xfile.dump fpath (dump_gmap_ch gmap)
let load_gmap_ch ch =
let l = ref [] in
try
while true do
let s = input_line ch in
Scanf.sscanf s "%d - %d" (fun i j -> l := (i, j)::!l)
done;
[]
with
End_of_file -> List.rev !l
let load_gmap fpath =
DEBUG_MSG "fpath=\"%s\"" fpath;
try
Xfile.load fpath load_gmap_ch
with
Failure _ -> []
let digest_of_file options file =
DEBUG_MSG "file=\"%s\"" file;
Xhash.digest_of_file options#hash_algo file
let encode_digest options d =
(Xhash.algo_to_string options#fact_algo)^Entity.sub_sep^(Xhash.to_hex d)
let encoded_digest_of_file options file =
let d = digest_of_file options file in
encode_digest options d
let int_of_origin ogn =
if ogn = unknown_origin then
Origin.attr_unknown
else begin
try
int_of_string ogn
with
Invalid_argument s -> ERROR_MSG "int_of_origin: %s" s; exit 1
end
let merge_locs nds =
let lmerge loc1 loc2 =
if loc1 = Loc.dummy then loc2
else if loc2 = Loc.dummy then loc1
else Loc.merge loc1 loc2
in
List.fold_left (fun l n -> lmerge l n#data#src_loc) Loc.dummy nds
let is_ghost_node nd = nd#data#src_loc = Loc.ghost
let dec_attrs = List.map (fun (a, v) -> a, (XML._decode_string v))
module Tree (L : Spec.LABEL_T) = struct
let of_elem_data name attrs =
let lname = XML.get_local_part name in
let lattrs = List.map (fun (a, v) -> XML.get_local_part a, v) attrs in
L.of_elem_data lname lattrs ""
let compare_node nd1 nd2 = compare nd1#data#label nd2#data#label
exception Found
exception Malformed_row of string
let get_lab nd = (Obj.obj nd#data#_label : L.t)
let get_orig_lab_opt nd =
match nd#data#orig_lab_opt with
| Some o -> Some (Obj.obj o : L.t)
| None -> None
let get_annotation nd = (Obj.obj nd#data#_annotation : L.annotation)
val mutable ordinal_list = l
method get_ordinal nth =
let rec doit i a = function
| [] -> raise Not_found
| h::t ->
let ah = a + h in
if a <= nth && nth < ah then
i
else
doit (i+1) ah t
in
doit 0 0 ordinal_list
method list = ordinal_list
method add_list l =
ordinal_list <- ordinal_list @ l
method to_string =
"["^(Xlist.to_string string_of_int ";" ordinal_list)^"]"
end
let null_ordinal_tbl = new ordinal_tbl []
class node_data
options
?(annot=L.null_annotation)
?(ordinal_tbl_opt=(None : ordinal_tbl option))
?(orig_lab_opt=(None : L.t option))
(lab : L.t)
=
let is_named = L.is_named lab in
let is_named_orig = L.is_named_orig lab in
let category = L.get_category lab in
object (self : 'self)
inherit Otree.data2
constraint 'node = 'self Otree.node2
val mutable prefix = ""
method set_prefix s = prefix <- s
method get_prefix = prefix
val mutable suffix = ""
method set_suffix s = suffix <- s
method get_suffix = suffix
val mutable _eq = fun _ -> false
val mutable source_fid = ""
method set_source_fid x = source_fid <- x
method source_fid = source_fid
method get_ordinal nth =
match ordinal_tbl_opt with
| None -> nth
| Some tbl -> tbl#get_ordinal nth
method add_to_ordinal_list l =
match ordinal_tbl_opt with
| None -> failwith "Sourcecode.node_data#add_to_ordinal_list"
| Some tbl -> tbl#add_list l
val mutable lab = lab
val mutable orig_lab_opt = orig_lab_opt
val mutable _label = Obj.repr ()
method _label = _label
val mutable label = ""
method label = label
val mutable rep = ""
method to_rep = rep
val mutable short_string = ""
method to_short_string = short_string
val mutable _digest = None
method _digest = _digest
val mutable digest = None
method digest = digest
method private update =
label <- L.to_string lab;
_label <- Obj.repr lab;
let ignore_identifiers_flag = options#ignore_identifiers_flag in
let short_str = L.to_short_string ~ignore_identifiers_flag lab in
rep <- short_str;
short_string <- short_str;
match _digest with
| Some d -> rep <- String.concat "" [rep;"<";d;">"]
| None -> ()
method elem_name_for_delta =
let n, _, _ = self#to_elem_data_for_delta in
n
method orig_elem_name_for_delta =
let n, _, _ = self#orig_to_elem_data_for_delta in
n
method elem_attrs_for_delta =
let _, attrs, _ = self#to_elem_data_for_delta in
attrs
method orig_elem_attrs_for_delta =
let _, attrs, _ = self#orig_to_elem_data_for_delta in
attrs
method change_attr (attr : string) (v : string) =
let name, attrs, _ = self#orig_to_elem_data_for_delta in
if List.mem_assoc attr attrs then begin
let attrs' = dec_attrs (List.remove_assoc attr attrs) in
let lab' = of_elem_data name ((attr, v)::attrs') in
DEBUG_MSG "%s -> %s" (L.to_string lab) (L.to_string lab');
orig_lab_opt <- Some lab';
DEBUG_MSG "%s" self#to_string
self#update
end
method delete_attr (attr : string) =
let name, attrs, _ = self#orig_to_elem_data_for_delta in
let attrs' = dec_attrs (List.remove_assoc attr attrs) in
orig_lab_opt <- Some (of_elem_data name attrs');
self#update
method insert_attr (attr : string) (v : string) =
let name, attrs, _ = self#orig_to_elem_data_for_delta in
let attrs' = dec_attrs (List.remove_assoc attr attrs) in
orig_lab_opt <- Some (of_elem_data name ((attr, v)::attrs'));
self#update
val successors = (Xset.create 0 : 'node Xset.t)
method successors = successors
method add_successor nd = Xset.add successors nd
val mutable binding = Binding.NoBinding
method binding = binding
method set_binding b = binding <- b
val mutable bindings = []
method bindings = bindings
method add_binding (b : Binding.t) =
if not (List.mem b bindings) then
bindings <- b :: bindings
method get_ident_use = L.get_ident_use lab
val mutable origin = unknown_origin
method origin = origin
method set_origin o = origin <- o
val mutable ending = unknown_origin
method ending = ending
method set_ending e = ending <- e
val mutable frommacro = ""
method frommacro = frommacro
method set_frommacro fm = frommacro <- fm
method is_frommacro = frommacro <> ""
method not_frommacro = frommacro = ""
val _annotation = Obj.repr annot
method _annotation = _annotation
method quasi_eq (ndat : 'self) =
L.quasi_eq lab (Obj.obj ndat#_label : L.t)
method relabel_allowed (ndat : 'self) =
L.relabel_allowed (lab, (Obj.obj ndat#_label : L.t))
method is_compatible_with ?(weak=false) (ndat : 'self) =
L.is_compatible ~weak lab (Obj.obj ndat#_label : L.t) ||
match orig_lab_opt, ndat#orig_lab_opt with
| Some l1, Some o2 -> L.is_compatible ~weak l1 (Obj.obj o2)
| _ -> false
method is_order_insensitive = L.is_order_insensitive lab
method move_disallowed = L.move_disallowed lab
method is_common = L.is_common lab
method _anonymized_label = Obj.repr (L.anonymize lab)
val mutable anonymized_label = None
method anonymized_label =
match anonymized_label with
| None ->
let alab = L.to_string (L.anonymize lab) in
anonymized_label <- Some alab;
alab
| Some alab -> alab
val mutable more_anonymized_label = None
method more_anonymized_label =
match more_anonymized_label with
| None ->
let alab = L.to_string (L.anonymize ~more:true lab) in
more_anonymized_label <- Some alab;
alab
| Some alab -> alab
val mutable anonymized2_label = None
method _anonymized2_label = Obj.repr (L.anonymize2 lab)
method anonymized2_label =
match anonymized2_label with
| None ->
let alab = L.to_string (L.anonymize2 lab) in
anonymized2_label <- Some alab;
alab
| Some alab -> alab
val mutable anonymized3_label = None
method _anonymized3_label = Obj.repr (L.anonymize3 lab)
method anonymized3_label =
match anonymized3_label with
| None ->
let alab = L.to_string (L.anonymize3 lab) in
anonymized3_label <- Some alab;
alab
| Some alab -> alab
method to_simple_string = L.to_simple_string lab
method _set_digest d =
_digest <- Some d;
let ignore_identifiers_flag = options#ignore_identifiers_flag in
rep <- String.concat ""
[L.to_short_string ~ignore_identifiers_flag lab;"<";d;">"]
method set_digest d =
digest <- Some d;
self#_set_digest d
method reset_digest = digest <- None
method to_be_notified = L.is_to_be_notified lab
method is_boundary = L.is_boundary lab
method is_partition = L.is_partition lab
method is_sequence = L.is_sequence lab
method is_phantom = L.is_phantom lab
method is_special = L.is_special lab
method to_elem_data = L.to_elem_data self#src_loc lab
method to_elem_data_for_delta = L.to_elem_data ~strip:true ?afilt:None self#src_loc lab
method orig_to_elem_data_for_delta =
let lab_ =
match orig_lab_opt with
| Some l -> l
| None -> lab
in
L.to_elem_data ~strip:true ?afilt:None self#src_loc lab_
method orig_to_elem_data_for_eq =
let lab_ =
match orig_lab_opt with
| Some l -> l
| None -> lab
in
let afilt a = not (Xstring.startswith a "___") in
L.to_elem_data ~strip:true ~afilt self#src_loc lab_
method eq ndat = _eq ndat
method subtree_equals ndat =
self#eq ndat && _digest = ndat#_digest && _digest <> None
method equals ndat = self#eq ndat && digest = ndat#digest
val mutable src_loc = Loc.dummy
method set_loc loc = src_loc <- loc
method src_loc = src_loc
method to_string =
sprintf "%s%s[%s]"
self#label
(match orig_lab_opt with Some l -> "("^(L.to_string l)^")" | None -> "")
(Loc.to_string src_loc)
method is_named = is_named
method is_named_orig = is_named_orig
method is_anonymous = not is_named
method is_anonymous_orig = not is_named_orig
method feature =
if self#is_named then
self#_label, None
else
self#_label, self#digest
method get_category = category
method get_name = L.get_name lab
method get_orig_name =
match orig_lab_opt with
| Some o -> L.get_name o
| None -> self#get_name
method get_value = L.get_value lab
method has_value = L.has_value lab
method has_non_trivial_value = L.has_non_trivial_value lab
method is_string_literal = L.is_string_literal lab
method is_int_literal = L.is_int_literal lab
method is_real_literal = L.is_real_literal lab
method is_statement = L.is_statement lab
method is_op = L.is_op lab
val mutable move_id = MID.unknown
method set_mid mid = move_id <- mid
method mid = move_id
method orig_lab_opt =
match orig_lab_opt with
| Some l -> Some (Obj.repr l)
| None -> None
initializer
_eq <-
if options#weak_eq_flag then
(fun x ->
_label = x#_label && self#orig_lab_opt = x#orig_lab_opt ||
(not self#is_named_orig) && (not self#has_value) &&
(not x#is_named_orig) && (not x#has_value) &&
self#elem_name_for_delta = x#elem_name_for_delta ||
(match self#orig_lab_opt, x#orig_lab_opt with
| Some o1, Some o2 -> o1 = o2
| Some o1, None -> L.is_compatible ~weak:true (Obj.obj o1) (Obj.obj x#_label)
| None, Some o2 -> L.is_compatible ~weak:true (Obj.obj _label) (Obj.obj o2)
| _ -> false) ||
self#is_compatible_with ~weak:true x)
else
self#update
val mutable char = None
method char =
if char = None then begin
let c = L.to_char lab in
char <- Some c;
c
end
else
match char with
| Some c -> c
| _ -> assert false
let mknode options
?(annot=L.null_annotation)
?(ordinal_tbl_opt=None)
?(orig_lab_opt=None)
lab nodes
=
Otree.create_node2 options#uid_generator
(new node_data options ~annot ~ordinal_tbl_opt ~orig_lab_opt lab) (Array.of_list nodes)
let mklnode options ?(annot=L.null_annotation) ?(orig_lab_opt=None) lab nodes =
mknode options ~annot ~ordinal_tbl_opt:(Some null_ordinal_tbl) ~orig_lab_opt lab nodes
let mkleaf options ?(annot=L.null_annotation) ?(orig_lab_opt=None) lab =
Otree.create_node2 options#uid_generator
(new node_data options ~annot ~orig_lab_opt lab) [||]
let _get_logical_nth_child nd nth =
let l = ref [] in
Array.iteri
(fun i x ->
if (nd#data#get_ordinal i) = nth then
l := x :: !l
) nd#children;
Array.of_list (List.rev !l)
let get_logical_nth_child nd nth =
let l = ref [] in
Array.iteri
(fun i x ->
if (nd#data#get_ordinal i) = nth then
l := x :: !l
) nd#initial_children;
Array.of_list (List.rev !l)
class node_maker options = object (self)
method private mknode
?(annot=L.null_annotation)
?(ordinal_tbl_opt=None)
?(orig_lab_opt=None)
lab nodes
=
mknode options ~annot ~ordinal_tbl_opt ~orig_lab_opt lab nodes
method private mklnode ?(annot=L.null_annotation) ?(orig_lab_opt=None) lab nodes =
mklnode options ~annot ~orig_lab_opt lab nodes
method private mkleaf ?(annot=L.null_annotation) ?(orig_lab_opt=None) lab =
mkleaf options ~annot ~orig_lab_opt lab
end
type node_t = Spec.node_t
let make_unparser unparse node ch =
let redirect = not (SB.OutChannel.is_stdout ch) in
if redirect then begin
try
Format.set_formatter_out_channel (SB.OutChannel.to_pervasives ch)
with
_ ->
let xc = SB.OutChannel.to_xchannel ch in
let out s pos len = ignore (xc#output_ s pos len) in
let flush () = xc#close in
Format.set_formatter_output_functions out flush
end;
unparse node;
if redirect then begin
Format.set_formatter_out_channel Stdlib.stdout
end
class c options (root : node_t) (is_whole : bool) = object (self : 'self)
inherit node_maker options
inherit [ node_t ] Otree.otree2 root is_whole as super
method private create root is_whole =
let t = new c options root is_whole in
t#setup_initial_children;
t
method extra_namespaces = ([] : (string * string) list)
method unparse_subtree_ch :
?no_boxing:bool -> ?no_header:bool -> ?fail_on_error:bool -> node_t -> SB.OutChannel.t -> unit =
fun ?(no_boxing=false) ?(no_header=false) ?(fail_on_error=true) _ _ ->
failwith "Sourcecode.unparse_subtree_ch: unparser is not implemented yet"
method unparse_ch ?(no_boxing=false) ?(no_header=false) ?(fail_on_error=true) =
self#unparse_subtree_ch ~no_boxing ~no_header ~fail_on_error root
method get_digest nd =
let st = self#create nd false in
let d = st#digest in
nd#data#_set_digest d;
d
val mutable true_parent_tbl = (Hashtbl.create 0 : (UID.t, node_t) Hashtbl.t)
method set_true_parent_tbl tbl = true_parent_tbl <- tbl
method find_true_parent uid =
Hashtbl.find true_parent_tbl uid
val mutable true_children_tbl = (Hashtbl.create 0 : (node_t, node_t array) Hashtbl.t)
method set_true_children_tbl tbl = true_children_tbl <- tbl
method recover_true_children ~initial_only () =
DEBUG_MSG "initial_only=%B" initial_only;
let modified = ref false in
Hashtbl.iter
(fun nd c ->
DEBUG_MSG "recovering true children: %a -> [%s]"
UID.ps nd#uid (Xarray.to_string (fun n -> UID.to_string n#uid) ";" c);
nd#set_initial_children c;
if not initial_only then
nd#set_children c;
Array.iteri
(fun i n ->
n#set_initial_parent nd;
n#set_initial_pos i;
if not initial_only then begin
n#set_parent nd;
n#set_pos i
end
) c;
modified := true
) true_children_tbl;
BEGIN_DEBUG
Hashtbl.iter
(fun uid nd ->
DEBUG_MSG "true parent: %a -> %a" UID.ps uid UID.ps nd#uid
) true_parent_tbl
END_DEBUG;
if !modified then begin
self#fast_scan_whole_initial (fun nd -> nd#set_gindex GI.unknown);
self#setup_initial_size;
self#setup_gindex_table;
self#setup_initial_leftmost_table;
self#setup_apath
val mutable source_path = "unknown"
method set_source_path p = source_path <- p
method source_path = source_path
val mutable source_fullpath = "unknown"
method set_source_fullpath p = source_fullpath <- p
method source_fullpath = source_fullpath
val mutable source_kind = Storage.kind_dummy
method set_source_kind k = source_kind <- k
method source_kind = source_kind
val mutable vkind = Entity.V_UNKNOWN
method set_vkind k = vkind <- k
method vkind = vkind
val mutable version = ""
method set_version n = version <- n
method version = version
val mutable proj_root = ""
method set_proj_root r = proj_root <- r
method proj_root = proj_root
val mutable source_digest = "unknown"
method set_source_digest d = source_digest <- d
method source_digest = source_digest
method encoded_source_digest = encode_digest options source_digest
method set_source_info (file : Storage.file) =
self#set_source_path file#path;
self#set_source_fullpath file#fullpath;
self#set_source_kind file#kind;
self#set_source_digest file#digest
val mutable parser_name = "unknown"
method set_parser_name n = parser_name <- n
method parser_name = parser_name
method private get_attrs =
let attrs_to_string attrs =
String.concat "" (List.map (fun (a, v) -> sprintf " %s='%s'" a v) attrs)
in
let lang_attr =
try
["xmlns:"^L.lang_prefix, List.assoc L.lang_prefix Astml.parser_tbl;]
with
Not_found -> []
in
let l =
lang_attr @
[ "xmlns:"^Astml.default_prefix, Astml.ast_ns;
Astml.parser_attr_name, self#parser_name;
Astml.source_attr_name, Filename.basename self#source_path;
Astml.source_digest_attr_name, self#encoded_source_digest;
]
in
attrs_to_string l
method dump_astml ?(comp=C.none) fname =
let pre_tags = sprintf "<%s%s>" Astml.astml_tag self#get_attrs in
let post_tags = sprintf "</%s>" Astml.astml_tag in
super#save_in_xml ~initial:true ~comp ~pre_tags ~post_tags fname
method collapse =
let filt nd =
let lab = get_lab nd in
if L.forced_to_be_collapsible lab then
nd#set_collapsible;
L.is_collapse_target options lab
in
self#collapse_nodes filt
subtree copy ( gindexes are inherited )
method make_subtree_copy ?(find_hook=fun _ -> raise Not_found) (nd : node_t) =
let hooked = ref [] in
let rec doit nd =
let gi = nd#gindex in
if GI.is_valid gi then
let children = Xlist.filter_map doit (Array.to_list nd#initial_children) in
let lab = get_lab nd in
let orig_lab_opt = get_orig_lab_opt nd in
let new_nd = self#mknode ~orig_lab_opt lab children in
new_nd#set_gindex gi;
begin
try
let a = find_hook nd in
hooked := (new_nd, a) :: !hooked
with
Not_found -> ()
end;
Some new_nd
else
None
in
let root =
match doit nd with
| Some r -> r
| None -> raise (Invalid_argument "Sourcecode.c#make_subtree_copy")
in
let tree = self#create root false in
tree#_register_gindexes;
List.iter
(fun (n, a) ->
a n
) !hooked;
tree
subtree copy ( gindexes are inherited )
method private make_anonymizedx_subtree_copy anonymize ?(uids_left_named=[]) (nd : node_t) =
let rec doit n =
let gi = n#gindex in
if GI.is_valid gi then
let children = Xlist.filter_map doit (Array.to_list n#initial_children) in
let alab =
if List.mem n#uid uids_left_named then
get_lab n
else
anonymize n
in
let new_nd = self#mknode alab children in
new_nd#set_gindex gi;
Some new_nd
else
None
in
let root =
match doit nd with
| Some r -> r
| None -> raise (Invalid_argument "Sourcecode.c#make_anonymized_subtree_copy")
in
let tree = self#create root false in
tree#_register_gindexes;
tree
method make_anonymized_subtree_copy ?(uids_left_named=[]) (nd : node_t) =
let anonymize n = (Obj.obj n#data#_anonymized_label : L.t) in
self#make_anonymizedx_subtree_copy anonymize ~uids_left_named nd
method make_anonymized2_subtree_copy ?(uids_left_named=[]) (nd : node_t) =
let anonymize n = (Obj.obj n#data#_anonymized2_label : L.t) in
self#make_anonymizedx_subtree_copy anonymize ~uids_left_named nd
method make_anonymized3_subtree_copy ?(uids_left_named=[]) (nd : node_t) =
let anonymize n = (Obj.obj n#data#_anonymized3_label : L.t) in
self#make_anonymizedx_subtree_copy anonymize ~uids_left_named nd
method get_ident_use_list gid =
let nd = self#search_node_by_gindex gid in
let res = ref [] in
self#preorder_scan_whole_initial_subtree nd
(fun n ->
let s = n#data#get_ident_use in
if not (List.mem s !res) && s <> "" then
res := s::!res
);
List.rev !res
method initial_subtree_to_rep nd =
let buf = Buffer.create 0 in
self#scan_whole_initial_subtree nd
(fun n ->
Buffer.add_string buf n#to_rep
);
Buffer.contents buf
method initial_to_rep = self#initial_subtree_to_rep root
method subtree_to_simple_string gid =
let nd = self#search_node_by_gindex gid in
let children = Array.to_list nd#initial_children in
match children with
| [] -> nd#data#to_simple_string
| _ ->
sprintf "%s(%s)"
nd#data#to_simple_string
(String.concat ","
(List.map
(fun nd -> self#subtree_to_simple_string nd#gindex)
children
)
)
method dump_line_ranges fpath =
let ch = open_out fpath in
self#fast_scan_whole_initial
(fun nd ->
Printf.fprintf ch "%d-%d\n"
nd#data#src_loc.Loc.start_line nd#data#src_loc.Loc.end_line
)
val mutable ignored_regions = ([] : (int * int) list)
method set_ignored_regions r = ignored_regions <- r
method ignored_regions = ignored_regions
val mutable misparsed_regions = ([] : (int * int) list)
method set_misparsed_regions r = misparsed_regions <- r
method misparsed_regions = misparsed_regions
val mutable total_LOC = 0
method set_total_LOC n = total_LOC <- n
method total_LOC = total_LOC
val mutable misparsed_LOC = 0
method set_misparsed_LOC n = misparsed_LOC <- n
method misparsed_LOC = misparsed_LOC
method get_units_to_be_notified =
let res = ref [] in
self#fast_scan_whole_initial
(fun nd ->
if nd#data#to_be_notified then
res := nd::!res
);
!res
method get_nearest_containing_unit uid =
let nd = self#search_node_by_uid uid in
let ancs = List.rev (self#initial_ancestor_nodes nd) in
if nd#data#to_be_notified then
nd
else
let rec scan = function
h::t -> if h#data#to_be_notified then h else scan t
| [] -> raise Not_found
in
scan ancs
method make_subtree_from_node nd =
let tree = self#create nd false in
tree#_set_gindex_table gindex_table;
tree#_set_initial_leftmost_table initial_leftmost_table;
tree
method make_subtree_from_uid uid =
let nd = self#search_node_by_uid uid in
self#make_subtree_from_node nd
method make_subtree_from_path path =
let nd = self#initial_acc path in
self#make_subtree_from_node nd
method label_match kw =
let re = Str.regexp (".*"^kw^".*") in
try
self#fast_scan_whole_initial
(fun nd ->
if Str.string_match re nd#data#label 0 then begin
Xprint.verbose options#verbose_flag "keyword=\"%s\" matched=%s" kw nd#data#to_string;
raise Found
end
);
false
with
Found -> true
method merge_locs_adjusting_to_boundary gids =
BEGIN_DEBUG
DEBUG_MSG "tree size: %d" self#size;
List.iter
(fun gid ->
if gid >= self#size then begin
WARN_MSG "invalid gid: %a" GI.ps gid;
exit 1
end
) gids
END_DEBUG;
let groups = ref [] in
let nds = List.map self#search_node_by_gindex gids in
let rec scan = function
| [] -> ()
| nd0::rest ->
let group = ref [nd0] in
List.iter
(fun nd ->
if not (self#cross_boundary nd0 nd) then
group := nd::!group
) rest;
groups := !group::!groups
in
scan nds;
let max_group = ref [] in
let max = ref 0 in
List.iter
(fun g ->
if (List.length g) > !max then begin
max_group := g;
max := List.length g
end
) !groups;
merge_locs !max_group
method private cross_boundary nd1 nd2 =
let ands1 = List.filter (fun n -> n#data#not_frommacro) (self#initial_ancestor_nodes nd1) in
let ands2 = List.filter (fun n -> n#data#not_frommacro) (self#initial_ancestor_nodes nd2) in
let rec scan b = function
| h1::t1, h2::t2 ->
if h1 == h2 then
scan false (t1, t2)
else
scan (b || h1#data#is_boundary || h2#data#is_boundary) (t1, t2)
| [], rest | rest, [] ->
if b then
true
else
let rec restscan = function
h::t ->
if h#data#is_boundary then
true
else
restscan t
| [] -> false
in
restscan rest
in
scan false (ands1, ands2)
method get_nearest_boundary nd =
let ancs = List.rev (self#initial_ancestor_nodes nd) in
if nd#data#is_boundary then
nd
else
try
let rec scan = function
h::t -> if h#data#is_boundary then h else scan t
| [] -> raise Not_found
in
scan ancs
with Not_found ->
WARN_MSG "boundary not found in [%s] node=\"%s\""
(Xlist.to_string (fun x -> x#data#to_string) "; " ancs) nd#data#to_string;
raise Not_found
method nearest_common_ancestor ?(closed=false) nds =
let get_ancestors n =
let base = self#initial_ancestor_nodes n in
if closed then
base @ [n]
else
base
in
let rec intersect a = function
h1::t1, h2::t2 ->
if h1 == h2 then
intersect (h1::a) (t1, t2)
else
List.rev a
| _, [] | [], _ -> List.rev a
in
let common = ref [] in
begin
match nds with
h::t ->
common := (get_ancestors h);
List.iter
(fun nd ->
common := intersect [] (!common, get_ancestors nd)
) t
| [] -> ()
end;
try
Xlist.last !common, List.length !common
with
Failure _ ->
BEGIN_DEBUG
let nds_to_str nds = (String.concat ", " (List.map (fun n -> GI.to_string n#gindex) nds)) in
DEBUG_MSG "nearest_common_ancestor of [%s]\n" (nds_to_str nds);
List.iter
(fun n ->
DEBUG_MSG " initial ancestor of %a: [%s]\n"
GI.ps n#gindex (nds_to_str (self#initial_ancestor_nodes n))
) nds
END_DEBUG;
raise (Failure "Sourcecode.Tree.c#nearest_common_ancestor")
method private _get_origin row revidx =
let get i =
try
List.nth row i
with
Failure _ ->
ERROR_MSG "_get_origin.get: index out of bounds: i=%d row=%s"
i (Xlist.to_string (fun x -> x) ", " row);
exit 1
in
let origin = get 1 in
let ending = get 2 in
if (int_of_string origin) <= revidx && revidx <= (int_of_string ending) then
let len = List.length row in
let n = len - 2 in
for i = 10 to n do
if i mod 2 = 0 then
let ri = int_of_string(get i) in
let gi = int_of_string(get (i + 1)) in
if revidx >= ri then
gid := gi
done;
(!gid, origin, ending)
else
raise Not_found
method dump_origin bufsize nctms_file revidx origin_file ending_file =
DEBUG_MSG "bufsize=%d" bufsize;
let revidx_s = string_of_int revidx in
let csv = Csv.load nctms_file in
let csv =
match csv with
[] -> []
| _::tl -> tl
in
List.iter
(fun row ->
let row_s = (Xlist.to_string (fun x -> x) ", " row) in
DEBUG_MSG "dump_origin: row=(%s)" row_s;
try
let (gid, origin, ending) = self#_get_origin row revidx in
let nd = self#search_node_by_gindex gid in
nd#data#set_origin origin;
nd#data#set_ending ending
with
| Not_found -> ()
| Failure _ -> raise (Malformed_row row_s)
) csv;
let buf = new Origin.abuf bufsize in
let buf_ending = new Origin.abuf bufsize in
let nunknown_origin = ref 0 in
let nunknown_ending = ref 0 in
let nds_tbl = Hashtbl.create 0 in
let nds_tbl_ending = Hashtbl.create 0 in
self#preorder_scan_whole_initial
(fun nd ->
if nd != self#root then begin
let ndat = nd#data in
if ndat#origin = unknown_origin then begin
incr nunknown_origin;
ndat#set_origin revidx_s
end;
if ndat#ending = unknown_origin then begin
incr nunknown_ending;
ndat#set_ending revidx_s
end;
let ogn = ndat#origin in
let edg = ndat#ending in
let latest_ending = options#latest_target in
let ogn_cond = revidx_s = ogn && (ogn <> edg || ogn = latest_ending) in
let edg_cond = revidx_s = edg && (ogn <> edg || edg = earliest_origin) in
if ogn_cond || edg_cond then begin
(self#initial_ancestor_nodes nd)
in
if List.length ancestors > 0 then List.tl ancestors else []
in
if ogn_cond then begin
try
List.iter
(fun a ->
if a#data#origin = ogn
then begin
try
let nds = Hashtbl.find nds_tbl a in
Hashtbl.replace nds_tbl a (nd::nds);
raise Found
with
Not_found ->
Hashtbl.add nds_tbl a [nd; a];
raise Found
end
) ancestors;
Hashtbl.add nds_tbl nd [nd]
with
Found -> ()
end;
if edg_cond then begin
try
List.iter
(fun a ->
if a#data#ending = edg
then begin
try
let nds = Hashtbl.find nds_tbl_ending a in
Hashtbl.replace nds_tbl_ending a (nd::nds);
raise Found
with
Not_found ->
Hashtbl.add nds_tbl_ending a [nd; a];
raise Found
end
) ancestors;
Hashtbl.add nds_tbl_ending nd [nd]
with
Found -> ()
end
end;
let loc = ndat#src_loc in
let st = loc.Loc.start_offset in
let ed = loc.Loc.end_offset in
if st >= 0 && ed >= 0 then begin
let range = Origin.create_range (int_of_origin ogn) st ed in
buf#put range;
let range_ending = Origin.create_range (int_of_origin edg) st ed in
buf_ending#put range_ending
end
end
);
let sz = self#size in
let nknown_origin = sz - !nunknown_origin in
let cov = float(nknown_origin) *. 100.0 /. float(sz) in
let nknown_ending = sz - !nunknown_ending in
let cov_ending = float(nknown_ending) *. 100.0 /. float(sz) in
Xprint.message "coverage (origin): %d/%d (%f%%)" nknown_origin sz cov;
Hashtbl.iter
(fun nd nds ->
Xprint.message "size of fragment: (gid:%a, origin:%s) -> %d"
GI.ps nd#gindex nd#data#origin (List.length nds)
) nds_tbl;
buf#dump origin_file;
Xprint.message "coverage (ending): %d/%d (%f%%)" nknown_ending sz cov_ending;
Hashtbl.iter
(fun nd nds ->
Xprint.message "size of fragment: (gid:%a, ending:%s) -> %d"
GI.ps nd#gindex nd#data#ending (List.length nds)
) nds_tbl_ending;
buf_ending#dump ending_file;
(sz, nknown_origin, cov, nds_tbl, nknown_ending, cov_ending, nds_tbl_ending)
method align_fragments (gmap : (int * int) list) (tree : 'self) =
let gmap_tbl = Hashtbl.create (List.length gmap) in
List.iter (fun (i, j) -> Hashtbl.replace gmap_tbl i j) gmap;
let nds_tbl1 = Hashtbl.create 0 in
let nds_tbl2 = Hashtbl.create 0 in
let check_mapping nd' a =
try
let ai' = Hashtbl.find gmap_tbl a#gindex in
let a' = tree#search_node_by_gindex ai' in
let b = List.memq a' (tree#initial_ancestor_nodes nd') in
if b then begin
try
let nds' = Hashtbl.find nds_tbl2 a' in
Hashtbl.replace nds_tbl2 a' (nd'::nds')
with Not_found ->
Hashtbl.add nds_tbl2 a' [nd'; a']
end;
b
with
Not_found -> false
in
self#preorder_scan_whole_initial
(fun nd ->
if nd != self#root then begin
try
let ni' = Hashtbl.find gmap_tbl nd#gindex in
let nd' = tree#search_node_by_gindex ni' in
(self#initial_ancestor_nodes nd)
in
if List.length ancestors > 0 then List.tl ancestors else []
in
begin
try
List.iter
(fun a ->
if check_mapping nd' a
then begin
try
let nds = Hashtbl.find nds_tbl1 a in
Hashtbl.replace nds_tbl1 a (nd::nds);
raise Found
with
Not_found ->
Hashtbl.add nds_tbl1 a [nd; a];
raise Found
end
) ancestors;
Hashtbl.add nds_tbl1 nd [nd];
Hashtbl.add nds_tbl2 nd' [nd'];
with
Found -> ()
end
with Not_found -> ()
end
);
Hashtbl.iter
(fun nd nds ->
try
let ni' = Hashtbl.find gmap_tbl nd#gindex in
let nd' = tree#search_node_by_gindex ni' in
let nds' = Hashtbl.find nds_tbl2 nd' in
let loc = nd#data#src_loc in
let loc' = nd'#data#src_loc in
Printf.printf "%a <%s> (%s) (%d lines %d nodes) --- %a <%s> (%s) (%d lines %d nodes)\n"
GI.p nd#gindex nd#data#label (Loc.to_string loc) (Loc.lines loc) (List.length nds)
GI.p nd'#gindex nd'#data#label (Loc.to_string loc') (Loc.lines loc') (List.length nds')
with Not_found -> ()
) nds_tbl1
method find_nodes_by_line_range (start_line, end_line) =
let res = ref [] in
self#preorder_scan_whole_initial
(fun nd ->
let loc = nd#data#src_loc in
if start_line <= loc.Loc.start_line && loc.Loc.end_line <= end_line then
res := nd::!res
);
if !res = [] then
WARN_MSG "no nodes found: %d-%d" start_line end_line;
!res
method find_nodes_by_line_col_range ((start_line, start_col), (end_line, end_col)) =
let res = ref [] in
self#preorder_scan_whole_initial
(fun nd ->
let loc = nd#data#src_loc in
if
( (start_line = loc.Loc.start_line && start_col <= loc.Loc.start_char)
|| start_line < loc.Loc.start_line )
&&
( (loc.Loc.end_line = end_line && loc.Loc.end_char <= end_col)
|| loc.Loc.end_line < end_line )
then
res := nd::!res
);
if !res = [] then
WARN_MSG "no nodes found: %d-%d" start_line end_line;
!res
val mutable token_array = [||]
val mutable node_array = [||]
method find_token_node i =
try
node_array.(i)
with
Invalid_argument _ ->
WARN_MSG "not found \"%d\"" i;
raise Not_found
method to_token_array =
if token_array = [||] then
let l = ref [] in
let ndl = ref [] in
self#preorder_scan_whole_initial
(fun nd ->
if nd#data#not_frommacro then begin
l := nd#data#to_short_string :: !l;
ndl := nd :: !ndl
end
);
let a = Array.of_list(List.rev !l) in
let nda = Array.of_list(List.rev !ndl) in
token_array <- a;
node_array <- nda;
a
else
token_array
val mutable node_array_pat = [||]
method find_token_node_pat i =
try
node_array_pat.(i)
with
Invalid_argument _ ->
WARN_MSG "not found \"%d\"" i;
raise Not_found
method get_token_array_pat (frag : GIDfragment.c) =
let l = ref [] in
let ndl = ref [] in
self#preorder_scan_whole_initial
(fun nd ->
if frag#contains nd#gindex && nd#data#not_frommacro then begin
l := nd#data#to_short_string :: !l;
ndl := nd :: !ndl
end
);
node_array_pat <- Array.of_list(List.rev !ndl);
Array.of_list(List.rev !l)
let total_gap =
let rec scan a = function
i0::i1::t -> scan ((i1 - i0 - 1) + a) (i1::t)
| [_] -> a
| [] -> 0
in
scan 0 matched
in
let range =
match matched with
i0::i1::t -> (Xlist.last (i1::t)) - i0 + 1
| [_] -> 1
| [] -> 0
in
let continuity = (float (range - total_gap)) /. (float range) in
DEBUG_MSG "continuity=%f (tgap=%d,range=%d)\n" continuity total_gap range;
continuity
method match_token_array_pat_ch cache_path frag_src pat gindextok_array ch =
let re = Str.regexp "^\\([0-9]+\\):\\(.+\\)" in
let gid_array = Array.make (Array.length gindextok_array) (-1) in
let tokpat =
Array.mapi
(fun i gidtok ->
if Str.string_match re gidtok 0 then
let gid_s = Str.matched_group 1 gidtok in
let tok = Str.matched_group 2 gidtok in
gid_array.(i) <- int_of_string gid_s;
tok
else begin
ERROR_MSG "illegal token cache format: \"%s\"" gidtok;
exit 1
end
) gindextok_array
in
let getgid i = gid_array.(i) in
let patfrag = new GIDfragment.c in
let _ = patfrag#set_rep pat in
let pathash = (encoded_digest_of_file options frag_src) ^ ":" ^ patfrag#hash in
let gmap_path = mkgmapfilepath ~gmap_ext:options#gmap_ext cache_path patfrag in
try
self#_match_token_array_pat_ch tokpat pathash getgid gmap_path ch
with
exn ->
WARN_MSG "caught \"%s\"" (Printexc.to_string exn)
Printf.printf "node_array_pat:\n";
Array.iter
(fun nd ->
Printf.printf "%a [%s] (%s)\n" GI.p nd#gindex nd#data#label (Loc.to_string nd#data#src_loc)
) node_array_pat;
method match_pat_ch cache_path (pat_tree : 'self) tokpat patfrag ch =
BEGIN_DEBUG
Printf.printf "PAT:\n";
pat_tree#show_node_array_pat
END_DEBUG;
let getgid i = (pat_tree#find_token_node_pat i)#gindex in
let gmap_path = mkgmapfilepath ~gmap_ext:options#gmap_ext cache_path patfrag in
let pathash = pat_tree#encoded_source_digest ^ ":" ^ patfrag#hash in
try
self#_match_token_array_pat_ch tokpat pathash getgid gmap_path ch
with
exn ->
WARN_MSG "caught \"%s\"" (Printexc.to_string exn)
method private _match_token_array_pat_ch tokpat pathash getgid gmap_path ch =
let tokpat_len = Array.length tokpat in
let a = self#to_token_array in
let n , st_pos , ed_pos , _ , _ = LCS.lcs a tokpat in
let exact_matches, relabels, _, _ = Adiff.adiff a tokpat in
let matches = exact_matches in
let matched, _ = List.split matches in
let relabeled, _ = List.split relabels in
let matched = List.fast_sort Stdlib.compare matched in
let gaps =
let rec loop a = function
| i0::i1::t -> loop ((i1 - i0 - 1)::a) (i1::t)
| [i] -> List.rev a
| [] -> []
in
loop [] matched
in
let matched_nds = List.map self#find_token_node matched in
let relabeled_nds = List.map self#find_token_node relabeled in
let gap_tbl = Hashtbl.create 0 in
let index_tbl = Hashtbl.create 0 in
let count = ref 0 in
List.iter
(fun nd ->
try
Hashtbl.replace index_tbl nd (List.nth matched !count);
Hashtbl.replace gap_tbl nd (List.nth gaps !count);
incr count
with _ -> ()
) matched_nds;
BEGIN_DEBUG
DEBUG_MSG "%d matched nodes (gindex):\n" (List.length matched_nds);
List.iter
(fun n ->
DEBUG_MSG "%a [%s](%s)\n" GI.ps n#gindex n#data#label (Loc.to_string n#data#src_loc)
) matched_nds
END_DEBUG;
compute size - threshold ratio ( STR )
let rec scan segs cur_seg = function
n0::(n1::t as rest) -> begin
if self#cross_boundary n0 n1 then
scan ((n0::cur_seg)::segs) [] rest
else
scan segs (n0::cur_seg) rest
end
| [n] -> (List.rev (List.map List.rev ((n::cur_seg)::segs)))
| [] -> []
in
let segs = scan [] [] m in
let nsegs = in
let sizes = List.map (fun seg -> List.length seg) segs in
let locs = List.map merge_locs segs in
let rels = List.map (fun seg -> List.filter (fun n -> List.memq n relabeled_nds) seg) segs in
let ranges =
let get_range seg =
let last = List.hd (List.rev seg) in
let first = List.hd seg in
try
(Hashtbl.find index_tbl last) - (Hashtbl.find index_tbl first) + 1
with
Not_found ->
ERROR_MSG "not found: gid:%a or gid:%a" GI.ps first#gindex GI.ps last#gindex;
exit 1
in
List.map get_range segs
in
let gap_sizes =
List.map
(fun seg ->
List.fold_left
(fun s n ->
try
s + try Hashtbl.find gap_tbl n with _ -> 0
with
Not_found ->
ERROR_MSG "not found: \"%s\"" n#to_string;
exit 1
) 0 (List.rev(List.tl(List.rev seg)))
) segs
in
let rates =
List.map2
(fun sz (g, r) ->
(float sz) /. (float options#size_threshold) *. (float (r - g)) /. (float r)
) sizes (List.combine gap_sizes ranges) in
let rec combine4 = function
h1::t1, h2::t2, h3::t3, h4::t4 -> (h1, h2, h3, h4)::combine4(t1, t2, t3, t4)
| [], [], [], [] -> []
| _ -> raise (Invalid_argument "combine4")
in
BEGIN_DEBUG
for i = 0 to (List.length segs) - 1 do
DEBUG_MSG "size=%d(nrels=%d,tgap=%d,range=%d) [%f] %s\n"
(List.nth sizes i)
(List.length (List.nth rels i))
(List.nth gap_sizes i)
(List.nth ranges i)
(List.nth rates i)
(Loc.to_string (List.nth locs i))
done
END_DEBUG;
let final_rates = ref [] in
let final_locs = ref [] in
let final_matched_nds = ref [] in
let final_relabeled_nds = ref [] in
List.iter
(fun (seg, rate, loc, rel) ->
if rate >= options#str_threshold then begin
final_matched_nds := !final_matched_nds @ seg;
final_rates := rate::!final_rates;
final_locs := loc::!final_locs;
final_relabeled_nds := !final_relabeled_nds @ rel
end
) (combine4(segs, rates, locs, rels));
let nmatches = List.length !final_matched_nds in
let nrelabels = List.length !final_relabeled_nds in
let sim = (float nmatches) /. (float tokpat_len) in
let str =
let sum = List.fold_left (fun s r -> s +. r) 0.0 !final_rates in
if sum > 0.0 then
sum /. (float (List.length !final_rates))
else
0.0
in
nmatches,
nrelabels,
sim,
str,
(String.concat "|" (List.map Loc.to_string !final_locs)),
!final_matched_nds,
!final_relabeled_nds
let nmats, nrels, sim, str, loc, matched_nodes, relabeled_nodes =
if (List.length matched) = 0 then
0, 0, 0.0, 0.0, "???", [], []
else
scan_matched matched_nds
in
DEBUG_MSG "loc=%s" loc;
: exact match - match ratio
let renamed_nodes = List.filter (fun nd -> nd#data#is_named) relabeled_nodes in
let nrenamed = List.length renamed_nodes in
: weak
Printf.fprintf ch " similarity : ( % d/%d)=%f relabels:%d STR:%f EMR:%f WEMR:%f loc:%s pathash:%s\n "
nmats tokpat_len sim nrels str emr pathash ;
Printf.fprintf ch "similarity: (%d/%d)=%f relabels:%d STR:%f EMR:%f WEMR:%f loc:%s pathash:%s\n"
nmats tokpat_len sim nrels str emr wemr loc pathash;
*)
if nmats > 0 then begin
let ca, d = self#nearest_common_ancestor matched_nodes in
let nearest_boundary_opt =
try
Some (self#get_nearest_boundary ca)
with Not_found -> None
in
if ca != self#root && nearest_boundary_opt <> None then begin
let nearest_boundary =
match nearest_boundary_opt with Some nb -> nb | None -> assert false
in
DEBUG_MSG "%s (%s)\n"
nearest_boundary#data#label
(Loc.to_string nearest_boundary#data#src_loc);
let src_frag = new GIDfragment.c in
let rep =
sprintf "%a-%a"
GI.rs (self#initial_leftmost nearest_boundary)#gindex GI.rs nearest_boundary#gindex
in
src_frag#set_rep rep;
let src_token_array = self#get_token_array_pat src_frag in
let exact_matches2, relabels2, _, _ = Adiff.adiff src_token_array tokpat in
let matches2 = exact_matches2 @ relabels2 in
let nmats2 = List.length matches2 in
let sim2 = (float nmats2) /. (float tokpat_len) in
let nrels2 = List.length relabels2 in
let matched2, _ = List.split matches2 in
let matched2 = List.fast_sort Stdlib.compare matched2 in
let continuity = self#compute_continuity matched2 in
let matched_nds2 = List.map self#find_token_node_pat matched2 in
let loc2 = merge_locs matched_nds2 in
DEBUG_MSG "loc2=%s" (Loc.to_string loc2);
let relabeled2, _ = List.split relabels2 in
let relabeled_nds2 = List.map self#find_token_node_pat relabeled2 in
let renamed_nds2 = List.filter (fun nd -> nd#data#is_named) relabeled_nds2 in
let nrenamed2 = List.length renamed_nds2 in
BEGIN_DEBUG
DEBUG_MSG "%d matched nodes (2) (gindex):\n" (List.length matched_nds2);
List.iter
(fun n ->
DEBUG_MSG "%a [%s](%s)\n" GI.ps n#gindex n#data#label (Loc.to_string n#data#src_loc)
) matched_nds2;
DEBUG_MSG "%d relabeled nodes (2) (gindex):\n" (List.length relabeled_nds2);
List.iter
(fun n ->
Printf.printf "%a [%s](%s)\n" GI.p n#gindex n#data#label (Loc.to_string n#data#src_loc)
) relabeled_nds2
END_DEBUG;
let emr2 = (float nmats2) /. (float (nmats2 + nrels2)) in
let wemr2 = (float nmats2) /. (float (nmats2 + nrenamed2)) in
let str2 = (float nmats2) /. (float options#size_threshold) in
if (List.length exact_matches2) > nmats && continuity >= options#continuity_threshold then begin
let _ =
if sim2 >= options#sim_threshold then
let gmap =
List.map
(fun (i, j) ->
((self#find_token_node_pat i)#gindex, (getgid j))
) matches2
in
dump_gmap gmap gmap_path
in
Printf.fprintf ch "similarity: (%d/%d)=%f relabels:%d STR:%f EMR:%f WEMR:%f loc:%s pathash:%s\n"
nmats2 tokpat_len sim2 nrels2 str2 emr2 wemr2 (Loc.to_string loc2) pathash;
end
else
Printf.fprintf ch "similarity: (0/%d)=0.0 relabels:%d STR:0.0 EMR:0.0 WEMR:0.0 loc:WITHDRAWN pathash:%s\n"
tokpat_len nrels2 pathash
end
else
let matched =
List.fast_sort Stdlib.compare (List.map (fun n -> Hashtbl.find index_tbl n) matched_nodes)
in
let c = self#compute_continuity matched in
if c >= options#continuity_threshold then begin
let _ =
if sim >= options#sim_threshold then
let matches =
let ms = List.map (fun n -> Hashtbl.find index_tbl n) matched_nodes in
List.filter (fun (i, _) -> List.mem i ms) matches
in
let gmap =
List.map
(fun (i, j) ->
((self#find_token_node i)#gindex, (getgid j))
) matches
in
dump_gmap gmap gmap_path
in
Printf.fprintf ch "similarity: (%d/%d)=%f relabels:%d STR:%f EMR:%f WEMR:%f loc:%s pathash:%s\n"
nmats tokpat_len sim nrels str emr wemr loc pathash
end
else
Printf.fprintf ch "similarity: (0/%d)=0.0 relabels:%d STR:0.0 EMR:0.0 WEMR:0.0 loc:WITHDRAWN pathash:%s\n"
tokpat_len nrels pathash
end
else
let loc = if (List.length matches) > 0 then "CUTOFF" else "-" in
Printf.fprintf ch "similarity: (0/%d)=0.0 relabels:%d STR:0.0 EMR:0.0 WEMR:0.0 loc:%s pathash:%s\n"
tokpat_len nrels loc pathash
end of method _ match_token_array_pat_ch
method match_pats cache_path ofile pat_tree patfrags =
Xfile.dump ofile
(fun ch ->
List.iter
(fun p ->
let tokpat = pat_tree#get_token_array_pat p in
self#match_pat_ch cache_path pat_tree tokpat p ch
) patfrags)
method find_label (root : 'node) (nd : 'node) =
let labs = ref [] in
let lab = get_lab nd in
self#scan_whole_initial_subtree root
(fun n ->
if lab = get_lab n then
labs := n :: !labs
);
!labs
method dump_subtree_for_delta_ch
(root : node_t)
(except : node_t list)
(ch : Xchannel.out_channel)
=
let fprintf = Xchannel.fprintf in
let attrs_to_string attrs =
String.concat ""
(List.map
(fun (a, v) ->
sprintf " %s=\"%s\"" a v
) attrs)
in
let rec doit nd =
if not (List.memq nd except) then
let name, attrs, _ = nd#data#orig_to_elem_data_for_delta in
if nd#is_leaf then begin
fprintf ch "<%s%s/>" name (attrs_to_string attrs)
end
else begin
fprintf ch "<%s%s>" name (attrs_to_string attrs);
Array.iter doit nd#initial_children;
fprintf ch "</%s>" name
end
in
doit root
of class . Tree.c
module PxpD = Pxp_document
exception Ignore
let attrs_of_anodes anodes =
List.fold_left
(fun l anode ->
match anode#node_type with
| PxpD.T_attribute name -> l @ [name, anode#data]
| _ -> assert false
) [] anodes
let xnode_to_string = Delta_base.xnode_to_string
let of_xnode
?(tree_creator=fun options nd -> new c options nd true)
(options : #Parser_options.c)
(xnode : SB.xnode_t)
=
let rec scan_xnode xnode =
match xnode#node_type with
| PxpD.T_element name ->
if name = Delta_base.text_tag then begin
failwith (sprintf "illegal node: %s" (xnode_to_string xnode))
end
else begin
let children = scan_xnodes xnode#sub_nodes in
let anodes = xnode#attributes_as_nodes in
let attrs = attrs_of_anodes anodes in
let nd = mknode options (of_elem_data name attrs) children in
nd
end
| t -> begin
Xprint.warning "ignored: %s" (XML.node_type_to_string xnode#node_type);
raise Ignore
end
and scan_xnodes xnodes =
List.fold_right
(fun n l -> try (scan_xnode n)::l with Ignore -> l) xnodes []
in
let nd = scan_xnode xnode in
let tree = tree_creator options nd in
tree
end of func . Tree.node_of_xnode
of functor . Tree
let scan_ancestors ?(moveon=fun x -> true) nd f =
try
let cur = ref nd in
while (moveon !cur) do
cur := (!cur)#initial_parent;
f !cur
done
with
Otreediff.Otree.Parent_not_found _ -> ()
let find_nearest_p_ancestor_node pred nd =
let rec scan n =
try
let pn = n#initial_parent in
if pred pn then
pn
else
scan pn
with
Otreediff.Otree.Parent_not_found _ -> raise Not_found
in
let a = scan nd in
DEBUG_MSG "%a --> %a" UID.ps nd#uid UID.ps a#uid;
a
let find_nearest_mapped_ancestor_node is_mapped nd =
let rec scan n =
try
let pn = n#initial_parent in
if is_mapped pn#uid then
pn
else
scan pn
with
Otreediff.Otree.Parent_not_found _ -> raise Not_found
in
let a = scan nd in
DEBUG_MSG "%a --> %a" UID.ps nd#uid UID.ps a#uid;
a
let scan_descendants ?(moveon=fun _ -> true) nd f =
let rec scan nd =
f nd;
if moveon nd then begin
Array.iter scan nd#initial_children
end
in
if moveon nd then
Array.iter scan nd#initial_children
let find_nearest_mapped_descendant_nodes is_mapped node =
let rec get nd =
List.flatten
(List.map
(fun n ->
if is_mapped n#uid then
[n]
else
get n
) (Array.to_list nd#initial_children))
in
get node
type frame =
{ f_scope_node : Spec.node_t;
f_table : (name, Spec.node_t) Hashtbl.t;
}
exception Found of Spec.node_t
class stack = object (self)
val _global_tbl = Hashtbl.create 0
val _stack = Stack.create()
let frm = { f_scope_node=nd; f_table = Hashtbl.create 0 } in
Stack.push frm _stack
method pop = ignore (Stack.pop _stack)
method register_global name decl_node =
DEBUG_MSG "registering global \"%s\"" name;
Hashtbl.replace _global_tbl name decl_node
method register name decl_node =
DEBUG_MSG "registering \"%s\"" name;
let frm = Stack.top _stack in
Hashtbl.replace frm.f_table name decl_node
method lookup name =
try
Stack.iter
(fun frm ->
if Hashtbl.mem frm.f_table name then
raise (Found (Hashtbl.find frm.f_table name))
) _stack;
Hashtbl.find _global_tbl name
with
Found n -> n
class visitor tree = object (self)
method scanner_body_before_subscan (nd : Spec.node_t) = ()
method scanner_body_after_subscan (nd : Spec.node_t) = ()
method scan nd =
self#scanner_body_before_subscan nd;
Array.iter self#scan nd#initial_children;
self#scanner_body_after_subscan nd
method visit_all =
self#scan tree#root
end
|
1a89270aae163ab437e8a391eccce622e6bbe0d5b5aebeda8ea942a51f6b8479 | honix/Lire | text.lisp | ;;
;; Lire - text drawing
;;
(in-package :lire)
(defstruct text-texture
id width heigth)
(defparameter *text-hash* (make-hash-table :test #'equal))
(defun clean-text-hash ()
(labels ((delete-texture (key value)
(declare (ignore key))
(gl:delete-textures (list (text-texture-id value)))))
(maphash #'delete-texture *text-hash*)
(clrhash *text-hash*)))
(defun make-text (string)
(or (gethash string *text-hash*)
(let* ((font (sdl2-ttf:open-font "media/saxmono.ttf" 30))
(texture (car (gl:gen-textures 1)))
(surface (sdl2-ttf:render-utf8-blended
font string 255 255 255 0))
(surface-w (sdl2:surface-width surface))
(surface-h (sdl2:surface-height surface))
(surface-data (sdl2:surface-pixels surface)))
(gl:bind-texture :texture-2d texture)
(gl:tex-parameter :texture-2d :texture-min-filter :linear)
(gl:tex-parameter :texture-2d :texture-mag-filter :linear)
(gl:tex-image-2d :texture-2d 0 :rgba surface-w surface-h 0
:rgba :unsigned-byte surface-data)
(sdl2:free-surface surface)
(sdl2-ttf:close-font font)
(setf (gethash string *text-hash*)
(make-text-texture :id texture
:width (/ surface-w 30)
:heigth (/ surface-h 30 -1))))))
(defun text (string x y size rotation)
(let ((text-texture (make-text string)))
(with-slots (id width heigth) text-texture
(quad-textured id x y
rotation (* width size) (* heigth size -1)))))
(defun text-align (string x y size rotation)
(let ((text-texture (make-text string)))
(with-slots (id width heigth) text-texture
(quad-textured id (+ x (* width size)) y
rotation (* width size) (* heigth size -1)))))
| null | https://raw.githubusercontent.com/honix/Lire/36c18b8944919ef428ed856935746955a4cc38cc/text.lisp | lisp |
Lire - text drawing
|
(in-package :lire)
(defstruct text-texture
id width heigth)
(defparameter *text-hash* (make-hash-table :test #'equal))
(defun clean-text-hash ()
(labels ((delete-texture (key value)
(declare (ignore key))
(gl:delete-textures (list (text-texture-id value)))))
(maphash #'delete-texture *text-hash*)
(clrhash *text-hash*)))
(defun make-text (string)
(or (gethash string *text-hash*)
(let* ((font (sdl2-ttf:open-font "media/saxmono.ttf" 30))
(texture (car (gl:gen-textures 1)))
(surface (sdl2-ttf:render-utf8-blended
font string 255 255 255 0))
(surface-w (sdl2:surface-width surface))
(surface-h (sdl2:surface-height surface))
(surface-data (sdl2:surface-pixels surface)))
(gl:bind-texture :texture-2d texture)
(gl:tex-parameter :texture-2d :texture-min-filter :linear)
(gl:tex-parameter :texture-2d :texture-mag-filter :linear)
(gl:tex-image-2d :texture-2d 0 :rgba surface-w surface-h 0
:rgba :unsigned-byte surface-data)
(sdl2:free-surface surface)
(sdl2-ttf:close-font font)
(setf (gethash string *text-hash*)
(make-text-texture :id texture
:width (/ surface-w 30)
:heigth (/ surface-h 30 -1))))))
(defun text (string x y size rotation)
(let ((text-texture (make-text string)))
(with-slots (id width heigth) text-texture
(quad-textured id x y
rotation (* width size) (* heigth size -1)))))
(defun text-align (string x y size rotation)
(let ((text-texture (make-text string)))
(with-slots (id width heigth) text-texture
(quad-textured id (+ x (* width size)) y
rotation (* width size) (* heigth size -1)))))
|
3d363be1737a94cddf0ae3d8b12c7052074bf38a16556cc3291cfc0e0e6fb657 | jkvor/emysql | emysql_eqc.erl | %% erlc -o ebin t/*.erl -W0
%% erl -pa ebin -sasl sasl_error_logger false -name emysql_eqc@`hostname`
eqc : : prop_emysql_eqc ( ) ) .
%% eqc_gen:sample(eqc_statem:commands(rpcore_user_eqc)).
-module(emysql_eqc).
-behaviour(eqc_statem).
-export([command/1, initial_state/0, next_state/3, precondition/2, postcondition/3]).
-compile(export_all).
-include_lib("eqc/include/eqc.hrl").
-include_lib("eqc/include/eqc_statem.hrl").
-include_lib("emysql/include/emysql.hrl").
-record(state, {pool_id, num_conns, tables, insert_statements}).
-record(column_def, {'Field', 'Type', 'Null', 'Key', 'Default', 'Extra'}).
-define(POOLID, test1).
-define(MAX_CONNECTIONS, 40).
initial_state() -> #state{pool_id=?POOLID, num_conns=1, tables=[], insert_statements=[]}.
command(State) ->
oneof(
[{call, ?MODULE, increment_pool_size, [State#state.pool_id, 1]}] ++
[{call, ?MODULE, decrement_pool_size, [State#state.pool_id, 1]}] ++
[{call, ?MODULE, show_tables, [State#state.pool_id]}] ++
[{call, ?MODULE, create_table, [State#state.pool_id, table_name(), ?SUCHTHAT(Y, list(column()), length(Y) > 0)]}] ++
[{call, ?MODULE, drop_table, [State#state.pool_id, oneof(State#state.tables)]} || length(State#state.tables) > 0] ++
[{call, ?MODULE, prepare_insert, [State#state.pool_id, oneof(State#state.tables)]} || length(State#state.tables) > 0] ++
[{call, ?MODULE, call_insert, [State#state.pool_id, ?LET({TN,CD}, oneof(State#state.tables), {TN, column_data(CD)})]} || length(State#state.tables) > 0] ++
[{call, ?MODULE, timeout, [State#state.pool_id]}] ++
[]
).
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
precondition(S, {call, ?MODULE, increment_pool_size, [_PoolId, Num]}) ->
S#state.num_conns + Num < ?MAX_CONNECTIONS;
precondition(S, {call, ?MODULE, decrement_pool_size, [_PoolId, Num]}) ->
S#state.num_conns - Num >= 1;
precondition(_S, {call, ?MODULE, create_table, [_PoolId, _Name, Columns]}) ->
length(lists:usort([string:to_lower(K) || {K,_} <- Columns])) == length(Columns);
precondition(S, {call, ?MODULE, drop_table, [_PoolId, {Name, _}]}) ->
proplists:is_defined(Name, S#state.tables);
precondition(S, {call, ?MODULE, call_insert, [_PoolId, {Name, _}]}) ->
proplists:is_defined(Name, S#state.tables) andalso lists:member(Name, S#state.insert_statements);
precondition(_, _) -> true.
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
next_state(S, _V, {call, ?MODULE, increment_pool_size, [_PoolId, Num]}) ->
S#state{num_conns = (S#state.num_conns + Num)};
next_state(S, _V, {call, ?MODULE, decrement_pool_size, [_PoolId, Num]}) ->
S#state{num_conns = (S#state.num_conns - Num)};
next_state(S, _V, {call, ?MODULE, create_table, [_PoolId, Name, Columns]}) ->
case proplists:is_defined(Name, S#state.tables) of
false ->
S#state{tables = [{Name, Columns} | S#state.tables]};
true ->
S
end;
next_state(S, _V, {call, ?MODULE, drop_table, [_PoolId, {Name, _}]}) ->
S#state{tables = proplists:delete(Name, S#state.tables)};
next_state(S, _V, {call, ?MODULE, prepare_insert, [_PoolId, {TableName, _}]}) ->
S#state{insert_statements = [TableName|S#state.insert_statements]};
next_state(S, _, _) -> S.
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
postcondition(_S, {call, ?MODULE, increment_pool_size, [_PoolId, _Num]}, Result) ->
Result == ok;
postcondition(_S, {call, ?MODULE, decrement_pool_size, [_PoolId, _Num]}, Result) ->
Result == ok;
postcondition(_S, {call, ?MODULE, show_tables, [_PoolId]}, Result) ->
is_record(Result, result_packet);
postcondition(_S, {call, ?MODULE, create_table, [_PoolId, _Name, _Columns]}, Result) ->
case Result of
Err when is_record(Err, error_packet) ->
case Err:code() of
1050 -> %% table already exists
true;
_ ->
false
end;
_ ->
true == is_record(Result, ok_packet)
end;
postcondition(_S, {call, ?MODULE, drop_table, [_PoolId, {_Name, _}]}, Result) ->
case Result of
OK when is_record(OK, ok_packet) ->
true;
Err when is_record(Err, error_packet) ->
case Err:code() of
1051 -> %% unknown table
true;
_ ->
false
end
end;
postcondition(_S, {call, ?MODULE, prepare_insert, [_PoolId, {_Name, _}]}, Result) ->
case Result of
ok ->
true;
Err when is_record(Err, error_packet) ->
case Err:code() of
1146 ->
true;
_ ->
false
end
end;
postcondition(_S, {call, ?MODULE, call_insert, [_PoolId, {_Name, _}]}, Result) ->
is_record(Result, ok_packet) andalso 1 == Result:affected_rows();
postcondition(_S, {call, ?MODULE, timeout, [_PoolId]}, Result) ->
Result == {'EXIT', mysql_timeout};
postcondition(_, _, _) -> true.
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
prop_emysql_eqc() ->
?FORALL(Cmds, commands(?MODULE),
begin
init(),
{H,S,Res} = run_commands(?MODULE,Cmds),
cleanup(),
?WHENFAIL(io:format("FAIL ~p\n~p\n~p\n",[H, S, Res]), Res==ok)
end).
increment_pool_size(PoolId, Num) ->
emysql:increment_pool_size(PoolId, Num).
decrement_pool_size(PoolId, Num) ->
emysql:decrement_pool_size(PoolId, Num).
column() ->
{column_name(), column_type()}.
column_name() ->
?SUCHTHAT(X, list(alpha()), length(X) > 0).
? SUCHTHAT(X , [ alpha ( ) ] + + list(safe_char ( ) ) , length(X ) > 0 andalso hd(lists : ) ) = /= 32 ) .
column_data(Columns) ->
[data_for_type(Type) || {_Name, Type} <- Columns].
data_for_type("DECIMAL") -> real();
data_for_type("TINYINT") -> int();
data_for_type("LONG") -> int();
data_for_type("FLOAT") -> real();
data_for_type("DOUBLE") -> real();
data_for_type("TIMESTAMP") -> "null";
data_for_type("INT") -> int();
data_for_type("DATE") -> "null";
data_for_type("TIME") -> "null";
data_for_type("DATETIME") -> "null";
data_for_type("YEAR") -> choose(0, 3000);
data_for_type("VARCHAR(255)") -> list(char());
data_for_type("BIT") -> oneof([1,0,true,false]);
data_for_type("BLOB") -> list(char()).
table_name() ->
?SUCHTHAT(X, list(alpha()), length(X) > 0).
? SUCHTHAT(X , [ alpha ( ) ] + + list(safe_char ( ) ) , length(X ) > 0 andalso hd(lists : ) ) = /= 32 ) .
alpha() ->
oneof([
%%choose(65,90),
choose(97,122)
]).
safe_char() ->
oneof([
choose(32,95),
choose(97,126)
]).
column_type() ->
elements([
"DECIMAL",
"TINYINT",
"LONG",
"FLOAT",
"DOUBLE",
"TIMESTAMP",
"INT",
"DATE",
"TIME",
"DATETIME",
"YEAR",
"VARCHAR(255)",
"BIT",
"BLOB"
]).
show_tables(PoolId) ->
(catch emysql:execute(PoolId, "SHOW TABLES")).
create_table(PoolId, TableName, Columns) ->
ColumnDefs = ["`" ++ CName ++ "` " ++ CType || {CName, CType} <- Columns],
Query = "CREATE TABLE IF NOT EXISTS `" ++ TableName ++ "` ( " ++ string:join(ColumnDefs, ", ") ++ ")",
(catch emysql:execute(PoolId, Query)).
drop_table(PoolId, {TableName, _}) ->
(catch emysql:execute(PoolId, "DROP TABLE `" ++ TableName ++ "`")).
prepare_insert(PoolId, {TableName, _}) ->
case (catch emysql:execute(PoolId, "DESC `" ++ TableName ++ "`")) of
Result when is_record(Result, result_packet) ->
ColDefs = Result:as_record(column_def, record_info(fields, column_def)),
Stmt = "INSERT INTO `" ++ TableName ++ "` ( " ++ string:join(["`" ++ binary_to_list(Col) ++ "`" || {_,Col,_,_,_,_,_} <- ColDefs], ", ") ++ " ) VALUES ( " ++ string:join(["?" || _ <- ColDefs], ", ") ++ " )",
(catch emysql:prepare(list_to_atom(TableName), Stmt));
Err ->
Err
end.
call_insert(PoolId, {TableName, Args}) ->
(catch emysql:execute(PoolId, list_to_atom(TableName), Args)).
timeout(PoolId) ->
(catch emysql:execute(PoolId, "SELECT SLEEP(8)", 10)).
init() ->
error_logger:tty(false),
ok = load_app(crypto),
ok = application:start(crypto),
ok = load_app(emysql),
ok = application:set_env(emysql, pools, [
{?POOLID, [
{size, 1},
{user, "test"},
{password, "test"},
{host, "localhost"},
{port, 3306},
{database, "testdatabase"},
{encoding, 'utf8'}
]}
]),
ok = application:start(emysql),
[emysql:execute(?POOLID, "DROP TABLE " ++ Table) || [Table] <- (emysql:execute(?POOLID, "SHOW TABLES")):rows()],
ok.
cleanup() ->
ok = application:stop(crypto),
ok = application:stop(emysql),
ok = application:unload(crypto),
ok = application:unload(emysql),
ok.
load_app(Name) ->
case application:load(Name) of
{error, {already_loaded, Name}} ->
application:stop(Name),
application:unload(Name),
application:load(Name);
ok ->
ok
end. | null | https://raw.githubusercontent.com/jkvor/emysql/6f72bc729200024f5940a2c11f15afd2af6f3d11/t/emysql_eqc.erl | erlang | erlc -o ebin t/*.erl -W0
erl -pa ebin -sasl sasl_error_logger false -name emysql_eqc@`hostname`
eqc_gen:sample(eqc_statem:commands(rpcore_user_eqc)).
table already exists
unknown table
choose(65,90), | eqc : : prop_emysql_eqc ( ) ) .
-module(emysql_eqc).
-behaviour(eqc_statem).
-export([command/1, initial_state/0, next_state/3, precondition/2, postcondition/3]).
-compile(export_all).
-include_lib("eqc/include/eqc.hrl").
-include_lib("eqc/include/eqc_statem.hrl").
-include_lib("emysql/include/emysql.hrl").
-record(state, {pool_id, num_conns, tables, insert_statements}).
-record(column_def, {'Field', 'Type', 'Null', 'Key', 'Default', 'Extra'}).
-define(POOLID, test1).
-define(MAX_CONNECTIONS, 40).
initial_state() -> #state{pool_id=?POOLID, num_conns=1, tables=[], insert_statements=[]}.
command(State) ->
oneof(
[{call, ?MODULE, increment_pool_size, [State#state.pool_id, 1]}] ++
[{call, ?MODULE, decrement_pool_size, [State#state.pool_id, 1]}] ++
[{call, ?MODULE, show_tables, [State#state.pool_id]}] ++
[{call, ?MODULE, create_table, [State#state.pool_id, table_name(), ?SUCHTHAT(Y, list(column()), length(Y) > 0)]}] ++
[{call, ?MODULE, drop_table, [State#state.pool_id, oneof(State#state.tables)]} || length(State#state.tables) > 0] ++
[{call, ?MODULE, prepare_insert, [State#state.pool_id, oneof(State#state.tables)]} || length(State#state.tables) > 0] ++
[{call, ?MODULE, call_insert, [State#state.pool_id, ?LET({TN,CD}, oneof(State#state.tables), {TN, column_data(CD)})]} || length(State#state.tables) > 0] ++
[{call, ?MODULE, timeout, [State#state.pool_id]}] ++
[]
).
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
precondition(S, {call, ?MODULE, increment_pool_size, [_PoolId, Num]}) ->
S#state.num_conns + Num < ?MAX_CONNECTIONS;
precondition(S, {call, ?MODULE, decrement_pool_size, [_PoolId, Num]}) ->
S#state.num_conns - Num >= 1;
precondition(_S, {call, ?MODULE, create_table, [_PoolId, _Name, Columns]}) ->
length(lists:usort([string:to_lower(K) || {K,_} <- Columns])) == length(Columns);
precondition(S, {call, ?MODULE, drop_table, [_PoolId, {Name, _}]}) ->
proplists:is_defined(Name, S#state.tables);
precondition(S, {call, ?MODULE, call_insert, [_PoolId, {Name, _}]}) ->
proplists:is_defined(Name, S#state.tables) andalso lists:member(Name, S#state.insert_statements);
precondition(_, _) -> true.
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
next_state(S, _V, {call, ?MODULE, increment_pool_size, [_PoolId, Num]}) ->
S#state{num_conns = (S#state.num_conns + Num)};
next_state(S, _V, {call, ?MODULE, decrement_pool_size, [_PoolId, Num]}) ->
S#state{num_conns = (S#state.num_conns - Num)};
next_state(S, _V, {call, ?MODULE, create_table, [_PoolId, Name, Columns]}) ->
case proplists:is_defined(Name, S#state.tables) of
false ->
S#state{tables = [{Name, Columns} | S#state.tables]};
true ->
S
end;
next_state(S, _V, {call, ?MODULE, drop_table, [_PoolId, {Name, _}]}) ->
S#state{tables = proplists:delete(Name, S#state.tables)};
next_state(S, _V, {call, ?MODULE, prepare_insert, [_PoolId, {TableName, _}]}) ->
S#state{insert_statements = [TableName|S#state.insert_statements]};
next_state(S, _, _) -> S.
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
postcondition(_S, {call, ?MODULE, increment_pool_size, [_PoolId, _Num]}, Result) ->
Result == ok;
postcondition(_S, {call, ?MODULE, decrement_pool_size, [_PoolId, _Num]}, Result) ->
Result == ok;
postcondition(_S, {call, ?MODULE, show_tables, [_PoolId]}, Result) ->
is_record(Result, result_packet);
postcondition(_S, {call, ?MODULE, create_table, [_PoolId, _Name, _Columns]}, Result) ->
case Result of
Err when is_record(Err, error_packet) ->
case Err:code() of
true;
_ ->
false
end;
_ ->
true == is_record(Result, ok_packet)
end;
postcondition(_S, {call, ?MODULE, drop_table, [_PoolId, {_Name, _}]}, Result) ->
case Result of
OK when is_record(OK, ok_packet) ->
true;
Err when is_record(Err, error_packet) ->
case Err:code() of
true;
_ ->
false
end
end;
postcondition(_S, {call, ?MODULE, prepare_insert, [_PoolId, {_Name, _}]}, Result) ->
case Result of
ok ->
true;
Err when is_record(Err, error_packet) ->
case Err:code() of
1146 ->
true;
_ ->
false
end
end;
postcondition(_S, {call, ?MODULE, call_insert, [_PoolId, {_Name, _}]}, Result) ->
is_record(Result, ok_packet) andalso 1 == Result:affected_rows();
postcondition(_S, {call, ?MODULE, timeout, [_PoolId]}, Result) ->
Result == {'EXIT', mysql_timeout};
postcondition(_, _, _) -> true.
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
prop_emysql_eqc() ->
?FORALL(Cmds, commands(?MODULE),
begin
init(),
{H,S,Res} = run_commands(?MODULE,Cmds),
cleanup(),
?WHENFAIL(io:format("FAIL ~p\n~p\n~p\n",[H, S, Res]), Res==ok)
end).
increment_pool_size(PoolId, Num) ->
emysql:increment_pool_size(PoolId, Num).
decrement_pool_size(PoolId, Num) ->
emysql:decrement_pool_size(PoolId, Num).
column() ->
{column_name(), column_type()}.
column_name() ->
?SUCHTHAT(X, list(alpha()), length(X) > 0).
? SUCHTHAT(X , [ alpha ( ) ] + + list(safe_char ( ) ) , length(X ) > 0 andalso hd(lists : ) ) = /= 32 ) .
column_data(Columns) ->
[data_for_type(Type) || {_Name, Type} <- Columns].
data_for_type("DECIMAL") -> real();
data_for_type("TINYINT") -> int();
data_for_type("LONG") -> int();
data_for_type("FLOAT") -> real();
data_for_type("DOUBLE") -> real();
data_for_type("TIMESTAMP") -> "null";
data_for_type("INT") -> int();
data_for_type("DATE") -> "null";
data_for_type("TIME") -> "null";
data_for_type("DATETIME") -> "null";
data_for_type("YEAR") -> choose(0, 3000);
data_for_type("VARCHAR(255)") -> list(char());
data_for_type("BIT") -> oneof([1,0,true,false]);
data_for_type("BLOB") -> list(char()).
table_name() ->
?SUCHTHAT(X, list(alpha()), length(X) > 0).
? SUCHTHAT(X , [ alpha ( ) ] + + list(safe_char ( ) ) , length(X ) > 0 andalso hd(lists : ) ) = /= 32 ) .
alpha() ->
oneof([
choose(97,122)
]).
safe_char() ->
oneof([
choose(32,95),
choose(97,126)
]).
column_type() ->
elements([
"DECIMAL",
"TINYINT",
"LONG",
"FLOAT",
"DOUBLE",
"TIMESTAMP",
"INT",
"DATE",
"TIME",
"DATETIME",
"YEAR",
"VARCHAR(255)",
"BIT",
"BLOB"
]).
show_tables(PoolId) ->
(catch emysql:execute(PoolId, "SHOW TABLES")).
create_table(PoolId, TableName, Columns) ->
ColumnDefs = ["`" ++ CName ++ "` " ++ CType || {CName, CType} <- Columns],
Query = "CREATE TABLE IF NOT EXISTS `" ++ TableName ++ "` ( " ++ string:join(ColumnDefs, ", ") ++ ")",
(catch emysql:execute(PoolId, Query)).
drop_table(PoolId, {TableName, _}) ->
(catch emysql:execute(PoolId, "DROP TABLE `" ++ TableName ++ "`")).
prepare_insert(PoolId, {TableName, _}) ->
case (catch emysql:execute(PoolId, "DESC `" ++ TableName ++ "`")) of
Result when is_record(Result, result_packet) ->
ColDefs = Result:as_record(column_def, record_info(fields, column_def)),
Stmt = "INSERT INTO `" ++ TableName ++ "` ( " ++ string:join(["`" ++ binary_to_list(Col) ++ "`" || {_,Col,_,_,_,_,_} <- ColDefs], ", ") ++ " ) VALUES ( " ++ string:join(["?" || _ <- ColDefs], ", ") ++ " )",
(catch emysql:prepare(list_to_atom(TableName), Stmt));
Err ->
Err
end.
call_insert(PoolId, {TableName, Args}) ->
(catch emysql:execute(PoolId, list_to_atom(TableName), Args)).
timeout(PoolId) ->
(catch emysql:execute(PoolId, "SELECT SLEEP(8)", 10)).
init() ->
error_logger:tty(false),
ok = load_app(crypto),
ok = application:start(crypto),
ok = load_app(emysql),
ok = application:set_env(emysql, pools, [
{?POOLID, [
{size, 1},
{user, "test"},
{password, "test"},
{host, "localhost"},
{port, 3306},
{database, "testdatabase"},
{encoding, 'utf8'}
]}
]),
ok = application:start(emysql),
[emysql:execute(?POOLID, "DROP TABLE " ++ Table) || [Table] <- (emysql:execute(?POOLID, "SHOW TABLES")):rows()],
ok.
cleanup() ->
ok = application:stop(crypto),
ok = application:stop(emysql),
ok = application:unload(crypto),
ok = application:unload(emysql),
ok.
load_app(Name) ->
case application:load(Name) of
{error, {already_loaded, Name}} ->
application:stop(Name),
application:unload(Name),
application:load(Name);
ok ->
ok
end. |
6bc61280f4a19ca42d1ac02aeb9c719927aebadc96c8fbb4cd5bffd803049033 | spurious/sagittarius-scheme-mirror | %3a132.scm | Test program for SRFI 132 ( Sort Libraries ) .
Copyright ( 2016 ) .
;;;
;;; 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.
test harness . Here is his copyright notice :
;;; This code is
Copyright ( c ) 1998 by .
;;; The terms are: You may do as you please with this code, as long as
;;; you do not delete this notice or hold me responsible for any outcome
;;; related to its use.
;;;
;;; Blah blah blah. Don't you think source files should contain more lines
;;; of code than copyright notice?
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
To run this program in Larceny , from this directory :
;;;
%
% cp 132.sld * .scm srfi
;;; % larceny --r7rs --program srfi-132-test.sps --path .
;;;
Other implementations of the R7RS may use other conventions
;;; for naming and locating library files, but the conventions
;;; assumed by this program are the most widely implemented.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Olin 's test harness tests some procedures that are n't part of SRFI 132 ,
so the ( local olin ) library defined here is just to support 's tests .
( Including Olin 's code within the test program would create name
;;; conflicts.)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(import (except (scheme base) vector-copy or)
(rename (scheme base)
(vector-copy r7rs-vector-copy))
(scheme write)
(scheme process-context)
(scheme time)
(only (srfi 27) random-integer)
(srfi 132)
(srfi 64)
)
(test-begin "SRFI-132")
(define-syntax or
(syntax-rules (fail)
((_ expr (fail who))
(test-assert who expr))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
Additional tests written specifically for SRFI 132 .
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(or (list-sorted? > '())
(fail 'list-sorted?:empty-list))
(or (list-sorted? > '(987))
(fail 'list-sorted?:singleton))
(or (list-sorted? > '(9 8 7))
(fail 'list-sorted?:non-empty-list))
(or (vector-sorted? > '#())
(fail 'vector-sorted?:empty-vector))
(or (vector-sorted? > '#(987))
(fail 'vector-sorted?:singleton))
(or (vector-sorted? > '#(9 8 7 6 5))
(fail 'vector-sorted?:non-empty-vector))
(or (vector-sorted? > '#() 0)
(fail 'vector-sorted?:empty-vector:0))
(or (vector-sorted? > '#(987) 1)
(fail 'vector-sorted?:singleton:1))
(or (vector-sorted? > '#(9 8 7 6 5) 1)
(fail 'vector-sorted?:non-empty-vector:1))
(or (vector-sorted? > '#() 0 0)
(fail 'vector-sorted?:empty-vector:0:0))
(or (vector-sorted? > '#(987) 1 1)
(fail 'vector-sorted?:singleton:1:1))
(or (vector-sorted? > '#(9 8 7 6 5) 1 2)
(fail 'vector-sorted?:non-empty-vector:1:2))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(or (equal? (list-sort > (list))
'())
(fail 'list-sort:empty-list))
(or (equal? (list-sort > (list 987))
'(987))
(fail 'list-sort:singleton))
(or (equal? (list-sort > (list 987 654))
'(987 654))
(fail 'list-sort:doubleton))
(or (equal? (list-sort > (list 9 8 6 3 0 4 2 5 7 1))
'(9 8 7 6 5 4 3 2 1 0))
(fail 'list-sort:iota10))
(or (equal? (list-stable-sort > (list))
'())
(fail 'list-stable-sort:empty-list))
(or (equal? (list-stable-sort > (list 987))
'(987))
(fail 'list-stable-sort:singleton))
(or (equal? (list-stable-sort > (list 987 654))
'(987 654))
(fail 'list-stable-sort:doubleton))
(or (equal? (list-stable-sort > (list 9 8 6 3 0 4 2 5 7 1))
'(9 8 7 6 5 4 3 2 1 0))
(fail 'list-stable-sort:iota10))
(or (equal? (list-stable-sort (lambda (x y)
(> (quotient x 2)
(quotient y 2)))
(list 9 8 6 3 0 4 2 5 7 1))
'(9 8 6 7 4 5 3 2 0 1))
(fail 'list-stable-sort:iota10-quotient2))
(or (equal? (let ((v (vector)))
(vector-sort > v))
'#())
(fail 'vector-sort:empty-vector))
(or (equal? (let ((v (vector 987)))
(vector-sort > (vector 987)))
'#(987))
(fail 'vector-sort:singleton))
(or (equal? (let ((v (vector 987 654)))
(vector-sort > v))
'#(987 654))
(fail 'vector-sort:doubleton))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-sort > v))
'#(9 8 7 6 5 4 3 2 1 0))
(fail 'vector-sort:iota10))
(or (equal? (let ((v (vector)))
(vector-stable-sort > v))
'#())
(fail 'vector-stable-sort:empty-vector))
(or (equal? (let ((v (vector 987)))
(vector-stable-sort > (vector 987)))
'#(987))
(fail 'vector-stable-sort:singleton))
(or (equal? (let ((v (vector 987 654)))
(vector-stable-sort > v))
'#(987 654))
(fail 'vector-stable-sort:doubleton))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort > v))
'#(9 8 7 6 5 4 3 2 1 0))
(fail 'vector-stable-sort:iota10))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort (lambda (x y)
(> (quotient x 2)
(quotient y 2)))
v))
'#(9 8 6 7 4 5 3 2 0 1))
(fail 'vector-stable-sort:iota10-quotient2))
(or (equal? (let ((v (vector)))
(vector-sort > v 0))
'#())
(fail 'vector-sort:empty-vector:0))
(or (equal? (let ((v (vector 987)))
(vector-sort > (vector 987) 1))
'#())
(fail 'vector-sort:singleton:1))
(or (equal? (let ((v (vector 987 654)))
(vector-sort > v 1))
'#(654))
(fail 'vector-sort:doubleton:1))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-sort > v 3))
'#(7 5 4 3 2 1 0))
(fail 'vector-sort:iota10:3))
(or (equal? (let ((v (vector)))
(vector-stable-sort > v 0))
'#())
(fail 'vector-stable-sort:empty-vector:0))
(or (equal? (let ((v (vector 987)))
(vector-stable-sort > (vector 987) 1))
'#())
(fail 'vector-stable-sort:singleton:1))
(or (equal? (let ((v (vector 987 654)))
(vector-stable-sort < v 0 2))
'#(654 987))
(fail 'vector-stable-sort:doubleton:0:2))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort > v 3))
'#(7 5 4 3 2 1 0))
(fail 'vector-stable-sort:iota10:3))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort (lambda (x y)
(> (quotient x 2)
(quotient y 2)))
v
3))
'#(7 4 5 3 2 0 1))
(fail 'vector-stable-sort:iota10-quotient2:3))
(or (equal? (let ((v (vector)))
(vector-sort > v 0 0))
'#())
(fail 'vector-sort:empty-vector:0:0))
(or (equal? (let ((v (vector 987)))
(vector-sort > (vector 987) 1 1))
'#())
(fail 'vector-sort:singleton:1:1))
(or (equal? (let ((v (vector 987 654)))
(vector-sort > v 1 2))
'#(654))
(fail 'vector-sort:doubleton:1:2))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-sort > v 4 8))
'#(5 4 2 0))
(fail 'vector-sort:iota10:4:8))
(or (equal? (let ((v (vector)))
(vector-stable-sort > v 0 0))
'#())
(fail 'vector-stable-sort:empty-vector:0:0))
(or (equal? (let ((v (vector 987)))
(vector-stable-sort > (vector 987) 1 1))
'#())
(fail 'vector-stable-sort:singleton:1:1))
(or (equal? (let ((v (vector 987 654)))
(vector-stable-sort > v 1 2))
'#(654))
(fail 'vector-stable-sort:doubleton:1:2))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort > v 2 6))
'#(6 4 3 0))
(fail 'vector-stable-sort:iota10:2:6))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort (lambda (x y)
(> (quotient x 2)
(quotient y 2)))
v
1
8))
'#(8 6 4 5 3 2 0))
(fail 'vector-stable-sort:iota10-quotient2:1:8))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(or (equal? (list-sort! > (list))
'())
(fail 'list-sort!:empty-list))
(or (equal? (list-sort! > (list 987))
'(987))
(fail 'list-sort!:singleton))
(or (equal? (list-sort! > (list 987 654))
'(987 654))
(fail 'list-sort!:doubleton))
(or (equal? (list-sort! > (list 9 8 6 3 0 4 2 5 7 1))
'(9 8 7 6 5 4 3 2 1 0))
(fail 'list-sort!:iota10))
(or (equal? (list-stable-sort! > (list))
'())
(fail 'list-stable-sort!:empty-list))
(or (equal? (list-stable-sort! > (list 987))
'(987))
(fail 'list-stable-sort!:singleton))
(or (equal? (list-stable-sort! > (list 987 654))
'(987 654))
(fail 'list-stable-sort!:doubleton))
(or (equal? (list-stable-sort! > (list 9 8 6 3 0 4 2 5 7 1))
'(9 8 7 6 5 4 3 2 1 0))
(fail 'list-stable-sort!:iota10))
(or (equal? (list-stable-sort! (lambda (x y)
(> (quotient x 2)
(quotient y 2)))
(list 9 8 6 3 0 4 2 5 7 1))
'(9 8 6 7 4 5 3 2 0 1))
(fail 'list-stable-sort!:iota10-quotient2))
(or (equal? (let ((v (vector)))
(vector-sort! > v)
v)
'#())
(fail 'vector-sort!:empty-vector))
(or (equal? (let ((v (vector 987)))
(vector-sort! > (vector 987))
v)
'#(987))
(fail 'vector-sort!:singleton))
(or (equal? (let ((v (vector 987 654)))
(vector-sort! > v)
v)
'#(987 654))
(fail 'vector-sort!:doubleton))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-sort! > v)
v)
'#(9 8 7 6 5 4 3 2 1 0))
(fail 'vector-sort!:iota10))
(or (equal? (let ((v (vector)))
(vector-stable-sort! > v)
v)
'#())
(fail 'vector-stable-sort!:empty-vector))
(or (equal? (let ((v (vector 987)))
(vector-stable-sort! > (vector 987))
v)
'#(987))
(fail 'vector-stable-sort!:singleton))
(or (equal? (let ((v (vector 987 654)))
(vector-stable-sort! > v)
v)
'#(987 654))
(fail 'vector-stable-sort!:doubleton))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort! > v)
v)
'#(9 8 7 6 5 4 3 2 1 0))
(fail 'vector-stable-sort!:iota10))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort! (lambda (x y)
(> (quotient x 2)
(quotient y 2)))
v)
v)
'#(9 8 6 7 4 5 3 2 0 1))
(fail 'vector-stable-sort!:iota10-quotient2))
(or (equal? (let ((v (vector)))
(vector-sort! > v 0)
v)
'#())
(fail 'vector-sort!:empty-vector:0))
(or (equal? (let ((v (vector 987)))
(vector-sort! > (vector 987) 1)
v)
'#(987))
(fail 'vector-sort!:singleton:1))
(or (equal? (let ((v (vector 987 654)))
(vector-sort! > v 1)
v)
'#(987 654))
(fail 'vector-sort!:doubleton:1))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-sort! > v 3)
v)
'#(9 8 6 7 5 4 3 2 1 0))
(fail 'vector-sort!:iota10:3))
(or (equal? (let ((v (vector)))
(vector-stable-sort! > v 0)
v)
'#())
(fail 'vector-stable-sort!:empty-vector:0))
(or (equal? (let ((v (vector 987)))
(vector-stable-sort! > (vector 987) 1)
v)
'#(987))
(fail 'vector-stable-sort!:singleton:1))
(or (equal? (let ((v (vector 987 654)))
(vector-stable-sort! < v 0 2)
v)
'#(654 987))
(fail 'vector-stable-sort!:doubleton:0:2))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort! > v 3)
v)
'#(9 8 6 7 5 4 3 2 1 0))
(fail 'vector-stable-sort!:iota10:3))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort! (lambda (x y)
(> (quotient x 2)
(quotient y 2)))
v
3)
v)
'#(9 8 6 7 4 5 3 2 0 1))
(fail 'vector-stable-sort!:iota10-quotient2:3))
(or (equal? (let ((v (vector)))
(vector-sort! > v 0 0)
v)
'#())
(fail 'vector-sort!:empty-vector:0:0))
(or (equal? (let ((v (vector 987)))
(vector-sort! > (vector 987) 1 1)
v)
'#(987))
(fail 'vector-sort!:singleton:1:1))
(or (equal? (let ((v (vector 987 654)))
(vector-sort! > v 1 2)
v)
'#(987 654))
(fail 'vector-sort!:doubleton:1:2))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-sort! > v 4 8)
v)
'#(9 8 6 3 5 4 2 0 7 1))
(fail 'vector-sort!:iota10:4:8))
(or (equal? (let ((v (vector)))
(vector-stable-sort! > v 0 0)
v)
'#())
(fail 'vector-stable-sort!:empty-vector:0:0))
(or (equal? (let ((v (vector 987)))
(vector-stable-sort! > (vector 987) 1 1)
v)
'#(987))
(fail 'vector-stable-sort!:singleton:1:1))
(or (equal? (let ((v (vector 987 654)))
(vector-stable-sort! > v 1 2)
v)
'#(987 654))
(fail 'vector-stable-sort!:doubleton:1:2))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort! > v 2 6)
v)
'#(9 8 6 4 3 0 2 5 7 1))
(fail 'vector-stable-sort!:iota10:2:6))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort! (lambda (x y)
(> (quotient x 2)
(quotient y 2)))
v
1
8)
v)
'#(9 8 6 4 5 3 2 0 7 1))
(fail 'vector-stable-sort!:iota10-quotient2:1:8))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(or (equal? (list-merge > (list) (list))
'())
(fail 'list-merge:empty:empty))
(or (equal? (list-merge > (list) (list 9 6 3 0))
'(9 6 3 0))
(fail 'list-merge:empty:nonempty))
(or (equal? (list-merge > (list 9 7 5 3 1) (list))
'(9 7 5 3 1))
(fail 'list-merge:nonempty:empty))
(or (equal? (list-merge > (list 9 7 5 3 1) (list 9 6 3 0))
'(9 9 7 6 5 3 3 1 0))
(fail 'list-merge:nonempty:nonempty))
(or (equal? (list-merge! > (list) (list))
'())
(fail 'list-merge!:empty:empty))
(or (equal? (list-merge! > (list) (list 9 6 3 0))
'(9 6 3 0))
(fail 'list-merge!:empty:nonempty))
(or (equal? (list-merge! > (list 9 7 5 3 1) (list))
'(9 7 5 3 1))
(fail 'list-merge!:nonempty:empty))
(or (equal? (list-merge! > (list 9 7 5 3 1) (list 9 6 3 0))
'(9 9 7 6 5 3 3 1 0))
(fail 'list-merge!:nonempty:nonempty))
(or (equal? (vector-merge > (vector) (vector))
'#())
(fail 'vector-merge:empty:empty))
(or (equal? (vector-merge > (vector) (vector 9 6 3 0))
'#(9 6 3 0))
(fail 'vector-merge:empty:nonempty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector))
'#(9 7 5 3 1))
(fail 'vector-merge:nonempty:empty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector 9 6 3 0))
'#(9 9 7 6 5 3 3 1 0))
(fail 'vector-merge:nonempty:nonempty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector))
v)
'#(#f #f #f #f #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:empty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector 9 6 3 0))
v)
'#( 9 6 3 0 #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:nonempty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector))
v)
'#( 9 7 5 3 1 #f #f #f #f #f #f #f))
(fail 'vector-merge!:nonempty:empty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector 9 6 3 0))
v)
'#( 9 9 7 6 5 3 3 1 0 #f #f #f))
(fail 'vector-merge!:nonempty:nonempty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector) 0)
v)
'#(#f #f #f #f #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:empty:0))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector 9 6 3 0) 0)
v)
'#( 9 6 3 0 #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:nonempty:0))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector) 0)
v)
'#( 9 7 5 3 1 #f #f #f #f #f #f #f))
(fail 'vector-merge!:nonempty:empty:0))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector 9 6 3 0) 0)
v)
'#( 9 9 7 6 5 3 3 1 0 #f #f #f))
(fail 'vector-merge!:nonempty:nonempty:0))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector) 2)
v)
'#(#f #f #f #f #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector 9 6 3 0) 2)
v)
'#(#f #f 9 6 3 0 #f #f #f #f #f #f))
(fail 'vector-merge!:empty:nonempty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector) 2)
v)
'#(#f #f 9 7 5 3 1 #f #f #f #f #f))
(fail 'vector-merge!:nonempty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector 9 6 3 0) 2)
v)
'#(#f #f 9 9 7 6 5 3 3 1 0 #f))
(fail 'vector-merge!:nonempty:nonempty:2))
(or (equal? (vector-merge > (vector) (vector) 0)
'#())
(fail 'vector-merge:empty:empty))
(or (equal? (vector-merge > (vector) (vector 9 6 3 0) 0)
'#(9 6 3 0))
(fail 'vector-merge:empty:nonempty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector) 2)
'#(5 3 1))
(fail 'vector-merge:nonempty:empty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector 9 6 3 0) 2)
'#(9 6 5 3 3 1 0))
(fail 'vector-merge:nonempty:nonempty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector) 2 0)
v)
'#(#f #f #f #f #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector 9 6 3 0) 2 0)
v)
'#(#f #f 9 6 3 0 #f #f #f #f #f #f))
(fail 'vector-merge!:empty:nonempty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector) 2 2)
v)
'#(#f #f 5 3 1 #f #f #f #f #f #f #f))
(fail 'vector-merge!:nonempty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector 9 6 3 0) 2 2)
v)
'#(#f #f 9 6 5 3 3 1 0 #f #f #f))
(fail 'vector-merge!:nonempty:nonempty:2))
(or (equal? (vector-merge > (vector) (vector) 0 0)
'#())
(fail 'vector-merge:empty:empty))
(or (equal? (vector-merge > (vector) (vector 9 6 3 0) 0 0)
'#(9 6 3 0))
(fail 'vector-merge:empty:nonempty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector) 2 5)
'#(5 3 1))
(fail 'vector-merge:nonempty:empty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector 9 6 3 0) 2 5)
'#(9 6 5 3 3 1 0))
(fail 'vector-merge:nonempty:nonempty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector) 2 0 0)
v)
'#(#f #f #f #f #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector 9 6 3 0) 2 0 0)
v)
'#(#f #f 9 6 3 0 #f #f #f #f #f #f))
(fail 'vector-merge!:empty:nonempty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector) 2 2 5)
v)
'#(#f #f 5 3 1 #f #f #f #f #f #f #f))
(fail 'vector-merge!:nonempty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector 9 6 3 0) 2 2 5)
v)
'#(#f #f 9 6 5 3 3 1 0 #f #f #f))
(fail 'vector-merge!:nonempty:nonempty:2))
;;; Some tests are duplicated to make the pattern easier to discern.
(or (equal? (vector-merge > (vector) (vector) 0 0)
'#())
(fail 'vector-merge:empty:empty))
(or (equal? (vector-merge > (vector) (vector 9 6 3 0) 0 0)
'#(9 6 3 0))
(fail 'vector-merge:empty:nonempty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector) 2 4)
'#(5 3))
(fail 'vector-merge:nonempty:empty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector 9 6 3 0) 2 4)
'#(9 6 5 3 3 0))
(fail 'vector-merge:nonempty:nonempty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector) 2 0 0)
v)
'#(#f #f #f #f #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector 9 6 3 0) 2 0 0)
v)
'#(#f #f 9 6 3 0 #f #f #f #f #f #f))
(fail 'vector-merge!:empty:nonempty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector) 2 2 4)
v)
'#(#f #f 5 3 #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:nonempty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector 9 6 3 0) 2 2 4)
v)
'#(#f #f 9 6 5 3 3 0 #f #f #f #f))
(fail 'vector-merge!:nonempty:nonempty:2))
(or (equal? (vector-merge > (vector) (vector) 0 0 0)
'#())
(fail 'vector-merge:empty:empty))
(or (equal? (vector-merge > (vector) (vector 9 6 3 0) 0 0 0)
'#(9 6 3 0))
(fail 'vector-merge:empty:nonempty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector) 2 4 0)
'#(5 3))
(fail 'vector-merge:nonempty:empty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector 9 6 3 0) 2 4 0)
'#(9 6 5 3 3 0))
(fail 'vector-merge:nonempty:nonempty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector) 2 0 0 0)
v)
'#(#f #f #f #f #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector 9 6 3 0) 2 0 0 0)
v)
'#(#f #f 9 6 3 0 #f #f #f #f #f #f))
(fail 'vector-merge!:empty:nonempty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector) 2 2 4 0)
v)
'#(#f #f 5 3 #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:nonempty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector 9 6 3 0) 2 2 4 0)
v)
'#(#f #f 9 6 5 3 3 0 #f #f #f #f))
(fail 'vector-merge!:nonempty:nonempty:2))
(or (equal? (vector-merge > (vector) (vector) 0 0 0)
'#())
(fail 'vector-merge:empty:empty))
(or (equal? (vector-merge > (vector) (vector 9 6 3 0) 0 0 1)
'#(6 3 0))
(fail 'vector-merge:empty:nonempty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector) 2 4 0)
'#(5 3))
(fail 'vector-merge:nonempty:empty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector 9 6 3 0) 2 4 1)
'#(6 5 3 3 0))
(fail 'vector-merge:nonempty:nonempty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector) 2 0 0 0)
v)
'#(#f #f #f #f #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector 9 6 3 0) 2 0 0 1)
v)
'#(#f #f 6 3 0 #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:nonempty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector) 2 2 4 0)
v)
'#(#f #f 5 3 #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:nonempty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector 9 6 3 0) 2 2 4 1)
v)
'#(#f #f 6 5 3 3 0 #f #f #f #f #f))
(fail 'vector-merge!:nonempty:nonempty:2))
(or (equal? (vector-merge > (vector) (vector) 0 0 0 0)
'#())
(fail 'vector-merge:empty:empty))
(or (equal? (vector-merge > (vector) (vector 9 6 3 0) 0 0 1 4)
'#(6 3 0))
(fail 'vector-merge:empty:nonempty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector) 2 4 0 0)
'#(5 3))
(fail 'vector-merge:nonempty:empty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector 9 6 3 0) 2 4 1 4)
'#(6 5 3 3 0))
(fail 'vector-merge:nonempty:nonempty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector) 2 0 0 0 0)
v)
'#(#f #f #f #f #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector 9 6 3 0) 2 0 0 1 4)
v)
'#(#f #f 6 3 0 #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:nonempty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector) 2 2 4 0 0)
v)
'#(#f #f 5 3 #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:nonempty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector 9 6 3 0) 2 2 4 1 4)
v)
'#(#f #f 6 5 3 3 0 #f #f #f #f #f))
(fail 'vector-merge!:nonempty:nonempty:2))
(or (equal? (vector-merge > (vector) (vector) 0 0 0 0)
'#())
(fail 'vector-merge:empty:empty))
(or (equal? (vector-merge > (vector) (vector 9 6 3 0) 0 0 1 2)
'#(6))
(fail 'vector-merge:empty:nonempty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector) 2 4 0 0)
'#(5 3))
(fail 'vector-merge:nonempty:empty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector 9 6 3 0) 2 4 1 2)
'#(6 5 3))
(fail 'vector-merge:nonempty:nonempty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector) 2 0 0 0 0)
v)
'#(#f #f #f #f #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector 9 6 3 0) 2 0 0 1 2)
v)
'#(#f #f 6 #f #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:nonempty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector) 2 2 4 0 0)
v)
'#(#f #f 5 3 #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:nonempty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector 9 6 3 0) 2 2 4 1 2)
v)
'#(#f #f 6 5 3 #f #f #f #f #f #f #f))
(fail 'vector-merge!:nonempty:nonempty:2))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(or (equal? (list-delete-neighbor-dups char=? (list))
'())
(fail 'list-delete-neighbor-dups:empty))
(or (equal? (list-delete-neighbor-dups char=? (list #\a))
'(#\a))
(fail 'list-delete-neighbor-dups:singleton))
(or (equal? (list-delete-neighbor-dups char=? (list #\a #\a #\a #\b #\b #\a))
'(#\a #\b #\a))
(fail 'list-delete-neighbor-dups:nonempty))
(or (equal? (list-delete-neighbor-dups! char=? (list))
'())
(fail 'list-delete-neighbor-dups!:empty))
(or (equal? (list-delete-neighbor-dups! char=? (list #\a))
'(#\a))
(fail 'list-delete-neighbor-dups!:singleton))
(or (equal? (list-delete-neighbor-dups! char=? (list #\a #\a #\a #\b #\b #\a))
'(#\a #\b #\a))
(fail 'list-delete-neighbor-dups!:nonempty))
(or (equal? (let ((v (vector)))
(vector-delete-neighbor-dups char=? v))
'#())
(fail 'vector-delete-neighbor-dups:empty))
(or (equal? (let ((v (vector #\a)))
(vector-delete-neighbor-dups char=? v))
'#(#\a))
(fail 'vector-delete-neighbor-dups:singleton))
(or (equal? (let ((v (vector #\a #\a #\a #\b #\b #\a)))
(vector-delete-neighbor-dups char=? v))
'#(#\a #\b #\a))
(fail 'vector-delete-neighbor-dups:nonempty))
(or (equal? (let ((v (vector)))
(list (vector-delete-neighbor-dups! char=? v) v))
'(0 #()))
(fail 'vector-delete-neighbor-dups!:empty))
(or (equal? (let ((v (vector #\a)))
(list (vector-delete-neighbor-dups! char=? v) v))
'(1 #(#\a)))
(fail 'vector-delete-neighbor-dups!:singleton))
(or (equal? (let ((v (vector #\a #\a #\a #\b #\b #\a)))
(list (vector-delete-neighbor-dups! char=? v) v))
'(3 #(#\a #\b #\a #\b #\b #\a)))
(fail 'vector-delete-neighbor-dups!:nonempty))
(or (equal? (let ((v (vector)))
(vector-delete-neighbor-dups char=? v 0))
'#())
(fail 'vector-delete-neighbor-dups:empty:0))
(or (equal? (let ((v (vector #\a)))
(vector-delete-neighbor-dups char=? v 0))
'#(#\a))
(fail 'vector-delete-neighbor-dups:singleton:0))
(or (equal? (let ((v (vector #\a #\a #\a #\b #\b #\a)))
(vector-delete-neighbor-dups char=? v 0))
'#(#\a #\b #\a))
(fail 'vector-delete-neighbor-dups:nonempty:0))
(or (equal? (let ((v (vector)))
(list (vector-delete-neighbor-dups! char=? v 0) v))
'(0 #()))
(fail 'vector-delete-neighbor-dups!:empty:0))
(or (equal? (let ((v (vector #\a)))
(list (vector-delete-neighbor-dups! char=? v 0) v))
'(1 #(#\a)))
(fail 'vector-delete-neighbor-dups!:singleton:0))
(or (equal? (let ((v (vector #\a #\a #\a #\b #\b #\a)))
(list (vector-delete-neighbor-dups! char=? v 0) v))
'(3 #(#\a #\b #\a #\b #\b #\a)))
(fail 'vector-delete-neighbor-dups!:nonempty:0))
(or (equal? (let ((v (vector)))
(vector-delete-neighbor-dups char=? v 0))
'#())
(fail 'vector-delete-neighbor-dups:empty:0))
(or (equal? (let ((v (vector #\a)))
(vector-delete-neighbor-dups char=? v 1))
'#())
(fail 'vector-delete-neighbor-dups:singleton:1))
(or (equal? (let ((v (vector #\a #\a #\a #\b #\b #\a)))
(vector-delete-neighbor-dups char=? v 3))
'#(#\b #\a))
(fail 'vector-delete-neighbor-dups:nonempty:3))
(or (equal? (let ((v (vector)))
(list (vector-delete-neighbor-dups! char=? v 0) v))
'(0 #()))
(fail 'vector-delete-neighbor-dups!:empty:0))
(or (equal? (let ((v (vector #\a)))
(list (vector-delete-neighbor-dups! char=? v 1) v))
'(1 #(#\a)))
(fail 'vector-delete-neighbor-dups!:singleton:1))
(or (equal? (let ((v (vector #\a #\a #\a #\b #\b #\a)))
(list (vector-delete-neighbor-dups! char=? v 3) v))
'(5 #(#\a #\a #\a #\b #\a #\a)))
(fail 'vector-delete-neighbor-dups!:nonempty:3))
(or (equal? (let ((v (vector)))
(vector-delete-neighbor-dups char=? v 0 0))
'#())
(fail 'vector-delete-neighbor-dups:empty:0:0))
(or (equal? (let ((v (vector #\a)))
(vector-delete-neighbor-dups char=? v 1 1))
'#())
(fail 'vector-delete-neighbor-dups:singleton:1:1))
(or (equal? (let ((v (vector #\a #\a #\a #\b #\b #\a)))
(vector-delete-neighbor-dups char=? v 3 5))
'#(#\b))
(fail 'vector-delete-neighbor-dups:nonempty:3:5))
(or (equal? (let ((v (vector)))
(list (vector-delete-neighbor-dups! char=? v 0 0) v))
'(0 #()))
(fail 'vector-delete-neighbor-dups!:empty:0:0))
(or (equal? (let ((v (vector #\a)))
(list (vector-delete-neighbor-dups! char=? v 0 1) v))
'(1 #(#\a)))
(fail 'vector-delete-neighbor-dups!:singleton:0:1))
(or (equal? (let ((v (vector #\a)))
(list (vector-delete-neighbor-dups! char=? v 1 1) v))
'(1 #(#\a)))
(fail 'vector-delete-neighbor-dups!:singleton:1:1))
(or (equal? (let ((v (vector #\a #\a #\a #\b #\b #\a)))
(list (vector-delete-neighbor-dups! char=? v 3 5) v))
'(4 #(#\a #\a #\a #\b #\b #\a)))
(fail 'vector-delete-neighbor-dups!:nonempty:3:5))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(or (equal? (vector-find-median < (vector) "knil")
"knil")
(fail 'vector-find-median:empty))
(or (equal? (vector-find-median < (vector 17) "knil")
17)
(fail 'vector-find-median:singleton))
(or (equal? (vector-find-median < (vector 18 1 12 14 12 5 18 2) "knil")
12)
(fail 'vector-find-median:8same))
(or (equal? (vector-find-median < (vector 18 1 11 14 12 5 18 2) "knil")
23/2)
(fail 'vector-find-median:8diff))
(or (equal? (vector-find-median < (vector 18 1 12 14 12 5 18 2) "knil" list)
(list 12 12))
(fail 'vector-find-median:8samelist))
(or (equal? (vector-find-median < (vector 18 1 11 14 12 5 18 2) "knil" list)
(list 11 12))
(fail 'vector-find-median:8difflist))
(or (equal? (vector-find-median < (vector 7 6 9 3 1 18 15 7 8) "knil")
7)
(fail 'vector-find-median:9))
(or (equal? (vector-find-median < (vector 7 6 9 3 1 18 15 7 8) "knil" list)
7)
(fail 'vector-find-median:9list))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(or (equal? (let ((v (vector 19)))
(vector-select! < v 0))
19)
(fail 'vector-select!:singleton:0))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 0))
3)
(fail 'vector-select!:ten:0))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 2))
9)
(fail 'vector-select!:ten:2))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 8))
22)
(fail 'vector-select!:ten:8))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 9))
23)
(fail 'vector-select!:ten:9))
(or (equal? (let ((v (vector 19)))
(vector-select! < v 0 0))
19)
(fail 'vector-select!:singleton:0:0))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 0 0))
3)
(fail 'vector-select!:ten:0:0))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 2 0))
9)
(fail 'vector-select!:ten:2:0))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 8 0))
22)
(fail 'vector-select!:ten:8:0))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 9 0))
23)
(fail 'vector-select!:ten:9:0))
(or (equal? (let ((v (vector 19)))
(vector-select! < v 0 0 1))
19)
(fail 'vector-select!:singleton:0:0:1))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 0 0 10))
3)
(fail 'vector-select!:ten:0:0:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 2 0 10))
9)
(fail 'vector-select!:ten:2:0:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 8 0 10))
22)
(fail 'vector-select!:ten:8:0:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 9 0 10))
23)
(fail 'vector-select!:ten:9:0:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 0 4 10))
3)
(fail 'vector-select!:ten:0:4:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 2 4 10))
13)
(fail 'vector-select!:ten:2:4:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 4 4 10))
21)
(fail 'vector-select!:ten:4:4:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 5 4 10))
23)
(fail 'vector-select!:ten:5:4:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 0 4 10))
3)
(fail 'vector-select!:ten:0:4:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 2 4 10))
13)
(fail 'vector-select!:ten:2:4:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 3 4 10))
13)
(fail 'vector-select!:ten:3:4:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 4 4 10))
21)
(fail 'vector-select!:ten:4:4:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 5 4 10))
23)
(fail 'vector-select!:ten:9:4:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 0 4 8))
9)
(fail 'vector-select!:ten:0:4:8))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 1 4 8))
13)
(fail 'vector-select!:ten:1:4:8))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 2 4 8))
13)
(fail 'vector-select!:ten:2:4:8))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 3 4 8))
21)
(fail 'vector-select!:ten:3:4:8))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(or (equal? (let ((v (vector)))
(vector-separate! < v 0)
(vector-sort < (r7rs-vector-copy v 0 0)))
'#())
(fail 'vector-separate!:empty:0))
(or (equal? (let ((v (vector 19)))
(vector-separate! < v 0)
(vector-sort < (r7rs-vector-copy v 0 0)))
'#())
(fail 'vector-separate!:singleton:0))
(or (equal? (let ((v (vector 19)))
(vector-separate! < v 1)
(vector-sort < (r7rs-vector-copy v 0 1)))
'#(19))
(fail 'vector-separate!:singleton:1))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-separate! < v 0)
(vector-sort < (r7rs-vector-copy v 0 0)))
'#())
(fail 'vector-separate!:ten:0))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-separate! < v 3)
(vector-sort < (r7rs-vector-copy v 0 3)))
'#(3 8 9))
(fail 'vector-separate!:ten:3))
(or (equal? (let ((v (vector)))
(vector-separate! < v 0 0)
(vector-sort < (r7rs-vector-copy v 0 0)))
'#())
(fail 'vector-separate!:empty:0:0))
(or (equal? (let ((v (vector 19)))
(vector-separate! < v 0 0)
(vector-sort < (r7rs-vector-copy v 0 0)))
'#())
(fail 'vector-separate!:singleton:0:0))
(or (equal? (let ((v (vector 19)))
(vector-separate! < v 1 0)
(vector-sort < (r7rs-vector-copy v 0 1)))
'#(19))
(fail 'vector-separate!:singleton:1:0))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-separate! < v 0 0)
(vector-sort < (r7rs-vector-copy v 0 0)))
'#())
(fail 'vector-separate!:ten:0:0))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-separate! < v 3 0)
(vector-sort < (r7rs-vector-copy v 0 3)))
'#(3 8 9))
(fail 'vector-separate!:ten:3:0))
(or (equal? (let ((v (vector 19)))
(vector-separate! < v 0 1)
(vector-sort < (r7rs-vector-copy v 1 1)))
'#())
(fail 'vector-separate!:singleton:0:1))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-separate! < v 0 2)
(vector-sort < (r7rs-vector-copy v 2 2)))
'#())
(fail 'vector-separate!:ten:0:2))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-separate! < v 3 2)
(vector-sort < (r7rs-vector-copy v 2 5)))
'#(3 9 13))
(fail 'vector-separate!:ten:3:2))
(or (equal? (let ((v (vector)))
(vector-separate! < v 0 0 0)
(vector-sort < (r7rs-vector-copy v 0 0)))
'#())
(fail 'vector-separate!:empty:0:0:0))
(or (equal? (let ((v (vector 19)))
(vector-separate! < v 0 1 1)
(vector-sort < (r7rs-vector-copy v 1 1)))
'#())
(fail 'vector-separate!:singleton:0:1:1))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-separate! < v 0 2 8)
(vector-sort < (r7rs-vector-copy v 2 2)))
'#())
(fail 'vector-separate!:ten:0:2:8))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-separate! < v 3 2 8)
(vector-sort < (r7rs-vector-copy v 2 5)))
'#(9 13 13))
(fail 'vector-separate!:ten:3:2:8))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Sorting routines often have internal boundary cases or
;;; randomness, so it's prudent to run a lot of tests with
;;; different lengths.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (random-vector size)
(let ((v (make-vector size)))
(fill-vector-randomly! v (* 10 size))
v))
(define (fill-vector-randomly! v range)
(let ((half (quotient range 2)))
(do ((i (- (vector-length v) 1) (- i 1)))
((< i 0))
(vector-set! v i (- (random-integer range) half)))))
(define (all-sorts-okay? m n)
(if (> m 0)
(let* ((v (random-vector n))
(v2 (vector-copy v))
(lst (vector->list v))
(ans (vector-sort < v2))
(med (cond ((= n 0) -97)
((odd? n)
(vector-ref ans (quotient n 2)))
(else
(/ (+ (vector-ref ans (- (quotient n 2) 1))
(vector-ref ans (quotient n 2)))
2)))))
(define (dsort vsort!)
(let ((v2 (vector-copy v)))
(vsort! < v2)
v2))
(and (equal? ans (list->vector (list-sort < lst)))
(equal? ans (list->vector (list-stable-sort < lst)))
(equal? ans (list->vector (list-sort! < (list-copy lst))))
(equal? ans (list->vector (list-stable-sort! < (list-copy lst))))
(equal? ans (vector-sort < v2))
(equal? ans (vector-stable-sort < v2))
(equal? ans (dsort vector-sort!))
(equal? ans (dsort vector-stable-sort!))
(equal? med (vector-find-median < v2 -97))
(equal? v v2)
(equal? lst (vector->list v))
(equal? med (vector-find-median! < v2 -97))
(equal? ans v2)
(all-sorts-okay? (- m 1) n)))
#t))
(define (test-all-sorts m n)
(or (all-sorts-okay? m n)
(fail (list 'test-all-sorts m n))))
(for-each test-all-sorts
'( 3 5 10 10 10 20 20 10 10 10 10 10 10 10 10 10 10)
'( 0 1 2 3 4 5 10 20 30 40 50 99 100 101 499 500 501))
(test-end)
| null | https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/test/tests/srfi/%253a132.scm | scheme |
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
Software is 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.
This code is
The terms are: You may do as you please with this code, as long as
you do not delete this notice or hold me responsible for any outcome
related to its use.
Blah blah blah. Don't you think source files should contain more lines
of code than copyright notice?
% larceny --r7rs --program srfi-132-test.sps --path .
for naming and locating library files, but the conventions
assumed by this program are the most widely implemented.
conflicts.)
Some tests are duplicated to make the pattern easier to discern.
Sorting routines often have internal boundary cases or
randomness, so it's prudent to run a lot of tests with
different lengths.
| Test program for SRFI 132 ( Sort Libraries ) .
Copyright ( 2016 ) .
files ( the " Software " ) , to deal in the Software without
sell copies of the Software , and to permit persons to whom the
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
test harness . Here is his copyright notice :
Copyright ( c ) 1998 by .
To run this program in Larceny , from this directory :
%
% cp 132.sld * .scm srfi
Other implementations of the R7RS may use other conventions
Olin 's test harness tests some procedures that are n't part of SRFI 132 ,
so the ( local olin ) library defined here is just to support 's tests .
( Including Olin 's code within the test program would create name
(import (except (scheme base) vector-copy or)
(rename (scheme base)
(vector-copy r7rs-vector-copy))
(scheme write)
(scheme process-context)
(scheme time)
(only (srfi 27) random-integer)
(srfi 132)
(srfi 64)
)
(test-begin "SRFI-132")
(define-syntax or
(syntax-rules (fail)
((_ expr (fail who))
(test-assert who expr))))
Additional tests written specifically for SRFI 132 .
(or (list-sorted? > '())
(fail 'list-sorted?:empty-list))
(or (list-sorted? > '(987))
(fail 'list-sorted?:singleton))
(or (list-sorted? > '(9 8 7))
(fail 'list-sorted?:non-empty-list))
(or (vector-sorted? > '#())
(fail 'vector-sorted?:empty-vector))
(or (vector-sorted? > '#(987))
(fail 'vector-sorted?:singleton))
(or (vector-sorted? > '#(9 8 7 6 5))
(fail 'vector-sorted?:non-empty-vector))
(or (vector-sorted? > '#() 0)
(fail 'vector-sorted?:empty-vector:0))
(or (vector-sorted? > '#(987) 1)
(fail 'vector-sorted?:singleton:1))
(or (vector-sorted? > '#(9 8 7 6 5) 1)
(fail 'vector-sorted?:non-empty-vector:1))
(or (vector-sorted? > '#() 0 0)
(fail 'vector-sorted?:empty-vector:0:0))
(or (vector-sorted? > '#(987) 1 1)
(fail 'vector-sorted?:singleton:1:1))
(or (vector-sorted? > '#(9 8 7 6 5) 1 2)
(fail 'vector-sorted?:non-empty-vector:1:2))
(or (equal? (list-sort > (list))
'())
(fail 'list-sort:empty-list))
(or (equal? (list-sort > (list 987))
'(987))
(fail 'list-sort:singleton))
(or (equal? (list-sort > (list 987 654))
'(987 654))
(fail 'list-sort:doubleton))
(or (equal? (list-sort > (list 9 8 6 3 0 4 2 5 7 1))
'(9 8 7 6 5 4 3 2 1 0))
(fail 'list-sort:iota10))
(or (equal? (list-stable-sort > (list))
'())
(fail 'list-stable-sort:empty-list))
(or (equal? (list-stable-sort > (list 987))
'(987))
(fail 'list-stable-sort:singleton))
(or (equal? (list-stable-sort > (list 987 654))
'(987 654))
(fail 'list-stable-sort:doubleton))
(or (equal? (list-stable-sort > (list 9 8 6 3 0 4 2 5 7 1))
'(9 8 7 6 5 4 3 2 1 0))
(fail 'list-stable-sort:iota10))
(or (equal? (list-stable-sort (lambda (x y)
(> (quotient x 2)
(quotient y 2)))
(list 9 8 6 3 0 4 2 5 7 1))
'(9 8 6 7 4 5 3 2 0 1))
(fail 'list-stable-sort:iota10-quotient2))
(or (equal? (let ((v (vector)))
(vector-sort > v))
'#())
(fail 'vector-sort:empty-vector))
(or (equal? (let ((v (vector 987)))
(vector-sort > (vector 987)))
'#(987))
(fail 'vector-sort:singleton))
(or (equal? (let ((v (vector 987 654)))
(vector-sort > v))
'#(987 654))
(fail 'vector-sort:doubleton))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-sort > v))
'#(9 8 7 6 5 4 3 2 1 0))
(fail 'vector-sort:iota10))
(or (equal? (let ((v (vector)))
(vector-stable-sort > v))
'#())
(fail 'vector-stable-sort:empty-vector))
(or (equal? (let ((v (vector 987)))
(vector-stable-sort > (vector 987)))
'#(987))
(fail 'vector-stable-sort:singleton))
(or (equal? (let ((v (vector 987 654)))
(vector-stable-sort > v))
'#(987 654))
(fail 'vector-stable-sort:doubleton))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort > v))
'#(9 8 7 6 5 4 3 2 1 0))
(fail 'vector-stable-sort:iota10))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort (lambda (x y)
(> (quotient x 2)
(quotient y 2)))
v))
'#(9 8 6 7 4 5 3 2 0 1))
(fail 'vector-stable-sort:iota10-quotient2))
(or (equal? (let ((v (vector)))
(vector-sort > v 0))
'#())
(fail 'vector-sort:empty-vector:0))
(or (equal? (let ((v (vector 987)))
(vector-sort > (vector 987) 1))
'#())
(fail 'vector-sort:singleton:1))
(or (equal? (let ((v (vector 987 654)))
(vector-sort > v 1))
'#(654))
(fail 'vector-sort:doubleton:1))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-sort > v 3))
'#(7 5 4 3 2 1 0))
(fail 'vector-sort:iota10:3))
(or (equal? (let ((v (vector)))
(vector-stable-sort > v 0))
'#())
(fail 'vector-stable-sort:empty-vector:0))
(or (equal? (let ((v (vector 987)))
(vector-stable-sort > (vector 987) 1))
'#())
(fail 'vector-stable-sort:singleton:1))
(or (equal? (let ((v (vector 987 654)))
(vector-stable-sort < v 0 2))
'#(654 987))
(fail 'vector-stable-sort:doubleton:0:2))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort > v 3))
'#(7 5 4 3 2 1 0))
(fail 'vector-stable-sort:iota10:3))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort (lambda (x y)
(> (quotient x 2)
(quotient y 2)))
v
3))
'#(7 4 5 3 2 0 1))
(fail 'vector-stable-sort:iota10-quotient2:3))
(or (equal? (let ((v (vector)))
(vector-sort > v 0 0))
'#())
(fail 'vector-sort:empty-vector:0:0))
(or (equal? (let ((v (vector 987)))
(vector-sort > (vector 987) 1 1))
'#())
(fail 'vector-sort:singleton:1:1))
(or (equal? (let ((v (vector 987 654)))
(vector-sort > v 1 2))
'#(654))
(fail 'vector-sort:doubleton:1:2))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-sort > v 4 8))
'#(5 4 2 0))
(fail 'vector-sort:iota10:4:8))
(or (equal? (let ((v (vector)))
(vector-stable-sort > v 0 0))
'#())
(fail 'vector-stable-sort:empty-vector:0:0))
(or (equal? (let ((v (vector 987)))
(vector-stable-sort > (vector 987) 1 1))
'#())
(fail 'vector-stable-sort:singleton:1:1))
(or (equal? (let ((v (vector 987 654)))
(vector-stable-sort > v 1 2))
'#(654))
(fail 'vector-stable-sort:doubleton:1:2))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort > v 2 6))
'#(6 4 3 0))
(fail 'vector-stable-sort:iota10:2:6))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort (lambda (x y)
(> (quotient x 2)
(quotient y 2)))
v
1
8))
'#(8 6 4 5 3 2 0))
(fail 'vector-stable-sort:iota10-quotient2:1:8))
(or (equal? (list-sort! > (list))
'())
(fail 'list-sort!:empty-list))
(or (equal? (list-sort! > (list 987))
'(987))
(fail 'list-sort!:singleton))
(or (equal? (list-sort! > (list 987 654))
'(987 654))
(fail 'list-sort!:doubleton))
(or (equal? (list-sort! > (list 9 8 6 3 0 4 2 5 7 1))
'(9 8 7 6 5 4 3 2 1 0))
(fail 'list-sort!:iota10))
(or (equal? (list-stable-sort! > (list))
'())
(fail 'list-stable-sort!:empty-list))
(or (equal? (list-stable-sort! > (list 987))
'(987))
(fail 'list-stable-sort!:singleton))
(or (equal? (list-stable-sort! > (list 987 654))
'(987 654))
(fail 'list-stable-sort!:doubleton))
(or (equal? (list-stable-sort! > (list 9 8 6 3 0 4 2 5 7 1))
'(9 8 7 6 5 4 3 2 1 0))
(fail 'list-stable-sort!:iota10))
(or (equal? (list-stable-sort! (lambda (x y)
(> (quotient x 2)
(quotient y 2)))
(list 9 8 6 3 0 4 2 5 7 1))
'(9 8 6 7 4 5 3 2 0 1))
(fail 'list-stable-sort!:iota10-quotient2))
(or (equal? (let ((v (vector)))
(vector-sort! > v)
v)
'#())
(fail 'vector-sort!:empty-vector))
(or (equal? (let ((v (vector 987)))
(vector-sort! > (vector 987))
v)
'#(987))
(fail 'vector-sort!:singleton))
(or (equal? (let ((v (vector 987 654)))
(vector-sort! > v)
v)
'#(987 654))
(fail 'vector-sort!:doubleton))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-sort! > v)
v)
'#(9 8 7 6 5 4 3 2 1 0))
(fail 'vector-sort!:iota10))
(or (equal? (let ((v (vector)))
(vector-stable-sort! > v)
v)
'#())
(fail 'vector-stable-sort!:empty-vector))
(or (equal? (let ((v (vector 987)))
(vector-stable-sort! > (vector 987))
v)
'#(987))
(fail 'vector-stable-sort!:singleton))
(or (equal? (let ((v (vector 987 654)))
(vector-stable-sort! > v)
v)
'#(987 654))
(fail 'vector-stable-sort!:doubleton))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort! > v)
v)
'#(9 8 7 6 5 4 3 2 1 0))
(fail 'vector-stable-sort!:iota10))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort! (lambda (x y)
(> (quotient x 2)
(quotient y 2)))
v)
v)
'#(9 8 6 7 4 5 3 2 0 1))
(fail 'vector-stable-sort!:iota10-quotient2))
(or (equal? (let ((v (vector)))
(vector-sort! > v 0)
v)
'#())
(fail 'vector-sort!:empty-vector:0))
(or (equal? (let ((v (vector 987)))
(vector-sort! > (vector 987) 1)
v)
'#(987))
(fail 'vector-sort!:singleton:1))
(or (equal? (let ((v (vector 987 654)))
(vector-sort! > v 1)
v)
'#(987 654))
(fail 'vector-sort!:doubleton:1))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-sort! > v 3)
v)
'#(9 8 6 7 5 4 3 2 1 0))
(fail 'vector-sort!:iota10:3))
(or (equal? (let ((v (vector)))
(vector-stable-sort! > v 0)
v)
'#())
(fail 'vector-stable-sort!:empty-vector:0))
(or (equal? (let ((v (vector 987)))
(vector-stable-sort! > (vector 987) 1)
v)
'#(987))
(fail 'vector-stable-sort!:singleton:1))
(or (equal? (let ((v (vector 987 654)))
(vector-stable-sort! < v 0 2)
v)
'#(654 987))
(fail 'vector-stable-sort!:doubleton:0:2))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort! > v 3)
v)
'#(9 8 6 7 5 4 3 2 1 0))
(fail 'vector-stable-sort!:iota10:3))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort! (lambda (x y)
(> (quotient x 2)
(quotient y 2)))
v
3)
v)
'#(9 8 6 7 4 5 3 2 0 1))
(fail 'vector-stable-sort!:iota10-quotient2:3))
(or (equal? (let ((v (vector)))
(vector-sort! > v 0 0)
v)
'#())
(fail 'vector-sort!:empty-vector:0:0))
(or (equal? (let ((v (vector 987)))
(vector-sort! > (vector 987) 1 1)
v)
'#(987))
(fail 'vector-sort!:singleton:1:1))
(or (equal? (let ((v (vector 987 654)))
(vector-sort! > v 1 2)
v)
'#(987 654))
(fail 'vector-sort!:doubleton:1:2))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-sort! > v 4 8)
v)
'#(9 8 6 3 5 4 2 0 7 1))
(fail 'vector-sort!:iota10:4:8))
(or (equal? (let ((v (vector)))
(vector-stable-sort! > v 0 0)
v)
'#())
(fail 'vector-stable-sort!:empty-vector:0:0))
(or (equal? (let ((v (vector 987)))
(vector-stable-sort! > (vector 987) 1 1)
v)
'#(987))
(fail 'vector-stable-sort!:singleton:1:1))
(or (equal? (let ((v (vector 987 654)))
(vector-stable-sort! > v 1 2)
v)
'#(987 654))
(fail 'vector-stable-sort!:doubleton:1:2))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort! > v 2 6)
v)
'#(9 8 6 4 3 0 2 5 7 1))
(fail 'vector-stable-sort!:iota10:2:6))
(or (equal? (let ((v (vector 9 8 6 3 0 4 2 5 7 1)))
(vector-stable-sort! (lambda (x y)
(> (quotient x 2)
(quotient y 2)))
v
1
8)
v)
'#(9 8 6 4 5 3 2 0 7 1))
(fail 'vector-stable-sort!:iota10-quotient2:1:8))
(or (equal? (list-merge > (list) (list))
'())
(fail 'list-merge:empty:empty))
(or (equal? (list-merge > (list) (list 9 6 3 0))
'(9 6 3 0))
(fail 'list-merge:empty:nonempty))
(or (equal? (list-merge > (list 9 7 5 3 1) (list))
'(9 7 5 3 1))
(fail 'list-merge:nonempty:empty))
(or (equal? (list-merge > (list 9 7 5 3 1) (list 9 6 3 0))
'(9 9 7 6 5 3 3 1 0))
(fail 'list-merge:nonempty:nonempty))
(or (equal? (list-merge! > (list) (list))
'())
(fail 'list-merge!:empty:empty))
(or (equal? (list-merge! > (list) (list 9 6 3 0))
'(9 6 3 0))
(fail 'list-merge!:empty:nonempty))
(or (equal? (list-merge! > (list 9 7 5 3 1) (list))
'(9 7 5 3 1))
(fail 'list-merge!:nonempty:empty))
(or (equal? (list-merge! > (list 9 7 5 3 1) (list 9 6 3 0))
'(9 9 7 6 5 3 3 1 0))
(fail 'list-merge!:nonempty:nonempty))
(or (equal? (vector-merge > (vector) (vector))
'#())
(fail 'vector-merge:empty:empty))
(or (equal? (vector-merge > (vector) (vector 9 6 3 0))
'#(9 6 3 0))
(fail 'vector-merge:empty:nonempty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector))
'#(9 7 5 3 1))
(fail 'vector-merge:nonempty:empty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector 9 6 3 0))
'#(9 9 7 6 5 3 3 1 0))
(fail 'vector-merge:nonempty:nonempty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector))
v)
'#(#f #f #f #f #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:empty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector 9 6 3 0))
v)
'#( 9 6 3 0 #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:nonempty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector))
v)
'#( 9 7 5 3 1 #f #f #f #f #f #f #f))
(fail 'vector-merge!:nonempty:empty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector 9 6 3 0))
v)
'#( 9 9 7 6 5 3 3 1 0 #f #f #f))
(fail 'vector-merge!:nonempty:nonempty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector) 0)
v)
'#(#f #f #f #f #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:empty:0))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector 9 6 3 0) 0)
v)
'#( 9 6 3 0 #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:nonempty:0))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector) 0)
v)
'#( 9 7 5 3 1 #f #f #f #f #f #f #f))
(fail 'vector-merge!:nonempty:empty:0))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector 9 6 3 0) 0)
v)
'#( 9 9 7 6 5 3 3 1 0 #f #f #f))
(fail 'vector-merge!:nonempty:nonempty:0))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector) 2)
v)
'#(#f #f #f #f #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector 9 6 3 0) 2)
v)
'#(#f #f 9 6 3 0 #f #f #f #f #f #f))
(fail 'vector-merge!:empty:nonempty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector) 2)
v)
'#(#f #f 9 7 5 3 1 #f #f #f #f #f))
(fail 'vector-merge!:nonempty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector 9 6 3 0) 2)
v)
'#(#f #f 9 9 7 6 5 3 3 1 0 #f))
(fail 'vector-merge!:nonempty:nonempty:2))
(or (equal? (vector-merge > (vector) (vector) 0)
'#())
(fail 'vector-merge:empty:empty))
(or (equal? (vector-merge > (vector) (vector 9 6 3 0) 0)
'#(9 6 3 0))
(fail 'vector-merge:empty:nonempty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector) 2)
'#(5 3 1))
(fail 'vector-merge:nonempty:empty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector 9 6 3 0) 2)
'#(9 6 5 3 3 1 0))
(fail 'vector-merge:nonempty:nonempty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector) 2 0)
v)
'#(#f #f #f #f #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector 9 6 3 0) 2 0)
v)
'#(#f #f 9 6 3 0 #f #f #f #f #f #f))
(fail 'vector-merge!:empty:nonempty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector) 2 2)
v)
'#(#f #f 5 3 1 #f #f #f #f #f #f #f))
(fail 'vector-merge!:nonempty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector 9 6 3 0) 2 2)
v)
'#(#f #f 9 6 5 3 3 1 0 #f #f #f))
(fail 'vector-merge!:nonempty:nonempty:2))
(or (equal? (vector-merge > (vector) (vector) 0 0)
'#())
(fail 'vector-merge:empty:empty))
(or (equal? (vector-merge > (vector) (vector 9 6 3 0) 0 0)
'#(9 6 3 0))
(fail 'vector-merge:empty:nonempty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector) 2 5)
'#(5 3 1))
(fail 'vector-merge:nonempty:empty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector 9 6 3 0) 2 5)
'#(9 6 5 3 3 1 0))
(fail 'vector-merge:nonempty:nonempty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector) 2 0 0)
v)
'#(#f #f #f #f #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector 9 6 3 0) 2 0 0)
v)
'#(#f #f 9 6 3 0 #f #f #f #f #f #f))
(fail 'vector-merge!:empty:nonempty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector) 2 2 5)
v)
'#(#f #f 5 3 1 #f #f #f #f #f #f #f))
(fail 'vector-merge!:nonempty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector 9 6 3 0) 2 2 5)
v)
'#(#f #f 9 6 5 3 3 1 0 #f #f #f))
(fail 'vector-merge!:nonempty:nonempty:2))
(or (equal? (vector-merge > (vector) (vector) 0 0)
'#())
(fail 'vector-merge:empty:empty))
(or (equal? (vector-merge > (vector) (vector 9 6 3 0) 0 0)
'#(9 6 3 0))
(fail 'vector-merge:empty:nonempty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector) 2 4)
'#(5 3))
(fail 'vector-merge:nonempty:empty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector 9 6 3 0) 2 4)
'#(9 6 5 3 3 0))
(fail 'vector-merge:nonempty:nonempty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector) 2 0 0)
v)
'#(#f #f #f #f #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector 9 6 3 0) 2 0 0)
v)
'#(#f #f 9 6 3 0 #f #f #f #f #f #f))
(fail 'vector-merge!:empty:nonempty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector) 2 2 4)
v)
'#(#f #f 5 3 #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:nonempty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector 9 6 3 0) 2 2 4)
v)
'#(#f #f 9 6 5 3 3 0 #f #f #f #f))
(fail 'vector-merge!:nonempty:nonempty:2))
(or (equal? (vector-merge > (vector) (vector) 0 0 0)
'#())
(fail 'vector-merge:empty:empty))
(or (equal? (vector-merge > (vector) (vector 9 6 3 0) 0 0 0)
'#(9 6 3 0))
(fail 'vector-merge:empty:nonempty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector) 2 4 0)
'#(5 3))
(fail 'vector-merge:nonempty:empty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector 9 6 3 0) 2 4 0)
'#(9 6 5 3 3 0))
(fail 'vector-merge:nonempty:nonempty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector) 2 0 0 0)
v)
'#(#f #f #f #f #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector 9 6 3 0) 2 0 0 0)
v)
'#(#f #f 9 6 3 0 #f #f #f #f #f #f))
(fail 'vector-merge!:empty:nonempty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector) 2 2 4 0)
v)
'#(#f #f 5 3 #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:nonempty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector 9 6 3 0) 2 2 4 0)
v)
'#(#f #f 9 6 5 3 3 0 #f #f #f #f))
(fail 'vector-merge!:nonempty:nonempty:2))
(or (equal? (vector-merge > (vector) (vector) 0 0 0)
'#())
(fail 'vector-merge:empty:empty))
(or (equal? (vector-merge > (vector) (vector 9 6 3 0) 0 0 1)
'#(6 3 0))
(fail 'vector-merge:empty:nonempty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector) 2 4 0)
'#(5 3))
(fail 'vector-merge:nonempty:empty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector 9 6 3 0) 2 4 1)
'#(6 5 3 3 0))
(fail 'vector-merge:nonempty:nonempty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector) 2 0 0 0)
v)
'#(#f #f #f #f #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector 9 6 3 0) 2 0 0 1)
v)
'#(#f #f 6 3 0 #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:nonempty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector) 2 2 4 0)
v)
'#(#f #f 5 3 #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:nonempty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector 9 6 3 0) 2 2 4 1)
v)
'#(#f #f 6 5 3 3 0 #f #f #f #f #f))
(fail 'vector-merge!:nonempty:nonempty:2))
(or (equal? (vector-merge > (vector) (vector) 0 0 0 0)
'#())
(fail 'vector-merge:empty:empty))
(or (equal? (vector-merge > (vector) (vector 9 6 3 0) 0 0 1 4)
'#(6 3 0))
(fail 'vector-merge:empty:nonempty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector) 2 4 0 0)
'#(5 3))
(fail 'vector-merge:nonempty:empty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector 9 6 3 0) 2 4 1 4)
'#(6 5 3 3 0))
(fail 'vector-merge:nonempty:nonempty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector) 2 0 0 0 0)
v)
'#(#f #f #f #f #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector 9 6 3 0) 2 0 0 1 4)
v)
'#(#f #f 6 3 0 #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:nonempty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector) 2 2 4 0 0)
v)
'#(#f #f 5 3 #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:nonempty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector 9 6 3 0) 2 2 4 1 4)
v)
'#(#f #f 6 5 3 3 0 #f #f #f #f #f))
(fail 'vector-merge!:nonempty:nonempty:2))
(or (equal? (vector-merge > (vector) (vector) 0 0 0 0)
'#())
(fail 'vector-merge:empty:empty))
(or (equal? (vector-merge > (vector) (vector 9 6 3 0) 0 0 1 2)
'#(6))
(fail 'vector-merge:empty:nonempty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector) 2 4 0 0)
'#(5 3))
(fail 'vector-merge:nonempty:empty))
(or (equal? (vector-merge > (vector 9 7 5 3 1) (vector 9 6 3 0) 2 4 1 2)
'#(6 5 3))
(fail 'vector-merge:nonempty:nonempty))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector) 2 0 0 0 0)
v)
'#(#f #f #f #f #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector) (vector 9 6 3 0) 2 0 0 1 2)
v)
'#(#f #f 6 #f #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:empty:nonempty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector) 2 2 4 0 0)
v)
'#(#f #f 5 3 #f #f #f #f #f #f #f #f))
(fail 'vector-merge!:nonempty:empty:2))
(or (equal? (let ((v (make-vector 12 #f)))
(vector-merge! > v (vector 9 7 5 3 1) (vector 9 6 3 0) 2 2 4 1 2)
v)
'#(#f #f 6 5 3 #f #f #f #f #f #f #f))
(fail 'vector-merge!:nonempty:nonempty:2))
(or (equal? (list-delete-neighbor-dups char=? (list))
'())
(fail 'list-delete-neighbor-dups:empty))
(or (equal? (list-delete-neighbor-dups char=? (list #\a))
'(#\a))
(fail 'list-delete-neighbor-dups:singleton))
(or (equal? (list-delete-neighbor-dups char=? (list #\a #\a #\a #\b #\b #\a))
'(#\a #\b #\a))
(fail 'list-delete-neighbor-dups:nonempty))
(or (equal? (list-delete-neighbor-dups! char=? (list))
'())
(fail 'list-delete-neighbor-dups!:empty))
(or (equal? (list-delete-neighbor-dups! char=? (list #\a))
'(#\a))
(fail 'list-delete-neighbor-dups!:singleton))
(or (equal? (list-delete-neighbor-dups! char=? (list #\a #\a #\a #\b #\b #\a))
'(#\a #\b #\a))
(fail 'list-delete-neighbor-dups!:nonempty))
(or (equal? (let ((v (vector)))
(vector-delete-neighbor-dups char=? v))
'#())
(fail 'vector-delete-neighbor-dups:empty))
(or (equal? (let ((v (vector #\a)))
(vector-delete-neighbor-dups char=? v))
'#(#\a))
(fail 'vector-delete-neighbor-dups:singleton))
(or (equal? (let ((v (vector #\a #\a #\a #\b #\b #\a)))
(vector-delete-neighbor-dups char=? v))
'#(#\a #\b #\a))
(fail 'vector-delete-neighbor-dups:nonempty))
(or (equal? (let ((v (vector)))
(list (vector-delete-neighbor-dups! char=? v) v))
'(0 #()))
(fail 'vector-delete-neighbor-dups!:empty))
(or (equal? (let ((v (vector #\a)))
(list (vector-delete-neighbor-dups! char=? v) v))
'(1 #(#\a)))
(fail 'vector-delete-neighbor-dups!:singleton))
(or (equal? (let ((v (vector #\a #\a #\a #\b #\b #\a)))
(list (vector-delete-neighbor-dups! char=? v) v))
'(3 #(#\a #\b #\a #\b #\b #\a)))
(fail 'vector-delete-neighbor-dups!:nonempty))
(or (equal? (let ((v (vector)))
(vector-delete-neighbor-dups char=? v 0))
'#())
(fail 'vector-delete-neighbor-dups:empty:0))
(or (equal? (let ((v (vector #\a)))
(vector-delete-neighbor-dups char=? v 0))
'#(#\a))
(fail 'vector-delete-neighbor-dups:singleton:0))
(or (equal? (let ((v (vector #\a #\a #\a #\b #\b #\a)))
(vector-delete-neighbor-dups char=? v 0))
'#(#\a #\b #\a))
(fail 'vector-delete-neighbor-dups:nonempty:0))
(or (equal? (let ((v (vector)))
(list (vector-delete-neighbor-dups! char=? v 0) v))
'(0 #()))
(fail 'vector-delete-neighbor-dups!:empty:0))
(or (equal? (let ((v (vector #\a)))
(list (vector-delete-neighbor-dups! char=? v 0) v))
'(1 #(#\a)))
(fail 'vector-delete-neighbor-dups!:singleton:0))
(or (equal? (let ((v (vector #\a #\a #\a #\b #\b #\a)))
(list (vector-delete-neighbor-dups! char=? v 0) v))
'(3 #(#\a #\b #\a #\b #\b #\a)))
(fail 'vector-delete-neighbor-dups!:nonempty:0))
(or (equal? (let ((v (vector)))
(vector-delete-neighbor-dups char=? v 0))
'#())
(fail 'vector-delete-neighbor-dups:empty:0))
(or (equal? (let ((v (vector #\a)))
(vector-delete-neighbor-dups char=? v 1))
'#())
(fail 'vector-delete-neighbor-dups:singleton:1))
(or (equal? (let ((v (vector #\a #\a #\a #\b #\b #\a)))
(vector-delete-neighbor-dups char=? v 3))
'#(#\b #\a))
(fail 'vector-delete-neighbor-dups:nonempty:3))
(or (equal? (let ((v (vector)))
(list (vector-delete-neighbor-dups! char=? v 0) v))
'(0 #()))
(fail 'vector-delete-neighbor-dups!:empty:0))
(or (equal? (let ((v (vector #\a)))
(list (vector-delete-neighbor-dups! char=? v 1) v))
'(1 #(#\a)))
(fail 'vector-delete-neighbor-dups!:singleton:1))
(or (equal? (let ((v (vector #\a #\a #\a #\b #\b #\a)))
(list (vector-delete-neighbor-dups! char=? v 3) v))
'(5 #(#\a #\a #\a #\b #\a #\a)))
(fail 'vector-delete-neighbor-dups!:nonempty:3))
(or (equal? (let ((v (vector)))
(vector-delete-neighbor-dups char=? v 0 0))
'#())
(fail 'vector-delete-neighbor-dups:empty:0:0))
(or (equal? (let ((v (vector #\a)))
(vector-delete-neighbor-dups char=? v 1 1))
'#())
(fail 'vector-delete-neighbor-dups:singleton:1:1))
(or (equal? (let ((v (vector #\a #\a #\a #\b #\b #\a)))
(vector-delete-neighbor-dups char=? v 3 5))
'#(#\b))
(fail 'vector-delete-neighbor-dups:nonempty:3:5))
(or (equal? (let ((v (vector)))
(list (vector-delete-neighbor-dups! char=? v 0 0) v))
'(0 #()))
(fail 'vector-delete-neighbor-dups!:empty:0:0))
(or (equal? (let ((v (vector #\a)))
(list (vector-delete-neighbor-dups! char=? v 0 1) v))
'(1 #(#\a)))
(fail 'vector-delete-neighbor-dups!:singleton:0:1))
(or (equal? (let ((v (vector #\a)))
(list (vector-delete-neighbor-dups! char=? v 1 1) v))
'(1 #(#\a)))
(fail 'vector-delete-neighbor-dups!:singleton:1:1))
(or (equal? (let ((v (vector #\a #\a #\a #\b #\b #\a)))
(list (vector-delete-neighbor-dups! char=? v 3 5) v))
'(4 #(#\a #\a #\a #\b #\b #\a)))
(fail 'vector-delete-neighbor-dups!:nonempty:3:5))
(or (equal? (vector-find-median < (vector) "knil")
"knil")
(fail 'vector-find-median:empty))
(or (equal? (vector-find-median < (vector 17) "knil")
17)
(fail 'vector-find-median:singleton))
(or (equal? (vector-find-median < (vector 18 1 12 14 12 5 18 2) "knil")
12)
(fail 'vector-find-median:8same))
(or (equal? (vector-find-median < (vector 18 1 11 14 12 5 18 2) "knil")
23/2)
(fail 'vector-find-median:8diff))
(or (equal? (vector-find-median < (vector 18 1 12 14 12 5 18 2) "knil" list)
(list 12 12))
(fail 'vector-find-median:8samelist))
(or (equal? (vector-find-median < (vector 18 1 11 14 12 5 18 2) "knil" list)
(list 11 12))
(fail 'vector-find-median:8difflist))
(or (equal? (vector-find-median < (vector 7 6 9 3 1 18 15 7 8) "knil")
7)
(fail 'vector-find-median:9))
(or (equal? (vector-find-median < (vector 7 6 9 3 1 18 15 7 8) "knil" list)
7)
(fail 'vector-find-median:9list))
(or (equal? (let ((v (vector 19)))
(vector-select! < v 0))
19)
(fail 'vector-select!:singleton:0))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 0))
3)
(fail 'vector-select!:ten:0))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 2))
9)
(fail 'vector-select!:ten:2))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 8))
22)
(fail 'vector-select!:ten:8))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 9))
23)
(fail 'vector-select!:ten:9))
(or (equal? (let ((v (vector 19)))
(vector-select! < v 0 0))
19)
(fail 'vector-select!:singleton:0:0))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 0 0))
3)
(fail 'vector-select!:ten:0:0))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 2 0))
9)
(fail 'vector-select!:ten:2:0))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 8 0))
22)
(fail 'vector-select!:ten:8:0))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 9 0))
23)
(fail 'vector-select!:ten:9:0))
(or (equal? (let ((v (vector 19)))
(vector-select! < v 0 0 1))
19)
(fail 'vector-select!:singleton:0:0:1))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 0 0 10))
3)
(fail 'vector-select!:ten:0:0:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 2 0 10))
9)
(fail 'vector-select!:ten:2:0:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 8 0 10))
22)
(fail 'vector-select!:ten:8:0:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 9 0 10))
23)
(fail 'vector-select!:ten:9:0:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 0 4 10))
3)
(fail 'vector-select!:ten:0:4:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 2 4 10))
13)
(fail 'vector-select!:ten:2:4:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 4 4 10))
21)
(fail 'vector-select!:ten:4:4:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 5 4 10))
23)
(fail 'vector-select!:ten:5:4:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 0 4 10))
3)
(fail 'vector-select!:ten:0:4:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 2 4 10))
13)
(fail 'vector-select!:ten:2:4:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 3 4 10))
13)
(fail 'vector-select!:ten:3:4:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 4 4 10))
21)
(fail 'vector-select!:ten:4:4:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 5 4 10))
23)
(fail 'vector-select!:ten:9:4:10))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 0 4 8))
9)
(fail 'vector-select!:ten:0:4:8))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 1 4 8))
13)
(fail 'vector-select!:ten:1:4:8))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 2 4 8))
13)
(fail 'vector-select!:ten:2:4:8))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-select! < v 3 4 8))
21)
(fail 'vector-select!:ten:3:4:8))
(or (equal? (let ((v (vector)))
(vector-separate! < v 0)
(vector-sort < (r7rs-vector-copy v 0 0)))
'#())
(fail 'vector-separate!:empty:0))
(or (equal? (let ((v (vector 19)))
(vector-separate! < v 0)
(vector-sort < (r7rs-vector-copy v 0 0)))
'#())
(fail 'vector-separate!:singleton:0))
(or (equal? (let ((v (vector 19)))
(vector-separate! < v 1)
(vector-sort < (r7rs-vector-copy v 0 1)))
'#(19))
(fail 'vector-separate!:singleton:1))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-separate! < v 0)
(vector-sort < (r7rs-vector-copy v 0 0)))
'#())
(fail 'vector-separate!:ten:0))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-separate! < v 3)
(vector-sort < (r7rs-vector-copy v 0 3)))
'#(3 8 9))
(fail 'vector-separate!:ten:3))
(or (equal? (let ((v (vector)))
(vector-separate! < v 0 0)
(vector-sort < (r7rs-vector-copy v 0 0)))
'#())
(fail 'vector-separate!:empty:0:0))
(or (equal? (let ((v (vector 19)))
(vector-separate! < v 0 0)
(vector-sort < (r7rs-vector-copy v 0 0)))
'#())
(fail 'vector-separate!:singleton:0:0))
(or (equal? (let ((v (vector 19)))
(vector-separate! < v 1 0)
(vector-sort < (r7rs-vector-copy v 0 1)))
'#(19))
(fail 'vector-separate!:singleton:1:0))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-separate! < v 0 0)
(vector-sort < (r7rs-vector-copy v 0 0)))
'#())
(fail 'vector-separate!:ten:0:0))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-separate! < v 3 0)
(vector-sort < (r7rs-vector-copy v 0 3)))
'#(3 8 9))
(fail 'vector-separate!:ten:3:0))
(or (equal? (let ((v (vector 19)))
(vector-separate! < v 0 1)
(vector-sort < (r7rs-vector-copy v 1 1)))
'#())
(fail 'vector-separate!:singleton:0:1))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-separate! < v 0 2)
(vector-sort < (r7rs-vector-copy v 2 2)))
'#())
(fail 'vector-separate!:ten:0:2))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-separate! < v 3 2)
(vector-sort < (r7rs-vector-copy v 2 5)))
'#(3 9 13))
(fail 'vector-separate!:ten:3:2))
(or (equal? (let ((v (vector)))
(vector-separate! < v 0 0 0)
(vector-sort < (r7rs-vector-copy v 0 0)))
'#())
(fail 'vector-separate!:empty:0:0:0))
(or (equal? (let ((v (vector 19)))
(vector-separate! < v 0 1 1)
(vector-sort < (r7rs-vector-copy v 1 1)))
'#())
(fail 'vector-separate!:singleton:0:1:1))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-separate! < v 0 2 8)
(vector-sort < (r7rs-vector-copy v 2 2)))
'#())
(fail 'vector-separate!:ten:0:2:8))
(or (equal? (let ((v (vector 8 22 19 19 13 9 21 13 3 23)))
(vector-separate! < v 3 2 8)
(vector-sort < (r7rs-vector-copy v 2 5)))
'#(9 13 13))
(fail 'vector-separate!:ten:3:2:8))
(define (random-vector size)
(let ((v (make-vector size)))
(fill-vector-randomly! v (* 10 size))
v))
(define (fill-vector-randomly! v range)
(let ((half (quotient range 2)))
(do ((i (- (vector-length v) 1) (- i 1)))
((< i 0))
(vector-set! v i (- (random-integer range) half)))))
(define (all-sorts-okay? m n)
(if (> m 0)
(let* ((v (random-vector n))
(v2 (vector-copy v))
(lst (vector->list v))
(ans (vector-sort < v2))
(med (cond ((= n 0) -97)
((odd? n)
(vector-ref ans (quotient n 2)))
(else
(/ (+ (vector-ref ans (- (quotient n 2) 1))
(vector-ref ans (quotient n 2)))
2)))))
(define (dsort vsort!)
(let ((v2 (vector-copy v)))
(vsort! < v2)
v2))
(and (equal? ans (list->vector (list-sort < lst)))
(equal? ans (list->vector (list-stable-sort < lst)))
(equal? ans (list->vector (list-sort! < (list-copy lst))))
(equal? ans (list->vector (list-stable-sort! < (list-copy lst))))
(equal? ans (vector-sort < v2))
(equal? ans (vector-stable-sort < v2))
(equal? ans (dsort vector-sort!))
(equal? ans (dsort vector-stable-sort!))
(equal? med (vector-find-median < v2 -97))
(equal? v v2)
(equal? lst (vector->list v))
(equal? med (vector-find-median! < v2 -97))
(equal? ans v2)
(all-sorts-okay? (- m 1) n)))
#t))
(define (test-all-sorts m n)
(or (all-sorts-okay? m n)
(fail (list 'test-all-sorts m n))))
(for-each test-all-sorts
'( 3 5 10 10 10 20 20 10 10 10 10 10 10 10 10 10 10)
'( 0 1 2 3 4 5 10 20 30 40 50 99 100 101 499 500 501))
(test-end)
|
2b688fda1cbbc2b968a9e56d81b97aecac6eee4d04994661a32b2e9a97a1ebd7 | tdammers/sprinkles | Bake.hs | # LANGUAGE NoImplicitPrelude #
{-#LANGUAGE OverloadedStrings #-}
# LANGUAGE OverloadedLists #
# LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE FlexibleInstances #
# LANGUAGE FlexibleContexts #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
module Web.Sprinkles.Bake
where
import Web.Sprinkles.Prelude
import qualified Data.Text as Text
import Data.Text (Text)
import qualified Data.Set as Set
import Data.Set (Set)
import System.Directory (createDirectoryIfMissing)
import System.FilePath ( (</>), takeDirectory, replaceExtension )
import Control.Monad.State
import Control.Lens
import Control.Lens.TH (makeLenses)
import Text.Printf (printf)
import Network.HTTP.Types (Status (..), status200)
import Network.Wai.Test
import Network.Wai (Application, Request (..))
import qualified Network.Wai as Wai
import Web.Sprinkles.Serve (appFromProject)
import Web.Sprinkles.Project
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString as BS
import Data.Char (ord)
import Text.HTML.TagSoup (parseTags, Tag (..), Attribute)
import qualified Data.CSS.Syntax.Tokens as CSS
import Data.FileEmbed (embedStringFile)
defHtaccess :: ByteString
defHtaccess = $(embedStringFile "embedded/.htaccess")
data BakeState
= BakeState
{ _bsTodo :: [FilePath]
, _bsDone :: Set FilePath
, _bsBasedir :: FilePath
, _bsApp :: Application
}
makeLenses ''BakeState
defBakeState :: BakeState
defBakeState = BakeState [] Set.empty "." defaultApplication
defaultApplication :: Application
defaultApplication rq respond =
respond $
Wai.responseLBS
status200
[("Content-type", "text/plain;charset=utf8")]
"Hello, world!"
type Bake = StateT BakeState IO
bakeProject :: FilePath -> Project -> [FilePath] -> IO ()
bakeProject destDir project extraEntryPoints = do
putStrLn @Text $ "Baking project into " <> pack destDir
createDirectoryIfMissing True destDir
let app = appFromProject project
runBake destDir entryPoints app $ do
bakeHtaccess
bake404
bakeApp
where
entryPoints =
[ "/"
, "/sitemap.xml"
, "/favicon.ico"
, "/robots.txt"
]
++ extraEntryPoints
runBake :: FilePath -> [FilePath] -> Application -> Bake a -> IO a
runBake baseDir entryPoints app a =
evalStateT a $ defBakeState
{ _bsTodo = entryPoints
, _bsBasedir = baseDir
, _bsApp = app
}
bakeHtaccess :: Bake ()
bakeHtaccess = do
basedir <- use bsBasedir
liftIO $ writeFile (basedir </> ".htaccess") defHtaccess
bakeApp :: Bake ()
bakeApp = do
use bsTodo >>= \case
(current:rest) -> do
bsTodo .= rest
bakePath current
bsDone %= Set.insert current
bakeApp
_ -> return ()
bakePath :: FilePath -> Bake ()
bakePath fp = do
done <- use bsDone
unless (fp `Set.member` done) $
bakePage CreateIndexHtml [200] fp (dropLeadingSlash fp)
data HtmlMappingMode = MapHtmlDirect | CreateIndexHtml
bake404 :: Bake ()
bake404 = do
bakePage MapHtmlDirect [404] nonsensicalPath "_errors/404"
where
nonsensicalPath = "/123087408972309872109873012984709218371209847123"
dropLeadingSlash :: FilePath -> FilePath
dropLeadingSlash = \case
'/':x -> x
x -> x
bakePage :: HtmlMappingMode -> [Int] -> FilePath -> FilePath -> Bake ()
bakePage htmlMode expectedStatuses fp fn = do
app <- use bsApp
basedir <- use bsBasedir
let dstFile = basedir </> fn
dstDir = takeDirectory dstFile
let session = do
let rq = setPath defaultRequest (fromString fp)
request rq
rp <- liftIO $ runSession session app
let status = simpleStatus rp
liftIO $ printf "GET %s %i %s\n" ("/" </> fp) (statusCode status) (decodeUtf8 $ statusMessage status)
if statusCode status `elem` expectedStatuses
then do
let ty = fromMaybe "application/octet-stream" $ lookup "content-type" (simpleHeaders rp)
rawTy = BS.takeWhile (/= fromIntegral (ord ';')) ty
rawTySplit = BS.split (fromIntegral . ord $ '/') rawTy
liftIO $ printf "%s\n" (decodeUtf8 ty)
let (linkUrls, dstDir', dstFile') = case rawTySplit of
["text", "html"] ->
let body = LBS.toStrict $ simpleBody rp
soup = parseTags (decodeUtf8 body)
linkUrls = map (fp </>) . map Text.unpack $ extractLinkedUrls soup
in case htmlMode of
CreateIndexHtml ->
(linkUrls, dstFile, dstFile </> "index.html")
MapHtmlDirect ->
(linkUrls, dstDir, replaceExtension dstFile "html")
[_, "css"] ->
let body = decodeUtf8 . LBS.toStrict $ simpleBody rp
tokens = CSS.tokenize body
linkUrls = map (takeDirectory fp </>) . map Text.unpack $ extractCssUrls tokens
in (linkUrls, dstDir, dstFile)
_ ->
([], dstDir, dstFile)
liftIO $ do
createDirectoryIfMissing True dstDir'
LBS.writeFile dstFile' (simpleBody rp)
bsTodo <>= linkUrls
else do
liftIO $ putStrLn @String "skip"
extractLinkedUrls :: [Tag Text] -> [Text]
extractLinkedUrls tags = filter isLocalUrl $ do
tags >>= \case
TagOpen "a" attrs -> do
attrs >>= \case
("href", url) -> return url
_ -> []
TagOpen "link" attrs -> do
attrs >>= \case
("href", url) -> return url
_ -> []
TagOpen "script" attrs -> do
attrs >>= \case
("src", url) -> return url
_ -> []
TagOpen "img" attrs -> do
attrs >>= \case
("src", url) -> return url
_ -> []
_ -> []
isLocalUrl :: Text -> Bool
isLocalUrl url = not
( ("//" `Text.isPrefixOf` url)
|| ("http://" `Text.isPrefixOf` url)
|| ("https://" `Text.isPrefixOf` url)
)
extractCssUrls :: [CSS.Token] -> [Text]
extractCssUrls tokens = filter isLocalUrl $ go tokens
where
go (CSS.Url url:xs) = url:go xs
go (CSS.Function "url":CSS.String url:xs) = url:go xs
go (x:xs) = go xs
go _ = []
| null | https://raw.githubusercontent.com/tdammers/sprinkles/a9161e4506427a3cf5f686654edc7ed9aa3ea82b/src/Web/Sprinkles/Bake.hs | haskell | #LANGUAGE OverloadedStrings # | # LANGUAGE NoImplicitPrelude #
# LANGUAGE OverloadedLists #
# LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE FlexibleInstances #
# LANGUAGE FlexibleContexts #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
module Web.Sprinkles.Bake
where
import Web.Sprinkles.Prelude
import qualified Data.Text as Text
import Data.Text (Text)
import qualified Data.Set as Set
import Data.Set (Set)
import System.Directory (createDirectoryIfMissing)
import System.FilePath ( (</>), takeDirectory, replaceExtension )
import Control.Monad.State
import Control.Lens
import Control.Lens.TH (makeLenses)
import Text.Printf (printf)
import Network.HTTP.Types (Status (..), status200)
import Network.Wai.Test
import Network.Wai (Application, Request (..))
import qualified Network.Wai as Wai
import Web.Sprinkles.Serve (appFromProject)
import Web.Sprinkles.Project
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString as BS
import Data.Char (ord)
import Text.HTML.TagSoup (parseTags, Tag (..), Attribute)
import qualified Data.CSS.Syntax.Tokens as CSS
import Data.FileEmbed (embedStringFile)
defHtaccess :: ByteString
defHtaccess = $(embedStringFile "embedded/.htaccess")
data BakeState
= BakeState
{ _bsTodo :: [FilePath]
, _bsDone :: Set FilePath
, _bsBasedir :: FilePath
, _bsApp :: Application
}
makeLenses ''BakeState
defBakeState :: BakeState
defBakeState = BakeState [] Set.empty "." defaultApplication
defaultApplication :: Application
defaultApplication rq respond =
respond $
Wai.responseLBS
status200
[("Content-type", "text/plain;charset=utf8")]
"Hello, world!"
type Bake = StateT BakeState IO
bakeProject :: FilePath -> Project -> [FilePath] -> IO ()
bakeProject destDir project extraEntryPoints = do
putStrLn @Text $ "Baking project into " <> pack destDir
createDirectoryIfMissing True destDir
let app = appFromProject project
runBake destDir entryPoints app $ do
bakeHtaccess
bake404
bakeApp
where
entryPoints =
[ "/"
, "/sitemap.xml"
, "/favicon.ico"
, "/robots.txt"
]
++ extraEntryPoints
runBake :: FilePath -> [FilePath] -> Application -> Bake a -> IO a
runBake baseDir entryPoints app a =
evalStateT a $ defBakeState
{ _bsTodo = entryPoints
, _bsBasedir = baseDir
, _bsApp = app
}
bakeHtaccess :: Bake ()
bakeHtaccess = do
basedir <- use bsBasedir
liftIO $ writeFile (basedir </> ".htaccess") defHtaccess
bakeApp :: Bake ()
bakeApp = do
use bsTodo >>= \case
(current:rest) -> do
bsTodo .= rest
bakePath current
bsDone %= Set.insert current
bakeApp
_ -> return ()
bakePath :: FilePath -> Bake ()
bakePath fp = do
done <- use bsDone
unless (fp `Set.member` done) $
bakePage CreateIndexHtml [200] fp (dropLeadingSlash fp)
data HtmlMappingMode = MapHtmlDirect | CreateIndexHtml
bake404 :: Bake ()
bake404 = do
bakePage MapHtmlDirect [404] nonsensicalPath "_errors/404"
where
nonsensicalPath = "/123087408972309872109873012984709218371209847123"
dropLeadingSlash :: FilePath -> FilePath
dropLeadingSlash = \case
'/':x -> x
x -> x
bakePage :: HtmlMappingMode -> [Int] -> FilePath -> FilePath -> Bake ()
bakePage htmlMode expectedStatuses fp fn = do
app <- use bsApp
basedir <- use bsBasedir
let dstFile = basedir </> fn
dstDir = takeDirectory dstFile
let session = do
let rq = setPath defaultRequest (fromString fp)
request rq
rp <- liftIO $ runSession session app
let status = simpleStatus rp
liftIO $ printf "GET %s %i %s\n" ("/" </> fp) (statusCode status) (decodeUtf8 $ statusMessage status)
if statusCode status `elem` expectedStatuses
then do
let ty = fromMaybe "application/octet-stream" $ lookup "content-type" (simpleHeaders rp)
rawTy = BS.takeWhile (/= fromIntegral (ord ';')) ty
rawTySplit = BS.split (fromIntegral . ord $ '/') rawTy
liftIO $ printf "%s\n" (decodeUtf8 ty)
let (linkUrls, dstDir', dstFile') = case rawTySplit of
["text", "html"] ->
let body = LBS.toStrict $ simpleBody rp
soup = parseTags (decodeUtf8 body)
linkUrls = map (fp </>) . map Text.unpack $ extractLinkedUrls soup
in case htmlMode of
CreateIndexHtml ->
(linkUrls, dstFile, dstFile </> "index.html")
MapHtmlDirect ->
(linkUrls, dstDir, replaceExtension dstFile "html")
[_, "css"] ->
let body = decodeUtf8 . LBS.toStrict $ simpleBody rp
tokens = CSS.tokenize body
linkUrls = map (takeDirectory fp </>) . map Text.unpack $ extractCssUrls tokens
in (linkUrls, dstDir, dstFile)
_ ->
([], dstDir, dstFile)
liftIO $ do
createDirectoryIfMissing True dstDir'
LBS.writeFile dstFile' (simpleBody rp)
bsTodo <>= linkUrls
else do
liftIO $ putStrLn @String "skip"
extractLinkedUrls :: [Tag Text] -> [Text]
extractLinkedUrls tags = filter isLocalUrl $ do
tags >>= \case
TagOpen "a" attrs -> do
attrs >>= \case
("href", url) -> return url
_ -> []
TagOpen "link" attrs -> do
attrs >>= \case
("href", url) -> return url
_ -> []
TagOpen "script" attrs -> do
attrs >>= \case
("src", url) -> return url
_ -> []
TagOpen "img" attrs -> do
attrs >>= \case
("src", url) -> return url
_ -> []
_ -> []
isLocalUrl :: Text -> Bool
isLocalUrl url = not
( ("//" `Text.isPrefixOf` url)
|| ("http://" `Text.isPrefixOf` url)
|| ("https://" `Text.isPrefixOf` url)
)
extractCssUrls :: [CSS.Token] -> [Text]
extractCssUrls tokens = filter isLocalUrl $ go tokens
where
go (CSS.Url url:xs) = url:go xs
go (CSS.Function "url":CSS.String url:xs) = url:go xs
go (x:xs) = go xs
go _ = []
|
53a37a1fc2ba65b64a0985b3bf26aa1cc5e08f5c294eb4071259fd16ab2d003e | mokus0/junkbox | MergeSort.hs | # LANGUAGE
MagicHash , UnboxedTuples
#
MagicHash, UnboxedTuples
#-}
module Functions.MergeSort where
import Data.Array.Simple
import Data.Bits
import Control.Monad
import Control.Monad.ST
a ! i = marray_read a i
copy_array a = array_new (array_size a) (array_index a)
mergeSort a = runST $ do
a <- array_thaw (copy_array a)
marray_merge_sort a
marray_freeze a
marray_merge_sort a = go 0 sz
where
sz = marray_size a
go off 0 = return ()
go off 1 = return ()
go off 2 = do
x <- a ! off
y <- a ! (off + 1)
when (x>y) $ do
marray_write a off y
marray_write a (off+1) x
go off n = do
let p = n `shiftR` 1
q = n - p
go off p
go (off+p) q
merge off p (p+q)
merge off p q = undefined | null | https://raw.githubusercontent.com/mokus0/junkbox/151014bbef9db2b9205209df66c418d6d58b0d9e/Haskell/Functions/MergeSort.hs | haskell | # LANGUAGE
MagicHash , UnboxedTuples
#
MagicHash, UnboxedTuples
#-}
module Functions.MergeSort where
import Data.Array.Simple
import Data.Bits
import Control.Monad
import Control.Monad.ST
a ! i = marray_read a i
copy_array a = array_new (array_size a) (array_index a)
mergeSort a = runST $ do
a <- array_thaw (copy_array a)
marray_merge_sort a
marray_freeze a
marray_merge_sort a = go 0 sz
where
sz = marray_size a
go off 0 = return ()
go off 1 = return ()
go off 2 = do
x <- a ! off
y <- a ! (off + 1)
when (x>y) $ do
marray_write a off y
marray_write a (off+1) x
go off n = do
let p = n `shiftR` 1
q = n - p
go off p
go (off+p) q
merge off p (p+q)
merge off p q = undefined |
|
fff271a2d5b0310428b456ef239c278e781a3350c45334aed4655825fdbeec29 | ocaml-multicore/tezos | base.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2020 - 2021 Nomadic Labs < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
(* We let some exceptions propagate. They are caught when running tests and
logged as errors. We want to print a human-readable version of those errors.
Exceptions that should be caught, such as [Not_found] or [End_of_file],
do not need a human-readable version. *)
let () =
Printexc.register_printer @@ function
| Unix.Unix_error (error, _, _) -> Some (Unix.error_message error)
| Failure error -> Some error
| Sys_error error -> Some error
| _ -> None
let ( // ) = Filename.concat
let sf = Printf.sprintf
let ( let* ) = Lwt.bind
let ( and* ) = Lwt.both
let ( and*! ) a b =
let (main_promise, main_awakener) = Lwt.task () in
let already_woke_up = ref false in
Lwt.on_failure a (fun exn ->
if not !already_woke_up then (
already_woke_up := true ;
Lwt.wakeup_exn main_awakener exn) ;
Lwt.cancel b) ;
Lwt.on_failure b (fun exn ->
if not !already_woke_up then (
already_woke_up := true ;
Lwt.wakeup_exn main_awakener exn) ;
Lwt.cancel a) ;
let both = Lwt.both a b in
Lwt.on_success both (fun x -> Lwt.wakeup main_awakener x) ;
Lwt.on_cancel main_promise (fun () -> Lwt.cancel both) ;
main_promise
let return = Lwt.return
let unit = Lwt.return_unit
let none = Lwt.return_none
let some = Lwt.return_some
let mandatory name = function
| None -> failwith ("no value for " ^ name)
| Some x -> x
let range a b =
let rec range ?(acc = []) a b =
if b < a then acc else range ~acc:(b :: acc) a (b - 1)
in
range a b
let rec list_find_map f = function
| [] -> None
| head :: tail -> (
match f head with None -> list_find_map f tail | Some _ as x -> x)
type rex = string * Re.re
let rec take n l =
if n < 0 then invalid_arg "Tezt.Base.take: argument cannot be negative"
else if n = 0 then []
else match l with [] -> [] | hd :: rest -> hd :: take (n - 1) rest
let rec drop n l =
if n < 0 then invalid_arg "Tezt.Base.drop: argument cannot be negative"
else if n = 0 then l
else match l with [] -> [] | _ :: rest -> drop (n - 1) rest
let rex ?opts r = (r, Re.compile (Re.Perl.re ?opts r))
let show_rex = fst
let ( =~ ) s (_, r) = Re.execp r s
let ( =~! ) s (_, r) = not (Re.execp r s)
let get_group group index =
match Re.Group.get group index with
| exception Not_found ->
invalid_arg
"regular expression has not enough capture groups for its usage, did \
you forget parentheses?"
| value -> value
let ( =~* ) s (_, r) =
match Re.exec_opt r s with
| None -> None
| Some group -> Some (get_group group 1)
let ( =~** ) s (_, r) =
match Re.exec_opt r s with
| None -> None
| Some group -> Some (get_group group 1, get_group group 2)
let replace_string ?pos ?len ?all (_, r) ~by s =
Re.replace_string ?pos ?len ?all r ~by s
let rec repeat n f =
if n <= 0 then unit
else
let* () = f () in
repeat (n - 1) f
let fold n init f =
let rec aux k accu =
if k >= n then return accu
else
let* accu = f k accu in
aux (k + 1) accu
in
aux 0 init
let with_open_out file write_f =
let chan = open_out file in
try
write_f chan ;
close_out chan
with x ->
close_out chan ;
raise x
let with_open_in file read_f =
let chan = open_in file in
try
let value = read_f chan in
close_in chan ;
value
with x ->
close_in chan ;
raise x
let read_file filename =
let* ic = Lwt_io.open_file ~mode:Lwt_io.Input filename in
Lwt_io.read ic
module String_map = Map.Make (String)
module String_set = Set.Make (String)
| null | https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/tezt/lib/base.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
We let some exceptions propagate. They are caught when running tests and
logged as errors. We want to print a human-readable version of those errors.
Exceptions that should be caught, such as [Not_found] or [End_of_file],
do not need a human-readable version. | Copyright ( c ) 2020 - 2021 Nomadic Labs < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
let () =
Printexc.register_printer @@ function
| Unix.Unix_error (error, _, _) -> Some (Unix.error_message error)
| Failure error -> Some error
| Sys_error error -> Some error
| _ -> None
let ( // ) = Filename.concat
let sf = Printf.sprintf
let ( let* ) = Lwt.bind
let ( and* ) = Lwt.both
let ( and*! ) a b =
let (main_promise, main_awakener) = Lwt.task () in
let already_woke_up = ref false in
Lwt.on_failure a (fun exn ->
if not !already_woke_up then (
already_woke_up := true ;
Lwt.wakeup_exn main_awakener exn) ;
Lwt.cancel b) ;
Lwt.on_failure b (fun exn ->
if not !already_woke_up then (
already_woke_up := true ;
Lwt.wakeup_exn main_awakener exn) ;
Lwt.cancel a) ;
let both = Lwt.both a b in
Lwt.on_success both (fun x -> Lwt.wakeup main_awakener x) ;
Lwt.on_cancel main_promise (fun () -> Lwt.cancel both) ;
main_promise
let return = Lwt.return
let unit = Lwt.return_unit
let none = Lwt.return_none
let some = Lwt.return_some
let mandatory name = function
| None -> failwith ("no value for " ^ name)
| Some x -> x
let range a b =
let rec range ?(acc = []) a b =
if b < a then acc else range ~acc:(b :: acc) a (b - 1)
in
range a b
let rec list_find_map f = function
| [] -> None
| head :: tail -> (
match f head with None -> list_find_map f tail | Some _ as x -> x)
type rex = string * Re.re
let rec take n l =
if n < 0 then invalid_arg "Tezt.Base.take: argument cannot be negative"
else if n = 0 then []
else match l with [] -> [] | hd :: rest -> hd :: take (n - 1) rest
let rec drop n l =
if n < 0 then invalid_arg "Tezt.Base.drop: argument cannot be negative"
else if n = 0 then l
else match l with [] -> [] | _ :: rest -> drop (n - 1) rest
let rex ?opts r = (r, Re.compile (Re.Perl.re ?opts r))
let show_rex = fst
let ( =~ ) s (_, r) = Re.execp r s
let ( =~! ) s (_, r) = not (Re.execp r s)
let get_group group index =
match Re.Group.get group index with
| exception Not_found ->
invalid_arg
"regular expression has not enough capture groups for its usage, did \
you forget parentheses?"
| value -> value
let ( =~* ) s (_, r) =
match Re.exec_opt r s with
| None -> None
| Some group -> Some (get_group group 1)
let ( =~** ) s (_, r) =
match Re.exec_opt r s with
| None -> None
| Some group -> Some (get_group group 1, get_group group 2)
let replace_string ?pos ?len ?all (_, r) ~by s =
Re.replace_string ?pos ?len ?all r ~by s
let rec repeat n f =
if n <= 0 then unit
else
let* () = f () in
repeat (n - 1) f
let fold n init f =
let rec aux k accu =
if k >= n then return accu
else
let* accu = f k accu in
aux (k + 1) accu
in
aux 0 init
let with_open_out file write_f =
let chan = open_out file in
try
write_f chan ;
close_out chan
with x ->
close_out chan ;
raise x
let with_open_in file read_f =
let chan = open_in file in
try
let value = read_f chan in
close_in chan ;
value
with x ->
close_in chan ;
raise x
let read_file filename =
let* ic = Lwt_io.open_file ~mode:Lwt_io.Input filename in
Lwt_io.read ic
module String_map = Map.Make (String)
module String_set = Set.Make (String)
|
91f7a3dd95912ae9b24de10e7c33d9cab18104b732213a13e8b2b0c0be13d515 | EMSL-NMR-EPR/Haskell-MFAPipe-Executable | Main.hs | -----------------------------------------------------------------------------
-- |
-- Module : Main
Copyright : 2016 - 17 Pacific Northwest National Laboratory
-- License : ECL-2.0 (see the LICENSE file in the distribution)
--
-- Maintainer :
-- Stability : experimental
-- Portability : portable
--
Entry point for the \"mfaPipe\ " command line application .
-----------------------------------------------------------------------------
import qualified Data.Default
import Data.LinearProgram.GLPK.Solver (GLPOpts(..))
import qualified Data.LinearProgram.GLPK.Solver
import qualified Data.Version
import MFAPipe.Command (Command(..))
import qualified MFAPipe.Command
import qualified MFAPipe.Version
import Numeric.LevMar (Options(..))
import qualified Numeric.LevMar
import System.Console.CmdArgs.Implicit (CmdArgs, Mode, (&=))
import qualified System.Console.CmdArgs.Implicit
import qualified Text.Printf
main :: IO ()
main = System.Console.CmdArgs.Implicit.cmdArgsRun mode >>= MFAPipe.Command.runCommand
where
mode :: Mode (CmdArgs Command)
mode = System.Console.CmdArgs.Implicit.cmdArgsMode $
System.Console.CmdArgs.Implicit.modes
[ let
seed :: Int
seed = 0
itMax :: Int
itMax = 100
opts :: Options Double
opts = Numeric.LevMar.defaultOpts
in
DoMFAUsingLevMar
{ input = Data.Default.def
&= System.Console.CmdArgs.Implicit.typFile
, output = Data.Default.def
&= System.Console.CmdArgs.Implicit.typFile
, _seed = seed
&= System.Console.CmdArgs.Implicit.explicit
&= System.Console.CmdArgs.Implicit.name "seed"
&= System.Console.CmdArgs.Implicit.help (Text.Printf.printf "Seed for random number generator (default: %d)." seed)
, _itMax = itMax
&= System.Console.CmdArgs.Implicit.explicit
&= System.Console.CmdArgs.Implicit.name "max-iterations"
&= System.Console.CmdArgs.Implicit.help (Text.Printf.printf "Maximum iterations (default: %d)." itMax)
, _optScaleInitMu = optScaleInitMu opts
&= System.Console.CmdArgs.Implicit.explicit
&= System.Console.CmdArgs.Implicit.name "scale-init-mu"
&= System.Console.CmdArgs.Implicit.help (Text.Printf.printf "Scale factor for initial mu (default: %f)." (optScaleInitMu opts))
&= System.Console.CmdArgs.Implicit.groupname "Minimization options"
, _optStopNormInfJacTe = optStopNormInfJacTe opts
&= System.Console.CmdArgs.Implicit.explicit
&= System.Console.CmdArgs.Implicit.name "stop-norm-inf-jac-te"
&= System.Console.CmdArgs.Implicit.help (Text.Printf.printf "Stopping thresholds for ||J^T e||_inf (default: %f)." (optStopNormInfJacTe opts))
&= System.Console.CmdArgs.Implicit.groupname "Minimization options"
, _optStopNorm2Dp = optStopNorm2Dp opts
&= System.Console.CmdArgs.Implicit.explicit
&= System.Console.CmdArgs.Implicit.name "stop-norm2-dp"
&= System.Console.CmdArgs.Implicit.help (Text.Printf.printf "Stopping thresholds for ||Dp||_2 (default: %f)." (optStopNorm2Dp opts))
&= System.Console.CmdArgs.Implicit.groupname "Minimization options"
, _optStopNorm2E = optStopNorm2E opts
&= System.Console.CmdArgs.Implicit.explicit
&= System.Console.CmdArgs.Implicit.name "stop-norm2-e"
&= System.Console.CmdArgs.Implicit.help (Text.Printf.printf "Stopping thresholds for ||e||_2 (default: %f)." (optStopNorm2E opts))
&= System.Console.CmdArgs.Implicit.groupname "Minimization options"
, _optDelta = optDelta opts
&= System.Console.CmdArgs.Implicit.explicit
&= System.Console.CmdArgs.Implicit.name "delta"
&= System.Console.CmdArgs.Implicit.help (Text.Printf.printf "Step used in the difference approximation to the Jacobian (default: %f). If delta<0, the Jacobian is approximated with central differences which are more accurate (but slower!) compared to the forward differences employed by default." (optDelta opts))
&= System.Console.CmdArgs.Implicit.groupname "Minimization options"
}
&= System.Console.CmdArgs.Implicit.name "mfa-levmar"
&= System.Console.CmdArgs.Implicit.help "Metabolic Flux Analysis (MFA) using the Levenberg-Marquardt algorithm"
, let
opts :: GLPOpts
opts = Data.LinearProgram.GLPK.Solver.simplexDefaults
in
DoFBAUsingSimplex
{ input = Data.Default.def
&= System.Console.CmdArgs.Implicit.typFile
, output = Data.Default.def
&= System.Console.CmdArgs.Implicit.typFile
, _tmLim = tmLim opts
&= System.Console.CmdArgs.Implicit.explicit
&= System.Console.CmdArgs.Implicit.name "tm-lim"
, _presolve = presolve opts
&= System.Console.CmdArgs.Implicit.explicit
&= System.Console.CmdArgs.Implicit.name "presolve"
}
&= System.Console.CmdArgs.Implicit.name "fba-simplex"
&= System.Console.CmdArgs.Implicit.help "Flux Balance Analysis (FBA) using the Simplex algorithm"
, let
opts :: GLPOpts
opts = Data.LinearProgram.GLPK.Solver.mipDefaults
in
DoFBAUsingMIP
{ input = Data.Default.def
&= System.Console.CmdArgs.Implicit.typFile
, output = Data.Default.def
&= System.Console.CmdArgs.Implicit.typFile
, _tmLim = tmLim opts
&= System.Console.CmdArgs.Implicit.explicit
&= System.Console.CmdArgs.Implicit.name "tm-lim"
, _presolve = presolve opts
&= System.Console.CmdArgs.Implicit.explicit
&= System.Console.CmdArgs.Implicit.name "presolve"
}
&= System.Console.CmdArgs.Implicit.name "fba-mip"
&= System.Console.CmdArgs.Implicit.help "Flux Balance Analysis (FBA) using Mixed Integer Programming (MIP)"
]
&= System.Console.CmdArgs.Implicit.help "MFAPipe - a command line application for parallel labeling, steady state Metabolic Flux Analysis (MFA) and Flux Balance Analysis (FBA), using the stoichiometric paradigm and Elementary Metabolite Units (EMU) method"
&= System.Console.CmdArgs.Implicit.program "mfaPipe"
&= System.Console.CmdArgs.Implicit.summary (Text.Printf.printf "MFAPipe v%s, (C) 2016 Pacific Northwest National Laboratory" (Data.Version.showVersion MFAPipe.Version.version))
| null | https://raw.githubusercontent.com/EMSL-NMR-EPR/Haskell-MFAPipe-Executable/8a7fd13202d3b6b7380af52d86e851e995a9b53e/MFAPipe/app/Main.hs | haskell | ---------------------------------------------------------------------------
|
Module : Main
License : ECL-2.0 (see the LICENSE file in the distribution)
Maintainer :
Stability : experimental
Portability : portable
--------------------------------------------------------------------------- | Copyright : 2016 - 17 Pacific Northwest National Laboratory
Entry point for the \"mfaPipe\ " command line application .
import qualified Data.Default
import Data.LinearProgram.GLPK.Solver (GLPOpts(..))
import qualified Data.LinearProgram.GLPK.Solver
import qualified Data.Version
import MFAPipe.Command (Command(..))
import qualified MFAPipe.Command
import qualified MFAPipe.Version
import Numeric.LevMar (Options(..))
import qualified Numeric.LevMar
import System.Console.CmdArgs.Implicit (CmdArgs, Mode, (&=))
import qualified System.Console.CmdArgs.Implicit
import qualified Text.Printf
main :: IO ()
main = System.Console.CmdArgs.Implicit.cmdArgsRun mode >>= MFAPipe.Command.runCommand
where
mode :: Mode (CmdArgs Command)
mode = System.Console.CmdArgs.Implicit.cmdArgsMode $
System.Console.CmdArgs.Implicit.modes
[ let
seed :: Int
seed = 0
itMax :: Int
itMax = 100
opts :: Options Double
opts = Numeric.LevMar.defaultOpts
in
DoMFAUsingLevMar
{ input = Data.Default.def
&= System.Console.CmdArgs.Implicit.typFile
, output = Data.Default.def
&= System.Console.CmdArgs.Implicit.typFile
, _seed = seed
&= System.Console.CmdArgs.Implicit.explicit
&= System.Console.CmdArgs.Implicit.name "seed"
&= System.Console.CmdArgs.Implicit.help (Text.Printf.printf "Seed for random number generator (default: %d)." seed)
, _itMax = itMax
&= System.Console.CmdArgs.Implicit.explicit
&= System.Console.CmdArgs.Implicit.name "max-iterations"
&= System.Console.CmdArgs.Implicit.help (Text.Printf.printf "Maximum iterations (default: %d)." itMax)
, _optScaleInitMu = optScaleInitMu opts
&= System.Console.CmdArgs.Implicit.explicit
&= System.Console.CmdArgs.Implicit.name "scale-init-mu"
&= System.Console.CmdArgs.Implicit.help (Text.Printf.printf "Scale factor for initial mu (default: %f)." (optScaleInitMu opts))
&= System.Console.CmdArgs.Implicit.groupname "Minimization options"
, _optStopNormInfJacTe = optStopNormInfJacTe opts
&= System.Console.CmdArgs.Implicit.explicit
&= System.Console.CmdArgs.Implicit.name "stop-norm-inf-jac-te"
&= System.Console.CmdArgs.Implicit.help (Text.Printf.printf "Stopping thresholds for ||J^T e||_inf (default: %f)." (optStopNormInfJacTe opts))
&= System.Console.CmdArgs.Implicit.groupname "Minimization options"
, _optStopNorm2Dp = optStopNorm2Dp opts
&= System.Console.CmdArgs.Implicit.explicit
&= System.Console.CmdArgs.Implicit.name "stop-norm2-dp"
&= System.Console.CmdArgs.Implicit.help (Text.Printf.printf "Stopping thresholds for ||Dp||_2 (default: %f)." (optStopNorm2Dp opts))
&= System.Console.CmdArgs.Implicit.groupname "Minimization options"
, _optStopNorm2E = optStopNorm2E opts
&= System.Console.CmdArgs.Implicit.explicit
&= System.Console.CmdArgs.Implicit.name "stop-norm2-e"
&= System.Console.CmdArgs.Implicit.help (Text.Printf.printf "Stopping thresholds for ||e||_2 (default: %f)." (optStopNorm2E opts))
&= System.Console.CmdArgs.Implicit.groupname "Minimization options"
, _optDelta = optDelta opts
&= System.Console.CmdArgs.Implicit.explicit
&= System.Console.CmdArgs.Implicit.name "delta"
&= System.Console.CmdArgs.Implicit.help (Text.Printf.printf "Step used in the difference approximation to the Jacobian (default: %f). If delta<0, the Jacobian is approximated with central differences which are more accurate (but slower!) compared to the forward differences employed by default." (optDelta opts))
&= System.Console.CmdArgs.Implicit.groupname "Minimization options"
}
&= System.Console.CmdArgs.Implicit.name "mfa-levmar"
&= System.Console.CmdArgs.Implicit.help "Metabolic Flux Analysis (MFA) using the Levenberg-Marquardt algorithm"
, let
opts :: GLPOpts
opts = Data.LinearProgram.GLPK.Solver.simplexDefaults
in
DoFBAUsingSimplex
{ input = Data.Default.def
&= System.Console.CmdArgs.Implicit.typFile
, output = Data.Default.def
&= System.Console.CmdArgs.Implicit.typFile
, _tmLim = tmLim opts
&= System.Console.CmdArgs.Implicit.explicit
&= System.Console.CmdArgs.Implicit.name "tm-lim"
, _presolve = presolve opts
&= System.Console.CmdArgs.Implicit.explicit
&= System.Console.CmdArgs.Implicit.name "presolve"
}
&= System.Console.CmdArgs.Implicit.name "fba-simplex"
&= System.Console.CmdArgs.Implicit.help "Flux Balance Analysis (FBA) using the Simplex algorithm"
, let
opts :: GLPOpts
opts = Data.LinearProgram.GLPK.Solver.mipDefaults
in
DoFBAUsingMIP
{ input = Data.Default.def
&= System.Console.CmdArgs.Implicit.typFile
, output = Data.Default.def
&= System.Console.CmdArgs.Implicit.typFile
, _tmLim = tmLim opts
&= System.Console.CmdArgs.Implicit.explicit
&= System.Console.CmdArgs.Implicit.name "tm-lim"
, _presolve = presolve opts
&= System.Console.CmdArgs.Implicit.explicit
&= System.Console.CmdArgs.Implicit.name "presolve"
}
&= System.Console.CmdArgs.Implicit.name "fba-mip"
&= System.Console.CmdArgs.Implicit.help "Flux Balance Analysis (FBA) using Mixed Integer Programming (MIP)"
]
&= System.Console.CmdArgs.Implicit.help "MFAPipe - a command line application for parallel labeling, steady state Metabolic Flux Analysis (MFA) and Flux Balance Analysis (FBA), using the stoichiometric paradigm and Elementary Metabolite Units (EMU) method"
&= System.Console.CmdArgs.Implicit.program "mfaPipe"
&= System.Console.CmdArgs.Implicit.summary (Text.Printf.printf "MFAPipe v%s, (C) 2016 Pacific Northwest National Laboratory" (Data.Version.showVersion MFAPipe.Version.version))
|
0353c1fb9687d966f7f0532db7ee9ede77bf2659de560a4812f5759183fb03ed | EligiusSantori/L2Apf | validate_auth.scm | (module system racket/base
(provide game-client-packet/validate-auth)
(require srfi/1 "../../packet.scm")
(define (game-client-packet/validate-auth struct)
(let ((s (open-output-bytes)) (lk (or (cdr (assoc 'login-key struct)) (make-bytes 8))) (gk (cdr (assoc 'game-key struct))))
(begin
(write-byte #x08 s)
(write-utf16 (cdr (assoc 'login struct)) s)
(write-bytes (subbytes gk 4 8) s)
(write-bytes (subbytes gk 0 4) s)
(write-bytes (subbytes lk 0 4) s)
(write-bytes (subbytes lk 4 8) s)
(write-int32 1 #f s)
(get-output-bytes s)
)
)
)
)
| null | https://raw.githubusercontent.com/EligiusSantori/L2Apf/30ffe0828e8a401f58d39984efd862c8aeab8c30/packet/game/client/validate_auth.scm | scheme | (module system racket/base
(provide game-client-packet/validate-auth)
(require srfi/1 "../../packet.scm")
(define (game-client-packet/validate-auth struct)
(let ((s (open-output-bytes)) (lk (or (cdr (assoc 'login-key struct)) (make-bytes 8))) (gk (cdr (assoc 'game-key struct))))
(begin
(write-byte #x08 s)
(write-utf16 (cdr (assoc 'login struct)) s)
(write-bytes (subbytes gk 4 8) s)
(write-bytes (subbytes gk 0 4) s)
(write-bytes (subbytes lk 0 4) s)
(write-bytes (subbytes lk 4 8) s)
(write-int32 1 #f s)
(get-output-bytes s)
)
)
)
)
|
|
1eba12175271c77e1ea2d1828b78ce698646ef7cd60740d72b821c3f9472270a | kind2-mc/kind2 | lustreTypeChecker.mli | This file is part of the Kind 2 model checker .
Copyright ( c ) 2020 by the Board of Trustees of the University of Iowa
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you
may not use this file except in compliance with the License . You
may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or
implied . See the License for the specific language governing
permissions and limitations under the License .
Copyright (c) 2020 by the Board of Trustees of the University of Iowa
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.
*)
* Functions for type checking surface syntax [ LustreAst ]
@author
@author Apoorv Ingle *)
module LA = LustreAst
open TypeCheckerContext
type error_kind = Unknown of string
| Impossible of string
| MergeCaseExtraneous of HString.t * tc_type
| MergeCaseMissing of HString.t
| MergeCaseNotUnique of HString.t
| UnboundIdentifier of HString.t
| UnboundModeReference of HString.t
| NotAFieldOfRecord of HString.t
| NoValueForRecordField of HString.t
| IlltypedRecordProjection of tc_type
| TupleIndexOutOfBounds of int * tc_type
| IlltypedTupleProjection of tc_type
| UnequalIteBranchTypes of tc_type * tc_type
| ExpectedBooleanExpression of tc_type
| Unsupported of string
| UnequalArrayExpressionType
| ExpectedNumeralArrayBound
| TypeMismatchOfRecordLabel of HString.t * tc_type * tc_type
| IlltypedRecordUpdate of tc_type
| ExpectedLabel of LA.expr
| IlltypedArraySlice of tc_type
| ExpectedIntegerTypeForSlice
| IlltypedArrayIndex of tc_type
| ExpectedIntegerTypeForArrayIndex of tc_type
| IlltypedArrayConcat of bool * tc_type * tc_type option
| IlltypedDefaults
| IlltypedMerge of tc_type
| IlltypedFby of tc_type * tc_type
| IlltypedArrow of tc_type * tc_type
| IlltypedCall of tc_type * tc_type
| ExpectedFunctionType of tc_type
| IlltypedIdentifier of HString.t * tc_type * tc_type
| UnificationFailed of tc_type * tc_type
| ExpectedType of tc_type * tc_type
| EmptyArrayExpression
| ExpectedArrayType of tc_type
| MismatchedNodeType of HString.t * tc_type * tc_type
| IlltypedBitNot of tc_type
| IlltypedUnaryMinus of tc_type
| ExpectedIntegerTypes of tc_type * tc_type
| ExpectedNumberTypes of tc_type * tc_type
| ExpectedMachineIntegerTypes of tc_type * tc_type
| ExpectedBitShiftConstant
| ExpectedBitShiftConstantOfSameWidth of tc_type
| ExpectedBitShiftMachineIntegerType of tc_type
| InvalidConversion of tc_type * tc_type
| NodeArgumentOnLHS of HString.t
| NodeInputOutputShareIdentifier of ty_set
| MismatchOfEquationType of LA.struct_item list option * tc_type
| DisallowedReassignment of ty_set
| DisallowedSubrangeInContractReturn of bool * HString.t * tc_type
| AssumptionMustBeInputOrOutput of HString.t
| Redeclaration of HString.t
| ExpectedConstant of LA.expr
| ArrayBoundsInvalidExpression
| UndeclaredType of HString.t
| EmptySubrange of int * int
| SubrangeArgumentMustBeConstantInteger of LA.expr
| ExpectedRecordType of tc_type
type error = [
| `LustreTypeCheckerError of Lib.position * error_kind
| `LustreSyntaxChecksError of Lib.position * LustreSyntaxChecks.error_kind
| `LustreAstInlineConstantsError of Lib.position * LustreAstInlineConstants.error_kind
]
val error_message: error_kind -> string
val type_error: Lib.position -> error_kind -> ('a, [> error]) result
(** [type_error] returns an [Error] of [tc_result] *)
val type_check_infer_globals: tc_context -> LA.t -> (tc_context, [> error]) result
(** Typechecks the toplevel globals i.e. constant decls and type decls. It returns
a [Ok (tc_context)] if it succeeds or and [Error of String] if the typechecker fails *)
val type_check_infer_nodes_and_contracts: tc_context -> LA.t -> (tc_context, [> error]) result
(** Typechecks and infers type for the nodes and contracts. It returns
a [Ok (tc_context)] if it succeeds or and [Error of String] if the typechecker fails *)
val tc_ctx_of_contract: ?ignore_modes:bool -> tc_context -> LA.contract -> (tc_context, [> error]) result
val local_var_binding: tc_context -> LA.node_local_decl -> (tc_context, [> error]) result
val get_node_ctx : tc_context ->
'a * 'b * 'c * LA.const_clocked_typed_decl list *
LA.clocked_typed_decl list * LA.node_local_decl list * 'd * 'e ->
(tc_context, [> error ]) result
val infer_type_expr: tc_context -> LA.expr -> (tc_type, [> error]) result
* Infer type of Lustre expression given a typing context
val eq_lustre_type : tc_context -> LA.lustre_type -> LA.lustre_type -> (bool, [> error]) result
* Check if two lustre types are equal
Local Variables :
compile - command : " make -C .. "
indent - tabs - mode : nil
End :
Local Variables:
compile-command: "make -k -C .."
indent-tabs-mode: nil
End:
*)
| null | https://raw.githubusercontent.com/kind2-mc/kind2/d34694b4461323322fdcc291aa3c3d9c453fc098/src/lustre/lustreTypeChecker.mli | ocaml | * [type_error] returns an [Error] of [tc_result]
* Typechecks the toplevel globals i.e. constant decls and type decls. It returns
a [Ok (tc_context)] if it succeeds or and [Error of String] if the typechecker fails
* Typechecks and infers type for the nodes and contracts. It returns
a [Ok (tc_context)] if it succeeds or and [Error of String] if the typechecker fails | This file is part of the Kind 2 model checker .
Copyright ( c ) 2020 by the Board of Trustees of the University of Iowa
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you
may not use this file except in compliance with the License . You
may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or
implied . See the License for the specific language governing
permissions and limitations under the License .
Copyright (c) 2020 by the Board of Trustees of the University of Iowa
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.
*)
* Functions for type checking surface syntax [ LustreAst ]
@author
@author Apoorv Ingle *)
module LA = LustreAst
open TypeCheckerContext
type error_kind = Unknown of string
| Impossible of string
| MergeCaseExtraneous of HString.t * tc_type
| MergeCaseMissing of HString.t
| MergeCaseNotUnique of HString.t
| UnboundIdentifier of HString.t
| UnboundModeReference of HString.t
| NotAFieldOfRecord of HString.t
| NoValueForRecordField of HString.t
| IlltypedRecordProjection of tc_type
| TupleIndexOutOfBounds of int * tc_type
| IlltypedTupleProjection of tc_type
| UnequalIteBranchTypes of tc_type * tc_type
| ExpectedBooleanExpression of tc_type
| Unsupported of string
| UnequalArrayExpressionType
| ExpectedNumeralArrayBound
| TypeMismatchOfRecordLabel of HString.t * tc_type * tc_type
| IlltypedRecordUpdate of tc_type
| ExpectedLabel of LA.expr
| IlltypedArraySlice of tc_type
| ExpectedIntegerTypeForSlice
| IlltypedArrayIndex of tc_type
| ExpectedIntegerTypeForArrayIndex of tc_type
| IlltypedArrayConcat of bool * tc_type * tc_type option
| IlltypedDefaults
| IlltypedMerge of tc_type
| IlltypedFby of tc_type * tc_type
| IlltypedArrow of tc_type * tc_type
| IlltypedCall of tc_type * tc_type
| ExpectedFunctionType of tc_type
| IlltypedIdentifier of HString.t * tc_type * tc_type
| UnificationFailed of tc_type * tc_type
| ExpectedType of tc_type * tc_type
| EmptyArrayExpression
| ExpectedArrayType of tc_type
| MismatchedNodeType of HString.t * tc_type * tc_type
| IlltypedBitNot of tc_type
| IlltypedUnaryMinus of tc_type
| ExpectedIntegerTypes of tc_type * tc_type
| ExpectedNumberTypes of tc_type * tc_type
| ExpectedMachineIntegerTypes of tc_type * tc_type
| ExpectedBitShiftConstant
| ExpectedBitShiftConstantOfSameWidth of tc_type
| ExpectedBitShiftMachineIntegerType of tc_type
| InvalidConversion of tc_type * tc_type
| NodeArgumentOnLHS of HString.t
| NodeInputOutputShareIdentifier of ty_set
| MismatchOfEquationType of LA.struct_item list option * tc_type
| DisallowedReassignment of ty_set
| DisallowedSubrangeInContractReturn of bool * HString.t * tc_type
| AssumptionMustBeInputOrOutput of HString.t
| Redeclaration of HString.t
| ExpectedConstant of LA.expr
| ArrayBoundsInvalidExpression
| UndeclaredType of HString.t
| EmptySubrange of int * int
| SubrangeArgumentMustBeConstantInteger of LA.expr
| ExpectedRecordType of tc_type
type error = [
| `LustreTypeCheckerError of Lib.position * error_kind
| `LustreSyntaxChecksError of Lib.position * LustreSyntaxChecks.error_kind
| `LustreAstInlineConstantsError of Lib.position * LustreAstInlineConstants.error_kind
]
val error_message: error_kind -> string
val type_error: Lib.position -> error_kind -> ('a, [> error]) result
val type_check_infer_globals: tc_context -> LA.t -> (tc_context, [> error]) result
val type_check_infer_nodes_and_contracts: tc_context -> LA.t -> (tc_context, [> error]) result
val tc_ctx_of_contract: ?ignore_modes:bool -> tc_context -> LA.contract -> (tc_context, [> error]) result
val local_var_binding: tc_context -> LA.node_local_decl -> (tc_context, [> error]) result
val get_node_ctx : tc_context ->
'a * 'b * 'c * LA.const_clocked_typed_decl list *
LA.clocked_typed_decl list * LA.node_local_decl list * 'd * 'e ->
(tc_context, [> error ]) result
val infer_type_expr: tc_context -> LA.expr -> (tc_type, [> error]) result
* Infer type of Lustre expression given a typing context
val eq_lustre_type : tc_context -> LA.lustre_type -> LA.lustre_type -> (bool, [> error]) result
* Check if two lustre types are equal
Local Variables :
compile - command : " make -C .. "
indent - tabs - mode : nil
End :
Local Variables:
compile-command: "make -k -C .."
indent-tabs-mode: nil
End:
*)
|
05d04b4b790acbad3842850f0f9fd4c9825187cdf7c8e5b05fce02e124bcbfcc | input-output-hk/ouroboros-network | Integrity.hs | # LANGUAGE NamedFieldPuns #
module Ouroboros.Consensus.Byron.Ledger.Integrity (
verifyBlockIntegrity
, verifyHeaderIntegrity
, verifyHeaderSignature
) where
import Data.Either (isRight)
import qualified Cardano.Chain.Block as CC
import qualified Cardano.Crypto.DSIGN.Class as CC.Crypto
import Ouroboros.Consensus.Block
import Ouroboros.Consensus.Protocol.PBFT
import Ouroboros.Consensus.Byron.Ledger.Block
import Ouroboros.Consensus.Byron.Ledger.Config
import Ouroboros.Consensus.Byron.Ledger.PBFT ()
-- | Verify whether a header matches its signature.
--
-- Note that we cannot check this for an EBB, as an EBB contains no signature.
-- This function will always return 'True' for an EBB.
verifyHeaderSignature :: BlockConfig ByronBlock -> Header ByronBlock -> Bool
verifyHeaderSignature cfg hdr =
case validateView cfg hdr of
PBftValidateBoundary{} ->
-- EBB, no signature to check
True
PBftValidateRegular fields signed contextDSIGN ->
let PBftFields { pbftIssuer, pbftSignature } = fields
in isRight $ CC.Crypto.verifySignedDSIGN
contextDSIGN
pbftIssuer
signed
pbftSignature
-- | Verify whether a header is not corrupted.
--
-- The difference with 'verifyHeaderSignature' is that this function also
-- checks the integrity of the 'CC.headerProtocolMagicId' field, which is the
-- only field of a regular header that is not signed.
--
-- Note that we cannot check this for an EBB, as an EBB contains no signature.
-- This function will always return 'True' for an EBB.
verifyHeaderIntegrity :: BlockConfig ByronBlock -> Header ByronBlock -> Bool
verifyHeaderIntegrity cfg hdr =
verifyHeaderSignature cfg hdr &&
-- @CC.headerProtocolMagicId@ is the only field of a regular header that
-- is not signed, so check it manually.
case byronHeaderRaw hdr of
CC.ABOBBlockHdr h -> CC.headerProtocolMagicId h == protocolMagicId
-- EBB, we can't check it
CC.ABOBBoundaryHdr _ -> True
where
protocolMagicId = byronProtocolMagicId cfg
-- | Verifies whether the block is not corrupted by checking its signature and
-- witnesses.
--
-- This function will always return 'True' for an EBB, as we cannot check
-- anything for an EBB.
verifyBlockIntegrity :: BlockConfig ByronBlock -> ByronBlock -> Bool
verifyBlockIntegrity cfg blk =
verifyHeaderIntegrity cfg hdr &&
blockMatchesHeader hdr blk
where
hdr = getHeader blk
| null | https://raw.githubusercontent.com/input-output-hk/ouroboros-network/c82309f403e99d916a76bb4d96d6812fb0a9db81/ouroboros-consensus-byron/src/Ouroboros/Consensus/Byron/Ledger/Integrity.hs | haskell | | Verify whether a header matches its signature.
Note that we cannot check this for an EBB, as an EBB contains no signature.
This function will always return 'True' for an EBB.
EBB, no signature to check
| Verify whether a header is not corrupted.
The difference with 'verifyHeaderSignature' is that this function also
checks the integrity of the 'CC.headerProtocolMagicId' field, which is the
only field of a regular header that is not signed.
Note that we cannot check this for an EBB, as an EBB contains no signature.
This function will always return 'True' for an EBB.
@CC.headerProtocolMagicId@ is the only field of a regular header that
is not signed, so check it manually.
EBB, we can't check it
| Verifies whether the block is not corrupted by checking its signature and
witnesses.
This function will always return 'True' for an EBB, as we cannot check
anything for an EBB. | # LANGUAGE NamedFieldPuns #
module Ouroboros.Consensus.Byron.Ledger.Integrity (
verifyBlockIntegrity
, verifyHeaderIntegrity
, verifyHeaderSignature
) where
import Data.Either (isRight)
import qualified Cardano.Chain.Block as CC
import qualified Cardano.Crypto.DSIGN.Class as CC.Crypto
import Ouroboros.Consensus.Block
import Ouroboros.Consensus.Protocol.PBFT
import Ouroboros.Consensus.Byron.Ledger.Block
import Ouroboros.Consensus.Byron.Ledger.Config
import Ouroboros.Consensus.Byron.Ledger.PBFT ()
verifyHeaderSignature :: BlockConfig ByronBlock -> Header ByronBlock -> Bool
verifyHeaderSignature cfg hdr =
case validateView cfg hdr of
PBftValidateBoundary{} ->
True
PBftValidateRegular fields signed contextDSIGN ->
let PBftFields { pbftIssuer, pbftSignature } = fields
in isRight $ CC.Crypto.verifySignedDSIGN
contextDSIGN
pbftIssuer
signed
pbftSignature
verifyHeaderIntegrity :: BlockConfig ByronBlock -> Header ByronBlock -> Bool
verifyHeaderIntegrity cfg hdr =
verifyHeaderSignature cfg hdr &&
case byronHeaderRaw hdr of
CC.ABOBBlockHdr h -> CC.headerProtocolMagicId h == protocolMagicId
CC.ABOBBoundaryHdr _ -> True
where
protocolMagicId = byronProtocolMagicId cfg
verifyBlockIntegrity :: BlockConfig ByronBlock -> ByronBlock -> Bool
verifyBlockIntegrity cfg blk =
verifyHeaderIntegrity cfg hdr &&
blockMatchesHeader hdr blk
where
hdr = getHeader blk
|
2b02a4a16739702f44e27970ffd1447452f42140f64f28694ec4d09750890154 | alexandergunnarson/quantum | core.cljc | (ns quantum.audio.core)
1 . / - " Download tarball "
2 . / - Download all versions . Put in " dist " folder within jvst_examples
3 . cd to the /dist/ folder and type : " mvn assembly : assembly "
; ... but doesn't work... try it on Windows maybe?
Download VST SDK from 's website
; #input
; Put downloaded folder in jvsthost/ as vst3.0/ | null | https://raw.githubusercontent.com/alexandergunnarson/quantum/0c655af439734709566110949f9f2f482e468509/src/quantum/audio/core.cljc | clojure | ... but doesn't work... try it on Windows maybe?
#input
Put downloaded folder in jvsthost/ as vst3.0/ | (ns quantum.audio.core)
1 . / - " Download tarball "
2 . / - Download all versions . Put in " dist " folder within jvst_examples
3 . cd to the /dist/ folder and type : " mvn assembly : assembly "
Download VST SDK from 's website |
f17c9fd4363705b6dcde39002add11798ea1b56464695342b3f175a2c5541d4d | achirkin/qua-kit | LuciConsole.hs | -----------------------------------------------------------------------------
-- |
-- Module : Main
Copyright :
License : MIT
--
Maintainer :
-- Stability : experimental
--
An executable for sending and receiving simple messages .
--
-----------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Data.Aeson as JSON
import qualified Data.Text as Text
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import qualified Data.ByteString.Lazy.Char8 as BSLC
import Control.Concurrent.QSem
import Luci.Connect
import Luci.Connect.Base
import Luci.Messages
import System.Environment (getArgs)
import Data.List (stripPrefix)
import Data.Maybe (isNothing)
import Control.Monad (when)
import Data.Conduit
main :: IO ()
main = do
args <- getArgs
let sets = setSettings args RunSettings
{ host = "127.0.1.1"
, port = 7654
, logLevel = LevelInfo
, command = Nothing
}
when (isNothing $ command sets) $
putStrLn "Luci-console app. Usage:\n\
\luci-console [args..]\n\
\Parameters:\n\
\\tport=x - choose port (default: 7654)\n\
\\thost=a.b.c.d - choose host (default: 127.0.1.1)\n\
\\tloglevel=lvl - choose logging level (default: info)\n\
\\t possible levels: debug, info, warn, error\n\
\\t-c '<command>' - send a single JSON message to Luci and disconnect\n\
\\nType JSON message headers and press enter to send them."
runLuciProgram () (logLevel sets) $ luciChannels (port sets)
(Just $ host sets)
(case command sets of
Nothing -> return (awaitForever logResponse, source)
Just msg -> singleAction msg
)
return ()
where
logResponse (MessageHeader h, _) = liftIO $ do
putStr "[Server Message] "
BSLC.putStrLn $ encode h
source = do
val <- fmap eitherDecodeStrict' . liftIO $ BS.getLine
case val of
Left err -> liftIO $ putStrLn err
Right h -> yield (h, [])
source
setSettings [] s = s
setSettings (par:xs) s = case stripPrefix "port=" par of
Just n -> setSettings xs s{port = read n}
Nothing -> case stripPrefix "host=" par of
Just h -> setSettings xs s{host = BSC.pack h}
Nothing -> case stripPrefix "loglevel=" par of
Just "debug" -> setSettings xs s{logLevel = LevelDebug}
Just "info" -> setSettings xs s{logLevel = LevelInfo}
Just "warn" -> setSettings xs s{logLevel = LevelWarn}
Just "warning" -> setSettings xs s{logLevel = LevelWarn}
Just "error" -> setSettings xs s{logLevel = LevelError}
Just h -> setSettings xs s{logLevel = LevelOther $ Text.pack h}
Nothing -> if "-c" == par
then s{command = Just . BSC.pack $ unwords xs}
else setSettings xs s
singleAction :: ByteString -> LuciProgram () (Sink LuciMessage (LuciProgram ()) (), Source (LuciProgram ()) LuciMessage)
singleAction msg = do
sem <- liftIO $ newQSem 0
return (waitResults sem,source sem)
where
waitResults sem = do
m <- await
case m of
Nothing -> liftIO $ putStrLn "channel closed"
Just lm@(h,_) -> do
liftIO $ do
putStr "[Server Message] "
BSLC.putStrLn $ encode h
case parseMessage lm of
JSON.Success MsgResult{} -> liftIO (signalQSem sem)
JSON.Success MsgError{} -> liftIO (signalQSem sem)
_ -> waitResults sem
source sem = case eitherDecodeStrict' msg of
Left err -> liftIO $ putStrLn err
Right h -> yield (h, []) >> liftIO (waitQSem sem)
data RunSettings = RunSettings
{ host :: ByteString
, port :: Int
, logLevel :: LogLevel
, command :: Maybe ByteString
}
| null | https://raw.githubusercontent.com/achirkin/qua-kit/9f859e2078d5f059fb87b2f6baabcde7170d4e95/libs/hs/luci-connect/examples/LuciConsole.hs | haskell | ---------------------------------------------------------------------------
|
Module : Main
Stability : experimental
---------------------------------------------------------------------------
# LANGUAGE OverloadedStrings # | Copyright :
License : MIT
Maintainer :
An executable for sending and receiving simple messages .
module Main (main) where
import Data.Aeson as JSON
import qualified Data.Text as Text
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import qualified Data.ByteString.Lazy.Char8 as BSLC
import Control.Concurrent.QSem
import Luci.Connect
import Luci.Connect.Base
import Luci.Messages
import System.Environment (getArgs)
import Data.List (stripPrefix)
import Data.Maybe (isNothing)
import Control.Monad (when)
import Data.Conduit
main :: IO ()
main = do
args <- getArgs
let sets = setSettings args RunSettings
{ host = "127.0.1.1"
, port = 7654
, logLevel = LevelInfo
, command = Nothing
}
when (isNothing $ command sets) $
putStrLn "Luci-console app. Usage:\n\
\luci-console [args..]\n\
\Parameters:\n\
\\tport=x - choose port (default: 7654)\n\
\\thost=a.b.c.d - choose host (default: 127.0.1.1)\n\
\\tloglevel=lvl - choose logging level (default: info)\n\
\\t possible levels: debug, info, warn, error\n\
\\t-c '<command>' - send a single JSON message to Luci and disconnect\n\
\\nType JSON message headers and press enter to send them."
runLuciProgram () (logLevel sets) $ luciChannels (port sets)
(Just $ host sets)
(case command sets of
Nothing -> return (awaitForever logResponse, source)
Just msg -> singleAction msg
)
return ()
where
logResponse (MessageHeader h, _) = liftIO $ do
putStr "[Server Message] "
BSLC.putStrLn $ encode h
source = do
val <- fmap eitherDecodeStrict' . liftIO $ BS.getLine
case val of
Left err -> liftIO $ putStrLn err
Right h -> yield (h, [])
source
setSettings [] s = s
setSettings (par:xs) s = case stripPrefix "port=" par of
Just n -> setSettings xs s{port = read n}
Nothing -> case stripPrefix "host=" par of
Just h -> setSettings xs s{host = BSC.pack h}
Nothing -> case stripPrefix "loglevel=" par of
Just "debug" -> setSettings xs s{logLevel = LevelDebug}
Just "info" -> setSettings xs s{logLevel = LevelInfo}
Just "warn" -> setSettings xs s{logLevel = LevelWarn}
Just "warning" -> setSettings xs s{logLevel = LevelWarn}
Just "error" -> setSettings xs s{logLevel = LevelError}
Just h -> setSettings xs s{logLevel = LevelOther $ Text.pack h}
Nothing -> if "-c" == par
then s{command = Just . BSC.pack $ unwords xs}
else setSettings xs s
singleAction :: ByteString -> LuciProgram () (Sink LuciMessage (LuciProgram ()) (), Source (LuciProgram ()) LuciMessage)
singleAction msg = do
sem <- liftIO $ newQSem 0
return (waitResults sem,source sem)
where
waitResults sem = do
m <- await
case m of
Nothing -> liftIO $ putStrLn "channel closed"
Just lm@(h,_) -> do
liftIO $ do
putStr "[Server Message] "
BSLC.putStrLn $ encode h
case parseMessage lm of
JSON.Success MsgResult{} -> liftIO (signalQSem sem)
JSON.Success MsgError{} -> liftIO (signalQSem sem)
_ -> waitResults sem
source sem = case eitherDecodeStrict' msg of
Left err -> liftIO $ putStrLn err
Right h -> yield (h, []) >> liftIO (waitQSem sem)
data RunSettings = RunSettings
{ host :: ByteString
, port :: Int
, logLevel :: LogLevel
, command :: Maybe ByteString
}
|
a8029ff3d0f6eed513b612f874635c92c93a0c1f54a917c1bea66829d2916b6d | khinsen/leibniz | test-examples.rkt | #lang racket
(provide sorts a-signature)
(require "./sorts.rkt"
"./operators.rkt"
"./builtins.rkt"
"./terms.rkt"
threading)
(define sorts
(~> (merge-sort-graphs rational-sorts truth-sorts)
(add-sort 'A) (add-sort 'B)
(add-subsort-relation 'B 'A)
(add-sort 'X) (add-sort 'Y)
(add-subsort-relation 'Y 'X)))
(define a-signature
(~> (foldl (λ (s1 s2) (merge-signatures s1 s2 #f))
(empty-signature sorts)
(list rational-signature truth-signature))
(add-op 'an-A empty 'A)
(add-op 'a-B empty 'B)
(add-op 'an-X empty 'X)
(add-op 'a-Y empty 'Y)
(add-op 'foo empty 'B)
(add-op 'foo (list 'B) 'A)
(add-op 'foo (list 'A 'B) 'A)
(add-var 'Avar 'A)
(add-var 'Bvar 'B)
(add-var 'IntVar 'ℤ)
(add-var 'BoolVar 'boolean)))
| null | https://raw.githubusercontent.com/khinsen/leibniz/881955b4c642114fbdc2f36ecc99582ae2371238/leibniz/test-examples.rkt | racket | #lang racket
(provide sorts a-signature)
(require "./sorts.rkt"
"./operators.rkt"
"./builtins.rkt"
"./terms.rkt"
threading)
(define sorts
(~> (merge-sort-graphs rational-sorts truth-sorts)
(add-sort 'A) (add-sort 'B)
(add-subsort-relation 'B 'A)
(add-sort 'X) (add-sort 'Y)
(add-subsort-relation 'Y 'X)))
(define a-signature
(~> (foldl (λ (s1 s2) (merge-signatures s1 s2 #f))
(empty-signature sorts)
(list rational-signature truth-signature))
(add-op 'an-A empty 'A)
(add-op 'a-B empty 'B)
(add-op 'an-X empty 'X)
(add-op 'a-Y empty 'Y)
(add-op 'foo empty 'B)
(add-op 'foo (list 'B) 'A)
(add-op 'foo (list 'A 'B) 'A)
(add-var 'Avar 'A)
(add-var 'Bvar 'B)
(add-var 'IntVar 'ℤ)
(add-var 'BoolVar 'boolean)))
|
|
266574ee17efa43f91965c833379737180f0a2294b9ef0658160fe9caf070a34 | manuel-serrano/bigloo | substitute.scm | ;*=====================================================================*/
* ... /prgm / project / bigloo / / comptime / Ast / substitute.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : Fri Jan 6 11:09:14 1995 * /
* Last change : Thu Jul 8 11:25:32 2021 ( serrano ) * /
;* ------------------------------------------------------------- */
;* The substitution tools module */
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module ast_substitute
(include "Tools/trace.sch")
(import type_type
type_cache
ast_var
ast_node
tools_shape
tools_error
tools_shape
ast_apply
ast_app
ast_sexp)
(export (substitute!::node what* by* ::node site)))
;*---------------------------------------------------------------------*/
;* substitute! ... */
;* ------------------------------------------------------------- */
;* Substitute can replace a variable by a variable or an atom */
;* (including `fun') construction but nothing else. */
;*---------------------------------------------------------------------*/
(define (substitute! what* by* node site)
(assert (site) (memq site '(value apply app set!)))
;; we set alpha-fnode slot
(for-each (lambda (what by)
(assert (by) (variable? by))
(variable-fast-alpha-set! what by))
what*
by*)
(let ((res (do-substitute! node site)))
;; we remove alpha-fast slots
(for-each (lambda (what)
(variable-fast-alpha-set! what #unspecified))
what*)
res))
;*---------------------------------------------------------------------*/
;* do-substitute! ... */
;*---------------------------------------------------------------------*/
(define-generic (do-substitute!::node node::node site))
;*---------------------------------------------------------------------*/
;* do-substitute! ::atom ... */
;*---------------------------------------------------------------------*/
(define-method (do-substitute! node::atom site)
node)
;*---------------------------------------------------------------------*/
;* do-substitute! ::var ... */
;*---------------------------------------------------------------------*/
(define-method (do-substitute! node::var site)
(let* ((var (var-variable node))
(alpha (variable-fast-alpha var)))
(let loop ((alpha alpha))
(cond
((eq? alpha #unspecified)
node)
((var? alpha)
(loop (var-variable alpha)))
((variable? alpha)
(use-variable! alpha (node-loc node) site)
(if (and (fun? (variable-value alpha)) (not (eq? site 'app)))
(instantiate::closure
(loc (node-loc node))
(type (strict-node-type *procedure* (node-type node)))
(variable alpha))
(instantiate::ref
(loc (node-loc node))
(type (node-type node))
(variable alpha))))
((atom? alpha)
alpha)
(else
(internal-error "duplicate" "Illegal substitution" (shape node)))))))
;*---------------------------------------------------------------------*/
;* do-substitute! ::kwote ... */
;*---------------------------------------------------------------------*/
(define-method (do-substitute! node::kwote site)
node)
;*---------------------------------------------------------------------*/
;* do-substitute! ::sequence ... */
;*---------------------------------------------------------------------*/
(define-method (do-substitute! node::sequence site)
(do-substitute*! (sequence-nodes node) site)
node)
;*---------------------------------------------------------------------*/
;* do-substitute! ::sync ... */
;*---------------------------------------------------------------------*/
(define-method (do-substitute! node::sync site)
(sync-mutex-set! node (do-substitute! (sync-mutex node) site))
(sync-prelock-set! node (do-substitute! (sync-prelock node) site))
(sync-body-set! node (do-substitute! (sync-body node) site))
node)
;*---------------------------------------------------------------------*/
;* do-substitute! ::app ... */
;*---------------------------------------------------------------------*/
(define-method (do-substitute! node::app site)
(app-fun-set! node (do-substitute! (app-fun node) 'app))
(do-substitute*! (app-args node) 'value)
node)
;*---------------------------------------------------------------------*/
;* do-substitute! ::app-ly ... */
;*---------------------------------------------------------------------*/
(define-method (do-substitute! node::app-ly site)
(with-access::app-ly node (arg fun loc)
(let ((nfun (do-substitute! fun 'apply))
(narg (do-substitute! arg 'value)))
(if (and (closure? nfun)
(not (global-optional? (var-variable nfun)))
(not (global-key? (var-variable nfun))))
(known-app-ly->node '() loc (duplicate::ref nfun) narg site)
(begin
(set! fun nfun)
(set! arg narg)
node)))))
;*---------------------------------------------------------------------*/
;* do-substitute! ::funcall ... */
;* ------------------------------------------------------------- */
;* When transforming a funcall into an app node we have to remove */
;* the extra argument which hold the closure. */
;*---------------------------------------------------------------------*/
(define-method (do-substitute! node::funcall site)
(with-access::funcall node (args fun loc)
(let ((nfun (do-substitute! fun 'value))
(nargs (map (lambda (a) (do-substitute! a 'value)) args)))
(if (or (closure? nfun)
(and (var? nfun)
(fun? (variable-value (var-variable nfun)))))
(if (correct-arity-app? (var-variable nfun)
(cdr nargs))
(make-app-node '() loc 'funcall nfun (cdr nargs))
(user-error/location
loc
"Illegal application" "wrong number of argument(s)"
(shape node)))
(begin
(set! fun nfun)
(set! args nargs)
node)))))
;*---------------------------------------------------------------------*/
;* do-substitute! ::extern ... */
;*---------------------------------------------------------------------*/
(define-method (do-substitute! node::extern site)
(do-substitute*! (extern-expr* node) site)
node)
;*---------------------------------------------------------------------*/
;* do-substitute! ::cast ... */
;*---------------------------------------------------------------------*/
(define-method (do-substitute! node::cast site)
(cast-arg-set! node (do-substitute! (cast-arg node) site))
node)
;*---------------------------------------------------------------------*/
;* do-substitute! ::setq ... */
;*---------------------------------------------------------------------*/
(define-method (do-substitute! node::setq site)
(with-access::setq node (var value)
(set! var (do-substitute! var 'set!))
(set! value (do-substitute! value site))
node))
;*---------------------------------------------------------------------*/
;* do-substitute! ::conditional ... */
;*---------------------------------------------------------------------*/
(define-method (do-substitute! node::conditional site)
(with-access::conditional node (test true false)
(set! test (do-substitute! test 'value))
(set! true (do-substitute! true site))
(set! false (do-substitute! false site))
node))
;*---------------------------------------------------------------------*/
;* do-substitute! ::fail ... */
;*---------------------------------------------------------------------*/
(define-method (do-substitute! node::fail site)
(with-access::fail node (proc msg obj)
(set! proc (do-substitute! proc 'value))
(set! msg (do-substitute! msg 'value))
(set! obj (do-substitute! obj 'value))
node))
;*---------------------------------------------------------------------*/
;* do-substitute! ::switch ... */
;*---------------------------------------------------------------------*/
(define-method (do-substitute! node::switch site)
(switch-test-set! node (do-substitute! (switch-test node) 'value))
(for-each (lambda (clause)
(set-cdr! clause (do-substitute! (cdr clause) site)))
(switch-clauses node))
node)
;*---------------------------------------------------------------------*/
;* do-substitute! ::let-fun ... */
;*---------------------------------------------------------------------*/
(define-method (do-substitute! node::let-fun site)
(for-each (lambda (local)
(let ((fun (local-value local)))
(sfun-body-set! fun (do-substitute! (sfun-body fun)
'value))))
(let-fun-locals node))
(let-fun-body-set! node (do-substitute! (let-fun-body node) site))
node)
;*---------------------------------------------------------------------*/
;* do-substitute! ::let-var ... */
;*---------------------------------------------------------------------*/
(define-method (do-substitute! node::let-var site)
(for-each (lambda (binding)
(set-cdr! binding (do-substitute! (cdr binding) 'value)))
(let-var-bindings node))
(let-var-body-set! node (do-substitute! (let-var-body node) site))
node)
;*---------------------------------------------------------------------*/
;* do-substitute! ::set-ex-it ... */
;*---------------------------------------------------------------------*/
(define-method (do-substitute! node::set-ex-it site)
(set-ex-it-body-set! node (do-substitute! (set-ex-it-body node) site))
(set-ex-it-onexit-set! node (do-substitute! (set-ex-it-onexit node) site))
node)
;*---------------------------------------------------------------------*/
;* do-substitute! ::jump-ex-it ... */
;*---------------------------------------------------------------------*/
(define-method (do-substitute! node::jump-ex-it site)
(jump-ex-it-exit-set! node (do-substitute! (jump-ex-it-exit node) 'app))
(jump-ex-it-value-set! node (do-substitute! (jump-ex-it-value node) 'value))
node)
;*---------------------------------------------------------------------*/
;* do-substitute! ::make-box ... */
;*---------------------------------------------------------------------*/
(define-method (do-substitute! node::make-box site)
(make-box-value-set! node (do-substitute! (make-box-value node) 'value))
node)
;*---------------------------------------------------------------------*/
;* do-substitute! ::box-ref ... */
;*---------------------------------------------------------------------*/
(define-method (do-substitute! node::box-ref site)
(box-ref-var-set! node (do-substitute! (box-ref-var node) 'value))
node)
;*---------------------------------------------------------------------*/
;* do-substitute! ::box-set! ... */
;*---------------------------------------------------------------------*/
(define-method (do-substitute! node::box-set! site)
(box-set!-var-set! node (do-substitute! (box-set!-var node) 'value))
(box-set!-value-set! node (do-substitute! (box-set!-value node) 'value))
node)
;*---------------------------------------------------------------------*/
;* do-substitute*! ... */
;*---------------------------------------------------------------------*/
(define (do-substitute*! node* site)
(cond
((null? node*)
'done)
((null? (cdr node*))
(set-car! node* (do-substitute! (car node*) site))
'done)
(else
(set-car! node* (do-substitute! (car node*) 'value))
(do-substitute*! (cdr node*) site))))
| null | https://raw.githubusercontent.com/manuel-serrano/bigloo/fdeac39af72d5119d01818815b0f395f2907d6da/comptime/Ast/substitute.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
* The substitution tools module */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* substitute! ... */
* ------------------------------------------------------------- */
* Substitute can replace a variable by a variable or an atom */
* (including `fun') construction but nothing else. */
*---------------------------------------------------------------------*/
we set alpha-fnode slot
we remove alpha-fast slots
*---------------------------------------------------------------------*/
* do-substitute! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-substitute! ::atom ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-substitute! ::var ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-substitute! ::kwote ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-substitute! ::sequence ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-substitute! ::sync ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-substitute! ::app ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-substitute! ::app-ly ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-substitute! ::funcall ... */
* ------------------------------------------------------------- */
* When transforming a funcall into an app node we have to remove */
* the extra argument which hold the closure. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-substitute! ::extern ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-substitute! ::cast ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-substitute! ::setq ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-substitute! ::conditional ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-substitute! ::fail ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-substitute! ::switch ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-substitute! ::let-fun ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-substitute! ::let-var ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-substitute! ::set-ex-it ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-substitute! ::jump-ex-it ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-substitute! ::make-box ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-substitute! ::box-ref ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-substitute! ::box-set! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* do-substitute*! ... */
*---------------------------------------------------------------------*/ | * ... /prgm / project / bigloo / / comptime / Ast / substitute.scm * /
* Author : * /
* Creation : Fri Jan 6 11:09:14 1995 * /
* Last change : Thu Jul 8 11:25:32 2021 ( serrano ) * /
(module ast_substitute
(include "Tools/trace.sch")
(import type_type
type_cache
ast_var
ast_node
tools_shape
tools_error
tools_shape
ast_apply
ast_app
ast_sexp)
(export (substitute!::node what* by* ::node site)))
(define (substitute! what* by* node site)
(assert (site) (memq site '(value apply app set!)))
(for-each (lambda (what by)
(assert (by) (variable? by))
(variable-fast-alpha-set! what by))
what*
by*)
(let ((res (do-substitute! node site)))
(for-each (lambda (what)
(variable-fast-alpha-set! what #unspecified))
what*)
res))
(define-generic (do-substitute!::node node::node site))
(define-method (do-substitute! node::atom site)
node)
(define-method (do-substitute! node::var site)
(let* ((var (var-variable node))
(alpha (variable-fast-alpha var)))
(let loop ((alpha alpha))
(cond
((eq? alpha #unspecified)
node)
((var? alpha)
(loop (var-variable alpha)))
((variable? alpha)
(use-variable! alpha (node-loc node) site)
(if (and (fun? (variable-value alpha)) (not (eq? site 'app)))
(instantiate::closure
(loc (node-loc node))
(type (strict-node-type *procedure* (node-type node)))
(variable alpha))
(instantiate::ref
(loc (node-loc node))
(type (node-type node))
(variable alpha))))
((atom? alpha)
alpha)
(else
(internal-error "duplicate" "Illegal substitution" (shape node)))))))
(define-method (do-substitute! node::kwote site)
node)
(define-method (do-substitute! node::sequence site)
(do-substitute*! (sequence-nodes node) site)
node)
(define-method (do-substitute! node::sync site)
(sync-mutex-set! node (do-substitute! (sync-mutex node) site))
(sync-prelock-set! node (do-substitute! (sync-prelock node) site))
(sync-body-set! node (do-substitute! (sync-body node) site))
node)
(define-method (do-substitute! node::app site)
(app-fun-set! node (do-substitute! (app-fun node) 'app))
(do-substitute*! (app-args node) 'value)
node)
(define-method (do-substitute! node::app-ly site)
(with-access::app-ly node (arg fun loc)
(let ((nfun (do-substitute! fun 'apply))
(narg (do-substitute! arg 'value)))
(if (and (closure? nfun)
(not (global-optional? (var-variable nfun)))
(not (global-key? (var-variable nfun))))
(known-app-ly->node '() loc (duplicate::ref nfun) narg site)
(begin
(set! fun nfun)
(set! arg narg)
node)))))
(define-method (do-substitute! node::funcall site)
(with-access::funcall node (args fun loc)
(let ((nfun (do-substitute! fun 'value))
(nargs (map (lambda (a) (do-substitute! a 'value)) args)))
(if (or (closure? nfun)
(and (var? nfun)
(fun? (variable-value (var-variable nfun)))))
(if (correct-arity-app? (var-variable nfun)
(cdr nargs))
(make-app-node '() loc 'funcall nfun (cdr nargs))
(user-error/location
loc
"Illegal application" "wrong number of argument(s)"
(shape node)))
(begin
(set! fun nfun)
(set! args nargs)
node)))))
(define-method (do-substitute! node::extern site)
(do-substitute*! (extern-expr* node) site)
node)
(define-method (do-substitute! node::cast site)
(cast-arg-set! node (do-substitute! (cast-arg node) site))
node)
(define-method (do-substitute! node::setq site)
(with-access::setq node (var value)
(set! var (do-substitute! var 'set!))
(set! value (do-substitute! value site))
node))
(define-method (do-substitute! node::conditional site)
(with-access::conditional node (test true false)
(set! test (do-substitute! test 'value))
(set! true (do-substitute! true site))
(set! false (do-substitute! false site))
node))
(define-method (do-substitute! node::fail site)
(with-access::fail node (proc msg obj)
(set! proc (do-substitute! proc 'value))
(set! msg (do-substitute! msg 'value))
(set! obj (do-substitute! obj 'value))
node))
(define-method (do-substitute! node::switch site)
(switch-test-set! node (do-substitute! (switch-test node) 'value))
(for-each (lambda (clause)
(set-cdr! clause (do-substitute! (cdr clause) site)))
(switch-clauses node))
node)
(define-method (do-substitute! node::let-fun site)
(for-each (lambda (local)
(let ((fun (local-value local)))
(sfun-body-set! fun (do-substitute! (sfun-body fun)
'value))))
(let-fun-locals node))
(let-fun-body-set! node (do-substitute! (let-fun-body node) site))
node)
(define-method (do-substitute! node::let-var site)
(for-each (lambda (binding)
(set-cdr! binding (do-substitute! (cdr binding) 'value)))
(let-var-bindings node))
(let-var-body-set! node (do-substitute! (let-var-body node) site))
node)
(define-method (do-substitute! node::set-ex-it site)
(set-ex-it-body-set! node (do-substitute! (set-ex-it-body node) site))
(set-ex-it-onexit-set! node (do-substitute! (set-ex-it-onexit node) site))
node)
(define-method (do-substitute! node::jump-ex-it site)
(jump-ex-it-exit-set! node (do-substitute! (jump-ex-it-exit node) 'app))
(jump-ex-it-value-set! node (do-substitute! (jump-ex-it-value node) 'value))
node)
(define-method (do-substitute! node::make-box site)
(make-box-value-set! node (do-substitute! (make-box-value node) 'value))
node)
(define-method (do-substitute! node::box-ref site)
(box-ref-var-set! node (do-substitute! (box-ref-var node) 'value))
node)
(define-method (do-substitute! node::box-set! site)
(box-set!-var-set! node (do-substitute! (box-set!-var node) 'value))
(box-set!-value-set! node (do-substitute! (box-set!-value node) 'value))
node)
(define (do-substitute*! node* site)
(cond
((null? node*)
'done)
((null? (cdr node*))
(set-car! node* (do-substitute! (car node*) site))
'done)
(else
(set-car! node* (do-substitute! (car node*) 'value))
(do-substitute*! (cdr node*) site))))
|
389784a358a1cc1e2c8ad0abca16c0071f7102e3fa3336ae6a16613de806ec00 | davebryson/beepbeep | skel_sup.erl | -module(skel_sup).
-behaviour(supervisor).
%% External exports
-export([start_link/0, upgrade/0]).
%% supervisor callbacks
-export([init/1]).
( ) - > ServerRet
%% @doc API for starting the supervisor.
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
@spec upgrade ( ) - > ok
%% @doc Add processes if necessary.
upgrade() ->
{ok, {_, Specs}} = init([]),
Old = sets:from_list(
[Name || {Name, _, _, _} <- supervisor:which_children(?MODULE)]),
New = sets:from_list([Name || {Name, _, _, _, _, _} <- Specs]),
Kill = sets:subtract(Old, New),
sets:fold(fun (Id, ok) ->
supervisor:terminate_child(?MODULE, Id),
supervisor:delete_child(?MODULE, Id),
ok
end, ok, Kill),
[supervisor:start_child(?MODULE, Spec) || Spec <- Specs],
ok.
@spec init ( [ ] ) - > SupervisorTree
%% @doc supervisor callback.
init([]) ->
Ip = case os:getenv("MOCHIWEB_IP") of false -> "0.0.0.0"; Any -> Any end,
WebConfig = [
{ip, Ip},
{port, 8000}
],
Sets up the BeepBeep environment . Removing any of the below
%% will cause something to break.
BaseDir = skel_deps:get_base_dir(),
Web = {skel_web,
{skel_web, start, [WebConfig]},
permanent, 5000, worker, dynamic},
Router = {beepbeep_router,
{beepbeep_router, start, [BaseDir]},
permanent, 5000, worker, dynamic},
SessionServer = {beepbeep_session_server,
{beepbeep_session_server,start,[]},
permanent, 5000, worker, dynamic},
Processes = [Router,SessionServer,Web],
{ok, {{one_for_one, 10, 10}, Processes}}.
| null | https://raw.githubusercontent.com/davebryson/beepbeep/62db46d268c6cb6ad86345562b3c77f8ff070b27/priv/skel/src/skel_sup.erl | erlang | External exports
supervisor callbacks
@doc API for starting the supervisor.
@doc Add processes if necessary.
@doc supervisor callback.
will cause something to break. | -module(skel_sup).
-behaviour(supervisor).
-export([start_link/0, upgrade/0]).
-export([init/1]).
( ) - > ServerRet
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
@spec upgrade ( ) - > ok
upgrade() ->
{ok, {_, Specs}} = init([]),
Old = sets:from_list(
[Name || {Name, _, _, _} <- supervisor:which_children(?MODULE)]),
New = sets:from_list([Name || {Name, _, _, _, _, _} <- Specs]),
Kill = sets:subtract(Old, New),
sets:fold(fun (Id, ok) ->
supervisor:terminate_child(?MODULE, Id),
supervisor:delete_child(?MODULE, Id),
ok
end, ok, Kill),
[supervisor:start_child(?MODULE, Spec) || Spec <- Specs],
ok.
@spec init ( [ ] ) - > SupervisorTree
init([]) ->
Ip = case os:getenv("MOCHIWEB_IP") of false -> "0.0.0.0"; Any -> Any end,
WebConfig = [
{ip, Ip},
{port, 8000}
],
Sets up the BeepBeep environment . Removing any of the below
BaseDir = skel_deps:get_base_dir(),
Web = {skel_web,
{skel_web, start, [WebConfig]},
permanent, 5000, worker, dynamic},
Router = {beepbeep_router,
{beepbeep_router, start, [BaseDir]},
permanent, 5000, worker, dynamic},
SessionServer = {beepbeep_session_server,
{beepbeep_session_server,start,[]},
permanent, 5000, worker, dynamic},
Processes = [Router,SessionServer,Web],
{ok, {{one_for_one, 10, 10}, Processes}}.
|
2c4c977bebde74ea2125234ae01079003ea71133758944281bddb0d89a4c751f | 7bridges-eu/clj-odbp | command.clj | Copyright 2017 7bridges s.r.l .
;;
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; -2.0
;;
;; Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns clj-odbp.operations.command
(:require [clj-odbp
[constants :as constants]
[utils :refer [encode decode]]]
[clj-odbp.operations.specs.command :as specs]
[clj-odbp.binary.serialize.types :as t]
[clj-odbp.binary.deserialize.record :as deserialize]
[clj-odbp.network.read :as r])
(:import java.io.DataInputStream))
(defn get-bytes-type-length [bytes-type]
(if (empty? bytes-type)
0
(+ 4 (count bytes-type))))
(defn get-query-payload-length
[command fetch-plan serialized-params]
(+ 4 (count constants/request-command-query)
4 (count command)
4 ; non-text-limit length
4 (count fetch-plan)
(get-bytes-type-length serialized-params)))
(defn get-execute-payload-length
[command serialized-params]
(+ 4 (count constants/request-command-execute)
4 (count command)
1 (get-bytes-type-length serialized-params)
1))
(def ^:const params-serializer
(get-method t/serialize :embedded-record-type))
(defn serialize-params
[params-name params]
(if (empty? params)
""
(params-serializer {params-name params} 0)))
> QUERY
(defn query-request
[connection command
{:keys [params non-text-limit fetch-plan]
:or {params {} non-text-limit -1 fetch-plan "*:0"}}]
(let [session-id (:session-id connection)
token (:token connection)
serialized-params (serialize-params "params" params)]
(encode
specs/query-request
[[:operation 41]
[:session-id session-id]
[:token token]
[:mode constants/request-command-sync-mode]
[:payload-length (get-query-payload-length command
fetch-plan
serialized-params)]
[:class-name constants/request-command-query]
[:text command]
[:non-text-limit non-text-limit]
[:fetch-plan fetch-plan]
[:serialized-params serialized-params]])))
(defn- query-list-response
[^DataInputStream in]
(let [list-size (r/int-type in)]
(reduce
(fn [acc n]
(case (r/short-type in)
0 (conj acc (-> (decode in specs/record-response)
deserialize/deserialize-record))
(conj acc nil)))
[]
(range list-size))))
(defn- query-single-response
[^DataInputStream in]
(let [boh (r/short-type in)]
(-> (decode in specs/record-response)
deserialize/deserialize-record)))
(defn query-response
[^DataInputStream in]
(let [generic-response (decode in specs/sync-generic-response)
result-type (:result-type generic-response)]
(case result-type
\n []
\l (query-list-response in)
\s (query-list-response in)
\r (query-single-response in)
\w (query-single-response in))))
> EXECUTE
(defn execute-request
[connection command
{:keys [params] :or {params {}}}]
(let [session-id (:session-id connection)
token (:token connection)
serialized-params (serialize-params "parameters" params)]
(encode
specs/execute-request
[[:operation 41]
[:session-id session-id]
[:token token]
[:mode constants/request-command-sync-mode]
[:payload-length (get-execute-payload-length command
serialized-params)]
[:class-name constants/request-command-execute]
[:text command]
[:has-simple-params (not (empty? serialized-params))]
[:simple-params serialized-params]
[:has-complex-params false]
[:complex-params []]])))
| null | https://raw.githubusercontent.com/7bridges-eu/clj-odbp/5a92515c2e4c6198bd1093ace83da96e30b90829/src/clj_odbp/operations/command.clj | clojure |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
non-text-limit length | Copyright 2017 7bridges s.r.l .
distributed under the License is distributed on an " AS IS " BASIS ,
(ns clj-odbp.operations.command
(:require [clj-odbp
[constants :as constants]
[utils :refer [encode decode]]]
[clj-odbp.operations.specs.command :as specs]
[clj-odbp.binary.serialize.types :as t]
[clj-odbp.binary.deserialize.record :as deserialize]
[clj-odbp.network.read :as r])
(:import java.io.DataInputStream))
(defn get-bytes-type-length [bytes-type]
(if (empty? bytes-type)
0
(+ 4 (count bytes-type))))
(defn get-query-payload-length
[command fetch-plan serialized-params]
(+ 4 (count constants/request-command-query)
4 (count command)
4 (count fetch-plan)
(get-bytes-type-length serialized-params)))
(defn get-execute-payload-length
[command serialized-params]
(+ 4 (count constants/request-command-execute)
4 (count command)
1 (get-bytes-type-length serialized-params)
1))
(def ^:const params-serializer
(get-method t/serialize :embedded-record-type))
(defn serialize-params
[params-name params]
(if (empty? params)
""
(params-serializer {params-name params} 0)))
> QUERY
(defn query-request
[connection command
{:keys [params non-text-limit fetch-plan]
:or {params {} non-text-limit -1 fetch-plan "*:0"}}]
(let [session-id (:session-id connection)
token (:token connection)
serialized-params (serialize-params "params" params)]
(encode
specs/query-request
[[:operation 41]
[:session-id session-id]
[:token token]
[:mode constants/request-command-sync-mode]
[:payload-length (get-query-payload-length command
fetch-plan
serialized-params)]
[:class-name constants/request-command-query]
[:text command]
[:non-text-limit non-text-limit]
[:fetch-plan fetch-plan]
[:serialized-params serialized-params]])))
(defn- query-list-response
[^DataInputStream in]
(let [list-size (r/int-type in)]
(reduce
(fn [acc n]
(case (r/short-type in)
0 (conj acc (-> (decode in specs/record-response)
deserialize/deserialize-record))
(conj acc nil)))
[]
(range list-size))))
(defn- query-single-response
[^DataInputStream in]
(let [boh (r/short-type in)]
(-> (decode in specs/record-response)
deserialize/deserialize-record)))
(defn query-response
[^DataInputStream in]
(let [generic-response (decode in specs/sync-generic-response)
result-type (:result-type generic-response)]
(case result-type
\n []
\l (query-list-response in)
\s (query-list-response in)
\r (query-single-response in)
\w (query-single-response in))))
> EXECUTE
(defn execute-request
[connection command
{:keys [params] :or {params {}}}]
(let [session-id (:session-id connection)
token (:token connection)
serialized-params (serialize-params "parameters" params)]
(encode
specs/execute-request
[[:operation 41]
[:session-id session-id]
[:token token]
[:mode constants/request-command-sync-mode]
[:payload-length (get-execute-payload-length command
serialized-params)]
[:class-name constants/request-command-execute]
[:text command]
[:has-simple-params (not (empty? serialized-params))]
[:simple-params serialized-params]
[:has-complex-params false]
[:complex-params []]])))
|
e1fe1f206dfc992b3ae009ad35d26e05b3235e2be780d37dd0a8e275e1cb32e5 | razum2um/clj-debugger | config.clj | (ns debugger.config
(:require [debugger.time :as t]))
(declare ^:dynamic *locals*)
(def ^:dynamic *break-outside-repl* true)
(def ^:dynamic *code-context-lines* 5)
(def ^:dynamic *locals-print-length* 10)
(def ^:dynamic *skip-repl-if-last-quit-ago* 2)
(def ^:dynamic *last-quit-at* (atom (t/minus (t/now) (t/seconds *skip-repl-if-last-quit-ago*))))
| null | https://raw.githubusercontent.com/razum2um/clj-debugger/22f8775193b13e799c3879f6d8443e65600ad503/src/debugger/config.clj | clojure | (ns debugger.config
(:require [debugger.time :as t]))
(declare ^:dynamic *locals*)
(def ^:dynamic *break-outside-repl* true)
(def ^:dynamic *code-context-lines* 5)
(def ^:dynamic *locals-print-length* 10)
(def ^:dynamic *skip-repl-if-last-quit-ago* 2)
(def ^:dynamic *last-quit-at* (atom (t/minus (t/now) (t/seconds *skip-repl-if-last-quit-ago*))))
|
|
a99d81df894a5cd116fec8d61a1c2d8822acfc2d7e3b9cf894f68dbac4582007 | OscarSouth/theHarmonicAlgorithm | Lib.hs | module Lib (
------------
-- |MusicData
MusicData,
PitchClass (P),
NoteName,
Chord (Chord),
Cadence,
i,
pitchClass,
mostConsonant,
possibleTriads'',
toTriad,
flatTriad,
sharpTriad,
flatChord,
sharpChord,
flat,
sharp,
showTriad,
dissonanceLevel,
toCadence,
pc,
pcSet,
simpleInversions,
intervalVector,
fromCadence,
fromCadence',
movementFromCadence,
fromMovement',
movementFromCadence',
transposeCadence,
rootNote,
toMode,
basePenta,
sortPcSet,
fromChord,
progRoots',
toEnhTriad,
----------
-- experimental stuff
-- Movement,
-- Functionality,
constructCadence,
deconstructCadence,
-----------
-- |Analysis
prog3ecbc, pentaPatterns, -- temp
fullSet3title,
pentatonicSet1title,
pentatonicSet2title,
pentatonicSet3title,
diatonicSet12title,
diatonicSet23title,
diatonicSet31title,
generateScale,
triadSets,
chordSets,
vocab'',
allModes,
majorPentaChr,
okinaPentaChr,
iwatoPentaChr,
(?>),(<?),
-----------
-- |Markov
MarkovMap,
markovMap,
bigrams,
------------
-- |Overtone
chordList',
parseOvertones,
parseNotes,
parseTuning,
parseKey,
parseFunds,
------------
-- |Utility
unique,
-- uniqueAnalysis,
-- |GraphDB
-- testFunc,
-- testData
) where
import Markov -- contains markov chain numerical processing machinery
defines MusicData and many pitchclass analysis functions
import Analysis -- ad hoc analysis functionality for composing
import Overtone -- mainly parsing functions for generating lists of MusicData
import Utility -- various 'misc' helper functions
import GraphDB -- functions to populate and access markov graph database (Neo4j)
functions related to performance with TidalCycles | null | https://raw.githubusercontent.com/OscarSouth/theHarmonicAlgorithm/615b87c7ac98e06f59af225bb892c6caf97a4a29/src/Lib.hs | haskell | ----------
|MusicData
--------
experimental stuff
Movement,
Functionality,
---------
|Analysis
temp
---------
|Markov
----------
|Overtone
----------
|Utility
uniqueAnalysis,
|GraphDB
testFunc,
testData
contains markov chain numerical processing machinery
ad hoc analysis functionality for composing
mainly parsing functions for generating lists of MusicData
various 'misc' helper functions
functions to populate and access markov graph database (Neo4j) | module Lib (
MusicData,
PitchClass (P),
NoteName,
Chord (Chord),
Cadence,
i,
pitchClass,
mostConsonant,
possibleTriads'',
toTriad,
flatTriad,
sharpTriad,
flatChord,
sharpChord,
flat,
sharp,
showTriad,
dissonanceLevel,
toCadence,
pc,
pcSet,
simpleInversions,
intervalVector,
fromCadence,
fromCadence',
movementFromCadence,
fromMovement',
movementFromCadence',
transposeCadence,
rootNote,
toMode,
basePenta,
sortPcSet,
fromChord,
progRoots',
toEnhTriad,
constructCadence,
deconstructCadence,
fullSet3title,
pentatonicSet1title,
pentatonicSet2title,
pentatonicSet3title,
diatonicSet12title,
diatonicSet23title,
diatonicSet31title,
generateScale,
triadSets,
chordSets,
vocab'',
allModes,
majorPentaChr,
okinaPentaChr,
iwatoPentaChr,
(?>),(<?),
MarkovMap,
markovMap,
bigrams,
chordList',
parseOvertones,
parseNotes,
parseTuning,
parseKey,
parseFunds,
unique,
) where
defines MusicData and many pitchclass analysis functions
functions related to performance with TidalCycles |
44d0625d07ef253cdf56ac29d7677dedd8255b7b871a77b50168a7a19a18d165 | PLTools/OCanren | test010.ml | (* Some tests about constraints *)
open GT
open OCanren
open OCanren.Std
open Tester
let (!) = inji
let (!!) = inji
let g123 x = conde [x === !1; x === !2; x === !3]
let g12 x = (g123 x) &&& (x =/= !3)
let gxy x y = (g123 x) &&& (g123 y)
let gxy' x y = (gxy x y) &&& (x =/= y)
let gnot5 x = x =/= !5
let show_int = show(int)
let run_int eta = run_r OCanren.prj_exn show_int eta
let _ =
run_int 3 q qh (REPR (fun q -> g123 q ));
run_int 3 q qh (REPR (fun q -> g123 q ));
run_int 3 q qh (REPR (fun q -> g12 q ));
run_int 10 qr qrh (REPR (fun q r -> gxy q r ));
run_int 10 qr qrh (REPR (fun q r -> gxy' q r ));
run_int (-1) q qh (REPR (fun q -> (fresh (x y) (x === y)(x =/= y)) ));
run_int (-1) q qh (REPR (fun q -> (fresh (x y) (x =/= y)(x === y)) ));
run_int (-1) q qh (REPR (fun q -> (fresh (x y) (x =/= y)(!3 === x)(!3 === y)) ));
run_int (-1) q qh (REPR (fun q -> (fresh (x y) (!3 === x)(x =/= x)(!3 === y)) ));
run_int (-1) q qh (REPR (fun q -> (fresh (x y) (!3 === x)(!3 === y)(x =/= y)) ));
run_int (-1) q qh (REPR (fun q -> (fresh (x y) (!3 === x)(!3 === y)(y =/= x)) ));
run_int (-1) q qh (REPR (fun q -> (fresh (x y z) (x === y)(y === z)(x =/= !4)(z === !(2+2)))));
run_int (-1) q qh (REPR (fun q -> (fresh (x y z) (x === y)(y === z)(z === !(2+2))(x =/= !4))));
run_int (-1) q qh (REPR (fun q -> (fresh (x y z) (x =/= !4)(y === z)(x === y)(z === !(2+2)))))
let runI n = run_r OCanren.reify (show(logic) show_int) n
let _ =
runI (-1) q qh (REPR (fun q -> (q =/= !5) ));
runI (-1) q qh (REPR (fun q -> ((q =/= !3) &&& (q === !3)) ));
runI (-1) q qh (REPR (fun q -> ((q === !3) &&& (!3 =/= q)) ))
let show_bool = show(bool)
let runB n = run_r OCanren.reify (show(logic) show_bool) n
let _ =
runB (-1) qr qrh (REPR (fun q r -> (q =/= (!!true)) &&& (q =/= r)))
let run_list n = run_r (Std.List.reify OCanren.reify) (GT.show(Std.List.logic) @@ GT.show logic show_int) n
let _ =
run_list (-1) q qh (REPR (fun q -> (q =/= Std.nil()) ));
run_list (-1) q qh (REPR (fun q -> (q =/= !< !!2) ))
| null | https://raw.githubusercontent.com/PLTools/OCanren/1ead64bde16b0eb339a6bf790ea871e19bbaccd0/regression/test010.ml | ocaml | Some tests about constraints | open GT
open OCanren
open OCanren.Std
open Tester
let (!) = inji
let (!!) = inji
let g123 x = conde [x === !1; x === !2; x === !3]
let g12 x = (g123 x) &&& (x =/= !3)
let gxy x y = (g123 x) &&& (g123 y)
let gxy' x y = (gxy x y) &&& (x =/= y)
let gnot5 x = x =/= !5
let show_int = show(int)
let run_int eta = run_r OCanren.prj_exn show_int eta
let _ =
run_int 3 q qh (REPR (fun q -> g123 q ));
run_int 3 q qh (REPR (fun q -> g123 q ));
run_int 3 q qh (REPR (fun q -> g12 q ));
run_int 10 qr qrh (REPR (fun q r -> gxy q r ));
run_int 10 qr qrh (REPR (fun q r -> gxy' q r ));
run_int (-1) q qh (REPR (fun q -> (fresh (x y) (x === y)(x =/= y)) ));
run_int (-1) q qh (REPR (fun q -> (fresh (x y) (x =/= y)(x === y)) ));
run_int (-1) q qh (REPR (fun q -> (fresh (x y) (x =/= y)(!3 === x)(!3 === y)) ));
run_int (-1) q qh (REPR (fun q -> (fresh (x y) (!3 === x)(x =/= x)(!3 === y)) ));
run_int (-1) q qh (REPR (fun q -> (fresh (x y) (!3 === x)(!3 === y)(x =/= y)) ));
run_int (-1) q qh (REPR (fun q -> (fresh (x y) (!3 === x)(!3 === y)(y =/= x)) ));
run_int (-1) q qh (REPR (fun q -> (fresh (x y z) (x === y)(y === z)(x =/= !4)(z === !(2+2)))));
run_int (-1) q qh (REPR (fun q -> (fresh (x y z) (x === y)(y === z)(z === !(2+2))(x =/= !4))));
run_int (-1) q qh (REPR (fun q -> (fresh (x y z) (x =/= !4)(y === z)(x === y)(z === !(2+2)))))
let runI n = run_r OCanren.reify (show(logic) show_int) n
let _ =
runI (-1) q qh (REPR (fun q -> (q =/= !5) ));
runI (-1) q qh (REPR (fun q -> ((q =/= !3) &&& (q === !3)) ));
runI (-1) q qh (REPR (fun q -> ((q === !3) &&& (!3 =/= q)) ))
let show_bool = show(bool)
let runB n = run_r OCanren.reify (show(logic) show_bool) n
let _ =
runB (-1) qr qrh (REPR (fun q r -> (q =/= (!!true)) &&& (q =/= r)))
let run_list n = run_r (Std.List.reify OCanren.reify) (GT.show(Std.List.logic) @@ GT.show logic show_int) n
let _ =
run_list (-1) q qh (REPR (fun q -> (q =/= Std.nil()) ));
run_list (-1) q qh (REPR (fun q -> (q =/= !< !!2) ))
|
00e12406934a5302d14e2d03cc23c92c4d9848046352bb01ed106dd15e73f059 | juxt/jinx | clj_transform_test.cljc | Copyright © 2019 , JUXT LTD .
(ns juxt.jinx.clj-transform-test
(:require
[juxt.jinx.alpha.clj-transform :refer [clj->jsch]]
[clojure.test :refer [deftest is]]
#?(:clj
[clojure.test :refer [deftest is testing]]
:cljs
[cljs.test :refer-macros [deftest is testing run-tests]])))
(deftest clj->jsch-test
(is (= {"type" "string"} (clj->jsch 'string)))
(is (= {"type" "integer"} (clj->jsch 'integer)))
(is (= {"type" "object"} (clj->jsch 'object)))
(is (= {"type" "array" "items" {"type" "string"}} (clj->jsch '[string])))
(is (= {"type" "array" "items" [{"type" "string"}{"type" "integer"}]} (clj->jsch '(string integer))))
(is (= {"type" "null"} (clj->jsch nil)))
(is (= {"allOf" [{"type" "string"}{"type" "integer"}]} (clj->jsch '(all-of string integer))))
(is (= {"oneOf" [{"type" "string"}{"type" "integer"}]} (clj->jsch '(one-of string integer))))
(is (= {"anyOf" [{"type" "string"}{"type" "integer"}]} (clj->jsch '(any-of string integer))))
(is (= {"properties"
{"a" {"type" "array", "items" {"type" "string"}},
"b" {"type" "string", "constant" "20"}},
"required" ["a"]}
(clj->jsch {:properties {"a" ['string]
"b" "20"}
:required ["a"]})))
#?(:clj
(is (= {"pattern" "\\w+"} (clj->jsch #"\w+")))))
| null | https://raw.githubusercontent.com/juxt/jinx/48c889486e5606e39144043946063803ad6effa8/test/juxt/jinx/clj_transform_test.cljc | clojure | Copyright © 2019 , JUXT LTD .
(ns juxt.jinx.clj-transform-test
(:require
[juxt.jinx.alpha.clj-transform :refer [clj->jsch]]
[clojure.test :refer [deftest is]]
#?(:clj
[clojure.test :refer [deftest is testing]]
:cljs
[cljs.test :refer-macros [deftest is testing run-tests]])))
(deftest clj->jsch-test
(is (= {"type" "string"} (clj->jsch 'string)))
(is (= {"type" "integer"} (clj->jsch 'integer)))
(is (= {"type" "object"} (clj->jsch 'object)))
(is (= {"type" "array" "items" {"type" "string"}} (clj->jsch '[string])))
(is (= {"type" "array" "items" [{"type" "string"}{"type" "integer"}]} (clj->jsch '(string integer))))
(is (= {"type" "null"} (clj->jsch nil)))
(is (= {"allOf" [{"type" "string"}{"type" "integer"}]} (clj->jsch '(all-of string integer))))
(is (= {"oneOf" [{"type" "string"}{"type" "integer"}]} (clj->jsch '(one-of string integer))))
(is (= {"anyOf" [{"type" "string"}{"type" "integer"}]} (clj->jsch '(any-of string integer))))
(is (= {"properties"
{"a" {"type" "array", "items" {"type" "string"}},
"b" {"type" "string", "constant" "20"}},
"required" ["a"]}
(clj->jsch {:properties {"a" ['string]
"b" "20"}
:required ["a"]})))
#?(:clj
(is (= {"pattern" "\\w+"} (clj->jsch #"\w+")))))
|
|
c141740d0848341218cb7fd358e9eff4ae71904eb6d50900d2e89a3509ad128e | Haskell-Things/HSlice | Line.hs | {- ORMOLU_DISABLE -}
- Copyright 2020
-
- This program is free software : you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as published by
- the Free Software Foundation , either version 3 of the License , or
- ( at your option ) any later version .
-
- This program is distributed in the hope that it will be useful ,
- but WITHOUT ANY WARRANTY ; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
- GNU Affero General Public License for more details .
- You should have received a copy of the GNU Affero General Public License
- along with this program . If not , see < / > .
- Copyright 2020 Julia Longtin
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Affero General Public License for more details.
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see </>.
-}
-- inherit instances when deriving.
# LANGUAGE DerivingStrategies #
-- | Functions for for applying inset line segments to a series of faces, and for adding infill to a face.
module Graphics.Slicer.Math.Skeleton.Line (insetBy, infiniteInset) where
import Prelude ((==), all, concat, otherwise, (<$>), (<=), (&&), ($), (/=), error, (<>), show, (<>), (/), floor, fromIntegral, (+), (*), (-), (.), (<>), (>), (<), min, Bool(True, False), filter, fst, maybe, mempty, null, snd)
import Data.Either (isRight)
import Data.List (sortOn, dropWhile, last, length, takeWhile, transpose, uncons)
import Data.List.Extra (unsnoc)
import Data.Maybe (Maybe(Just,Nothing), catMaybes, fromMaybe, fromJust, isJust, isNothing, mapMaybe)
import Slist (head, isEmpty, len, slist)
import Slist.Type (Slist(Slist))
import Graphics.Slicer.Math.Contour (makePointContour, lineSegsOfContour)
import Graphics.Slicer.Math.Definitions (Contour, LineSeg, Point2, mapWithFollower, endPoint, makeLineSeg, startPoint)
import Graphics.Slicer.Math.Ganja (dumpGanja)
import Graphics.Slicer.Math.GeometricAlgebra (ulpVal)
import Graphics.Slicer.Math.Intersections (intersectionBetween, intersectionOf, noIntersection)
import Graphics.Slicer.Math.Skeleton.Face (Face(Face))
import Graphics.Slicer.Math.Lossy (distancePPointToPLineWithErr, eToPLine2, pToEPoint2)
import Graphics.Slicer.Math.PGA (PIntersection (IntersectsIn, PCollinear, PParallel), PLine2Err, ProjectiveLine, ProjectiveLine2, distance2PP, eToPL, eToPP, fuzzinessOfL, normalizeL, pLineErrAtPPoint, plinesIntersectIn, pLineIsLeft, pToEP, translateL)
import Graphics.Slicer.Machine.Contour (cleanContour)
import Graphics.Implicit.Definitions (ℝ, Fastℕ)
------------------------------------------------------------------
------------------ Line Segment Placement ------------------------
------------------------------------------------------------------
-- | Inset the given set of faces, returning new outside contours, and a new set of faces.
-- Requires the faces are a closed set, AKA, a set of faces created from a contour.
-- FIXME: handle inset requests that result in multiple contours.
insetBy :: ℝ -> Slist Face -> ([Contour], [Face])
insetBy distance faces
| null (concat lineSegSets) = ([], [])
| length (concat lineSegSets) < 3 = error "less than three, but not zero?"
| otherwise = (contours, remainingFaces)
where
contours = reclaimContours lineSegSets
lineSegSets = fst <$> res
remainingFaces = concat $ mapMaybe snd res
res = addLineSegsToFace distance (Just 1) <$> (\(Slist a _) -> a) faces
-- FUTUREWORK: Add a function that takes the contour formed by the remainders of the faces, and squeezes in a line segment, if possible.
-- | Cover a contour with lines, aligned to the faces of the contour.
-- FIXME: this should be returning a ContourTree.
infiniteInset :: ℝ -> Slist Face -> [[LineSeg]]
infiniteInset distance faces
| null (concat lineSegSets) = []
| length (concat lineSegSets) < 3 = error "less than three, but not zero?"
| otherwise = lineSegsOfContour <$> contours
where
contours = reclaimContours lineSegSets
lineSegSets = fst <$> res
res = addLineSegsToFace distance Nothing <$> (\(Slist a _) -> a) faces
| Place line segments on a face , parallel to the edge . Might return remainders , in the form of un - filled faces .
FIXME : return a ( ( ProjectivePoint , ) , ( ProjectivePoint , ) ) pair , so we can operate on it during contour reclamation without precision loss .
addLineSegsToFace :: ℝ -> Maybe Fastℕ -> Face -> ([LineSeg], Maybe [Face])
addLineSegsToFace distance insets face
-- we were called, but instructed to do nothing.
| isJust insets && fromJust insets < 1 = ([], Just [face])
| len midArcs == 0 = (foundLineSegs, twoSideRemainder)
| len midArcs == 1 = (foundLineSegs <> twoSideSubLineSegs, threeSideRemainder)
| otherwise = (foundLineSegs <> sides1 <> sides2, nSideRemainder)
where
-- | Run checks on our input face.
checkedFace@(Face edge firstArc midArcs@(Slist rawMidArcs _) lastArc) = checkFace face
where
checkFace inFace@(Face myEdge myFirstArc (Slist myMidArcs _) myLastArc)
| all (isRight . fromMaybe (error "wheee!")) intersections = inFace
| otherwise = error $ "given a degenerate face: \n"
<> show face <> "\n"
<> show intersections <> "\n"
<> show insets <> "\n"
where
intersections = mapWithFollower intersectionBetween $ eToPL myEdge : myFirstArc : myMidArcs <> [myLastArc]
-- | Subtract the line segments we place in this round from the input inset count.
-- Used to determine if we should recurse.
-- Just 0 or less == terminate, do not recurse.
-- Nothing = recurse until we run out of space in the Face.
subInsets = if isJust insets
then Just $ fromJust insets - linesToRender
else Nothing
-----------------------------------------------------------------------------------------
-- functions that are the same, regardless of number of sides of the ngon we are filling.
-----------------------------------------------------------------------------------------
-- | The direction we need to translate our edge in order for it to be going inward.
translateDir v = case eToPLine2 edge `pLineIsLeft` (fst firstArc) of
(Just True) -> (-v)
(Just False) -> v
Nothing -> error $ "cannot happen: edge and firstArc do not intersect?\n"
<> show distance <> "\n"
<> show insets <> "\n"
<> show face <> "\n"
<> show (normalizeL $ fst $ eToPL edge) <> "\n"
<> show (normalizeL $ fst firstArc) <> "\n"
<> show (plinesIntersectIn firstArc $ eToPL edge) <> "\n"
<> dumpGanja face <> "\n"
-- | How many lines we are going to place in this recursion. If inset is Nothing, cover the face entirely.
linesToRender = maybe availableLines (min availableLines) insets
where
availableLines = linesUntilEnd distance checkedFace
-- | The line segments we are placing.
foundLineSegs = [ makeLineSeg (pToEPoint2 $ fst $ safeIntersectionOf newSide firstArc) (pToEPoint2 $ fst $ safeIntersectionOf newSide lastArc) | newSide <- newSides ]
where
newSides = [ translateL (eToPLine2 edge) $ translateDir (-(distance+(distance * fromIntegral segmentNum))) | segmentNum <- [0..linesToRender-1] ]
| The line where we are no longer able to fill this face . from the firstArc to the lastArc , along the point that the lines we place stop .
finalSide = makeLineSeg (pToEPoint2 $ fst firstIntersection) (pToEPoint2 $ fst lastIntersection)
where
firstIntersection = safeIntersectionOf finalLine firstArc
lastIntersection = safeIntersectionOf finalLine lastArc
finalLine = translateL (eToPLine2 edge) $ translateDir (distance * fromIntegral linesToRender)
-- | A wrapper, for generating smart errors.
safeIntersectionOf a b
| noIntersection a b = error $ "given a non-intersecting pair of lines."
<> show a <> "\n"
<> show b <> "\n"
<> show (plinesIntersectIn a b) <> "\n"
<> showInputs
| otherwise = intersectionOf a b
-- | dump our inputs, in case of failure.
showInputs = "edge: " <> show edge <> "\n"
<> "edgeLine: \n" <> show (normalizeL $ fst $ eToPL edge) <> "\n"
<> "firstArc: \n" <> show firstArc <> "\n"
<> "midArcs: \n" <> show midArcs <> "\n"
<> "lastArc: \n" <> show lastArc <> "\n"
-----------------------------------------------------------
functions only used by n - gons with more than four sides .
-----------------------------------------------------------
nSideRemainder = case fromMaybe [] remains1 <> fromMaybe [] remains2 of
res@(_:_) -> Just res
[] -> error "no remains for an nSideRemainder?"
closestArc = (\(_,(b,_)) -> b) $ findClosestArc edge firstArc rawMidArcs lastArc
closestArcFollower = (\(_,(_,c)) -> c) $ findClosestArc edge firstArc rawMidArcs lastArc
-- | Return all of the arcs before and including the closest arc.
untilArc = if closestArc == firstArc
then [firstArc]
else takeWhile (/= closestArcFollower) $ rawMidArcs <> [lastArc]
-- | Return all of the arcs after the closest arc.
afterArc = dropWhile (/= closestArcFollower) $ rawMidArcs <> [lastArc]
(sides1, remains1) = if closestArc == firstArc
then noResult
else result firstArc untilArc
(sides2, remains2) = case unsnoc rawMidArcs of
Nothing -> noResult
Just (_,a) -> if closestArc == a
then noResult
else result closestArcFollower afterArc
noResult = ([],Nothing)
result begin arcs = case uncons arcs of
Nothing -> error "unpossible!"
Just (_,[]) -> addLineSegsToFace distance subInsets (makeFace finalSide begin (slist []) lastArc)
Just (_,manyArcs) -> addLineSegsToFace distance subInsets (makeFace finalSide begin remainingArcs lastArc)
where
remainingArcs = case unsnoc manyArcs of
Nothing -> error "unpossible!"
Just (as,_) -> slist as
---------------------------------------------
functions only used by a four - sided n - gon .
---------------------------------------------
threeSideRemainder
| null foundLineSegs = Nothing
| otherwise = case plinesIntersectIn edgeLine lastPlacedLine of
PCollinear -> Nothing
PParallel -> Just [makeFaceNoCheck finalSide firstArc (slist [midArc]) lastArc]
_ -> twoSideSubRemainder
Recurse , so we get the remainder and line segments of the three sided n - gon left over .
(twoSideSubLineSegs,
twoSideSubRemainder)
| null foundLineSegs = ([],Nothing)
| otherwise = case plinesIntersectIn edgeLine lastPlacedLine of
PCollinear -> ([], Nothing)
_ -> if firstArcEndsFarthest edge firstArc (head midArcs) lastArc
then addLineSegsToFace distance subInsets (makeFace finalSide firstArc (slist []) midArc)
else addLineSegsToFace distance subInsets (makeFace finalSide midArc (slist []) lastArc)
edgeLine = eToPL edge
lastPlacedLine = eToPL $ last foundLineSegs
midArc = case midArcs of
(Slist [oneArc] 1) -> oneArc
(Slist _ _) -> error $ "evaluated midArc with the wrong insets of items.\n"
<> "d: " <> show distance <> "\n"
<> "n: " <> show insets <> "\n"
<> "Face: " <> show face <> "\n"
----------------------------------------------
functions only used by a three - sided n - gon .
----------------------------------------------
twoSideRemainder = if distance * fromIntegral linesToRender /= distanceUntilEnd checkedFace
then Just [makeFaceNoCheck finalSide firstArc (slist []) lastArc]
else Nothing
-- | How many lines can be drawn onto a given Face, parallel to the face.
linesUntilEnd :: ℝ -> Face -> Fastℕ
linesUntilEnd distance face = floor (distanceUntilEnd face / distance)
-- | What is the distance from the edge of a face to the place where we can no longer place lines.
distanceUntilEnd :: Face -> ℝ
distanceUntilEnd (Face edge firstArc midArcs@(Slist rawMidArcs _) lastArc)
| isEmpty midArcs = distancePPointToPLineWithErr crossIntersection edgeLine
| len midArcs == 1 = if firstArcEndsFarthest edge firstArc midArc lastArc
then distancePPointToPLineWithErr firstIntersection edgeLine
else distancePPointToPLineWithErr lastIntersection edgeLine
| otherwise = fst $ findClosestArc edge firstArc rawMidArcs lastArc
where
firstIntersection = safeIntersectionOf firstArc midArc
lastIntersection = safeIntersectionOf midArc lastArc
crossIntersection = safeIntersectionOf firstArc lastArc
safeIntersectionOf a b
| noIntersection a b = error $ "given a non-intersecting pair of lines."
<> show a <> "\n"
<> show b <> "\n"
<> show (plinesIntersectIn a b) <> "\n"
<> showInputs
| otherwise = intersectionOf a b
showInputs = "edge: " <> show edge <> "\n"
<> "firstArc: \n" <> show firstArc <> "\n"
<> "midArcs: \n" <> show midArcs <> "\n"
<> "lastArc: \n" <> show lastArc <> "\n"
edgeLine = eToPL edge
midArc = head midArcs
| for a face with four sides , see which arc attached to the face ends the furthest away from the line of the face .
firstArcEndsFarthest :: (ProjectiveLine2 a) => LineSeg -> (a, PLine2Err) -> (a, PLine2Err) -> (a, PLine2Err) -> Bool
firstArcEndsFarthest edge firstArc midArc lastArc = distancePPointToPLineWithErr firstIntersection edgeLine > distancePPointToPLineWithErr lastIntersection edgeLine
where
firstIntersection = safeIntersectionOf firstArc midArc
lastIntersection = safeIntersectionOf midArc lastArc
safeIntersectionOf a b
| noIntersection a b = error $ "given a non-intersecting pair of lines."
<> show a <> "\n"
<> show b <> "\n"
<> show (plinesIntersectIn a b) <> "\n"
<> showInputs
| otherwise = intersectionOf a b
showInputs = "edge: " <> show edge <> "\n"
<> "firstArc: \n" <> show firstArc <> "\n"
<> "midArc: \n" <> show midArc <> "\n"
<> "lastArc: \n" <> show lastArc <> "\n"
edgeLine = eToPL edge
findClosestArc :: LineSeg -> (ProjectiveLine, PLine2Err) -> [(ProjectiveLine, PLine2Err)] -> (ProjectiveLine, PLine2Err) -> (ℝ, ((ProjectiveLine, PLine2Err), (ProjectiveLine, PLine2Err)))
findClosestArc edge firstArc rawMidArcs lastArc = case sortOn fst arcIntersections of
[] -> error "empty arcIntersections?"
[pair] -> pair
(pair:_) -> pair
where
| Find the closest point where two of our arcs intersect , relative to our side .
arcIntersections = case unsnoc $ mapWithFollower (\a b -> (distancePPointToPLineWithErr (safeIntersectionOf a b) (eToPL edge), (a, b))) $ firstArc : rawMidArcs <> [lastArc] of
Nothing -> []
Just (xs,_) -> xs
safeIntersectionOf a b
| noIntersection a b = error $ "given a non-intersecting pair of lines."
<> show a <> "\n"
<> show b <> "\n"
<> show (plinesIntersectIn a b) <> "\n"
<> showInputs
| otherwise = intersectionOf a b
showInputs = "edge: " <> show edge <> "\n"
<> "firstArc: \n" <> show firstArc <> "\n"
<> "midArcs: \n" <> show rawMidArcs <> "\n"
<> "lastArc: \n" <> show lastArc <> "\n"
-- | Take the output of many calls to addLineSegsToFace, and construct contours from them.
reclaimContours :: [[LineSeg]] -> [Contour]
reclaimContours lineSegSets = if all isJust reclaimedRings && all isJust cleanedContours
then catMaybes cleanedContours
else error $ "failed to clean a contour in rings: " <> show rings <> "\n"
where
cleanedContours = cleanContour <$> concat (fromJust <$> reclaimedRings)
reclaimedRings = reclaimRing <$> rings
-- The input set of line segments has all of the line segments that cover a face in the same list.
-- by transposing them, we get lists of rings around the object, rather than covered petals.
rings = transpose lineSegSets
-- | tage a ring around N contours, and generate the contours.
-- FIXME: not handling breaks yet.
reclaimRing :: [LineSeg] -> Maybe [Contour]
reclaimRing ring = case filter (\(a,_) -> isNothing a) reclaimedContour of
[] -> Just [makePointContour $ fromJust . fst <$> reclaimedContour]
[a] -> error $ "found one break in ring: " <> show ring <> " at " <> show a <> "\n"
_ -> Nothing
where
reclaimedContour = mapWithFollower recovery ring
where
detect if two line segments SHOULD end at the same point , and if they do , return the point .
recovery :: LineSeg -> LineSeg -> (Maybe Point2, (LineSeg, LineSeg))
recovery l1 l2
| endPoint l2 == startPoint l1 = (Just $ endPoint l2, (l1, l2))
FIXME : we should use intersection for line segments close to 90 degrees , and average for segments closest to parallel ?
| l1l2Distance <= l1l2DistanceErr = (Just $ fst $ pToEP $ fst $ intersectionOf (eToPL l2) (eToPL l1), (l1,l2))
| otherwise = (Nothing, (l1,l2))
where
- FIXME : magic number : 512
l1l2DistanceErr = 512 * ulpVal (l1l2DistanceErrRaw
<> pLineErrAtPPoint (eToPL l1) (eToPP $ startPoint l1)
<> fuzzinessOfL (eToPL l1)
<> pLineErrAtPPoint (eToPL l2) (eToPP $ endPoint l2)
<> fuzzinessOfL (eToPL l2))
(l1l2Distance, (_, _, l1l2DistanceErrRaw)) = distance2PP (eToPP $ endPoint l2, mempty) (eToPP $ startPoint l1, mempty)
-- | A face constructor that checks that a face is valid during construction.
makeFace :: LineSeg -> (ProjectiveLine, PLine2Err) -> Slist (ProjectiveLine, PLine2Err) -> (ProjectiveLine, PLine2Err) -> Face
makeFace edge firstArc arcs lastArc = res
where
res = checkFace $ Face edge firstArc arcs lastArc
checkFace inFace@(Face myEdge myFirstArc (Slist myMidArcs _) myLastArc)
| all isIntersection intersections = inFace
| otherwise = error $ "Tried to generate a degenerate face: "
<> show inFace <> "\n"
<> show intersections <> "\n"
where
isIntersection intersection = case intersection of
(IntersectsIn _ _) -> True
_ -> False
intersections = mapWithFollower plinesIntersectIn $ eToPL myEdge : myFirstArc : myMidArcs <> [myLastArc]
-- | a Face constructor with no checking.
makeFaceNoCheck :: LineSeg -> (ProjectiveLine, PLine2Err) -> Slist (ProjectiveLine, PLine2Err) -> (ProjectiveLine, PLine2Err) -> Face
makeFaceNoCheck edge firstArc arcs lastArc = res
where
res = Face edge firstArc arcs lastArc
| null | https://raw.githubusercontent.com/Haskell-Things/HSlice/dd6a26725d3b4b51f0f968425d63f2bde7bc03c6/Graphics/Slicer/Math/Skeleton/Line.hs | haskell | ORMOLU_DISABLE
inherit instances when deriving.
| Functions for for applying inset line segments to a series of faces, and for adding infill to a face.
----------------------------------------------------------------
---------------- Line Segment Placement ------------------------
----------------------------------------------------------------
| Inset the given set of faces, returning new outside contours, and a new set of faces.
Requires the faces are a closed set, AKA, a set of faces created from a contour.
FIXME: handle inset requests that result in multiple contours.
FUTUREWORK: Add a function that takes the contour formed by the remainders of the faces, and squeezes in a line segment, if possible.
| Cover a contour with lines, aligned to the faces of the contour.
FIXME: this should be returning a ContourTree.
we were called, but instructed to do nothing.
| Run checks on our input face.
| Subtract the line segments we place in this round from the input inset count.
Used to determine if we should recurse.
Just 0 or less == terminate, do not recurse.
Nothing = recurse until we run out of space in the Face.
---------------------------------------------------------------------------------------
functions that are the same, regardless of number of sides of the ngon we are filling.
---------------------------------------------------------------------------------------
| The direction we need to translate our edge in order for it to be going inward.
| How many lines we are going to place in this recursion. If inset is Nothing, cover the face entirely.
| The line segments we are placing.
| A wrapper, for generating smart errors.
| dump our inputs, in case of failure.
---------------------------------------------------------
---------------------------------------------------------
| Return all of the arcs before and including the closest arc.
| Return all of the arcs after the closest arc.
-------------------------------------------
-------------------------------------------
--------------------------------------------
--------------------------------------------
| How many lines can be drawn onto a given Face, parallel to the face.
| What is the distance from the edge of a face to the place where we can no longer place lines.
| Take the output of many calls to addLineSegsToFace, and construct contours from them.
The input set of line segments has all of the line segments that cover a face in the same list.
by transposing them, we get lists of rings around the object, rather than covered petals.
| tage a ring around N contours, and generate the contours.
FIXME: not handling breaks yet.
| A face constructor that checks that a face is valid during construction.
| a Face constructor with no checking. |
- Copyright 2020
-
- This program is free software : you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as published by
- the Free Software Foundation , either version 3 of the License , or
- ( at your option ) any later version .
-
- This program is distributed in the hope that it will be useful ,
- but WITHOUT ANY WARRANTY ; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
- GNU Affero General Public License for more details .
- You should have received a copy of the GNU Affero General Public License
- along with this program . If not , see < / > .
- Copyright 2020 Julia Longtin
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Affero General Public License for more details.
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see </>.
-}
# LANGUAGE DerivingStrategies #
module Graphics.Slicer.Math.Skeleton.Line (insetBy, infiniteInset) where
import Prelude ((==), all, concat, otherwise, (<$>), (<=), (&&), ($), (/=), error, (<>), show, (<>), (/), floor, fromIntegral, (+), (*), (-), (.), (<>), (>), (<), min, Bool(True, False), filter, fst, maybe, mempty, null, snd)
import Data.Either (isRight)
import Data.List (sortOn, dropWhile, last, length, takeWhile, transpose, uncons)
import Data.List.Extra (unsnoc)
import Data.Maybe (Maybe(Just,Nothing), catMaybes, fromMaybe, fromJust, isJust, isNothing, mapMaybe)
import Slist (head, isEmpty, len, slist)
import Slist.Type (Slist(Slist))
import Graphics.Slicer.Math.Contour (makePointContour, lineSegsOfContour)
import Graphics.Slicer.Math.Definitions (Contour, LineSeg, Point2, mapWithFollower, endPoint, makeLineSeg, startPoint)
import Graphics.Slicer.Math.Ganja (dumpGanja)
import Graphics.Slicer.Math.GeometricAlgebra (ulpVal)
import Graphics.Slicer.Math.Intersections (intersectionBetween, intersectionOf, noIntersection)
import Graphics.Slicer.Math.Skeleton.Face (Face(Face))
import Graphics.Slicer.Math.Lossy (distancePPointToPLineWithErr, eToPLine2, pToEPoint2)
import Graphics.Slicer.Math.PGA (PIntersection (IntersectsIn, PCollinear, PParallel), PLine2Err, ProjectiveLine, ProjectiveLine2, distance2PP, eToPL, eToPP, fuzzinessOfL, normalizeL, pLineErrAtPPoint, plinesIntersectIn, pLineIsLeft, pToEP, translateL)
import Graphics.Slicer.Machine.Contour (cleanContour)
import Graphics.Implicit.Definitions (ℝ, Fastℕ)
insetBy :: ℝ -> Slist Face -> ([Contour], [Face])
insetBy distance faces
| null (concat lineSegSets) = ([], [])
| length (concat lineSegSets) < 3 = error "less than three, but not zero?"
| otherwise = (contours, remainingFaces)
where
contours = reclaimContours lineSegSets
lineSegSets = fst <$> res
remainingFaces = concat $ mapMaybe snd res
res = addLineSegsToFace distance (Just 1) <$> (\(Slist a _) -> a) faces
infiniteInset :: ℝ -> Slist Face -> [[LineSeg]]
infiniteInset distance faces
| null (concat lineSegSets) = []
| length (concat lineSegSets) < 3 = error "less than three, but not zero?"
| otherwise = lineSegsOfContour <$> contours
where
contours = reclaimContours lineSegSets
lineSegSets = fst <$> res
res = addLineSegsToFace distance Nothing <$> (\(Slist a _) -> a) faces
| Place line segments on a face , parallel to the edge . Might return remainders , in the form of un - filled faces .
FIXME : return a ( ( ProjectivePoint , ) , ( ProjectivePoint , ) ) pair , so we can operate on it during contour reclamation without precision loss .
addLineSegsToFace :: ℝ -> Maybe Fastℕ -> Face -> ([LineSeg], Maybe [Face])
addLineSegsToFace distance insets face
| isJust insets && fromJust insets < 1 = ([], Just [face])
| len midArcs == 0 = (foundLineSegs, twoSideRemainder)
| len midArcs == 1 = (foundLineSegs <> twoSideSubLineSegs, threeSideRemainder)
| otherwise = (foundLineSegs <> sides1 <> sides2, nSideRemainder)
where
checkedFace@(Face edge firstArc midArcs@(Slist rawMidArcs _) lastArc) = checkFace face
where
checkFace inFace@(Face myEdge myFirstArc (Slist myMidArcs _) myLastArc)
| all (isRight . fromMaybe (error "wheee!")) intersections = inFace
| otherwise = error $ "given a degenerate face: \n"
<> show face <> "\n"
<> show intersections <> "\n"
<> show insets <> "\n"
where
intersections = mapWithFollower intersectionBetween $ eToPL myEdge : myFirstArc : myMidArcs <> [myLastArc]
subInsets = if isJust insets
then Just $ fromJust insets - linesToRender
else Nothing
translateDir v = case eToPLine2 edge `pLineIsLeft` (fst firstArc) of
(Just True) -> (-v)
(Just False) -> v
Nothing -> error $ "cannot happen: edge and firstArc do not intersect?\n"
<> show distance <> "\n"
<> show insets <> "\n"
<> show face <> "\n"
<> show (normalizeL $ fst $ eToPL edge) <> "\n"
<> show (normalizeL $ fst firstArc) <> "\n"
<> show (plinesIntersectIn firstArc $ eToPL edge) <> "\n"
<> dumpGanja face <> "\n"
linesToRender = maybe availableLines (min availableLines) insets
where
availableLines = linesUntilEnd distance checkedFace
foundLineSegs = [ makeLineSeg (pToEPoint2 $ fst $ safeIntersectionOf newSide firstArc) (pToEPoint2 $ fst $ safeIntersectionOf newSide lastArc) | newSide <- newSides ]
where
newSides = [ translateL (eToPLine2 edge) $ translateDir (-(distance+(distance * fromIntegral segmentNum))) | segmentNum <- [0..linesToRender-1] ]
| The line where we are no longer able to fill this face . from the firstArc to the lastArc , along the point that the lines we place stop .
finalSide = makeLineSeg (pToEPoint2 $ fst firstIntersection) (pToEPoint2 $ fst lastIntersection)
where
firstIntersection = safeIntersectionOf finalLine firstArc
lastIntersection = safeIntersectionOf finalLine lastArc
finalLine = translateL (eToPLine2 edge) $ translateDir (distance * fromIntegral linesToRender)
safeIntersectionOf a b
| noIntersection a b = error $ "given a non-intersecting pair of lines."
<> show a <> "\n"
<> show b <> "\n"
<> show (plinesIntersectIn a b) <> "\n"
<> showInputs
| otherwise = intersectionOf a b
showInputs = "edge: " <> show edge <> "\n"
<> "edgeLine: \n" <> show (normalizeL $ fst $ eToPL edge) <> "\n"
<> "firstArc: \n" <> show firstArc <> "\n"
<> "midArcs: \n" <> show midArcs <> "\n"
<> "lastArc: \n" <> show lastArc <> "\n"
functions only used by n - gons with more than four sides .
nSideRemainder = case fromMaybe [] remains1 <> fromMaybe [] remains2 of
res@(_:_) -> Just res
[] -> error "no remains for an nSideRemainder?"
closestArc = (\(_,(b,_)) -> b) $ findClosestArc edge firstArc rawMidArcs lastArc
closestArcFollower = (\(_,(_,c)) -> c) $ findClosestArc edge firstArc rawMidArcs lastArc
untilArc = if closestArc == firstArc
then [firstArc]
else takeWhile (/= closestArcFollower) $ rawMidArcs <> [lastArc]
afterArc = dropWhile (/= closestArcFollower) $ rawMidArcs <> [lastArc]
(sides1, remains1) = if closestArc == firstArc
then noResult
else result firstArc untilArc
(sides2, remains2) = case unsnoc rawMidArcs of
Nothing -> noResult
Just (_,a) -> if closestArc == a
then noResult
else result closestArcFollower afterArc
noResult = ([],Nothing)
result begin arcs = case uncons arcs of
Nothing -> error "unpossible!"
Just (_,[]) -> addLineSegsToFace distance subInsets (makeFace finalSide begin (slist []) lastArc)
Just (_,manyArcs) -> addLineSegsToFace distance subInsets (makeFace finalSide begin remainingArcs lastArc)
where
remainingArcs = case unsnoc manyArcs of
Nothing -> error "unpossible!"
Just (as,_) -> slist as
functions only used by a four - sided n - gon .
threeSideRemainder
| null foundLineSegs = Nothing
| otherwise = case plinesIntersectIn edgeLine lastPlacedLine of
PCollinear -> Nothing
PParallel -> Just [makeFaceNoCheck finalSide firstArc (slist [midArc]) lastArc]
_ -> twoSideSubRemainder
Recurse , so we get the remainder and line segments of the three sided n - gon left over .
(twoSideSubLineSegs,
twoSideSubRemainder)
| null foundLineSegs = ([],Nothing)
| otherwise = case plinesIntersectIn edgeLine lastPlacedLine of
PCollinear -> ([], Nothing)
_ -> if firstArcEndsFarthest edge firstArc (head midArcs) lastArc
then addLineSegsToFace distance subInsets (makeFace finalSide firstArc (slist []) midArc)
else addLineSegsToFace distance subInsets (makeFace finalSide midArc (slist []) lastArc)
edgeLine = eToPL edge
lastPlacedLine = eToPL $ last foundLineSegs
midArc = case midArcs of
(Slist [oneArc] 1) -> oneArc
(Slist _ _) -> error $ "evaluated midArc with the wrong insets of items.\n"
<> "d: " <> show distance <> "\n"
<> "n: " <> show insets <> "\n"
<> "Face: " <> show face <> "\n"
functions only used by a three - sided n - gon .
twoSideRemainder = if distance * fromIntegral linesToRender /= distanceUntilEnd checkedFace
then Just [makeFaceNoCheck finalSide firstArc (slist []) lastArc]
else Nothing
linesUntilEnd :: ℝ -> Face -> Fastℕ
linesUntilEnd distance face = floor (distanceUntilEnd face / distance)
distanceUntilEnd :: Face -> ℝ
distanceUntilEnd (Face edge firstArc midArcs@(Slist rawMidArcs _) lastArc)
| isEmpty midArcs = distancePPointToPLineWithErr crossIntersection edgeLine
| len midArcs == 1 = if firstArcEndsFarthest edge firstArc midArc lastArc
then distancePPointToPLineWithErr firstIntersection edgeLine
else distancePPointToPLineWithErr lastIntersection edgeLine
| otherwise = fst $ findClosestArc edge firstArc rawMidArcs lastArc
where
firstIntersection = safeIntersectionOf firstArc midArc
lastIntersection = safeIntersectionOf midArc lastArc
crossIntersection = safeIntersectionOf firstArc lastArc
safeIntersectionOf a b
| noIntersection a b = error $ "given a non-intersecting pair of lines."
<> show a <> "\n"
<> show b <> "\n"
<> show (plinesIntersectIn a b) <> "\n"
<> showInputs
| otherwise = intersectionOf a b
showInputs = "edge: " <> show edge <> "\n"
<> "firstArc: \n" <> show firstArc <> "\n"
<> "midArcs: \n" <> show midArcs <> "\n"
<> "lastArc: \n" <> show lastArc <> "\n"
edgeLine = eToPL edge
midArc = head midArcs
| for a face with four sides , see which arc attached to the face ends the furthest away from the line of the face .
firstArcEndsFarthest :: (ProjectiveLine2 a) => LineSeg -> (a, PLine2Err) -> (a, PLine2Err) -> (a, PLine2Err) -> Bool
firstArcEndsFarthest edge firstArc midArc lastArc = distancePPointToPLineWithErr firstIntersection edgeLine > distancePPointToPLineWithErr lastIntersection edgeLine
where
firstIntersection = safeIntersectionOf firstArc midArc
lastIntersection = safeIntersectionOf midArc lastArc
safeIntersectionOf a b
| noIntersection a b = error $ "given a non-intersecting pair of lines."
<> show a <> "\n"
<> show b <> "\n"
<> show (plinesIntersectIn a b) <> "\n"
<> showInputs
| otherwise = intersectionOf a b
showInputs = "edge: " <> show edge <> "\n"
<> "firstArc: \n" <> show firstArc <> "\n"
<> "midArc: \n" <> show midArc <> "\n"
<> "lastArc: \n" <> show lastArc <> "\n"
edgeLine = eToPL edge
findClosestArc :: LineSeg -> (ProjectiveLine, PLine2Err) -> [(ProjectiveLine, PLine2Err)] -> (ProjectiveLine, PLine2Err) -> (ℝ, ((ProjectiveLine, PLine2Err), (ProjectiveLine, PLine2Err)))
findClosestArc edge firstArc rawMidArcs lastArc = case sortOn fst arcIntersections of
[] -> error "empty arcIntersections?"
[pair] -> pair
(pair:_) -> pair
where
| Find the closest point where two of our arcs intersect , relative to our side .
arcIntersections = case unsnoc $ mapWithFollower (\a b -> (distancePPointToPLineWithErr (safeIntersectionOf a b) (eToPL edge), (a, b))) $ firstArc : rawMidArcs <> [lastArc] of
Nothing -> []
Just (xs,_) -> xs
safeIntersectionOf a b
| noIntersection a b = error $ "given a non-intersecting pair of lines."
<> show a <> "\n"
<> show b <> "\n"
<> show (plinesIntersectIn a b) <> "\n"
<> showInputs
| otherwise = intersectionOf a b
showInputs = "edge: " <> show edge <> "\n"
<> "firstArc: \n" <> show firstArc <> "\n"
<> "midArcs: \n" <> show rawMidArcs <> "\n"
<> "lastArc: \n" <> show lastArc <> "\n"
reclaimContours :: [[LineSeg]] -> [Contour]
reclaimContours lineSegSets = if all isJust reclaimedRings && all isJust cleanedContours
then catMaybes cleanedContours
else error $ "failed to clean a contour in rings: " <> show rings <> "\n"
where
cleanedContours = cleanContour <$> concat (fromJust <$> reclaimedRings)
reclaimedRings = reclaimRing <$> rings
rings = transpose lineSegSets
reclaimRing :: [LineSeg] -> Maybe [Contour]
reclaimRing ring = case filter (\(a,_) -> isNothing a) reclaimedContour of
[] -> Just [makePointContour $ fromJust . fst <$> reclaimedContour]
[a] -> error $ "found one break in ring: " <> show ring <> " at " <> show a <> "\n"
_ -> Nothing
where
reclaimedContour = mapWithFollower recovery ring
where
detect if two line segments SHOULD end at the same point , and if they do , return the point .
recovery :: LineSeg -> LineSeg -> (Maybe Point2, (LineSeg, LineSeg))
recovery l1 l2
| endPoint l2 == startPoint l1 = (Just $ endPoint l2, (l1, l2))
FIXME : we should use intersection for line segments close to 90 degrees , and average for segments closest to parallel ?
| l1l2Distance <= l1l2DistanceErr = (Just $ fst $ pToEP $ fst $ intersectionOf (eToPL l2) (eToPL l1), (l1,l2))
| otherwise = (Nothing, (l1,l2))
where
- FIXME : magic number : 512
l1l2DistanceErr = 512 * ulpVal (l1l2DistanceErrRaw
<> pLineErrAtPPoint (eToPL l1) (eToPP $ startPoint l1)
<> fuzzinessOfL (eToPL l1)
<> pLineErrAtPPoint (eToPL l2) (eToPP $ endPoint l2)
<> fuzzinessOfL (eToPL l2))
(l1l2Distance, (_, _, l1l2DistanceErrRaw)) = distance2PP (eToPP $ endPoint l2, mempty) (eToPP $ startPoint l1, mempty)
makeFace :: LineSeg -> (ProjectiveLine, PLine2Err) -> Slist (ProjectiveLine, PLine2Err) -> (ProjectiveLine, PLine2Err) -> Face
makeFace edge firstArc arcs lastArc = res
where
res = checkFace $ Face edge firstArc arcs lastArc
checkFace inFace@(Face myEdge myFirstArc (Slist myMidArcs _) myLastArc)
| all isIntersection intersections = inFace
| otherwise = error $ "Tried to generate a degenerate face: "
<> show inFace <> "\n"
<> show intersections <> "\n"
where
isIntersection intersection = case intersection of
(IntersectsIn _ _) -> True
_ -> False
intersections = mapWithFollower plinesIntersectIn $ eToPL myEdge : myFirstArc : myMidArcs <> [myLastArc]
makeFaceNoCheck :: LineSeg -> (ProjectiveLine, PLine2Err) -> Slist (ProjectiveLine, PLine2Err) -> (ProjectiveLine, PLine2Err) -> Face
makeFaceNoCheck edge firstArc arcs lastArc = res
where
res = Face edge firstArc arcs lastArc
|
4cd005d34d9ea946907c630ae9ebe1a1c63259ec7072626163621e16e2b3a47f | tfausak/monadoc-5 | MonadocSpec.hs | module MonadocSpec where
import qualified Monadoc
import Monadoc.Prelude
import qualified Monadoc.Type.Config as Config
import qualified Monadoc.Type.ConfigResult as ConfigResult
import qualified Monadoc.Type.Context as Context
import Test.Hspec
spec :: Spec
spec = describe "Monadoc" <| do
describe "argumentsToConfigResult" <| do
it "returns the default with no arguments" <| do
Monadoc.argumentsToConfigResult "x" []
`shouldBe` ConfigResult.Success [] Config.initial
it "shows the help" <| do
Monadoc.argumentsToConfigResult "x" ["--help"] `shouldSatisfy` isExitWith
it "shows the version" <| do
Monadoc.argumentsToConfigResult "x" ["--version"]
`shouldSatisfy` isExitWith
it "fails when given disallowed argument" <| do
Monadoc.argumentsToConfigResult "x" ["--help=0"]
`shouldSatisfy` isFailure
it "warns when given unexpected parameters" <| do
case Monadoc.argumentsToConfigResult "x" ["y"] of
ConfigResult.Success msgs _ -> msgs `shouldSatisfy` present
result -> result `shouldSatisfy` isSuccess
it "warns when given unknown options" <| do
case Monadoc.argumentsToConfigResult "x" ["-y"] of
ConfigResult.Success msgs _ -> msgs `shouldSatisfy` present
result -> result `shouldSatisfy` isSuccess
it "sets the port" <| do
case Monadoc.argumentsToConfigResult "x" ["--port=123"] of
ConfigResult.Success _ cfg -> Config.port cfg `shouldBe` 123
result -> result `shouldSatisfy` isSuccess
describe "configToContext" <| do
it "works" <| do
ctx <- Monadoc.configToContext Config.test
Context.config ctx `shouldBe` Config.test
isExitWith :: ConfigResult.ConfigResult -> Bool
isExitWith configResult = case configResult of
ConfigResult.ExitWith _ -> True
_ -> False
isFailure :: ConfigResult.ConfigResult -> Bool
isFailure configResult = case configResult of
ConfigResult.Failure _ -> True
_ -> False
isSuccess :: ConfigResult.ConfigResult -> Bool
isSuccess configResult = case configResult of
ConfigResult.Success _ _ -> True
_ -> False
| null | https://raw.githubusercontent.com/tfausak/monadoc-5/5361dd1870072cf2771857adbe92658118ddaa27/src/test/MonadocSpec.hs | haskell | module MonadocSpec where
import qualified Monadoc
import Monadoc.Prelude
import qualified Monadoc.Type.Config as Config
import qualified Monadoc.Type.ConfigResult as ConfigResult
import qualified Monadoc.Type.Context as Context
import Test.Hspec
spec :: Spec
spec = describe "Monadoc" <| do
describe "argumentsToConfigResult" <| do
it "returns the default with no arguments" <| do
Monadoc.argumentsToConfigResult "x" []
`shouldBe` ConfigResult.Success [] Config.initial
it "shows the help" <| do
Monadoc.argumentsToConfigResult "x" ["--help"] `shouldSatisfy` isExitWith
it "shows the version" <| do
Monadoc.argumentsToConfigResult "x" ["--version"]
`shouldSatisfy` isExitWith
it "fails when given disallowed argument" <| do
Monadoc.argumentsToConfigResult "x" ["--help=0"]
`shouldSatisfy` isFailure
it "warns when given unexpected parameters" <| do
case Monadoc.argumentsToConfigResult "x" ["y"] of
ConfigResult.Success msgs _ -> msgs `shouldSatisfy` present
result -> result `shouldSatisfy` isSuccess
it "warns when given unknown options" <| do
case Monadoc.argumentsToConfigResult "x" ["-y"] of
ConfigResult.Success msgs _ -> msgs `shouldSatisfy` present
result -> result `shouldSatisfy` isSuccess
it "sets the port" <| do
case Monadoc.argumentsToConfigResult "x" ["--port=123"] of
ConfigResult.Success _ cfg -> Config.port cfg `shouldBe` 123
result -> result `shouldSatisfy` isSuccess
describe "configToContext" <| do
it "works" <| do
ctx <- Monadoc.configToContext Config.test
Context.config ctx `shouldBe` Config.test
isExitWith :: ConfigResult.ConfigResult -> Bool
isExitWith configResult = case configResult of
ConfigResult.ExitWith _ -> True
_ -> False
isFailure :: ConfigResult.ConfigResult -> Bool
isFailure configResult = case configResult of
ConfigResult.Failure _ -> True
_ -> False
isSuccess :: ConfigResult.ConfigResult -> Bool
isSuccess configResult = case configResult of
ConfigResult.Success _ _ -> True
_ -> False
|
|
4c3b31066470c038d2ea336881808061eddf8fa7a751b4ead81ac6f704deca80 | Helium4Haskell/helium | Irrefutable.hs | module Irrefutable where
main = (f True (3,4), f False undefined)
f :: Bool -> (Int, Int) -> Int
f lookInside ~(True, y) = if lookInside then 1 else 0
| null | https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/simple/typeerrors/Examples/Irrefutable.hs | haskell | module Irrefutable where
main = (f True (3,4), f False undefined)
f :: Bool -> (Int, Int) -> Int
f lookInside ~(True, y) = if lookInside then 1 else 0
|
|
f0b45bc05ea98beec160408153fc46b1e0e798ad02a5398eded82b3a1849beca | karamellpelle/grid | ShadeWall.hs | grid is a game written in Haskell
Copyright ( C ) 2018
--
-- This file is part of grid.
--
-- grid 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.
--
-- grid 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 grid. If not, see </>.
--
module Game.LevelPuzzle.LevelPuzzleData.Plain.ShadeWall
(
ShadeWall (..),
loadShadeWall,
unloadShadeWall,
) where
import MyPrelude
import File
import OpenGL
import OpenGL.Helpers
import OpenGL.Shade
data ShadeWall =
ShadeWall
{
shadeWallPrg :: !GLuint,
shadeWallUniAlpha :: !GLint,
shadeWallUniProjModvMatrix :: !GLint,
shadeWallUniNormalMatrix :: !GLint,
shadeWallUniRefDir :: !GLint,
shadeWallTex :: !GLuint
}
loadShadeWall :: IO ShadeWall
loadShadeWall = do
vsh <- fileStaticData "shaders/LevelWall.vsh"
fsh <- fileStaticData "shaders/LevelWall.fsh"
prg <- createPrg vsh fsh [ (attPos, "a_pos"),
(attNormal, "a_normal"),
(attTexCoord, "a_texcoord") ] [
(tex0, "u_tex") ]
uProjModvMatrix <- getUniformLocation prg "u_projmodv_matrix"
uNormalMatrix <- getUniformLocation prg "u_normal_matrix"
uAlpha <- getUniformLocation prg "u_alpha"
uRefDir <- getUniformLocation prg "u_ref_dir"
-- tex
tex <- makeTex "LevelPuzzle/Output/wall_tex.png"
tmp , set
glProgramUniform3fEXT prg uRefDir 1.0 0.0 0.0
return ShadeWall
{
shadeWallPrg = prg,
shadeWallUniAlpha = uAlpha,
shadeWallUniProjModvMatrix = uProjModvMatrix,
shadeWallUniNormalMatrix = uNormalMatrix,
shadeWallUniRefDir = uRefDir,
shadeWallTex = tex
}
where
makeTex path = do
tex <- bindNewTex gl_TEXTURE_2D
glTexParameteri gl_TEXTURE_2D gl_TEXTURE_MAG_FILTER $
fI gl_LINEAR
glTexParameteri gl_TEXTURE_2D gl_TEXTURE_MIN_FILTER $
fI gl_LINEAR_MIPMAP_LINEAR
glTexParameteri gl_TEXTURE_2D gl_TEXTURE_WRAP_S $
fI gl_CLAMP_TO_EDGE
glTexParameteri gl_TEXTURE_2D gl_TEXTURE_WRAP_T $
fI gl_CLAMP_TO_EDGE
path <- fileStaticData path
loadTexPreMult gl_TEXTURE_2D gl_RGBA path
glGenerateMipmap gl_TEXTURE_2D
return tex
unloadShadeWall :: ShadeWall -> IO ()
unloadShadeWall sh = do
return ()
-- fixme
| null | https://raw.githubusercontent.com/karamellpelle/grid/56729e63ed6404fd6cfd6d11e73fa358f03c386f/source/Game/LevelPuzzle/LevelPuzzleData/Plain/ShadeWall.hs | haskell |
This file is part of grid.
grid is free software: you can redistribute it and/or modify
(at your option) any later version.
grid is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with grid. If not, see </>.
tex
fixme | grid is a game written in Haskell
Copyright ( C ) 2018
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
module Game.LevelPuzzle.LevelPuzzleData.Plain.ShadeWall
(
ShadeWall (..),
loadShadeWall,
unloadShadeWall,
) where
import MyPrelude
import File
import OpenGL
import OpenGL.Helpers
import OpenGL.Shade
data ShadeWall =
ShadeWall
{
shadeWallPrg :: !GLuint,
shadeWallUniAlpha :: !GLint,
shadeWallUniProjModvMatrix :: !GLint,
shadeWallUniNormalMatrix :: !GLint,
shadeWallUniRefDir :: !GLint,
shadeWallTex :: !GLuint
}
loadShadeWall :: IO ShadeWall
loadShadeWall = do
vsh <- fileStaticData "shaders/LevelWall.vsh"
fsh <- fileStaticData "shaders/LevelWall.fsh"
prg <- createPrg vsh fsh [ (attPos, "a_pos"),
(attNormal, "a_normal"),
(attTexCoord, "a_texcoord") ] [
(tex0, "u_tex") ]
uProjModvMatrix <- getUniformLocation prg "u_projmodv_matrix"
uNormalMatrix <- getUniformLocation prg "u_normal_matrix"
uAlpha <- getUniformLocation prg "u_alpha"
uRefDir <- getUniformLocation prg "u_ref_dir"
tex <- makeTex "LevelPuzzle/Output/wall_tex.png"
tmp , set
glProgramUniform3fEXT prg uRefDir 1.0 0.0 0.0
return ShadeWall
{
shadeWallPrg = prg,
shadeWallUniAlpha = uAlpha,
shadeWallUniProjModvMatrix = uProjModvMatrix,
shadeWallUniNormalMatrix = uNormalMatrix,
shadeWallUniRefDir = uRefDir,
shadeWallTex = tex
}
where
makeTex path = do
tex <- bindNewTex gl_TEXTURE_2D
glTexParameteri gl_TEXTURE_2D gl_TEXTURE_MAG_FILTER $
fI gl_LINEAR
glTexParameteri gl_TEXTURE_2D gl_TEXTURE_MIN_FILTER $
fI gl_LINEAR_MIPMAP_LINEAR
glTexParameteri gl_TEXTURE_2D gl_TEXTURE_WRAP_S $
fI gl_CLAMP_TO_EDGE
glTexParameteri gl_TEXTURE_2D gl_TEXTURE_WRAP_T $
fI gl_CLAMP_TO_EDGE
path <- fileStaticData path
loadTexPreMult gl_TEXTURE_2D gl_RGBA path
glGenerateMipmap gl_TEXTURE_2D
return tex
unloadShadeWall :: ShadeWall -> IO ()
unloadShadeWall sh = do
return ()
|
3874fa7a8f928e4df758c589974dbd97e6339b3dbf9c8c71a725b32a7a5030ec | haskell/statistics | Resampling.hs | {-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE DeriveTraversable #-}
# LANGUAGE FlexibleContexts #
{-# LANGUAGE TypeFamilies #-}
-- |
-- Module : Statistics.Resampling
Copyright : ( c ) 2009 , 2010
-- License : BSD3
--
-- Maintainer :
-- Stability : experimental
-- Portability : portable
--
-- Resampling statistics.
module Statistics.Resampling
( -- * Data types
Resample(..)
, Bootstrap(..)
, Estimator(..)
, estimate
-- * Resampling
, resampleST
, resample
, resampleVector
-- * Jackknife
, jackknife
, jackknifeMean
, jackknifeVariance
, jackknifeVarianceUnb
, jackknifeStdDev
-- * Helper functions
, splitGen
) where
import Data.Aeson (FromJSON, ToJSON)
import Control.Concurrent.Async (forConcurrently_)
import Control.Monad (forM_, forM, replicateM, liftM2)
import Control.Monad.Primitive (PrimMonad(..))
import Data.Binary (Binary(..))
import Data.Data (Data, Typeable)
import Data.Vector.Algorithms.Intro (sort)
import Data.Vector.Binary ()
import Data.Vector.Generic (unsafeFreeze,unsafeThaw)
import Data.Word (Word32)
import qualified Data.Foldable as T
import qualified Data.Traversable as T
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as MU
import GHC.Conc (numCapabilities)
import GHC.Generics (Generic)
import Numeric.Sum (Summation(..), kbn)
import Statistics.Function (indices)
import Statistics.Sample (mean, stdDev, variance, varianceUnbiased)
import Statistics.Types (Sample)
import System.Random.MWC (Gen, GenIO, initialize, uniformR, uniformVector)
----------------------------------------------------------------
-- Data types
----------------------------------------------------------------
-- | A resample drawn randomly, with replacement, from a set of data
-- points. Distinct from a normal array to make it harder for your
-- humble author's brain to go wrong.
newtype Resample = Resample {
fromResample :: U.Vector Double
} deriving (Eq, Read, Show, Typeable, Data, Generic)
instance FromJSON Resample
instance ToJSON Resample
instance Binary Resample where
put = put . fromResample
get = fmap Resample get
data Bootstrap v a = Bootstrap
{ fullSample :: !a
, resamples :: v a
}
deriving (Eq, Read, Show , Generic, Functor, T.Foldable, T.Traversable
, Typeable, Data
)
instance (Binary a, Binary (v a)) => Binary (Bootstrap v a) where
get = liftM2 Bootstrap get get
put (Bootstrap fs rs) = put fs >> put rs
instance (FromJSON a, FromJSON (v a)) => FromJSON (Bootstrap v a)
instance (ToJSON a, ToJSON (v a)) => ToJSON (Bootstrap v a)
-- | An estimator of a property of a sample, such as its 'mean'.
--
-- The use of an algebraic data type here allows functions such as
-- 'jackknife' and 'bootstrapBCA' to use more efficient algorithms
-- when possible.
data Estimator = Mean
| Variance
| VarianceUnbiased
| StdDev
| Function (Sample -> Double)
-- | Run an 'Estimator' over a sample.
estimate :: Estimator -> Sample -> Double
estimate Mean = mean
estimate Variance = variance
estimate VarianceUnbiased = varianceUnbiased
estimate StdDev = stdDev
estimate (Function est) = est
----------------------------------------------------------------
-- Resampling
----------------------------------------------------------------
-- | Single threaded and deterministic version of resample.
resampleST :: PrimMonad m
=> Gen (PrimState m)
-> [Estimator] -- ^ Estimation functions.
-> Int -- ^ Number of resamples to compute.
-> U.Vector Double -- ^ Original sample.
-> m [Bootstrap U.Vector Double]
resampleST gen ests numResamples sample = do
-- Generate resamples
res <- forM ests $ \e -> U.replicateM numResamples $ do
v <- resampleVector gen sample
return $! estimate e v
-- Sort resamples
resM <- mapM unsafeThaw res
mapM_ sort resM
resSorted <- mapM unsafeFreeze resM
return $ zipWith Bootstrap [estimate e sample | e <- ests]
resSorted
-- | /O(e*r*s)/ Resample a data set repeatedly, with replacement,
-- computing each estimate over the resampled data.
--
-- This function is expensive; it has to do work proportional to
/e*r*s/ , where /e/ is the number of estimation functions , /r/ is
-- the number of resamples to compute, and /s/ is the number of
-- original samples.
--
-- To improve performance, this function will make use of all
available CPUs . At least with GHC 7.0 , parallel performance seems
-- best if the parallel garbage collector is disabled (RTS option
@-qg@ ) .
resample :: GenIO
-> [Estimator] -- ^ Estimation functions.
-> Int -- ^ Number of resamples to compute.
-> U.Vector Double -- ^ Original sample.
-> IO [(Estimator, Bootstrap U.Vector Double)]
resample gen ests numResamples samples = do
let ixs = scanl (+) 0 $
zipWith (+) (replicate numCapabilities q)
(replicate r 1 ++ repeat 0)
where (q,r) = numResamples `quotRem` numCapabilities
results <- mapM (const (MU.new numResamples)) ests
gens <- splitGen numCapabilities gen
forConcurrently_ (zip3 ixs (tail ixs) gens) $ \ (start,!end,gen') -> do
on GHCJS it does n't make sense to do any forking .
JavaScript runtime has only single capability .
let loop k ers | k >= end = return ()
| otherwise = do
re <- resampleVector gen' samples
forM_ ers $ \(est,arr) ->
MU.write arr k . est $ re
loop (k+1) ers
loop start (zip ests' results)
mapM_ sort results
-- Build resamples
res <- mapM unsafeFreeze results
return $ zip ests
$ zipWith Bootstrap [estimate e samples | e <- ests]
res
where
ests' = map estimate ests
-- | Create vector using resamples
resampleVector :: (PrimMonad m, G.Vector v a)
=> Gen (PrimState m) -> v a -> m (v a)
resampleVector gen v
= G.replicateM n $ do i <- uniformR (0,n-1) gen
return $! G.unsafeIndex v i
where
n = G.length v
----------------------------------------------------------------
Jackknife
----------------------------------------------------------------
| /O(n ) or O(n^2)/ Compute a statistical estimate repeatedly over a
-- sample, each time omitting a successive element.
jackknife :: Estimator -> Sample -> U.Vector Double
jackknife Mean sample = jackknifeMean sample
jackknife Variance sample = jackknifeVariance sample
jackknife VarianceUnbiased sample = jackknifeVarianceUnb sample
jackknife StdDev sample = jackknifeStdDev sample
jackknife (Function est) sample
| G.length sample == 1 = singletonErr "jackknife"
| otherwise = U.map f . indices $ sample
where f i = est (dropAt i sample)
-- | /O(n)/ Compute the jackknife mean of a sample.
jackknifeMean :: Sample -> U.Vector Double
jackknifeMean samp
| len == 1 = singletonErr "jackknifeMean"
| otherwise = G.map (/l) $ G.zipWith (+) (pfxSumL samp) (pfxSumR samp)
where
l = fromIntegral (len - 1)
len = G.length samp
-- | /O(n)/ Compute the jackknife variance of a sample with a
correction factor @c@ , so we can get either the regular or
-- \"unbiased\" variance.
jackknifeVariance_ :: Double -> Sample -> U.Vector Double
jackknifeVariance_ c samp
| len == 1 = singletonErr "jackknifeVariance"
| otherwise = G.zipWith4 go als ars bls brs
where
als = pfxSumL . G.map goa $ samp
ars = pfxSumR . G.map goa $ samp
goa x = v * v where v = x - m
bls = pfxSumL . G.map (subtract m) $ samp
brs = pfxSumR . G.map (subtract m) $ samp
m = mean samp
n = fromIntegral len
go al ar bl br = (al + ar - (b * b) / q) / (q - c)
where b = bl + br
q = n - 1
len = G.length samp
-- | /O(n)/ Compute the unbiased jackknife variance of a sample.
jackknifeVarianceUnb :: Sample -> U.Vector Double
jackknifeVarianceUnb samp
| G.length samp == 2 = singletonErr "jackknifeVariance"
| otherwise = jackknifeVariance_ 1 samp
-- | /O(n)/ Compute the jackknife variance of a sample.
jackknifeVariance :: Sample -> U.Vector Double
jackknifeVariance = jackknifeVariance_ 0
-- | /O(n)/ Compute the jackknife standard deviation of a sample.
jackknifeStdDev :: Sample -> U.Vector Double
jackknifeStdDev = G.map sqrt . jackknifeVarianceUnb
pfxSumL :: U.Vector Double -> U.Vector Double
pfxSumL = G.map kbn . G.scanl add zero
pfxSumR :: U.Vector Double -> U.Vector Double
pfxSumR = G.tail . G.map kbn . G.scanr (flip add) zero
-- | Drop the /k/th element of a vector.
dropAt :: U.Unbox e => Int -> U.Vector e -> U.Vector e
dropAt n v = U.slice 0 n v U.++ U.slice (n+1) (U.length v - n - 1) v
singletonErr :: String -> a
singletonErr func = error $
"Statistics.Resampling." ++ func ++ ": not enough elements in sample"
-- | Split a generator into several that can run independently.
splitGen :: Int -> GenIO -> IO [GenIO]
splitGen n gen
| n <= 0 = return []
| otherwise =
fmap (gen:) . replicateM (n-1) $
initialize =<< (uniformVector gen 256 :: IO (U.Vector Word32))
| null | https://raw.githubusercontent.com/haskell/statistics/d018625f33e8b01911674bffdfcf541415cc3455/Statistics/Resampling.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE DeriveDataTypeable #
# LANGUAGE DeriveFoldable #
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveTraversable #
# LANGUAGE TypeFamilies #
|
Module : Statistics.Resampling
License : BSD3
Maintainer :
Stability : experimental
Portability : portable
Resampling statistics.
* Data types
* Resampling
* Jackknife
* Helper functions
--------------------------------------------------------------
Data types
--------------------------------------------------------------
| A resample drawn randomly, with replacement, from a set of data
points. Distinct from a normal array to make it harder for your
humble author's brain to go wrong.
| An estimator of a property of a sample, such as its 'mean'.
The use of an algebraic data type here allows functions such as
'jackknife' and 'bootstrapBCA' to use more efficient algorithms
when possible.
| Run an 'Estimator' over a sample.
--------------------------------------------------------------
Resampling
--------------------------------------------------------------
| Single threaded and deterministic version of resample.
^ Estimation functions.
^ Number of resamples to compute.
^ Original sample.
Generate resamples
Sort resamples
| /O(e*r*s)/ Resample a data set repeatedly, with replacement,
computing each estimate over the resampled data.
This function is expensive; it has to do work proportional to
the number of resamples to compute, and /s/ is the number of
original samples.
To improve performance, this function will make use of all
best if the parallel garbage collector is disabled (RTS option
^ Estimation functions.
^ Number of resamples to compute.
^ Original sample.
Build resamples
| Create vector using resamples
--------------------------------------------------------------
--------------------------------------------------------------
sample, each time omitting a successive element.
| /O(n)/ Compute the jackknife mean of a sample.
| /O(n)/ Compute the jackknife variance of a sample with a
\"unbiased\" variance.
| /O(n)/ Compute the unbiased jackknife variance of a sample.
| /O(n)/ Compute the jackknife variance of a sample.
| /O(n)/ Compute the jackknife standard deviation of a sample.
| Drop the /k/th element of a vector.
| Split a generator into several that can run independently. | # LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
Copyright : ( c ) 2009 , 2010
module Statistics.Resampling
Resample(..)
, Bootstrap(..)
, Estimator(..)
, estimate
, resampleST
, resample
, resampleVector
, jackknife
, jackknifeMean
, jackknifeVariance
, jackknifeVarianceUnb
, jackknifeStdDev
, splitGen
) where
import Data.Aeson (FromJSON, ToJSON)
import Control.Concurrent.Async (forConcurrently_)
import Control.Monad (forM_, forM, replicateM, liftM2)
import Control.Monad.Primitive (PrimMonad(..))
import Data.Binary (Binary(..))
import Data.Data (Data, Typeable)
import Data.Vector.Algorithms.Intro (sort)
import Data.Vector.Binary ()
import Data.Vector.Generic (unsafeFreeze,unsafeThaw)
import Data.Word (Word32)
import qualified Data.Foldable as T
import qualified Data.Traversable as T
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as MU
import GHC.Conc (numCapabilities)
import GHC.Generics (Generic)
import Numeric.Sum (Summation(..), kbn)
import Statistics.Function (indices)
import Statistics.Sample (mean, stdDev, variance, varianceUnbiased)
import Statistics.Types (Sample)
import System.Random.MWC (Gen, GenIO, initialize, uniformR, uniformVector)
newtype Resample = Resample {
fromResample :: U.Vector Double
} deriving (Eq, Read, Show, Typeable, Data, Generic)
instance FromJSON Resample
instance ToJSON Resample
instance Binary Resample where
put = put . fromResample
get = fmap Resample get
data Bootstrap v a = Bootstrap
{ fullSample :: !a
, resamples :: v a
}
deriving (Eq, Read, Show , Generic, Functor, T.Foldable, T.Traversable
, Typeable, Data
)
instance (Binary a, Binary (v a)) => Binary (Bootstrap v a) where
get = liftM2 Bootstrap get get
put (Bootstrap fs rs) = put fs >> put rs
instance (FromJSON a, FromJSON (v a)) => FromJSON (Bootstrap v a)
instance (ToJSON a, ToJSON (v a)) => ToJSON (Bootstrap v a)
data Estimator = Mean
| Variance
| VarianceUnbiased
| StdDev
| Function (Sample -> Double)
estimate :: Estimator -> Sample -> Double
estimate Mean = mean
estimate Variance = variance
estimate VarianceUnbiased = varianceUnbiased
estimate StdDev = stdDev
estimate (Function est) = est
resampleST :: PrimMonad m
=> Gen (PrimState m)
-> m [Bootstrap U.Vector Double]
resampleST gen ests numResamples sample = do
res <- forM ests $ \e -> U.replicateM numResamples $ do
v <- resampleVector gen sample
return $! estimate e v
resM <- mapM unsafeThaw res
mapM_ sort resM
resSorted <- mapM unsafeFreeze resM
return $ zipWith Bootstrap [estimate e sample | e <- ests]
resSorted
/e*r*s/ , where /e/ is the number of estimation functions , /r/ is
available CPUs . At least with GHC 7.0 , parallel performance seems
@-qg@ ) .
resample :: GenIO
-> IO [(Estimator, Bootstrap U.Vector Double)]
resample gen ests numResamples samples = do
let ixs = scanl (+) 0 $
zipWith (+) (replicate numCapabilities q)
(replicate r 1 ++ repeat 0)
where (q,r) = numResamples `quotRem` numCapabilities
results <- mapM (const (MU.new numResamples)) ests
gens <- splitGen numCapabilities gen
forConcurrently_ (zip3 ixs (tail ixs) gens) $ \ (start,!end,gen') -> do
on GHCJS it does n't make sense to do any forking .
JavaScript runtime has only single capability .
let loop k ers | k >= end = return ()
| otherwise = do
re <- resampleVector gen' samples
forM_ ers $ \(est,arr) ->
MU.write arr k . est $ re
loop (k+1) ers
loop start (zip ests' results)
mapM_ sort results
res <- mapM unsafeFreeze results
return $ zip ests
$ zipWith Bootstrap [estimate e samples | e <- ests]
res
where
ests' = map estimate ests
resampleVector :: (PrimMonad m, G.Vector v a)
=> Gen (PrimState m) -> v a -> m (v a)
resampleVector gen v
= G.replicateM n $ do i <- uniformR (0,n-1) gen
return $! G.unsafeIndex v i
where
n = G.length v
Jackknife
| /O(n ) or O(n^2)/ Compute a statistical estimate repeatedly over a
jackknife :: Estimator -> Sample -> U.Vector Double
jackknife Mean sample = jackknifeMean sample
jackknife Variance sample = jackknifeVariance sample
jackknife VarianceUnbiased sample = jackknifeVarianceUnb sample
jackknife StdDev sample = jackknifeStdDev sample
jackknife (Function est) sample
| G.length sample == 1 = singletonErr "jackknife"
| otherwise = U.map f . indices $ sample
where f i = est (dropAt i sample)
jackknifeMean :: Sample -> U.Vector Double
jackknifeMean samp
| len == 1 = singletonErr "jackknifeMean"
| otherwise = G.map (/l) $ G.zipWith (+) (pfxSumL samp) (pfxSumR samp)
where
l = fromIntegral (len - 1)
len = G.length samp
correction factor @c@ , so we can get either the regular or
jackknifeVariance_ :: Double -> Sample -> U.Vector Double
jackknifeVariance_ c samp
| len == 1 = singletonErr "jackknifeVariance"
| otherwise = G.zipWith4 go als ars bls brs
where
als = pfxSumL . G.map goa $ samp
ars = pfxSumR . G.map goa $ samp
goa x = v * v where v = x - m
bls = pfxSumL . G.map (subtract m) $ samp
brs = pfxSumR . G.map (subtract m) $ samp
m = mean samp
n = fromIntegral len
go al ar bl br = (al + ar - (b * b) / q) / (q - c)
where b = bl + br
q = n - 1
len = G.length samp
jackknifeVarianceUnb :: Sample -> U.Vector Double
jackknifeVarianceUnb samp
| G.length samp == 2 = singletonErr "jackknifeVariance"
| otherwise = jackknifeVariance_ 1 samp
jackknifeVariance :: Sample -> U.Vector Double
jackknifeVariance = jackknifeVariance_ 0
jackknifeStdDev :: Sample -> U.Vector Double
jackknifeStdDev = G.map sqrt . jackknifeVarianceUnb
pfxSumL :: U.Vector Double -> U.Vector Double
pfxSumL = G.map kbn . G.scanl add zero
pfxSumR :: U.Vector Double -> U.Vector Double
pfxSumR = G.tail . G.map kbn . G.scanr (flip add) zero
dropAt :: U.Unbox e => Int -> U.Vector e -> U.Vector e
dropAt n v = U.slice 0 n v U.++ U.slice (n+1) (U.length v - n - 1) v
singletonErr :: String -> a
singletonErr func = error $
"Statistics.Resampling." ++ func ++ ": not enough elements in sample"
splitGen :: Int -> GenIO -> IO [GenIO]
splitGen n gen
| n <= 0 = return []
| otherwise =
fmap (gen:) . replicateM (n-1) $
initialize =<< (uniformVector gen 256 :: IO (U.Vector Word32))
|
4b52aa67cf62a9365bd0ab02e05e5e44612f182ee9fea6109e2ad24370d4658d | rtoy/cmucl | nlx.lisp | ;;; -*- Package: PPC -*-
;;;
;;; **********************************************************************
This code was written as part of the Spice Lisp project at
Carnegie - Mellon University , and has been placed in the public domain .
If you want to use this code or any part of Spice Lisp , please contact
( FAHLMAN@CMUC ) .
;;; **********************************************************************
;;;
$ Header : src / compiler / ppc / nlx.lisp $
;;;
;;; This file contains the definitions of VOPs used for non-local exit
;;; (throw, lexical exit, etc.)
;;;
Written by
;;;
(in-package "PPC")
MAKE - NLX - SP - TN -- Interface
;;;
Make an environment - live stack TN for saving the SP for NLX entry .
;;;
(def-vm-support-routine make-nlx-sp-tn (env)
(environment-live-tn
(make-representation-tn *fixnum-primitive-type* immediate-arg-scn)
env))
Make - NLX - Entry - Argument - Start - Location -- Interface
;;;
Make a TN for the argument count passing location for a
;;; non-local entry.
;;;
(def-vm-support-routine make-nlx-entry-argument-start-location ()
(make-wired-tn *fixnum-primitive-type* immediate-arg-scn ocfp-offset))
;;; Save and restore dynamic environment.
;;;
;;; These VOPs are used in the reentered function to restore the appropriate
;;; dynamic environment. Currently we only save the Current-Catch and binding
;;; stack pointer. We don't need to save/restore the current unwind-protect,
;;; since unwind-protects are implicitly processed during unwinding. If there
;;; were any additional stacks, then this would be the place to restore the top
;;; pointers.
Make - Dynamic - State - TNs -- Interface
;;;
Return a list of TNs that can be used to snapshot the dynamic state for
use with the Save / Restore - Dynamic - Environment VOPs .
;;;
(def-vm-support-routine make-dynamic-state-tns ()
(make-n-tns 4 *any-primitive-type*))
(define-vop (save-dynamic-state)
(:results (catch :scs (descriptor-reg))
(nfp :scs (descriptor-reg))
(nsp :scs (descriptor-reg))
(eval :scs (descriptor-reg)))
(:vop-var vop)
(:generator 13
(load-symbol-value catch lisp::*current-catch-block*)
(let ((cur-nfp (current-nfp-tn vop)))
(when cur-nfp
(move nfp cur-nfp)))
(move nsp nsp-tn)
(load-symbol-value eval lisp::*eval-stack-top*)))
(define-vop (restore-dynamic-state)
(:args (catch :scs (descriptor-reg))
(nfp :scs (descriptor-reg))
(nsp :scs (descriptor-reg))
(eval :scs (descriptor-reg)))
(:vop-var vop)
(:generator 10
(store-symbol-value catch lisp::*current-catch-block*)
(store-symbol-value eval lisp::*eval-stack-top*)
(let ((cur-nfp (current-nfp-tn vop)))
(when cur-nfp
(move cur-nfp nfp)))
(move nsp-tn nsp)))
(define-vop (current-stack-pointer)
(:results (res :scs (any-reg descriptor-reg)))
(:generator 1
(move res csp-tn)))
(define-vop (current-binding-pointer)
(:results (res :scs (any-reg descriptor-reg)))
(:generator 1
(move res bsp-tn)))
;;;; Unwind block hackery:
Compute the address of the catch block from its TN , then store into the
block the current Fp , Env , Unwind - Protect , and the entry PC .
;;;
(define-vop (make-unwind-block)
(:args (tn))
(:info entry-label)
(:results (block :scs (any-reg)))
(:temporary (:scs (descriptor-reg)) temp)
(:temporary (:scs (non-descriptor-reg)) ndescr)
(:generator 22
(inst addi block cfp-tn (* (tn-offset tn) vm:word-bytes))
(load-symbol-value temp lisp::*current-unwind-protect-block*)
(storew temp block vm:unwind-block-current-uwp-slot)
(storew cfp-tn block vm:unwind-block-current-cont-slot)
(storew code-tn block vm:unwind-block-current-code-slot)
(inst compute-lra-from-code temp code-tn entry-label ndescr)
(storew temp block vm:catch-block-entry-pc-slot)))
;;; Like Make-Unwind-Block, except that we also store in the specified tag, and
;;; link the block into the Current-Catch list.
;;;
(define-vop (make-catch-block)
(:args (tn)
(tag :scs (descriptor-reg)))
(:info entry-label)
(:results (block :scs (any-reg)))
(:temporary (:scs (descriptor-reg)) temp)
(:temporary (:scs (descriptor-reg) :target block :to (:result 0)) result)
(:temporary (:scs (non-descriptor-reg)) ndescr)
(:generator 44
(inst addi result cfp-tn (* (tn-offset tn) vm:word-bytes))
(load-symbol-value temp lisp::*current-unwind-protect-block*)
(storew temp result vm:catch-block-current-uwp-slot)
(storew cfp-tn result vm:catch-block-current-cont-slot)
(storew code-tn result vm:catch-block-current-code-slot)
(inst compute-lra-from-code temp code-tn entry-label ndescr)
(storew temp result vm:catch-block-entry-pc-slot)
(storew tag result vm:catch-block-tag-slot)
(load-symbol-value temp lisp::*current-catch-block*)
(storew temp result vm:catch-block-previous-catch-slot)
(store-symbol-value result lisp::*current-catch-block*)
(move block result)))
Just set the current unwind - protect to TN 's address . This instantiates an
;;; unwind block as an unwind-protect.
;;;
(define-vop (set-unwind-protect)
(:args (tn))
(:temporary (:scs (descriptor-reg)) new-uwp)
(:generator 7
(inst addi new-uwp cfp-tn (* (tn-offset tn) vm:word-bytes))
(store-symbol-value new-uwp lisp::*current-unwind-protect-block*)))
(define-vop (unlink-catch-block)
(:temporary (:scs (any-reg)) block)
(:policy :fast-safe)
(:translate %catch-breakup)
(:generator 17
(load-symbol-value block lisp::*current-catch-block*)
(loadw block block vm:catch-block-previous-catch-slot)
(store-symbol-value block lisp::*current-catch-block*)))
(define-vop (unlink-unwind-protect)
(:temporary (:scs (any-reg)) block)
(:policy :fast-safe)
(:translate %unwind-protect-breakup)
(:generator 17
(load-symbol-value block lisp::*current-unwind-protect-block*)
(loadw block block vm:unwind-block-current-uwp-slot)
(store-symbol-value block lisp::*current-unwind-protect-block*)))
NLX entry VOPs :
(define-vop (nlx-entry)
(:args (sp) ; Note: we can't list an sc-restriction, 'cause any load vops
would be inserted before the LRA .
(start)
(count))
(:results (values :more t))
(:temporary (:scs (descriptor-reg)) move-temp)
(:info label nvals)
(:save-p :force-to-stack)
(:vop-var vop)
(:generator 30
(emit-return-pc label)
(note-this-location vop :non-local-entry)
(cond ((zerop nvals))
((= nvals 1)
(let ((no-values (gen-label)))
(inst cmpwi count 0)
(move (tn-ref-tn values) null-tn)
(inst beq no-values)
(loadw (tn-ref-tn values) start)
(emit-label no-values)))
(t
(collect ((defaults))
(inst addic. count count (- (fixnumize 1)))
(do ((i 0 (1+ i))
(tn-ref values (tn-ref-across tn-ref)))
((null tn-ref))
(let ((default-lab (gen-label))
(tn (tn-ref-tn tn-ref)))
(defaults (cons default-lab tn))
(inst subi count count (fixnumize 1))
(inst blt default-lab)
(sc-case tn
((descriptor-reg any-reg)
(loadw tn start i))
(control-stack
(loadw move-temp start i)
(store-stack-tn tn move-temp)))
(inst cmpwi count 0)))
(let ((defaulting-done (gen-label)))
(emit-label defaulting-done)
(assemble (*elsewhere*)
(dolist (def (defaults))
(emit-label (car def))
(let ((tn (cdr def)))
(sc-case tn
((descriptor-reg any-reg)
(move tn null-tn))
(control-stack
(store-stack-tn tn null-tn)))))
(inst b defaulting-done))))))
(load-stack-tn csp-tn sp)))
(define-vop (nlx-entry-multiple)
(:args (top :target result) (src) (count))
Again , no SC restrictions for the args , 'cause the loading would
;; happen before the entry label.
(:info label)
(:temporary (:scs (any-reg)) dst)
(:temporary (:scs (descriptor-reg)) temp)
(:results (result :scs (any-reg) :from (:argument 0))
(num :scs (any-reg) :from (:argument 0)))
(:save-p :force-to-stack)
(:vop-var vop)
(:generator 30
(emit-return-pc label)
(note-this-location vop :non-local-entry)
(let ((loop (gen-label))
(done (gen-label)))
Setup results , and test for the zero value case .
(load-stack-tn result top)
(inst cmpwi count 0)
(inst li num 0)
(inst beq done)
Compute dst as one slot down from result , because we inc the index
;; before we use it.
(inst subi dst result 4)
;; Copy stuff down the stack.
(emit-label loop)
(inst lwzx temp src num)
(inst addi num num (fixnumize 1))
(inst cmpw num count)
(inst stwx temp dst num)
(inst bne loop)
Reset the CSP .
(emit-label done)
(inst add csp-tn result num))))
This VOP is just to force the TNs used in the cleanup onto the stack .
;;;
(define-vop (uwp-entry)
(:info label)
(:save-p :force-to-stack)
(:results (block) (start) (count))
(:ignore block start count)
(:vop-var vop)
(:generator 0
(emit-return-pc label)
(note-this-location vop :non-local-entry)))
| null | https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/compiler/ppc/nlx.lisp | lisp | -*- Package: PPC -*-
**********************************************************************
**********************************************************************
This file contains the definitions of VOPs used for non-local exit
(throw, lexical exit, etc.)
non-local entry.
Save and restore dynamic environment.
These VOPs are used in the reentered function to restore the appropriate
dynamic environment. Currently we only save the Current-Catch and binding
stack pointer. We don't need to save/restore the current unwind-protect,
since unwind-protects are implicitly processed during unwinding. If there
were any additional stacks, then this would be the place to restore the top
pointers.
Unwind block hackery:
Like Make-Unwind-Block, except that we also store in the specified tag, and
link the block into the Current-Catch list.
unwind block as an unwind-protect.
Note: we can't list an sc-restriction, 'cause any load vops
happen before the entry label.
before we use it.
Copy stuff down the stack.
| This code was written as part of the Spice Lisp project at
Carnegie - Mellon University , and has been placed in the public domain .
If you want to use this code or any part of Spice Lisp , please contact
( FAHLMAN@CMUC ) .
$ Header : src / compiler / ppc / nlx.lisp $
Written by
(in-package "PPC")
MAKE - NLX - SP - TN -- Interface
Make an environment - live stack TN for saving the SP for NLX entry .
(def-vm-support-routine make-nlx-sp-tn (env)
(environment-live-tn
(make-representation-tn *fixnum-primitive-type* immediate-arg-scn)
env))
Make - NLX - Entry - Argument - Start - Location -- Interface
Make a TN for the argument count passing location for a
(def-vm-support-routine make-nlx-entry-argument-start-location ()
(make-wired-tn *fixnum-primitive-type* immediate-arg-scn ocfp-offset))
Make - Dynamic - State - TNs -- Interface
Return a list of TNs that can be used to snapshot the dynamic state for
use with the Save / Restore - Dynamic - Environment VOPs .
(def-vm-support-routine make-dynamic-state-tns ()
(make-n-tns 4 *any-primitive-type*))
(define-vop (save-dynamic-state)
(:results (catch :scs (descriptor-reg))
(nfp :scs (descriptor-reg))
(nsp :scs (descriptor-reg))
(eval :scs (descriptor-reg)))
(:vop-var vop)
(:generator 13
(load-symbol-value catch lisp::*current-catch-block*)
(let ((cur-nfp (current-nfp-tn vop)))
(when cur-nfp
(move nfp cur-nfp)))
(move nsp nsp-tn)
(load-symbol-value eval lisp::*eval-stack-top*)))
(define-vop (restore-dynamic-state)
(:args (catch :scs (descriptor-reg))
(nfp :scs (descriptor-reg))
(nsp :scs (descriptor-reg))
(eval :scs (descriptor-reg)))
(:vop-var vop)
(:generator 10
(store-symbol-value catch lisp::*current-catch-block*)
(store-symbol-value eval lisp::*eval-stack-top*)
(let ((cur-nfp (current-nfp-tn vop)))
(when cur-nfp
(move cur-nfp nfp)))
(move nsp-tn nsp)))
(define-vop (current-stack-pointer)
(:results (res :scs (any-reg descriptor-reg)))
(:generator 1
(move res csp-tn)))
(define-vop (current-binding-pointer)
(:results (res :scs (any-reg descriptor-reg)))
(:generator 1
(move res bsp-tn)))
Compute the address of the catch block from its TN , then store into the
block the current Fp , Env , Unwind - Protect , and the entry PC .
(define-vop (make-unwind-block)
(:args (tn))
(:info entry-label)
(:results (block :scs (any-reg)))
(:temporary (:scs (descriptor-reg)) temp)
(:temporary (:scs (non-descriptor-reg)) ndescr)
(:generator 22
(inst addi block cfp-tn (* (tn-offset tn) vm:word-bytes))
(load-symbol-value temp lisp::*current-unwind-protect-block*)
(storew temp block vm:unwind-block-current-uwp-slot)
(storew cfp-tn block vm:unwind-block-current-cont-slot)
(storew code-tn block vm:unwind-block-current-code-slot)
(inst compute-lra-from-code temp code-tn entry-label ndescr)
(storew temp block vm:catch-block-entry-pc-slot)))
(define-vop (make-catch-block)
(:args (tn)
(tag :scs (descriptor-reg)))
(:info entry-label)
(:results (block :scs (any-reg)))
(:temporary (:scs (descriptor-reg)) temp)
(:temporary (:scs (descriptor-reg) :target block :to (:result 0)) result)
(:temporary (:scs (non-descriptor-reg)) ndescr)
(:generator 44
(inst addi result cfp-tn (* (tn-offset tn) vm:word-bytes))
(load-symbol-value temp lisp::*current-unwind-protect-block*)
(storew temp result vm:catch-block-current-uwp-slot)
(storew cfp-tn result vm:catch-block-current-cont-slot)
(storew code-tn result vm:catch-block-current-code-slot)
(inst compute-lra-from-code temp code-tn entry-label ndescr)
(storew temp result vm:catch-block-entry-pc-slot)
(storew tag result vm:catch-block-tag-slot)
(load-symbol-value temp lisp::*current-catch-block*)
(storew temp result vm:catch-block-previous-catch-slot)
(store-symbol-value result lisp::*current-catch-block*)
(move block result)))
Just set the current unwind - protect to TN 's address . This instantiates an
(define-vop (set-unwind-protect)
(:args (tn))
(:temporary (:scs (descriptor-reg)) new-uwp)
(:generator 7
(inst addi new-uwp cfp-tn (* (tn-offset tn) vm:word-bytes))
(store-symbol-value new-uwp lisp::*current-unwind-protect-block*)))
(define-vop (unlink-catch-block)
(:temporary (:scs (any-reg)) block)
(:policy :fast-safe)
(:translate %catch-breakup)
(:generator 17
(load-symbol-value block lisp::*current-catch-block*)
(loadw block block vm:catch-block-previous-catch-slot)
(store-symbol-value block lisp::*current-catch-block*)))
(define-vop (unlink-unwind-protect)
(:temporary (:scs (any-reg)) block)
(:policy :fast-safe)
(:translate %unwind-protect-breakup)
(:generator 17
(load-symbol-value block lisp::*current-unwind-protect-block*)
(loadw block block vm:unwind-block-current-uwp-slot)
(store-symbol-value block lisp::*current-unwind-protect-block*)))
NLX entry VOPs :
(define-vop (nlx-entry)
would be inserted before the LRA .
(start)
(count))
(:results (values :more t))
(:temporary (:scs (descriptor-reg)) move-temp)
(:info label nvals)
(:save-p :force-to-stack)
(:vop-var vop)
(:generator 30
(emit-return-pc label)
(note-this-location vop :non-local-entry)
(cond ((zerop nvals))
((= nvals 1)
(let ((no-values (gen-label)))
(inst cmpwi count 0)
(move (tn-ref-tn values) null-tn)
(inst beq no-values)
(loadw (tn-ref-tn values) start)
(emit-label no-values)))
(t
(collect ((defaults))
(inst addic. count count (- (fixnumize 1)))
(do ((i 0 (1+ i))
(tn-ref values (tn-ref-across tn-ref)))
((null tn-ref))
(let ((default-lab (gen-label))
(tn (tn-ref-tn tn-ref)))
(defaults (cons default-lab tn))
(inst subi count count (fixnumize 1))
(inst blt default-lab)
(sc-case tn
((descriptor-reg any-reg)
(loadw tn start i))
(control-stack
(loadw move-temp start i)
(store-stack-tn tn move-temp)))
(inst cmpwi count 0)))
(let ((defaulting-done (gen-label)))
(emit-label defaulting-done)
(assemble (*elsewhere*)
(dolist (def (defaults))
(emit-label (car def))
(let ((tn (cdr def)))
(sc-case tn
((descriptor-reg any-reg)
(move tn null-tn))
(control-stack
(store-stack-tn tn null-tn)))))
(inst b defaulting-done))))))
(load-stack-tn csp-tn sp)))
(define-vop (nlx-entry-multiple)
(:args (top :target result) (src) (count))
Again , no SC restrictions for the args , 'cause the loading would
(:info label)
(:temporary (:scs (any-reg)) dst)
(:temporary (:scs (descriptor-reg)) temp)
(:results (result :scs (any-reg) :from (:argument 0))
(num :scs (any-reg) :from (:argument 0)))
(:save-p :force-to-stack)
(:vop-var vop)
(:generator 30
(emit-return-pc label)
(note-this-location vop :non-local-entry)
(let ((loop (gen-label))
(done (gen-label)))
Setup results , and test for the zero value case .
(load-stack-tn result top)
(inst cmpwi count 0)
(inst li num 0)
(inst beq done)
Compute dst as one slot down from result , because we inc the index
(inst subi dst result 4)
(emit-label loop)
(inst lwzx temp src num)
(inst addi num num (fixnumize 1))
(inst cmpw num count)
(inst stwx temp dst num)
(inst bne loop)
Reset the CSP .
(emit-label done)
(inst add csp-tn result num))))
This VOP is just to force the TNs used in the cleanup onto the stack .
(define-vop (uwp-entry)
(:info label)
(:save-p :force-to-stack)
(:results (block) (start) (count))
(:ignore block start count)
(:vop-var vop)
(:generator 0
(emit-return-pc label)
(note-this-location vop :non-local-entry)))
|
098bb5638a311cf332ad38143bfdfcd1070f8301dc2504d845a07166cf6aade5 | ryanpbrewster/haskell | valid_parentheses.hs | -- valid_parentheses.hs
- Given a string comprising just of the characters ( , ) , { , } , [ , ] determine if it
- is well - formed or not .
- Input sample :
-
- Your program should accept as its first argument a path to a filename . Each
- line in this file contains a string comprising of the characters mentioned
- above . e.g.
-
- ( )
- ( [ ) ]
-
- Output sample :
-
- Print out True or False if the string is well - formed e.g.
-
- True
- False
- Given a string comprising just of the characters (,),{,},[,] determine if it
- is well-formed or not.
- Input sample:
-
- Your program should accept as its first argument a path to a filename. Each
- line in this file contains a string comprising of the characters mentioned
- above. e.g.
-
- ()
- ([)]
-
- Output sample:
-
- Print out True or False if the string is well-formed e.g.
-
- True
- False
-}
{-
- I use a simple recursive descent parser for the language
- S -> VS | ""
- V -> (S) | [S] | {S}
-
- That is, the language of all properly formed parenthesis-like strings
-}
import System.Environment (getArgs)
main = do
args <- getArgs
txt <- readFile (head args)
putStr $ solveProblem txt
solveProblem txt = let inputs = lines txt
anss = map valid inputs
in unlines $ map show anss
lefts = "({["
right '(' = ')'
right '{' = '}'
right '[' = ']'
valid inp = valid' inp ""
where valid' "" stk = null stk
valid' (ch:inp) stk
| ch `elem` lefts = valid' inp (ch:stk)
| null stk = False
| ch == right (head stk) = valid' inp (tail stk)
| otherwise = False
| null | https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/CodeEval/valid_parentheses.hs | haskell | valid_parentheses.hs
- I use a simple recursive descent parser for the language
- S -> VS | ""
- V -> (S) | [S] | {S}
-
- That is, the language of all properly formed parenthesis-like strings
|
- Given a string comprising just of the characters ( , ) , { , } , [ , ] determine if it
- is well - formed or not .
- Input sample :
-
- Your program should accept as its first argument a path to a filename . Each
- line in this file contains a string comprising of the characters mentioned
- above . e.g.
-
- ( )
- ( [ ) ]
-
- Output sample :
-
- Print out True or False if the string is well - formed e.g.
-
- True
- False
- Given a string comprising just of the characters (,),{,},[,] determine if it
- is well-formed or not.
- Input sample:
-
- Your program should accept as its first argument a path to a filename. Each
- line in this file contains a string comprising of the characters mentioned
- above. e.g.
-
- ()
- ([)]
-
- Output sample:
-
- Print out True or False if the string is well-formed e.g.
-
- True
- False
-}
import System.Environment (getArgs)
main = do
args <- getArgs
txt <- readFile (head args)
putStr $ solveProblem txt
solveProblem txt = let inputs = lines txt
anss = map valid inputs
in unlines $ map show anss
lefts = "({["
right '(' = ')'
right '{' = '}'
right '[' = ']'
valid inp = valid' inp ""
where valid' "" stk = null stk
valid' (ch:inp) stk
| ch `elem` lefts = valid' inp (ch:stk)
| null stk = False
| ch == right (head stk) = valid' inp (tail stk)
| otherwise = False
|
f830afaa2bb4c7c1684a2439299efe80366816d91092734695ba603d9676cab4 | mfoemmel/erlang-otp | gs1.1.erl | -module(gs1).
-vsn(1).
-behaviour(gen_server).
-export([get_data/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state, {data}).
get_data() ->
gen_server:call(gs1, get_data).
init([Data]) ->
{ok, #state{data = Data}}.
handle_call(get_data, _From, State) ->
{reply, {ok, State#state.data}, State}.
handle_cast(_Request, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
| null | https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/sasl/doc/src/rel/gs1.1.erl | erlang | -module(gs1).
-vsn(1).
-behaviour(gen_server).
-export([get_data/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state, {data}).
get_data() ->
gen_server:call(gs1, get_data).
init([Data]) ->
{ok, #state{data = Data}}.
handle_call(get_data, _From, State) ->
{reply, {ok, State#state.data}, State}.
handle_cast(_Request, State) ->
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
|
|
f3720154dac62278ebbd1c7a8d4bf728fd8edda53c4e475e0193b3b84aeb731e | repl-electric/cassiopeia | alpha.clj | (ns cassiopeia.alpha
"
.'. | |`````````, | | .'.
.''```. | |''''''''' |_________| .''```.
.' `. | | | | .' `.
.' `. |_______ | | | .' `.
* Surface temperature: 4530 K
* Mass: 8.95E30 kg
* Radius: 29,280,000 km
* Magnitude: 2.24
"
(:use [overtone.live]
;;[cassiopeia.warm-up]
[cassiopeia.samples]
[overtone.synth.sampled-piano]
[mud.core])
(:require [mud.timing :as time]
;;[launchpad.sequencer :as lp-sequencer]
;;[launchpad.plugin.beat :as lp-beat]
[cassiopeia.engine.expediency :refer :all]
[cassiopeia.engine.mixers :as m]
[overtone.inst.synth :as s]
[overtone.synths :as syn]
[cassiopeia.waves.synths :as cs]))
(do
(def star-into-the-sun (load-sample "~/Workspace/music/samples/star-into-the-sun.wav"))
(def space-and-time-sun (load-sample "~/Workspace/music/samples/space_and_time.wav"))
(def windy (sample (freesound-path 17553)))
(defonce rhythm-g (group "Rhythm" :after time/timing-g))
(defonce saw-bf1 (buffer 256))
(defonce saw-bf2 (buffer 256))
(defonce saw-x-b1 (control-bus 1 "Timing Saw 1"))
(defonce saw-x-b2 (control-bus 1 "Timing Saw 2"))
(defonce saw-x-b3 (control-bus 1 "Timing Saw 3"))
(defonce phasor-b1 (control-bus 1 "Timing Saw Phasor 1"))
(defonce phasor-b2 (control-bus 1 "Timing Saw Phasor 2"))
(defonce phasor-b3 (control-bus 1 "Timing Saw Phasor 3"))
(defonce phasor-b4 (control-bus 1 "Timing Saw Phasor 4"))
(defonce phasor-b5 (control-bus 1 "Timing Saw Phasor 5"))
(defonce saw-s1 (time/saw-x [:head rhythm-g] :out-bus saw-x-b1))
(defonce saw-s2 (time/saw-x [:head rhythm-g] :out-bus saw-x-b2))
(defonce saw-s3 (time/saw-x [:head rhythm-g] :out-bus saw-x-b3))
(defonce phasor-s1 (time/buf-phasor [:after saw-s1] saw-x-b1 :out-bus phasor-b1 :buf saw-bf1))
(defonce phasor-s2 (time/buf-phasor [:after saw-s2] saw-x-b2 :out-bus phasor-b2 :buf saw-bf2))
(def space-notes-buf (buffer 5))
(def space-tones-buf (buffer 3))
(defonce phasor-s3 (time/buf-phasor [:after saw-s3] saw-x-b3 :out-bus phasor-b3 :buf space-notes-buf))
(defsynth buffered-plain-space-organ [out-bus 0 duration 4 amp 1]
(let [tone (/ (in:kr phasor-b2) 2)
tones (map #(blip (* % 2) (mul-add:kr (lf-noise1:kr 1/8) 1 4)) [tone])]
(out out-bus (pan2 (* amp (g-verb (sum tones) 200 8))))))
(defsynth ratatat [out-bus 0 amp 1]
(let [freq (in:kr phasor-b2)
sin1 (sin-osc (* 1.01 freq))
sin2 (sin-osc (* 1 freq))
sin3 (sin-osc (* 0.99 freq))
src (mix [sin1 sin2 sin3])
src (g-verb src :spread 10)]
(out out-bus (* amp (pan2 src)))))
(defn transpose [updown notes]
(map #(+ updown %1) notes))
(def space-notes [8 16 32 16 8])
(def space-tones [8 16 24])
(defsynth crystal-space-organ [out-bus 0 amp 1 size 200 r 8 numharm 0 trig 0 t0 8 t1 16 t2 24 d0 1 d1 1/2 d2 1/4 d3 1/8]
(let [notes (map #(midicps (duty:kr % (mod trig 16) (dseq space-notes INF))) [d0 d1 d2 d3])
tones (map (fn [note tone] (blip (* note tone) numharm)) notes [t0 t1 t2])]
(out out-bus (* amp (g-verb (sum tones) size r)))))
(comment (def csp (crystal-space-organ :numharm 0 :amp 0.5)))
(def space-notes [8 16 32 16 8])
(defsynth high-space-organ [cutoff 90 out-bus 0 amp 1 size 200 r 8 noise 10 trig 0 t0 8 t1 16 t2 24 d0 1 d1 1/2 d2 1/4]
(let [space-notes1-buf (buf-rd:kr 1 space-notes-buf 0)
space-notes2-buf (buf-rd:kr 1 space-notes-buf 1)
space-notes3-buf (buf-rd:kr 1 space-notes-buf 2)
space-notes4-buf (buf-rd:kr 1 space-notes-buf 3)
space-notes5-buf (buf-rd:kr 1 space-notes-buf 4)
space-notes-in [space-notes1-buf space-notes2-buf space-notes3-buf space-notes4-buf space-notes5-buf]
notes (map #(duty:kr % (mod trig 16) (dseq space-notes-in INF)) [d0 d1 d2])
tones (map (fn [note tone]
(println :none note :tone tone)
(blip (* note tone) (mul-add:kr (lf-noise1:kr noise) 3 4))) notes [t0 t1 t2])
_ (println tones)
src (* amp (g-verb (sum tones) size r))
src (lpf src cutoff)]
(out out-bus src)))
(println (map midi->hz [8 16 32 16 8]))
(ctl so :t0 1 :t1 1 :t2 1)
(pattern! space-notes-buf (map midi->hz (degrees-seq [:C#0 1 :C#0 3 :C#1 5])))
: t0 2 : t1 4 : t2 8 : out - bus 0
(pattern! space-notes-buf (map midi->hz [8 16 32 16 8]))
(def so (high-space-organ :amp 0.4
:trig time/beat-count-b
:noise 220 :t0 1 :t1 1 :t2 2 :out-bus 0))
(ctl so :cutoff 2000a)
(ctl so :amp 0.5)
(ctl so :t0 2)
(ctl so :t1 4)
(ctl so :t2 8)
(kill high-space-organ)
(comment (high-space-organ))
(defsynth timed-high-space-organ [out-bus 0 amp 1 size 200 r 8 noise 10 ]
(let [note (in:kr phasor-b3)
tone1 (buf-rd:kr 1 space-tones-buf 0)
tone2 (buf-rd:kr 1 space-tones-buf 1)
tone3 (buf-rd:kr 1 space-tones-buf 2)
trig1 (t-duty:kr (dseq [1] INFINITE))
trig2 (t-duty:kr (dseq [1/2] INFINITE))
trig3 (t-duty:kr (dseq [1/4] INFINITE))
note1 (midicps (demand:kr trig1 0 (drand note INFINITE)))
note2 (midicps (demand:kr trig2 0 (drand note INFINITE)))
note3 (midicps (demand:kr trig3 0 (drand note INFINITE)))
all-tones [tone1 tone2 tone3]
all-notes [note1 note2 note3]
tones (map (fn [note tone] (blip (* note tone)
(mul-add:kr (lf-noise1:kr noise) 3 4))) all-notes all-tones)]
(out out-bus (* amp (g-verb (sum tones) size r)))))
(comment
(show-graphviz-synth timed-high-space-organ)
(ctl saw-s3 :freq-mul 1/32)
(buffer-write! space-notes-buf [8 16 32 16 8])
(buffer-write! space-tones-buf [2 4 8])
(buffer-write! space-tones-buf [8 12 16])
(buffer-write! space-tones-buf [8 16 24])
(def thso (timed-high-space-organ :noise 220 :amp 0.4))
(ctl thso :noise 10)
(ctl thso :size 0)
(ctl thso :size 200)
(def so (high-space-organ :amp 0.4 :trig time/beat-count-b :noise 220 :t0 2 :t1 4 :t2 8 :out-bus 0))
(show-graphviz-synth high-space-organ)
(stop))
(defsynth plain-space-organ [out-bus 0 tone 1 duration 3 amp 1]
(let [tones (map #(blip (* % 2) (mul-add:kr 1/8 1 4)) [tone])]
(out out-bus (* amp (g-verb (sum tones) 200 8) (line 1 0 duration FREE)))))
(defsynth space-organ [out-bus 0 tone 1 duration 3 amp 1]
(let [f (map #(midicps (duty:kr % 0 (dseq 2 4)))
[1])
tones (map #(blip (* % %2) (mul-add:kr (lf-noise1:kr 1/8) 2 4))
f
[tone])]
(out out-bus (* amp (g-verb (sum tones) 200 8) (line 1 0 duration FREE))))))
SCORE
(def sun (sample-player star-into-the-sun :rate 0.99 :amp 8 :out-bus 0))
(def space-and-time (sample-player space-and-time-sun :rate 0.8))
(ctl space-and-time :rate 0.7)
(ctl space-and-time :rate 0.8)
(syn/fallout-wind)
(syn/soft-phasing :amp 0.0)
(def dark (syn/dark-sea-horns :amp 0.3))
(ctl dark :amp 1)
(kill dark)
(kill syn/soft-phasing)
(kill syn/fallout-wind)
;;Rythm
(def score (map note [:F5 :G5 :G5 :G5 :G5 :BB5 :BB5 :D#5]))
(buffer-write! saw-bf2 (repeat 256 (midi->hz (note :A3))))
(buffer-write! saw-bf2 (map midi->hz
(map (fn [midi-note] (+ -12 midi-note))
(map note (take 256 (cycle score))))))
(buffer-write! saw-bf2 (map midi->hz
(map (fn [midi-note] (+ -5 midi-note))
(map note (take 256 (cycle score))))))
(buffer-write! saw-bf2 (map midi->hz
(map (fn [midi-note] (+ 0 midi-note))
(map note (take 256 (cycle score))))))
(ratatat :amp 0.9)
(ctl saw-s2 :freq-mul 1/40)
(kill ratatat)
(buffered-plain-space-organ :amp 0.8)
(kill buffered-plain-space-organ)
(stop)
;;Jaming
(plain-space-organ :tone (/ 24 2) :duration 16)
(def note-cycle (degrees [1 2 3] :major :C#2))
(def note-inc (atom 0))
(def trigger-g99018
(on-beat-trigger 8 (fn []
(swap! note-inc inc)
(plain-space-organ :tone (/ (midi->hz (nth (degrees [1 2 3] :major :C#1) (mod @note-inc 3) ) ) 1) :duration 16.0 :amp 0.2)
)))
(remove-beat-trigger trigger-g99018)
(remove-all-beat-triggers)
(def so (high-space-organ :amp 0.4 :trig time/beat-count-b :noise 220 :t0 2 :t1 4 :t2 8 :out-bus 0))
(def so (high-space-organ :amp 0.4 :trig time/beat-count-b :noise 220 :t0 1 :t1 1 :t2 1 :out-bus 0))
(ctl so :cutoff 250)
(kill so)
(ctl so :noise 50)
(ctl so :vol 1)
(ctl so :t0 1 :t1 1 :t2 1)
(ctl so :t0 8 :t1 12 :t2 16)
(ctl so :t0 8 :t1 16 :t2 24)
(ctl so :r 10)
(ctl so :size 0)
(ctl so :size 200)
(ctl so :amp 0.1)
(volume 1.0)
(comment (stop))
(comment
(defonce kick-seq-buf (buffer 256))
(def beats (cs/buffer->tap-lite kick-seq-buf (:count time/beat-1th) :measure 8))
(start-graphics "resources/shaders/space_and_time.glsl"
:textures [:overtone-audio
:previous-frame
"resources/textures/tex16.png"
"resources/textures/time.png"
;;"resources/textures/space.png"
]
:user-data {"iGlobalBeatCount" (atom {:synth beats :tap "global-beat-count"})})
(stop-graphics "resources/shaders/space_and_time.glsl")
)
| null | https://raw.githubusercontent.com/repl-electric/cassiopeia/a42c01752fc8dd04ea5db95c8037f393c29cdb75/src/cassiopeia/destination/alpha.clj | clojure | [cassiopeia.warm-up]
[launchpad.sequencer :as lp-sequencer]
[launchpad.plugin.beat :as lp-beat]
Rythm
Jaming
"resources/textures/space.png" | (ns cassiopeia.alpha
"
.'. | |`````````, | | .'.
.''```. | |''''''''' |_________| .''```.
.' `. | | | | .' `.
.' `. |_______ | | | .' `.
* Surface temperature: 4530 K
* Mass: 8.95E30 kg
* Radius: 29,280,000 km
* Magnitude: 2.24
"
(:use [overtone.live]
[cassiopeia.samples]
[overtone.synth.sampled-piano]
[mud.core])
(:require [mud.timing :as time]
[cassiopeia.engine.expediency :refer :all]
[cassiopeia.engine.mixers :as m]
[overtone.inst.synth :as s]
[overtone.synths :as syn]
[cassiopeia.waves.synths :as cs]))
(do
(def star-into-the-sun (load-sample "~/Workspace/music/samples/star-into-the-sun.wav"))
(def space-and-time-sun (load-sample "~/Workspace/music/samples/space_and_time.wav"))
(def windy (sample (freesound-path 17553)))
(defonce rhythm-g (group "Rhythm" :after time/timing-g))
(defonce saw-bf1 (buffer 256))
(defonce saw-bf2 (buffer 256))
(defonce saw-x-b1 (control-bus 1 "Timing Saw 1"))
(defonce saw-x-b2 (control-bus 1 "Timing Saw 2"))
(defonce saw-x-b3 (control-bus 1 "Timing Saw 3"))
(defonce phasor-b1 (control-bus 1 "Timing Saw Phasor 1"))
(defonce phasor-b2 (control-bus 1 "Timing Saw Phasor 2"))
(defonce phasor-b3 (control-bus 1 "Timing Saw Phasor 3"))
(defonce phasor-b4 (control-bus 1 "Timing Saw Phasor 4"))
(defonce phasor-b5 (control-bus 1 "Timing Saw Phasor 5"))
(defonce saw-s1 (time/saw-x [:head rhythm-g] :out-bus saw-x-b1))
(defonce saw-s2 (time/saw-x [:head rhythm-g] :out-bus saw-x-b2))
(defonce saw-s3 (time/saw-x [:head rhythm-g] :out-bus saw-x-b3))
(defonce phasor-s1 (time/buf-phasor [:after saw-s1] saw-x-b1 :out-bus phasor-b1 :buf saw-bf1))
(defonce phasor-s2 (time/buf-phasor [:after saw-s2] saw-x-b2 :out-bus phasor-b2 :buf saw-bf2))
(def space-notes-buf (buffer 5))
(def space-tones-buf (buffer 3))
(defonce phasor-s3 (time/buf-phasor [:after saw-s3] saw-x-b3 :out-bus phasor-b3 :buf space-notes-buf))
(defsynth buffered-plain-space-organ [out-bus 0 duration 4 amp 1]
(let [tone (/ (in:kr phasor-b2) 2)
tones (map #(blip (* % 2) (mul-add:kr (lf-noise1:kr 1/8) 1 4)) [tone])]
(out out-bus (pan2 (* amp (g-verb (sum tones) 200 8))))))
(defsynth ratatat [out-bus 0 amp 1]
(let [freq (in:kr phasor-b2)
sin1 (sin-osc (* 1.01 freq))
sin2 (sin-osc (* 1 freq))
sin3 (sin-osc (* 0.99 freq))
src (mix [sin1 sin2 sin3])
src (g-verb src :spread 10)]
(out out-bus (* amp (pan2 src)))))
(defn transpose [updown notes]
(map #(+ updown %1) notes))
(def space-notes [8 16 32 16 8])
(def space-tones [8 16 24])
(defsynth crystal-space-organ [out-bus 0 amp 1 size 200 r 8 numharm 0 trig 0 t0 8 t1 16 t2 24 d0 1 d1 1/2 d2 1/4 d3 1/8]
(let [notes (map #(midicps (duty:kr % (mod trig 16) (dseq space-notes INF))) [d0 d1 d2 d3])
tones (map (fn [note tone] (blip (* note tone) numharm)) notes [t0 t1 t2])]
(out out-bus (* amp (g-verb (sum tones) size r)))))
(comment (def csp (crystal-space-organ :numharm 0 :amp 0.5)))
(def space-notes [8 16 32 16 8])
(defsynth high-space-organ [cutoff 90 out-bus 0 amp 1 size 200 r 8 noise 10 trig 0 t0 8 t1 16 t2 24 d0 1 d1 1/2 d2 1/4]
(let [space-notes1-buf (buf-rd:kr 1 space-notes-buf 0)
space-notes2-buf (buf-rd:kr 1 space-notes-buf 1)
space-notes3-buf (buf-rd:kr 1 space-notes-buf 2)
space-notes4-buf (buf-rd:kr 1 space-notes-buf 3)
space-notes5-buf (buf-rd:kr 1 space-notes-buf 4)
space-notes-in [space-notes1-buf space-notes2-buf space-notes3-buf space-notes4-buf space-notes5-buf]
notes (map #(duty:kr % (mod trig 16) (dseq space-notes-in INF)) [d0 d1 d2])
tones (map (fn [note tone]
(println :none note :tone tone)
(blip (* note tone) (mul-add:kr (lf-noise1:kr noise) 3 4))) notes [t0 t1 t2])
_ (println tones)
src (* amp (g-verb (sum tones) size r))
src (lpf src cutoff)]
(out out-bus src)))
(println (map midi->hz [8 16 32 16 8]))
(ctl so :t0 1 :t1 1 :t2 1)
(pattern! space-notes-buf (map midi->hz (degrees-seq [:C#0 1 :C#0 3 :C#1 5])))
: t0 2 : t1 4 : t2 8 : out - bus 0
(pattern! space-notes-buf (map midi->hz [8 16 32 16 8]))
(def so (high-space-organ :amp 0.4
:trig time/beat-count-b
:noise 220 :t0 1 :t1 1 :t2 2 :out-bus 0))
(ctl so :cutoff 2000a)
(ctl so :amp 0.5)
(ctl so :t0 2)
(ctl so :t1 4)
(ctl so :t2 8)
(kill high-space-organ)
(comment (high-space-organ))
(defsynth timed-high-space-organ [out-bus 0 amp 1 size 200 r 8 noise 10 ]
(let [note (in:kr phasor-b3)
tone1 (buf-rd:kr 1 space-tones-buf 0)
tone2 (buf-rd:kr 1 space-tones-buf 1)
tone3 (buf-rd:kr 1 space-tones-buf 2)
trig1 (t-duty:kr (dseq [1] INFINITE))
trig2 (t-duty:kr (dseq [1/2] INFINITE))
trig3 (t-duty:kr (dseq [1/4] INFINITE))
note1 (midicps (demand:kr trig1 0 (drand note INFINITE)))
note2 (midicps (demand:kr trig2 0 (drand note INFINITE)))
note3 (midicps (demand:kr trig3 0 (drand note INFINITE)))
all-tones [tone1 tone2 tone3]
all-notes [note1 note2 note3]
tones (map (fn [note tone] (blip (* note tone)
(mul-add:kr (lf-noise1:kr noise) 3 4))) all-notes all-tones)]
(out out-bus (* amp (g-verb (sum tones) size r)))))
(comment
(show-graphviz-synth timed-high-space-organ)
(ctl saw-s3 :freq-mul 1/32)
(buffer-write! space-notes-buf [8 16 32 16 8])
(buffer-write! space-tones-buf [2 4 8])
(buffer-write! space-tones-buf [8 12 16])
(buffer-write! space-tones-buf [8 16 24])
(def thso (timed-high-space-organ :noise 220 :amp 0.4))
(ctl thso :noise 10)
(ctl thso :size 0)
(ctl thso :size 200)
(def so (high-space-organ :amp 0.4 :trig time/beat-count-b :noise 220 :t0 2 :t1 4 :t2 8 :out-bus 0))
(show-graphviz-synth high-space-organ)
(stop))
(defsynth plain-space-organ [out-bus 0 tone 1 duration 3 amp 1]
(let [tones (map #(blip (* % 2) (mul-add:kr 1/8 1 4)) [tone])]
(out out-bus (* amp (g-verb (sum tones) 200 8) (line 1 0 duration FREE)))))
(defsynth space-organ [out-bus 0 tone 1 duration 3 amp 1]
(let [f (map #(midicps (duty:kr % 0 (dseq 2 4)))
[1])
tones (map #(blip (* % %2) (mul-add:kr (lf-noise1:kr 1/8) 2 4))
f
[tone])]
(out out-bus (* amp (g-verb (sum tones) 200 8) (line 1 0 duration FREE))))))
SCORE
(def sun (sample-player star-into-the-sun :rate 0.99 :amp 8 :out-bus 0))
(def space-and-time (sample-player space-and-time-sun :rate 0.8))
(ctl space-and-time :rate 0.7)
(ctl space-and-time :rate 0.8)
(syn/fallout-wind)
(syn/soft-phasing :amp 0.0)
(def dark (syn/dark-sea-horns :amp 0.3))
(ctl dark :amp 1)
(kill dark)
(kill syn/soft-phasing)
(kill syn/fallout-wind)
(def score (map note [:F5 :G5 :G5 :G5 :G5 :BB5 :BB5 :D#5]))
(buffer-write! saw-bf2 (repeat 256 (midi->hz (note :A3))))
(buffer-write! saw-bf2 (map midi->hz
(map (fn [midi-note] (+ -12 midi-note))
(map note (take 256 (cycle score))))))
(buffer-write! saw-bf2 (map midi->hz
(map (fn [midi-note] (+ -5 midi-note))
(map note (take 256 (cycle score))))))
(buffer-write! saw-bf2 (map midi->hz
(map (fn [midi-note] (+ 0 midi-note))
(map note (take 256 (cycle score))))))
(ratatat :amp 0.9)
(ctl saw-s2 :freq-mul 1/40)
(kill ratatat)
(buffered-plain-space-organ :amp 0.8)
(kill buffered-plain-space-organ)
(stop)
(plain-space-organ :tone (/ 24 2) :duration 16)
(def note-cycle (degrees [1 2 3] :major :C#2))
(def note-inc (atom 0))
(def trigger-g99018
(on-beat-trigger 8 (fn []
(swap! note-inc inc)
(plain-space-organ :tone (/ (midi->hz (nth (degrees [1 2 3] :major :C#1) (mod @note-inc 3) ) ) 1) :duration 16.0 :amp 0.2)
)))
(remove-beat-trigger trigger-g99018)
(remove-all-beat-triggers)
(def so (high-space-organ :amp 0.4 :trig time/beat-count-b :noise 220 :t0 2 :t1 4 :t2 8 :out-bus 0))
(def so (high-space-organ :amp 0.4 :trig time/beat-count-b :noise 220 :t0 1 :t1 1 :t2 1 :out-bus 0))
(ctl so :cutoff 250)
(kill so)
(ctl so :noise 50)
(ctl so :vol 1)
(ctl so :t0 1 :t1 1 :t2 1)
(ctl so :t0 8 :t1 12 :t2 16)
(ctl so :t0 8 :t1 16 :t2 24)
(ctl so :r 10)
(ctl so :size 0)
(ctl so :size 200)
(ctl so :amp 0.1)
(volume 1.0)
(comment (stop))
(comment
(defonce kick-seq-buf (buffer 256))
(def beats (cs/buffer->tap-lite kick-seq-buf (:count time/beat-1th) :measure 8))
(start-graphics "resources/shaders/space_and_time.glsl"
:textures [:overtone-audio
:previous-frame
"resources/textures/tex16.png"
"resources/textures/time.png"
]
:user-data {"iGlobalBeatCount" (atom {:synth beats :tap "global-beat-count"})})
(stop-graphics "resources/shaders/space_and_time.glsl")
)
|
89d82d9fca12d831246add73a68dbf79452e3951f20017bcb185416ad204e103 | Apress/beg-haskell | FnsParams.hs | # LANGUAGE LambdaCase #
module Chapter3.FnsParams where
map' :: (a -> b) -> [a] -> [b]
map' _ [] = []
map' f (x:xs) = (f x) : (map f xs)
apply3f2 :: (Integer -> Integer) -> Integer -> Integer
apply3f2 f x = 3 * f (x + 2)
equalTuples :: [(Integer,Integer)] -> [Bool]
equalTuples t = map (\(x,y) -> x == y) t
sayHello :: [String] -> [String]
sayHello names = map (\name -> case name of
"Alejandro" -> "Hello, writer"
_ -> "Welcome, " ++ name
) names
sayHello' :: [String] -> [String]
sayHello' names = map (\case "Alejandro" -> "Hello, writer"
name -> "Welcome, " ++ name
) names
multiplyByN :: Integer -> (Integer -> Integer)
multiplyByN n = \x -> n*x
duplicateOdds :: [Integer] -> [Integer]
duplicateOdds list = map (*2) $ filter odd list
duplicateOdds' :: [Integer] -> [Integer]
duplicateOdds' = map (*2) . filter odd
--uncurry :: (a -> b -> c) -> (a,b) -> c
--uncurry f = \(x,y) -> f x y
--curry :: ((a,b) -> c) -> a -> b -> c
--curry f = \x y -> f (x,y)
(***) :: (a -> b) -> (c -> d) -> ((a,c) -> (b,d))
f *** g = \(x,y) -> (f x, g y)
duplicate :: a -> (a,a)
duplicate x = (x,x)
formula1 :: Integer -> Integer
formula1 = uncurry (+) . ( ((*7) . (+2)) *** (*3) ) . duplicate
maximum' :: [Integer] -> Integer
maximum' = foldr1 max
| null | https://raw.githubusercontent.com/Apress/beg-haskell/aaacbf047d553e6177c38807e662cc465409dffd/chapter3/src/Chapter3/FnsParams.hs | haskell | uncurry :: (a -> b -> c) -> (a,b) -> c
uncurry f = \(x,y) -> f x y
curry :: ((a,b) -> c) -> a -> b -> c
curry f = \x y -> f (x,y) | # LANGUAGE LambdaCase #
module Chapter3.FnsParams where
map' :: (a -> b) -> [a] -> [b]
map' _ [] = []
map' f (x:xs) = (f x) : (map f xs)
apply3f2 :: (Integer -> Integer) -> Integer -> Integer
apply3f2 f x = 3 * f (x + 2)
equalTuples :: [(Integer,Integer)] -> [Bool]
equalTuples t = map (\(x,y) -> x == y) t
sayHello :: [String] -> [String]
sayHello names = map (\name -> case name of
"Alejandro" -> "Hello, writer"
_ -> "Welcome, " ++ name
) names
sayHello' :: [String] -> [String]
sayHello' names = map (\case "Alejandro" -> "Hello, writer"
name -> "Welcome, " ++ name
) names
multiplyByN :: Integer -> (Integer -> Integer)
multiplyByN n = \x -> n*x
duplicateOdds :: [Integer] -> [Integer]
duplicateOdds list = map (*2) $ filter odd list
duplicateOdds' :: [Integer] -> [Integer]
duplicateOdds' = map (*2) . filter odd
(***) :: (a -> b) -> (c -> d) -> ((a,c) -> (b,d))
f *** g = \(x,y) -> (f x, g y)
duplicate :: a -> (a,a)
duplicate x = (x,x)
formula1 :: Integer -> Integer
formula1 = uncurry (+) . ( ((*7) . (+2)) *** (*3) ) . duplicate
maximum' :: [Integer] -> Integer
maximum' = foldr1 max
|
5f44aaa889a861c546d029cd5efb1e514d8b3697a2b819f799658d04b21e9014 | maacl/websocket-test | crypto.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 compojure.crypto
"Functions for cryptographically signing, verifying and encrypting data."
(:use compojure.encodings
clojure.contrib.def
clojure.contrib.java-utils)
(:import java.security.SecureRandom
[javax.crypto Cipher KeyGenerator Mac]
[javax.crypto.spec SecretKeySpec IvParameterSpec]
java.util.UUID))
(defvar hmac-defaults
{:algorithm "HmacSHA256"}
"Default options for HMACs.")
(defvar encrypt-defaults
{:algorithm "AES"
:key-size 128
:mode "CBC"
:padding "PKCS5Padding"}
"Default options for symmetric encryption.")
(defn secure-random-bytes
"Returns a random byte array of the specified size. Can optionally supply
an PRNG algorithm (defaults is SHA1PRNG)."
([size]
(secure-random-bytes size "SHA1PRNG"))
([size algorithm]
(let [seed (make-array Byte/TYPE size)]
(.nextBytes (SecureRandom/getInstance algorithm) seed)
seed)))
(defn gen-secret-key
"Generate a random secret key from a map of encryption options."
([]
(gen-secret-key {}))
([options]
(secure-random-bytes (/ (options :key-size) 8))))
(defn gen-uuid
"Generate a random UUID."
[]
(str (UUID/randomUUID)))
(defn- to-bytes
"Converts its argument into an array of bytes."
[x]
(cond
(string? x) (.getBytes x)
(sequential? x) (into-array Byte/TYPE x)
:else x))
(defn hmac-bytes
"Generate a HMAC byte array with the supplied key on a byte array of data.
Takes an optional map of cryptography options."
[options key data]
(let [options (merge hmac-defaults options)
algorithm (options :algorithm)
hmac (doto (Mac/getInstance algorithm)
(.init (SecretKeySpec. key algorithm)))]
(.doFinal hmac data)))
(defn hmac
"Generate a Basc64-encoded HMAC with the supplied key on a byte array or
string of data. Takes an optional map of cryptography options."
[options key data]
(base64-encode-bytes (hmac-bytes options key (to-bytes data))))
(defn- make-algorithm
"Return an algorithm string suitable for JCE from a map of options."
[options]
(str "AES/" (options :mode) "/" (options :padding)))
(defn- make-cipher
"Create an AES Cipher instance."
[options]
(Cipher/getInstance (make-algorithm options)))
(defn encrypt-bytes
"Encrypts a byte array with the given key and encryption options."
[options key data]
(let [options (merge encrypt-defaults options)
cipher (make-cipher options)
secret-key (SecretKeySpec. key (options :algorithm))
iv (secure-random-bytes (.getBlockSize cipher))]
(.init cipher Cipher/ENCRYPT_MODE secret-key (IvParameterSpec. iv))
(to-bytes (concat iv (.doFinal cipher data)))))
(defn decrypt-bytes
"Decrypts a byte array with the given key and encryption options."
[options key data]
(let [options (merge encrypt-defaults options)
cipher (make-cipher options)
[iv data] (split-at (.getBlockSize cipher) data)
iv-spec (IvParameterSpec. (to-bytes iv))
secret-key (SecretKeySpec. key (options :algorithm))]
(.init cipher Cipher/DECRYPT_MODE secret-key iv-spec)
(.doFinal cipher (to-bytes data))))
(defn encrypt
"Encrypts a string or byte array with the given key and encryption options."
[options key data]
(base64-encode-bytes (encrypt-bytes options key (to-bytes data))))
(defn decrypt
"Base64 encodes and encrypts a string with the given key and algorithm."
[options key data]
(String. (decrypt-bytes options key (base64-decode-bytes data))))
(defn seal
"Seal a data structure into a cryptographically secure string. Ensures no-one
looks at or tampers with the data inside."
[key data]
(let [data (encrypt {} key (marshal data))]
(str data "--" (hmac {} key data))))
(defn unseal
"Read a cryptographically sealed data structure."
[key data]
(let [[data mac] (.split data "--")]
(if (= mac (hmac {} key data))
(unmarshal (decrypt {} key data)))))
| null | https://raw.githubusercontent.com/maacl/websocket-test/d79dfdf82762d566cd89b535c3dbede2788bb034/src/compojure/crypto.clj | clojure | 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 .
The use and distribution terms for this software are covered by the Eclipse
(ns compojure.crypto
"Functions for cryptographically signing, verifying and encrypting data."
(:use compojure.encodings
clojure.contrib.def
clojure.contrib.java-utils)
(:import java.security.SecureRandom
[javax.crypto Cipher KeyGenerator Mac]
[javax.crypto.spec SecretKeySpec IvParameterSpec]
java.util.UUID))
(defvar hmac-defaults
{:algorithm "HmacSHA256"}
"Default options for HMACs.")
(defvar encrypt-defaults
{:algorithm "AES"
:key-size 128
:mode "CBC"
:padding "PKCS5Padding"}
"Default options for symmetric encryption.")
(defn secure-random-bytes
"Returns a random byte array of the specified size. Can optionally supply
an PRNG algorithm (defaults is SHA1PRNG)."
([size]
(secure-random-bytes size "SHA1PRNG"))
([size algorithm]
(let [seed (make-array Byte/TYPE size)]
(.nextBytes (SecureRandom/getInstance algorithm) seed)
seed)))
(defn gen-secret-key
"Generate a random secret key from a map of encryption options."
([]
(gen-secret-key {}))
([options]
(secure-random-bytes (/ (options :key-size) 8))))
(defn gen-uuid
"Generate a random UUID."
[]
(str (UUID/randomUUID)))
(defn- to-bytes
"Converts its argument into an array of bytes."
[x]
(cond
(string? x) (.getBytes x)
(sequential? x) (into-array Byte/TYPE x)
:else x))
(defn hmac-bytes
"Generate a HMAC byte array with the supplied key on a byte array of data.
Takes an optional map of cryptography options."
[options key data]
(let [options (merge hmac-defaults options)
algorithm (options :algorithm)
hmac (doto (Mac/getInstance algorithm)
(.init (SecretKeySpec. key algorithm)))]
(.doFinal hmac data)))
(defn hmac
"Generate a Basc64-encoded HMAC with the supplied key on a byte array or
string of data. Takes an optional map of cryptography options."
[options key data]
(base64-encode-bytes (hmac-bytes options key (to-bytes data))))
(defn- make-algorithm
"Return an algorithm string suitable for JCE from a map of options."
[options]
(str "AES/" (options :mode) "/" (options :padding)))
(defn- make-cipher
"Create an AES Cipher instance."
[options]
(Cipher/getInstance (make-algorithm options)))
(defn encrypt-bytes
"Encrypts a byte array with the given key and encryption options."
[options key data]
(let [options (merge encrypt-defaults options)
cipher (make-cipher options)
secret-key (SecretKeySpec. key (options :algorithm))
iv (secure-random-bytes (.getBlockSize cipher))]
(.init cipher Cipher/ENCRYPT_MODE secret-key (IvParameterSpec. iv))
(to-bytes (concat iv (.doFinal cipher data)))))
(defn decrypt-bytes
"Decrypts a byte array with the given key and encryption options."
[options key data]
(let [options (merge encrypt-defaults options)
cipher (make-cipher options)
[iv data] (split-at (.getBlockSize cipher) data)
iv-spec (IvParameterSpec. (to-bytes iv))
secret-key (SecretKeySpec. key (options :algorithm))]
(.init cipher Cipher/DECRYPT_MODE secret-key iv-spec)
(.doFinal cipher (to-bytes data))))
(defn encrypt
"Encrypts a string or byte array with the given key and encryption options."
[options key data]
(base64-encode-bytes (encrypt-bytes options key (to-bytes data))))
(defn decrypt
"Base64 encodes and encrypts a string with the given key and algorithm."
[options key data]
(String. (decrypt-bytes options key (base64-decode-bytes data))))
(defn seal
"Seal a data structure into a cryptographically secure string. Ensures no-one
looks at or tampers with the data inside."
[key data]
(let [data (encrypt {} key (marshal data))]
(str data "--" (hmac {} key data))))
(defn unseal
"Read a cryptographically sealed data structure."
[key data]
(let [[data mac] (.split data "--")]
(if (= mac (hmac {} key data))
(unmarshal (decrypt {} key data)))))
|
3bec48ada637baf3b58f1531b21fa5e69b2300514017903c364b9918cc057a05 | Lovesan/clave | io-flags.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
Copyright ( C ) 2017 , < lovesan.ru at gmail.com >
;;; 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 #:clave)
(defbitfield io-flags
(:read 1)
(:write 2)
(:non-block 8)
(:direct #x8000))
;; vim: ft=lisp et
| null | https://raw.githubusercontent.com/Lovesan/clave/3b08ed4c4cb3fa885739355821f73bbfd75a2a7d/src/io-flags.lisp | lisp | -*- Mode: lisp; indent-tabs-mode: nil -*-
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.
vim: ft=lisp et |
Copyright ( C ) 2017 , < lovesan.ru at gmail.com >
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 #:clave)
(defbitfield io-flags
(:read 1)
(:write 2)
(:non-block 8)
(:direct #x8000))
|
a606e7d7373807ef03ed17bceb2647ce3222fedba0e71cc7f6896afd849a5eec | polymeris/cljs-aws | s3_example.cljs | (ns cljs-aws.s3-example
(:require [cljs-aws.s3 :as s3]
[cljs.core.async :refer [go <!]]
[cljs-aws.examples-util :as util :refer [throw-or-print]]))
(enable-console-print!)
(defn -main
"Example cljs script using cljs-aws.
Fetches a list of buckets from S3, then the objects contained in the first bucket.
Set your credentials before executing."
[& args]
(go
(util/override-endpoint-with-env)
(let [first-bucket-name (-> (<! (s3/list-buckets {}))
(throw-or-print)
:buckets
(first)
:name)
object-keys (when first-bucket-name
(->> (<! (s3/list-objects-v2 {:bucket first-bucket-name}))
(throw-or-print)
:contents
(map :key)))]
(println "KEYS:" object-keys))))
(set! *main-cli-fn* -main) | null | https://raw.githubusercontent.com/polymeris/cljs-aws/3326e7c4db4dfc36dcb80770610c14c8a7fd0d66/node-examples/src/cljs_aws/s3_example.cljs | clojure | (ns cljs-aws.s3-example
(:require [cljs-aws.s3 :as s3]
[cljs.core.async :refer [go <!]]
[cljs-aws.examples-util :as util :refer [throw-or-print]]))
(enable-console-print!)
(defn -main
"Example cljs script using cljs-aws.
Fetches a list of buckets from S3, then the objects contained in the first bucket.
Set your credentials before executing."
[& args]
(go
(util/override-endpoint-with-env)
(let [first-bucket-name (-> (<! (s3/list-buckets {}))
(throw-or-print)
:buckets
(first)
:name)
object-keys (when first-bucket-name
(->> (<! (s3/list-objects-v2 {:bucket first-bucket-name}))
(throw-or-print)
:contents
(map :key)))]
(println "KEYS:" object-keys))))
(set! *main-cli-fn* -main) |
|
24d57f84da89472b9cf69e6b0b4e55265cf5e3ac833847c2f51460ed50a9ee5e | polymeris/cljs-aws | s3_test.cljs | (ns cljs-aws.services.s3-test
(:require [clojure.test :refer [deftest is async]]
[camel-snake-kebab.core :refer [->camelCaseString]]
[cljs.core.async :as a]
[cljs-aws.s3 :as s3])
(:require-macros [cljs-aws.test-macros :refer [with-example-mocks]]))
(deftest examples--s3--ok
(async done
(a/go
(with-example-mocks "S3" "s3-2006-03-01.examples.json"
(is (= {}
(a/<! (s3/abort-multipart-upload
{:bucket "examplebucket"
:key "bigobject"
:upload-id "xadcOB_7YPBOJuoFiQ9cz4P3Pe6FIZwO4f7wN93uHsNBEw97pl5eNwzExg0LAT2dUN91cOmrEQHDsP3WA60CEg--"}))))
(is (= {:bucket "acexamplebucket"
:e-tag "\"4d9031c7644d8081c2829f4ea23c55f7-2\""
:key "bigobject"
:location ""}
(a/<! (s3/complete-multipart-upload
{:bucket "examplebucket"
:key "bigobject"
:multipart-upload {:parts [{:e-tag "\"d8c2eafd90c266e19ab9dcacc479f8af\"", :part-number "1"}
{:e-tag "\"d8c2eafd90c266e19ab9dcacc479f8af\"", :part-number "2"}]}
:upload-id "7YPBOJuoFiQ9cz4P3Pe6FIZwO4f7wN93uHsNBEw97pl5eNwzExg0LAT2dUN91cOmrEQHDsP3WA60CEg--"}))))
(is (= {:copy-object-result {:e-tag "\"6805f2cfc46c0f04559748bb039d69ae\"", :last-modified "2016-12-15T17:38:53.000Z"}}
(a/<! (s3/copy-object {:bucket "destinationbucket"
:copy-source "/sourcebucket/HappyFacejpg"
:key "HappyFaceCopyjpg"}))))
(is (= {:location "/"}
(a/<! (s3/create-bucket {:bucket "examplebucket"
:create-bucket-configuration {:location-constraint "eu-west-1"}}))))
(done))))) | null | https://raw.githubusercontent.com/polymeris/cljs-aws/3326e7c4db4dfc36dcb80770610c14c8a7fd0d66/test/cljs_aws/services/s3_test.cljs | clojure | (ns cljs-aws.services.s3-test
(:require [clojure.test :refer [deftest is async]]
[camel-snake-kebab.core :refer [->camelCaseString]]
[cljs.core.async :as a]
[cljs-aws.s3 :as s3])
(:require-macros [cljs-aws.test-macros :refer [with-example-mocks]]))
(deftest examples--s3--ok
(async done
(a/go
(with-example-mocks "S3" "s3-2006-03-01.examples.json"
(is (= {}
(a/<! (s3/abort-multipart-upload
{:bucket "examplebucket"
:key "bigobject"
:upload-id "xadcOB_7YPBOJuoFiQ9cz4P3Pe6FIZwO4f7wN93uHsNBEw97pl5eNwzExg0LAT2dUN91cOmrEQHDsP3WA60CEg--"}))))
(is (= {:bucket "acexamplebucket"
:e-tag "\"4d9031c7644d8081c2829f4ea23c55f7-2\""
:key "bigobject"
:location ""}
(a/<! (s3/complete-multipart-upload
{:bucket "examplebucket"
:key "bigobject"
:multipart-upload {:parts [{:e-tag "\"d8c2eafd90c266e19ab9dcacc479f8af\"", :part-number "1"}
{:e-tag "\"d8c2eafd90c266e19ab9dcacc479f8af\"", :part-number "2"}]}
:upload-id "7YPBOJuoFiQ9cz4P3Pe6FIZwO4f7wN93uHsNBEw97pl5eNwzExg0LAT2dUN91cOmrEQHDsP3WA60CEg--"}))))
(is (= {:copy-object-result {:e-tag "\"6805f2cfc46c0f04559748bb039d69ae\"", :last-modified "2016-12-15T17:38:53.000Z"}}
(a/<! (s3/copy-object {:bucket "destinationbucket"
:copy-source "/sourcebucket/HappyFacejpg"
:key "HappyFaceCopyjpg"}))))
(is (= {:location "/"}
(a/<! (s3/create-bucket {:bucket "examplebucket"
:create-bucket-configuration {:location-constraint "eu-west-1"}}))))
(done))))) |
|
1bd9c9a79cba351ef35e0cc3e42b3d2581a2b48dbf74dbc4ba285e42f665224e | gfngfn/otfed | encodeError.ml |
open Basic
type unsupported_report =
| LocalSubrOperation
[@@deriving show { with_path = false }]
type t =
| NotEncodableAsUint8 of int
| NotEncodableAsInt8 of int
| NotEncodableAsUint16 of int
| NotEncodableAsInt16 of int
| NotEncodableAsUint24 of int
| NotEncodableAsUint32 of wint
| NotEncodableAsInt32 of wint
| NotEncodableAsTimestamp of wint
| NotA10BytePanose of string
| NotA4ByteAchVendId of string
| Version4FsSelection of Value.Os2.fs_selection
| TooLargeToDetermineOffSize of int
| NotEncodableAsDictValue of int
| InvalidNumberOfGlyphNames of { expected : int; got : int }
| Unsupported of unsupported_report
[@@deriving show { with_path = false }]
| null | https://raw.githubusercontent.com/gfngfn/otfed/3c6d8ea0b05fc18a48cb423451da7858bf73d1d0/src/encodeError.ml | ocaml |
open Basic
type unsupported_report =
| LocalSubrOperation
[@@deriving show { with_path = false }]
type t =
| NotEncodableAsUint8 of int
| NotEncodableAsInt8 of int
| NotEncodableAsUint16 of int
| NotEncodableAsInt16 of int
| NotEncodableAsUint24 of int
| NotEncodableAsUint32 of wint
| NotEncodableAsInt32 of wint
| NotEncodableAsTimestamp of wint
| NotA10BytePanose of string
| NotA4ByteAchVendId of string
| Version4FsSelection of Value.Os2.fs_selection
| TooLargeToDetermineOffSize of int
| NotEncodableAsDictValue of int
| InvalidNumberOfGlyphNames of { expected : int; got : int }
| Unsupported of unsupported_report
[@@deriving show { with_path = false }]
|
|
1d0d9818c232bbd8baf7f276ebccb35ec1665a576a8a547d0d25b6994b8fe484 | spechub/Hets | PPrel.hs |
module PPrel where
-- Standard types, classes, instances and related functions
-- Numeric classes
class (Num a, Ord a) => RealK a where
toRational' :: a -> Rational
class (RealK a, Enum a) => IntegralK a where
quot', rem' :: a -> a -> a
div', mod' :: a -> a -> a
quotRem', divMod' :: a -> a -> (a, a)
toInteger' :: a -> Integer
{- Minimal complete definition:
quotRem, toInteger -}
n `quot'` d = fst (quotRem' n d)
n `rem'` d = snd (quotRem' n d)
n `div'` d = fst (divMod' n d)
n `mod'` d = snd (divMod' n d)
divMod' n d = let qr = quotRem' n d
q = fst qr
r = snd qr
in if signum r == (0 - signum d) then
(q - 1, r + d) else quotRem' n d
if signum r = = - signum d then ( q-1 , r+d )
else quotRem n d
else quotRem n d -}
class (Num a) => FractionalK a where
(/#) :: a -> a -> a
recip' :: a -> a
fromRational' :: Rational -> a
{- Minimal complete definition:
fromRational and (recip or (/)) -}
recip' x = 1 /# x
x /# y = x * recip' y
-- Numeric functions
subtract ' : : ( a ) = > a - > a - > a
subtract ' = flip ' ( - )
subtract' = flip' (-) -}
even', odd' :: (IntegralK a) => a -> Bool
even' n = n `rem'` 2 == 0
odd' = not . even'
gcd' :: (IntegralK a) => a -> a -> a
gcd' 0 0 = error "Prelude.gcd: gcd 0 0 is undefined"
gcd' x y = gcdH (abs x) (abs y)
gcdH :: (IntegralK a) => a -> a -> a
gcdH x 0 = x
gcdH x y = gcdH y (x `rem'` y)
lcm' :: (IntegralK a) => a -> a -> a
lcm' _ 0 = 0
lcm' 0 _ = 0
lcm' x y = abs ((x `quot'` (gcd' x y)) * y)
(^#) :: (Num a, IntegralK b) => a -> b -> a
x ^# 0 = 1
x ^# n | n > 0 = powAux x (n - 1) x
_ ^# _ = error "Prelude.^: negative exponent"
powAux :: (Num a, IntegralK b) => a -> b -> a -> a
powAux _ 0 y = y
powAux x n y = powBux x n y
powBux :: (Num a, IntegralK b) => a -> b -> a -> a
powBux x n y | even' n = powBux (x * x) (n `quot'` 2) y
| otherwise' = powAux x (n - 1) (x * y)
(^^#) :: (FractionalK a, IntegralK b) => a -> b -> a
x ^^# n = if n >= 0 then x ^# n else recip' (x ^# (0 - n))
fromIntegral' :: (IntegralK a, Num b) => a -> b
fromIntegral' = fromInteger . toInteger'
realToFrac' :: (RealK a, FractionalK b) => a -> b
realToFrac' = fromRational' . toRational'
-- Trivial type
data ( ) = ( ) deriving ( Eq , Ord , , Bounded )
Not legal ; for illustration only
Not legal Haskell; for illustration only -}
-- Function type
-- identity function
id' :: a -> a
id' x = x
-- constant function
const' :: a -> b -> a
const' x _ = x
-- function composition
{- (.) :: (b -> c) -> (a -> b) -> a -> c
f . g = \ x -> f (g x) -}
flip f takes its ( first ) two arguments in the reverse order of f.
{- flip' :: (a -> b -> c) -> b -> a -> c
flip' f x y = f y x -}
{-
seq :: a -> b -> b
seq = ... -- Primitive
-}
{- right-associating infix application operators
(useful in continuation-passing style) -}
( $ ) , ( $ ! ) : : ( a - > b ) - > a - > b
f $ x = f x
f $ ! x = ( f x )
f $ x = f x
f $! x = P.seq x (f x) -}
-- Boolean type
data Bool = False | True deriving ( P.Eq , P.Ord , P.Enum , P.Bounded )
-- Boolean functions
otherwise' :: Bool
otherwise' = True
{- primIntToChar = undefined'
primCharToInt = undefined'
primUnicodeMaxChar = undefined' -}
maybe' :: b -> (a -> b) -> Maybe a -> b
maybe' n f Nothing = n
maybe' n f (Just x) = f x
either' :: (a -> c) -> (b -> c) -> Either a b -> c
either' f g (Left x) = f x
either' f g (Right y) = g y
{- curry converts an uncurried function to a curried function;
uncurry converts a curried function to a function on pairs. -}
curry' :: ((a, b) -> c) -> a -> b -> c
curry' f x y = f (x, y)
uncurry' :: (a -> b -> c) -> ((a, b) -> c)
uncurry' f p = f (fst p) (snd p)
-- Misc functions
until p f yields the result of applying f until p holds .
until' :: (a -> Bool) -> (a -> a) -> a -> a
until' p f x
| p x = x
| otherwise' = until' p f (f x)
asTypeOf is a type - restricted version of const . It is usually used
as an infix operator , and its typing forces its first argument
( which is usually overloaded ) to have the same type as the second .
as an infix operator, and its typing forces its first argument
(which is usually overloaded) to have the same type as the second. -}
asTypeOf' :: a -> a -> a
asTypeOf' = const'
-- error stops execution and displays an error message
{- error' :: String -> a
error' = primError -}
{- It is expected that compilers will recognize this and insert error
messages that are more appropriate to the context in which undefined
appears. -}
undefined' :: a
undefined' = error "Prelude.undefined"
-- Standard list functions
-- Map and append
head' :: [a] -> a
head' (x : _) = x
head' [] = error "Prelude.head: empty list"
tail' :: [a] -> [a]
tail' (_ : xs) = xs
tail' [] = error "Prelude.tail: empty list"
{- map' :: (a -> b) -> [a] -> [b]
map' f [] = []
map' f (x:xs) = f x : map' f xs -}
(++#) :: [a] -> [a] -> [a]
[] ++# ys = ys
(x : xs) ++# ys = x : (xs ++# ys)
filter' :: (a -> Bool) -> [a] -> [a]
filter' p [] = []
filter' p (x : xs) | p x = x : filter' p xs
| otherwise' = filter' p xs
concat' :: [[a]] -> [a]
concat' xss = foldr' (++#) [] xss
concatMap' :: (a -> [b]) -> [a] -> [b]
concatMap' f = concat' . map f
head and tail extract the first element and remaining elements ,
respectively , of a list , which must be non - empty . last and init
are the dual functions working from the end of a finite list ,
rather than the beginning .
respectively, of a list, which must be non-empty. last and init
are the dual functions working from the end of a finite list,
rather than the beginning. -}
last' :: [a] -> a
last' [x] = x
last' (_ : xs) = last' xs
last' [] = error "Prelude.last: empty list"
init' :: [a] -> [a]
init' [x] = []
init' (x : xs) = x : init' xs
init' [] = error "Prelude.init: empty list"
null' :: [a] -> Bool
null' [] = True
null' (_ : _) = False
-- length returns the length of a finite list as an Int.
length' :: [a] -> Int
length' [] = 0
length' (_ : l) = 1 + length' l
-- List index (subscript) operator, 0-origin
(!!#) :: [a] -> Int -> a
xs !!# n | n < 0 = error "Prelude.!!: negative index"
[] !!# _ = error "Prelude.!!: index too large"
(x : _) !!# 0 = x
(_ : xs) !!# n = xs !!# (n - 1)
foldl , applied to a binary operator , a starting value ( typically the
left - identity of the operator ) , and a list , reduces the list using
the binary operator , from left to right :
foldl f z [ x1 , x2 , ... , xn ] = = ( ... ( ( z ` f ` x1 ) ` f ` x2 ) ` f ` ... ) ` f ` xn
foldl1 is a variant that has no starting value argument , and thus must
be applied to non - empty lists . is similar to foldl , but returns
a list of successive reduced values from the left :
f z [ x1 , x2 , ... ] = = [ z , z ` f ` x1 , ( z ` f ` x1 ) ` f ` x2 , ... ]
Note that last ( f z xs ) = = foldl f z xs .
scanl1 is similar , again without the starting element :
f [ x1 , x2 , ... ] = = [ x1 , x1 ` f ` x2 , ... ]
left-identity of the operator), and a list, reduces the list using
the binary operator, from left to right:
foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn
foldl1 is a variant that has no starting value argument, and thus must
be applied to non-empty lists. scanl is similar to foldl, but returns
a list of successive reduced values from the left:
scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
Note that last (scanl f z xs) == foldl f z xs.
scanl1 is similar, again without the starting element:
scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...] -}
foldl' :: (a -> b -> a) -> a -> [b] -> a
foldl' f z [] = z
foldl' f z (x : xs) = foldl' f (f z x) xs
foldl1' :: (a -> a -> a) -> [a] -> a
foldl1' f (x : xs) = foldl' f x xs
foldl1' _ [] = error "Prelude.foldl1: empty list"
scanl' :: (a -> b -> a) -> a -> [b] -> [a]
scanl' f q xs = q : (case xs of
[] -> []
x : xs -> scanl' f (f q x) xs)
scanl1' :: (a -> a -> a) -> [a] -> [a]
scanl1' f (x : xs) = scanl' f x xs
scanl1' _ [] = []
foldr , foldr1 , , and scanr1 are the right - to - left duals of the
above functions .
above functions. -}
foldr' :: (a -> b -> b) -> b -> [a] -> b
foldr' f z [] = z
foldr' f z (x : xs) = f x (foldr' f z xs)
foldr1' :: (a -> a -> a) -> [a] -> a
foldr1' f [x] = x
foldr1' f (x : xs) = f x (foldr1' f xs)
foldr1' _ [] = error "Prelude.foldr1: empty list"
scanr' :: (a -> b -> b) -> b -> [a] -> [b]
scanr' f q0 [] = [q0]
scanr' f q0 (x : xs) = let qs = scanr' f q0 xs
in f x (head' qs) : qs
-- where qs@(q:_) = scanr f q0 xs
scanr1' :: (a -> a -> a) -> [a] -> [a]
scanr1' f [] = []
scanr1' f [x] = [x]
scanr1' f (x : xs) = let qs = scanr1' f xs
in f x (head' qs) : qs
{- iterate f x returns an infinite list of repeated applications of f to x:
iterate f x == [x, f x, f (f x), ...] -}
iterate' :: (a -> a) -> a -> [a]
iterate' f x = x : iterate' f (f x)
-- repeat x is an infinite list, with x the value of every element.
repeat' :: a -> [a]
repeat' x = x : (repeat' x)
-- replicate n x is a list of length n with x the value of every element
replicate' :: Int -> a -> [a]
replicate' n x = take' n (repeat' x)
{- cycle ties a finite list into a circular one, or equivalently,
the infinite repetition of the original list. It is the identity
on infinite lists. -}
cycle' :: [a] -> [a]
cycle' [] = error "Prelude.cycle: empty list"
cycle' xs = xs ++# cycle' xs
-- cycle xs = xs' where xs' = xs ++ xs'
take n , applied to a list xs , returns the prefix of xs of length n ,
or xs itself if n > length xs . drop n xs returns the suffix of xs
after the first n elements , or [ ] if n > length xs . splitAt n xs
is equivalent to ( take n xs , drop n xs ) .
or xs itself if n > length xs. drop n xs returns the suffix of xs
after the first n elements, or [] if n > length xs. splitAt n xs
is equivalent to (take n xs, drop n xs). -}
take' :: Int -> [a] -> [a]
take' n _ | n <= 0 = []
take' _ [] = []
take' n (x : xs) = x : take' (n - 1) xs
drop' :: Int -> [a] -> [a]
drop' n xs | n <= 0 = xs
drop' _ [] = []
drop' n (_ : xs) = drop' (n - 1) xs
splitAt' :: Int -> [a] -> ([a], [a])
splitAt' n xs = (take' n xs, drop' n xs)
takeWhile , applied to a predicate p and a list xs , returns the longest
prefix ( possibly empty ) of xs of elements that satisfy p. dropWhile p xs
returns the remaining suffix . span is equivalent to
( takeWhile p xs , dropWhile p xs ) , while break p uses the negation of p.
prefix (possibly empty) of xs of elements that satisfy p. dropWhile p xs
returns the remaining suffix. span p xs is equivalent to
(takeWhile p xs, dropWhile p xs), while break p uses the negation of p. -}
takeWhile' :: (a -> Bool) -> [a] -> [a]
takeWhile' p [] = []
takeWhile' p (x : xs)
| p x = x : takeWhile' p xs
| otherwise' = []
dropWhile' :: (a -> Bool) -> [a] -> [a]
dropWhile' p [] = []
dropWhile' p (x : xs)
| p x = dropWhile' p xs
| otherwise' = x : xs
span', break' :: (a -> Bool) -> [a] -> ([a], [a])
span' p [] = ([], [])
span' p (x : xs)
| p x = let yz = span' p xs
in (x : (fst yz), snd yz)
| otherwise' = ([], x : xs)
| p x = ( x : ys , zs )
where ( ys , zs ) = span
where (ys,zs) = span p xs -}
break' p = span' (not . p)
lines breaks a string up into a list of strings at newline characters .
The resulting strings do not contain newlines . Similary , words
breaks a string up into a list of words , which were delimited by
white space . unlines and unwords are the inverse operations .
unlines joins lines with terminating newlines , and unwords joins
words with separating spaces .
The resulting strings do not contain newlines. Similary, words
breaks a string up into a list of words, which were delimited by
white space. unlines and unwords are the inverse operations.
unlines joins lines with terminating newlines, and unwords joins
words with separating spaces. -}
isSpace ' : : Bool
isSpace ' c = elem ' c " \t\n\r\f\v\xA0 "
isSpace' c = elem' c " \t\n\r\f\v\xA0" -}
lines' :: String -> [String]
lines' s = if s == "" then []
else let ls = break' (== '\n') s
l = fst ls
s' = snd ls
in l : case s' of
[] -> []
(_ : s'') -> lines' s''
words ' : : String - > [ String ]
words ' s = let s ' = dropWhile ' isSpace ' s
in if s ' = = " " then [ ]
else let ws = break ' isSpace ' s '
in ( fst ws ) : words ' ( snd ws )
words' :: String -> [String]
words' s = let s' = dropWhile' isSpace' s
in if s' == "" then []
else let ws = break' isSpace' s'
in (fst ws) : words' (snd ws)
-}
{- unlines' :: [String] -> String
unlines' = concatMap' (++# "\n") -}
unwords ' : : [ String ] - > String
unwords ' [ ] = " "
unwords ' ws = ' ( \w s - > w + + # ( ' ' : s ) ) ws
unwords' :: [String] -> String
unwords' [] = ""
unwords' ws = foldr1' (\w s -> w ++# (' ':s)) ws
-}
-- reverse xs returns the elements of xs in reverse order. xs must be finite.
reverse' :: [a] -> [a]
reverse' = foldl' (flip (:)) []
and returns the conjunction of a Boolean list . For the result to be
True , the list must be finite ; False , however , results from a False
value at a finite index of a finite or infinite list . or is the
disjunctive dual of and .
True, the list must be finite; False, however, results from a False
value at a finite index of a finite or infinite list. or is the
disjunctive dual of and. -}
and', or' :: [Bool] -> Bool
and' = foldr' (&&) True
or' = foldr' (||) False
Applied to a predicate and a list , any determines if any element
of the list satisfies the predicate . Similarly , for all .
of the list satisfies the predicate. Similarly, for all. -}
any', all' :: (a -> Bool) -> [a] -> Bool
any' p = or' . map p
all' p = and' . map p
{- elem is the list membership predicate, usually written in infix form,
e.g., x `elem` xs. notElem is the negation. -}
elem', notElem' :: (Eq a) => a -> [a] -> Bool
elem' x = any' (== x)
notElem' x = all' (/= x)
lookup key assocs looks up a key in an association list .
lookup' :: (Eq a) => a -> [(a, b)] -> Maybe b
lookup' key [] = Nothing
lookup' key (xy : xys)
| key == fst xy = Just (snd xy)
| otherwise' = lookup' key xys
-- sum and product compute the sum or product of a finite list of numbers.
sum', product' :: (Num a) => [a] -> a
sum' = foldl' (+) 0
product' = foldl' (*) 1
{- maximum and minimum return the maximum or minimum value from a list,
which must be non-empty, finite, and of an ordered type. -}
maximum ' , minimum ' : : ( a ) = > [ a ] - > a
maximum ' [ ] = error " Prelude.maximum : empty list "
maximum ' xs = foldl1 ' max xs
minimum ' [ ] = error " Prelude.minimum : empty list "
minimum ' xs = foldl1 ' min xs
maximum', minimum' :: (Ord a) => [a] -> a
maximum' [] = error "Prelude.maximum: empty list"
maximum' xs = foldl1' max xs
minimum' [] = error "Prelude.minimum: empty list"
minimum' xs = foldl1' min xs
-}
zip takes two lists and returns a list of corresponding pairs . If one
input list is short , excess elements of the longer list are discarded .
zip3 takes three lists and returns a list of triples . for larger
tuples are in the List library
input list is short, excess elements of the longer list are discarded.
zip3 takes three lists and returns a list of triples. Zips for larger
tuples are in the List library -}
zip' :: [a] -> [b] -> [(a, b)]
zip' = zipWith' (,)
The zipWith family generalises the zip family by zipping with the
function given as the first argument , instead of a tupling function .
For example , zipWith ( + ) is applied to two lists to produce the list
of corresponding sums .
function given as the first argument, instead of a tupling function.
For example, zipWith (+) is applied to two lists to produce the list
of corresponding sums. -}
zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith' z (a : as) (b : bs)
= z a b : zipWith' z as bs
zipWith' _ _ _ = []
-- unzip transforms a list of pairs into a pair of lists.
unzip' :: [(a, b)] -> ([a], [b])
unzip' = foldr' (\ x xs -> ((fst x) :
(fst xs), (snd x) : (snd xs))) ([], [])
| null | https://raw.githubusercontent.com/spechub/Hets/af7b628a75aab0d510b8ae7f067a5c9bc48d0f9e/Haskell/test/HOLCF/PPrel.hs | haskell | Standard types, classes, instances and related functions
Numeric classes
Minimal complete definition:
quotRem, toInteger
Minimal complete definition:
fromRational and (recip or (/))
Numeric functions
Trivial type
Function type
identity function
constant function
function composition
(.) :: (b -> c) -> (a -> b) -> a -> c
f . g = \ x -> f (g x)
flip' :: (a -> b -> c) -> b -> a -> c
flip' f x y = f y x
seq :: a -> b -> b
seq = ... -- Primitive
right-associating infix application operators
(useful in continuation-passing style)
Boolean type
Boolean functions
primIntToChar = undefined'
primCharToInt = undefined'
primUnicodeMaxChar = undefined'
curry converts an uncurried function to a curried function;
uncurry converts a curried function to a function on pairs.
Misc functions
error stops execution and displays an error message
error' :: String -> a
error' = primError
It is expected that compilers will recognize this and insert error
messages that are more appropriate to the context in which undefined
appears.
Standard list functions
Map and append
map' :: (a -> b) -> [a] -> [b]
map' f [] = []
map' f (x:xs) = f x : map' f xs
length returns the length of a finite list as an Int.
List index (subscript) operator, 0-origin
where qs@(q:_) = scanr f q0 xs
iterate f x returns an infinite list of repeated applications of f to x:
iterate f x == [x, f x, f (f x), ...]
repeat x is an infinite list, with x the value of every element.
replicate n x is a list of length n with x the value of every element
cycle ties a finite list into a circular one, or equivalently,
the infinite repetition of the original list. It is the identity
on infinite lists.
cycle xs = xs' where xs' = xs ++ xs'
unlines' :: [String] -> String
unlines' = concatMap' (++# "\n")
reverse xs returns the elements of xs in reverse order. xs must be finite.
elem is the list membership predicate, usually written in infix form,
e.g., x `elem` xs. notElem is the negation.
sum and product compute the sum or product of a finite list of numbers.
maximum and minimum return the maximum or minimum value from a list,
which must be non-empty, finite, and of an ordered type.
unzip transforms a list of pairs into a pair of lists. |
module PPrel where
class (Num a, Ord a) => RealK a where
toRational' :: a -> Rational
class (RealK a, Enum a) => IntegralK a where
quot', rem' :: a -> a -> a
div', mod' :: a -> a -> a
quotRem', divMod' :: a -> a -> (a, a)
toInteger' :: a -> Integer
n `quot'` d = fst (quotRem' n d)
n `rem'` d = snd (quotRem' n d)
n `div'` d = fst (divMod' n d)
n `mod'` d = snd (divMod' n d)
divMod' n d = let qr = quotRem' n d
q = fst qr
r = snd qr
in if signum r == (0 - signum d) then
(q - 1, r + d) else quotRem' n d
if signum r = = - signum d then ( q-1 , r+d )
else quotRem n d
else quotRem n d -}
class (Num a) => FractionalK a where
(/#) :: a -> a -> a
recip' :: a -> a
fromRational' :: Rational -> a
recip' x = 1 /# x
x /# y = x * recip' y
subtract ' : : ( a ) = > a - > a - > a
subtract ' = flip ' ( - )
subtract' = flip' (-) -}
even', odd' :: (IntegralK a) => a -> Bool
even' n = n `rem'` 2 == 0
odd' = not . even'
gcd' :: (IntegralK a) => a -> a -> a
gcd' 0 0 = error "Prelude.gcd: gcd 0 0 is undefined"
gcd' x y = gcdH (abs x) (abs y)
gcdH :: (IntegralK a) => a -> a -> a
gcdH x 0 = x
gcdH x y = gcdH y (x `rem'` y)
lcm' :: (IntegralK a) => a -> a -> a
lcm' _ 0 = 0
lcm' 0 _ = 0
lcm' x y = abs ((x `quot'` (gcd' x y)) * y)
(^#) :: (Num a, IntegralK b) => a -> b -> a
x ^# 0 = 1
x ^# n | n > 0 = powAux x (n - 1) x
_ ^# _ = error "Prelude.^: negative exponent"
powAux :: (Num a, IntegralK b) => a -> b -> a -> a
powAux _ 0 y = y
powAux x n y = powBux x n y
powBux :: (Num a, IntegralK b) => a -> b -> a -> a
powBux x n y | even' n = powBux (x * x) (n `quot'` 2) y
| otherwise' = powAux x (n - 1) (x * y)
(^^#) :: (FractionalK a, IntegralK b) => a -> b -> a
x ^^# n = if n >= 0 then x ^# n else recip' (x ^# (0 - n))
fromIntegral' :: (IntegralK a, Num b) => a -> b
fromIntegral' = fromInteger . toInteger'
realToFrac' :: (RealK a, FractionalK b) => a -> b
realToFrac' = fromRational' . toRational'
data ( ) = ( ) deriving ( Eq , Ord , , Bounded )
Not legal ; for illustration only
Not legal Haskell; for illustration only -}
id' :: a -> a
id' x = x
const' :: a -> b -> a
const' x _ = x
flip f takes its ( first ) two arguments in the reverse order of f.
( $ ) , ( $ ! ) : : ( a - > b ) - > a - > b
f $ x = f x
f $ ! x = ( f x )
f $ x = f x
f $! x = P.seq x (f x) -}
data Bool = False | True deriving ( P.Eq , P.Ord , P.Enum , P.Bounded )
otherwise' :: Bool
otherwise' = True
maybe' :: b -> (a -> b) -> Maybe a -> b
maybe' n f Nothing = n
maybe' n f (Just x) = f x
either' :: (a -> c) -> (b -> c) -> Either a b -> c
either' f g (Left x) = f x
either' f g (Right y) = g y
curry' :: ((a, b) -> c) -> a -> b -> c
curry' f x y = f (x, y)
uncurry' :: (a -> b -> c) -> ((a, b) -> c)
uncurry' f p = f (fst p) (snd p)
until p f yields the result of applying f until p holds .
until' :: (a -> Bool) -> (a -> a) -> a -> a
until' p f x
| p x = x
| otherwise' = until' p f (f x)
asTypeOf is a type - restricted version of const . It is usually used
as an infix operator , and its typing forces its first argument
( which is usually overloaded ) to have the same type as the second .
as an infix operator, and its typing forces its first argument
(which is usually overloaded) to have the same type as the second. -}
asTypeOf' :: a -> a -> a
asTypeOf' = const'
undefined' :: a
undefined' = error "Prelude.undefined"
head' :: [a] -> a
head' (x : _) = x
head' [] = error "Prelude.head: empty list"
tail' :: [a] -> [a]
tail' (_ : xs) = xs
tail' [] = error "Prelude.tail: empty list"
(++#) :: [a] -> [a] -> [a]
[] ++# ys = ys
(x : xs) ++# ys = x : (xs ++# ys)
filter' :: (a -> Bool) -> [a] -> [a]
filter' p [] = []
filter' p (x : xs) | p x = x : filter' p xs
| otherwise' = filter' p xs
concat' :: [[a]] -> [a]
concat' xss = foldr' (++#) [] xss
concatMap' :: (a -> [b]) -> [a] -> [b]
concatMap' f = concat' . map f
head and tail extract the first element and remaining elements ,
respectively , of a list , which must be non - empty . last and init
are the dual functions working from the end of a finite list ,
rather than the beginning .
respectively, of a list, which must be non-empty. last and init
are the dual functions working from the end of a finite list,
rather than the beginning. -}
last' :: [a] -> a
last' [x] = x
last' (_ : xs) = last' xs
last' [] = error "Prelude.last: empty list"
init' :: [a] -> [a]
init' [x] = []
init' (x : xs) = x : init' xs
init' [] = error "Prelude.init: empty list"
null' :: [a] -> Bool
null' [] = True
null' (_ : _) = False
length' :: [a] -> Int
length' [] = 0
length' (_ : l) = 1 + length' l
(!!#) :: [a] -> Int -> a
xs !!# n | n < 0 = error "Prelude.!!: negative index"
[] !!# _ = error "Prelude.!!: index too large"
(x : _) !!# 0 = x
(_ : xs) !!# n = xs !!# (n - 1)
foldl , applied to a binary operator , a starting value ( typically the
left - identity of the operator ) , and a list , reduces the list using
the binary operator , from left to right :
foldl f z [ x1 , x2 , ... , xn ] = = ( ... ( ( z ` f ` x1 ) ` f ` x2 ) ` f ` ... ) ` f ` xn
foldl1 is a variant that has no starting value argument , and thus must
be applied to non - empty lists . is similar to foldl , but returns
a list of successive reduced values from the left :
f z [ x1 , x2 , ... ] = = [ z , z ` f ` x1 , ( z ` f ` x1 ) ` f ` x2 , ... ]
Note that last ( f z xs ) = = foldl f z xs .
scanl1 is similar , again without the starting element :
f [ x1 , x2 , ... ] = = [ x1 , x1 ` f ` x2 , ... ]
left-identity of the operator), and a list, reduces the list using
the binary operator, from left to right:
foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn
foldl1 is a variant that has no starting value argument, and thus must
be applied to non-empty lists. scanl is similar to foldl, but returns
a list of successive reduced values from the left:
scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
Note that last (scanl f z xs) == foldl f z xs.
scanl1 is similar, again without the starting element:
scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...] -}
foldl' :: (a -> b -> a) -> a -> [b] -> a
foldl' f z [] = z
foldl' f z (x : xs) = foldl' f (f z x) xs
foldl1' :: (a -> a -> a) -> [a] -> a
foldl1' f (x : xs) = foldl' f x xs
foldl1' _ [] = error "Prelude.foldl1: empty list"
scanl' :: (a -> b -> a) -> a -> [b] -> [a]
scanl' f q xs = q : (case xs of
[] -> []
x : xs -> scanl' f (f q x) xs)
scanl1' :: (a -> a -> a) -> [a] -> [a]
scanl1' f (x : xs) = scanl' f x xs
scanl1' _ [] = []
foldr , foldr1 , , and scanr1 are the right - to - left duals of the
above functions .
above functions. -}
foldr' :: (a -> b -> b) -> b -> [a] -> b
foldr' f z [] = z
foldr' f z (x : xs) = f x (foldr' f z xs)
foldr1' :: (a -> a -> a) -> [a] -> a
foldr1' f [x] = x
foldr1' f (x : xs) = f x (foldr1' f xs)
foldr1' _ [] = error "Prelude.foldr1: empty list"
scanr' :: (a -> b -> b) -> b -> [a] -> [b]
scanr' f q0 [] = [q0]
scanr' f q0 (x : xs) = let qs = scanr' f q0 xs
in f x (head' qs) : qs
scanr1' :: (a -> a -> a) -> [a] -> [a]
scanr1' f [] = []
scanr1' f [x] = [x]
scanr1' f (x : xs) = let qs = scanr1' f xs
in f x (head' qs) : qs
iterate' :: (a -> a) -> a -> [a]
iterate' f x = x : iterate' f (f x)
repeat' :: a -> [a]
repeat' x = x : (repeat' x)
replicate' :: Int -> a -> [a]
replicate' n x = take' n (repeat' x)
cycle' :: [a] -> [a]
cycle' [] = error "Prelude.cycle: empty list"
cycle' xs = xs ++# cycle' xs
take n , applied to a list xs , returns the prefix of xs of length n ,
or xs itself if n > length xs . drop n xs returns the suffix of xs
after the first n elements , or [ ] if n > length xs . splitAt n xs
is equivalent to ( take n xs , drop n xs ) .
or xs itself if n > length xs. drop n xs returns the suffix of xs
after the first n elements, or [] if n > length xs. splitAt n xs
is equivalent to (take n xs, drop n xs). -}
take' :: Int -> [a] -> [a]
take' n _ | n <= 0 = []
take' _ [] = []
take' n (x : xs) = x : take' (n - 1) xs
drop' :: Int -> [a] -> [a]
drop' n xs | n <= 0 = xs
drop' _ [] = []
drop' n (_ : xs) = drop' (n - 1) xs
splitAt' :: Int -> [a] -> ([a], [a])
splitAt' n xs = (take' n xs, drop' n xs)
takeWhile , applied to a predicate p and a list xs , returns the longest
prefix ( possibly empty ) of xs of elements that satisfy p. dropWhile p xs
returns the remaining suffix . span is equivalent to
( takeWhile p xs , dropWhile p xs ) , while break p uses the negation of p.
prefix (possibly empty) of xs of elements that satisfy p. dropWhile p xs
returns the remaining suffix. span p xs is equivalent to
(takeWhile p xs, dropWhile p xs), while break p uses the negation of p. -}
takeWhile' :: (a -> Bool) -> [a] -> [a]
takeWhile' p [] = []
takeWhile' p (x : xs)
| p x = x : takeWhile' p xs
| otherwise' = []
dropWhile' :: (a -> Bool) -> [a] -> [a]
dropWhile' p [] = []
dropWhile' p (x : xs)
| p x = dropWhile' p xs
| otherwise' = x : xs
span', break' :: (a -> Bool) -> [a] -> ([a], [a])
span' p [] = ([], [])
span' p (x : xs)
| p x = let yz = span' p xs
in (x : (fst yz), snd yz)
| otherwise' = ([], x : xs)
| p x = ( x : ys , zs )
where ( ys , zs ) = span
where (ys,zs) = span p xs -}
break' p = span' (not . p)
lines breaks a string up into a list of strings at newline characters .
The resulting strings do not contain newlines . Similary , words
breaks a string up into a list of words , which were delimited by
white space . unlines and unwords are the inverse operations .
unlines joins lines with terminating newlines , and unwords joins
words with separating spaces .
The resulting strings do not contain newlines. Similary, words
breaks a string up into a list of words, which were delimited by
white space. unlines and unwords are the inverse operations.
unlines joins lines with terminating newlines, and unwords joins
words with separating spaces. -}
isSpace ' : : Bool
isSpace ' c = elem ' c " \t\n\r\f\v\xA0 "
isSpace' c = elem' c " \t\n\r\f\v\xA0" -}
lines' :: String -> [String]
lines' s = if s == "" then []
else let ls = break' (== '\n') s
l = fst ls
s' = snd ls
in l : case s' of
[] -> []
(_ : s'') -> lines' s''
words ' : : String - > [ String ]
words ' s = let s ' = dropWhile ' isSpace ' s
in if s ' = = " " then [ ]
else let ws = break ' isSpace ' s '
in ( fst ws ) : words ' ( snd ws )
words' :: String -> [String]
words' s = let s' = dropWhile' isSpace' s
in if s' == "" then []
else let ws = break' isSpace' s'
in (fst ws) : words' (snd ws)
-}
unwords ' : : [ String ] - > String
unwords ' [ ] = " "
unwords ' ws = ' ( \w s - > w + + # ( ' ' : s ) ) ws
unwords' :: [String] -> String
unwords' [] = ""
unwords' ws = foldr1' (\w s -> w ++# (' ':s)) ws
-}
reverse' :: [a] -> [a]
reverse' = foldl' (flip (:)) []
and returns the conjunction of a Boolean list . For the result to be
True , the list must be finite ; False , however , results from a False
value at a finite index of a finite or infinite list . or is the
disjunctive dual of and .
True, the list must be finite; False, however, results from a False
value at a finite index of a finite or infinite list. or is the
disjunctive dual of and. -}
and', or' :: [Bool] -> Bool
and' = foldr' (&&) True
or' = foldr' (||) False
Applied to a predicate and a list , any determines if any element
of the list satisfies the predicate . Similarly , for all .
of the list satisfies the predicate. Similarly, for all. -}
any', all' :: (a -> Bool) -> [a] -> Bool
any' p = or' . map p
all' p = and' . map p
elem', notElem' :: (Eq a) => a -> [a] -> Bool
elem' x = any' (== x)
notElem' x = all' (/= x)
lookup key assocs looks up a key in an association list .
lookup' :: (Eq a) => a -> [(a, b)] -> Maybe b
lookup' key [] = Nothing
lookup' key (xy : xys)
| key == fst xy = Just (snd xy)
| otherwise' = lookup' key xys
sum', product' :: (Num a) => [a] -> a
sum' = foldl' (+) 0
product' = foldl' (*) 1
maximum ' , minimum ' : : ( a ) = > [ a ] - > a
maximum ' [ ] = error " Prelude.maximum : empty list "
maximum ' xs = foldl1 ' max xs
minimum ' [ ] = error " Prelude.minimum : empty list "
minimum ' xs = foldl1 ' min xs
maximum', minimum' :: (Ord a) => [a] -> a
maximum' [] = error "Prelude.maximum: empty list"
maximum' xs = foldl1' max xs
minimum' [] = error "Prelude.minimum: empty list"
minimum' xs = foldl1' min xs
-}
zip takes two lists and returns a list of corresponding pairs . If one
input list is short , excess elements of the longer list are discarded .
zip3 takes three lists and returns a list of triples . for larger
tuples are in the List library
input list is short, excess elements of the longer list are discarded.
zip3 takes three lists and returns a list of triples. Zips for larger
tuples are in the List library -}
zip' :: [a] -> [b] -> [(a, b)]
zip' = zipWith' (,)
The zipWith family generalises the zip family by zipping with the
function given as the first argument , instead of a tupling function .
For example , zipWith ( + ) is applied to two lists to produce the list
of corresponding sums .
function given as the first argument, instead of a tupling function.
For example, zipWith (+) is applied to two lists to produce the list
of corresponding sums. -}
zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith' z (a : as) (b : bs)
= z a b : zipWith' z as bs
zipWith' _ _ _ = []
unzip' :: [(a, b)] -> ([a], [b])
unzip' = foldr' (\ x xs -> ((fst x) :
(fst xs), (snd x) : (snd xs))) ([], [])
|
d4be28cb94930d74cf81ce8dda0b20890ffb06d52a6c99a6b3e191706609f0dd | fluree/db | async.cljc | (ns fluree.db.util.async
(:require
[fluree.db.util.core :as util]
[fluree.db.util.log :as log]
[fluree.db.util.core #?(:clj :refer :cljs :refer-macros) [try* catch*]]
[clojure.core.async :refer [go <!] :as async]
[clojure.core.async.impl.protocols :as async-protocols])
#?(:cljs (:require-macros [fluree.db.util.async :refer [<? go-try]])))
#?(:clj (set! *warn-on-reflection* true))
;; some macros for working with core async
#?(:clj
(defn cljs-env?
"Take the &env from a macro, and tell whether we are expanding into cljs."
[env]
(boolean (:ns env))))
#?(:clj
(defmacro if-cljs
"Return then if we are generating cljs code and else for Clojure code.
"
[then else]
(if (cljs-env? &env) then else)))
(defn throw-err [e]
(when (util/exception? e)
(throw e))
e)
#?(:clj
(defmacro <?
"Like <! but throws errors."
[ch]
`(if-cljs
(throw-err (cljs.core.async/<! ~ch))
(throw-err (clojure.core.async/<! ~ch)))))
#?(:clj
(defmacro <??
"Like <!! but throws errors. Only works for Java platform - no JavaScript."
[ch]
`(throw-err (clojure.core.async/<!! ~ch))))
#?(:clj
(defmacro alts??
"Like alts!! but throws errors. Only works for Java platform - no JavaScript."
[ports & opts]
`(let [[result# ch#] (clojure.core.async/alts!! ~ports ~@opts)]
[(throw-err result#) ch#])))
#?(:clj
(defmacro go-try
"Like go but catches the first thrown error and puts it on the returned channel."
[& body]
`(if-cljs
(cljs.core.async/go
(try
~@body
(catch js/Error e# e#)))
(clojure.core.async/go
(try
~@body
(catch Throwable t# t#))))))
(defn throw-if-exception
"Helper method that checks if x is Exception and if yes, wraps it in a new
exception, passing though ex-data if any, and throws it. The wrapping is done
to maintain a full stack trace when jumping between multiple contexts."
[x]
(if (instance? #?(:clj Throwable :cljs js/Error) x)
(throw (ex-info #?(:clj (or (.getMessage ^Throwable x) (str x))
:cljs (str x))
(or (ex-data x) {})
x))
x))
(defn merge-into?
"Takes a sequence of single-value chans and returns the conjoined into collection.
Realizes entire channel sequence first, and if an error value exists returns just the exception."
[coll chs]
(async/go
(try*
(loop [[c & r] chs
acc coll]
(if-not c
acc
(recur r (conj acc (<? c)))))
(catch* e
e))))
(defn into?
"Like async/into, but checks each item for an error response and returns exception
onto the response channel instead of results if there is one."
[coll chan]
(async/go
(try*
(loop [acc coll]
(if-some [v (<? chan)]
(recur (conj acc v))
acc))
(catch* e
e))))
(defn channel?
"Returns true if core async channel."
[x]
(satisfies? async-protocols/Channel x))
| null | https://raw.githubusercontent.com/fluree/db/9e9718b11e954c47621ea2c4651105f6d0765535/src/fluree/db/util/async.cljc | clojure | some macros for working with core async | (ns fluree.db.util.async
(:require
[fluree.db.util.core :as util]
[fluree.db.util.log :as log]
[fluree.db.util.core #?(:clj :refer :cljs :refer-macros) [try* catch*]]
[clojure.core.async :refer [go <!] :as async]
[clojure.core.async.impl.protocols :as async-protocols])
#?(:cljs (:require-macros [fluree.db.util.async :refer [<? go-try]])))
#?(:clj (set! *warn-on-reflection* true))
#?(:clj
(defn cljs-env?
"Take the &env from a macro, and tell whether we are expanding into cljs."
[env]
(boolean (:ns env))))
#?(:clj
(defmacro if-cljs
"Return then if we are generating cljs code and else for Clojure code.
"
[then else]
(if (cljs-env? &env) then else)))
(defn throw-err [e]
(when (util/exception? e)
(throw e))
e)
#?(:clj
(defmacro <?
"Like <! but throws errors."
[ch]
`(if-cljs
(throw-err (cljs.core.async/<! ~ch))
(throw-err (clojure.core.async/<! ~ch)))))
#?(:clj
(defmacro <??
"Like <!! but throws errors. Only works for Java platform - no JavaScript."
[ch]
`(throw-err (clojure.core.async/<!! ~ch))))
#?(:clj
(defmacro alts??
"Like alts!! but throws errors. Only works for Java platform - no JavaScript."
[ports & opts]
`(let [[result# ch#] (clojure.core.async/alts!! ~ports ~@opts)]
[(throw-err result#) ch#])))
#?(:clj
(defmacro go-try
"Like go but catches the first thrown error and puts it on the returned channel."
[& body]
`(if-cljs
(cljs.core.async/go
(try
~@body
(catch js/Error e# e#)))
(clojure.core.async/go
(try
~@body
(catch Throwable t# t#))))))
(defn throw-if-exception
"Helper method that checks if x is Exception and if yes, wraps it in a new
exception, passing though ex-data if any, and throws it. The wrapping is done
to maintain a full stack trace when jumping between multiple contexts."
[x]
(if (instance? #?(:clj Throwable :cljs js/Error) x)
(throw (ex-info #?(:clj (or (.getMessage ^Throwable x) (str x))
:cljs (str x))
(or (ex-data x) {})
x))
x))
(defn merge-into?
"Takes a sequence of single-value chans and returns the conjoined into collection.
Realizes entire channel sequence first, and if an error value exists returns just the exception."
[coll chs]
(async/go
(try*
(loop [[c & r] chs
acc coll]
(if-not c
acc
(recur r (conj acc (<? c)))))
(catch* e
e))))
(defn into?
"Like async/into, but checks each item for an error response and returns exception
onto the response channel instead of results if there is one."
[coll chan]
(async/go
(try*
(loop [acc coll]
(if-some [v (<? chan)]
(recur (conj acc v))
acc))
(catch* e
e))))
(defn channel?
"Returns true if core async channel."
[x]
(satisfies? async-protocols/Channel x))
|