_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
8bd7d78b319ce15b78b0ce527f4eaf8e96f2f0513471fa769c8872ba07a6f926
jcclinton/wow-emulator
player_rcv.erl
This is a World of Warcraft emulator written in erlang , supporting client 1.12.x %% Copyright ( C ) 2014 < jamieclinton.com > %% %% This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or %% (at your option) any later version. %% %% This program is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %% GNU General Public License for more details. %% You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . %% %% World of Warcraft, and all World of Warcraft or Warcraft art, images, and lore ande copyrighted by Blizzard Entertainment , Inc. -module(player_rcv). -export([start_link/2, init/1, rcv/1]). -export([upgrade/0]). -include("include/binary.hrl"). -include("include/network_defines.hrl"). -include("include/data_types.hrl"). -record(state, { socket, key_state, account_id }). start_link(ListenSocket, ParentPid) -> Pid = spawn_link(?MODULE, init, [{ListenSocket, ParentPid}]), {ok, Pid}. init({ListenSocket, ParentPid}) -> io:format("player starting rcv~n"), {ok, Socket} = gen_tcp:accept(ListenSocket), %% start another acceptor players_sup:start_socket(), Seed = random:uniform(16#FFFFFFFF), Payload = <<Seed?L>>, ChallengeOpcode = opcodes:get_num_by_atom(smsg_auth_challenge), network:send_packet(ChallengeOpcode, Payload, ?SEND_HDR_LEN, _KeyState=nil, Socket, _ShouldEncrypt=false), try network:receive_packet(?RCV_HDR_LEN, _KeyState=nil, Socket, _ShouldDecrypt=false) of {Opcode, PayloadIn, _} -> {PayloadOut, AccountId, KeyState} = auth_session(PayloadIn), %% now authorized start_siblings(Socket, KeyState, AccountId, ParentPid), player_controller:packet_received(AccountId, Opcode, PayloadOut), rcv(#state{key_state=KeyState, account_id=AccountId, socket=Socket}) catch Error -> {error, Error} end. rcv(State = #state{socket=Socket, key_state=KeyState, account_id=AccountId}) -> try network:receive_packet(?RCV_HDR_LEN, KeyState, Socket, _ShouldDecrypt=true) of {Opcode, Payload, NewKeyState} -> io : format("rcv : received payload ~p ~ n " , [ Rest ] ) , player_controller:packet_received(AccountId, Opcode, Payload), rcv(State#state{key_state=NewKeyState}) catch Error -> {error, Error} end. upgrade() -> ok. %% private -spec auth_session(binary()) -> {binary(), binary(), key_state()}. auth_session(Rest) -> AccountId = cmsg_auth_session(Rest), Response = smsg_auth_response(), Key = world_crypto:encryption_key(AccountId), KeyState = world_crypto:create_key_state(Key), {Response, AccountId, KeyState}. -spec cmsg_auth_session(binary()) -> binary(). cmsg_auth_session(<<_Build?L, _Unk?L, Rest/binary>>) -> {Account, _Key} = cmsg_auth_session_extract(Rest, <<>>), Account; cmsg_auth_session(_) -> {error, bad_cmsg_auth_session}. -spec cmsg_auth_session_extract(binary(), binary()) -> {binary(), binary()}. cmsg_auth_session_extract(<<0?B, Rest/binary>>, AccountId) -> {AccountId, Rest}; cmsg_auth_session_extract(<<Letter?B, Rest/binary>>, AccountId) -> cmsg_auth_session_extract(Rest, <<AccountId/binary, Letter?B>>). -spec smsg_auth_response() -> binary(). smsg_auth_response() -> <<16#0c?B, 0?L, 0?B, 0?L>>. -spec start_siblings(term(), key_state(), binary(), pid()) -> 'ok'. start_siblings(Socket, KeyState, AccountId, ParentPid) -> SendPid = start_child(player_send, [Socket, KeyState], ParentPid, worker), _ = start_child(player_controller_sup, [AccountId, SendPid], ParentPid, supervisor), _ = start_child(player_workers_sup, [AccountId], ParentPid, supervisor), _ = start_child(player_model_sup, [AccountId], ParentPid, supervisor), ok. -type proc_type() :: worker | supervisor. -spec start_child(atom(), [any()], pid(), proc_type()) -> pid(). start_child(Name, Args, ParentPid, Type) -> Spec = {Name, {Name, start_link, Args}, permanent, 2000, Type, [Name]}, {ok, Pid} = supervisor:start_child(ParentPid, Spec), Pid.
null
https://raw.githubusercontent.com/jcclinton/wow-emulator/21bc67bfc9eea131c447c67f7f889ba040dcdd79/src/player_rcv.erl
erlang
This program is free software; you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. World of Warcraft, and all World of Warcraft or Warcraft art, images, start another acceptor now authorized private
This is a World of Warcraft emulator written in erlang , supporting client 1.12.x Copyright ( C ) 2014 < jamieclinton.com > it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . and lore ande copyrighted by Blizzard Entertainment , Inc. -module(player_rcv). -export([start_link/2, init/1, rcv/1]). -export([upgrade/0]). -include("include/binary.hrl"). -include("include/network_defines.hrl"). -include("include/data_types.hrl"). -record(state, { socket, key_state, account_id }). start_link(ListenSocket, ParentPid) -> Pid = spawn_link(?MODULE, init, [{ListenSocket, ParentPid}]), {ok, Pid}. init({ListenSocket, ParentPid}) -> io:format("player starting rcv~n"), {ok, Socket} = gen_tcp:accept(ListenSocket), players_sup:start_socket(), Seed = random:uniform(16#FFFFFFFF), Payload = <<Seed?L>>, ChallengeOpcode = opcodes:get_num_by_atom(smsg_auth_challenge), network:send_packet(ChallengeOpcode, Payload, ?SEND_HDR_LEN, _KeyState=nil, Socket, _ShouldEncrypt=false), try network:receive_packet(?RCV_HDR_LEN, _KeyState=nil, Socket, _ShouldDecrypt=false) of {Opcode, PayloadIn, _} -> {PayloadOut, AccountId, KeyState} = auth_session(PayloadIn), start_siblings(Socket, KeyState, AccountId, ParentPid), player_controller:packet_received(AccountId, Opcode, PayloadOut), rcv(#state{key_state=KeyState, account_id=AccountId, socket=Socket}) catch Error -> {error, Error} end. rcv(State = #state{socket=Socket, key_state=KeyState, account_id=AccountId}) -> try network:receive_packet(?RCV_HDR_LEN, KeyState, Socket, _ShouldDecrypt=true) of {Opcode, Payload, NewKeyState} -> io : format("rcv : received payload ~p ~ n " , [ Rest ] ) , player_controller:packet_received(AccountId, Opcode, Payload), rcv(State#state{key_state=NewKeyState}) catch Error -> {error, Error} end. upgrade() -> ok. -spec auth_session(binary()) -> {binary(), binary(), key_state()}. auth_session(Rest) -> AccountId = cmsg_auth_session(Rest), Response = smsg_auth_response(), Key = world_crypto:encryption_key(AccountId), KeyState = world_crypto:create_key_state(Key), {Response, AccountId, KeyState}. -spec cmsg_auth_session(binary()) -> binary(). cmsg_auth_session(<<_Build?L, _Unk?L, Rest/binary>>) -> {Account, _Key} = cmsg_auth_session_extract(Rest, <<>>), Account; cmsg_auth_session(_) -> {error, bad_cmsg_auth_session}. -spec cmsg_auth_session_extract(binary(), binary()) -> {binary(), binary()}. cmsg_auth_session_extract(<<0?B, Rest/binary>>, AccountId) -> {AccountId, Rest}; cmsg_auth_session_extract(<<Letter?B, Rest/binary>>, AccountId) -> cmsg_auth_session_extract(Rest, <<AccountId/binary, Letter?B>>). -spec smsg_auth_response() -> binary(). smsg_auth_response() -> <<16#0c?B, 0?L, 0?B, 0?L>>. -spec start_siblings(term(), key_state(), binary(), pid()) -> 'ok'. start_siblings(Socket, KeyState, AccountId, ParentPid) -> SendPid = start_child(player_send, [Socket, KeyState], ParentPid, worker), _ = start_child(player_controller_sup, [AccountId, SendPid], ParentPid, supervisor), _ = start_child(player_workers_sup, [AccountId], ParentPid, supervisor), _ = start_child(player_model_sup, [AccountId], ParentPid, supervisor), ok. -type proc_type() :: worker | supervisor. -spec start_child(atom(), [any()], pid(), proc_type()) -> pid(). start_child(Name, Args, ParentPid, Type) -> Spec = {Name, {Name, start_link, Args}, permanent, 2000, Type, [Name]}, {ok, Pid} = supervisor:start_child(ParentPid, Spec), Pid.
ac215c26ae0f084e67ca8d469df00dd324d4a7d59ab44793cdd757605d6ef9f5
robert-strandh/SICL
setf-generic-function-name.lisp
(cl:in-package #:sicl-clos) ;;; For the specification of this generic function, see ;;; -MOP/setf-generic-function-name.html (defgeneric (setf generic-function-name) (new-name generic-function)) (defmethod (setf generic-function-name) (new-name (generic-function generic-function)) (reinitialize-instance generic-function :name new-name))
null
https://raw.githubusercontent.com/robert-strandh/SICL/1c93380897fe3c7b7b1ae14d5771971759d065fd/Code/CLOS/setf-generic-function-name.lisp
lisp
For the specification of this generic function, see -MOP/setf-generic-function-name.html
(cl:in-package #:sicl-clos) (defgeneric (setf generic-function-name) (new-name generic-function)) (defmethod (setf generic-function-name) (new-name (generic-function generic-function)) (reinitialize-instance generic-function :name new-name))
e139f088bc5bfdc0a07b02d428e6e2f51e402110b12e9528cc11e35a76fddb31
GlideAngle/flare-timing
Path.hs
# OPTIONS_GHC -fno - warn - partial - type - signatures # module Flight.Zone.Path (costSegment, distancePointToPoint) where import Prelude hiding (sum, span) import Data.List (foldl') import Data.UnitsOfMeasure ((+:), (-:), u, abs', zero) import Data.UnitsOfMeasure.Internal (Quantity(..)) import Flight.LatLng (LatLng(..)) import Flight.Zone (Zone(..), Radius(..), center) import Flight.Distance (QTaskDistance, TaskDistance(..), PathDistance(..), SpanLatLng) costSegment :: Real a => SpanLatLng a -> Zone a -> Zone a -> PathDistance a costSegment span x y = distancePointToPoint span [x, y] -- | One way of measuring task distance is going point-to-point through each -- control zone's center along the course from start to goal. This is not used by but sometimes task distance will be reported this way . -- -- The speed section usually goes from start exit cylinder to goal cylinder or -- to goal line. The optimal way to fly this in a zig-zagging course will avoid -- zone centers for a shorter flown distance. distancePointToPoint :: Real a => SpanLatLng a -> [Zone a] -> PathDistance a distancePointToPoint span xs = PathDistance { edgesSum = distanceViaCenters span xs , vertices = center <$> xs } # INLINABLE distancePointToPoint # distanceViaCenters :: Real a => SpanLatLng a -> [Zone a] -> QTaskDistance a [u| m |] distanceViaCenters _ [] = TaskDistance [u| 0 m |] distanceViaCenters _ [_] = TaskDistance [u| 0 m |] distanceViaCenters span [Cylinder (Radius xR) x, Cylinder (Radius yR) y] | x == y && xR /= yR = TaskDistance dR | otherwise = distanceViaCenters span ([Point x, Point y] :: [Zone _]) where dR :: Quantity _ [u| m |] dR = abs' $ xR -: yR distanceViaCenters span xs@[a, b] | a == b = TaskDistance zero | otherwise = distance span xs distanceViaCenters span xs = distance span xs sum :: Num a => [Quantity a [u| m |]] -> Quantity a [u| m |] sum = foldl' (+:) zero distance :: Num a => SpanLatLng a -> [Zone a] -> QTaskDistance a [u| m |] distance span xs = TaskDistance $ sum $ zipWith f ys (tail ys) where ys = center <$> xs unwrap (TaskDistance x) = x f :: LatLng _ [u| rad |] -> LatLng _ [u| rad |] -> Quantity _ [u| m |] f = (unwrap .) . span
null
https://raw.githubusercontent.com/GlideAngle/flare-timing/27bd34c1943496987382091441a1c2516c169263/lang-haskell/zone/library/Flight/Zone/Path.hs
haskell
| One way of measuring task distance is going point-to-point through each control zone's center along the course from start to goal. This is not used The speed section usually goes from start exit cylinder to goal cylinder or to goal line. The optimal way to fly this in a zig-zagging course will avoid zone centers for a shorter flown distance.
# OPTIONS_GHC -fno - warn - partial - type - signatures # module Flight.Zone.Path (costSegment, distancePointToPoint) where import Prelude hiding (sum, span) import Data.List (foldl') import Data.UnitsOfMeasure ((+:), (-:), u, abs', zero) import Data.UnitsOfMeasure.Internal (Quantity(..)) import Flight.LatLng (LatLng(..)) import Flight.Zone (Zone(..), Radius(..), center) import Flight.Distance (QTaskDistance, TaskDistance(..), PathDistance(..), SpanLatLng) costSegment :: Real a => SpanLatLng a -> Zone a -> Zone a -> PathDistance a costSegment span x y = distancePointToPoint span [x, y] by but sometimes task distance will be reported this way . distancePointToPoint :: Real a => SpanLatLng a -> [Zone a] -> PathDistance a distancePointToPoint span xs = PathDistance { edgesSum = distanceViaCenters span xs , vertices = center <$> xs } # INLINABLE distancePointToPoint # distanceViaCenters :: Real a => SpanLatLng a -> [Zone a] -> QTaskDistance a [u| m |] distanceViaCenters _ [] = TaskDistance [u| 0 m |] distanceViaCenters _ [_] = TaskDistance [u| 0 m |] distanceViaCenters span [Cylinder (Radius xR) x, Cylinder (Radius yR) y] | x == y && xR /= yR = TaskDistance dR | otherwise = distanceViaCenters span ([Point x, Point y] :: [Zone _]) where dR :: Quantity _ [u| m |] dR = abs' $ xR -: yR distanceViaCenters span xs@[a, b] | a == b = TaskDistance zero | otherwise = distance span xs distanceViaCenters span xs = distance span xs sum :: Num a => [Quantity a [u| m |]] -> Quantity a [u| m |] sum = foldl' (+:) zero distance :: Num a => SpanLatLng a -> [Zone a] -> QTaskDistance a [u| m |] distance span xs = TaskDistance $ sum $ zipWith f ys (tail ys) where ys = center <$> xs unwrap (TaskDistance x) = x f :: LatLng _ [u| rad |] -> LatLng _ [u| rad |] -> Quantity _ [u| m |] f = (unwrap .) . span
328bcf9d9f942e011f3218dab7a26172023d367ce9c532378b94241dece11631
Vaguery/klapaucius
core_test.clj
(ns push.core-test (:require [push.interpreter.core :as i] [push.core :as p]) (:use midje.sweet)) (fact "I can produce a generic interpreter" (class (p/interpreter)) => push.interpreter.definitions.Interpreter ) (fact "I can set input values" (keys (:bindings (p/interpreter :bindings [7 2 3]))) => '(:input!1 :input!2 :input!3) (:bindings (p/interpreter :bindings {:a 8 :b false})) => {:a '(8), :b '(false)}) (fact "I can set a program" (:program (p/interpreter :program [1 2 3])) => [1 2 3]) (fact "when I invoke push.core/interpreter with a :stacks argument, the indicated items are present on the result" (:stacks (p/interpreter :stacks {:foo '(1 2 3)})) => (contains {:foo '(1 2 3)})) (fact "I can use merge-stacks to merge new values onto an interpreter" (:stacks (p/merge-stacks (p/interpreter) {:foo '(1 2 3)})) => (contains {:foo '(1 2 3)})) (fact "I can produce a list of instructions from an interpreter" (p/known-instructions (p/interpreter)) => (contains [:scalar-add :boolean-or :code-dup :exec-flipstack] :in-any-order :gaps-ok)) (fact "I can produce a list of input names (keywords) from an interpreter" (p/binding-names (p/interpreter :bindings {:a 2 :b 7})) => [:a :b] ) (fact "I can produce a list of types and modules loaded into the interpreter" (p/types-and-modules (p/interpreter)) => (contains [:introspection :print :snapshot :code :error :log :exec :set :vector :strings :chars :booleans :string :char :boolean :scalar :scalars] :in-any-order :gaps-ok)) (fact "I can produce the router list for an interpreter" (p/routing-list (p/interpreter)) => (contains [:ref :refs :boolean :char :complex :complexes :snapshot :generator :quoted :string :booleans :chars :strings :tagspace :scalars :vector :set :scalar] :in-any-order :gaps-ok)) (fact "I can run a Push program and get a named stack" (p/get-stack (p/run (p/interpreter) [88 99 :scalar-add] 100) :scalar) => '(187)) (fact "I can re-run an interpreter with bound inputs, replacing the input values" (let [a-99 (p/interpreter :bindings {:a 99})] (p/get-stack (p/run a-99 [:a 99 :scalar-add] 100) :scalar) => '(198) (p/get-stack (p/run a-99 [:a 99 :scalar-add] 100 :bindings {:a -99}) :scalar) => '(0) (p/get-stack (p/run a-99 [:a 99 :scalar-add :b] 100 :bindings {:b -99}) :scalar) => '(-99 198))) (fact "I can turn off individual instructions with the forget-instructions function" (keys (:instructions (p/forget-instructions (p/interpreter) [:scalar-add]))) =not=> (contains :scalar-add) (keys (:instructions (p/interpreter))) => (contains :scalar-add)) (fact "I can turn off multiple instructions with the forget-instructions function" (count (keys (:instructions (p/forget-instructions (p/interpreter) [:scalar-add :scalar-subtract])))) => (- (count (keys (:instructions (p/interpreter)))) 2)) (fact "I can turn off unknown instructions with no trouble" (keys (:instructions (p/forget-instructions (p/interpreter) [:foo-bar :baz-quux]))) => (keys (:instructions (p/interpreter)))) ;; a fixture (def foo-pop (push.instructions.core/build-instruction foo-pop (push.instructions.dsl/consume-top-of :foo :as :gone))) (fact "about :foo-pop" (:token foo-pop) => :foo-pop (:needs foo-pop) => {:foo 1}) (fact "I can add a new instruction with register-instructions" (keys (:instructions (p/register-instructions (p/interpreter) [foo-pop]))) => (contains :foo-pop)) (fact "I can overwrite an old instruction with register-instructions" (:docstring (:scalar-add (:instructions (p/register-instructions (p/interpreter) [(assoc foo-pop :token :scalar-add)])))) => (:docstring foo-pop))
null
https://raw.githubusercontent.com/Vaguery/klapaucius/17b55eb76feaa520a85d4df93597cccffe6bdba4/test/push/core_test.clj
clojure
a fixture
(ns push.core-test (:require [push.interpreter.core :as i] [push.core :as p]) (:use midje.sweet)) (fact "I can produce a generic interpreter" (class (p/interpreter)) => push.interpreter.definitions.Interpreter ) (fact "I can set input values" (keys (:bindings (p/interpreter :bindings [7 2 3]))) => '(:input!1 :input!2 :input!3) (:bindings (p/interpreter :bindings {:a 8 :b false})) => {:a '(8), :b '(false)}) (fact "I can set a program" (:program (p/interpreter :program [1 2 3])) => [1 2 3]) (fact "when I invoke push.core/interpreter with a :stacks argument, the indicated items are present on the result" (:stacks (p/interpreter :stacks {:foo '(1 2 3)})) => (contains {:foo '(1 2 3)})) (fact "I can use merge-stacks to merge new values onto an interpreter" (:stacks (p/merge-stacks (p/interpreter) {:foo '(1 2 3)})) => (contains {:foo '(1 2 3)})) (fact "I can produce a list of instructions from an interpreter" (p/known-instructions (p/interpreter)) => (contains [:scalar-add :boolean-or :code-dup :exec-flipstack] :in-any-order :gaps-ok)) (fact "I can produce a list of input names (keywords) from an interpreter" (p/binding-names (p/interpreter :bindings {:a 2 :b 7})) => [:a :b] ) (fact "I can produce a list of types and modules loaded into the interpreter" (p/types-and-modules (p/interpreter)) => (contains [:introspection :print :snapshot :code :error :log :exec :set :vector :strings :chars :booleans :string :char :boolean :scalar :scalars] :in-any-order :gaps-ok)) (fact "I can produce the router list for an interpreter" (p/routing-list (p/interpreter)) => (contains [:ref :refs :boolean :char :complex :complexes :snapshot :generator :quoted :string :booleans :chars :strings :tagspace :scalars :vector :set :scalar] :in-any-order :gaps-ok)) (fact "I can run a Push program and get a named stack" (p/get-stack (p/run (p/interpreter) [88 99 :scalar-add] 100) :scalar) => '(187)) (fact "I can re-run an interpreter with bound inputs, replacing the input values" (let [a-99 (p/interpreter :bindings {:a 99})] (p/get-stack (p/run a-99 [:a 99 :scalar-add] 100) :scalar) => '(198) (p/get-stack (p/run a-99 [:a 99 :scalar-add] 100 :bindings {:a -99}) :scalar) => '(0) (p/get-stack (p/run a-99 [:a 99 :scalar-add :b] 100 :bindings {:b -99}) :scalar) => '(-99 198))) (fact "I can turn off individual instructions with the forget-instructions function" (keys (:instructions (p/forget-instructions (p/interpreter) [:scalar-add]))) =not=> (contains :scalar-add) (keys (:instructions (p/interpreter))) => (contains :scalar-add)) (fact "I can turn off multiple instructions with the forget-instructions function" (count (keys (:instructions (p/forget-instructions (p/interpreter) [:scalar-add :scalar-subtract])))) => (- (count (keys (:instructions (p/interpreter)))) 2)) (fact "I can turn off unknown instructions with no trouble" (keys (:instructions (p/forget-instructions (p/interpreter) [:foo-bar :baz-quux]))) => (keys (:instructions (p/interpreter)))) (def foo-pop (push.instructions.core/build-instruction foo-pop (push.instructions.dsl/consume-top-of :foo :as :gone))) (fact "about :foo-pop" (:token foo-pop) => :foo-pop (:needs foo-pop) => {:foo 1}) (fact "I can add a new instruction with register-instructions" (keys (:instructions (p/register-instructions (p/interpreter) [foo-pop]))) => (contains :foo-pop)) (fact "I can overwrite an old instruction with register-instructions" (:docstring (:scalar-add (:instructions (p/register-instructions (p/interpreter) [(assoc foo-pop :token :scalar-add)])))) => (:docstring foo-pop))
2efba7f11594a68203f46836cf8b4a1183f2d80bf78c80083485bc7e55b79458
Frama-C/Frama-C-snapshot
offsm_value.mli
(**************************************************************************) (* *) 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 ) . (* *) (**************************************************************************) type offsm_or_top = O of Cvalue.V_Offsetmap.t | Top val cast : old_size: Integer.t -> new_size: Integer.t -> signed: bool -> Cvalue.V_Offsetmap.t -> Cvalue.V_Offsetmap.t module Offsm : Abstract_value.Leaf with type t = offsm_or_top module CvalueOffsm : Abstract.Value.Internal with type t = Cvalue.V.t * offsm_or_top
null
https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/value/values/offsm_value.mli
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. ************************************************************************
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 ) . type offsm_or_top = O of Cvalue.V_Offsetmap.t | Top val cast : old_size: Integer.t -> new_size: Integer.t -> signed: bool -> Cvalue.V_Offsetmap.t -> Cvalue.V_Offsetmap.t module Offsm : Abstract_value.Leaf with type t = offsm_or_top module CvalueOffsm : Abstract.Value.Internal with type t = Cvalue.V.t * offsm_or_top
94f0be21f0abe82c3a3b1710f43f790a6b01fbd17d32fc003c633a17da172efb
input-output-hk/plutus-apps
Vesting.hs
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE FlexibleContexts # {-# LANGUAGE NamedFieldPuns #-} # LANGUAGE NoImplicitPrelude # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} # LANGUAGE TypeApplications # {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} # OPTIONS_GHC -fno - ignore - interface - pragmas # # OPTIONS_GHC -fno - specialise # module Plutus.Contracts.Vesting ( -- $vesting VestingParams(..), VestingSchema, VestingTranche(..), VestingError(..), AsVestingError(..), totalAmount, vestingContract, validate, vestingScript ) where import Control.Lens import Control.Monad (void, when) import Data.Aeson (FromJSON, ToJSON) import Data.Map qualified as Map import Prelude (Semigroup (..)) import Cardano.Node.Emulator.Params (pNetworkId, testnet) import GHC.Generics (Generic) import Ledger (CardanoAddress, POSIXTime, POSIXTimeRange, PaymentPubKeyHash (unPaymentPubKeyHash), decoratedTxOutPlutusValue) import Ledger.Interval qualified as Interval import Ledger.Tx.Constraints (TxConstraints, mustBeSignedBy, mustPayToTheScriptWithDatumInTx, mustValidateInTimeRange) import Ledger.Tx.Constraints qualified as Constraints import Ledger.Tx.Constraints.ValidityInterval qualified as ValidityInterval import Ledger.Typed.Scripts (ValidatorTypes (..)) import Ledger.Typed.Scripts qualified as Scripts import Plutus.Contract import Plutus.Script.Utils.V2.Typed.Scripts qualified as V2 import Plutus.Script.Utils.Value (Value) import Plutus.Script.Utils.Value qualified as Value import Plutus.V2.Ledger.Api (ScriptContext (..), TxInfo (..), Validator) import Plutus.V2.Ledger.Contexts qualified as V2 import PlutusTx qualified import PlutusTx.Prelude hiding (Semigroup (..), fold) import Prelude qualified as Haskell | A simple vesting scheme . Money is locked by a contract and may only be retrieved after some time has passed . This is our first example of a contract that covers multiple transactions , with a contract state that changes over time . In our vesting scheme the money will be released in two _ tranches _ ( parts ): A smaller part will be available after an initial number of time has passed , and the entire amount will be released at the end . The owner of the vesting scheme does not have to take out all the money at once : They can take out any amount up to the total that has been released so far . The remaining funds stay locked and can be retrieved later . Let 's start with the data types . A simple vesting scheme. Money is locked by a contract and may only be retrieved after some time has passed. This is our first example of a contract that covers multiple transactions, with a contract state that changes over time. In our vesting scheme the money will be released in two _tranches_ (parts): A smaller part will be available after an initial number of time has passed, and the entire amount will be released at the end. The owner of the vesting scheme does not have to take out all the money at once: They can take out any amount up to the total that has been released so far. The remaining funds stay locked and can be retrieved later. Let's start with the data types. -} type VestingSchema = Endpoint "vest funds" () .\/ Endpoint "retrieve funds" Value data Vesting instance ValidatorTypes Vesting where type instance RedeemerType Vesting = () type instance DatumType Vesting = () -- | Tranche of a vesting scheme. data VestingTranche = VestingTranche { vestingTrancheDate :: POSIXTime, vestingTrancheAmount :: Value } deriving Generic PlutusTx.makeLift ''VestingTranche | A vesting scheme consisting of two tranches . Each tranche defines a date -- (POSIX time) after which an additional amount can be spent. data VestingParams = VestingParams { vestingTranche1 :: VestingTranche, vestingTranche2 :: VestingTranche, vestingOwner :: PaymentPubKeyHash } deriving Generic PlutusTx.makeLift ''VestingParams # INLINABLE totalAmount # -- | The total amount vested totalAmount :: VestingParams -> Value totalAmount VestingParams{vestingTranche1,vestingTranche2} = vestingTrancheAmount vestingTranche1 + vestingTrancheAmount vestingTranche2 # INLINABLE availableFrom # -- | The amount guaranteed to be available from a given tranche in a given time range. availableFrom :: VestingTranche -> POSIXTimeRange -> Value availableFrom (VestingTranche d v) range = -- The valid range is an open-ended range starting from the tranche vesting date let validRange = Interval.from d -- If the valid range completely contains the argument range (meaning in particular -- that the start time of the argument range is after the tranche vesting date), then -- the money in the tranche is available, otherwise nothing is available. in if validRange `Interval.contains` range then v else zero availableAt :: VestingParams -> POSIXTime -> Value availableAt VestingParams{vestingTranche1, vestingTranche2} time = let f VestingTranche{vestingTrancheDate, vestingTrancheAmount} = if time >= vestingTrancheDate then vestingTrancheAmount else mempty in foldMap f [vestingTranche1, vestingTranche2] # INLINABLE remainingFrom # -- | The amount that has not been released from this tranche yet remainingFrom :: VestingTranche -> POSIXTimeRange -> Value remainingFrom t@VestingTranche{vestingTrancheAmount} range = vestingTrancheAmount - availableFrom t range # INLINABLE validate # validate :: VestingParams -> () -> () -> V2.ScriptContext -> Bool validate VestingParams{vestingTranche1, vestingTranche2, vestingOwner} () () {scriptContextTxInfo=txInfo@TxInfo{txInfoValidRange}} = let remainingActual = V2.valueLockedBy txInfo (V2.ownHash ctx) remainingExpected = remainingFrom vestingTranche1 txInfoValidRange + remainingFrom vestingTranche2 txInfoValidRange in remainingActual `Value.geq` remainingExpected -- The policy encoded in this contract -- is "vestingOwner can do with the funds what they want" (as opposed -- to "the funds must be paid to vestingOwner"). This is enforcey by -- the following condition: && V2.txSignedBy txInfo (unPaymentPubKeyHash vestingOwner) -- That way the recipient of the funds can pay them to whatever address they please , potentially saving one transaction . vestingScript :: VestingParams -> Validator vestingScript = Scripts.validatorScript . typedValidator typedValidator :: VestingParams -> V2.TypedValidator Vesting typedValidator = V2.mkTypedValidatorParam @Vesting $$(PlutusTx.compile [|| validate ||]) $$(PlutusTx.compile [|| wrap ||]) where wrap = Scripts.mkUntypedValidator contractAddress :: VestingParams -> CardanoAddress contractAddress = Scripts.validatorCardanoAddress testnet . typedValidator data VestingError = VContractError ContractError | InsufficientFundsError Value Value Value deriving stock (Haskell.Eq, Haskell.Show, Generic) deriving anyclass (ToJSON, FromJSON) makeClassyPrisms ''VestingError instance AsContractError VestingError where _ContractError = _VContractError vestingContract :: VestingParams -> Contract () VestingSchema VestingError () vestingContract vesting = selectList [vest, retrieve] where vest = endpoint @"vest funds" $ \() -> vestFundsC vesting retrieve = endpoint @"retrieve funds" $ \payment -> do liveness <- retrieveFundsC vesting payment case liveness of Alive -> awaitPromise retrieve Dead -> pure () payIntoContract :: Value -> TxConstraints () () payIntoContract = mustPayToTheScriptWithDatumInTx () vestFundsC :: ( AsVestingError e ) => VestingParams -> Contract w s e () vestFundsC vesting = mapError (review _VestingError) $ do let tx = payIntoContract (totalAmount vesting) mkTxConstraints (Constraints.typedValidatorLookups $ typedValidator vesting) tx >>= adjustUnbalancedTx >>= void . submitUnbalancedTx data Liveness = Alive | Dead retrieveFundsC :: ( AsVestingError e ) => VestingParams -> Value -> Contract w s e Liveness retrieveFundsC vesting payment = mapError (review _VestingError) $ do networkId <- pNetworkId <$> getParams let inst = typedValidator vesting addr = Scripts.validatorCardanoAddress networkId inst now <- fst <$> currentNodeClientTimeRange unspentOutputs <- utxosAt addr let currentlyLocked = foldMap decoratedTxOutPlutusValue (Map.elems unspentOutputs) remainingValue = currentlyLocked - payment mustRemainLocked = totalAmount vesting - availableAt vesting now maxPayment = currentlyLocked - mustRemainLocked when (remainingValue `Value.lt` mustRemainLocked) $ throwError $ InsufficientFundsError payment maxPayment mustRemainLocked let liveness = if remainingValue `Value.gt` mempty then Alive else Dead remainingOutputs = case liveness of Alive -> payIntoContract remainingValue Dead -> mempty tx = Constraints.collectFromTheScript unspentOutputs () <> remainingOutputs <> mustValidateInTimeRange (ValidityInterval.from now) <> mustBeSignedBy (vestingOwner vesting) -- we don't need to add a pubkey output for 'vestingOwner' here -- because this will be done by the wallet when it balances the -- transaction. mkTxConstraints (Constraints.typedValidatorLookups inst <> Constraints.unspentOutputs unspentOutputs) tx >>= adjustUnbalancedTx >>= void . submitUnbalancedTx return liveness
null
https://raw.githubusercontent.com/input-output-hk/plutus-apps/8949ce26588166d9961205aa61edd66e4f83d4f5/plutus-use-cases/src/Plutus/Contracts/Vesting.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE DataKinds # # LANGUAGE DeriveAnyClass # # LANGUAGE NamedFieldPuns # # LANGUAGE OverloadedStrings # # LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # $vesting | Tranche of a vesting scheme. (POSIX time) after which an additional amount can be spent. | The total amount vested | The amount guaranteed to be available from a given tranche in a given time range. The valid range is an open-ended range starting from the tranche vesting date If the valid range completely contains the argument range (meaning in particular that the start time of the argument range is after the tranche vesting date), then the money in the tranche is available, otherwise nothing is available. | The amount that has not been released from this tranche yet The policy encoded in this contract is "vestingOwner can do with the funds what they want" (as opposed to "the funds must be paid to vestingOwner"). This is enforcey by the following condition: That way the recipient of the funds can pay them to whatever address they we don't need to add a pubkey output for 'vestingOwner' here because this will be done by the wallet when it balances the transaction.
# LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE FlexibleContexts # # LANGUAGE NoImplicitPrelude # # LANGUAGE TypeApplications # # OPTIONS_GHC -fno - ignore - interface - pragmas # # OPTIONS_GHC -fno - specialise # module Plutus.Contracts.Vesting ( VestingParams(..), VestingSchema, VestingTranche(..), VestingError(..), AsVestingError(..), totalAmount, vestingContract, validate, vestingScript ) where import Control.Lens import Control.Monad (void, when) import Data.Aeson (FromJSON, ToJSON) import Data.Map qualified as Map import Prelude (Semigroup (..)) import Cardano.Node.Emulator.Params (pNetworkId, testnet) import GHC.Generics (Generic) import Ledger (CardanoAddress, POSIXTime, POSIXTimeRange, PaymentPubKeyHash (unPaymentPubKeyHash), decoratedTxOutPlutusValue) import Ledger.Interval qualified as Interval import Ledger.Tx.Constraints (TxConstraints, mustBeSignedBy, mustPayToTheScriptWithDatumInTx, mustValidateInTimeRange) import Ledger.Tx.Constraints qualified as Constraints import Ledger.Tx.Constraints.ValidityInterval qualified as ValidityInterval import Ledger.Typed.Scripts (ValidatorTypes (..)) import Ledger.Typed.Scripts qualified as Scripts import Plutus.Contract import Plutus.Script.Utils.V2.Typed.Scripts qualified as V2 import Plutus.Script.Utils.Value (Value) import Plutus.Script.Utils.Value qualified as Value import Plutus.V2.Ledger.Api (ScriptContext (..), TxInfo (..), Validator) import Plutus.V2.Ledger.Contexts qualified as V2 import PlutusTx qualified import PlutusTx.Prelude hiding (Semigroup (..), fold) import Prelude qualified as Haskell | A simple vesting scheme . Money is locked by a contract and may only be retrieved after some time has passed . This is our first example of a contract that covers multiple transactions , with a contract state that changes over time . In our vesting scheme the money will be released in two _ tranches _ ( parts ): A smaller part will be available after an initial number of time has passed , and the entire amount will be released at the end . The owner of the vesting scheme does not have to take out all the money at once : They can take out any amount up to the total that has been released so far . The remaining funds stay locked and can be retrieved later . Let 's start with the data types . A simple vesting scheme. Money is locked by a contract and may only be retrieved after some time has passed. This is our first example of a contract that covers multiple transactions, with a contract state that changes over time. In our vesting scheme the money will be released in two _tranches_ (parts): A smaller part will be available after an initial number of time has passed, and the entire amount will be released at the end. The owner of the vesting scheme does not have to take out all the money at once: They can take out any amount up to the total that has been released so far. The remaining funds stay locked and can be retrieved later. Let's start with the data types. -} type VestingSchema = Endpoint "vest funds" () .\/ Endpoint "retrieve funds" Value data Vesting instance ValidatorTypes Vesting where type instance RedeemerType Vesting = () type instance DatumType Vesting = () data VestingTranche = VestingTranche { vestingTrancheDate :: POSIXTime, vestingTrancheAmount :: Value } deriving Generic PlutusTx.makeLift ''VestingTranche | A vesting scheme consisting of two tranches . Each tranche defines a date data VestingParams = VestingParams { vestingTranche1 :: VestingTranche, vestingTranche2 :: VestingTranche, vestingOwner :: PaymentPubKeyHash } deriving Generic PlutusTx.makeLift ''VestingParams # INLINABLE totalAmount # totalAmount :: VestingParams -> Value totalAmount VestingParams{vestingTranche1,vestingTranche2} = vestingTrancheAmount vestingTranche1 + vestingTrancheAmount vestingTranche2 # INLINABLE availableFrom # availableFrom :: VestingTranche -> POSIXTimeRange -> Value availableFrom (VestingTranche d v) range = let validRange = Interval.from d in if validRange `Interval.contains` range then v else zero availableAt :: VestingParams -> POSIXTime -> Value availableAt VestingParams{vestingTranche1, vestingTranche2} time = let f VestingTranche{vestingTrancheDate, vestingTrancheAmount} = if time >= vestingTrancheDate then vestingTrancheAmount else mempty in foldMap f [vestingTranche1, vestingTranche2] # INLINABLE remainingFrom # remainingFrom :: VestingTranche -> POSIXTimeRange -> Value remainingFrom t@VestingTranche{vestingTrancheAmount} range = vestingTrancheAmount - availableFrom t range # INLINABLE validate # validate :: VestingParams -> () -> () -> V2.ScriptContext -> Bool validate VestingParams{vestingTranche1, vestingTranche2, vestingOwner} () () {scriptContextTxInfo=txInfo@TxInfo{txInfoValidRange}} = let remainingActual = V2.valueLockedBy txInfo (V2.ownHash ctx) remainingExpected = remainingFrom vestingTranche1 txInfoValidRange + remainingFrom vestingTranche2 txInfoValidRange in remainingActual `Value.geq` remainingExpected && V2.txSignedBy txInfo (unPaymentPubKeyHash vestingOwner) please , potentially saving one transaction . vestingScript :: VestingParams -> Validator vestingScript = Scripts.validatorScript . typedValidator typedValidator :: VestingParams -> V2.TypedValidator Vesting typedValidator = V2.mkTypedValidatorParam @Vesting $$(PlutusTx.compile [|| validate ||]) $$(PlutusTx.compile [|| wrap ||]) where wrap = Scripts.mkUntypedValidator contractAddress :: VestingParams -> CardanoAddress contractAddress = Scripts.validatorCardanoAddress testnet . typedValidator data VestingError = VContractError ContractError | InsufficientFundsError Value Value Value deriving stock (Haskell.Eq, Haskell.Show, Generic) deriving anyclass (ToJSON, FromJSON) makeClassyPrisms ''VestingError instance AsContractError VestingError where _ContractError = _VContractError vestingContract :: VestingParams -> Contract () VestingSchema VestingError () vestingContract vesting = selectList [vest, retrieve] where vest = endpoint @"vest funds" $ \() -> vestFundsC vesting retrieve = endpoint @"retrieve funds" $ \payment -> do liveness <- retrieveFundsC vesting payment case liveness of Alive -> awaitPromise retrieve Dead -> pure () payIntoContract :: Value -> TxConstraints () () payIntoContract = mustPayToTheScriptWithDatumInTx () vestFundsC :: ( AsVestingError e ) => VestingParams -> Contract w s e () vestFundsC vesting = mapError (review _VestingError) $ do let tx = payIntoContract (totalAmount vesting) mkTxConstraints (Constraints.typedValidatorLookups $ typedValidator vesting) tx >>= adjustUnbalancedTx >>= void . submitUnbalancedTx data Liveness = Alive | Dead retrieveFundsC :: ( AsVestingError e ) => VestingParams -> Value -> Contract w s e Liveness retrieveFundsC vesting payment = mapError (review _VestingError) $ do networkId <- pNetworkId <$> getParams let inst = typedValidator vesting addr = Scripts.validatorCardanoAddress networkId inst now <- fst <$> currentNodeClientTimeRange unspentOutputs <- utxosAt addr let currentlyLocked = foldMap decoratedTxOutPlutusValue (Map.elems unspentOutputs) remainingValue = currentlyLocked - payment mustRemainLocked = totalAmount vesting - availableAt vesting now maxPayment = currentlyLocked - mustRemainLocked when (remainingValue `Value.lt` mustRemainLocked) $ throwError $ InsufficientFundsError payment maxPayment mustRemainLocked let liveness = if remainingValue `Value.gt` mempty then Alive else Dead remainingOutputs = case liveness of Alive -> payIntoContract remainingValue Dead -> mempty tx = Constraints.collectFromTheScript unspentOutputs () <> remainingOutputs <> mustValidateInTimeRange (ValidityInterval.from now) <> mustBeSignedBy (vestingOwner vesting) mkTxConstraints (Constraints.typedValidatorLookups inst <> Constraints.unspentOutputs unspentOutputs) tx >>= adjustUnbalancedTx >>= void . submitUnbalancedTx return liveness
0034abc5519aafc2b5a3df51aa2002226789d4ead3be139e4b6b4b2703525ae6
anmonteiro/graphql-sdl
graphql_schema_printer.ml
open Easy_format type break_criterion = | Never | IfNeed | Always | Always_rec let easyLabel ?(break = `Auto) ?(space = false) ?(indent = 0) labelTerm term = let settings = { label_break = break ; space_after_label = space ; indent_after_label = indent ; label_style = Some "label" } in Easy_format.Label ((labelTerm, settings), term) let label ?break ?space ?indent (labelTerm : Easy_format.t) (term : Easy_format.t) = easyLabel ?break ?indent ?space labelTerm term let atom str = let style = { Easy_format.atom_style = Some "atomClss" } in Atom (str, style) let makeList ?(break = IfNeed) ?(preSpace = false) ?(space = true) ?(indent = 2) ?(inline = true, false) ?(wrap = "", "") ?(sep = "") nodes = let inlineStart, inlineEnd = inline in let easy_break = match break with | Never -> `No_breaks | IfNeed -> `Never_wrap | Always -> `Force_breaks | Always_rec -> `Force_breaks_rec in let style = { Easy_format.list with space_after_opening = false ; space_before_separator = preSpace ; space_after_separator = space ; space_before_closing = false ; wrap_body = easy_break ; indent_body = indent ; stick_to_label = inlineStart ; align_closing = not inlineEnd } in let opn, cls = wrap in List ((opn, sep, cls, style), nodes) let rec formatFieldTyp typ = match typ with | Graphql_parser.NamedType x -> x | ListType t -> "[" ^ formatFieldTyp t ^ "]" | NonNullType t -> formatFieldTyp t ^ "!" let rec formatConstValue value = match value with | `Null -> atom "null" | `Int x -> atom (string_of_int x) | `Float x -> atom (string_of_float x) | `Enum x -> atom x | `String x -> atom ("\"" ^ x ^ "\"") | `Bool x -> atom (string_of_bool x) | `List xs -> makeList ~sep:"," (List.map formatConstValue xs) | `Assoc xs -> makeList ~wrap:("{", "}") (List.map (fun (k, v) -> makeList ~sep:":" [ atom k; formatConstValue v ]) xs) let formatDescription ?(inline = true) description layout = match description with | None -> layout | Some description -> let description_layout = makeList ~break:Never ~space:false [ atom "\""; atom description; atom "\"" ] in makeList ~indent:0 ~space:false ~inline: (if inline then true, true else true, false) ~break:Always [ description_layout; layout ] let formatArguments arguments = match arguments with | [] -> None | xs -> let args_len = List.length arguments in let args_layout = makeList ~inline:(true, true) (List.mapi (fun i ({ Ast.name; typ; default_value; description } : Ast.argument_definition) -> let argDef = makeList [ makeList ~space:false [ atom name; atom ":" ] ; (if i == args_len - 1 then atom (formatFieldTyp typ) else makeList ~break:Never ~space:false [ atom (formatFieldTyp typ); atom "," ]) ] in let break = match description with None -> Never | Some _ -> Always_rec in let arg_def_layout = match default_value with | None -> argDef | Some value -> makeList [ argDef; atom "="; formatConstValue value ] in formatDescription description (makeList ~inline:(true, true) ~break ~space:false [ arg_def_layout ])) xs) in Some args_layout let format_directives directives = List.map (fun ({ name; arguments } : Ast.directive) -> let arguments_layout = makeList ~sep:"," ~wrap:("(", ")") (List.map (fun (name, value) -> makeList [ makeList ~space:false [ atom name; atom ":" ] ; formatConstValue value ]) arguments) in makeList ~space:false ([ atom "@"; atom name ] @ if arguments == [] then [] else [ arguments_layout ])) directives let formatInputFields fields = List.map (fun { Ast.typ; name; arguments; description; directives; default_value } -> let layout = match formatArguments arguments with | None -> atom name | Some args_layout -> let wrapped = makeList ~wrap:("(", ")") [ args_layout ] in label ~break:`Never (atom name) wrapped in let field_layout = makeList ~space:false ~indent:0 ~break:Never [ layout; makeList [ atom ":"; atom (formatFieldTyp typ) ] ] in let field_layout = match default_value with | None -> field_layout | Some value -> makeList [ field_layout; atom "="; formatConstValue value ] in formatDescription description (makeList ~inline:(true, true) ~indent:0 (field_layout :: format_directives directives))) fields let formatFields fields = List.map (fun { Ast.typ; name; arguments; description; directives } -> let layout = match formatArguments arguments with | None -> atom name | Some args_layout -> let wrapped = makeList ~wrap:("(", ")") [ args_layout ] in label ~break:`Never (atom name) wrapped in let field_layout = makeList ~space:false ~indent:0 ~break:Never [ layout; makeList [ atom ":"; atom (formatFieldTyp typ) ] ] in formatDescription description (makeList ~inline:(true, true) ~indent:0 (field_layout :: format_directives directives))) fields let formatEnumVals enumVals = List.map (fun ({ name; description } : Ast.enumValue) -> formatDescription description (atom name)) enumVals let formatSchemaFields fields = List.map (fun { Ast.name; typ } -> makeList ~space:false [ atom name; makeList [ atom ":"; atom typ ] ]) fields let formatUnion unionDef possibleVals description = let union = makeList [ unionDef ; atom "=" ; makeList ~preSpace:true ~sep:"|" (List.map (fun ({ name; _ } : Ast.enumValue) -> atom name) possibleVals) ] in formatDescription description union let formatType typeDef fields description = let typ = label ~space:true typeDef (makeList ~break:Always ~wrap:("{", "}") fields) in formatDescription description typ let pprint_typ typ = match typ with | Ast.Type { name; field_defs; directives; description; interfaces } -> let intfs_layout = match interfaces with | None -> [] | Some intfs -> List.concat (List.map (fun intf -> [ atom "implements"; atom intf ]) intfs) in formatType (label ~space:true (atom "type") (makeList (List.concat [ [ atom name ]; intfs_layout; format_directives directives ]))) (formatFields field_defs) description | InputType { name; field_defs; directives; description; _ } -> formatType (label ~space:true (atom "input") (makeList (atom name :: format_directives directives))) (formatInputFields field_defs) description | Enum { name; possibleVals; directives; description } -> formatType (label ~space:true (atom "enum") (makeList (atom name :: format_directives directives))) (formatEnumVals possibleVals) description | Union { name; possibleVals; directives; description } -> formatUnion (label ~space:true (atom "union") (makeList (atom name :: format_directives directives))) possibleVals description | Interface { name; field_defs; directives; description; _ } -> formatType (label ~space:true (atom "interface") (makeList (atom name :: format_directives directives))) (formatFields field_defs) description | Scalar { name; directives; description } -> let scalar = label ~space:true (atom "scalar") (makeList (atom name :: format_directives directives)) in formatDescription description scalar | Schema { fields; directives; description } -> formatType (makeList ~space:true (atom "schema" :: format_directives directives)) (formatSchemaFields fields) description let pprint_schema schema = makeList ~break:Always ~sep:"\n" ~indent:0 (List.map pprint_typ schema)
null
https://raw.githubusercontent.com/anmonteiro/graphql-sdl/ac3b90a24928f0a7b1ca7e242004250bba8b8f98/lib/graphql_schema_printer.ml
ocaml
open Easy_format type break_criterion = | Never | IfNeed | Always | Always_rec let easyLabel ?(break = `Auto) ?(space = false) ?(indent = 0) labelTerm term = let settings = { label_break = break ; space_after_label = space ; indent_after_label = indent ; label_style = Some "label" } in Easy_format.Label ((labelTerm, settings), term) let label ?break ?space ?indent (labelTerm : Easy_format.t) (term : Easy_format.t) = easyLabel ?break ?indent ?space labelTerm term let atom str = let style = { Easy_format.atom_style = Some "atomClss" } in Atom (str, style) let makeList ?(break = IfNeed) ?(preSpace = false) ?(space = true) ?(indent = 2) ?(inline = true, false) ?(wrap = "", "") ?(sep = "") nodes = let inlineStart, inlineEnd = inline in let easy_break = match break with | Never -> `No_breaks | IfNeed -> `Never_wrap | Always -> `Force_breaks | Always_rec -> `Force_breaks_rec in let style = { Easy_format.list with space_after_opening = false ; space_before_separator = preSpace ; space_after_separator = space ; space_before_closing = false ; wrap_body = easy_break ; indent_body = indent ; stick_to_label = inlineStart ; align_closing = not inlineEnd } in let opn, cls = wrap in List ((opn, sep, cls, style), nodes) let rec formatFieldTyp typ = match typ with | Graphql_parser.NamedType x -> x | ListType t -> "[" ^ formatFieldTyp t ^ "]" | NonNullType t -> formatFieldTyp t ^ "!" let rec formatConstValue value = match value with | `Null -> atom "null" | `Int x -> atom (string_of_int x) | `Float x -> atom (string_of_float x) | `Enum x -> atom x | `String x -> atom ("\"" ^ x ^ "\"") | `Bool x -> atom (string_of_bool x) | `List xs -> makeList ~sep:"," (List.map formatConstValue xs) | `Assoc xs -> makeList ~wrap:("{", "}") (List.map (fun (k, v) -> makeList ~sep:":" [ atom k; formatConstValue v ]) xs) let formatDescription ?(inline = true) description layout = match description with | None -> layout | Some description -> let description_layout = makeList ~break:Never ~space:false [ atom "\""; atom description; atom "\"" ] in makeList ~indent:0 ~space:false ~inline: (if inline then true, true else true, false) ~break:Always [ description_layout; layout ] let formatArguments arguments = match arguments with | [] -> None | xs -> let args_len = List.length arguments in let args_layout = makeList ~inline:(true, true) (List.mapi (fun i ({ Ast.name; typ; default_value; description } : Ast.argument_definition) -> let argDef = makeList [ makeList ~space:false [ atom name; atom ":" ] ; (if i == args_len - 1 then atom (formatFieldTyp typ) else makeList ~break:Never ~space:false [ atom (formatFieldTyp typ); atom "," ]) ] in let break = match description with None -> Never | Some _ -> Always_rec in let arg_def_layout = match default_value with | None -> argDef | Some value -> makeList [ argDef; atom "="; formatConstValue value ] in formatDescription description (makeList ~inline:(true, true) ~break ~space:false [ arg_def_layout ])) xs) in Some args_layout let format_directives directives = List.map (fun ({ name; arguments } : Ast.directive) -> let arguments_layout = makeList ~sep:"," ~wrap:("(", ")") (List.map (fun (name, value) -> makeList [ makeList ~space:false [ atom name; atom ":" ] ; formatConstValue value ]) arguments) in makeList ~space:false ([ atom "@"; atom name ] @ if arguments == [] then [] else [ arguments_layout ])) directives let formatInputFields fields = List.map (fun { Ast.typ; name; arguments; description; directives; default_value } -> let layout = match formatArguments arguments with | None -> atom name | Some args_layout -> let wrapped = makeList ~wrap:("(", ")") [ args_layout ] in label ~break:`Never (atom name) wrapped in let field_layout = makeList ~space:false ~indent:0 ~break:Never [ layout; makeList [ atom ":"; atom (formatFieldTyp typ) ] ] in let field_layout = match default_value with | None -> field_layout | Some value -> makeList [ field_layout; atom "="; formatConstValue value ] in formatDescription description (makeList ~inline:(true, true) ~indent:0 (field_layout :: format_directives directives))) fields let formatFields fields = List.map (fun { Ast.typ; name; arguments; description; directives } -> let layout = match formatArguments arguments with | None -> atom name | Some args_layout -> let wrapped = makeList ~wrap:("(", ")") [ args_layout ] in label ~break:`Never (atom name) wrapped in let field_layout = makeList ~space:false ~indent:0 ~break:Never [ layout; makeList [ atom ":"; atom (formatFieldTyp typ) ] ] in formatDescription description (makeList ~inline:(true, true) ~indent:0 (field_layout :: format_directives directives))) fields let formatEnumVals enumVals = List.map (fun ({ name; description } : Ast.enumValue) -> formatDescription description (atom name)) enumVals let formatSchemaFields fields = List.map (fun { Ast.name; typ } -> makeList ~space:false [ atom name; makeList [ atom ":"; atom typ ] ]) fields let formatUnion unionDef possibleVals description = let union = makeList [ unionDef ; atom "=" ; makeList ~preSpace:true ~sep:"|" (List.map (fun ({ name; _ } : Ast.enumValue) -> atom name) possibleVals) ] in formatDescription description union let formatType typeDef fields description = let typ = label ~space:true typeDef (makeList ~break:Always ~wrap:("{", "}") fields) in formatDescription description typ let pprint_typ typ = match typ with | Ast.Type { name; field_defs; directives; description; interfaces } -> let intfs_layout = match interfaces with | None -> [] | Some intfs -> List.concat (List.map (fun intf -> [ atom "implements"; atom intf ]) intfs) in formatType (label ~space:true (atom "type") (makeList (List.concat [ [ atom name ]; intfs_layout; format_directives directives ]))) (formatFields field_defs) description | InputType { name; field_defs; directives; description; _ } -> formatType (label ~space:true (atom "input") (makeList (atom name :: format_directives directives))) (formatInputFields field_defs) description | Enum { name; possibleVals; directives; description } -> formatType (label ~space:true (atom "enum") (makeList (atom name :: format_directives directives))) (formatEnumVals possibleVals) description | Union { name; possibleVals; directives; description } -> formatUnion (label ~space:true (atom "union") (makeList (atom name :: format_directives directives))) possibleVals description | Interface { name; field_defs; directives; description; _ } -> formatType (label ~space:true (atom "interface") (makeList (atom name :: format_directives directives))) (formatFields field_defs) description | Scalar { name; directives; description } -> let scalar = label ~space:true (atom "scalar") (makeList (atom name :: format_directives directives)) in formatDescription description scalar | Schema { fields; directives; description } -> formatType (makeList ~space:true (atom "schema" :: format_directives directives)) (formatSchemaFields fields) description let pprint_schema schema = makeList ~break:Always ~sep:"\n" ~indent:0 (List.map pprint_typ schema)
474cd8ba44f023574b0d4efe6f62e6fd86a356c1c4fb6425efa06196ba2620ce
input-output-hk/cardano-sl
Types.hs
# LANGUAGE CPP # {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE ExplicitNamespaces #-} # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE KindSignatures # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PolyKinds #-} # LANGUAGE StandaloneDeriving # # LANGUAGE StrictData # {-# LANGUAGE TemplateHaskell #-} -- The hlint parser fails on the `pattern` function, so we disable the -- language extension here. {-# LANGUAGE NoPatternSynonyms #-} # LANGUAGE NamedFieldPuns # Needed for the ` Buildable ` , ` SubscriptionStatus ` and ` NodeId ` orphans . # OPTIONS_GHC -fno - warn - orphans # module Cardano.Wallet.API.V1.Types ( V1 (..) , unV1 -- * Swagger & REST-related types , PasswordUpdate (..) , AccountUpdate (..) , NewAccount (..) , Update , New , ForceNtpCheck (..) -- * Domain-specific types -- * Wallets , Wallet (..) , AssuranceLevel (..) , NewWallet (..) , WalletUpdate (..) , WalletId (..) , exampleWalletId , WalletOperation (..) , SpendingPassword , mkSpendingPassword -- * Addresses , AddressOwnership (..) , AddressValidity (..) -- * Accounts , Account (..) , accountsHaveSameId , AccountIndex , AccountAddresses (..) , AccountBalance (..) , getAccIndex , mkAccountIndex , mkAccountIndexM , unsafeMkAccountIndex , AccountIndexError(..) -- * Addresses , WalletAddress (..) , NewAddress (..) , BatchImportResult(..) -- * Payments , Payment (..) , PaymentSource (..) , PaymentDistribution (..) , Transaction (..) , TransactionType (..) , TransactionDirection (..) , TransactionStatus(..) , EstimatedFees (..) -- * Updates , WalletSoftwareUpdate (..) -- * Importing a wallet from a backup , WalletImport (..) -- * Settings , NodeSettings (..) , SlotDuration , mkSlotDuration , BlockchainHeight , mkBlockchainHeight , LocalTimeDifference , mkLocalTimeDifference , EstimatedCompletionTime , mkEstimatedCompletionTime , SyncThroughput , mkSyncThroughput , SyncState (..) , SyncProgress (..) , SyncPercentage , mkSyncPercentage , NodeInfo (..) , TimeInfo(..) , SubscriptionStatus(..) , Redemption(..) , RedemptionMnemonic(..) , BackupPhrase(..) , ShieldedRedemptionCode(..) , WAddressMeta (..) -- * Some types for the API , CaptureWalletId , CaptureAccountId -- * Core re-exports , Core.Address , Core.InputSelectionPolicy(..) , Core.Coin , Core.Timestamp(..) , Core.mkCoin -- * Wallet Errors , WalletError(..) , ErrNotEnoughMoney(..) , ErrUtxoNotEnoughFragmented(..) , msgUtxoNotEnoughFragmented , toServantError , toHttpErrorStatus , MnemonicBalance(..) , module Cardano.Wallet.Types.UtxoStatistics ) where import qualified Prelude import Universum import qualified Cardano.Crypto.Wallet as CC import Control.Lens (at, to, (?~)) import Data.Aeson import qualified Data.Aeson.Options as Aeson import Data.Aeson.TH as A import Data.Aeson.Types (Parser, Value (..), typeMismatch) import Data.Bifunctor (first) import qualified Data.ByteArray as ByteArray import qualified Data.ByteString as BS import Data.ByteString.Base58 (bitcoinAlphabet, decodeBase58) import qualified Data.Char as C import Data.Default (Default (def)) import Data.List ((!!)) import Data.Maybe (fromJust) import Data.Semigroup (Semigroup) import Data.Swagger hiding (Example, example) import Data.Text (Text, dropEnd, toLower) import Formatting (bprint, build, fconst, int, sformat, (%)) import qualified Formatting.Buildable import Generics.SOP.TH (deriveGeneric) import Serokell.Util (listJson) import qualified Serokell.Util.Base16 as Base16 import Servant import Test.QuickCheck import Test.QuickCheck.Gen (Gen (..)) import qualified Test.QuickCheck.Gen as Gen import qualified Test.QuickCheck.Modifiers as Gen import Pos.Node.API import Cardano.Wallet.API.Response.JSend (HasDiagnostic (..), noDiagnosticKey) import Cardano.Wallet.API.Types.UnitOfMeasure (MeasuredIn (..), UnitOfMeasure (..)) import Cardano.Wallet.API.V1.Errors (ToHttpErrorStatus (..), ToServantError (..)) import Cardano.Wallet.API.V1.Generic (jsendErrorGenericParseJSON, jsendErrorGenericToJSON) import Cardano.Wallet.API.V1.Swagger.Example (Example, example) import Cardano.Wallet.Types.UtxoStatistics import Cardano.Wallet.Util (mkJsonKey, showApiUtcTime) import Cardano.Mnemonic (Mnemonic) import qualified Pos.Chain.Txp as Txp import qualified Pos.Client.Txp.Util as Core import qualified Pos.Core as Core import Pos.Crypto (PublicKey (..), decodeHash, hashHexF) import qualified Pos.Crypto.Signing as Core import Pos.Infra.Communication.Types.Protocol () import Pos.Infra.Diffusion.Subscription.Status (SubscriptionStatus (..)) import Pos.Infra.Util.LogSafe (BuildableSafeGen (..), buildSafe, buildSafeList, buildSafeMaybe, deriveSafeBuildable, plainOrSecureF) import Test.Pos.Core.Arbitrary () -- | Declare generic schema, while documenting properties -- For instance: -- data -- { myDataField1 :: String , : : String -- } deriving (Generic) -- instance where -- declareNamedSchema = -- genericSchemaDroppingPrefix "myData" (\(--^) props -> props -- & ("field1" --^ "Description 1") & ( " field2 " --^ " Description 2 " ) -- ) -- -- -- or, if no descriptions are added to the underlying properties -- instance where -- declareNamedSchema = -- genericSchemaDroppingPrefix "myData" (\_ -> id) -- optsADTCamelCase :: A.Options optsADTCamelCase = defaultOptions { A.constructorTagModifier = mkJsonKey , A.sumEncoding = A.ObjectWithSingleField } -- -- Versioning -- mkSpendingPassword :: Text -> Either Text SpendingPassword mkSpendingPassword = fmap V1 . mkPassPhrase mkPassPhrase :: Text -> Either Text Core.PassPhrase mkPassPhrase text = case Base16.decode text of Left e -> Left e Right bs -> do let bl = BS.length bs Currently passphrase may be either 32 - byte long or empty ( for -- unencrypted keys). if bl == 0 || bl == Core.passphraseLength then Right $ ByteArray.convert bs else Left $ sformat ("Expected spending password to be of either length 0 or "%int%", not "%int) Core.passphraseLength bl instance ToJSON (V1 Core.PassPhrase) where toJSON = String . Base16.encode . ByteArray.convert instance FromJSON (V1 Core.PassPhrase) where parseJSON (String pp) = case mkPassPhrase pp of Left e -> fail (toString e) Right pp' -> pure (V1 pp') parseJSON x = typeMismatch "parseJSON failed for PassPhrase" x instance Arbitrary (V1 Core.PassPhrase) where arbitrary = fmap V1 arbitrary instance ToSchema (V1 Core.PassPhrase) where declareNamedSchema _ = pure $ NamedSchema (Just "V1PassPhrase") $ mempty & type_ ?~ SwaggerString & format ?~ "hex|base16" instance ToJSON (V1 Core.Coin) where toJSON (V1 c) = toJSON . Core.unsafeGetCoin $ c instance FromJSON (V1 Core.Coin) where parseJSON v = do i <- Core.Coin <$> parseJSON v either (fail . toString) (const (pure (V1 i))) $ Core.checkCoin i instance Arbitrary (V1 Core.Coin) where arbitrary = fmap V1 arbitrary instance ToSchema (V1 Core.Coin) where declareNamedSchema _ = pure $ NamedSchema (Just "V1Coin") $ mempty & type_ ?~ SwaggerNumber & maximum_ .~ Just (fromIntegral Core.maxCoinVal) instance ToJSON (V1 Core.Address) where toJSON (V1 c) = String $ sformat Core.addressF c instance FromJSON (V1 Core.Address) where parseJSON (String a) = case Core.decodeTextAddress a of Left e -> fail $ "Not a valid Cardano Address: " <> toString e Right addr -> pure (V1 addr) parseJSON x = typeMismatch "parseJSON failed for Address" x instance Arbitrary (V1 Core.Address) where arbitrary = fmap V1 arbitrary instance ToSchema (V1 Core.Address) where declareNamedSchema _ = pure $ NamedSchema (Just "Address") $ mempty & type_ ?~ SwaggerString & format ?~ "base58" instance FromHttpApiData (V1 Core.Address) where parseQueryParam = fmap (fmap V1) Core.decodeTextAddress instance ToHttpApiData (V1 Core.Address) where toQueryParam (V1 a) = sformat build a deriving instance Hashable (V1 Core.Address) deriving instance NFData (V1 Core.Address) -- | Represents according to 'apiTimeFormat' format. instance ToJSON (V1 Core.Timestamp) where toJSON timestamp = let utcTime = timestamp ^. _V1 . Core.timestampToUTCTimeL in String $ showApiUtcTime utcTime instance ToHttpApiData (V1 Core.Timestamp) where toQueryParam = view (_V1 . Core.timestampToUTCTimeL . to showApiUtcTime) instance FromHttpApiData (V1 Core.Timestamp) where parseQueryParam t = maybe (Left ("Couldn't parse timestamp or datetime out of: " <> t)) (Right . V1) (Core.parseTimestamp t) -- | Parses from both UTC time in 'apiTimeFormat' format and a fractional -- timestamp format. instance FromJSON (V1 Core.Timestamp) where parseJSON = withText "Timestamp" $ \t -> maybe (fail ("Couldn't parse timestamp or datetime out of: " <> toString t)) (pure . V1) (Core.parseTimestamp t) instance Arbitrary (V1 Core.Timestamp) where arbitrary = fmap V1 arbitrary instance ToSchema (V1 Core.Timestamp) where declareNamedSchema _ = pure $ NamedSchema (Just "Timestamp") $ mempty & type_ ?~ SwaggerString & description ?~ "Time in ISO 8601 format" -- -- Domain-specific types, mostly placeholders. -- | A ' SpendingPassword ' represent a secret piece of information which can be -- optionally supplied by the user to encrypt the private keys. As private keys -- are needed to spend funds and this password secures spending, here the name ' SpendingPassword ' . Practically speaking , it 's just a type synonym for a PassPhrase , which is a -- base16-encoded string. type SpendingPassword = V1 Core.PassPhrase instance Semigroup (V1 Core.PassPhrase) where V1 a <> V1 b = V1 (a <> b) instance Monoid (V1 Core.PassPhrase) where mempty = V1 mempty mappend = (<>) instance BuildableSafeGen SpendingPassword where buildSafeGen sl pwd = bprint (plainOrSecureF sl build (fconst "<spending password>")) pwd type WalletName = Text -- | Wallet's Assurance Level data AssuranceLevel = NormalAssurance | StrictAssurance deriving (Eq, Ord, Show, Enum, Bounded) instance Arbitrary AssuranceLevel where arbitrary = elements [minBound .. maxBound] deriveJSON Aeson.defaultOptions { A.constructorTagModifier = toString . toLower . dropEnd 9 . fromString } ''AssuranceLevel instance ToSchema AssuranceLevel where declareNamedSchema _ = pure $ NamedSchema (Just "AssuranceLevel") $ mempty & type_ ?~ SwaggerString & enum_ ?~ ["normal", "strict"] deriveSafeBuildable ''AssuranceLevel instance BuildableSafeGen AssuranceLevel where buildSafeGen _ NormalAssurance = "normal" buildSafeGen _ StrictAssurance = "strict" -- | A Wallet ID. newtype WalletId = WalletId Text deriving (Show, Eq, Ord, Generic) exampleWalletId :: WalletId exampleWalletId = WalletId "J7rQqaLLHBFPrgJXwpktaMB1B1kQBXAyc2uRSfRPzNVGiv6TdxBzkPNBUWysZZZdhFG9gRy3sQFfX5wfpLbi4XTFGFxTg" deriveJSON Aeson.defaultOptions ''WalletId instance ToSchema WalletId where declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions instance ToJSONKey WalletId instance Arbitrary WalletId where arbitrary = elements [exampleWalletId] deriveSafeBuildable ''WalletId instance BuildableSafeGen WalletId where buildSafeGen sl (WalletId wid) = bprint (plainOrSecureF sl build (fconst "<wallet id>")) wid instance FromHttpApiData WalletId where parseQueryParam = Right . WalletId instance ToHttpApiData WalletId where toQueryParam (WalletId wid) = wid instance Hashable WalletId instance NFData WalletId -- | A Wallet Operation data WalletOperation = CreateWallet | RestoreWallet deriving (Eq, Show, Enum, Bounded) instance Arbitrary WalletOperation where arbitrary = elements [minBound .. maxBound] -- Drops the @Wallet@ suffix. deriveJSON Aeson.defaultOptions { A.constructorTagModifier = reverse . drop 6 . reverse . map C.toLower } ''WalletOperation instance ToSchema WalletOperation where declareNamedSchema _ = pure $ NamedSchema (Just "WalletOperation") $ mempty & type_ ?~ SwaggerString & enum_ ?~ ["create", "restore"] deriveSafeBuildable ''WalletOperation instance BuildableSafeGen WalletOperation where buildSafeGen _ CreateWallet = "create" buildSafeGen _ RestoreWallet = "restore" newtype BackupPhrase = BackupPhrase { unBackupPhrase :: Mnemonic 12 } deriving stock (Eq, Show) deriving newtype (ToJSON, FromJSON, Arbitrary) deriveSafeBuildable ''BackupPhrase instance BuildableSafeGen BackupPhrase where buildSafeGen _ _ = "<backup phrase>" instance ToSchema BackupPhrase where declareNamedSchema _ = pure . NamedSchema (Just "V1BackupPhrase") $ toSchema (Proxy @(Mnemonic 12)) -- | A type modelling the request for a new 'Wallet'. data NewWallet = NewWallet { newwalBackupPhrase :: !BackupPhrase , newwalSpendingPassword :: !(Maybe SpendingPassword) , newwalAssuranceLevel :: !AssuranceLevel , newwalName :: !WalletName , newwalOperation :: !WalletOperation } deriving (Eq, Show, Generic) deriveJSON Aeson.defaultOptions ''NewWallet instance Arbitrary NewWallet where arbitrary = NewWallet <$> arbitrary <*> pure Nothing <*> arbitrary <*> pure "My Wallet" <*> arbitrary instance ToSchema NewWallet where declareNamedSchema = genericSchemaDroppingPrefix "newwal" (\(--^) props -> props & ("backupPhrase" --^ "Backup phrase to restore the wallet.") & ("spendingPassword" --^ "Optional (but recommended) password to protect the wallet on sensitive operations.") & ("assuranceLevel" --^ "Desired assurance level based on the number of confirmations counter of each transaction.") & ("name" --^ "Wallet's name.") & ("operation" --^ "Create a new wallet or Restore an existing one.") ) deriveSafeBuildable ''NewWallet instance BuildableSafeGen NewWallet where buildSafeGen sl NewWallet{..} = bprint ("{" %" backupPhrase="%buildSafe sl %" spendingPassword="%(buildSafeMaybe mempty sl) %" assuranceLevel="%buildSafe sl %" name="%buildSafe sl %" operation"%buildSafe sl %" }") newwalBackupPhrase newwalSpendingPassword newwalAssuranceLevel newwalName newwalOperation -- | A type modelling the update of an existing wallet. data WalletUpdate = WalletUpdate { uwalAssuranceLevel :: !AssuranceLevel , uwalName :: !Text } deriving (Eq, Show, Generic) deriveJSON Aeson.defaultOptions ''WalletUpdate instance ToSchema WalletUpdate where declareNamedSchema = genericSchemaDroppingPrefix "uwal" (\(--^) props -> props & ("assuranceLevel" --^ "New assurance level.") & ("name" --^ "New wallet's name.") ) instance Arbitrary WalletUpdate where arbitrary = WalletUpdate <$> arbitrary <*> pure "My Wallet" deriveSafeBuildable ''WalletUpdate instance BuildableSafeGen WalletUpdate where buildSafeGen sl WalletUpdate{..} = bprint ("{" %" assuranceLevel="%buildSafe sl %" name="%buildSafe sl %" }") uwalAssuranceLevel uwalName newtype EstimatedCompletionTime = EstimatedCompletionTime (MeasuredIn 'Milliseconds Word) deriving (Show, Eq) mkEstimatedCompletionTime :: Word -> EstimatedCompletionTime mkEstimatedCompletionTime = EstimatedCompletionTime . MeasuredIn instance Ord EstimatedCompletionTime where compare (EstimatedCompletionTime (MeasuredIn w1)) (EstimatedCompletionTime (MeasuredIn w2)) = compare w1 w2 instance Arbitrary EstimatedCompletionTime where arbitrary = EstimatedCompletionTime . MeasuredIn <$> arbitrary deriveSafeBuildable ''EstimatedCompletionTime instance BuildableSafeGen EstimatedCompletionTime where buildSafeGen _ (EstimatedCompletionTime (MeasuredIn w)) = bprint ("{" %" quantity="%build %" unit=milliseconds" %" }") w instance ToJSON EstimatedCompletionTime where toJSON (EstimatedCompletionTime (MeasuredIn w)) = object [ "quantity" .= toJSON w , "unit" .= String "milliseconds" ] instance FromJSON EstimatedCompletionTime where parseJSON = withObject "EstimatedCompletionTime" $ \sl -> mkEstimatedCompletionTime <$> sl .: "quantity" instance ToSchema EstimatedCompletionTime where declareNamedSchema _ = pure $ NamedSchema (Just "EstimatedCompletionTime") $ mempty & type_ ?~ SwaggerObject & required .~ ["quantity", "unit"] & properties .~ (mempty & at "quantity" ?~ (Inline $ mempty & type_ ?~ SwaggerNumber & minimum_ .~ Just 0 ) & at "unit" ?~ (Inline $ mempty & type_ ?~ SwaggerString & enum_ ?~ ["milliseconds"] ) ) newtype SyncThroughput = SyncThroughput (MeasuredIn 'BlocksPerSecond Core.BlockCount) deriving (Show, Eq) mkSyncThroughput :: Core.BlockCount -> SyncThroughput mkSyncThroughput = SyncThroughput . MeasuredIn instance Ord SyncThroughput where compare (SyncThroughput (MeasuredIn (Core.BlockCount b1))) (SyncThroughput (MeasuredIn (Core.BlockCount b2))) = compare b1 b2 instance Arbitrary SyncThroughput where arbitrary = SyncThroughput . MeasuredIn <$> arbitrary deriveSafeBuildable ''SyncThroughput instance BuildableSafeGen SyncThroughput where buildSafeGen _ (SyncThroughput (MeasuredIn (Core.BlockCount blocks))) = bprint ("{" %" quantity="%build %" unit=blocksPerSecond" %" }") blocks instance ToJSON SyncThroughput where toJSON (SyncThroughput (MeasuredIn (Core.BlockCount blocks))) = object [ "quantity" .= toJSON blocks , "unit" .= String "blocksPerSecond" ] instance FromJSON SyncThroughput where parseJSON = withObject "SyncThroughput" $ \sl -> mkSyncThroughput . Core.BlockCount <$> sl .: "quantity" instance ToSchema SyncThroughput where declareNamedSchema _ = pure $ NamedSchema (Just "SyncThroughput") $ mempty & type_ ?~ SwaggerObject & required .~ ["quantity", "unit"] & properties .~ (mempty & at "quantity" ?~ (Inline $ mempty & type_ ?~ SwaggerNumber ) & at "unit" ?~ (Inline $ mempty & type_ ?~ SwaggerString & enum_ ?~ ["blocksPerSecond"] ) ) data SyncProgress = SyncProgress { spEstimatedCompletionTime :: !EstimatedCompletionTime , spThroughput :: !SyncThroughput , spPercentage :: !SyncPercentage } deriving (Show, Eq, Ord, Generic) deriveJSON Aeson.defaultOptions ''SyncProgress instance ToSchema SyncProgress where declareNamedSchema = genericSchemaDroppingPrefix "sp" (\(--^) props -> props & "estimatedCompletionTime" --^ "The estimated time the wallet is expected to be fully sync, based on the information available." & "throughput" --^ "The sync throughput, measured in blocks/s." & "percentage" ^ " The sync percentage , from 0 % to 100 % . " ) deriveSafeBuildable ''SyncProgress Nothing secret to redact for a SyncProgress . instance BuildableSafeGen SyncProgress where buildSafeGen sl SyncProgress {..} = bprint ("{" %" estimatedCompletionTime="%buildSafe sl %" throughput="%buildSafe sl %" percentage="%buildSafe sl %" }") spEstimatedCompletionTime spThroughput spPercentage instance Example SyncProgress where example = do exPercentage <- example pure $ SyncProgress { spEstimatedCompletionTime = mkEstimatedCompletionTime 3000 , spThroughput = mkSyncThroughput (Core.BlockCount 400) , spPercentage = exPercentage } instance Arbitrary SyncProgress where arbitrary = SyncProgress <$> arbitrary <*> arbitrary <*> arbitrary data SyncState = Restoring SyncProgress -- ^ Restoring from seed or from backup. | Synced -- ^ Following the blockchain. deriving (Eq, Show, Ord) instance ToJSON SyncState where toJSON ss = object [ "tag" .= toJSON (renderAsTag ss) , "data" .= renderAsData ss ] where renderAsTag :: SyncState -> Text renderAsTag (Restoring _) = "restoring" renderAsTag Synced = "synced" renderAsData :: SyncState -> Value renderAsData (Restoring sp) = toJSON sp renderAsData Synced = Null instance FromJSON SyncState where parseJSON = withObject "SyncState" $ \ss -> do t <- ss .: "tag" case (t :: Text) of "synced" -> pure Synced "restoring" -> Restoring <$> ss .: "data" _ -> typeMismatch "unrecognised tag" (Object ss) instance ToSchema SyncState where declareNamedSchema _ = do syncProgress <- declareSchemaRef @SyncProgress Proxy pure $ NamedSchema (Just "SyncState") $ mempty & type_ ?~ SwaggerObject & required .~ ["tag"] & properties .~ (mempty & at "tag" ?~ (Inline $ mempty & type_ ?~ SwaggerString & enum_ ?~ ["restoring", "synced"] ) & at "data" ?~ syncProgress ) instance Arbitrary SyncState where arbitrary = oneof [ Restoring <$> arbitrary , pure Synced ] -- | A 'Wallet'. data Wallet = Wallet { walId :: !WalletId , walName :: !WalletName , walBalance :: !(V1 Core.Coin) , walHasSpendingPassword :: !Bool , walSpendingPasswordLastUpdate :: !(V1 Core.Timestamp) , walCreatedAt :: !(V1 Core.Timestamp) , walAssuranceLevel :: !AssuranceLevel , walSyncState :: !SyncState } deriving (Eq, Ord, Show, Generic) deriveJSON Aeson.defaultOptions ''Wallet instance ToSchema Wallet where declareNamedSchema = genericSchemaDroppingPrefix "wal" (\(--^) props -> props & "id" --^ "Unique wallet identifier." & "name" --^ "Wallet's name." & "balance" ^ " Current balance , in . " & "hasSpendingPassword" --^ "Whether or not the wallet has a passphrase." & "spendingPasswordLastUpdate" --^ "The timestamp that the passphrase was last updated." & "createdAt" --^ "The timestamp that the wallet was created." & "assuranceLevel" --^ "The assurance level of the wallet." & "syncState" --^ "The sync state for this wallet." ) instance Arbitrary Wallet where arbitrary = Wallet <$> arbitrary <*> pure "My wallet" <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary deriveSafeBuildable ''Wallet instance BuildableSafeGen Wallet where buildSafeGen sl Wallet{..} = bprint ("{" %" id="%buildSafe sl %" name="%buildSafe sl %" balance="%buildSafe sl %" }") walId walName walBalance instance Buildable [Wallet] where build = bprint listJson data MnemonicBalance = MnemonicBalance { mbWalletId :: !WalletId , mbBalance :: !(Maybe Integer) } deriving (Eq, Ord, Show, Generic) deriveJSON Aeson.defaultOptions ''MnemonicBalance instance ToSchema MnemonicBalance where declareNamedSchema = genericSchemaDroppingPrefix "mb" (\(--^) props -> props & "walletId" --^ "Unique wallet identifier." & "balance" ^ " Current balance , in . " ) instance Arbitrary MnemonicBalance where arbitrary = MnemonicBalance <$> arbitrary <*> arbitrary deriveSafeBuildable ''MnemonicBalance instance BuildableSafeGen MnemonicBalance where buildSafeGen sl MnemonicBalance{mbWalletId,mbBalance} = case mbBalance of Just bal -> bprint ("{" %" id="%buildSafe sl %" balance="%build %" }") mbWalletId bal Nothing -> bprint ("{" %" id="%buildSafe sl %" }") mbWalletId instance Example MnemonicBalance where example = do MnemonicBalance <$> example <*> (pure $ Just 1000000) instance ToSchema PublicKey where declareNamedSchema _ = pure $ NamedSchema (Just "PublicKey") $ mempty & type_ ?~ SwaggerString & format ?~ "base58" -------------------------------------------------------------------------------- -- Addresses -------------------------------------------------------------------------------- -- | Whether an address is valid or not. newtype AddressValidity = AddressValidity { isValid :: Bool } deriving (Eq, Show, Generic) deriveJSON Aeson.defaultOptions ''AddressValidity instance ToSchema AddressValidity where declareNamedSchema = genericSchemaDroppingPrefix "is" (const identity) instance Arbitrary AddressValidity where arbitrary = AddressValidity <$> arbitrary deriveSafeBuildable ''AddressValidity instance BuildableSafeGen AddressValidity where buildSafeGen _ AddressValidity{..} = bprint ("{ valid="%build%" }") isValid -- | An address is either recognised as "ours" or not. An address that is not -- recognised may still be ours e.g. an address generated by another wallet instance -- will not be considered "ours" until the relevant transaction is confirmed. -- -- In other words, `AddressAmbiguousOwnership` makes an inconclusive statement about -- an address, whereas `AddressOwnership` is unambiguous. data AddressOwnership = AddressIsOurs | AddressAmbiguousOwnership deriving (Show, Eq, Generic, Ord) instance ToJSON (V1 AddressOwnership) where toJSON = genericToJSON optsADTCamelCase . unV1 instance FromJSON (V1 AddressOwnership) where parseJSON = fmap V1 . genericParseJSON optsADTCamelCase instance ToSchema (V1 AddressOwnership) where declareNamedSchema _ = pure $ NamedSchema (Just "V1AddressOwnership") $ mempty & type_ ?~ SwaggerString & enum_ ?~ ["isOurs", "ambiguousOwnership"] instance Arbitrary (V1 AddressOwnership) where arbitrary = fmap V1 $ oneof [ pure AddressIsOurs , pure AddressAmbiguousOwnership ] -- | Address with associated metadata locating it in an account in a wallet. data WAddressMeta = WAddressMeta { _wamWalletId :: !WalletId , _wamAccountIndex :: !Word32 , _wamAddressIndex :: !Word32 , _wamAddress :: !(V1 Core.Address) } deriving (Eq, Ord, Show, Generic, Typeable) instance Hashable WAddressMeta instance NFData WAddressMeta instance Buildable WAddressMeta where build WAddressMeta{..} = bprint (build%"@"%build%"@"%build%" ("%build%")") _wamWalletId _wamAccountIndex _wamAddressIndex _wamAddress -------------------------------------------------------------------------------- -- Accounts -------------------------------------------------------------------------------- -- | Summary about single address. data WalletAddress = WalletAddress { addrId :: !(V1 Core.Address) , addrUsed :: !Bool , addrChangeAddress :: !Bool , addrOwnership :: !(V1 AddressOwnership) } deriving (Show, Eq, Generic, Ord) deriveJSON Aeson.defaultOptions ''WalletAddress instance ToSchema WalletAddress where declareNamedSchema = genericSchemaDroppingPrefix "addr" (\(--^) props -> props & ("id" --^ "Actual address.") & ("used" --^ "True if this address has been used.") & ("changeAddress" --^ "True if this address stores change from a previous transaction.") & ("ownership" --^ "'isOurs' if this address is recognised as ours, 'ambiguousOwnership' if the node doesn't have information to make a unambiguous statement.") ) instance Arbitrary WalletAddress where arbitrary = WalletAddress <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary newtype AccountIndex = AccountIndex { getAccIndex :: Word32 } deriving (Show, Eq, Ord, Generic) newtype AccountIndexError = AccountIndexError Word32 deriving (Eq, Show) instance Buildable AccountIndexError where build (AccountIndexError i) = bprint ("Account index should be in range ["%int%".."%int%"], but "%int%" was provided.") (getAccIndex minBound) (getAccIndex maxBound) i mkAccountIndex :: Word32 -> Either AccountIndexError AccountIndex mkAccountIndex index | index >= getAccIndex minBound = Right $ AccountIndex index | otherwise = Left $ AccountIndexError index mkAccountIndexM :: MonadFail m => Word32 -> m AccountIndex mkAccountIndexM = either (fail . toString . sformat build) pure . mkAccountIndex unsafeMkAccountIndex :: Word32 -> AccountIndex unsafeMkAccountIndex = either (error . sformat build) identity . mkAccountIndex instance Bounded AccountIndex where -- NOTE: minimum for hardened key. See -309 minBound = AccountIndex 2147483648 maxBound = AccountIndex maxBound instance ToJSON AccountIndex where toJSON = toJSON . getAccIndex instance FromJSON AccountIndex where parseJSON = mkAccountIndexM <=< parseJSON instance Arbitrary AccountIndex where arbitrary = AccountIndex <$> choose (getAccIndex minBound, getAccIndex maxBound) deriveSafeBuildable ''AccountIndex -- Nothing secret to redact for a AccountIndex. instance BuildableSafeGen AccountIndex where buildSafeGen _ = bprint build . getAccIndex instance ToParamSchema AccountIndex where toParamSchema _ = mempty & type_ ?~ SwaggerNumber & minimum_ .~ Just (fromIntegral $ getAccIndex minBound) & maximum_ .~ Just (fromIntegral $ getAccIndex maxBound) instance ToSchema AccountIndex where declareNamedSchema = pure . paramSchemaToNamedSchema defaultSchemaOptions instance FromHttpApiData AccountIndex where parseQueryParam = first (sformat build) . mkAccountIndex <=< parseQueryParam instance ToHttpApiData AccountIndex where toQueryParam = fromString . show . getAccIndex -- | A wallet 'Account'. data Account = Account { accIndex :: !AccountIndex , accAddresses :: ![WalletAddress] , accAmount :: !(V1 Core.Coin) , accName :: !Text , accWalletId :: !WalletId } deriving (Show, Ord, Eq, Generic) -- IxSet indices -- | Datatype wrapping addresses for per - field endpoint newtype AccountAddresses = AccountAddresses { acaAddresses :: [WalletAddress] } deriving (Show, Ord, Eq, Generic) | Datatype wrapping balance for per - field endpoint newtype AccountBalance = AccountBalance { acbAmount :: V1 Core.Coin } deriving (Show, Ord, Eq, Generic) accountsHaveSameId :: Account -> Account -> Bool accountsHaveSameId a b = accWalletId a == accWalletId b && accIndex a == accIndex b deriveJSON Aeson.defaultOptions ''Account deriveJSON Aeson.defaultOptions ''AccountAddresses deriveJSON Aeson.defaultOptions ''AccountBalance instance ToSchema Account where declareNamedSchema = genericSchemaDroppingPrefix "acc" (\(--^) props -> props & ("index" --^ "Account's index in the wallet, starting at 0.") & ("addresses" --^ "Public addresses pointing to this account.") ^ " Available funds , in . " ) & ("name" --^ "Account's name.") & ("walletId" --^ "Id of the wallet this account belongs to.") ) instance ToSchema AccountAddresses where declareNamedSchema = genericSchemaDroppingPrefix "aca" (\(--^) props -> props & ("addresses" --^ "Public addresses pointing to this account.") ) instance ToSchema AccountBalance where declareNamedSchema = genericSchemaDroppingPrefix "acb" (\(--^) props -> props ^ " Available funds , in . " ) ) instance Arbitrary Account where arbitrary = Account <$> arbitrary <*> arbitrary <*> arbitrary <*> pure "My account" <*> arbitrary instance Arbitrary AccountAddresses where arbitrary = AccountAddresses <$> arbitrary instance Arbitrary AccountBalance where arbitrary = AccountBalance <$> arbitrary deriveSafeBuildable ''Account instance BuildableSafeGen Account where buildSafeGen sl Account{..} = bprint ("{" %" index="%buildSafe sl %" name="%buildSafe sl %" addresses="%buildSafe sl %" amount="%buildSafe sl %" walletId="%buildSafe sl %" }") accIndex accName accAddresses accAmount accWalletId instance Buildable AccountAddresses where build = bprint listJson . acaAddresses instance Buildable AccountBalance where build = bprint build . acbAmount instance Buildable [Account] where build = bprint listJson -- | Account Update data AccountUpdate = AccountUpdate { uaccName :: !Text } deriving (Show, Eq, Generic) deriveJSON Aeson.defaultOptions ''AccountUpdate instance ToSchema AccountUpdate where declareNamedSchema = genericSchemaDroppingPrefix "uacc" (\(--^) props -> props & ("name" --^ "New account's name.") ) instance Arbitrary AccountUpdate where arbitrary = AccountUpdate <$> pure "myAccount" deriveSafeBuildable ''AccountUpdate instance BuildableSafeGen AccountUpdate where buildSafeGen sl AccountUpdate{..} = bprint ("{ name="%buildSafe sl%" }") uaccName -- | New Account data NewAccount = NewAccount { naccSpendingPassword :: !(Maybe SpendingPassword) , naccName :: !Text } deriving (Show, Eq, Generic) deriveJSON Aeson.defaultOptions ''NewAccount instance Arbitrary NewAccount where arbitrary = NewAccount <$> arbitrary <*> arbitrary instance ToSchema NewAccount where declareNamedSchema = genericSchemaDroppingPrefix "nacc" (\(--^) props -> props & ("spendingPassword" --^ "Wallet's protection password, required if defined.") & ("name" --^ "Account's name.") ) deriveSafeBuildable ''NewAccount instance BuildableSafeGen NewAccount where buildSafeGen sl NewAccount{..} = bprint ("{" %" spendingPassword="%(buildSafeMaybe mempty sl) %" name="%buildSafe sl %" }") naccSpendingPassword naccName deriveSafeBuildable ''WalletAddress instance BuildableSafeGen WalletAddress where buildSafeGen sl WalletAddress{..} = bprint ("{" %" id="%buildSafe sl %" used="%build %" changeAddress="%build %" }") addrId addrUsed addrChangeAddress instance Buildable [WalletAddress] where build = bprint listJson instance Buildable [V1 Core.Address] where build = bprint listJson data BatchImportResult a = BatchImportResult { aimTotalSuccess :: !Natural , aimFailures :: ![a] } deriving (Show, Ord, Eq, Generic) instance Buildable (BatchImportResult a) where build res = bprint ("BatchImportResult (success:"%int%", failures:"%int%")") (aimTotalSuccess res) (length $ aimFailures res) instance ToJSON a => ToJSON (BatchImportResult a) where toJSON = genericToJSON Aeson.defaultOptions instance FromJSON a => FromJSON (BatchImportResult a) where parseJSON = genericParseJSON Aeson.defaultOptions instance (ToJSON a, ToSchema a, Arbitrary a) => ToSchema (BatchImportResult a) where declareNamedSchema = genericSchemaDroppingPrefix "aim" (\(--^) props -> props & ("totalSuccess" --^ "Total number of entities successfully imported") & ("failures" --^ "Entities failed to be imported, if any") ) instance Arbitrary a => Arbitrary (BatchImportResult a) where arbitrary = BatchImportResult <$> arbitrary <*> scale (`mod` 3) arbitrary -- NOTE Small list instance Arbitrary a => Example (BatchImportResult a) instance Semigroup (BatchImportResult a) where (BatchImportResult a0 b0) <> (BatchImportResult a1 b1) = BatchImportResult (a0 + a1) (b0 <> b1) instance Monoid (BatchImportResult a) where mempty = BatchImportResult 0 mempty -- | Create a new Address data NewAddress = NewAddress { newaddrSpendingPassword :: !(Maybe SpendingPassword) , newaddrAccountIndex :: !AccountIndex , newaddrWalletId :: !WalletId } deriving (Show, Eq, Generic) deriveJSON Aeson.defaultOptions ''NewAddress instance ToSchema NewAddress where declareNamedSchema = genericSchemaDroppingPrefix "newaddr" (\(--^) props -> props & ("spendingPassword" --^ "Wallet's protection password, required if defined.") ^ " Target account 's index to store this address in . " ) & ("walletId" --^ "Corresponding wallet identifier.") ) instance Arbitrary NewAddress where arbitrary = NewAddress <$> arbitrary <*> arbitrary <*> arbitrary deriveSafeBuildable ''NewAddress instance BuildableSafeGen NewAddress where buildSafeGen sl NewAddress{..} = bprint("{" %" spendingPassword="%(buildSafeMaybe mempty sl) %" accountIndex="%buildSafe sl %" walletId="%buildSafe sl %" }") newaddrSpendingPassword newaddrAccountIndex newaddrWalletId -- | A type incapsulating a password update request. data PasswordUpdate = PasswordUpdate { pwdOld :: !SpendingPassword , pwdNew :: !SpendingPassword } deriving (Show, Eq, Generic) deriveJSON Aeson.defaultOptions ''PasswordUpdate instance ToSchema PasswordUpdate where declareNamedSchema = genericSchemaDroppingPrefix "pwd" (\(--^) props -> props & ("old" --^ "Old password.") & ("new" --^ "New passowrd.") ) instance Arbitrary PasswordUpdate where arbitrary = PasswordUpdate <$> arbitrary <*> arbitrary deriveSafeBuildable ''PasswordUpdate instance BuildableSafeGen PasswordUpdate where buildSafeGen sl PasswordUpdate{..} = bprint("{" %" old="%buildSafe sl %" new="%buildSafe sl %" }") pwdOld pwdNew | ' EstimatedFees ' represents the fees which would be generated -- for a 'Payment' in case the latter would actually be performed. data EstimatedFees = EstimatedFees { feeEstimatedAmount :: !(V1 Core.Coin) } deriving (Show, Eq, Generic) deriveJSON Aeson.defaultOptions ''EstimatedFees instance ToSchema EstimatedFees where declareNamedSchema = genericSchemaDroppingPrefix "fee" (\(--^) props -> props ^ " Estimated fees , in . " ) ) instance Arbitrary EstimatedFees where arbitrary = EstimatedFees <$> arbitrary deriveSafeBuildable ''EstimatedFees instance BuildableSafeGen EstimatedFees where buildSafeGen sl EstimatedFees{..} = bprint("{" %" estimatedAmount="%buildSafe sl %" }") feeEstimatedAmount -- | Maps an 'Address' to some 'Coin's, and it's -- typically used to specify where to send money during a 'Payment'. data PaymentDistribution = PaymentDistribution { pdAddress :: !(V1 Core.Address) , pdAmount :: !(V1 Core.Coin) } deriving (Show, Ord, Eq, Generic) deriveJSON Aeson.defaultOptions ''PaymentDistribution instance ToSchema PaymentDistribution where declareNamedSchema = genericSchemaDroppingPrefix "pd" (\(--^) props -> props & ("address" --^ "Address to map coins to.") ^ " Amount of coin to bind , in . " ) ) instance Arbitrary PaymentDistribution where arbitrary = PaymentDistribution <$> arbitrary <*> arbitrary deriveSafeBuildable ''PaymentDistribution instance BuildableSafeGen PaymentDistribution where buildSafeGen sl PaymentDistribution{..} = bprint ("{" %" address="%buildSafe sl %" amount="%buildSafe sl %" }") pdAddress pdAmount | A ' PaymentSource ' encapsulate two essentially piece of data to reach for some funds : a ' WalletId ' and an ' AccountIndex ' within it . data PaymentSource = PaymentSource { psWalletId :: !WalletId , psAccountIndex :: !AccountIndex } deriving (Show, Ord, Eq, Generic) deriveJSON Aeson.defaultOptions ''PaymentSource instance ToSchema PaymentSource where declareNamedSchema = genericSchemaDroppingPrefix "ps" (\(--^) props -> props ^ " Target wallet identifier to reach . " ) & ("accountIndex" --^ "Corresponding account's index on the wallet.") ) instance Arbitrary PaymentSource where arbitrary = PaymentSource <$> arbitrary <*> arbitrary deriveSafeBuildable ''PaymentSource instance BuildableSafeGen PaymentSource where buildSafeGen sl PaymentSource{..} = bprint ("{" %" walletId="%buildSafe sl %" accountIndex="%buildSafe sl %" }") psWalletId psAccountIndex | A ' Payment ' from one source account to one or more ' PaymentDistribution'(s ) . data Payment = Payment { pmtSource :: !PaymentSource , pmtDestinations :: !(NonEmpty PaymentDistribution) , pmtGroupingPolicy :: !(Maybe (V1 Core.InputSelectionPolicy)) , pmtSpendingPassword :: !(Maybe SpendingPassword) } deriving (Show, Eq, Generic) instance ToJSON (V1 Core.InputSelectionPolicy) where toJSON (V1 Core.OptimizeForSecurity) = String "OptimizeForSecurity" toJSON (V1 Core.OptimizeForHighThroughput) = String "OptimizeForHighThroughput" instance FromJSON (V1 Core.InputSelectionPolicy) where parseJSON (String "OptimizeForSecurity") = pure (V1 Core.OptimizeForSecurity) parseJSON (String "OptimizeForHighThroughput") = pure (V1 Core.OptimizeForHighThroughput) parseJSON x = typeMismatch "Not a valid InputSelectionPolicy" x instance ToSchema (V1 Core.InputSelectionPolicy) where declareNamedSchema _ = pure $ NamedSchema (Just "V1InputSelectionPolicy") $ mempty & type_ ?~ SwaggerString & enum_ ?~ ["OptimizeForSecurity", "OptimizeForHighThroughput"] instance Arbitrary (V1 Core.InputSelectionPolicy) where arbitrary = fmap V1 arbitrary deriveJSON Aeson.defaultOptions ''Payment instance Arbitrary Payment where arbitrary = Payment <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary instance ToSchema Payment where declareNamedSchema = genericSchemaDroppingPrefix "pmt" (\(--^) props -> props & ("source" --^ "Source for the payment.") ^ " One or more destinations for the payment . " ) & ("groupingPolicy" --^ "Optional strategy to use for selecting the transaction inputs.") & ("spendingPassword" --^ "Wallet's protection password, required to spend funds if defined.") ) deriveSafeBuildable ''Payment instance BuildableSafeGen Payment where buildSafeGen sl (Payment{..}) = bprint ("{" %" source="%buildSafe sl %" destinations="%buildSafeList sl %" groupingPolicty="%build %" spendingPassword="%(buildSafeMaybe mempty sl) %" }") pmtSource (toList pmtDestinations) pmtGroupingPolicy pmtSpendingPassword ---------------------------------------------------------------------------- -- TxId ---------------------------------------------------------------------------- instance Arbitrary (V1 Txp.TxId) where arbitrary = V1 <$> arbitrary instance ToJSON (V1 Txp.TxId) where toJSON (V1 t) = String (sformat hashHexF t) instance FromJSON (V1 Txp.TxId) where parseJSON = withText "TxId" $ \t -> do case decodeHash t of Left err -> fail $ "Failed to parse transaction ID: " <> toString err Right a -> pure (V1 a) instance FromHttpApiData (V1 Txp.TxId) where parseQueryParam = fmap (fmap V1) decodeHash instance ToHttpApiData (V1 Txp.TxId) where toQueryParam (V1 txId) = sformat hashHexF txId instance ToSchema (V1 Txp.TxId) where declareNamedSchema _ = declareNamedSchema (Proxy @Text) ---------------------------------------------------------------------------- -- Transaction types ---------------------------------------------------------------------------- -- | The 'Transaction' type. data TransactionType = LocalTransaction -- ^ This transaction is local, which means all the inputs -- and all the outputs belongs to the wallet from which the -- transaction was originated. | ForeignTransaction -- ^ This transaction is not local to this wallet. deriving (Show, Ord, Eq, Enum, Bounded) instance Arbitrary TransactionType where arbitrary = elements [minBound .. maxBound] -- Drops the @Transaction@ suffix. deriveJSON defaultOptions { A.constructorTagModifier = reverse . drop 11 . reverse . map C.toLower } ''TransactionType instance ToSchema TransactionType where declareNamedSchema _ = pure $ NamedSchema (Just "TransactionType") $ mempty & type_ ?~ SwaggerString & enum_ ?~ ["local", "foreign"] & description ?~ mconcat [ "A transaction is 'local' if all the inputs and outputs " , "belong to the current wallet. A transaction is foreign " , "if the transaction is not local to this wallet." ] deriveSafeBuildable ''TransactionType instance BuildableSafeGen TransactionType where buildSafeGen _ LocalTransaction = "local" buildSafeGen _ ForeignTransaction = "foreign" -- | The 'Transaction' @direction@ data TransactionDirection = IncomingTransaction -- ^ This represents an incoming transactions. | OutgoingTransaction -- ^ This qualifies external transactions. deriving (Show, Ord, Eq, Enum, Bounded) instance Arbitrary TransactionDirection where arbitrary = elements [minBound .. maxBound] -- Drops the @Transaction@ suffix. deriveJSON defaultOptions { A.constructorTagModifier = reverse . drop 11 . reverse . map C.toLower } ''TransactionDirection instance ToSchema TransactionDirection where declareNamedSchema _ = pure $ NamedSchema (Just "TransactionDirection") $ mempty & type_ ?~ SwaggerString & enum_ ?~ ["outgoing", "incoming"] | This is an information - less variant of ' PtxCondition ' . data TransactionStatus = Applying | InNewestBlocks | Persisted | WontApply | Creating deriving (Eq, Show, Ord) allTransactionStatuses :: [TransactionStatus] allTransactionStatuses = [Applying, InNewestBlocks, Persisted, WontApply, Creating] transactionStatusToText :: TransactionStatus -> Text transactionStatusToText x = case x of Applying {} -> "applying" InNewestBlocks {} -> "inNewestBlocks" Persisted {} -> "persisted" WontApply {} -> "wontApply" Creating {} -> "creating" instance ToJSON TransactionStatus where toJSON x = object [ "tag" .= transactionStatusToText x , "data" .= Object mempty ] instance ToSchema TransactionStatus where declareNamedSchema _ = pure $ NamedSchema (Just "TransactionStatus") $ mempty & type_ ?~ SwaggerObject & required .~ ["tag", "data"] & properties .~ (mempty & at "tag" ?~ Inline (mempty & type_ ?~ SwaggerString & enum_ ?~ map (String . transactionStatusToText) allTransactionStatuses ) & at "data" ?~ Inline (mempty & type_ ?~ SwaggerObject ) ) instance FromJSON TransactionStatus where parseJSON = withObject "TransactionStatus" $ \o -> do tag <- o .: "tag" case tag of "applying" -> pure Applying "inNewestBlocks" -> pure InNewestBlocks "persisted" -> pure Persisted "wontApply" -> pure WontApply "creating" -> pure Creating _ -> fail $ "Couldn't parse out of " ++ toString (tag :: Text) instance Arbitrary TransactionStatus where arbitrary = elements allTransactionStatuses deriveSafeBuildable ''TransactionDirection instance BuildableSafeGen TransactionDirection where buildSafeGen _ IncomingTransaction = "incoming" buildSafeGen _ OutgoingTransaction = "outgoing" -- | A 'Wallet''s 'Transaction'. data Transaction = Transaction { txId :: !(V1 Txp.TxId) , txConfirmations :: !Word , txAmount :: !(V1 Core.Coin) , txInputs :: !(NonEmpty PaymentDistribution) , txOutputs :: !(NonEmpty PaymentDistribution) -- ^ The output money distribution. , txType :: !TransactionType -- ^ The type for this transaction (e.g local, foreign, etc). , txDirection :: !TransactionDirection -- ^ The direction for this transaction (e.g incoming, outgoing). , txCreationTime :: !(V1 Core.Timestamp) -- ^ The time when transaction was created. , txStatus :: !TransactionStatus } deriving (Show, Ord, Eq, Generic) deriveJSON Aeson.defaultOptions ''Transaction instance ToSchema Transaction where declareNamedSchema = genericSchemaDroppingPrefix "tx" (\(--^) props -> props ^ " Transaction 's i d. " ) & ("confirmations" --^ "Number of confirmations.") ^ " Coins moved as part of the transaction , in . " ) ^ " One or more input money distributions . " ) ^ " One or more ouputs money distributions . " ) & ("type" --^ "Whether the transaction is entirely local or foreign.") & ("direction" --^ "Direction for this transaction.") & ("creationTime" --^ "Timestamp indicating when the transaction was created.") & ("status" --^ "Shows whether or not the transaction is accepted.") ) instance Arbitrary Transaction where arbitrary = Transaction <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary deriveSafeBuildable ''Transaction instance BuildableSafeGen Transaction where buildSafeGen sl Transaction{..} = bprint ("{" %" id="%buildSafe sl %" confirmations="%build %" amount="%buildSafe sl %" inputs="%buildSafeList sl %" outputs="%buildSafeList sl %" type="%buildSafe sl %" direction"%buildSafe sl %" }") txId txConfirmations txAmount (toList txInputs) (toList txOutputs) txType txDirection instance Buildable [Transaction] where build = bprint listJson -- | A type representing an upcoming wallet update. data WalletSoftwareUpdate = WalletSoftwareUpdate { updSoftwareVersion :: !Text , updBlockchainVersion :: !Text , updScriptVersion :: !Int -- Other types omitted for now. } deriving (Show, Eq, Generic) deriveJSON Aeson.defaultOptions ''WalletSoftwareUpdate instance ToSchema WalletSoftwareUpdate where declareNamedSchema = genericSchemaDroppingPrefix "upd" (\(--^) props -> props & ("softwareVersion" --^ "Current software (wallet) version.") & ("blockchainVersion" --^ "Version of the underlying blockchain.") & ("scriptVersion" --^ "Update script version.") ) instance Arbitrary WalletSoftwareUpdate where arbitrary = WalletSoftwareUpdate <$> arbitrary <*> arbitrary <*> fmap getPositive arbitrary deriveSafeBuildable ''WalletSoftwareUpdate instance BuildableSafeGen WalletSoftwareUpdate where buildSafeGen _ WalletSoftwareUpdate{..} = bprint("{" %" softwareVersion="%build %" blockchainVersion="%build %" scriptVersion="%build %" }") updSoftwareVersion updBlockchainVersion updScriptVersion -- | A type encapsulating enough information to import a wallet from a -- backup file. data WalletImport = WalletImport { wiSpendingPassword :: !(Maybe SpendingPassword) , wiFilePath :: !FilePath } deriving (Show, Eq, Generic) deriveJSON Aeson.defaultOptions ''WalletImport instance ToSchema WalletImport where declareNamedSchema = genericSchemaDroppingPrefix "wi" (\(--^) props -> props & ("spendingPassword" --^ "An optional spending password to set for the imported wallet.") ^ " The path to the .key file holding the backup . " ) ) instance Arbitrary WalletImport where arbitrary = WalletImport <$> arbitrary <*> arbitrary deriveSafeBuildable ''WalletImport instance BuildableSafeGen WalletImport where buildSafeGen sl WalletImport{..} = bprint("{" %" spendingPassword="%build %" filePath="%build %" }") (maybe "null" (buildSafeGen sl) wiSpendingPassword) wiFilePath -- | A redemption mnemonic. newtype RedemptionMnemonic = RedemptionMnemonic { unRedemptionMnemonic :: Mnemonic 9 } deriving stock (Eq, Show, Generic) deriving newtype (ToJSON, FromJSON, Arbitrary) instance ToSchema RedemptionMnemonic where declareNamedSchema _ = pure $ NamedSchema (Just "RedemptionMnemonic") (toSchema (Proxy @(Mnemonic 9))) -- | A shielded redemption code. newtype ShieldedRedemptionCode = ShieldedRedemptionCode { unShieldedRedemptionCode :: Text } deriving (Eq, Show, Generic) deriving newtype (ToJSON, FromJSON) -- | This instance could probably be improved. A 'ShieldedRedemptionCode' is -- a hash of the redemption key. instance Arbitrary ShieldedRedemptionCode where arbitrary = ShieldedRedemptionCode <$> arbitrary instance ToSchema ShieldedRedemptionCode where declareNamedSchema _ = pure $ NamedSchema (Just "ShieldedRedemptionCode") $ mempty & type_ ?~ SwaggerString deriveSafeBuildable ''ShieldedRedemptionCode instance BuildableSafeGen ShieldedRedemptionCode where buildSafeGen _ _ = bprint "<shielded redemption code>" | The request body for redeeming some . data Redemption = Redemption { redemptionRedemptionCode :: ShieldedRedemptionCode ^ The redemption code associated with the to redeem . , redemptionMnemonic :: Maybe RedemptionMnemonic -- ^ An optional mnemonic. This mnemonic was included with paper -- certificates, and the presence of this field indicates that we're -- doing a paper vend. , redemptionSpendingPassword :: SpendingPassword -- ^ The user must provide a spending password that matches the wallet that -- will be receiving the redemption funds. , redemptionWalletId :: WalletId -- ^ Redeem to this wallet , redemptionAccountIndex :: AccountIndex -- ^ Redeem to this account index in the wallet } deriving (Eq, Show, Generic) deriveSafeBuildable ''Redemption instance BuildableSafeGen Redemption where buildSafeGen sl r = bprint ("{" %" redemptionCode="%buildSafe sl %" mnemonic=<mnemonic>" %" spendingPassword="%buildSafe sl %" }") (redemptionRedemptionCode r) (redemptionSpendingPassword r) deriveJSON Aeson.defaultOptions ''Redemption instance ToSchema Redemption where declareNamedSchema = genericSchemaDroppingPrefix "redemption" (\(--^) props -> props & "redemptionCode" ^ " The redemption code associated with the to redeem . " & "mnemonic" --^ ( "An optional mnemonic. This must be provided for a paper " <> "certificate redemption." ) & "spendingPassword" --^ ( "An optional spending password. This must match the password " <> "for the provided wallet ID and account index." ) ) instance Arbitrary Redemption where arbitrary = Redemption <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary -- -- POST/PUT requests isomorphisms -- type family Update (original :: *) :: * where Update Wallet = WalletUpdate Update Account = AccountUpdate Update WalletAddress = () -- read-only type family New (original :: *) :: * where New Wallet = NewWallet New Account = NewAccount New WalletAddress = NewAddress type CaptureWalletId = Capture "walletId" WalletId type CaptureAccountId = Capture "accountId" AccountIndex -- -- Example typeclass instances -- instance Example Core.Address instance Example AccountIndex instance Example AccountBalance instance Example AccountAddresses instance Example WalletId instance Example AssuranceLevel instance Example LocalTimeDifference instance Example PaymentDistribution instance Example AccountUpdate instance Example Wallet instance Example WalletUpdate instance Example WalletOperation instance Example PasswordUpdate instance Example EstimatedFees instance Example Transaction instance Example WalletSoftwareUpdate instance Example WalletAddress instance Example NewAccount instance Example AddressValidity instance Example NewAddress instance Example ShieldedRedemptionCode instance Example (V1 Core.PassPhrase) instance Example (V1 Core.Coin) | We have a specific ' Example ' instance for ' ' because we want -- to control the length of the examples. It is possible for the encoded length to become huge , up to 1000 + bytes , if the ' UnsafeMultiKeyDistr ' constructor -- is used. We do not use this constructor, which keeps the address between -- ~80-150 bytes long. instance Example (V1 Core.Address) where example = fmap V1 . Core.makeAddress <$> arbitrary <*> arbitraryAttributes where arbitraryAttributes = Core.AddrAttributes <$> arbitrary <*> oneof [ pure Core.BootstrapEraDistr , Core.SingleKeyDistr <$> arbitrary ] <*> arbitrary instance Example BackupPhrase where example = pure (BackupPhrase def) instance Example Core.InputSelectionPolicy where example = pure Core.OptimizeForHighThroughput instance Example (V1 Core.InputSelectionPolicy) where example = pure (V1 Core.OptimizeForHighThroughput) instance Example Account where example = Account <$> example <*> example -- NOTE: this will produce non empty list <*> example <*> pure "My account" <*> example instance Example NewWallet where example = NewWallet <$> example <*> example -- Note: will produce `Just a` <*> example <*> pure "My Wallet" <*> example instance Example PublicKey where example = PublicKey <$> pure xpub where xpub = rights [ CC.xpub . fromJust . decodeBase58 bitcoinAlphabet . encodeUtf8 $ encodedPublicKey ] !! 0 encodedPublicKey :: Text encodedPublicKey = "bNfWjshJG9xxy6VkpV2KurwGah3jQWjGb4QveDGZteaCwupdKWAi371r8uS5yFCny5i5EQuSNSLKqvRHmWEoHe45pZ" instance Example PaymentSource where example = PaymentSource <$> example <*> example instance Example Payment where example = Payment <$> example <*> example <*> example -- TODO: will produce `Just groupingPolicy` <*> example instance Example Redemption where example = Redemption <$> example <*> pure Nothing <*> example <*> example <*> example instance Example WalletImport where example = WalletImport <$> example <*> pure "/Users/foo/Documents/wallet_to_import.key" -- -- Wallet Errors -- -- | Details about what 'NotEnoughMoney' means data ErrNotEnoughMoney -- | UTxO exhausted whilst trying to pick inputs to cover remaining fee = ErrCannotCoverFee -- | UTxO exhausted during input selection -- We record the available balance of the UTxO | ErrAvailableBalanceIsInsufficient Int deriving (Eq, Show, Generic) instance Buildable ErrNotEnoughMoney where build = \case ErrCannotCoverFee -> bprint "Not enough coins to cover fee." ErrAvailableBalanceIsInsufficient _ -> bprint "Not enough available coins to proceed." instance ToJSON ErrNotEnoughMoney where toJSON = \case e@ErrCannotCoverFee -> object [ "msg" .= sformat build e ] e@(ErrAvailableBalanceIsInsufficient balance) -> object [ "msg" .= sformat build e , "availableBalance" .= balance ] instance FromJSON ErrNotEnoughMoney where parseJSON v = withObject "AvailableBalanceIsInsufficient" availableBalanceIsInsufficientParser v <|> withObject "CannotCoverFee" cannotCoverFeeParser v where cannotCoverFeeParser :: Object -> Parser ErrNotEnoughMoney cannotCoverFeeParser o = do msg <- o .: "msg" when (msg /= sformat build ErrCannotCoverFee) mempty pure ErrCannotCoverFee availableBalanceIsInsufficientParser :: Object -> Parser ErrNotEnoughMoney availableBalanceIsInsufficientParser o = do msg <- o .: "msg" when (msg /= sformat build (ErrAvailableBalanceIsInsufficient 0)) mempty ErrAvailableBalanceIsInsufficient <$> (o .: "availableBalance") data ErrUtxoNotEnoughFragmented = ErrUtxoNotEnoughFragmented { theMissingUtxos :: !Int , theHelp :: !Text } deriving (Eq, Generic, Show) msgUtxoNotEnoughFragmented :: Text msgUtxoNotEnoughFragmented = "Utxo is not enough fragmented to handle the number of outputs of this transaction. Query /api/v1/wallets/{walletId}/statistics/utxos endpoint for more information" deriveJSON Aeson.defaultOptions ''ErrUtxoNotEnoughFragmented instance Buildable ErrUtxoNotEnoughFragmented where build (ErrUtxoNotEnoughFragmented missingUtxos _ ) = bprint ("Missing "%build%" utxo(s) to accommodate all outputs of the transaction") missingUtxos -- | Type representing any error which might be thrown by wallet. -- Errors are represented in JSON in the JSend format ( < > ): -- ``` -- { -- "status": "error" -- "message" : <constr_name>, -- "diagnostic" : <data> -- } -- ``` where ` < constr_name > ` is a string containing name of error 's constructor ( ) , -- and `<data>` is an object containing additional error data. -- Additional data contains constructor fields, field names are record field names without a ` we ` prefix , for ` OutputIsRedeem ` error " diagnostic " field will be the following : -- ``` -- { -- "address" : <address> -- } -- ``` -- -- Additional data in constructor should be represented as record fields. Otherwise TemplateHaskell will raise an error . -- If constructor does not have additional data ( like in case of ` WalletNotFound ` error ) , -- then "diagnostic" field will be empty object. -- -- TODO: change fields' types to actual Cardano core types, like `Coin` and `Address` data WalletError = -- | NotEnoughMoney weNeedMore NotEnoughMoney !ErrNotEnoughMoney -- | OutputIsRedeem weAddress | OutputIsRedeem !(V1 Core.Address) -- | UnknownError weMsg | UnknownError !Text | InvalidAddressFormat weMsg | InvalidAddressFormat !Text | WalletNotFound | WalletAlreadyExists !WalletId | AddressNotFound | TxFailedToStabilize | InvalidPublicKey !Text | UnsignedTxCreationError | TooBigTransaction -- ^ Size of transaction (in bytes) is greater than maximum. | SignedTxSubmitError !Text | TxRedemptionDepleted -- | TxSafeSignerNotFound weAddress | TxSafeSignerNotFound !(V1 Core.Address) -- | MissingRequiredParams requiredParams | MissingRequiredParams !(NonEmpty (Text, Text)) -- | WalletIsNotReadyToProcessPayments weStillRestoring | CannotCreateAddress !Text -- ^ Cannot create derivation path for new address (for external wallet). | WalletIsNotReadyToProcessPayments !SyncProgress -- ^ The @Wallet@ where a @Payment@ is being originated is not fully -- synced (its 'WalletSyncState' indicates it's either syncing or restoring ) and thus can not accept new @Payment@ requests . -- | NodeIsStillSyncing wenssStillSyncing | NodeIsStillSyncing !SyncPercentage -- ^ The backend couldn't process the incoming request as the underlying -- node is still syncing with the blockchain. | RequestThrottled !Word64 -- ^ The request has been throttled. The 'Word64' is a count of microseconds -- until the user should retry. | UtxoNotEnoughFragmented !ErrUtxoNotEnoughFragmented ^ available is not enough fragmented , ie . , there is more outputs of transaction than -- utxos deriving (Generic, Show, Eq) deriveGeneric ''WalletError instance Exception WalletError instance ToHttpErrorStatus WalletError instance ToJSON WalletError where toJSON = jsendErrorGenericToJSON instance FromJSON WalletError where parseJSON = jsendErrorGenericParseJSON instance Arbitrary WalletError where arbitrary = Gen.oneof [ NotEnoughMoney <$> Gen.oneof [ pure ErrCannotCoverFee , ErrAvailableBalanceIsInsufficient <$> Gen.choose (1, 1000) ] , OutputIsRedeem . V1 <$> arbitrary , UnknownError <$> arbitraryText , InvalidAddressFormat <$> arbitraryText , pure WalletNotFound , WalletAlreadyExists <$> arbitrary , pure AddressNotFound , InvalidPublicKey <$> arbitraryText , pure UnsignedTxCreationError , SignedTxSubmitError <$> arbitraryText , pure TooBigTransaction , pure TxFailedToStabilize , pure TxRedemptionDepleted , TxSafeSignerNotFound . V1 <$> arbitrary , MissingRequiredParams <$> Gen.oneof [ unsafeMkNonEmpty <$> Gen.vectorOf 1 arbitraryParam , unsafeMkNonEmpty <$> Gen.vectorOf 2 arbitraryParam , unsafeMkNonEmpty <$> Gen.vectorOf 3 arbitraryParam ] , WalletIsNotReadyToProcessPayments <$> arbitrary , NodeIsStillSyncing <$> arbitrary , CannotCreateAddress <$> arbitraryText , RequestThrottled <$> arbitrary , UtxoNotEnoughFragmented <$> Gen.oneof [ ErrUtxoNotEnoughFragmented <$> Gen.choose (1, 10) <*> arbitrary ] ] where arbitraryText :: Gen Text arbitraryText = toText . Gen.getASCIIString <$> arbitrary arbitraryParam :: Gen (Text, Text) arbitraryParam = (,) <$> arbitrary <*> arbitrary unsafeMkNonEmpty :: [a] -> NonEmpty a unsafeMkNonEmpty (h:q) = h :| q unsafeMkNonEmpty _ = error "unsafeMkNonEmpty called with empty list" -- | Give a short description of an error instance Buildable WalletError where build = \case NotEnoughMoney x -> bprint build x OutputIsRedeem _ -> bprint "One of the TX outputs is a redemption address." UnknownError _ -> bprint "Unexpected internal error." InvalidAddressFormat _ -> bprint "Provided address format is not valid." WalletNotFound -> bprint "Reference to an unexisting wallet was given." WalletAlreadyExists _ -> bprint "Can't create or restore a wallet. The wallet already exists." AddressNotFound -> bprint "Reference to an unexisting address was given." InvalidPublicKey _ -> bprint "Extended public key (for external wallet) is invalid." UnsignedTxCreationError -> bprint "Unable to create unsigned transaction for an external wallet." TooBigTransaction -> bprint "Transaction size is greater than 4096 bytes." SignedTxSubmitError _ -> bprint "Unable to submit externally-signed transaction." MissingRequiredParams _ -> bprint "Missing required parameters in the request payload." WalletIsNotReadyToProcessPayments _ -> bprint "This wallet is restoring, and it cannot send new transactions until restoration completes." NodeIsStillSyncing _ -> bprint "The node is still syncing with the blockchain, and cannot process the request yet." TxRedemptionDepleted -> bprint "The redemption address was already used." TxSafeSignerNotFound _ -> bprint "The safe signer at the specified address was not found." TxFailedToStabilize -> bprint "We were unable to find a set of inputs to satisfy this transaction." CannotCreateAddress _ -> bprint "Cannot create derivation path for new address, for external wallet." RequestThrottled _ -> bprint "You've made too many requests too soon, and this one was throttled." UtxoNotEnoughFragmented x -> bprint build x -- | Convert wallet errors to Servant errors instance ToServantError WalletError where declareServantError = \case NotEnoughMoney{} -> err403 OutputIsRedeem{} -> err403 UnknownError{} -> err500 WalletNotFound{} -> err404 WalletAlreadyExists{} -> err403 InvalidAddressFormat{} -> err401 AddressNotFound{} -> err404 InvalidPublicKey{} -> err400 UnsignedTxCreationError{} -> err500 TooBigTransaction{} -> err400 SignedTxSubmitError{} -> err500 MissingRequiredParams{} -> err400 WalletIsNotReadyToProcessPayments{} -> err403 NodeIsStillSyncing{} -> Precondition failed TxFailedToStabilize{} -> err500 TxRedemptionDepleted{} -> err400 TxSafeSignerNotFound{} -> err400 CannotCreateAddress{} -> err500 RequestThrottled{} -> err400 { errHTTPCode = 429 } UtxoNotEnoughFragmented{} -> err403 -- | Declare the key used to wrap the diagnostic payload, if any instance HasDiagnostic WalletError where getDiagnosticKey = \case NotEnoughMoney{} -> "details" OutputIsRedeem{} -> "address" UnknownError{} -> "msg" WalletNotFound{} -> noDiagnosticKey WalletAlreadyExists{} -> "walletId" InvalidAddressFormat{} -> "msg" AddressNotFound{} -> noDiagnosticKey InvalidPublicKey{} -> "msg" UnsignedTxCreationError{} -> noDiagnosticKey TooBigTransaction{} -> noDiagnosticKey SignedTxSubmitError{} -> "msg" MissingRequiredParams{} -> "params" WalletIsNotReadyToProcessPayments{} -> "stillRestoring" NodeIsStillSyncing{} -> "stillSyncing" TxFailedToStabilize{} -> noDiagnosticKey TxRedemptionDepleted{} -> noDiagnosticKey TxSafeSignerNotFound{} -> "address" CannotCreateAddress{} -> "msg" RequestThrottled{} -> "microsecondsUntilRetry" UtxoNotEnoughFragmented{} -> "details"
null
https://raw.githubusercontent.com/input-output-hk/cardano-sl/1499214d93767b703b9599369a431e67d83f10a2/wallet/src/Cardano/Wallet/API/V1/Types.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE ExplicitNamespaces # # LANGUAGE OverloadedStrings # # LANGUAGE PolyKinds # # LANGUAGE TemplateHaskell # The hlint parser fails on the `pattern` function, so we disable the language extension here. # LANGUAGE NoPatternSynonyms # * Swagger & REST-related types * Domain-specific types * Wallets * Addresses * Accounts * Addresses * Payments * Updates * Importing a wallet from a backup * Settings * Some types for the API * Core re-exports * Wallet Errors | Declare generic schema, while documenting properties For instance: { myDataField1 :: String } deriving (Generic) declareNamedSchema = genericSchemaDroppingPrefix "myData" (\(--^) props -> props & ("field1" --^ "Description 1") ^ " Description 2 " ) ) -- or, if no descriptions are added to the underlying properties declareNamedSchema = genericSchemaDroppingPrefix "myData" (\_ -> id) Versioning unencrypted keys). | Represents according to 'apiTimeFormat' format. | Parses from both UTC time in 'apiTimeFormat' format and a fractional timestamp format. Domain-specific types, mostly placeholders. optionally supplied by the user to encrypt the private keys. As private keys are needed to spend funds and this password secures spending, here the name base16-encoded string. | Wallet's Assurance Level | A Wallet ID. | A Wallet Operation Drops the @Wallet@ suffix. | A type modelling the request for a new 'Wallet'. ^) props -> props ^ "Backup phrase to restore the wallet.") ^ "Optional (but recommended) password to protect the wallet on sensitive operations.") ^ "Desired assurance level based on the number of confirmations counter of each transaction.") ^ "Wallet's name.") ^ "Create a new wallet or Restore an existing one.") | A type modelling the update of an existing wallet. ^) props -> props ^ "New assurance level.") ^ "New wallet's name.") ^) props -> props ^ "The estimated time the wallet is expected to be fully sync, based on the information available." ^ "The sync throughput, measured in blocks/s." ^ Restoring from seed or from backup. ^ Following the blockchain. | A 'Wallet'. ^) props -> props ^ "Unique wallet identifier." ^ "Wallet's name." ^ "Whether or not the wallet has a passphrase." ^ "The timestamp that the passphrase was last updated." ^ "The timestamp that the wallet was created." ^ "The assurance level of the wallet." ^ "The sync state for this wallet." ^) props -> props ^ "Unique wallet identifier." ------------------------------------------------------------------------------ Addresses ------------------------------------------------------------------------------ | Whether an address is valid or not. | An address is either recognised as "ours" or not. An address that is not recognised may still be ours e.g. an address generated by another wallet instance will not be considered "ours" until the relevant transaction is confirmed. In other words, `AddressAmbiguousOwnership` makes an inconclusive statement about an address, whereas `AddressOwnership` is unambiguous. | Address with associated metadata locating it in an account in a wallet. ------------------------------------------------------------------------------ Accounts ------------------------------------------------------------------------------ | Summary about single address. ^) props -> props ^ "Actual address.") ^ "True if this address has been used.") ^ "True if this address stores change from a previous transaction.") ^ "'isOurs' if this address is recognised as ours, 'ambiguousOwnership' if the node doesn't have information to make a unambiguous statement.") NOTE: minimum for hardened key. See -309 Nothing secret to redact for a AccountIndex. | A wallet 'Account'. ^) props -> props ^ "Account's index in the wallet, starting at 0.") ^ "Public addresses pointing to this account.") ^ "Account's name.") ^ "Id of the wallet this account belongs to.") ^) props -> props ^ "Public addresses pointing to this account.") ^) props -> props | Account Update ^) props -> props ^ "New account's name.") | New Account ^) props -> props ^ "Wallet's protection password, required if defined.") ^ "Account's name.") ^) props -> props ^ "Total number of entities successfully imported") ^ "Entities failed to be imported, if any") NOTE Small list | Create a new Address ^) props -> props ^ "Wallet's protection password, required if defined.") ^ "Corresponding wallet identifier.") | A type incapsulating a password update request. ^) props -> props ^ "Old password.") ^ "New passowrd.") for a 'Payment' in case the latter would actually be performed. ^) props -> props | Maps an 'Address' to some 'Coin's, and it's typically used to specify where to send money during a 'Payment'. ^) props -> props ^ "Address to map coins to.") ^) props -> props ^ "Corresponding account's index on the wallet.") ^) props -> props ^ "Source for the payment.") ^ "Optional strategy to use for selecting the transaction inputs.") ^ "Wallet's protection password, required to spend funds if defined.") -------------------------------------------------------------------------- TxId -------------------------------------------------------------------------- -------------------------------------------------------------------------- Transaction types -------------------------------------------------------------------------- | The 'Transaction' type. ^ This transaction is local, which means all the inputs and all the outputs belongs to the wallet from which the transaction was originated. ^ This transaction is not local to this wallet. Drops the @Transaction@ suffix. | The 'Transaction' @direction@ ^ This represents an incoming transactions. ^ This qualifies external transactions. Drops the @Transaction@ suffix. | A 'Wallet''s 'Transaction'. ^ The output money distribution. ^ The type for this transaction (e.g local, foreign, etc). ^ The direction for this transaction (e.g incoming, outgoing). ^ The time when transaction was created. ^) props -> props ^ "Number of confirmations.") ^ "Whether the transaction is entirely local or foreign.") ^ "Direction for this transaction.") ^ "Timestamp indicating when the transaction was created.") ^ "Shows whether or not the transaction is accepted.") | A type representing an upcoming wallet update. Other types omitted for now. ^) props -> props ^ "Current software (wallet) version.") ^ "Version of the underlying blockchain.") ^ "Update script version.") | A type encapsulating enough information to import a wallet from a backup file. ^) props -> props ^ "An optional spending password to set for the imported wallet.") | A redemption mnemonic. | A shielded redemption code. | This instance could probably be improved. A 'ShieldedRedemptionCode' is a hash of the redemption key. ^ An optional mnemonic. This mnemonic was included with paper certificates, and the presence of this field indicates that we're doing a paper vend. ^ The user must provide a spending password that matches the wallet that will be receiving the redemption funds. ^ Redeem to this wallet ^ Redeem to this account index in the wallet ^) props -> props ^ ( "An optional mnemonic. This must be provided for a paper " ^ ( "An optional spending password. This must match the password " POST/PUT requests isomorphisms read-only Example typeclass instances to control the length of the examples. It is possible for the encoded length is used. We do not use this constructor, which keeps the address between ~80-150 bytes long. NOTE: this will produce non empty list Note: will produce `Just a` TODO: will produce `Just groupingPolicy` Wallet Errors | Details about what 'NotEnoughMoney' means | UTxO exhausted whilst trying to pick inputs to cover remaining fee | UTxO exhausted during input selection | Type representing any error which might be thrown by wallet. ``` { "status": "error" "message" : <constr_name>, "diagnostic" : <data> } ``` and `<data>` is an object containing additional error data. Additional data contains constructor fields, field names are record field names without ``` { "address" : <address> } ``` Additional data in constructor should be represented as record fields. then "diagnostic" field will be empty object. TODO: change fields' types to actual Cardano core types, like `Coin` and `Address` | NotEnoughMoney weNeedMore | OutputIsRedeem weAddress | UnknownError weMsg ^ Size of transaction (in bytes) is greater than maximum. | TxSafeSignerNotFound weAddress | MissingRequiredParams requiredParams | WalletIsNotReadyToProcessPayments weStillRestoring ^ Cannot create derivation path for new address (for external wallet). ^ The @Wallet@ where a @Payment@ is being originated is not fully synced (its 'WalletSyncState' indicates it's either syncing or | NodeIsStillSyncing wenssStillSyncing ^ The backend couldn't process the incoming request as the underlying node is still syncing with the blockchain. ^ The request has been throttled. The 'Word64' is a count of microseconds until the user should retry. utxos | Give a short description of an error | Convert wallet errors to Servant errors | Declare the key used to wrap the diagnostic payload, if any
# LANGUAGE CPP # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE KindSignatures # # LANGUAGE LambdaCase # # LANGUAGE StandaloneDeriving # # LANGUAGE StrictData # # LANGUAGE NamedFieldPuns # Needed for the ` Buildable ` , ` SubscriptionStatus ` and ` NodeId ` orphans . # OPTIONS_GHC -fno - warn - orphans # module Cardano.Wallet.API.V1.Types ( V1 (..) , unV1 , PasswordUpdate (..) , AccountUpdate (..) , NewAccount (..) , Update , New , ForceNtpCheck (..) , Wallet (..) , AssuranceLevel (..) , NewWallet (..) , WalletUpdate (..) , WalletId (..) , exampleWalletId , WalletOperation (..) , SpendingPassword , mkSpendingPassword , AddressOwnership (..) , AddressValidity (..) , Account (..) , accountsHaveSameId , AccountIndex , AccountAddresses (..) , AccountBalance (..) , getAccIndex , mkAccountIndex , mkAccountIndexM , unsafeMkAccountIndex , AccountIndexError(..) , WalletAddress (..) , NewAddress (..) , BatchImportResult(..) , Payment (..) , PaymentSource (..) , PaymentDistribution (..) , Transaction (..) , TransactionType (..) , TransactionDirection (..) , TransactionStatus(..) , EstimatedFees (..) , WalletSoftwareUpdate (..) , WalletImport (..) , NodeSettings (..) , SlotDuration , mkSlotDuration , BlockchainHeight , mkBlockchainHeight , LocalTimeDifference , mkLocalTimeDifference , EstimatedCompletionTime , mkEstimatedCompletionTime , SyncThroughput , mkSyncThroughput , SyncState (..) , SyncProgress (..) , SyncPercentage , mkSyncPercentage , NodeInfo (..) , TimeInfo(..) , SubscriptionStatus(..) , Redemption(..) , RedemptionMnemonic(..) , BackupPhrase(..) , ShieldedRedemptionCode(..) , WAddressMeta (..) , CaptureWalletId , CaptureAccountId , Core.Address , Core.InputSelectionPolicy(..) , Core.Coin , Core.Timestamp(..) , Core.mkCoin , WalletError(..) , ErrNotEnoughMoney(..) , ErrUtxoNotEnoughFragmented(..) , msgUtxoNotEnoughFragmented , toServantError , toHttpErrorStatus , MnemonicBalance(..) , module Cardano.Wallet.Types.UtxoStatistics ) where import qualified Prelude import Universum import qualified Cardano.Crypto.Wallet as CC import Control.Lens (at, to, (?~)) import Data.Aeson import qualified Data.Aeson.Options as Aeson import Data.Aeson.TH as A import Data.Aeson.Types (Parser, Value (..), typeMismatch) import Data.Bifunctor (first) import qualified Data.ByteArray as ByteArray import qualified Data.ByteString as BS import Data.ByteString.Base58 (bitcoinAlphabet, decodeBase58) import qualified Data.Char as C import Data.Default (Default (def)) import Data.List ((!!)) import Data.Maybe (fromJust) import Data.Semigroup (Semigroup) import Data.Swagger hiding (Example, example) import Data.Text (Text, dropEnd, toLower) import Formatting (bprint, build, fconst, int, sformat, (%)) import qualified Formatting.Buildable import Generics.SOP.TH (deriveGeneric) import Serokell.Util (listJson) import qualified Serokell.Util.Base16 as Base16 import Servant import Test.QuickCheck import Test.QuickCheck.Gen (Gen (..)) import qualified Test.QuickCheck.Gen as Gen import qualified Test.QuickCheck.Modifiers as Gen import Pos.Node.API import Cardano.Wallet.API.Response.JSend (HasDiagnostic (..), noDiagnosticKey) import Cardano.Wallet.API.Types.UnitOfMeasure (MeasuredIn (..), UnitOfMeasure (..)) import Cardano.Wallet.API.V1.Errors (ToHttpErrorStatus (..), ToServantError (..)) import Cardano.Wallet.API.V1.Generic (jsendErrorGenericParseJSON, jsendErrorGenericToJSON) import Cardano.Wallet.API.V1.Swagger.Example (Example, example) import Cardano.Wallet.Types.UtxoStatistics import Cardano.Wallet.Util (mkJsonKey, showApiUtcTime) import Cardano.Mnemonic (Mnemonic) import qualified Pos.Chain.Txp as Txp import qualified Pos.Client.Txp.Util as Core import qualified Pos.Core as Core import Pos.Crypto (PublicKey (..), decodeHash, hashHexF) import qualified Pos.Crypto.Signing as Core import Pos.Infra.Communication.Types.Protocol () import Pos.Infra.Diffusion.Subscription.Status (SubscriptionStatus (..)) import Pos.Infra.Util.LogSafe (BuildableSafeGen (..), buildSafe, buildSafeList, buildSafeMaybe, deriveSafeBuildable, plainOrSecureF) import Test.Pos.Core.Arbitrary () data , : : String instance where instance where optsADTCamelCase :: A.Options optsADTCamelCase = defaultOptions { A.constructorTagModifier = mkJsonKey , A.sumEncoding = A.ObjectWithSingleField } mkSpendingPassword :: Text -> Either Text SpendingPassword mkSpendingPassword = fmap V1 . mkPassPhrase mkPassPhrase :: Text -> Either Text Core.PassPhrase mkPassPhrase text = case Base16.decode text of Left e -> Left e Right bs -> do let bl = BS.length bs Currently passphrase may be either 32 - byte long or empty ( for if bl == 0 || bl == Core.passphraseLength then Right $ ByteArray.convert bs else Left $ sformat ("Expected spending password to be of either length 0 or "%int%", not "%int) Core.passphraseLength bl instance ToJSON (V1 Core.PassPhrase) where toJSON = String . Base16.encode . ByteArray.convert instance FromJSON (V1 Core.PassPhrase) where parseJSON (String pp) = case mkPassPhrase pp of Left e -> fail (toString e) Right pp' -> pure (V1 pp') parseJSON x = typeMismatch "parseJSON failed for PassPhrase" x instance Arbitrary (V1 Core.PassPhrase) where arbitrary = fmap V1 arbitrary instance ToSchema (V1 Core.PassPhrase) where declareNamedSchema _ = pure $ NamedSchema (Just "V1PassPhrase") $ mempty & type_ ?~ SwaggerString & format ?~ "hex|base16" instance ToJSON (V1 Core.Coin) where toJSON (V1 c) = toJSON . Core.unsafeGetCoin $ c instance FromJSON (V1 Core.Coin) where parseJSON v = do i <- Core.Coin <$> parseJSON v either (fail . toString) (const (pure (V1 i))) $ Core.checkCoin i instance Arbitrary (V1 Core.Coin) where arbitrary = fmap V1 arbitrary instance ToSchema (V1 Core.Coin) where declareNamedSchema _ = pure $ NamedSchema (Just "V1Coin") $ mempty & type_ ?~ SwaggerNumber & maximum_ .~ Just (fromIntegral Core.maxCoinVal) instance ToJSON (V1 Core.Address) where toJSON (V1 c) = String $ sformat Core.addressF c instance FromJSON (V1 Core.Address) where parseJSON (String a) = case Core.decodeTextAddress a of Left e -> fail $ "Not a valid Cardano Address: " <> toString e Right addr -> pure (V1 addr) parseJSON x = typeMismatch "parseJSON failed for Address" x instance Arbitrary (V1 Core.Address) where arbitrary = fmap V1 arbitrary instance ToSchema (V1 Core.Address) where declareNamedSchema _ = pure $ NamedSchema (Just "Address") $ mempty & type_ ?~ SwaggerString & format ?~ "base58" instance FromHttpApiData (V1 Core.Address) where parseQueryParam = fmap (fmap V1) Core.decodeTextAddress instance ToHttpApiData (V1 Core.Address) where toQueryParam (V1 a) = sformat build a deriving instance Hashable (V1 Core.Address) deriving instance NFData (V1 Core.Address) instance ToJSON (V1 Core.Timestamp) where toJSON timestamp = let utcTime = timestamp ^. _V1 . Core.timestampToUTCTimeL in String $ showApiUtcTime utcTime instance ToHttpApiData (V1 Core.Timestamp) where toQueryParam = view (_V1 . Core.timestampToUTCTimeL . to showApiUtcTime) instance FromHttpApiData (V1 Core.Timestamp) where parseQueryParam t = maybe (Left ("Couldn't parse timestamp or datetime out of: " <> t)) (Right . V1) (Core.parseTimestamp t) instance FromJSON (V1 Core.Timestamp) where parseJSON = withText "Timestamp" $ \t -> maybe (fail ("Couldn't parse timestamp or datetime out of: " <> toString t)) (pure . V1) (Core.parseTimestamp t) instance Arbitrary (V1 Core.Timestamp) where arbitrary = fmap V1 arbitrary instance ToSchema (V1 Core.Timestamp) where declareNamedSchema _ = pure $ NamedSchema (Just "Timestamp") $ mempty & type_ ?~ SwaggerString & description ?~ "Time in ISO 8601 format" | A ' SpendingPassword ' represent a secret piece of information which can be ' SpendingPassword ' . Practically speaking , it 's just a type synonym for a PassPhrase , which is a type SpendingPassword = V1 Core.PassPhrase instance Semigroup (V1 Core.PassPhrase) where V1 a <> V1 b = V1 (a <> b) instance Monoid (V1 Core.PassPhrase) where mempty = V1 mempty mappend = (<>) instance BuildableSafeGen SpendingPassword where buildSafeGen sl pwd = bprint (plainOrSecureF sl build (fconst "<spending password>")) pwd type WalletName = Text data AssuranceLevel = NormalAssurance | StrictAssurance deriving (Eq, Ord, Show, Enum, Bounded) instance Arbitrary AssuranceLevel where arbitrary = elements [minBound .. maxBound] deriveJSON Aeson.defaultOptions { A.constructorTagModifier = toString . toLower . dropEnd 9 . fromString } ''AssuranceLevel instance ToSchema AssuranceLevel where declareNamedSchema _ = pure $ NamedSchema (Just "AssuranceLevel") $ mempty & type_ ?~ SwaggerString & enum_ ?~ ["normal", "strict"] deriveSafeBuildable ''AssuranceLevel instance BuildableSafeGen AssuranceLevel where buildSafeGen _ NormalAssurance = "normal" buildSafeGen _ StrictAssurance = "strict" newtype WalletId = WalletId Text deriving (Show, Eq, Ord, Generic) exampleWalletId :: WalletId exampleWalletId = WalletId "J7rQqaLLHBFPrgJXwpktaMB1B1kQBXAyc2uRSfRPzNVGiv6TdxBzkPNBUWysZZZdhFG9gRy3sQFfX5wfpLbi4XTFGFxTg" deriveJSON Aeson.defaultOptions ''WalletId instance ToSchema WalletId where declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions instance ToJSONKey WalletId instance Arbitrary WalletId where arbitrary = elements [exampleWalletId] deriveSafeBuildable ''WalletId instance BuildableSafeGen WalletId where buildSafeGen sl (WalletId wid) = bprint (plainOrSecureF sl build (fconst "<wallet id>")) wid instance FromHttpApiData WalletId where parseQueryParam = Right . WalletId instance ToHttpApiData WalletId where toQueryParam (WalletId wid) = wid instance Hashable WalletId instance NFData WalletId data WalletOperation = CreateWallet | RestoreWallet deriving (Eq, Show, Enum, Bounded) instance Arbitrary WalletOperation where arbitrary = elements [minBound .. maxBound] deriveJSON Aeson.defaultOptions { A.constructorTagModifier = reverse . drop 6 . reverse . map C.toLower } ''WalletOperation instance ToSchema WalletOperation where declareNamedSchema _ = pure $ NamedSchema (Just "WalletOperation") $ mempty & type_ ?~ SwaggerString & enum_ ?~ ["create", "restore"] deriveSafeBuildable ''WalletOperation instance BuildableSafeGen WalletOperation where buildSafeGen _ CreateWallet = "create" buildSafeGen _ RestoreWallet = "restore" newtype BackupPhrase = BackupPhrase { unBackupPhrase :: Mnemonic 12 } deriving stock (Eq, Show) deriving newtype (ToJSON, FromJSON, Arbitrary) deriveSafeBuildable ''BackupPhrase instance BuildableSafeGen BackupPhrase where buildSafeGen _ _ = "<backup phrase>" instance ToSchema BackupPhrase where declareNamedSchema _ = pure . NamedSchema (Just "V1BackupPhrase") $ toSchema (Proxy @(Mnemonic 12)) data NewWallet = NewWallet { newwalBackupPhrase :: !BackupPhrase , newwalSpendingPassword :: !(Maybe SpendingPassword) , newwalAssuranceLevel :: !AssuranceLevel , newwalName :: !WalletName , newwalOperation :: !WalletOperation } deriving (Eq, Show, Generic) deriveJSON Aeson.defaultOptions ''NewWallet instance Arbitrary NewWallet where arbitrary = NewWallet <$> arbitrary <*> pure Nothing <*> arbitrary <*> pure "My Wallet" <*> arbitrary instance ToSchema NewWallet where declareNamedSchema = ) deriveSafeBuildable ''NewWallet instance BuildableSafeGen NewWallet where buildSafeGen sl NewWallet{..} = bprint ("{" %" backupPhrase="%buildSafe sl %" spendingPassword="%(buildSafeMaybe mempty sl) %" assuranceLevel="%buildSafe sl %" name="%buildSafe sl %" operation"%buildSafe sl %" }") newwalBackupPhrase newwalSpendingPassword newwalAssuranceLevel newwalName newwalOperation data WalletUpdate = WalletUpdate { uwalAssuranceLevel :: !AssuranceLevel , uwalName :: !Text } deriving (Eq, Show, Generic) deriveJSON Aeson.defaultOptions ''WalletUpdate instance ToSchema WalletUpdate where declareNamedSchema = ) instance Arbitrary WalletUpdate where arbitrary = WalletUpdate <$> arbitrary <*> pure "My Wallet" deriveSafeBuildable ''WalletUpdate instance BuildableSafeGen WalletUpdate where buildSafeGen sl WalletUpdate{..} = bprint ("{" %" assuranceLevel="%buildSafe sl %" name="%buildSafe sl %" }") uwalAssuranceLevel uwalName newtype EstimatedCompletionTime = EstimatedCompletionTime (MeasuredIn 'Milliseconds Word) deriving (Show, Eq) mkEstimatedCompletionTime :: Word -> EstimatedCompletionTime mkEstimatedCompletionTime = EstimatedCompletionTime . MeasuredIn instance Ord EstimatedCompletionTime where compare (EstimatedCompletionTime (MeasuredIn w1)) (EstimatedCompletionTime (MeasuredIn w2)) = compare w1 w2 instance Arbitrary EstimatedCompletionTime where arbitrary = EstimatedCompletionTime . MeasuredIn <$> arbitrary deriveSafeBuildable ''EstimatedCompletionTime instance BuildableSafeGen EstimatedCompletionTime where buildSafeGen _ (EstimatedCompletionTime (MeasuredIn w)) = bprint ("{" %" quantity="%build %" unit=milliseconds" %" }") w instance ToJSON EstimatedCompletionTime where toJSON (EstimatedCompletionTime (MeasuredIn w)) = object [ "quantity" .= toJSON w , "unit" .= String "milliseconds" ] instance FromJSON EstimatedCompletionTime where parseJSON = withObject "EstimatedCompletionTime" $ \sl -> mkEstimatedCompletionTime <$> sl .: "quantity" instance ToSchema EstimatedCompletionTime where declareNamedSchema _ = pure $ NamedSchema (Just "EstimatedCompletionTime") $ mempty & type_ ?~ SwaggerObject & required .~ ["quantity", "unit"] & properties .~ (mempty & at "quantity" ?~ (Inline $ mempty & type_ ?~ SwaggerNumber & minimum_ .~ Just 0 ) & at "unit" ?~ (Inline $ mempty & type_ ?~ SwaggerString & enum_ ?~ ["milliseconds"] ) ) newtype SyncThroughput = SyncThroughput (MeasuredIn 'BlocksPerSecond Core.BlockCount) deriving (Show, Eq) mkSyncThroughput :: Core.BlockCount -> SyncThroughput mkSyncThroughput = SyncThroughput . MeasuredIn instance Ord SyncThroughput where compare (SyncThroughput (MeasuredIn (Core.BlockCount b1))) (SyncThroughput (MeasuredIn (Core.BlockCount b2))) = compare b1 b2 instance Arbitrary SyncThroughput where arbitrary = SyncThroughput . MeasuredIn <$> arbitrary deriveSafeBuildable ''SyncThroughput instance BuildableSafeGen SyncThroughput where buildSafeGen _ (SyncThroughput (MeasuredIn (Core.BlockCount blocks))) = bprint ("{" %" quantity="%build %" unit=blocksPerSecond" %" }") blocks instance ToJSON SyncThroughput where toJSON (SyncThroughput (MeasuredIn (Core.BlockCount blocks))) = object [ "quantity" .= toJSON blocks , "unit" .= String "blocksPerSecond" ] instance FromJSON SyncThroughput where parseJSON = withObject "SyncThroughput" $ \sl -> mkSyncThroughput . Core.BlockCount <$> sl .: "quantity" instance ToSchema SyncThroughput where declareNamedSchema _ = pure $ NamedSchema (Just "SyncThroughput") $ mempty & type_ ?~ SwaggerObject & required .~ ["quantity", "unit"] & properties .~ (mempty & at "quantity" ?~ (Inline $ mempty & type_ ?~ SwaggerNumber ) & at "unit" ?~ (Inline $ mempty & type_ ?~ SwaggerString & enum_ ?~ ["blocksPerSecond"] ) ) data SyncProgress = SyncProgress { spEstimatedCompletionTime :: !EstimatedCompletionTime , spThroughput :: !SyncThroughput , spPercentage :: !SyncPercentage } deriving (Show, Eq, Ord, Generic) deriveJSON Aeson.defaultOptions ''SyncProgress instance ToSchema SyncProgress where declareNamedSchema = & "estimatedCompletionTime" & "throughput" & "percentage" ^ " The sync percentage , from 0 % to 100 % . " ) deriveSafeBuildable ''SyncProgress Nothing secret to redact for a SyncProgress . instance BuildableSafeGen SyncProgress where buildSafeGen sl SyncProgress {..} = bprint ("{" %" estimatedCompletionTime="%buildSafe sl %" throughput="%buildSafe sl %" percentage="%buildSafe sl %" }") spEstimatedCompletionTime spThroughput spPercentage instance Example SyncProgress where example = do exPercentage <- example pure $ SyncProgress { spEstimatedCompletionTime = mkEstimatedCompletionTime 3000 , spThroughput = mkSyncThroughput (Core.BlockCount 400) , spPercentage = exPercentage } instance Arbitrary SyncProgress where arbitrary = SyncProgress <$> arbitrary <*> arbitrary <*> arbitrary data SyncState = Restoring SyncProgress | Synced deriving (Eq, Show, Ord) instance ToJSON SyncState where toJSON ss = object [ "tag" .= toJSON (renderAsTag ss) , "data" .= renderAsData ss ] where renderAsTag :: SyncState -> Text renderAsTag (Restoring _) = "restoring" renderAsTag Synced = "synced" renderAsData :: SyncState -> Value renderAsData (Restoring sp) = toJSON sp renderAsData Synced = Null instance FromJSON SyncState where parseJSON = withObject "SyncState" $ \ss -> do t <- ss .: "tag" case (t :: Text) of "synced" -> pure Synced "restoring" -> Restoring <$> ss .: "data" _ -> typeMismatch "unrecognised tag" (Object ss) instance ToSchema SyncState where declareNamedSchema _ = do syncProgress <- declareSchemaRef @SyncProgress Proxy pure $ NamedSchema (Just "SyncState") $ mempty & type_ ?~ SwaggerObject & required .~ ["tag"] & properties .~ (mempty & at "tag" ?~ (Inline $ mempty & type_ ?~ SwaggerString & enum_ ?~ ["restoring", "synced"] ) & at "data" ?~ syncProgress ) instance Arbitrary SyncState where arbitrary = oneof [ Restoring <$> arbitrary , pure Synced ] data Wallet = Wallet { walId :: !WalletId , walName :: !WalletName , walBalance :: !(V1 Core.Coin) , walHasSpendingPassword :: !Bool , walSpendingPasswordLastUpdate :: !(V1 Core.Timestamp) , walCreatedAt :: !(V1 Core.Timestamp) , walAssuranceLevel :: !AssuranceLevel , walSyncState :: !SyncState } deriving (Eq, Ord, Show, Generic) deriveJSON Aeson.defaultOptions ''Wallet instance ToSchema Wallet where declareNamedSchema = & "id" & "name" & "balance" ^ " Current balance , in . " & "hasSpendingPassword" & "spendingPasswordLastUpdate" & "createdAt" & "assuranceLevel" & "syncState" ) instance Arbitrary Wallet where arbitrary = Wallet <$> arbitrary <*> pure "My wallet" <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary deriveSafeBuildable ''Wallet instance BuildableSafeGen Wallet where buildSafeGen sl Wallet{..} = bprint ("{" %" id="%buildSafe sl %" name="%buildSafe sl %" balance="%buildSafe sl %" }") walId walName walBalance instance Buildable [Wallet] where build = bprint listJson data MnemonicBalance = MnemonicBalance { mbWalletId :: !WalletId , mbBalance :: !(Maybe Integer) } deriving (Eq, Ord, Show, Generic) deriveJSON Aeson.defaultOptions ''MnemonicBalance instance ToSchema MnemonicBalance where declareNamedSchema = & "walletId" & "balance" ^ " Current balance , in . " ) instance Arbitrary MnemonicBalance where arbitrary = MnemonicBalance <$> arbitrary <*> arbitrary deriveSafeBuildable ''MnemonicBalance instance BuildableSafeGen MnemonicBalance where buildSafeGen sl MnemonicBalance{mbWalletId,mbBalance} = case mbBalance of Just bal -> bprint ("{" %" id="%buildSafe sl %" balance="%build %" }") mbWalletId bal Nothing -> bprint ("{" %" id="%buildSafe sl %" }") mbWalletId instance Example MnemonicBalance where example = do MnemonicBalance <$> example <*> (pure $ Just 1000000) instance ToSchema PublicKey where declareNamedSchema _ = pure $ NamedSchema (Just "PublicKey") $ mempty & type_ ?~ SwaggerString & format ?~ "base58" newtype AddressValidity = AddressValidity { isValid :: Bool } deriving (Eq, Show, Generic) deriveJSON Aeson.defaultOptions ''AddressValidity instance ToSchema AddressValidity where declareNamedSchema = genericSchemaDroppingPrefix "is" (const identity) instance Arbitrary AddressValidity where arbitrary = AddressValidity <$> arbitrary deriveSafeBuildable ''AddressValidity instance BuildableSafeGen AddressValidity where buildSafeGen _ AddressValidity{..} = bprint ("{ valid="%build%" }") isValid data AddressOwnership = AddressIsOurs | AddressAmbiguousOwnership deriving (Show, Eq, Generic, Ord) instance ToJSON (V1 AddressOwnership) where toJSON = genericToJSON optsADTCamelCase . unV1 instance FromJSON (V1 AddressOwnership) where parseJSON = fmap V1 . genericParseJSON optsADTCamelCase instance ToSchema (V1 AddressOwnership) where declareNamedSchema _ = pure $ NamedSchema (Just "V1AddressOwnership") $ mempty & type_ ?~ SwaggerString & enum_ ?~ ["isOurs", "ambiguousOwnership"] instance Arbitrary (V1 AddressOwnership) where arbitrary = fmap V1 $ oneof [ pure AddressIsOurs , pure AddressAmbiguousOwnership ] data WAddressMeta = WAddressMeta { _wamWalletId :: !WalletId , _wamAccountIndex :: !Word32 , _wamAddressIndex :: !Word32 , _wamAddress :: !(V1 Core.Address) } deriving (Eq, Ord, Show, Generic, Typeable) instance Hashable WAddressMeta instance NFData WAddressMeta instance Buildable WAddressMeta where build WAddressMeta{..} = bprint (build%"@"%build%"@"%build%" ("%build%")") _wamWalletId _wamAccountIndex _wamAddressIndex _wamAddress data WalletAddress = WalletAddress { addrId :: !(V1 Core.Address) , addrUsed :: !Bool , addrChangeAddress :: !Bool , addrOwnership :: !(V1 AddressOwnership) } deriving (Show, Eq, Generic, Ord) deriveJSON Aeson.defaultOptions ''WalletAddress instance ToSchema WalletAddress where declareNamedSchema = ) instance Arbitrary WalletAddress where arbitrary = WalletAddress <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary newtype AccountIndex = AccountIndex { getAccIndex :: Word32 } deriving (Show, Eq, Ord, Generic) newtype AccountIndexError = AccountIndexError Word32 deriving (Eq, Show) instance Buildable AccountIndexError where build (AccountIndexError i) = bprint ("Account index should be in range ["%int%".."%int%"], but "%int%" was provided.") (getAccIndex minBound) (getAccIndex maxBound) i mkAccountIndex :: Word32 -> Either AccountIndexError AccountIndex mkAccountIndex index | index >= getAccIndex minBound = Right $ AccountIndex index | otherwise = Left $ AccountIndexError index mkAccountIndexM :: MonadFail m => Word32 -> m AccountIndex mkAccountIndexM = either (fail . toString . sformat build) pure . mkAccountIndex unsafeMkAccountIndex :: Word32 -> AccountIndex unsafeMkAccountIndex = either (error . sformat build) identity . mkAccountIndex instance Bounded AccountIndex where minBound = AccountIndex 2147483648 maxBound = AccountIndex maxBound instance ToJSON AccountIndex where toJSON = toJSON . getAccIndex instance FromJSON AccountIndex where parseJSON = mkAccountIndexM <=< parseJSON instance Arbitrary AccountIndex where arbitrary = AccountIndex <$> choose (getAccIndex minBound, getAccIndex maxBound) deriveSafeBuildable ''AccountIndex instance BuildableSafeGen AccountIndex where buildSafeGen _ = bprint build . getAccIndex instance ToParamSchema AccountIndex where toParamSchema _ = mempty & type_ ?~ SwaggerNumber & minimum_ .~ Just (fromIntegral $ getAccIndex minBound) & maximum_ .~ Just (fromIntegral $ getAccIndex maxBound) instance ToSchema AccountIndex where declareNamedSchema = pure . paramSchemaToNamedSchema defaultSchemaOptions instance FromHttpApiData AccountIndex where parseQueryParam = first (sformat build) . mkAccountIndex <=< parseQueryParam instance ToHttpApiData AccountIndex where toQueryParam = fromString . show . getAccIndex data Account = Account { accIndex :: !AccountIndex , accAddresses :: ![WalletAddress] , accAmount :: !(V1 Core.Coin) , accName :: !Text , accWalletId :: !WalletId } deriving (Show, Ord, Eq, Generic) IxSet indices | Datatype wrapping addresses for per - field endpoint newtype AccountAddresses = AccountAddresses { acaAddresses :: [WalletAddress] } deriving (Show, Ord, Eq, Generic) | Datatype wrapping balance for per - field endpoint newtype AccountBalance = AccountBalance { acbAmount :: V1 Core.Coin } deriving (Show, Ord, Eq, Generic) accountsHaveSameId :: Account -> Account -> Bool accountsHaveSameId a b = accWalletId a == accWalletId b && accIndex a == accIndex b deriveJSON Aeson.defaultOptions ''Account deriveJSON Aeson.defaultOptions ''AccountAddresses deriveJSON Aeson.defaultOptions ''AccountBalance instance ToSchema Account where declareNamedSchema = ^ " Available funds , in . " ) ) instance ToSchema AccountAddresses where declareNamedSchema = ) instance ToSchema AccountBalance where declareNamedSchema = ^ " Available funds , in . " ) ) instance Arbitrary Account where arbitrary = Account <$> arbitrary <*> arbitrary <*> arbitrary <*> pure "My account" <*> arbitrary instance Arbitrary AccountAddresses where arbitrary = AccountAddresses <$> arbitrary instance Arbitrary AccountBalance where arbitrary = AccountBalance <$> arbitrary deriveSafeBuildable ''Account instance BuildableSafeGen Account where buildSafeGen sl Account{..} = bprint ("{" %" index="%buildSafe sl %" name="%buildSafe sl %" addresses="%buildSafe sl %" amount="%buildSafe sl %" walletId="%buildSafe sl %" }") accIndex accName accAddresses accAmount accWalletId instance Buildable AccountAddresses where build = bprint listJson . acaAddresses instance Buildable AccountBalance where build = bprint build . acbAmount instance Buildable [Account] where build = bprint listJson data AccountUpdate = AccountUpdate { uaccName :: !Text } deriving (Show, Eq, Generic) deriveJSON Aeson.defaultOptions ''AccountUpdate instance ToSchema AccountUpdate where declareNamedSchema = ) instance Arbitrary AccountUpdate where arbitrary = AccountUpdate <$> pure "myAccount" deriveSafeBuildable ''AccountUpdate instance BuildableSafeGen AccountUpdate where buildSafeGen sl AccountUpdate{..} = bprint ("{ name="%buildSafe sl%" }") uaccName data NewAccount = NewAccount { naccSpendingPassword :: !(Maybe SpendingPassword) , naccName :: !Text } deriving (Show, Eq, Generic) deriveJSON Aeson.defaultOptions ''NewAccount instance Arbitrary NewAccount where arbitrary = NewAccount <$> arbitrary <*> arbitrary instance ToSchema NewAccount where declareNamedSchema = ) deriveSafeBuildable ''NewAccount instance BuildableSafeGen NewAccount where buildSafeGen sl NewAccount{..} = bprint ("{" %" spendingPassword="%(buildSafeMaybe mempty sl) %" name="%buildSafe sl %" }") naccSpendingPassword naccName deriveSafeBuildable ''WalletAddress instance BuildableSafeGen WalletAddress where buildSafeGen sl WalletAddress{..} = bprint ("{" %" id="%buildSafe sl %" used="%build %" changeAddress="%build %" }") addrId addrUsed addrChangeAddress instance Buildable [WalletAddress] where build = bprint listJson instance Buildable [V1 Core.Address] where build = bprint listJson data BatchImportResult a = BatchImportResult { aimTotalSuccess :: !Natural , aimFailures :: ![a] } deriving (Show, Ord, Eq, Generic) instance Buildable (BatchImportResult a) where build res = bprint ("BatchImportResult (success:"%int%", failures:"%int%")") (aimTotalSuccess res) (length $ aimFailures res) instance ToJSON a => ToJSON (BatchImportResult a) where toJSON = genericToJSON Aeson.defaultOptions instance FromJSON a => FromJSON (BatchImportResult a) where parseJSON = genericParseJSON Aeson.defaultOptions instance (ToJSON a, ToSchema a, Arbitrary a) => ToSchema (BatchImportResult a) where declareNamedSchema = ) instance Arbitrary a => Arbitrary (BatchImportResult a) where arbitrary = BatchImportResult <$> arbitrary instance Arbitrary a => Example (BatchImportResult a) instance Semigroup (BatchImportResult a) where (BatchImportResult a0 b0) <> (BatchImportResult a1 b1) = BatchImportResult (a0 + a1) (b0 <> b1) instance Monoid (BatchImportResult a) where mempty = BatchImportResult 0 mempty data NewAddress = NewAddress { newaddrSpendingPassword :: !(Maybe SpendingPassword) , newaddrAccountIndex :: !AccountIndex , newaddrWalletId :: !WalletId } deriving (Show, Eq, Generic) deriveJSON Aeson.defaultOptions ''NewAddress instance ToSchema NewAddress where declareNamedSchema = ^ " Target account 's index to store this address in . " ) ) instance Arbitrary NewAddress where arbitrary = NewAddress <$> arbitrary <*> arbitrary <*> arbitrary deriveSafeBuildable ''NewAddress instance BuildableSafeGen NewAddress where buildSafeGen sl NewAddress{..} = bprint("{" %" spendingPassword="%(buildSafeMaybe mempty sl) %" accountIndex="%buildSafe sl %" walletId="%buildSafe sl %" }") newaddrSpendingPassword newaddrAccountIndex newaddrWalletId data PasswordUpdate = PasswordUpdate { pwdOld :: !SpendingPassword , pwdNew :: !SpendingPassword } deriving (Show, Eq, Generic) deriveJSON Aeson.defaultOptions ''PasswordUpdate instance ToSchema PasswordUpdate where declareNamedSchema = ) instance Arbitrary PasswordUpdate where arbitrary = PasswordUpdate <$> arbitrary <*> arbitrary deriveSafeBuildable ''PasswordUpdate instance BuildableSafeGen PasswordUpdate where buildSafeGen sl PasswordUpdate{..} = bprint("{" %" old="%buildSafe sl %" new="%buildSafe sl %" }") pwdOld pwdNew | ' EstimatedFees ' represents the fees which would be generated data EstimatedFees = EstimatedFees { feeEstimatedAmount :: !(V1 Core.Coin) } deriving (Show, Eq, Generic) deriveJSON Aeson.defaultOptions ''EstimatedFees instance ToSchema EstimatedFees where declareNamedSchema = ^ " Estimated fees , in . " ) ) instance Arbitrary EstimatedFees where arbitrary = EstimatedFees <$> arbitrary deriveSafeBuildable ''EstimatedFees instance BuildableSafeGen EstimatedFees where buildSafeGen sl EstimatedFees{..} = bprint("{" %" estimatedAmount="%buildSafe sl %" }") feeEstimatedAmount data PaymentDistribution = PaymentDistribution { pdAddress :: !(V1 Core.Address) , pdAmount :: !(V1 Core.Coin) } deriving (Show, Ord, Eq, Generic) deriveJSON Aeson.defaultOptions ''PaymentDistribution instance ToSchema PaymentDistribution where declareNamedSchema = ^ " Amount of coin to bind , in . " ) ) instance Arbitrary PaymentDistribution where arbitrary = PaymentDistribution <$> arbitrary <*> arbitrary deriveSafeBuildable ''PaymentDistribution instance BuildableSafeGen PaymentDistribution where buildSafeGen sl PaymentDistribution{..} = bprint ("{" %" address="%buildSafe sl %" amount="%buildSafe sl %" }") pdAddress pdAmount | A ' PaymentSource ' encapsulate two essentially piece of data to reach for some funds : a ' WalletId ' and an ' AccountIndex ' within it . data PaymentSource = PaymentSource { psWalletId :: !WalletId , psAccountIndex :: !AccountIndex } deriving (Show, Ord, Eq, Generic) deriveJSON Aeson.defaultOptions ''PaymentSource instance ToSchema PaymentSource where declareNamedSchema = ^ " Target wallet identifier to reach . " ) ) instance Arbitrary PaymentSource where arbitrary = PaymentSource <$> arbitrary <*> arbitrary deriveSafeBuildable ''PaymentSource instance BuildableSafeGen PaymentSource where buildSafeGen sl PaymentSource{..} = bprint ("{" %" walletId="%buildSafe sl %" accountIndex="%buildSafe sl %" }") psWalletId psAccountIndex | A ' Payment ' from one source account to one or more ' PaymentDistribution'(s ) . data Payment = Payment { pmtSource :: !PaymentSource , pmtDestinations :: !(NonEmpty PaymentDistribution) , pmtGroupingPolicy :: !(Maybe (V1 Core.InputSelectionPolicy)) , pmtSpendingPassword :: !(Maybe SpendingPassword) } deriving (Show, Eq, Generic) instance ToJSON (V1 Core.InputSelectionPolicy) where toJSON (V1 Core.OptimizeForSecurity) = String "OptimizeForSecurity" toJSON (V1 Core.OptimizeForHighThroughput) = String "OptimizeForHighThroughput" instance FromJSON (V1 Core.InputSelectionPolicy) where parseJSON (String "OptimizeForSecurity") = pure (V1 Core.OptimizeForSecurity) parseJSON (String "OptimizeForHighThroughput") = pure (V1 Core.OptimizeForHighThroughput) parseJSON x = typeMismatch "Not a valid InputSelectionPolicy" x instance ToSchema (V1 Core.InputSelectionPolicy) where declareNamedSchema _ = pure $ NamedSchema (Just "V1InputSelectionPolicy") $ mempty & type_ ?~ SwaggerString & enum_ ?~ ["OptimizeForSecurity", "OptimizeForHighThroughput"] instance Arbitrary (V1 Core.InputSelectionPolicy) where arbitrary = fmap V1 arbitrary deriveJSON Aeson.defaultOptions ''Payment instance Arbitrary Payment where arbitrary = Payment <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary instance ToSchema Payment where declareNamedSchema = ^ " One or more destinations for the payment . " ) ) deriveSafeBuildable ''Payment instance BuildableSafeGen Payment where buildSafeGen sl (Payment{..}) = bprint ("{" %" source="%buildSafe sl %" destinations="%buildSafeList sl %" groupingPolicty="%build %" spendingPassword="%(buildSafeMaybe mempty sl) %" }") pmtSource (toList pmtDestinations) pmtGroupingPolicy pmtSpendingPassword instance Arbitrary (V1 Txp.TxId) where arbitrary = V1 <$> arbitrary instance ToJSON (V1 Txp.TxId) where toJSON (V1 t) = String (sformat hashHexF t) instance FromJSON (V1 Txp.TxId) where parseJSON = withText "TxId" $ \t -> do case decodeHash t of Left err -> fail $ "Failed to parse transaction ID: " <> toString err Right a -> pure (V1 a) instance FromHttpApiData (V1 Txp.TxId) where parseQueryParam = fmap (fmap V1) decodeHash instance ToHttpApiData (V1 Txp.TxId) where toQueryParam (V1 txId) = sformat hashHexF txId instance ToSchema (V1 Txp.TxId) where declareNamedSchema _ = declareNamedSchema (Proxy @Text) data TransactionType = LocalTransaction | ForeignTransaction deriving (Show, Ord, Eq, Enum, Bounded) instance Arbitrary TransactionType where arbitrary = elements [minBound .. maxBound] deriveJSON defaultOptions { A.constructorTagModifier = reverse . drop 11 . reverse . map C.toLower } ''TransactionType instance ToSchema TransactionType where declareNamedSchema _ = pure $ NamedSchema (Just "TransactionType") $ mempty & type_ ?~ SwaggerString & enum_ ?~ ["local", "foreign"] & description ?~ mconcat [ "A transaction is 'local' if all the inputs and outputs " , "belong to the current wallet. A transaction is foreign " , "if the transaction is not local to this wallet." ] deriveSafeBuildable ''TransactionType instance BuildableSafeGen TransactionType where buildSafeGen _ LocalTransaction = "local" buildSafeGen _ ForeignTransaction = "foreign" data TransactionDirection = IncomingTransaction | OutgoingTransaction deriving (Show, Ord, Eq, Enum, Bounded) instance Arbitrary TransactionDirection where arbitrary = elements [minBound .. maxBound] deriveJSON defaultOptions { A.constructorTagModifier = reverse . drop 11 . reverse . map C.toLower } ''TransactionDirection instance ToSchema TransactionDirection where declareNamedSchema _ = pure $ NamedSchema (Just "TransactionDirection") $ mempty & type_ ?~ SwaggerString & enum_ ?~ ["outgoing", "incoming"] | This is an information - less variant of ' PtxCondition ' . data TransactionStatus = Applying | InNewestBlocks | Persisted | WontApply | Creating deriving (Eq, Show, Ord) allTransactionStatuses :: [TransactionStatus] allTransactionStatuses = [Applying, InNewestBlocks, Persisted, WontApply, Creating] transactionStatusToText :: TransactionStatus -> Text transactionStatusToText x = case x of Applying {} -> "applying" InNewestBlocks {} -> "inNewestBlocks" Persisted {} -> "persisted" WontApply {} -> "wontApply" Creating {} -> "creating" instance ToJSON TransactionStatus where toJSON x = object [ "tag" .= transactionStatusToText x , "data" .= Object mempty ] instance ToSchema TransactionStatus where declareNamedSchema _ = pure $ NamedSchema (Just "TransactionStatus") $ mempty & type_ ?~ SwaggerObject & required .~ ["tag", "data"] & properties .~ (mempty & at "tag" ?~ Inline (mempty & type_ ?~ SwaggerString & enum_ ?~ map (String . transactionStatusToText) allTransactionStatuses ) & at "data" ?~ Inline (mempty & type_ ?~ SwaggerObject ) ) instance FromJSON TransactionStatus where parseJSON = withObject "TransactionStatus" $ \o -> do tag <- o .: "tag" case tag of "applying" -> pure Applying "inNewestBlocks" -> pure InNewestBlocks "persisted" -> pure Persisted "wontApply" -> pure WontApply "creating" -> pure Creating _ -> fail $ "Couldn't parse out of " ++ toString (tag :: Text) instance Arbitrary TransactionStatus where arbitrary = elements allTransactionStatuses deriveSafeBuildable ''TransactionDirection instance BuildableSafeGen TransactionDirection where buildSafeGen _ IncomingTransaction = "incoming" buildSafeGen _ OutgoingTransaction = "outgoing" data Transaction = Transaction { txId :: !(V1 Txp.TxId) , txConfirmations :: !Word , txAmount :: !(V1 Core.Coin) , txInputs :: !(NonEmpty PaymentDistribution) , txOutputs :: !(NonEmpty PaymentDistribution) , txType :: !TransactionType , txDirection :: !TransactionDirection , txCreationTime :: !(V1 Core.Timestamp) , txStatus :: !TransactionStatus } deriving (Show, Ord, Eq, Generic) deriveJSON Aeson.defaultOptions ''Transaction instance ToSchema Transaction where declareNamedSchema = ^ " Transaction 's i d. " ) ^ " Coins moved as part of the transaction , in . " ) ^ " One or more input money distributions . " ) ^ " One or more ouputs money distributions . " ) ) instance Arbitrary Transaction where arbitrary = Transaction <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary deriveSafeBuildable ''Transaction instance BuildableSafeGen Transaction where buildSafeGen sl Transaction{..} = bprint ("{" %" id="%buildSafe sl %" confirmations="%build %" amount="%buildSafe sl %" inputs="%buildSafeList sl %" outputs="%buildSafeList sl %" type="%buildSafe sl %" direction"%buildSafe sl %" }") txId txConfirmations txAmount (toList txInputs) (toList txOutputs) txType txDirection instance Buildable [Transaction] where build = bprint listJson data WalletSoftwareUpdate = WalletSoftwareUpdate { updSoftwareVersion :: !Text , updBlockchainVersion :: !Text , updScriptVersion :: !Int } deriving (Show, Eq, Generic) deriveJSON Aeson.defaultOptions ''WalletSoftwareUpdate instance ToSchema WalletSoftwareUpdate where declareNamedSchema = ) instance Arbitrary WalletSoftwareUpdate where arbitrary = WalletSoftwareUpdate <$> arbitrary <*> arbitrary <*> fmap getPositive arbitrary deriveSafeBuildable ''WalletSoftwareUpdate instance BuildableSafeGen WalletSoftwareUpdate where buildSafeGen _ WalletSoftwareUpdate{..} = bprint("{" %" softwareVersion="%build %" blockchainVersion="%build %" scriptVersion="%build %" }") updSoftwareVersion updBlockchainVersion updScriptVersion data WalletImport = WalletImport { wiSpendingPassword :: !(Maybe SpendingPassword) , wiFilePath :: !FilePath } deriving (Show, Eq, Generic) deriveJSON Aeson.defaultOptions ''WalletImport instance ToSchema WalletImport where declareNamedSchema = ^ " The path to the .key file holding the backup . " ) ) instance Arbitrary WalletImport where arbitrary = WalletImport <$> arbitrary <*> arbitrary deriveSafeBuildable ''WalletImport instance BuildableSafeGen WalletImport where buildSafeGen sl WalletImport{..} = bprint("{" %" spendingPassword="%build %" filePath="%build %" }") (maybe "null" (buildSafeGen sl) wiSpendingPassword) wiFilePath newtype RedemptionMnemonic = RedemptionMnemonic { unRedemptionMnemonic :: Mnemonic 9 } deriving stock (Eq, Show, Generic) deriving newtype (ToJSON, FromJSON, Arbitrary) instance ToSchema RedemptionMnemonic where declareNamedSchema _ = pure $ NamedSchema (Just "RedemptionMnemonic") (toSchema (Proxy @(Mnemonic 9))) newtype ShieldedRedemptionCode = ShieldedRedemptionCode { unShieldedRedemptionCode :: Text } deriving (Eq, Show, Generic) deriving newtype (ToJSON, FromJSON) instance Arbitrary ShieldedRedemptionCode where arbitrary = ShieldedRedemptionCode <$> arbitrary instance ToSchema ShieldedRedemptionCode where declareNamedSchema _ = pure $ NamedSchema (Just "ShieldedRedemptionCode") $ mempty & type_ ?~ SwaggerString deriveSafeBuildable ''ShieldedRedemptionCode instance BuildableSafeGen ShieldedRedemptionCode where buildSafeGen _ _ = bprint "<shielded redemption code>" | The request body for redeeming some . data Redemption = Redemption { redemptionRedemptionCode :: ShieldedRedemptionCode ^ The redemption code associated with the to redeem . , redemptionMnemonic :: Maybe RedemptionMnemonic , redemptionSpendingPassword :: SpendingPassword , redemptionWalletId :: WalletId , redemptionAccountIndex :: AccountIndex } deriving (Eq, Show, Generic) deriveSafeBuildable ''Redemption instance BuildableSafeGen Redemption where buildSafeGen sl r = bprint ("{" %" redemptionCode="%buildSafe sl %" mnemonic=<mnemonic>" %" spendingPassword="%buildSafe sl %" }") (redemptionRedemptionCode r) (redemptionSpendingPassword r) deriveJSON Aeson.defaultOptions ''Redemption instance ToSchema Redemption where declareNamedSchema = & "redemptionCode" ^ " The redemption code associated with the to redeem . " & "mnemonic" <> "certificate redemption." ) & "spendingPassword" <> "for the provided wallet ID and account index." ) ) instance Arbitrary Redemption where arbitrary = Redemption <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary type family Update (original :: *) :: * where Update Wallet = WalletUpdate Update Account = AccountUpdate Update WalletAddress = type family New (original :: *) :: * where New Wallet = NewWallet New Account = NewAccount New WalletAddress = NewAddress type CaptureWalletId = Capture "walletId" WalletId type CaptureAccountId = Capture "accountId" AccountIndex instance Example Core.Address instance Example AccountIndex instance Example AccountBalance instance Example AccountAddresses instance Example WalletId instance Example AssuranceLevel instance Example LocalTimeDifference instance Example PaymentDistribution instance Example AccountUpdate instance Example Wallet instance Example WalletUpdate instance Example WalletOperation instance Example PasswordUpdate instance Example EstimatedFees instance Example Transaction instance Example WalletSoftwareUpdate instance Example WalletAddress instance Example NewAccount instance Example AddressValidity instance Example NewAddress instance Example ShieldedRedemptionCode instance Example (V1 Core.PassPhrase) instance Example (V1 Core.Coin) | We have a specific ' Example ' instance for ' ' because we want to become huge , up to 1000 + bytes , if the ' UnsafeMultiKeyDistr ' constructor instance Example (V1 Core.Address) where example = fmap V1 . Core.makeAddress <$> arbitrary <*> arbitraryAttributes where arbitraryAttributes = Core.AddrAttributes <$> arbitrary <*> oneof [ pure Core.BootstrapEraDistr , Core.SingleKeyDistr <$> arbitrary ] <*> arbitrary instance Example BackupPhrase where example = pure (BackupPhrase def) instance Example Core.InputSelectionPolicy where example = pure Core.OptimizeForHighThroughput instance Example (V1 Core.InputSelectionPolicy) where example = pure (V1 Core.OptimizeForHighThroughput) instance Example Account where example = Account <$> example <*> example <*> pure "My account" <*> example instance Example NewWallet where example = NewWallet <$> example <*> example <*> pure "My Wallet" <*> example instance Example PublicKey where example = PublicKey <$> pure xpub where xpub = rights [ CC.xpub . fromJust . decodeBase58 bitcoinAlphabet . encodeUtf8 $ encodedPublicKey ] !! 0 encodedPublicKey :: Text encodedPublicKey = "bNfWjshJG9xxy6VkpV2KurwGah3jQWjGb4QveDGZteaCwupdKWAi371r8uS5yFCny5i5EQuSNSLKqvRHmWEoHe45pZ" instance Example PaymentSource where example = PaymentSource <$> example <*> example instance Example Payment where example = Payment <$> example <*> example <*> example instance Example Redemption where example = Redemption <$> example <*> pure Nothing <*> example <*> example <*> example instance Example WalletImport where example = WalletImport <$> example <*> pure "/Users/foo/Documents/wallet_to_import.key" data ErrNotEnoughMoney = ErrCannotCoverFee We record the available balance of the UTxO | ErrAvailableBalanceIsInsufficient Int deriving (Eq, Show, Generic) instance Buildable ErrNotEnoughMoney where build = \case ErrCannotCoverFee -> bprint "Not enough coins to cover fee." ErrAvailableBalanceIsInsufficient _ -> bprint "Not enough available coins to proceed." instance ToJSON ErrNotEnoughMoney where toJSON = \case e@ErrCannotCoverFee -> object [ "msg" .= sformat build e ] e@(ErrAvailableBalanceIsInsufficient balance) -> object [ "msg" .= sformat build e , "availableBalance" .= balance ] instance FromJSON ErrNotEnoughMoney where parseJSON v = withObject "AvailableBalanceIsInsufficient" availableBalanceIsInsufficientParser v <|> withObject "CannotCoverFee" cannotCoverFeeParser v where cannotCoverFeeParser :: Object -> Parser ErrNotEnoughMoney cannotCoverFeeParser o = do msg <- o .: "msg" when (msg /= sformat build ErrCannotCoverFee) mempty pure ErrCannotCoverFee availableBalanceIsInsufficientParser :: Object -> Parser ErrNotEnoughMoney availableBalanceIsInsufficientParser o = do msg <- o .: "msg" when (msg /= sformat build (ErrAvailableBalanceIsInsufficient 0)) mempty ErrAvailableBalanceIsInsufficient <$> (o .: "availableBalance") data ErrUtxoNotEnoughFragmented = ErrUtxoNotEnoughFragmented { theMissingUtxos :: !Int , theHelp :: !Text } deriving (Eq, Generic, Show) msgUtxoNotEnoughFragmented :: Text msgUtxoNotEnoughFragmented = "Utxo is not enough fragmented to handle the number of outputs of this transaction. Query /api/v1/wallets/{walletId}/statistics/utxos endpoint for more information" deriveJSON Aeson.defaultOptions ''ErrUtxoNotEnoughFragmented instance Buildable ErrUtxoNotEnoughFragmented where build (ErrUtxoNotEnoughFragmented missingUtxos _ ) = bprint ("Missing "%build%" utxo(s) to accommodate all outputs of the transaction") missingUtxos Errors are represented in JSON in the JSend format ( < > ): where ` < constr_name > ` is a string containing name of error 's constructor ( ) , a ` we ` prefix , for ` OutputIsRedeem ` error " diagnostic " field will be the following : Otherwise TemplateHaskell will raise an error . If constructor does not have additional data ( like in case of ` WalletNotFound ` error ) , data WalletError = NotEnoughMoney !ErrNotEnoughMoney | OutputIsRedeem !(V1 Core.Address) | UnknownError !Text | InvalidAddressFormat weMsg | InvalidAddressFormat !Text | WalletNotFound | WalletAlreadyExists !WalletId | AddressNotFound | TxFailedToStabilize | InvalidPublicKey !Text | UnsignedTxCreationError | TooBigTransaction | SignedTxSubmitError !Text | TxRedemptionDepleted | TxSafeSignerNotFound !(V1 Core.Address) | MissingRequiredParams !(NonEmpty (Text, Text)) | CannotCreateAddress !Text | WalletIsNotReadyToProcessPayments !SyncProgress restoring ) and thus can not accept new @Payment@ requests . | NodeIsStillSyncing !SyncPercentage | RequestThrottled !Word64 | UtxoNotEnoughFragmented !ErrUtxoNotEnoughFragmented ^ available is not enough fragmented , ie . , there is more outputs of transaction than deriving (Generic, Show, Eq) deriveGeneric ''WalletError instance Exception WalletError instance ToHttpErrorStatus WalletError instance ToJSON WalletError where toJSON = jsendErrorGenericToJSON instance FromJSON WalletError where parseJSON = jsendErrorGenericParseJSON instance Arbitrary WalletError where arbitrary = Gen.oneof [ NotEnoughMoney <$> Gen.oneof [ pure ErrCannotCoverFee , ErrAvailableBalanceIsInsufficient <$> Gen.choose (1, 1000) ] , OutputIsRedeem . V1 <$> arbitrary , UnknownError <$> arbitraryText , InvalidAddressFormat <$> arbitraryText , pure WalletNotFound , WalletAlreadyExists <$> arbitrary , pure AddressNotFound , InvalidPublicKey <$> arbitraryText , pure UnsignedTxCreationError , SignedTxSubmitError <$> arbitraryText , pure TooBigTransaction , pure TxFailedToStabilize , pure TxRedemptionDepleted , TxSafeSignerNotFound . V1 <$> arbitrary , MissingRequiredParams <$> Gen.oneof [ unsafeMkNonEmpty <$> Gen.vectorOf 1 arbitraryParam , unsafeMkNonEmpty <$> Gen.vectorOf 2 arbitraryParam , unsafeMkNonEmpty <$> Gen.vectorOf 3 arbitraryParam ] , WalletIsNotReadyToProcessPayments <$> arbitrary , NodeIsStillSyncing <$> arbitrary , CannotCreateAddress <$> arbitraryText , RequestThrottled <$> arbitrary , UtxoNotEnoughFragmented <$> Gen.oneof [ ErrUtxoNotEnoughFragmented <$> Gen.choose (1, 10) <*> arbitrary ] ] where arbitraryText :: Gen Text arbitraryText = toText . Gen.getASCIIString <$> arbitrary arbitraryParam :: Gen (Text, Text) arbitraryParam = (,) <$> arbitrary <*> arbitrary unsafeMkNonEmpty :: [a] -> NonEmpty a unsafeMkNonEmpty (h:q) = h :| q unsafeMkNonEmpty _ = error "unsafeMkNonEmpty called with empty list" instance Buildable WalletError where build = \case NotEnoughMoney x -> bprint build x OutputIsRedeem _ -> bprint "One of the TX outputs is a redemption address." UnknownError _ -> bprint "Unexpected internal error." InvalidAddressFormat _ -> bprint "Provided address format is not valid." WalletNotFound -> bprint "Reference to an unexisting wallet was given." WalletAlreadyExists _ -> bprint "Can't create or restore a wallet. The wallet already exists." AddressNotFound -> bprint "Reference to an unexisting address was given." InvalidPublicKey _ -> bprint "Extended public key (for external wallet) is invalid." UnsignedTxCreationError -> bprint "Unable to create unsigned transaction for an external wallet." TooBigTransaction -> bprint "Transaction size is greater than 4096 bytes." SignedTxSubmitError _ -> bprint "Unable to submit externally-signed transaction." MissingRequiredParams _ -> bprint "Missing required parameters in the request payload." WalletIsNotReadyToProcessPayments _ -> bprint "This wallet is restoring, and it cannot send new transactions until restoration completes." NodeIsStillSyncing _ -> bprint "The node is still syncing with the blockchain, and cannot process the request yet." TxRedemptionDepleted -> bprint "The redemption address was already used." TxSafeSignerNotFound _ -> bprint "The safe signer at the specified address was not found." TxFailedToStabilize -> bprint "We were unable to find a set of inputs to satisfy this transaction." CannotCreateAddress _ -> bprint "Cannot create derivation path for new address, for external wallet." RequestThrottled _ -> bprint "You've made too many requests too soon, and this one was throttled." UtxoNotEnoughFragmented x -> bprint build x instance ToServantError WalletError where declareServantError = \case NotEnoughMoney{} -> err403 OutputIsRedeem{} -> err403 UnknownError{} -> err500 WalletNotFound{} -> err404 WalletAlreadyExists{} -> err403 InvalidAddressFormat{} -> err401 AddressNotFound{} -> err404 InvalidPublicKey{} -> err400 UnsignedTxCreationError{} -> err500 TooBigTransaction{} -> err400 SignedTxSubmitError{} -> err500 MissingRequiredParams{} -> err400 WalletIsNotReadyToProcessPayments{} -> err403 NodeIsStillSyncing{} -> Precondition failed TxFailedToStabilize{} -> err500 TxRedemptionDepleted{} -> err400 TxSafeSignerNotFound{} -> err400 CannotCreateAddress{} -> err500 RequestThrottled{} -> err400 { errHTTPCode = 429 } UtxoNotEnoughFragmented{} -> err403 instance HasDiagnostic WalletError where getDiagnosticKey = \case NotEnoughMoney{} -> "details" OutputIsRedeem{} -> "address" UnknownError{} -> "msg" WalletNotFound{} -> noDiagnosticKey WalletAlreadyExists{} -> "walletId" InvalidAddressFormat{} -> "msg" AddressNotFound{} -> noDiagnosticKey InvalidPublicKey{} -> "msg" UnsignedTxCreationError{} -> noDiagnosticKey TooBigTransaction{} -> noDiagnosticKey SignedTxSubmitError{} -> "msg" MissingRequiredParams{} -> "params" WalletIsNotReadyToProcessPayments{} -> "stillRestoring" NodeIsStillSyncing{} -> "stillSyncing" TxFailedToStabilize{} -> noDiagnosticKey TxRedemptionDepleted{} -> noDiagnosticKey TxSafeSignerNotFound{} -> "address" CannotCreateAddress{} -> "msg" RequestThrottled{} -> "microsecondsUntilRetry" UtxoNotEnoughFragmented{} -> "details"
7f08d991194b1fe0872379aaa3bef3f5e9f9de930662188fb27aa1d2857d8ae7
samrushing/irken-compiler
t_rx.scm
;; -*- Mode: Irken -*- (include "lib/basis.scm") (include "lib/map.scm") (include "lib/counter.scm") (include "lib/dfa/charset.scm") (include "lib/dfa/rx.scm") (printf (rx-repr (parse-rx "[A-Z]+")) "\n") (printf (rx-repr (parse-rx "(ab+)?")) "\n") (printf (rx-repr (parse-rx "a*bca*")) "\n") (printf (rx-repr (parse-rx "([abc]~)?[de]+")) "\n") (printf (rx-repr (parse-rx "[a-z]\\[0")) "\n") (let ((r0 (parse-rx "a+b*a+")) (r1 (parse-rx "a+b*a+"))) (printf "r0 < r1 = " (bool (rx< r0 r1)) "\n") (printf "r1 < r0 = " (bool (rx< r1 r0)) "\n") ) (let ((r0 (parse-rx "a+")) (r1 (parse-rx "a+"))) (printf "r0 < r1 = " (bool (rx< r0 r1)) "\n") (printf "r1 < r0 = " (bool (rx< r1 r0)) "\n") ) (printf (pp-rx (parse-rx "((ab)~c)~d*")) "\n") (printf (pp-rx (parse-rx "{(ab)~c}~d*")) "\n")
null
https://raw.githubusercontent.com/samrushing/irken-compiler/690da48852d55497f873738df54f14e8e135d006/tests/dfa/t_rx.scm
scheme
-*- Mode: Irken -*-
(include "lib/basis.scm") (include "lib/map.scm") (include "lib/counter.scm") (include "lib/dfa/charset.scm") (include "lib/dfa/rx.scm") (printf (rx-repr (parse-rx "[A-Z]+")) "\n") (printf (rx-repr (parse-rx "(ab+)?")) "\n") (printf (rx-repr (parse-rx "a*bca*")) "\n") (printf (rx-repr (parse-rx "([abc]~)?[de]+")) "\n") (printf (rx-repr (parse-rx "[a-z]\\[0")) "\n") (let ((r0 (parse-rx "a+b*a+")) (r1 (parse-rx "a+b*a+"))) (printf "r0 < r1 = " (bool (rx< r0 r1)) "\n") (printf "r1 < r0 = " (bool (rx< r1 r0)) "\n") ) (let ((r0 (parse-rx "a+")) (r1 (parse-rx "a+"))) (printf "r0 < r1 = " (bool (rx< r0 r1)) "\n") (printf "r1 < r0 = " (bool (rx< r1 r0)) "\n") ) (printf (pp-rx (parse-rx "((ab)~c)~d*")) "\n") (printf (pp-rx (parse-rx "{(ab)~c}~d*")) "\n")
efd456c42d078e95f743b7efae1731e872e004a19ed4a4e1f279011151f65c84
fulcrologic/fulcro
mock_server_remote.cljs
(ns com.fulcrologic.fulcro.networking.mock-server-remote "Simple adapter code that allows you to use a generic parser 'as if' it were a client remote in CLJS." (:require [com.fulcrologic.fulcro.algorithms.tx-processing :as txn] [taoensso.timbre :as log] [edn-query-language.core :as eql] [cljs.core.async :as async])) (defn mock-http-server "Create a remote that mocks a Fulcro remote server. :parser - A function `(fn [eql-query] async-channel)` that returns a core async channel with the result for the given eql-query." [{:keys [parser] :as options}] (merge options {:transmit! (fn transmit! [{:keys [active-requests]} {:keys [::txn/ast ::txn/result-handler ::txn/update-handler] :as send-node}] (let [edn (eql/ast->query ast) ok-handler (fn [result] (try (result-handler (select-keys result #{:transaction :status-code :body :status-text})) (catch :default e (log/error e "Result handler failed with an exception. See /#err-msr-res-handler-exc")))) error-handler (fn [error-result] (try (result-handler (merge {:status-code 500} (select-keys error-result #{:transaction :status-code :body :status-text}))) (catch :default e (log/error e "Error handler failed with an exception. See /#err-msr-err-handler-exc"))))] (try (async/go (let [result (async/<! (parser edn))] (ok-handler {:transaction edn :status-code 200 :body result}))) (catch :default e (error-handler {:transaction edn :status-code 500}))))) :abort! (fn abort! [this id])}))
null
https://raw.githubusercontent.com/fulcrologic/fulcro/71ed79c650222567ac4a566513365a95f12657e3/src/main/com/fulcrologic/fulcro/networking/mock_server_remote.cljs
clojure
(ns com.fulcrologic.fulcro.networking.mock-server-remote "Simple adapter code that allows you to use a generic parser 'as if' it were a client remote in CLJS." (:require [com.fulcrologic.fulcro.algorithms.tx-processing :as txn] [taoensso.timbre :as log] [edn-query-language.core :as eql] [cljs.core.async :as async])) (defn mock-http-server "Create a remote that mocks a Fulcro remote server. :parser - A function `(fn [eql-query] async-channel)` that returns a core async channel with the result for the given eql-query." [{:keys [parser] :as options}] (merge options {:transmit! (fn transmit! [{:keys [active-requests]} {:keys [::txn/ast ::txn/result-handler ::txn/update-handler] :as send-node}] (let [edn (eql/ast->query ast) ok-handler (fn [result] (try (result-handler (select-keys result #{:transaction :status-code :body :status-text})) (catch :default e (log/error e "Result handler failed with an exception. See /#err-msr-res-handler-exc")))) error-handler (fn [error-result] (try (result-handler (merge {:status-code 500} (select-keys error-result #{:transaction :status-code :body :status-text}))) (catch :default e (log/error e "Error handler failed with an exception. See /#err-msr-err-handler-exc"))))] (try (async/go (let [result (async/<! (parser edn))] (ok-handler {:transaction edn :status-code 200 :body result}))) (catch :default e (error-handler {:transaction edn :status-code 500}))))) :abort! (fn abort! [this id])}))
16f570e841378709faf239d7bcc8e575e2250356084f87cbb766edda45ef3ef9
scicloj/tablecloth
project.clj
(defproject scicloj/tablecloth "7.000-beta-27" :description "Dataset manipulation library built on the top of tech.ml.dataset." :url "" :license {:name "The MIT Licence" :url ""} :plugins [[lein-tools-deps "0.4.5"]] :middleware [lein-tools-deps.plugin/resolve-dependencies-with-deps-edn] :lein-tools-deps/config {:config-files [:install :user :project]} :profiles {:dev {:cloverage {:runner :midje} :dependencies [[midje "1.9.9"]] :plugins [[lein-midje "3.2.1"] [lein-cloverage "1.1.2"]]}})
null
https://raw.githubusercontent.com/scicloj/tablecloth/1e9c8d88c46cdf4492f8fd0e219b4f6af94886a9/project.clj
clojure
(defproject scicloj/tablecloth "7.000-beta-27" :description "Dataset manipulation library built on the top of tech.ml.dataset." :url "" :license {:name "The MIT Licence" :url ""} :plugins [[lein-tools-deps "0.4.5"]] :middleware [lein-tools-deps.plugin/resolve-dependencies-with-deps-edn] :lein-tools-deps/config {:config-files [:install :user :project]} :profiles {:dev {:cloverage {:runner :midje} :dependencies [[midje "1.9.9"]] :plugins [[lein-midje "3.2.1"] [lein-cloverage "1.1.2"]]}})
ad109118774f672f0bc4f67eff8d902c4c8708d80546b2139f88c3a0bd487c59
inhabitedtype/ocaml-aws
describeMaintenanceWindowExecutions.mli
open Types type input = DescribeMaintenanceWindowExecutionsRequest.t type output = DescribeMaintenanceWindowExecutionsResult.t type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
null
https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/3bc554af7ae7ef9e2dcea44a1b72c9e687435fa9/libraries/ssm/lib/describeMaintenanceWindowExecutions.mli
ocaml
open Types type input = DescribeMaintenanceWindowExecutionsRequest.t type output = DescribeMaintenanceWindowExecutionsResult.t type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
353fba1fc8229b712fc58222f05681388f6f1b971ec01e306e16de013f2312d8
papers-we-love/seattle
slides.rkt
#lang slideshow (slide #:title "Papers We Love 2017" (para #:align 'center "The Styx Architecture for Distributed Systems") (para #:align 'center "Rob Pike and Dennis M. Ritchie, 1999")) (slide #:title "Definitions" (item "Plan 9 (from Bell Labs)") (subitem "a distributed operating system") (item "9P") (subitem "a simple message-oriented file system protocol") (item "Inferno") (subitem "a commercialized distributed portable operating system") (item "Styx") (subitem "an update of 9P for Inferno, officially '9P2000'") ) (slide #:title "What?" (para "What is a file? ") 'next (item "Just a miserable pile of bytes!") 'next (item "What does it matter where they come from in your program?") 'next (bitmap "tweet_pike.png")) (slide #:title "9p operations" (para (list (tt "version") " : start a new session")) (para (list (tt "attach/auth") " : attach/auth to the root of a file tree")) (para (list (tt "walk") " : walk up or down in the file tree")) (para (list (tt "open") " : open a file (directory) checking permissions")) (para (list (tt "create/remove") " : create or remove a file")) (para (list (tt "read/write") " : read or write data from an open file")) (para (list (tt "stat/wstat") " : retrieve or write a file’s attributes")) (para (list (tt "flush") " : flush pending requests (eg, on interrupt)")) (para (list (tt "clunk") " : discard a file tree reference (ie, close)")) (para (list (tt "error") " : (not an operation) error reply with diagnostic")) ) (slide #:title "OS-level operations" (para (list (tt "bind") ": create a new reference to another file/directory")) (subitem "(the original union mount!)") (para (list (tt "mount") " : create a reference to a file server on an existing directory")) (para (list (tt "unmount") " : remove a bind or mount reference")) (para (list (tt "exportfs") " : translates file calls into system calls and vice-versa," (it "itself as a file server")) ) ) (slide #:title "Thus!" (item "A \"file server\" is any program that manufactures a name space by implementing the server-side of 9P") 'next (item (list "The entire name space is thus" (it "computable"))) 'next (item (list "There is" (it "no") "true name space")) 'next (subitem "The Farnsworth Parabox") 'next (item "open /net/tcp/clone -> /net/tcp/42") 'next (subitem "It didn't exist a second ago!") 'next (subitem "No other process can see it!") 'next (subitem "do it again -> /net/tcp/43") ) (slide #:title "Relate this to programming!" 'next (para "\"to jail a process, simply give it a namespace that doesn't have anything you don't want it to\"") 'next (item "Lua: setfenv / setupvalue") 'next (subitem "Just provide a table of functions to an environment!") 'next (item "Io / Self") 'next (subitem "Just remove the base slot reference once you have an object setup!") 'next (item "Smalltalk") 'next (subitem "Message-send and truly private variables (ok, reaching)")) (slide #:title "Uses:" (item "Devices!") (subitem "PathStar") 'next (item "Shells!") (subitem "cpu / rc") 'next (item "IPC / Message bus!") (subitem "plumber") 'next (item "Graphics!") (subitem "rio") 'next ;(item "Mail reader!") ( subitem " upas " ) (item "IDE!") (subitem "acme") ) (slide (para #:align 'center "Styx On A Brick") 'next (para #:align 'center "(a serious write-up)")) (slide (para #:align 'center "An example of a \"distributed system\"") 'next (para #:align 'center "...but done as a LAN over exotic data links") ) (slide #:title "But on an embedded device?" 'next (item "Nobody says you need a full 9P implementation") 'next (subitem (list "you just need "(it "enough"))) 'next (item "Can fake qids or subsidiary nodes to reduce code size") ) (slide #:title "an aside" 'next (item "like the Scheme of network protocols") 'next (subitem "For the most part, it is very simple, but people see need to extend it to fit their environments.") 'next (subitem "Luckily this is done in ways that are often backwards compatible.") ) (slide #:title "Mapping physical devices" 'next (item "Just make them \"files!\"") 'next (subitem "Read = sensors") 'next (subitem "Write = motors") 'next (item "Let the bind'ee determine how to use them!") ) (slide #:title "But unsaaafe!" 'next (item "McIlroy vs. Knuth") 'next (subitem "6 lines and 4 Unix commands to replace an entire literate program") 'next (item "It may not be safe, but that's not what it's for")) (slide #:title "But 9P isn't used anymore, right?" 'next (item "QEMU: libvirt") (item "Erlang-on-Xen: code loading, storage access, node monitoring, message passing, goofs(filesystem)") (item " : supercomputing interconnect") (item "Forsyth's use of inferno for grid computing") ) (slide #:title "Wrapup" 'next (para #:align 'center "I love this paper!") 'next (para #:align 'center "The idea is so simple, almost trivial") 'next (para #:align 'center "\"Everything falls out of doing the little stuff right\"") 'next (para #:align 'center "It gives discoverability back to the user, doesn't remove need for docs/protocols/agreements") ) (current-font-size 24) (slide #:title "Further reading/watching" (para #:align 'center "The Ubiquitious File Server in Plan 9 : ") (para #:align 'center "-v.org/plan_9/misc/ubiquitous_fileserver/ubiquitous_fileserver.pdf") (para #:align 'center "LP49: Embedded system OS based on L4 and Plan 9 : ") (para #:align 'center"") (para #:align 'center"OSHUG 46 — The Name Game, feat. Plan 9 & Inferno, Dr Charles Forsyth : ") (para #:align 'center"") )
null
https://raw.githubusercontent.com/papers-we-love/seattle/9b5e847058c96292e377f763ba4cf9740e26de75/styx-architecture/slides.rkt
racket
(item "Mail reader!")
#lang slideshow (slide #:title "Papers We Love 2017" (para #:align 'center "The Styx Architecture for Distributed Systems") (para #:align 'center "Rob Pike and Dennis M. Ritchie, 1999")) (slide #:title "Definitions" (item "Plan 9 (from Bell Labs)") (subitem "a distributed operating system") (item "9P") (subitem "a simple message-oriented file system protocol") (item "Inferno") (subitem "a commercialized distributed portable operating system") (item "Styx") (subitem "an update of 9P for Inferno, officially '9P2000'") ) (slide #:title "What?" (para "What is a file? ") 'next (item "Just a miserable pile of bytes!") 'next (item "What does it matter where they come from in your program?") 'next (bitmap "tweet_pike.png")) (slide #:title "9p operations" (para (list (tt "version") " : start a new session")) (para (list (tt "attach/auth") " : attach/auth to the root of a file tree")) (para (list (tt "walk") " : walk up or down in the file tree")) (para (list (tt "open") " : open a file (directory) checking permissions")) (para (list (tt "create/remove") " : create or remove a file")) (para (list (tt "read/write") " : read or write data from an open file")) (para (list (tt "stat/wstat") " : retrieve or write a file’s attributes")) (para (list (tt "flush") " : flush pending requests (eg, on interrupt)")) (para (list (tt "clunk") " : discard a file tree reference (ie, close)")) (para (list (tt "error") " : (not an operation) error reply with diagnostic")) ) (slide #:title "OS-level operations" (para (list (tt "bind") ": create a new reference to another file/directory")) (subitem "(the original union mount!)") (para (list (tt "mount") " : create a reference to a file server on an existing directory")) (para (list (tt "unmount") " : remove a bind or mount reference")) (para (list (tt "exportfs") " : translates file calls into system calls and vice-versa," (it "itself as a file server")) ) ) (slide #:title "Thus!" (item "A \"file server\" is any program that manufactures a name space by implementing the server-side of 9P") 'next (item (list "The entire name space is thus" (it "computable"))) 'next (item (list "There is" (it "no") "true name space")) 'next (subitem "The Farnsworth Parabox") 'next (item "open /net/tcp/clone -> /net/tcp/42") 'next (subitem "It didn't exist a second ago!") 'next (subitem "No other process can see it!") 'next (subitem "do it again -> /net/tcp/43") ) (slide #:title "Relate this to programming!" 'next (para "\"to jail a process, simply give it a namespace that doesn't have anything you don't want it to\"") 'next (item "Lua: setfenv / setupvalue") 'next (subitem "Just provide a table of functions to an environment!") 'next (item "Io / Self") 'next (subitem "Just remove the base slot reference once you have an object setup!") 'next (item "Smalltalk") 'next (subitem "Message-send and truly private variables (ok, reaching)")) (slide #:title "Uses:" (item "Devices!") (subitem "PathStar") 'next (item "Shells!") (subitem "cpu / rc") 'next (item "IPC / Message bus!") (subitem "plumber") 'next (item "Graphics!") (subitem "rio") 'next ( subitem " upas " ) (item "IDE!") (subitem "acme") ) (slide (para #:align 'center "Styx On A Brick") 'next (para #:align 'center "(a serious write-up)")) (slide (para #:align 'center "An example of a \"distributed system\"") 'next (para #:align 'center "...but done as a LAN over exotic data links") ) (slide #:title "But on an embedded device?" 'next (item "Nobody says you need a full 9P implementation") 'next (subitem (list "you just need "(it "enough"))) 'next (item "Can fake qids or subsidiary nodes to reduce code size") ) (slide #:title "an aside" 'next (item "like the Scheme of network protocols") 'next (subitem "For the most part, it is very simple, but people see need to extend it to fit their environments.") 'next (subitem "Luckily this is done in ways that are often backwards compatible.") ) (slide #:title "Mapping physical devices" 'next (item "Just make them \"files!\"") 'next (subitem "Read = sensors") 'next (subitem "Write = motors") 'next (item "Let the bind'ee determine how to use them!") ) (slide #:title "But unsaaafe!" 'next (item "McIlroy vs. Knuth") 'next (subitem "6 lines and 4 Unix commands to replace an entire literate program") 'next (item "It may not be safe, but that's not what it's for")) (slide #:title "But 9P isn't used anymore, right?" 'next (item "QEMU: libvirt") (item "Erlang-on-Xen: code loading, storage access, node monitoring, message passing, goofs(filesystem)") (item " : supercomputing interconnect") (item "Forsyth's use of inferno for grid computing") ) (slide #:title "Wrapup" 'next (para #:align 'center "I love this paper!") 'next (para #:align 'center "The idea is so simple, almost trivial") 'next (para #:align 'center "\"Everything falls out of doing the little stuff right\"") 'next (para #:align 'center "It gives discoverability back to the user, doesn't remove need for docs/protocols/agreements") ) (current-font-size 24) (slide #:title "Further reading/watching" (para #:align 'center "The Ubiquitious File Server in Plan 9 : ") (para #:align 'center "-v.org/plan_9/misc/ubiquitous_fileserver/ubiquitous_fileserver.pdf") (para #:align 'center "LP49: Embedded system OS based on L4 and Plan 9 : ") (para #:align 'center"") (para #:align 'center"OSHUG 46 — The Name Game, feat. Plan 9 & Inferno, Dr Charles Forsyth : ") (para #:align 'center"") )
39d3c5d75d25d36395a4e998e0609d1691b65c5b23af7ead36f5f778ea46dfc7
FlowerWrong/mblog
lib_misc.erl
%% --- Excerpted from " Programming Erlang , Second Edition " , published by The Pragmatic Bookshelf . %% Copyrights apply to this code. It may not be used to create training material, %% courses, books, articles, and the like. Contact us if you are in doubt. %% We make no guarantees that this code is fit for any purpose. %% Visit for more book information. %%--- -module(lib_misc). %% commonly used routines -export([consult/1, dump/2, first/1, for/3, is_prefix/2, deliberate_error/1, deliberate_error1/1, duplicates/1, downcase_char/1, downcase_str/1, extract_attribute/2, eval_file/1, every/3, file_size_and_type/1, flush_buffer/0, foreachWordInFile/2, foreachWordInString/2, keep_alive/2, glurk/2, lookup/2, odds_and_evens1/1, odds_and_evens2/1, on_exit/2, make_global/2, make_test_strings/1, merge_kv/1, ndots/1, test_function_over_substrings/2, partition/2, pmap/2, pmap1/2, priority_receive/0, pythag/1, replace/3, split/2, safe/1, too_hot/0, ls/1, mini_shell/0, odd/1, outOfDate/2, exists/1, perms/1, qsort/1, random_seed/0, read_file_as_lines/1, remove_duplicates/1, remove_prefix/2, remove_leading_whitespace/1, remove_trailing_whitespace/1, rpc/2, spawn_monitor/3, sum/1, sqrt/1, string2term/1, string2value/1, term2string/1, term2file/2, file2term/1, longest_common_prefix/1, unconsult/2]). -export([complete/2, skip_blanks/1, trim_blanks/1, sleep/1, split_at_char/2, mk_tree/1 , is_blank_line/1, have_common_prefix/1]). -import(lists, [all/2, any/2, filter/2, reverse/1, reverse/2, foreach/2, map/2, member/2, sort/1]). -define(NYI(X),(begin io:format("*** NYI ~p ~p ~p~n",[?MODULE, ?LINE, X]), exit(nyi) end)). glurk(X, Y) -> ?NYI({glurk, X, Y}). -include_lib("kernel/include/file.hrl"). file_size_and_type(File) -> case file:read_file_info(File) of {ok, Facts} -> {Facts#file_info.type, Facts#file_info.size}; _ -> error end. ls(Dir) -> {ok, L} = file:list_dir(Dir), lists:map(fun(I) -> {I, file_size_and_type(I)} end, lists:sort(L)). consult(File) -> case file:open(File, read) of {ok, S} -> Val = consult1(S), file:close(S), {ok, Val}; {error, Why} -> {error, Why} end. consult1(S) -> case io:read(S, '') of {ok, Term} -> [Term|consult1(S)]; eof -> []; Error -> Error end. dump(File, Term) -> Out = File ++ ".tmp", io:format("** dumping to ~s~n",[Out]), {ok, S} = file:open(Out, [write]), io:format(S, "~p.~n",[Term]), file:close(S). partition(F, L) -> partition(F, L, [], []). partition(F, [H|T], Yes, No) -> case F(H) of true -> partition(F, T, [H|Yes], No); false -> partition(F, T, Yes, [H|No]) end; partition(_, [], Yes, No) -> {Yes, No}. remove_duplicates(L) -> remove_duplicates(lists:sort(L), []). remove_duplicates([H|X=[H|_]], L) -> remove_duplicates(X, L); remove_duplicates([H|T], L) -> remove_duplicates(T, [H|L]); remove_duplicates([], L) -> L. %% is_prefix(A, B) -> bool() %% true if A is a prefix of B is_prefix([], _) -> true; is_prefix([H|T], [H|T1]) -> is_prefix(T, T1); is_prefix(_, _) -> false. first([_]) -> []; first([H|T]) -> [H|first(T)]. sleep(T) -> receive after T -> true end. flush_buffer() -> receive _Any -> flush_buffer() after 0 -> true end. priority_receive() -> receive {alarm, X} -> {alarm, X} after 0 -> receive Any -> Any end end. duplicates(X) -> find_duplicates(sort(X), []). find_duplicates([H,H|T], [H|_]=L) -> find_duplicates(T, L); find_duplicates([H,H|T], L) -> find_duplicates(T, [H|L]); find_duplicates([_|T], L) -> find_duplicates(T, L); find_duplicates([], L) -> L. %% complete(A, L) -> {yes, S} %% error - means no string will ever match %% {more,L} - means there are completions but I need more characters L = [ ] = list of possible completions %% {yes, S} - means there is a unique completion %% A = S = str ( ) , L=[str ( ) ] %% used to compute the smallest S %% such that A ++ S is a member of all elements of L complete(Str, L) -> case filter(fun(I) -> is_prefix(Str, I) end, L) of [] -> error; [L1] -> J = remove_prefix(Str, L1), {yes, J}; L1 -> %% L1 is not empty so it's either more or a string We know that is a prefix of all elements in L1 L2 = map(fun(I) -> remove_prefix(Str, I) end, L1), %% L2 will also not be empty %% io:format("L1=~p L2=~p~n",[L1,L2]), case longest_common_prefix(L2) of [] -> {more, L1}; S -> {yes, S} end end. %% remove_prefix(X, Y) -> Z %% finds Z such that X ++ Z = Y %% remove_prefix([H|T], [H|T1]) -> remove_prefix(T, T1); remove_prefix([], L) -> L. %% longest_common_prefix([str()]) -> str() longest_common_prefix(L) -> longest_common_prefix(L, []). longest_common_prefix(Ls, L) -> case have_common_prefix(Ls) of {yes, H, Ls1} -> longest_common_prefix(Ls1, [H|L]); no -> reverse(L) end. have_common_prefix([]) -> no; have_common_prefix(L) -> case any(fun is_empty_list/1, L) of true -> no; false -> %% All lists have heads and tails Heads = map(fun(I) -> hd(I) end, L), H = hd(Heads), case all(fun(X) -> hd(X) =:= H end, L) of true -> Tails = map(fun(I) -> tl(I) end, L), {yes, H, Tails}; false -> no end end. is_empty_list([]) -> true; is_empty_list(X) when is_list(X) -> false. skip_blanks([$\s|T]) -> skip_blanks(T); skip_blanks(X) -> X. trim_blanks(X) -> reverse(skip_blanks(reverse(X))). split_at_char(Str, C) -> split_at_char(Str, C, []). split_at_char([C|T], C, L) -> {yes, reverse(L), T}; split_at_char([H|T], C, L) -> split_at_char(T, C, [H|L]); split_at_char([], _, _) -> no. %% read file into line buffer read_file_as_lines(File) -> case file:read_file(File) of {ok, Bin} -> {ok, split_into_lines(binary_to_list(Bin), 1, [])}; {error, _} -> {error, eNoFile} end. split_into_lines([], _, L) -> reverse(L); split_into_lines(Str, Ln, L) -> {Line, Rest} = get_line(Str, []), split_into_lines(Rest, Ln+1, [{Ln,Line}|L]). get_line([$\n|T], L) -> {reverse(L), T}; get_line([H|T], L) -> get_line(T, [H|L]); get_line([], L) -> {reverse(L), []}. is_blank_line([$\s|T]) -> is_blank_line(T); is_blank_line([$\n|T]) -> is_blank_line(T); is_blank_line([$\r|T]) -> is_blank_line(T); is_blank_line([$\t|T]) -> is_blank_line(T); is_blank_line([]) -> true; is_blank_line(_) -> false. %%---------------------------------------------------------------------- %% lookup %%---------------------------------------------------------------------- %% split(Pred, L) -> {True, False} split(F, L) -> split(F, L, [], []). split(F, [H|T], True, False) -> case F(H) of true -> split(F, T, [H|True], False); false -> split(F, T, True, [H|False]) end; split(_, [], True, False) -> {reverse(True), reverse(False)}. %%---------------------------------------------------------------------- outOfDate(In, Out) -> case exists(Out) of true -> case {last_modified(In), last_modified(Out)} of {T1, T2} when T1 > T2 -> true; _ -> false end; false -> true end. last_modified(File) -> case file:read_file_info(File) of {ok, Info} -> Info#file_info.mtime; _ -> 0 end. exists(File) -> case file:read_file_info(File) of {ok, _} -> true; _ -> false end. %%---------------------------------------------------------------------- replace(Key , , [ { Key , Val } ] ) - > [ { Key , Val } ] replace and Key with Key , in the association list Old replace(Key, Val, Old) -> replace(Key, Val, Old, []). replace(Key, Val1, [{Key,_Val}|T], L) -> reverse(L, [{Key, Val1}|T]); replace(Key, Val, [H|T], L) -> replace(Key, Val, T, [H|L]); replace(Key, Val, [], L) -> [{Key,Val}|L]. %%---------------------------------------------------------------------- %% make_test_strings(Str) %% make_test_strings(Str) -> L = length(Str), make_test_strings(Str, L+1, 1). make_test_strings(_, Max, Max) -> []; make_test_strings(Str, Max, N) -> [string:sub_string(Str, 1, N)|make_test_strings(Str, Max, N+1)]. test_function_over_substrings(F, Str) -> L = make_test_strings(Str), foreach(fun(S) -> io:format("|~s|~n => ~p~n", [S, F(S)]) end, L). %%---------------------------------------------------------------------- %% merge_kv(Kv) -> Kv' %% Take a association list of {Key, Val} where Key can occure More than once and make it into a list { Key , [ ] } where %% each Key occurs only once merge_kv(KV) -> merge_kv(KV, dict:new()). merge_kv([{Key,Val}|T], D0) -> case dict:find(Key, D0) of {ok, L} -> merge_kv(T, dict:store(Key, [Val|L], D0)); error -> merge_kv(T, dict:store(Key, [Val], D0)) end; merge_kv([], D) -> dict:to_list(D). %% rpc/2 %% rpc(Pid, Q) -> Pid ! {self(), Q}, receive {Pid, Reply} -> Reply end. %% odd(X) %% odd(X) -> case X band 1 of 1 -> true; 0 -> false end. ndots([$.|T]) -> 1 + ndots(T); ndots([_|T]) -> ndots(T); ndots([]) -> 0. term2file(File, Term) -> file:write_file(File, term_to_binary(Term)). file2term(File) -> {ok, Bin} = file:read_file(File), binary_to_term(Bin). string2term(Str) -> {ok,Tokens,_} = erl_scan:string(Str ++ "."), {ok,Term} = erl_parse:parse_term(Tokens), Term. term2string(Term) -> lists:flatten(io_lib:format("~p",[Term])). downcase_str(Str) -> map(fun downcase_char/1, Str). downcase_char(X) when $A =< X, X =< $Z -> X+ $a - $A; downcase_char(X) -> X. string2value(Str) -> {ok, Tokens, _} = erl_scan:string(Str ++ "."), {ok, Exprs} = erl_parse:parse_exprs(Tokens), Bindings = erl_eval:new_bindings(), {value, Value, _} = erl_eval:exprs(Exprs, Bindings), Value. mini_shell() -> mini_shell(erl_eval:new_bindings()). mini_shell(Bindings0) -> case io:get_line('>>> ') of "q\n" -> void; Str -> {Value, Bindings1} = string2value(Str, Bindings0), io:format("~p~n",[Value]), mini_shell(Bindings1) end. string2value(Str, Bindings0) -> {ok, Tokens, _} = erl_scan:string(Str ++ "."), {ok, Exprs} = erl_parse:parse_exprs(Tokens), {value, Value, Bindings1} = erl_eval:exprs(Exprs, Bindings0), {Value, Bindings1}. eval_file(File) -> {ok, S} = file:open(File, [read]), Vals = eval_file(S, 1, erl_eval:new_bindings()), file:close(S), Vals. eval_file(S, Line, B0) -> case io:parse_erl_exprs(S, '', Line) of {ok, Form, Line1} -> {value, Value, B1} = erl_eval:exprs(Form, B0), [Value|eval_file(S, Line1, B1)]; {eof, _} -> [] end. remove_leading_whitespace([$\n|T]) -> remove_leading_whitespace(T); remove_leading_whitespace([$\s|T]) -> remove_leading_whitespace(T); remove_leading_whitespace([$\t|T]) -> remove_leading_whitespace(T); remove_leading_whitespace(X) -> X. remove_trailing_whitespace(X) -> reverse(remove_leading_whitespace(reverse(X))). safe(Fun) -> case (catch Fun()) of {'EXIT', Why} -> {error, Why}; Other -> Other end. too_hot() -> event_handler:event(errors, too_hot). %% spawn_monitor behaves just like spawn spawn_monitor(_, false, Fun) -> spawn(Fun); spawn_monitor(Term, true, Fun) -> spawn(fun() -> starter(Term, Fun) end). starter(Term, Fun) -> S = self(), io:format("process:~p started at:~p ~p~n", [self(), erlang:now(), Term]), Monitor = spawn_link(fun() -> amonitor(Term, S) end), receive {Monitor, ready} -> Fun() end. amonitor(Term, Parent) -> process_flag(trap_exit, true), Parent ! {self(), ready}, receive {'EXIT', Parent, Why} -> io:format("process:~p dies at:~p ~p reason:~p~n", [self(), erlang:now(), Term, Why]) end. keep_alive(Name, Fun) -> register(Name, Pid = spawn(Fun)), on_exit(Pid, fun(_Why) -> keep_alive(Name, Fun) end). %% make_global(Name, Fun) checks if there is a global process with the %% registered name Name. If there is no process it spawns a process to %% evaluate Fun() and registers it with the name Name. make_global(Name, Fun) -> S = self(), Pid = spawn(fun() -> make_global(S, Name, Fun) end), receive {Pid, Reply} -> Reply end. make_global(Parent, Name, Fun) -> case (catch register(Name, self())) of true -> Fun(); _ -> true end, Parent ! {self(), ok}. on_exit(Pid , Fun ) links to Pid . If Pid dies with reason Why then %% Fun(Why) is evaluated: on_exit(Pid, Fun) -> spawn(fun() -> Ref = monitor(process, Pid), %% <label id="code.onexit2"/> receive {'DOWN', Ref, process, Pid, Why} -> %% <label id="code.onexit3"/> Fun(Why) %% <label id="code.onexit4"/> end end). every(Pid , Time , Fun ) links to Pid then every Time Fun ( ) is evaluated . If Pid exits , this process stops . every(Pid, Time, Fun) -> spawn(fun() -> process_flag(trap_exit, true), link(Pid), every_loop(Pid, Time, Fun) end). every_loop(Pid, Time, Fun) -> receive {'EXIT', Pid, _Why} -> true after Time -> Fun(), every_loop(Pid, Time, Fun) end. for(Max, Max, F) -> [F(Max)]; for(I, Max, F) -> [F(I)|for(I+1, Max, F)]. qsort([]) -> []; qsort([Pivot|T]) -> qsort([X || X <- T, X < Pivot]) ++ [Pivot] ++ qsort([X || X <- T, X >= Pivot]). perms([]) -> [[]]; perms(L) -> [[H|T] || H <- L, T <- perms(L--[H])]. pythag(N) -> [ {A,B,C} || A <- lists:seq(1,N), B <- lists:seq(1,N), C <- lists:seq(1,N), A+B+C =< N, A*A+B*B =:= C*C ]. extract_attribute(File, Key) -> case beam_lib:chunks(File,[attributes]) of {ok, {attrs, [{attributes,L}]}} -> lookup(Key, L); _ -> exit(badFile) end. lookup(Key, [{Key,Val}|_]) -> {ok, Val}; lookup(Key, [_|T]) -> lookup(Key, T); lookup(_, []) -> error. unconsult(File, L) -> {ok, S} = file:open(File, write), lists:foreach(fun(X) -> io:format(S, "~p.~n",[X]) end, L), file:close(S). random_seed() -> {_,_,X} = erlang:now(), {H,M,S} = time(), H1 = H * X rem 32767, M1 = M * X rem 32767, S1 = S * X rem 32767, put(random_seed, {H1,M1,S1}). odds_and_evens1(L) -> Odds = [X || X <- L, (X rem 2) =:= 1], Evens = [X || X <- L, (X rem 2) =:= 0], {Odds, Evens}. odds_and_evens2(L) -> odds_and_evens_acc(L, [], []). odds_and_evens_acc([H|T], Odds, Evens) -> case (H rem 2) of 1 -> odds_and_evens_acc(T, [H|Odds], Evens); 0 -> odds_and_evens_acc(T, Odds, [H|Evens]) end; odds_and_evens_acc([], Odds, Evens) -> {Odds, Evens}. sum(L) -> sum(L, 0). sum([], N) -> N; sum([H|T], N) -> sum(T, H+N). sqrt(X) when X < 0 -> error({squareRootNegativeArgument, X}); sqrt(X) -> math:sqrt(X). pmap(F, L) -> S = self(), %% make_ref() returns a unique reference %% we'll match on this later Ref = erlang:make_ref(), Pids = map(fun(I) -> spawn(fun() -> do_f(S, Ref, F, I) end) end, L), %% gather the results gather(Pids, Ref). do_f(Parent, Ref, F, I) -> Parent ! {self(), Ref, (catch F(I))}. gather([Pid|T], Ref) -> receive {Pid, Ref, Ret} -> [Ret|gather(T, Ref)] end; gather([], _) -> []. pmap1(F, L) -> S = self(), Ref = erlang:make_ref(), foreach(fun(I) -> spawn(fun() -> do_f1(S, Ref, F, I) end) end, L), %% gather the results gather1(length(L), Ref, []). do_f1(Parent, Ref, F, I) -> Parent ! {Ref, (catch F(I))}. gather1(0, _, L) -> L; gather1(N, Ref, L) -> receive {Ref, Ret} -> gather1(N-1, Ref, [Ret|L]) end. %% evalute F(Word) for each word in the file File foreachWordInFile(File, F) -> case file:read_file(File) of {ok, Bin} -> foreachWordInString(binary_to_list(Bin), F); _ -> void end. foreachWordInString(Str, F) -> case get_word(Str) of no -> void; {Word, Str1} -> F(Word), foreachWordInString(Str1, F) end. isWordChar(X) when $A=< X, X=<$Z -> true; isWordChar(X) when $0=< X, X=<$9 -> true; isWordChar(X) when $a=< X, X=<$z -> true; isWordChar(_) -> false. get_word([H|T]) -> case isWordChar(H) of true -> collect_word(T, [H]); false -> get_word(T) end; get_word([]) -> no. collect_word([H|T]=All, L) -> case isWordChar(H) of true -> collect_word(T, [H|L]); false -> {reverse(L), All} end; collect_word([], L) -> {reverse(L), []}. deliberate_error(A) -> bad_function(A, 12), lists:reverse(A). bad_function(A, _) -> {ok, Bin} = file:open({abc,123}, A), binary_to_list(Bin). deliberate_error1(A) -> bad_function(A, 12).
null
https://raw.githubusercontent.com/FlowerWrong/mblog/3233ede938d2019a7b57391405197ac19c805b27/categories/erlang/demo/jaerlang2_code/lib_misc.erl
erlang
--- Copyrights apply to this code. It may not be used to create training material, courses, books, articles, and the like. Contact us if you are in doubt. We make no guarantees that this code is fit for any purpose. Visit for more book information. --- commonly used routines is_prefix(A, B) -> bool() true if A is a prefix of B complete(A, L) -> {yes, S} error - means no string will ever match {more,L} - means there are completions but I need more characters {yes, S} - means there is a unique completion used to compute the smallest S such that A ++ S is a member of all elements of L L1 is not empty so it's either more or a string L2 will also not be empty io:format("L1=~p L2=~p~n",[L1,L2]), remove_prefix(X, Y) -> Z finds Z such that X ++ Z = Y longest_common_prefix([str()]) -> str() All lists have heads and tails read file into line buffer ---------------------------------------------------------------------- lookup ---------------------------------------------------------------------- split(Pred, L) -> {True, False} ---------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- make_test_strings(Str) ---------------------------------------------------------------------- merge_kv(Kv) -> Kv' Take a association list of {Key, Val} where Key can occure each Key occurs only once rpc/2 odd(X) spawn_monitor behaves just like spawn make_global(Name, Fun) checks if there is a global process with the registered name Name. If there is no process it spawns a process to evaluate Fun() and registers it with the name Name. Fun(Why) is evaluated: <label id="code.onexit2"/> <label id="code.onexit3"/> <label id="code.onexit4"/> make_ref() returns a unique reference we'll match on this later gather the results gather the results evalute F(Word) for each word in the file File
Excerpted from " Programming Erlang , Second Edition " , published by The Pragmatic Bookshelf . -module(lib_misc). -export([consult/1, dump/2, first/1, for/3, is_prefix/2, deliberate_error/1, deliberate_error1/1, duplicates/1, downcase_char/1, downcase_str/1, extract_attribute/2, eval_file/1, every/3, file_size_and_type/1, flush_buffer/0, foreachWordInFile/2, foreachWordInString/2, keep_alive/2, glurk/2, lookup/2, odds_and_evens1/1, odds_and_evens2/1, on_exit/2, make_global/2, make_test_strings/1, merge_kv/1, ndots/1, test_function_over_substrings/2, partition/2, pmap/2, pmap1/2, priority_receive/0, pythag/1, replace/3, split/2, safe/1, too_hot/0, ls/1, mini_shell/0, odd/1, outOfDate/2, exists/1, perms/1, qsort/1, random_seed/0, read_file_as_lines/1, remove_duplicates/1, remove_prefix/2, remove_leading_whitespace/1, remove_trailing_whitespace/1, rpc/2, spawn_monitor/3, sum/1, sqrt/1, string2term/1, string2value/1, term2string/1, term2file/2, file2term/1, longest_common_prefix/1, unconsult/2]). -export([complete/2, skip_blanks/1, trim_blanks/1, sleep/1, split_at_char/2, mk_tree/1 , is_blank_line/1, have_common_prefix/1]). -import(lists, [all/2, any/2, filter/2, reverse/1, reverse/2, foreach/2, map/2, member/2, sort/1]). -define(NYI(X),(begin io:format("*** NYI ~p ~p ~p~n",[?MODULE, ?LINE, X]), exit(nyi) end)). glurk(X, Y) -> ?NYI({glurk, X, Y}). -include_lib("kernel/include/file.hrl"). file_size_and_type(File) -> case file:read_file_info(File) of {ok, Facts} -> {Facts#file_info.type, Facts#file_info.size}; _ -> error end. ls(Dir) -> {ok, L} = file:list_dir(Dir), lists:map(fun(I) -> {I, file_size_and_type(I)} end, lists:sort(L)). consult(File) -> case file:open(File, read) of {ok, S} -> Val = consult1(S), file:close(S), {ok, Val}; {error, Why} -> {error, Why} end. consult1(S) -> case io:read(S, '') of {ok, Term} -> [Term|consult1(S)]; eof -> []; Error -> Error end. dump(File, Term) -> Out = File ++ ".tmp", io:format("** dumping to ~s~n",[Out]), {ok, S} = file:open(Out, [write]), io:format(S, "~p.~n",[Term]), file:close(S). partition(F, L) -> partition(F, L, [], []). partition(F, [H|T], Yes, No) -> case F(H) of true -> partition(F, T, [H|Yes], No); false -> partition(F, T, Yes, [H|No]) end; partition(_, [], Yes, No) -> {Yes, No}. remove_duplicates(L) -> remove_duplicates(lists:sort(L), []). remove_duplicates([H|X=[H|_]], L) -> remove_duplicates(X, L); remove_duplicates([H|T], L) -> remove_duplicates(T, [H|L]); remove_duplicates([], L) -> L. is_prefix([], _) -> true; is_prefix([H|T], [H|T1]) -> is_prefix(T, T1); is_prefix(_, _) -> false. first([_]) -> []; first([H|T]) -> [H|first(T)]. sleep(T) -> receive after T -> true end. flush_buffer() -> receive _Any -> flush_buffer() after 0 -> true end. priority_receive() -> receive {alarm, X} -> {alarm, X} after 0 -> receive Any -> Any end end. duplicates(X) -> find_duplicates(sort(X), []). find_duplicates([H,H|T], [H|_]=L) -> find_duplicates(T, L); find_duplicates([H,H|T], L) -> find_duplicates(T, [H|L]); find_duplicates([_|T], L) -> find_duplicates(T, L); find_duplicates([], L) -> L. L = [ ] = list of possible completions A = S = str ( ) , L=[str ( ) ] complete(Str, L) -> case filter(fun(I) -> is_prefix(Str, I) end, L) of [] -> error; [L1] -> J = remove_prefix(Str, L1), {yes, J}; L1 -> We know that is a prefix of all elements in L1 L2 = map(fun(I) -> remove_prefix(Str, I) end, L1), case longest_common_prefix(L2) of [] -> {more, L1}; S -> {yes, S} end end. remove_prefix([H|T], [H|T1]) -> remove_prefix(T, T1); remove_prefix([], L) -> L. longest_common_prefix(L) -> longest_common_prefix(L, []). longest_common_prefix(Ls, L) -> case have_common_prefix(Ls) of {yes, H, Ls1} -> longest_common_prefix(Ls1, [H|L]); no -> reverse(L) end. have_common_prefix([]) -> no; have_common_prefix(L) -> case any(fun is_empty_list/1, L) of true -> no; false -> Heads = map(fun(I) -> hd(I) end, L), H = hd(Heads), case all(fun(X) -> hd(X) =:= H end, L) of true -> Tails = map(fun(I) -> tl(I) end, L), {yes, H, Tails}; false -> no end end. is_empty_list([]) -> true; is_empty_list(X) when is_list(X) -> false. skip_blanks([$\s|T]) -> skip_blanks(T); skip_blanks(X) -> X. trim_blanks(X) -> reverse(skip_blanks(reverse(X))). split_at_char(Str, C) -> split_at_char(Str, C, []). split_at_char([C|T], C, L) -> {yes, reverse(L), T}; split_at_char([H|T], C, L) -> split_at_char(T, C, [H|L]); split_at_char([], _, _) -> no. read_file_as_lines(File) -> case file:read_file(File) of {ok, Bin} -> {ok, split_into_lines(binary_to_list(Bin), 1, [])}; {error, _} -> {error, eNoFile} end. split_into_lines([], _, L) -> reverse(L); split_into_lines(Str, Ln, L) -> {Line, Rest} = get_line(Str, []), split_into_lines(Rest, Ln+1, [{Ln,Line}|L]). get_line([$\n|T], L) -> {reverse(L), T}; get_line([H|T], L) -> get_line(T, [H|L]); get_line([], L) -> {reverse(L), []}. is_blank_line([$\s|T]) -> is_blank_line(T); is_blank_line([$\n|T]) -> is_blank_line(T); is_blank_line([$\r|T]) -> is_blank_line(T); is_blank_line([$\t|T]) -> is_blank_line(T); is_blank_line([]) -> true; is_blank_line(_) -> false. split(F, L) -> split(F, L, [], []). split(F, [H|T], True, False) -> case F(H) of true -> split(F, T, [H|True], False); false -> split(F, T, True, [H|False]) end; split(_, [], True, False) -> {reverse(True), reverse(False)}. outOfDate(In, Out) -> case exists(Out) of true -> case {last_modified(In), last_modified(Out)} of {T1, T2} when T1 > T2 -> true; _ -> false end; false -> true end. last_modified(File) -> case file:read_file_info(File) of {ok, Info} -> Info#file_info.mtime; _ -> 0 end. exists(File) -> case file:read_file_info(File) of {ok, _} -> true; _ -> false end. replace(Key , , [ { Key , Val } ] ) - > [ { Key , Val } ] replace and Key with Key , in the association list Old replace(Key, Val, Old) -> replace(Key, Val, Old, []). replace(Key, Val1, [{Key,_Val}|T], L) -> reverse(L, [{Key, Val1}|T]); replace(Key, Val, [H|T], L) -> replace(Key, Val, T, [H|L]); replace(Key, Val, [], L) -> [{Key,Val}|L]. make_test_strings(Str) -> L = length(Str), make_test_strings(Str, L+1, 1). make_test_strings(_, Max, Max) -> []; make_test_strings(Str, Max, N) -> [string:sub_string(Str, 1, N)|make_test_strings(Str, Max, N+1)]. test_function_over_substrings(F, Str) -> L = make_test_strings(Str), foreach(fun(S) -> io:format("|~s|~n => ~p~n", [S, F(S)]) end, L). More than once and make it into a list { Key , [ ] } where merge_kv(KV) -> merge_kv(KV, dict:new()). merge_kv([{Key,Val}|T], D0) -> case dict:find(Key, D0) of {ok, L} -> merge_kv(T, dict:store(Key, [Val|L], D0)); error -> merge_kv(T, dict:store(Key, [Val], D0)) end; merge_kv([], D) -> dict:to_list(D). rpc(Pid, Q) -> Pid ! {self(), Q}, receive {Pid, Reply} -> Reply end. odd(X) -> case X band 1 of 1 -> true; 0 -> false end. ndots([$.|T]) -> 1 + ndots(T); ndots([_|T]) -> ndots(T); ndots([]) -> 0. term2file(File, Term) -> file:write_file(File, term_to_binary(Term)). file2term(File) -> {ok, Bin} = file:read_file(File), binary_to_term(Bin). string2term(Str) -> {ok,Tokens,_} = erl_scan:string(Str ++ "."), {ok,Term} = erl_parse:parse_term(Tokens), Term. term2string(Term) -> lists:flatten(io_lib:format("~p",[Term])). downcase_str(Str) -> map(fun downcase_char/1, Str). downcase_char(X) when $A =< X, X =< $Z -> X+ $a - $A; downcase_char(X) -> X. string2value(Str) -> {ok, Tokens, _} = erl_scan:string(Str ++ "."), {ok, Exprs} = erl_parse:parse_exprs(Tokens), Bindings = erl_eval:new_bindings(), {value, Value, _} = erl_eval:exprs(Exprs, Bindings), Value. mini_shell() -> mini_shell(erl_eval:new_bindings()). mini_shell(Bindings0) -> case io:get_line('>>> ') of "q\n" -> void; Str -> {Value, Bindings1} = string2value(Str, Bindings0), io:format("~p~n",[Value]), mini_shell(Bindings1) end. string2value(Str, Bindings0) -> {ok, Tokens, _} = erl_scan:string(Str ++ "."), {ok, Exprs} = erl_parse:parse_exprs(Tokens), {value, Value, Bindings1} = erl_eval:exprs(Exprs, Bindings0), {Value, Bindings1}. eval_file(File) -> {ok, S} = file:open(File, [read]), Vals = eval_file(S, 1, erl_eval:new_bindings()), file:close(S), Vals. eval_file(S, Line, B0) -> case io:parse_erl_exprs(S, '', Line) of {ok, Form, Line1} -> {value, Value, B1} = erl_eval:exprs(Form, B0), [Value|eval_file(S, Line1, B1)]; {eof, _} -> [] end. remove_leading_whitespace([$\n|T]) -> remove_leading_whitespace(T); remove_leading_whitespace([$\s|T]) -> remove_leading_whitespace(T); remove_leading_whitespace([$\t|T]) -> remove_leading_whitespace(T); remove_leading_whitespace(X) -> X. remove_trailing_whitespace(X) -> reverse(remove_leading_whitespace(reverse(X))). safe(Fun) -> case (catch Fun()) of {'EXIT', Why} -> {error, Why}; Other -> Other end. too_hot() -> event_handler:event(errors, too_hot). spawn_monitor(_, false, Fun) -> spawn(Fun); spawn_monitor(Term, true, Fun) -> spawn(fun() -> starter(Term, Fun) end). starter(Term, Fun) -> S = self(), io:format("process:~p started at:~p ~p~n", [self(), erlang:now(), Term]), Monitor = spawn_link(fun() -> amonitor(Term, S) end), receive {Monitor, ready} -> Fun() end. amonitor(Term, Parent) -> process_flag(trap_exit, true), Parent ! {self(), ready}, receive {'EXIT', Parent, Why} -> io:format("process:~p dies at:~p ~p reason:~p~n", [self(), erlang:now(), Term, Why]) end. keep_alive(Name, Fun) -> register(Name, Pid = spawn(Fun)), on_exit(Pid, fun(_Why) -> keep_alive(Name, Fun) end). make_global(Name, Fun) -> S = self(), Pid = spawn(fun() -> make_global(S, Name, Fun) end), receive {Pid, Reply} -> Reply end. make_global(Parent, Name, Fun) -> case (catch register(Name, self())) of true -> Fun(); _ -> true end, Parent ! {self(), ok}. on_exit(Pid , Fun ) links to Pid . If Pid dies with reason Why then on_exit(Pid, Fun) -> spawn(fun() -> receive end end). every(Pid , Time , Fun ) links to Pid then every Time Fun ( ) is evaluated . If Pid exits , this process stops . every(Pid, Time, Fun) -> spawn(fun() -> process_flag(trap_exit, true), link(Pid), every_loop(Pid, Time, Fun) end). every_loop(Pid, Time, Fun) -> receive {'EXIT', Pid, _Why} -> true after Time -> Fun(), every_loop(Pid, Time, Fun) end. for(Max, Max, F) -> [F(Max)]; for(I, Max, F) -> [F(I)|for(I+1, Max, F)]. qsort([]) -> []; qsort([Pivot|T]) -> qsort([X || X <- T, X < Pivot]) ++ [Pivot] ++ qsort([X || X <- T, X >= Pivot]). perms([]) -> [[]]; perms(L) -> [[H|T] || H <- L, T <- perms(L--[H])]. pythag(N) -> [ {A,B,C} || A <- lists:seq(1,N), B <- lists:seq(1,N), C <- lists:seq(1,N), A+B+C =< N, A*A+B*B =:= C*C ]. extract_attribute(File, Key) -> case beam_lib:chunks(File,[attributes]) of {ok, {attrs, [{attributes,L}]}} -> lookup(Key, L); _ -> exit(badFile) end. lookup(Key, [{Key,Val}|_]) -> {ok, Val}; lookup(Key, [_|T]) -> lookup(Key, T); lookup(_, []) -> error. unconsult(File, L) -> {ok, S} = file:open(File, write), lists:foreach(fun(X) -> io:format(S, "~p.~n",[X]) end, L), file:close(S). random_seed() -> {_,_,X} = erlang:now(), {H,M,S} = time(), H1 = H * X rem 32767, M1 = M * X rem 32767, S1 = S * X rem 32767, put(random_seed, {H1,M1,S1}). odds_and_evens1(L) -> Odds = [X || X <- L, (X rem 2) =:= 1], Evens = [X || X <- L, (X rem 2) =:= 0], {Odds, Evens}. odds_and_evens2(L) -> odds_and_evens_acc(L, [], []). odds_and_evens_acc([H|T], Odds, Evens) -> case (H rem 2) of 1 -> odds_and_evens_acc(T, [H|Odds], Evens); 0 -> odds_and_evens_acc(T, Odds, [H|Evens]) end; odds_and_evens_acc([], Odds, Evens) -> {Odds, Evens}. sum(L) -> sum(L, 0). sum([], N) -> N; sum([H|T], N) -> sum(T, H+N). sqrt(X) when X < 0 -> error({squareRootNegativeArgument, X}); sqrt(X) -> math:sqrt(X). pmap(F, L) -> S = self(), Ref = erlang:make_ref(), Pids = map(fun(I) -> spawn(fun() -> do_f(S, Ref, F, I) end) end, L), gather(Pids, Ref). do_f(Parent, Ref, F, I) -> Parent ! {self(), Ref, (catch F(I))}. gather([Pid|T], Ref) -> receive {Pid, Ref, Ret} -> [Ret|gather(T, Ref)] end; gather([], _) -> []. pmap1(F, L) -> S = self(), Ref = erlang:make_ref(), foreach(fun(I) -> spawn(fun() -> do_f1(S, Ref, F, I) end) end, L), gather1(length(L), Ref, []). do_f1(Parent, Ref, F, I) -> Parent ! {Ref, (catch F(I))}. gather1(0, _, L) -> L; gather1(N, Ref, L) -> receive {Ref, Ret} -> gather1(N-1, Ref, [Ret|L]) end. foreachWordInFile(File, F) -> case file:read_file(File) of {ok, Bin} -> foreachWordInString(binary_to_list(Bin), F); _ -> void end. foreachWordInString(Str, F) -> case get_word(Str) of no -> void; {Word, Str1} -> F(Word), foreachWordInString(Str1, F) end. isWordChar(X) when $A=< X, X=<$Z -> true; isWordChar(X) when $0=< X, X=<$9 -> true; isWordChar(X) when $a=< X, X=<$z -> true; isWordChar(_) -> false. get_word([H|T]) -> case isWordChar(H) of true -> collect_word(T, [H]); false -> get_word(T) end; get_word([]) -> no. collect_word([H|T]=All, L) -> case isWordChar(H) of true -> collect_word(T, [H|L]); false -> {reverse(L), All} end; collect_word([], L) -> {reverse(L), []}. deliberate_error(A) -> bad_function(A, 12), lists:reverse(A). bad_function(A, _) -> {ok, Bin} = file:open({abc,123}, A), binary_to_list(Bin). deliberate_error1(A) -> bad_function(A, 12).
d689f554a9237808b52ae621d0265b70ff5d04d19871d40215080a5de6fda866
cocreature/lrucaching
IO.hs
| Module : Data . LruCache . IO Copyright : ( c ) , 2016 ( c ) , 2015 License : : Convenience module for the common case of caching results of IO actions . See ' Data . LruCache . IO.Finalizer ' if you want to run finalizers automatically when cache entries are evicted Module : Data.LruCache.IO Copyright : (c) Moritz Kiefer, 2016 (c) Jasper Van der Jeugt, 2015 License : BSD3 Maintainer : Convenience module for the common case of caching results of IO actions. See 'Data.LruCache.IO.Finalizer' if you want to run finalizers automatically when cache entries are evicted -} module Data.LruCache.IO ( LruHandle(..) , cached , newLruHandle , StripedLruHandle(..) , stripedCached , newStripedLruHandle ) where import Control.Applicative ((<$>)) import Data.Hashable (Hashable, hash) import Data.IORef (IORef, atomicModifyIORef', newIORef) import Data.Vector (Vector) import qualified Data.Vector as Vector import Prelude hiding (lookup) import Data.LruCache | Store a LRU cache in an ' IORef to be able to conveniently update it . newtype LruHandle k v = LruHandle (IORef (LruCache k v)) | Create a new LRU cache of the given size . newLruHandle :: Int -> IO (LruHandle k v) newLruHandle capacity = LruHandle <$> newIORef (empty capacity) -- | Return the cached result of the action or, in the case of a cache -- miss, execute the action and insert it in the cache. cached :: (Hashable k, Ord k) => LruHandle k v -> k -> IO v -> IO v cached (LruHandle ref) k io = do lookupRes <- atomicModifyIORef' ref $ \c -> case lookup k c of Nothing -> (c, Nothing) Just (v, c') -> (c', Just v) case lookupRes of Just v -> return v Nothing -> do v <- io atomicModifyIORef' ref $ \c -> (insert k v c, ()) return v -- | Using a stripe of multiple handles can improve the performance in -- the case of concurrent accesses since several handles can be -- accessed in parallel. newtype StripedLruHandle k v = StripedLruHandle (Vector (LruHandle k v)) -- | Create a new 'StripedHandle' with the given number of stripes and -- the given capacity for each stripe. newStripedLruHandle :: Int -> Int -> IO (StripedLruHandle k v) newStripedLruHandle numStripes capacityPerStripe = StripedLruHandle <$> Vector.replicateM numStripes (newLruHandle capacityPerStripe) -- | Striped version of 'cached'. stripedCached :: (Hashable k, Ord k) => StripedLruHandle k v -> k -> IO v -> IO v stripedCached (StripedLruHandle v) k = cached (v Vector.! idx) k where idx = hash k `mod` Vector.length v
null
https://raw.githubusercontent.com/cocreature/lrucaching/b722777185d9df6145c8efc6ddc6057983dec5db/src/Data/LruCache/IO.hs
haskell
| Return the cached result of the action or, in the case of a cache miss, execute the action and insert it in the cache. | Using a stripe of multiple handles can improve the performance in the case of concurrent accesses since several handles can be accessed in parallel. | Create a new 'StripedHandle' with the given number of stripes and the given capacity for each stripe. | Striped version of 'cached'.
| Module : Data . LruCache . IO Copyright : ( c ) , 2016 ( c ) , 2015 License : : Convenience module for the common case of caching results of IO actions . See ' Data . LruCache . IO.Finalizer ' if you want to run finalizers automatically when cache entries are evicted Module : Data.LruCache.IO Copyright : (c) Moritz Kiefer, 2016 (c) Jasper Van der Jeugt, 2015 License : BSD3 Maintainer : Convenience module for the common case of caching results of IO actions. See 'Data.LruCache.IO.Finalizer' if you want to run finalizers automatically when cache entries are evicted -} module Data.LruCache.IO ( LruHandle(..) , cached , newLruHandle , StripedLruHandle(..) , stripedCached , newStripedLruHandle ) where import Control.Applicative ((<$>)) import Data.Hashable (Hashable, hash) import Data.IORef (IORef, atomicModifyIORef', newIORef) import Data.Vector (Vector) import qualified Data.Vector as Vector import Prelude hiding (lookup) import Data.LruCache | Store a LRU cache in an ' IORef to be able to conveniently update it . newtype LruHandle k v = LruHandle (IORef (LruCache k v)) | Create a new LRU cache of the given size . newLruHandle :: Int -> IO (LruHandle k v) newLruHandle capacity = LruHandle <$> newIORef (empty capacity) cached :: (Hashable k, Ord k) => LruHandle k v -> k -> IO v -> IO v cached (LruHandle ref) k io = do lookupRes <- atomicModifyIORef' ref $ \c -> case lookup k c of Nothing -> (c, Nothing) Just (v, c') -> (c', Just v) case lookupRes of Just v -> return v Nothing -> do v <- io atomicModifyIORef' ref $ \c -> (insert k v c, ()) return v newtype StripedLruHandle k v = StripedLruHandle (Vector (LruHandle k v)) newStripedLruHandle :: Int -> Int -> IO (StripedLruHandle k v) newStripedLruHandle numStripes capacityPerStripe = StripedLruHandle <$> Vector.replicateM numStripes (newLruHandle capacityPerStripe) stripedCached :: (Hashable k, Ord k) => StripedLruHandle k v -> k -> IO v -> IO v stripedCached (StripedLruHandle v) k = cached (v Vector.! idx) k where idx = hash k `mod` Vector.length v
f0cfd0c66a944cbc02b992bac1c475b2a0af9f1a1fd78db64fdd6906e8108cd2
bef/poc-apps
ast_ami_sup.erl
%%% %%% 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 . %%% %%% 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 %%%------------------------------------------------------------------- %%% File : ast_man_sup.erl Author : < > %%% Description : %%% Created : 29 Mar 2006 by < > %%%------------------------------------------------------------------- @private -module(ast_ami_sup). -behaviour(supervisor). %% API -export([start_link/1]). %% Supervisor callbacks -export([init/1]). -define(SERVER, ?MODULE). %%==================================================================== %% API functions %%==================================================================== %%-------------------------------------------------------------------- Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error } %% Description: Starts the supervisor %%-------------------------------------------------------------------- start_link(_StartArgs) -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %%==================================================================== %% Supervisor callbacks %%==================================================================== %%-------------------------------------------------------------------- Func : init(Args ) - > { ok , { SupFlags , [ ChildSpec ] } } | %% ignore | %% {error, Reason} %% Description: Whenever a supervisor is started using %% supervisor:start_link/[2,3], this function is called by the new process %% to find out about restart strategy, maximum restart frequency and child %% specifications. %%-------------------------------------------------------------------- init([]) -> Ip = get_env(ip, {127,0,0,1}), Port = get_env(port, 5038), User = get_env(user, "admin"), Secret = get_env(passwd, "secret"), = { ast_evt,{ast_man_events , start_link , [ ] } , % permanent,2000,worker,[ast_man_events]}, AstEvt = {ast_evt,{ast_ami_events,start_link,[]}, permanent,2000,worker,[ast_ami_events]}, AstMan = {ast_man,{ast_ami_client,start_link,[User, Secret]}, permanent,2000,worker,[ast_ami_client]}, AstDrv = {ast_drv,{ast_ami_drv,start_link,[Ip, Port]}, permanent,2000,worker,[ast_ami_drv]}, {ok,{{one_for_all,100,1000}, [AstDrv,AstEvt,AstMan]}}. %%==================================================================== Internal functions %%==================================================================== get_env(Key, Default) -> case application:get_env(Key) of {ok, Value} -> Value; _Undef -> Default end.
null
https://raw.githubusercontent.com/bef/poc-apps/754c308f0f170a3dd766f828fff7081122867f8b/lib/erlast/lib/ast_man/src/ast_ami_sup.erl
erlang
This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public 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. License along with this library; if not, write to the Free Software ------------------------------------------------------------------- File : ast_man_sup.erl Description : ------------------------------------------------------------------- API Supervisor callbacks ==================================================================== API functions ==================================================================== -------------------------------------------------------------------- Description: Starts the supervisor -------------------------------------------------------------------- ==================================================================== Supervisor callbacks ==================================================================== -------------------------------------------------------------------- ignore | {error, Reason} Description: Whenever a supervisor is started using supervisor:start_link/[2,3], this function is called by the new process to find out about restart strategy, maximum restart frequency and child specifications. -------------------------------------------------------------------- permanent,2000,worker,[ast_man_events]}, ==================================================================== ====================================================================
License as published by the Free Software Foundation ; either version 2.1 of the License , or ( at your option ) any later version . You should have received a copy of the GNU Lesser General Public Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA Author : < > Created : 29 Mar 2006 by < > @private -module(ast_ami_sup). -behaviour(supervisor). -export([start_link/1]). -export([init/1]). -define(SERVER, ?MODULE). Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error } start_link(_StartArgs) -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). Func : init(Args ) - > { ok , { SupFlags , [ ChildSpec ] } } | init([]) -> Ip = get_env(ip, {127,0,0,1}), Port = get_env(port, 5038), User = get_env(user, "admin"), Secret = get_env(passwd, "secret"), = { ast_evt,{ast_man_events , start_link , [ ] } , AstEvt = {ast_evt,{ast_ami_events,start_link,[]}, permanent,2000,worker,[ast_ami_events]}, AstMan = {ast_man,{ast_ami_client,start_link,[User, Secret]}, permanent,2000,worker,[ast_ami_client]}, AstDrv = {ast_drv,{ast_ami_drv,start_link,[Ip, Port]}, permanent,2000,worker,[ast_ami_drv]}, {ok,{{one_for_all,100,1000}, [AstDrv,AstEvt,AstMan]}}. Internal functions get_env(Key, Default) -> case application:get_env(Key) of {ok, Value} -> Value; _Undef -> Default end.
4ce77667b1221572355174ece6b17b97c49db1cf120eff7fcca36bdd54ba6ecb
pfdietz/ansi-test
tan.lsp
;-*- Mode: Lisp -*- Author : Created : Mon Feb 9 20:55:40 2004 Contains : Tests of (deftest tan.1 (loop for i from -1000 to 1000 for rlist = (multiple-value-list (tan i)) for y = (car rlist) always (and (null (cdr rlist)) (or (rationalp y) (typep y 'single-float)))) t) (deftest tan.2 (loop for x = (- (random 2000.0s0) 1000.0s0) for y = (safe-tan x 0.0s0) repeat 1000 always (typep y 'short-float)) t) (deftest tan.3 (loop for x = (- (random 2000.0f0) 1000.0f0) for y = (safe-tan x 0.0) repeat 1000 always (typep y 'single-float)) t) (deftest tan.4 (loop for x = (- (random 2000.0d0) 1000.0d0) for y = (safe-tan x 0.0d0) repeat 1000 always (typep y 'double-float)) t) (deftest tan.5 (loop for x = (- (random 2000.0l0) 1000.0l0) for y = (safe-tan 0.0l0) repeat 1000 always (typep y 'long-float)) t) (deftest tan.6 (let ((r (tan 0))) (or (eqlt r 0) (eqlt r 0.0))) t) (deftest tan.7 (tan 0.0s0) 0.0s0) (deftest tan.8 (tan 0.0) 0.0) (deftest tan.9 (tan 0.0d0) 0.0d0) (deftest tan.10 (tan 0.0l0) 0.0l0) (deftest tan.11 (loop for i from 1 to 100 unless (approx= (tan i) (tan (coerce i 'single-float))) collect i) nil) (deftest tan.12 (approx= (tan (coerce (/ pi 4) 'single-float)) 1.0) t) (deftest tan.13 (approx= (tan (coerce (/ pi -4) 'single-float)) -1.0) t) (deftest tan.14 (approx= (tan (coerce (/ pi 4) 'short-float)) 1s0) t) (deftest tan.15 (approx= (tan (coerce (/ pi -4) 'short-float)) -1s0) t) (deftest tan.16 (approx= (tan (coerce (/ pi 4) 'double-float)) 1d0) t) (deftest tan.17 (approx= (tan (coerce (/ pi -4) 'double-float)) -1d0) t) (deftest tan.18 (approx= (tan (coerce (/ pi 4) 'long-float)) 1l0) t) (deftest tan.19 (approx= (tan (coerce (/ pi -4) 'long-float)) -1l0) t) (deftest tan.20 (loop for r = (- (random 2000) 1000) for i = (- (random 20) 10) for y = (safe-tan (complex r i)) repeat 1000 always (numberp y)) t) (deftest tan.21 (loop for r = (- (random 2000.0s0) 1000.0s0) for i = (- (random 20.0s0) 10.0s0) for y = (safe-tan (complex r i)) repeat 1000 always (numberp y)) t) (deftest tan.22 (loop for r = (- (random 2000.0f0) 1000.0f0) for i = (- (random 20.0f0) 10.0f0) for y = (safe-tan (complex r i)) repeat 1000 always (numberp y)) t) (deftest tan.23 (loop for r = (- (random 2000.0d0) 1000.0d0) for i = (- (random 20.0d0) 10.0d0) for y = (safe-tan (complex r i)) repeat 1000 always (numberp y)) t) (deftest tan.24 (loop for r = (- (random 2000.0l0) 1000.0l0) for i = (- (random 20.0l0) 10.0l0) for y = (safe-tan (complex r i)) repeat 1000 always (numberp y)) t) FIXME ;;; More accuracy tests here ;;; Error tests (deftest tan.error.1 (signals-error (tan) program-error) t) (deftest tan.error.2 (signals-error (tan 0.0 0.0) program-error) t) (deftest tan.error.3 (check-type-error #'tan #'numberp) nil)
null
https://raw.githubusercontent.com/pfdietz/ansi-test/3f4b9d31c3408114f0467eaeca4fd13b28e2ce31/numbers/tan.lsp
lisp
-*- Mode: Lisp -*- More accuracy tests here Error tests
Author : Created : Mon Feb 9 20:55:40 2004 Contains : Tests of (deftest tan.1 (loop for i from -1000 to 1000 for rlist = (multiple-value-list (tan i)) for y = (car rlist) always (and (null (cdr rlist)) (or (rationalp y) (typep y 'single-float)))) t) (deftest tan.2 (loop for x = (- (random 2000.0s0) 1000.0s0) for y = (safe-tan x 0.0s0) repeat 1000 always (typep y 'short-float)) t) (deftest tan.3 (loop for x = (- (random 2000.0f0) 1000.0f0) for y = (safe-tan x 0.0) repeat 1000 always (typep y 'single-float)) t) (deftest tan.4 (loop for x = (- (random 2000.0d0) 1000.0d0) for y = (safe-tan x 0.0d0) repeat 1000 always (typep y 'double-float)) t) (deftest tan.5 (loop for x = (- (random 2000.0l0) 1000.0l0) for y = (safe-tan 0.0l0) repeat 1000 always (typep y 'long-float)) t) (deftest tan.6 (let ((r (tan 0))) (or (eqlt r 0) (eqlt r 0.0))) t) (deftest tan.7 (tan 0.0s0) 0.0s0) (deftest tan.8 (tan 0.0) 0.0) (deftest tan.9 (tan 0.0d0) 0.0d0) (deftest tan.10 (tan 0.0l0) 0.0l0) (deftest tan.11 (loop for i from 1 to 100 unless (approx= (tan i) (tan (coerce i 'single-float))) collect i) nil) (deftest tan.12 (approx= (tan (coerce (/ pi 4) 'single-float)) 1.0) t) (deftest tan.13 (approx= (tan (coerce (/ pi -4) 'single-float)) -1.0) t) (deftest tan.14 (approx= (tan (coerce (/ pi 4) 'short-float)) 1s0) t) (deftest tan.15 (approx= (tan (coerce (/ pi -4) 'short-float)) -1s0) t) (deftest tan.16 (approx= (tan (coerce (/ pi 4) 'double-float)) 1d0) t) (deftest tan.17 (approx= (tan (coerce (/ pi -4) 'double-float)) -1d0) t) (deftest tan.18 (approx= (tan (coerce (/ pi 4) 'long-float)) 1l0) t) (deftest tan.19 (approx= (tan (coerce (/ pi -4) 'long-float)) -1l0) t) (deftest tan.20 (loop for r = (- (random 2000) 1000) for i = (- (random 20) 10) for y = (safe-tan (complex r i)) repeat 1000 always (numberp y)) t) (deftest tan.21 (loop for r = (- (random 2000.0s0) 1000.0s0) for i = (- (random 20.0s0) 10.0s0) for y = (safe-tan (complex r i)) repeat 1000 always (numberp y)) t) (deftest tan.22 (loop for r = (- (random 2000.0f0) 1000.0f0) for i = (- (random 20.0f0) 10.0f0) for y = (safe-tan (complex r i)) repeat 1000 always (numberp y)) t) (deftest tan.23 (loop for r = (- (random 2000.0d0) 1000.0d0) for i = (- (random 20.0d0) 10.0d0) for y = (safe-tan (complex r i)) repeat 1000 always (numberp y)) t) (deftest tan.24 (loop for r = (- (random 2000.0l0) 1000.0l0) for i = (- (random 20.0l0) 10.0l0) for y = (safe-tan (complex r i)) repeat 1000 always (numberp y)) t) FIXME (deftest tan.error.1 (signals-error (tan) program-error) t) (deftest tan.error.2 (signals-error (tan 0.0 0.0) program-error) t) (deftest tan.error.3 (check-type-error #'tan #'numberp) nil)
2017fdbf5f7bed858270917c922eb66232463bb30617cc37f12e41dbb5b61822
gildor478/ounit
oUnitPlugin.ml
(**************************************************************************) The OUnit library (* *) Copyright ( C ) 2002 - 2008 Maas - Maarten Zeeman . Copyright ( C ) 2010 OCamlCore SARL Copyright ( C ) 2013 (* *) The package OUnit is copyright by Maas - Maarten Zeeman , OCamlCore SARL and . (* *) (* Permission is hereby granted, free of charge, to any person obtaining *) a copy of this document and the OUnit software ( " 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 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. *) (* *) See LICENSE.txt for details . (**************************************************************************) (** Standard functions for plugin (register, choose). *) type name = string module type SETTINGS = sig type t val name: name val conf_help: string val default_name: name val default_value: t end module Make(Settings: SETTINGS) = struct let all = ref [0, (Settings.default_name, Settings.default_value)] let register name pref f = all := (pref, (name, f)) :: !all let of_name s = try List.assoc s (List.map snd !all) with Not_found -> OUnitUtils.failwithf "Unable to find %s '%s'." Settings.name s let choice = OUnitConf.make_enum Settings.name (fun () -> List.map snd !all) Settings.default_name Settings.conf_help let preset lst = let _, (default, _) = List.fold_left max (List.hd !all) (List.tl !all) in (Settings.name, default) :: lst end
null
https://raw.githubusercontent.com/gildor478/ounit/faf4936b17507406c7592186dcaa3f25c6fc138a/src/lib/ounit2/advanced/oUnitPlugin.ml
ocaml
************************************************************************ Permission is hereby granted, free of charge, to any person obtaining the rights to use, copy, modify, merge, publish, distribute, conditions: The above copyright notice and this permission notice shall be 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. or other liability, whether in an action of contract, tort or the use or other dealings in the software. ************************************************************************ * Standard functions for plugin (register, choose).
The OUnit library Copyright ( C ) 2002 - 2008 Maas - Maarten Zeeman . Copyright ( C ) 2010 OCamlCore SARL Copyright ( C ) 2013 The package OUnit is copyright by Maas - Maarten Zeeman , OCamlCore SARL and . a copy of this document and the OUnit software ( " the Software " ) , to deal in the Software without restriction , including without limitation 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 included in all copies or substantial portions of the Software . In no event shall be liable for any claim , damages otherwise , arising from , out of or in connection with the Software or See LICENSE.txt for details . type name = string module type SETTINGS = sig type t val name: name val conf_help: string val default_name: name val default_value: t end module Make(Settings: SETTINGS) = struct let all = ref [0, (Settings.default_name, Settings.default_value)] let register name pref f = all := (pref, (name, f)) :: !all let of_name s = try List.assoc s (List.map snd !all) with Not_found -> OUnitUtils.failwithf "Unable to find %s '%s'." Settings.name s let choice = OUnitConf.make_enum Settings.name (fun () -> List.map snd !all) Settings.default_name Settings.conf_help let preset lst = let _, (default, _) = List.fold_left max (List.hd !all) (List.tl !all) in (Settings.name, default) :: lst end
5a9d148131bcc44446d00579a7d8470bfb40914106eb958f54fa467a0eb17d6f
kupl/LearnML
original.ml
type nat = ZERO | SUCC of nat let rec natadd (n1 : nat) (n2 : nat) : nat = match n1 with ZERO -> n2 | SUCC nat -> natadd nat (SUCC n2) let rec natmul (n1 : nat) (n2 : nat) : nat = match n1 with | ZERO -> ZERO | SUCC nat -> if nat = ZERO then n2 else natmul nat (natadd n2 n2)
null
https://raw.githubusercontent.com/kupl/LearnML/c98ef2b95ef67e657b8158a2c504330e9cfb7700/result/cafe2/nat/sub6/original.ml
ocaml
type nat = ZERO | SUCC of nat let rec natadd (n1 : nat) (n2 : nat) : nat = match n1 with ZERO -> n2 | SUCC nat -> natadd nat (SUCC n2) let rec natmul (n1 : nat) (n2 : nat) : nat = match n1 with | ZERO -> ZERO | SUCC nat -> if nat = ZERO then n2 else natmul nat (natadd n2 n2)
8cf1b241fd75234dd4e5c765805e2c111601d2ac1b1dfb6a8fe09656b6672cef
tweag/haskell-training
Basics.hs
# LANGUAGE InstanceSigs # module Basics where -- QuickCheck import Test.QuickCheck x :: String x = "hello" f :: Bool -> Bool f x = x && x data Person = MkPerson { name :: String , age :: Int } personDetails :: Person -> String personDetails (MkPerson name age) = name ++ " is " ++ show age ++ " years old" data Person1 = MkPerson1 String Int data Shape = Rectangle {side1 :: Float, side2 :: Float} | Square {side :: Float} | Circle {radius :: Float} deriving Show instance Arbitrary Shape where arbitrary :: Gen Shape arbitrary = oneof [ Rectangle <$> arbitrary <*> arbitrary , Square <$> arbitrary , Circle <$> arbitrary ] -- | Perimeter of a shape -- > > > perimeter ( Rectangle 1 2 ) 6.0 -- > > > perimeter ( Square 1 ) 4.0 -- > > > perimeter ( Circle 1 ) 6.2831855 perimeter :: Shape -> Float perimeter (Rectangle side1 side2) = (side1 + side2) * 2 perimeter (Square side) = side * 4 perimeter (Circle radius) = 2 * pi * radius isDegenerate :: Shape -> Bool isDegenerate (Rectangle s1 s2) = s1 == 0 && s2 == 0 isDegenerate (Square s) = s == 0 isDegenerate (Circle r) = r == 0
null
https://raw.githubusercontent.com/tweag/haskell-training/89d930f7854075d692dfb127d2c54e953dbf1519/src/Basics.hs
haskell
QuickCheck | Perimeter of a shape
# LANGUAGE InstanceSigs # module Basics where import Test.QuickCheck x :: String x = "hello" f :: Bool -> Bool f x = x && x data Person = MkPerson { name :: String , age :: Int } personDetails :: Person -> String personDetails (MkPerson name age) = name ++ " is " ++ show age ++ " years old" data Person1 = MkPerson1 String Int data Shape = Rectangle {side1 :: Float, side2 :: Float} | Square {side :: Float} | Circle {radius :: Float} deriving Show instance Arbitrary Shape where arbitrary :: Gen Shape arbitrary = oneof [ Rectangle <$> arbitrary <*> arbitrary , Square <$> arbitrary , Circle <$> arbitrary ] > > > perimeter ( Rectangle 1 2 ) 6.0 > > > perimeter ( Square 1 ) 4.0 > > > perimeter ( Circle 1 ) 6.2831855 perimeter :: Shape -> Float perimeter (Rectangle side1 side2) = (side1 + side2) * 2 perimeter (Square side) = side * 4 perimeter (Circle radius) = 2 * pi * radius isDegenerate :: Shape -> Bool isDegenerate (Rectangle s1 s2) = s1 == 0 && s2 == 0 isDegenerate (Square s) = s == 0 isDegenerate (Circle r) = r == 0
8a98807da9f3a31f8fe10742b4a11ad78cf7ed5e41b704d85b8f5722385d6f82
mmottl/gsl-ocaml
interp.mli
gsl - ocaml - OCaml interface to GSL Copyright ( © ) 2002 - 2012 - Olivier Andrieu Distributed under the terms of the GPL version 3 (** Interpolation *) type t type accel type interp_type = | LINEAR | POLYNOMIAL | CSPLINE | CSPLINE_PERIODIC | AKIMA | AKIMA_PERIODIC val make : interp_type -> int -> t val init : t -> float array -> float array -> unit external name : t -> string = "ml_gsl_interp_name" external min_size : t -> int = "ml_gsl_interp_min_size" val make_accel : unit -> accel external i_eval : t -> float array -> float array -> float -> accel -> float = "ml_gsl_interp_eval" external i_eval_deriv : t -> float array -> float array -> float -> accel -> float = "ml_gsl_interp_eval_deriv" external i_eval_deriv2 : t -> float array -> float array -> float -> accel -> float = "ml_gsl_interp_eval_deriv2" external i_eval_integ : t -> float array -> float array -> float -> float -> accel -> float = "ml_gsl_interp_eval_integ_bc" "ml_gsl_interp_eval_integ" * { 3 Higher level functions } type interp = { interp : t ; accel : accel ; xa : float array ; ya : float array ; size : int ; i_type : interp_type ; } val make_interp : interp_type -> float array -> float array -> interp val eval : interp -> float -> float * [ eval_array interp ] fills the array [ y_a ] with the evaluation of the interpolation function [ interp ] for each point of array [ x_a ] . [ x_a ] and [ y_a ] must have the same length . evaluation of the interpolation function [interp] for each point of array [x_a]. [x_a] and [y_a] must have the same length. *) external eval_array : interp -> float array -> float array -> unit = "ml_gsl_interp_eval_array" val eval_deriv : interp -> float -> float val eval_deriv2 : interp -> float -> float val eval_integ : interp -> float -> float -> float
null
https://raw.githubusercontent.com/mmottl/gsl-ocaml/76f8d93cccc1f23084f4a33d3e0a8f1289450580/src/interp.mli
ocaml
* Interpolation
gsl - ocaml - OCaml interface to GSL Copyright ( © ) 2002 - 2012 - Olivier Andrieu Distributed under the terms of the GPL version 3 type t type accel type interp_type = | LINEAR | POLYNOMIAL | CSPLINE | CSPLINE_PERIODIC | AKIMA | AKIMA_PERIODIC val make : interp_type -> int -> t val init : t -> float array -> float array -> unit external name : t -> string = "ml_gsl_interp_name" external min_size : t -> int = "ml_gsl_interp_min_size" val make_accel : unit -> accel external i_eval : t -> float array -> float array -> float -> accel -> float = "ml_gsl_interp_eval" external i_eval_deriv : t -> float array -> float array -> float -> accel -> float = "ml_gsl_interp_eval_deriv" external i_eval_deriv2 : t -> float array -> float array -> float -> accel -> float = "ml_gsl_interp_eval_deriv2" external i_eval_integ : t -> float array -> float array -> float -> float -> accel -> float = "ml_gsl_interp_eval_integ_bc" "ml_gsl_interp_eval_integ" * { 3 Higher level functions } type interp = { interp : t ; accel : accel ; xa : float array ; ya : float array ; size : int ; i_type : interp_type ; } val make_interp : interp_type -> float array -> float array -> interp val eval : interp -> float -> float * [ eval_array interp ] fills the array [ y_a ] with the evaluation of the interpolation function [ interp ] for each point of array [ x_a ] . [ x_a ] and [ y_a ] must have the same length . evaluation of the interpolation function [interp] for each point of array [x_a]. [x_a] and [y_a] must have the same length. *) external eval_array : interp -> float array -> float array -> unit = "ml_gsl_interp_eval_array" val eval_deriv : interp -> float -> float val eval_deriv2 : interp -> float -> float val eval_integ : interp -> float -> float -> float
8fa07a0ffc13b14aa58720dc1d8602b1f37d061e8773ade635d08e6ef927d662
sjl/caves
core.clj
(ns caves.world.core (:use [caves.coords :only [neighbors radial-distance]])) ; Constants ------------------------------------------------------------------- (def world-size [120 50]) ; Data structures ------------------------------------------------------------- (defrecord World [tiles entities]) (defrecord Tile [kind glyph color]) (def tiles {:floor (->Tile :floor "." :white) :wall (->Tile :wall "#" :white) :up (->Tile :up "<" :white) :down (->Tile :down ">" :white) :bound (->Tile :bound "X" :black)}) ; Convenience functions ------------------------------------------------------- (defn get-tile-from-tiles [tiles [x y]] (get-in tiles [y x] (:bound tiles))) (defn random-coordinate [] (let [[cols rows] world-size] [(rand-int cols) (rand-int rows)])) (defn tile-walkable? "Return whether a (normal) entity can walk over this type of tile." [tile] (#{:floor :up :down} (:kind tile))) ; Querying a world ------------------------------------------------------------ (defn get-tile [world coord] (get-tile-from-tiles (:tiles world) coord)) (defn get-tile-kind [world coord] (:kind (get-tile world coord))) (defn set-tile [world [x y] tile] (assoc-in world [:tiles y x] tile)) (defn set-tile-floor [world coord] (set-tile world coord (:floor tiles))) (defn get-entities-at [world coord] (filter #(= coord (:location %)) (vals (:entities world)))) (defn get-entity-at [world coord] (first (get-entities-at world coord))) (defn get-entities-around ([world coord] (get-entities-around world coord 1)) ([world coord radius] (filter #(<= (radial-distance coord (:location %)) radius) (vals (:entities world))))) (defn is-empty? [world coord] (and (tile-walkable? (get-tile world coord)) (not (get-entity-at world coord)))) (defn find-empty-tile [world] (loop [coord (random-coordinate)] (if (is-empty? world coord) coord (recur (random-coordinate))))) (defn find-empty-neighbor [world coord] (let [candidates (filter #(is-empty? world %) (neighbors coord))] (when (seq candidates) (rand-nth candidates)))) (defn check-tile "Check that the tile at the destination passes the given predicate." [world dest pred] (pred (get-tile-kind world dest)))
null
https://raw.githubusercontent.com/sjl/caves/d39ee73eb5c54877d9706b16193b6cb044b2aaf6/src/caves/world/core.clj
clojure
Constants ------------------------------------------------------------------- Data structures ------------------------------------------------------------- Convenience functions ------------------------------------------------------- Querying a world ------------------------------------------------------------
(ns caves.world.core (:use [caves.coords :only [neighbors radial-distance]])) (def world-size [120 50]) (defrecord World [tiles entities]) (defrecord Tile [kind glyph color]) (def tiles {:floor (->Tile :floor "." :white) :wall (->Tile :wall "#" :white) :up (->Tile :up "<" :white) :down (->Tile :down ">" :white) :bound (->Tile :bound "X" :black)}) (defn get-tile-from-tiles [tiles [x y]] (get-in tiles [y x] (:bound tiles))) (defn random-coordinate [] (let [[cols rows] world-size] [(rand-int cols) (rand-int rows)])) (defn tile-walkable? "Return whether a (normal) entity can walk over this type of tile." [tile] (#{:floor :up :down} (:kind tile))) (defn get-tile [world coord] (get-tile-from-tiles (:tiles world) coord)) (defn get-tile-kind [world coord] (:kind (get-tile world coord))) (defn set-tile [world [x y] tile] (assoc-in world [:tiles y x] tile)) (defn set-tile-floor [world coord] (set-tile world coord (:floor tiles))) (defn get-entities-at [world coord] (filter #(= coord (:location %)) (vals (:entities world)))) (defn get-entity-at [world coord] (first (get-entities-at world coord))) (defn get-entities-around ([world coord] (get-entities-around world coord 1)) ([world coord radius] (filter #(<= (radial-distance coord (:location %)) radius) (vals (:entities world))))) (defn is-empty? [world coord] (and (tile-walkable? (get-tile world coord)) (not (get-entity-at world coord)))) (defn find-empty-tile [world] (loop [coord (random-coordinate)] (if (is-empty? world coord) coord (recur (random-coordinate))))) (defn find-empty-neighbor [world coord] (let [candidates (filter #(is-empty? world %) (neighbors coord))] (when (seq candidates) (rand-nth candidates)))) (defn check-tile "Check that the tile at the destination passes the given predicate." [world dest pred] (pred (get-tile-kind world dest)))
1eb56577839570b240efa0e2ca9f8ad1c4c59b20f10e0ca15df6cec33af27f9c
omelkonian/AlgoRhythm
Music.hs
module Music ( module Music.Constants , module Music.Operators , module Music.Transformations , module Music.Types , module Music.Utilities ) where import Music.Constants import Music.Operators import Music.Transformations import Music.Types import Music.Utilities
null
https://raw.githubusercontent.com/omelkonian/AlgoRhythm/fdc1ccbae0b3d8a7635b24d37716123aba2d6c11/AlgoRhythm/src/Music.hs
haskell
module Music ( module Music.Constants , module Music.Operators , module Music.Transformations , module Music.Types , module Music.Utilities ) where import Music.Constants import Music.Operators import Music.Transformations import Music.Types import Music.Utilities
e55cb5f22207bcc9d327d48312347c409f792399eb4b03e13c8d777b15b05b61
sinistersnare/aams
aceskt-star.rkt
#lang racket (require (only-in racket/hash hash-union)) ; An aCESKt* machine! implements a k - CFA - like machine . defined by the AAM paper ; This is a k-cfa, so this to the k you want. ; is it really that easy? Seems like `k` is only used in the `tick` function. ; nice! (define k-value 0) ; make a state of the machine. (define (state expr env env-store k-store k-addr timestamp) (list 'state expr env env-store k-store k-addr timestamp)) ; a timestamp is a label and a contour (define (timestamp label contour) (list 'timestamp label contour)) ; an address is a (label or variable) and a contour (define (address label contour) (list 'address label contour)) ; like `take` in the stdlib, but will return the ; taken items so far if we reach the end of the list. (define (takesafe lst n) (if (or (= n 0) (null? lst)) '() (cons (car lst) (takesafe (cdr lst) (- n 1))))) (define (tick st kont) (match st [(list 'state (cons (? symbol? _) _) _ _ _ _ t) t] [(list 'state (cons #f _) _ _ _ _ t) t] [(list 'state (cons `(,e0 ,e1) elabel) _ _ _ _ (list 'timestamp _ contour)) (timestamp elabel contour)] HELP : what to do here , cause i do nt truly understand ; the way these work. [(list 'state (cons `(if ,e0 ,e1, e2) iflabel) _ _ _ _ (list 'timestamp _ contour)) (timestamp iflabel contour)] [(list 'state (cons `(λ ,xvar ,ebody) elabel) _ _ _ _ (list 'timestamp label contour)) (match kont ; HELP: intereting that timestamp doesnt change here. Why? ; need to understand this whole thing a bit better. [(list 'ar _ _ _) (timestamp label contour)] ; add the label to the contour list, and then take the floor of it. the empty list ( bullet / nil from AAM ) is only allowed in label position , ; not contour position. Could cause issues! [(list 'fn _ _ _) (timestamp '() (takesafe (cons label contour) k-value))] [else (raise `(bad-kont-tick kont: ,kont st: ,st))])] [else (raise `(bad-tick-args st: ,st kont: ,kont))])) (define (alloc st kont) (match st [(list 'state (cons `(,(cons e0 e0label) ,e1) _) _ _ _ _ (list 'timestamp _ contour)) (address e0label contour)] [(list 'state (cons `(if ,e0 ,e1, e2) iflabel) _ _ _ _ (list 'timestamp _ contour)) (address iflabel contour)] [(list 'state (cons #f flabel) _ _ _ _ (list 'timestamp _ contour)) (address flabel contour)] [(list 'state (cons `(λ ,_ ,_) _) _ _ k-store k-addr (list 'timestamp _ contour)) (match kont ['mt (address 'mt contour)] [`(ar ,(cons _ elabel) ,_ ,_) (address elabel contour)] [`(fn ,(cons `(λ ,x ,_) (? symbol?)) ,_ ,_) (address x contour)] [else (println kont) (raise `(bad-kont-alloc kont: ,kont st: ,st))])] [else (println st) (raise `(bad-alloc-args st: ,st kont: ,kont))])) ; create an initial state around a closed expression (define (inj-aceskt* e) (define a0 (address '0 '())) (define t0 (timestamp '() '())) ; expr , env , env-store , k-store , k where the stores are Addr - > P(ValueType ) . (state e (hash) (hash) (hash a0 (set 'mt)) a0 t0)) ; The store is a mappingof AddrType -> P(ValType) ; if the address is not in the mapping, its added as a singleton set if the address is in the mapping , then the is added to the set (define (create-or-add store addr val) (hash-update store addr (lambda (value-set) (set-add value-set val)) (lambda () (set val)))) Move the machine 1 step . As this is an abstract machine , 1 given states returns a list of new states . (define (step-aceskt* st) (match-define (list 'state (cons expr (? symbol? label)) env env-store k-store k-addr _) st) (define current-ks (hash-ref k-store k-addr)) ; the lambda returns a list of states ; so the set-map returns a list of list of states. ; we flatten it so its only a single list. (foldl append '() (set-map current-ks (lambda (k) (define u (tick st k)) (match expr [(? symbol? x) (println 'sym) (define vals-at-x (hash-ref env-store (hash-ref env x))) (set-map vals-at-x (lambda (vals) (match-define (cons val envprime) vals) (state val envprime env-store k-store k-addr (tick st k))))] [`(,e0 ,e1) (println 'app) (define b (alloc st k)) (list (state e0 env env-store (create-or-add k-store b `(ar ,e1 ,env ,k-addr)) b u))] [`(if ,e0 ,e1 ,e2) (println 'if) (define b (alloc st k)) (define new-k `(if ,e1 ,e2 ,env ,k-addr)) (define new-k-store (create-or-add k-store b new-k)) (list (state e0 env env-store new-k-store b u))] [v (match k [`(ar ,e ,pprime ,c) (println 'ark) (define b (alloc st k)) (define new-cont `(fn ,(cons v label) ,env ,c)) (list (state e pprime env-store (create-or-add k-store b new-cont) b u))] [`(fn ,(cons `(λ ,x ,e) fnlabel) ,pprime ,c) (println 'fnk) (define b (alloc st k)) (list (state e (hash-set pprime x b) (create-or-add env-store b (cons (cons v fnlabel) env)) k-store c u))] [`(if ,e0 ,e1 ,pprime ,c) (println 'ifkont) (list (state (if (equal? v #f) e1 e0) pprime env-store k-store c u))] [else (raise `(bad-match ,st))])]))))) ; evaluate from an initial state ; this works differently from non-abstract abstract-machines, because here ; a step will return a list of states. We need to reach a fix-point ; which is when we have already seen all the states reached. HELP : But is nt the defn of fixpoint ` x where f(x ) = x ` ? ; how is 'reached before already' a fixpoint? Am I visualizing the step function wrong? (define (evaluate e) ; add labels to `e`. (define (label e) (define lab (gensym 'lab)) (match e ['#f (cons '#f lab)] ; TODO: numbers! ;[`,(? number? n) (cons n lab)] [`(if ,e0 ,e1 ,e2) (cons `(if ,(label e0) ,(label e1) ,(label e2)) lab)] [(? symbol? x) (cons x lab)] [`(,e0 ,e1) (cons `(,(label e0) ,(label e1)) lab)] [`(λ ,x ,e) (cons `(λ ,x ,(label e)) lab)] [else (raise `(labeling-error ,e))])) ; go takes a list of states to process and a hash of reached states (and where they lead) ; and returns a set of reached states, and where they lead (like an edge-list). (define (go states reached) ; compute new reached => new-reached ; from the newly reached states, figure which ones we havent seen before. => todo-states ; add all reached into total reached => union-reached ; If todo-states is empty: we are at fixed point, return union-reached. Else: ; Run `go` with todo-states and union-reached (define new-reached (make-hash (map (lambda (st) (cons st (step-aceskt* st))) states))) shoudnt be hit by dupe errors , as we check when calculating todo - states for possible dupes . (define union-reached (hash-union reached new-reached)) ; use union-reached instead of reached because when we reach a fixpoint we need to catch it. TODO : swap args and use ` dropf ` instead of filter - not . Feel like it ll read better . (define todo-states (dropf (append-map identity (hash-values new-reached)) (lambda (s) (hash-has-key? union-reached s)))) (if (empty? todo-states) union-reached (go todo-states union-reached))) (go (list (inj-aceskt* (label e))) (hash))) ;(define edges (evaluate '((λ n (λ s (λ z (s ((n s) z))))) (λ s (λ z z))))) (define edges (evaluate '((λ x (x x)) (λ x (x x))))) ; (step-aceskt* (state '(λ x (((x . lab1) (x . lab2)) . lab3)) '() '() '() '() '())) ( step - aceskt * ( state ' ( λ x ( ( ( x . lab99679 ) ( x . lab99680 ) ) . ) ) ' ( ) ' ( ) ' ( ) ' ( ) ' ( ) ) ) (evaluate '((λ x x) (if #f (λ x (x x)) (λ x x)))) ; use the formatting module! #;(println "digraph G {") #;(hash-for-each edges (lambda (src dests) (for-each (lambda (dest) (println (string-append src " -> " dest))) dests))) #;(println "}") ; found some λ-examples with this syntax, so ez transformation to mine. (define (unwrap e) (match e [(? symbol? x) x] [`(,efn ,earg) `(,(unwrap efn) ,(unwrap earg))] [`(λ (,(? symbol? fnarg)) ,e) `(λ ,fnarg ,(unwrap e))])) (define (eu e) (evaluate (unwrap e)))
null
https://raw.githubusercontent.com/sinistersnare/aams/367b43f4241f3cbfc5907970693157f0487cdd40/src/racket/basic_machines/aceskt-star.rkt
racket
An aCESKt* machine! This is a k-cfa, so this to the k you want. is it really that easy? Seems like `k` is only used in the `tick` function. nice! make a state of the machine. a timestamp is a label and a contour an address is a (label or variable) and a contour like `take` in the stdlib, but will return the taken items so far if we reach the end of the list. the way these work. HELP: intereting that timestamp doesnt change here. Why? need to understand this whole thing a bit better. add the label to the contour list, and then take the floor of it. not contour position. Could cause issues! create an initial state around a closed expression expr , env , env-store , k-store , k The store is a mappingof AddrType -> P(ValType) if the address is not in the mapping, its added as a singleton set the lambda returns a list of states so the set-map returns a list of list of states. we flatten it so its only a single list. evaluate from an initial state this works differently from non-abstract abstract-machines, because here a step will return a list of states. We need to reach a fix-point which is when we have already seen all the states reached. how is 'reached before already' a fixpoint? Am I visualizing the step function wrong? add labels to `e`. TODO: numbers! [`,(? number? n) (cons n lab)] go takes a list of states to process and a hash of reached states (and where they lead) and returns a set of reached states, and where they lead (like an edge-list). compute new reached => new-reached from the newly reached states, figure which ones we havent seen before. => todo-states add all reached into total reached => union-reached If todo-states is empty: we are at fixed point, return union-reached. Else: Run `go` with todo-states and union-reached use union-reached instead of reached because when we reach a fixpoint we need to catch it. (define edges (evaluate '((λ n (λ s (λ z (s ((n s) z))))) (λ s (λ z z))))) (step-aceskt* (state '(λ x (((x . lab1) (x . lab2)) . lab3)) '() '() '() '() '())) use the formatting module! (println "digraph G {") (hash-for-each (println "}") found some λ-examples with this syntax, so ez transformation to mine.
#lang racket (require (only-in racket/hash hash-union)) implements a k - CFA - like machine . defined by the AAM paper (define k-value 0) (define (state expr env env-store k-store k-addr timestamp) (list 'state expr env env-store k-store k-addr timestamp)) (define (timestamp label contour) (list 'timestamp label contour)) (define (address label contour) (list 'address label contour)) (define (takesafe lst n) (if (or (= n 0) (null? lst)) '() (cons (car lst) (takesafe (cdr lst) (- n 1))))) (define (tick st kont) (match st [(list 'state (cons (? symbol? _) _) _ _ _ _ t) t] [(list 'state (cons #f _) _ _ _ _ t) t] [(list 'state (cons `(,e0 ,e1) elabel) _ _ _ _ (list 'timestamp _ contour)) (timestamp elabel contour)] HELP : what to do here , cause i do nt truly understand [(list 'state (cons `(if ,e0 ,e1, e2) iflabel) _ _ _ _ (list 'timestamp _ contour)) (timestamp iflabel contour)] [(list 'state (cons `(λ ,xvar ,ebody) elabel) _ _ _ _ (list 'timestamp label contour)) (match kont [(list 'ar _ _ _) (timestamp label contour)] the empty list ( bullet / nil from AAM ) is only allowed in label position , [(list 'fn _ _ _) (timestamp '() (takesafe (cons label contour) k-value))] [else (raise `(bad-kont-tick kont: ,kont st: ,st))])] [else (raise `(bad-tick-args st: ,st kont: ,kont))])) (define (alloc st kont) (match st [(list 'state (cons `(,(cons e0 e0label) ,e1) _) _ _ _ _ (list 'timestamp _ contour)) (address e0label contour)] [(list 'state (cons `(if ,e0 ,e1, e2) iflabel) _ _ _ _ (list 'timestamp _ contour)) (address iflabel contour)] [(list 'state (cons #f flabel) _ _ _ _ (list 'timestamp _ contour)) (address flabel contour)] [(list 'state (cons `(λ ,_ ,_) _) _ _ k-store k-addr (list 'timestamp _ contour)) (match kont ['mt (address 'mt contour)] [`(ar ,(cons _ elabel) ,_ ,_) (address elabel contour)] [`(fn ,(cons `(λ ,x ,_) (? symbol?)) ,_ ,_) (address x contour)] [else (println kont) (raise `(bad-kont-alloc kont: ,kont st: ,st))])] [else (println st) (raise `(bad-alloc-args st: ,st kont: ,kont))])) (define (inj-aceskt* e) (define a0 (address '0 '())) (define t0 (timestamp '() '())) where the stores are Addr - > P(ValueType ) . (state e (hash) (hash) (hash a0 (set 'mt)) a0 t0)) if the address is in the mapping , then the is added to the set (define (create-or-add store addr val) (hash-update store addr (lambda (value-set) (set-add value-set val)) (lambda () (set val)))) Move the machine 1 step . As this is an abstract machine , 1 given states returns a list of new states . (define (step-aceskt* st) (match-define (list 'state (cons expr (? symbol? label)) env env-store k-store k-addr _) st) (define current-ks (hash-ref k-store k-addr)) (foldl append '() (set-map current-ks (lambda (k) (define u (tick st k)) (match expr [(? symbol? x) (println 'sym) (define vals-at-x (hash-ref env-store (hash-ref env x))) (set-map vals-at-x (lambda (vals) (match-define (cons val envprime) vals) (state val envprime env-store k-store k-addr (tick st k))))] [`(,e0 ,e1) (println 'app) (define b (alloc st k)) (list (state e0 env env-store (create-or-add k-store b `(ar ,e1 ,env ,k-addr)) b u))] [`(if ,e0 ,e1 ,e2) (println 'if) (define b (alloc st k)) (define new-k `(if ,e1 ,e2 ,env ,k-addr)) (define new-k-store (create-or-add k-store b new-k)) (list (state e0 env env-store new-k-store b u))] [v (match k [`(ar ,e ,pprime ,c) (println 'ark) (define b (alloc st k)) (define new-cont `(fn ,(cons v label) ,env ,c)) (list (state e pprime env-store (create-or-add k-store b new-cont) b u))] [`(fn ,(cons `(λ ,x ,e) fnlabel) ,pprime ,c) (println 'fnk) (define b (alloc st k)) (list (state e (hash-set pprime x b) (create-or-add env-store b (cons (cons v fnlabel) env)) k-store c u))] [`(if ,e0 ,e1 ,pprime ,c) (println 'ifkont) (list (state (if (equal? v #f) e1 e0) pprime env-store k-store c u))] [else (raise `(bad-match ,st))])]))))) HELP : But is nt the defn of fixpoint ` x where f(x ) = x ` ? (define (evaluate e) (define (label e) (define lab (gensym 'lab)) (match e ['#f (cons '#f lab)] [`(if ,e0 ,e1 ,e2) (cons `(if ,(label e0) ,(label e1) ,(label e2)) lab)] [(? symbol? x) (cons x lab)] [`(,e0 ,e1) (cons `(,(label e0) ,(label e1)) lab)] [`(λ ,x ,e) (cons `(λ ,x ,(label e)) lab)] [else (raise `(labeling-error ,e))])) (define (go states reached) (define new-reached (make-hash (map (lambda (st) (cons st (step-aceskt* st))) states))) shoudnt be hit by dupe errors , as we check when calculating todo - states for possible dupes . (define union-reached (hash-union reached new-reached)) TODO : swap args and use ` dropf ` instead of filter - not . Feel like it ll read better . (define todo-states (dropf (append-map identity (hash-values new-reached)) (lambda (s) (hash-has-key? union-reached s)))) (if (empty? todo-states) union-reached (go todo-states union-reached))) (go (list (inj-aceskt* (label e))) (hash))) (define edges (evaluate '((λ x (x x)) (λ x (x x))))) ( step - aceskt * ( state ' ( λ x ( ( ( x . lab99679 ) ( x . lab99680 ) ) . ) ) ' ( ) ' ( ) ' ( ) ' ( ) ' ( ) ) ) (evaluate '((λ x x) (if #f (λ x (x x)) (λ x x)))) edges (lambda (src dests) (for-each (lambda (dest) (println (string-append src " -> " dest))) dests))) (define (unwrap e) (match e [(? symbol? x) x] [`(,efn ,earg) `(,(unwrap efn) ,(unwrap earg))] [`(λ (,(? symbol? fnarg)) ,e) `(λ ,fnarg ,(unwrap e))])) (define (eu e) (evaluate (unwrap e)))
41a3139501259911a58a101d393950e0bd2acb10dfd04b3dda8afb65373e2723
motoshira/lib_for_competitive_programming
uf-closure.lisp
;;; ;;; Beginning of inserted contents ;;; (defmacro make-uf (size) (let ((parents (gensym))) `(let ((,parents (make-array ,size :element-type 'fixnum :adjustable nil :initial-element -1))) (labels ((%find (x) (declare (fixnum x)) (the fixnum (if (minusp (aref ,parents x)) x (setf (aref,parents x) (%find (aref ,parents x)))))) (%unite (x y) (declare (fixnum x y)) (let ((x (%find x)) (y (%find y))) (declare (fixnum x y)) (when (> x y) (rotatef x y)) (when (/= x y) (incf (aref ,parents x) (aref ,parents y)) (setf (aref ,parents y) x)))) (%inquire (x y) (declare (fixnum x y)) (= (aref ,parents x) (aref ,parents y)))) (lambda (key &optional (x -1) (y -1)) (declare (symbol key) (fixnum x y)) (ecase key (:find (%find x)) (:unite (%unite x y)) (:inquire (%inquire x y)) (:show ,parents))))))) ;;; ;;; End of inserted contents ;;;
null
https://raw.githubusercontent.com/motoshira/lib_for_competitive_programming/33fd81102f5d1067904e0aca9b3f9ba3c3c2ca73/experimental/uf-closure.lisp
lisp
Beginning of inserted contents End of inserted contents
(defmacro make-uf (size) (let ((parents (gensym))) `(let ((,parents (make-array ,size :element-type 'fixnum :adjustable nil :initial-element -1))) (labels ((%find (x) (declare (fixnum x)) (the fixnum (if (minusp (aref ,parents x)) x (setf (aref,parents x) (%find (aref ,parents x)))))) (%unite (x y) (declare (fixnum x y)) (let ((x (%find x)) (y (%find y))) (declare (fixnum x y)) (when (> x y) (rotatef x y)) (when (/= x y) (incf (aref ,parents x) (aref ,parents y)) (setf (aref ,parents y) x)))) (%inquire (x y) (declare (fixnum x y)) (= (aref ,parents x) (aref ,parents y)))) (lambda (key &optional (x -1) (y -1)) (declare (symbol key) (fixnum x y)) (ecase key (:find (%find x)) (:unite (%unite x y)) (:inquire (%inquire x y)) (:show ,parents)))))))
a3938a5aa681f1ddc3c71ccb4d187a1310c9bb955e68b3aa58271e5d4f72d073
hakaru-dev/hakaru
Datum.hs
# LANGUAGE CPP , , PolyKinds , GADTs , TypeOperators , TypeFamilies , ExistentialQuantification # , DataKinds , PolyKinds , GADTs , TypeOperators , TypeFamilies , ExistentialQuantification #-} {-# OPTIONS_GHC -Wall -fwarn-tabs #-} ---------------------------------------------------------------- -- 2016.05.24 -- | Module : Language . Hakaru . Syntax . Datum Copyright : Copyright ( c ) 2016 the Hakaru team -- License : BSD3 -- Maintainer : -- Stability : experimental Portability : GHC - only -- Haskell types and helpers for Hakaru 's user - defined data types . -- At present we only support regular-recursive polynomial data -- types. Reduction of case analysis on data types is in " Language . Hakaru . Syntax . Datum " . -- /Developers note:/ many of the ' JmEq1 ' instances in this file -- don't actually work because of problems with matching existentially -- quantified types in the basis cases. For now I've left the -- partially-defined code in place, but turned it off with the @__PARTIAL_DATUM_JMEQ__@ CPP macro . In the future we should -- either (a) remove this unused code, or (b) if the instances are -- truly necessary then we should add the 'Sing' arguments everywhere -- to make things work :( ---------------------------------------------------------------- module Language.Hakaru.Syntax.Datum ( -- * Data constructors Datum(..), datumHint, datumType , DatumCode(..) , DatumStruct(..) , DatumFun(..) -- ** Some smart constructors for the \"built-in\" datatypes , dTrue, dFalse, dBool , dUnit , dPair , dLeft, dRight , dNil, dCons , dNothing, dJust -- *** Variants which allow explicit type passing. , dPair_ , dLeft_, dRight_ , dNil_, dCons_ , dNothing_, dJust_ -- * Pattern constructors , Branch(..) , Pattern(..) , PDatumCode(..) , PDatumStruct(..) , PDatumFun(..) -- ** Some smart constructors for the \"built-in\" datatypes , pTrue, pFalse , pUnit , pPair , pLeft, pRight , pNil, pCons , pNothing, pJust -- ** Generalized branches , GBranch(..) ) where import qualified Data.Text as Text import Data.Text (Text) #if __GLASGOW_HASKELL__ < 710 import Data.Monoid (Monoid(..)) import Control.Applicative #endif import qualified Data.Foldable as F import qualified Data.Traversable as T import Language.Hakaru.Syntax.IClasses import Language.Hakaru.Syntax.Variable (Variable(..)) TODO : make things polykinded so we can make our ABT implementation independent of Hakaru 's type system . import Language.Hakaru.Types.DataKind import Language.Hakaru.Types.Sing ---------------------------------------------------------------- ---------------------------------------------------------------- #if __PARTIAL_DATUM_JMEQ__ cannotProve :: String -> a cannotProve fun = error $ "Language.Hakaru.Syntax.Datum." ++ fun ++ ": Cannot prove Refl because of phantomness" #endif -- TODO: change the kind to @(Hakaru -> *) -> HakaruCon -> *@ so we can avoid the use of GADTs ? Would that allow us to actually UNPACK ? -- | A fully saturated data constructor , which recurses as @ast@. We define this type as separate from ' DatumCode ' for two reasons . First is to capture the fact that the datum is " ( i.e. , is a well - formed constructor ) . The second is to have a type which is indexed by its ' Hakaru ' type , whereas ' DatumCode ' involves non - Hakaru types . -- The first component is a hint for what the data constructor -- should be called when pretty-printing, giving error messages, -- etc. Like the hints for variable names, its value is not actually -- used to decide which constructor is meant or which pattern -- matches. data Datum :: (Hakaru -> *) -> Hakaru -> * where Datum :: {-# UNPACK #-} !Text -> !(Sing (HData' t)) -> !(DatumCode (Code t) ast (HData' t)) -> Datum ast (HData' t) datumHint :: Datum ast (HData' t) -> Text datumHint (Datum hint _ _) = hint datumType :: Datum ast (HData' t) -> Sing (HData' t) datumType (Datum _ typ _) = typ N.B. , This does n't require jmEq on ' DatumCode ' nor on @ast@. The -- jmEq on the singleton is sufficient. instance Eq1 ast => JmEq1 (Datum ast) where jmEq1 (Datum _ typ1 d1) (Datum _ typ2 d2) = case jmEq1 typ1 typ2 of Just proof@Refl | eq1 d1 d2 -> Just proof _ -> Nothing instance Eq1 ast => Eq1 (Datum ast) where eq1 (Datum _ _ d1) (Datum _ _ d2) = eq1 d1 d2 instance Eq1 ast => Eq (Datum ast a) where (==) = eq1 -- TODO: instance Read (Datum ast a) instance Show1 ast => Show1 (Datum ast) where showsPrec1 p (Datum hint typ d) = showParen_011 p "Datum" hint typ d instance Show1 ast => Show (Datum ast a) where showsPrec = showsPrec1 show = show1 instance Functor11 Datum where fmap11 f (Datum hint typ d) = Datum hint typ (fmap11 f d) instance Foldable11 Datum where foldMap11 f (Datum _ _ d) = foldMap11 f d instance Traversable11 Datum where traverse11 f (Datum hint typ d) = Datum hint typ <$> traverse11 f d ---------------------------------------------------------------- infixr 7 `Et`, `PEt` -- | The intermediate components of a data constructor. The intuition behind the two indices is that the @[[HakaruFun]]@ is a functor applied to the Hakaru type . Initially the @[[HakaruFun]]@ functor will be the ' Code ' associated with the Hakaru type ; hence it 's the one - step unrolling of the fixed point for our recursive -- datatypes. But as we go along, we'll be doing induction on the -- @[[HakaruFun]]@ functor. data DatumCode :: [[HakaruFun]] -> (Hakaru -> *) -> Hakaru -> * where BUG : haddock does n't like annotations on GADT constructors -- <-dev/hakaru/issues/6> -- Skip rightwards along the sum. Inr :: !(DatumCode xss abt a) -> DatumCode (xs ': xss) abt a -- Inject into the sum. Inl :: !(DatumStruct xs abt a) -> DatumCode (xs ': xss) abt a N.B. , these " instances rely on polymorphic recursion , since the @code@ changes at each constructor . However , we do n't actually need to abstract over @code@ in order to define these -- functions, because (1) we never existentially close over any codes , and ( 2 ) the code is always getting smaller ; so we have -- a good enough inductive hypothesis from polymorphism alone. #if __PARTIAL_DATUM_JMEQ__ -- This instance works, but recurses into non-working instances. instance JmEq1 ast => JmEq1 (DatumCode xss ast) where jmEq1 (Inr c) (Inr d) = jmEq1 c d jmEq1 (Inl c) (Inl d) = jmEq1 c d jmEq1 _ _ = Nothing #endif instance Eq1 ast => Eq1 (DatumCode xss ast) where eq1 (Inr c) (Inr d) = eq1 c d eq1 (Inl c) (Inl d) = eq1 c d eq1 _ _ = False instance Eq1 ast => Eq (DatumCode xss ast a) where (==) = eq1 TODO : instance Read ( DatumCode xss abt a ) instance Show1 ast => Show1 (DatumCode xss ast) where showsPrec1 p (Inr d) = showParen_1 p "Inr" d showsPrec1 p (Inl d) = showParen_1 p "Inl" d instance Show1 ast => Show (DatumCode xss ast a) where showsPrec = showsPrec1 show = show1 instance Functor11 (DatumCode xss) where fmap11 f (Inr d) = Inr (fmap11 f d) fmap11 f (Inl d) = Inl (fmap11 f d) instance Foldable11 (DatumCode xss) where foldMap11 f (Inr d) = foldMap11 f d foldMap11 f (Inl d) = foldMap11 f d instance Traversable11 (DatumCode xss) where traverse11 f (Inr d) = Inr <$> traverse11 f d traverse11 f (Inl d) = Inl <$> traverse11 f d ---------------------------------------------------------------- data DatumStruct :: [HakaruFun] -> (Hakaru -> *) -> Hakaru -> * where BUG : haddock does n't like annotations on GADT constructors -- <-dev/hakaru/issues/6> Combine components of the product . ( \"et\ " means \"and\ " in Latin ) Et :: !(DatumFun x abt a) -> !(DatumStruct xs abt a) -> DatumStruct (x ': xs) abt a -- Close off the product. Done :: DatumStruct '[] abt a #if __PARTIAL_DATUM_JMEQ__ instance JmEq1 ast => JmEq1 (DatumStruct xs ast) where jmEq1 (Et c1 Done) (Et d1 Done) = jmEq1 c1 d1 -- HACK: to handle 'Done' in the cases where we can. jmEq1 (Et c1 c2) (Et d1 d2) = do Refl <- jmEq1 c1 d1 Refl <- jmEq1 c2 d2 Just Refl jmEq1 Done Done = Just (cannotProve "jmEq1@DatumStruct{Done}") jmEq1 _ _ = Nothing #endif instance Eq1 ast => Eq1 (DatumStruct xs ast) where eq1 (Et c1 c2) (Et d1 d2) = eq1 c1 d1 && eq1 c2 d2 eq1 Done Done = True instance Eq1 ast => Eq (DatumStruct xs ast a) where (==) = eq1 -- TODO: instance Read (DatumStruct xs abt a) instance Show1 ast => Show1 (DatumStruct xs ast) where showsPrec1 p (Et d1 d2) = showParen_11 p "Et" d1 d2 showsPrec1 _ Done = showString "Done" instance Show1 ast => Show (DatumStruct xs ast a) where showsPrec = showsPrec1 show = show1 instance Functor11 (DatumStruct xs) where fmap11 f (Et d1 d2) = Et (fmap11 f d1) (fmap11 f d2) fmap11 _ Done = Done instance Foldable11 (DatumStruct xs) where foldMap11 f (Et d1 d2) = foldMap11 f d1 `mappend` foldMap11 f d2 foldMap11 _ Done = mempty instance Traversable11 (DatumStruct xs) where traverse11 f (Et d1 d2) = Et <$> traverse11 f d1 <*> traverse11 f d2 traverse11 _ Done = pure Done ---------------------------------------------------------------- -- TODO: do we like those constructor names? Should we change them? data DatumFun :: HakaruFun -> (Hakaru -> *) -> Hakaru -> * where BUG : haddock does n't like annotations on GADT constructors -- <-dev/hakaru/issues/6> -- Hit a leaf which isn't a recursive component of the datatype. Konst :: !(ast b) -> DatumFun ('K b) ast a -- Hit a leaf which is a recursive component of the datatype. Ident :: !(ast a) -> DatumFun 'I ast a #if __PARTIAL_DATUM_JMEQ__ instance JmEq1 ast => JmEq1 (DatumFun x ast) where jmEq1 (Konst e) (Konst f) = do This ' ' should be free because @x@ is fixed Just (cannotProve "jmEq1@DatumFun{Konst}") jmEq1 (Ident e) (Ident f) = jmEq1 e f jmEq1 _ _ = Nothing #endif instance Eq1 ast => Eq1 (DatumFun x ast) where eq1 (Konst e) (Konst f) = eq1 e f eq1 (Ident e) (Ident f) = eq1 e f instance Eq1 ast => Eq (DatumFun x ast a) where (==) = eq1 TODO : instance Read ( DatumFun x abt a ) instance Show1 ast => Show1 (DatumFun x ast) where showsPrec1 p (Konst e) = showParen_1 p "Konst" e showsPrec1 p (Ident e) = showParen_1 p "Ident" e instance Show1 ast => Show (DatumFun x ast a) where showsPrec = showsPrec1 show = show1 instance Functor11 (DatumFun x) where fmap11 f (Konst e) = Konst (f e) fmap11 f (Ident e) = Ident (f e) instance Foldable11 (DatumFun x) where foldMap11 f (Konst e) = f e foldMap11 f (Ident e) = f e instance Traversable11 (DatumFun x) where traverse11 f (Konst e) = Konst <$> f e traverse11 f (Ident e) = Ident <$> f e ---------------------------------------------------------------- In GHC 7.8 we can make the monomorphic smart constructors into pattern synonyms , but 7.8 ca n't handle anything polymorphic ( but GHC 7.10 can ) . For libraries ( e.g. , " Language . Hakaru . Syntax . Prelude " ) -- we can use functions to construct our Case_ statements, so library -- designers don't need pattern synonyms. Whereas, for the internal aspects of the compiler , we need to handle all possible Datum -- values, so the pattern synonyms wouldn't even be helpful. dTrue, dFalse :: Datum ast HBool dTrue = Datum tdTrue sBool . Inl $ Done dFalse = Datum tdFalse sBool . Inr . Inl $ Done dBool :: Bool -> Datum ast HBool dBool b = if b then dTrue else dFalse dUnit :: Datum ast HUnit dUnit = Datum tdUnit sUnit . Inl $ Done dPair :: (SingI a, SingI b) => ast a -> ast b -> Datum ast (HPair a b) dPair = dPair_ sing sing dPair_ :: Sing a -> Sing b -> ast a -> ast b -> Datum ast (HPair a b) dPair_ a b x y = Datum tdPair (sPair a b) . Inl $ Konst x `Et` Konst y `Et` Done dLeft :: (SingI a, SingI b) => ast a -> Datum ast (HEither a b) dLeft = dLeft_ sing sing dLeft_ :: Sing a -> Sing b -> ast a -> Datum ast (HEither a b) dLeft_ a b = Datum tdLeft (sEither a b) . Inl . (`Et` Done) . Konst dRight :: (SingI a, SingI b) => ast b -> Datum ast (HEither a b) dRight = dRight_ sing sing dRight_ :: Sing a -> Sing b -> ast b -> Datum ast (HEither a b) dRight_ a b = Datum tdRight (sEither a b) . Inr . Inl . (`Et` Done) . Konst dNil :: (SingI a) => Datum ast (HList a) dNil = dNil_ sing dNil_ :: Sing a -> Datum ast (HList a) dNil_ a = Datum tdNil (sList a) . Inl $ Done dCons :: (SingI a) => ast a -> ast (HList a) -> Datum ast (HList a) dCons = dCons_ sing dCons_ :: Sing a -> ast a -> ast (HList a) -> Datum ast (HList a) dCons_ a x xs = Datum tdCons (sList a) . Inr . Inl $ Konst x `Et` Ident xs `Et` Done dNothing :: (SingI a) => Datum ast (HMaybe a) dNothing = dNothing_ sing dNothing_ :: Sing a -> Datum ast (HMaybe a) dNothing_ a = Datum tdNothing (sMaybe a) $ Inl Done dJust :: (SingI a) => ast a -> Datum ast (HMaybe a) dJust = dJust_ sing dJust_ :: Sing a -> ast a -> Datum ast (HMaybe a) dJust_ a = Datum tdJust (sMaybe a) . Inr . Inl . (`Et` Done) . Konst ---------------------------------------------------------------- tdTrue, tdFalse, tdUnit, tdPair, tdLeft, tdRight, tdNil, tdCons, tdNothing, tdJust :: Text tdTrue = Text.pack "true" tdFalse = Text.pack "false" tdUnit = Text.pack "unit" tdPair = Text.pack "pair" tdLeft = Text.pack "left" tdRight = Text.pack "right" tdNil = Text.pack "nil" tdCons = Text.pack "cons" tdNothing = Text.pack "nothing" tdJust = Text.pack "just" ---------------------------------------------------------------- ---------------------------------------------------------------- -- TODO: negative patterns? (to facilitate reordering of case branches) -- TODO: disjunctive patterns, a~la ML? TODO : equality patterns for Nat\/Int ? ( what about Prob\/Real ? ? ) -- TODO: exhaustiveness, non-overlap, dead-branch checking -- -- | We index patterns by the type they scrutinize. This requires -- the parser to be smart enough to build these patterns up, but -- then it guarantees that we can't have 'Case_' of patterns which -- can't possibly match according to our type system. In addition, -- we also index patterns by the type of what variables they bind, -- so that we can ensure that 'Branch' will never \"go wrong\". Alas , this latter indexing means we ca n't use ' DatumCode ' , ' DatumStruct ' , and ' DatumFun ' but rather must define our own @P@ -- variants for pattern matching. data Pattern :: [Hakaru] -> Hakaru -> * where BUG : haddock does n't like annotations on GADT constructors -- <-dev/hakaru/issues/6> The \"don't care\ " wildcard pattern . PWild :: Pattern '[] a -- A pattern variable. PVar :: Pattern '[ a ] a A data type constructor pattern . As with the ' Datum ' constructor , the first component is a hint . PDatum :: {-# UNPACK #-} !Text -> !(PDatumCode (Code t) vars (HData' t)) -> Pattern vars (HData' t) #if __PARTIAL_DATUM_JMEQ__ instance JmEq2 Pattern where jmEq2 PWild PWild = Just (Refl, cannotProve "jmEq2@Pattern{PWild}") jmEq2 PVar PVar = Just (cannotProve "jmEq2@Pattern{PVar}", cannotProve "jmEq2@Pattern{PVar}") jmEq2 (PDatum _ d1) (PDatum _ d2) = jmEq2_fake d1 d2 where jmEq2_fake :: PDatumCode xss vars1 a1 -> PDatumCode xss' vars2 a2 -> Maybe (TypeEq vars1 vars2, TypeEq a1 a2) jmEq2_fake = error "jmEq2@Pattern{PDatum}: can't recurse because Code isn't injective" -- so @xss@ and @xss'@ aren't guaranteed to be the same jmEq2 _ _ = Nothing instance JmEq1 (Pattern vars) where jmEq1 p1 p2 = jmEq2 p1 p2 >>= \(_,proof) -> Just proof #endif instance Eq2 Pattern where eq2 PWild PWild = True eq2 PVar PVar = True eq2 (PDatum _ d1) (PDatum _ d2) = eq2 d1 d2 eq2 _ _ = False instance Eq1 (Pattern vars) where eq1 = eq2 instance Eq (Pattern vars a) where (==) = eq1 -- TODO: instance Read (Pattern vars a) instance Show2 Pattern where showsPrec2 _ PWild = showString "PWild" showsPrec2 _ PVar = showString "PVar" showsPrec2 p (PDatum hint d) = showParen_02 p "PDatum" hint d instance Show1 (Pattern vars) where showsPrec1 = showsPrec2 show1 = show2 instance Show (Pattern vars a) where showsPrec = showsPrec1 show = show1 TODO : as necessary Functor22 , Foldable22 , ---------------------------------------------------------------- data PDatumCode :: [[HakaruFun]] -> [Hakaru] -> Hakaru -> * where PInr :: !(PDatumCode xss vars a) -> PDatumCode (xs ': xss) vars a PInl :: !(PDatumStruct xs vars a) -> PDatumCode (xs ': xss) vars a #if __PARTIAL_DATUM_JMEQ__ instance JmEq2 (PDatumCode xss) where jmEq2 (PInr c) (PInr d) = jmEq2 c d jmEq2 (PInl c) (PInl d) = jmEq2 c d jmEq2 _ _ = Nothing -- This instance works, but recurses into non-working instances. instance JmEq1 (PDatumCode xss vars) where jmEq1 (PInr c) (PInr d) = jmEq1 c d jmEq1 (PInl c) (PInl d) = jmEq1 c d jmEq1 _ _ = Nothing #endif instance Eq2 (PDatumCode xss) where eq2 (PInr c) (PInr d) = eq2 c d eq2 (PInl c) (PInl d) = eq2 c d eq2 _ _ = False instance Eq1 (PDatumCode xss vars) where eq1 = eq2 instance Eq (PDatumCode xss vars a) where (==) = eq1 -- TODO: instance Read (PDatumCode xss vars a) instance Show2 (PDatumCode xss) where showsPrec2 p (PInr d) = showParen_2 p "PInr" d showsPrec2 p (PInl d) = showParen_2 p "PInl" d instance Show1 (PDatumCode xss vars) where showsPrec1 = showsPrec2 show1 = show2 instance Show (PDatumCode xss vars a) where showsPrec = showsPrec1 show = show1 TODO : as necessary Functor22 , Foldable22 , ---------------------------------------------------------------- data PDatumStruct :: [HakaruFun] -> [Hakaru] -> Hakaru -> * where PEt :: !(PDatumFun x vars1 a) -> !(PDatumStruct xs vars2 a) -> PDatumStruct (x ': xs) (vars1 ++ vars2) a PDone :: PDatumStruct '[] '[] a This block of recursive functions are analogous to ' JmEq2 ' except -- we only return the equality proof for the penultimate index -- rather than both the penultimate and ultimate index. (Because we return proofs for the penultimate index , but not for the ultimate . ) This is necessary for defining the @Eq1 ( PDatumStruct -- xs vars)@ and @Eq1 (Branch a abt)@ instances, since we need to -- make sure the existential @vars@ match up. N.B. , that we can use ' ' in the ' PVar ' case relies on the -- fact that the @a@ parameter is fixed to be the same in both -- patterns. jmEq_P :: Pattern vs a -> Pattern ws a -> Maybe (TypeEq vs ws) jmEq_P PWild PWild = Just Refl jmEq_P PVar PVar = Just Refl jmEq_P (PDatum _ p1) (PDatum _ p2) = jmEq_PCode p1 p2 jmEq_P _ _ = Nothing jmEq_PCode :: PDatumCode xss vs a -> PDatumCode xss ws a -> Maybe (TypeEq vs ws) jmEq_PCode (PInr p1) (PInr p2) = jmEq_PCode p1 p2 jmEq_PCode (PInl p1) (PInl p2) = jmEq_PStruct p1 p2 jmEq_PCode _ _ = Nothing jmEq_PStruct :: PDatumStruct xs vs a -> PDatumStruct xs ws a -> Maybe (TypeEq vs ws) jmEq_PStruct (PEt c1 c2) (PEt d1 d2) = do Refl <- jmEq_PFun c1 d1 Refl <- jmEq_PStruct c2 d2 Just Refl jmEq_PStruct PDone PDone = Just Refl jmEq_PFun :: PDatumFun f vs a -> PDatumFun f ws a -> Maybe (TypeEq vs ws) jmEq_PFun (PKonst p1) (PKonst p2) = jmEq_P p1 p2 jmEq_PFun (PIdent p1) (PIdent p2) = jmEq_P p1 p2 #if __PARTIAL_DATUM_JMEQ__ instance JmEq2 (PDatumStruct xs) where jmEq2 (PEt c1 c2) (PEt d1 d2) = do (Refl, Refl) <- jmEq2 c1 d1 (Refl, Refl) <- jmEq2 c2 d2 Just (Refl, Refl) jmEq2 PDone PDone = Just (Refl, cannotProve "jmEq2@PDatumStruct{PDone}") jmEq2 _ _ = Nothing instance JmEq1 (PDatumStruct xs vars) where jmEq1 p1 p2 = jmEq2 p1 p2 >>= \(_,proof) -> Just proof #endif instance Eq2 (PDatumStruct xs) where eq2 p1 p2 = maybe False (const True) $ jmEq_PStruct p1 p2 instance Eq1 (PDatumStruct xs vars) where eq1 = eq2 instance Eq (PDatumStruct xs vars a) where (==) = eq1 -- TODO: instance Read (PDatumStruct xs vars a) instance Show2 (PDatumStruct xs) where showsPrec2 p (PEt d1 d2) = showParen_22 p "PEt" d1 d2 showsPrec2 _ PDone = showString "PDone" instance Show1 (PDatumStruct xs vars) where showsPrec1 = showsPrec2 show1 = show2 instance Show (PDatumStruct xs vars a) where showsPrec = showsPrec1 show = show1 TODO : as necessary Functor22 , Foldable22 , ---------------------------------------------------------------- data PDatumFun :: HakaruFun -> [Hakaru] -> Hakaru -> * where PKonst :: !(Pattern vars b) -> PDatumFun ('K b) vars a PIdent :: !(Pattern vars a) -> PDatumFun 'I vars a #if __PARTIAL_DATUM_JMEQ__ instance JmEq2 (PDatumFun x) where jmEq2 (PKonst p1) (PKonst p2) = do (Refl, Refl) <- jmEq2 p1 p2 Just (Refl, cannotProve "jmEq2@PDatumFun{PKonst}") jmEq2 (PIdent p1) (PIdent p2) = jmEq2 p1 p2 jmEq2 _ _ = Nothing instance JmEq1 (PDatumFun x vars) where jmEq1 (PKonst e) (PKonst f) = do Refl <- jmEq1 e f Just (cannotProve "jmEq1@PDatumFun{PKonst}") jmEq1 (PIdent e) (PIdent f) = jmEq1 e f jmEq1 _ _ = Nothing #endif instance Eq2 (PDatumFun x) where eq2 (PKonst e) (PKonst f) = eq2 e f eq2 (PIdent e) (PIdent f) = eq2 e f instance Eq1 (PDatumFun x vars) where eq1 = eq2 instance Eq (PDatumFun x vars a) where (==) = eq1 -- TODO: instance Read (PDatumFun x vars a) instance Show2 (PDatumFun x) where showsPrec2 p (PKonst e) = showParen_2 p "PKonst" e showsPrec2 p (PIdent e) = showParen_2 p "PIdent" e instance Show1 (PDatumFun x vars) where showsPrec1 = showsPrec2 show1 = show2 instance Show (PDatumFun x vars a) where showsPrec = showsPrec1 show = show1 TODO : as necessary Functor22 , Foldable22 , ---------------------------------------------------------------- pTrue, pFalse :: Pattern '[] HBool pTrue = PDatum tdTrue . PInl $ PDone pFalse = PDatum tdFalse . PInr . PInl $ PDone pUnit :: Pattern '[] HUnit pUnit = PDatum tdUnit . PInl $ PDone HACK : using undefined like that is n't going to help if we use -- the variant of eqAppendIdentity that actually needs the Sing... varsOfPattern :: Pattern vars a -> proxy vars varsOfPattern _ = error "TODO: varsOfPattern" pPair :: Pattern vars1 a -> Pattern vars2 b -> Pattern (vars1 ++ vars2) (HPair a b) pPair x y = case eqAppendIdentity (varsOfPattern y) of Refl -> PDatum tdPair . PInl $ PKonst x `PEt` PKonst y `PEt` PDone pLeft :: Pattern vars a -> Pattern vars (HEither a b) pLeft x = case eqAppendIdentity (varsOfPattern x) of Refl -> PDatum tdLeft . PInl $ PKonst x `PEt` PDone pRight :: Pattern vars b -> Pattern vars (HEither a b) pRight y = case eqAppendIdentity (varsOfPattern y) of Refl -> PDatum tdRight . PInr . PInl $ PKonst y `PEt` PDone pNil :: Pattern '[] (HList a) pNil = PDatum tdNil . PInl $ PDone pCons :: Pattern vars1 a -> Pattern vars2 (HList a) -> Pattern (vars1 ++ vars2) (HList a) pCons x xs = case eqAppendIdentity (varsOfPattern xs) of Refl -> PDatum tdCons . PInr . PInl $ PKonst x `PEt` PIdent xs `PEt` PDone pNothing :: Pattern '[] (HMaybe a) pNothing = PDatum tdNothing . PInl $ PDone pJust :: Pattern vars a -> Pattern vars (HMaybe a) pJust x = case eqAppendIdentity (varsOfPattern x) of Refl -> PDatum tdJust . PInr . PInl $ PKonst x `PEt` PDone ---------------------------------------------------------------- -- TODO: a pretty infix syntax, like (:=>) or something? -- -- TODO: this datatype is helpful for capturing the existential; -- but other than that, it should be replaced\/augmented with a -- type for pattern automata, so we can optimize case analysis. -- TODO : if we used the argument order @Branch abt a b@ then we could give @Foo2@ instances instead of just @Foo1@ instances . -- Also would possibly let us talk about branches as profunctors mapping @a@ to Would either of these actually be helpful -- in practice for us? data Branch (a :: Hakaru) -- The type of the scrutinee. The ' ABT ' of the body . (b :: Hakaru) -- The type of the body. = forall xs. Branch !(Pattern xs a) !(abt xs b) instance Eq2 abt => Eq1 (Branch a abt) where eq1 (Branch p1 e1) (Branch p2 e2) = case jmEq_P p1 p2 of Nothing -> False Just Refl -> eq2 e1 e2 instance Eq2 abt => Eq (Branch a abt b) where (==) = eq1 -- TODO: instance Read (Branch abt a b) instance Show2 abt => Show1 (Branch a abt) where showsPrec1 p (Branch pat e) = showParen_22 p "Branch" pat e instance Show2 abt => Show (Branch a abt b) where showsPrec = showsPrec1 show = show1 instance Functor21 (Branch a) where fmap21 f (Branch p e) = Branch p (f e) instance Foldable21 (Branch a) where foldMap21 f (Branch _ e) = f e instance Traversable21 (Branch a) where traverse21 f (Branch pat e) = Branch pat <$> f e ---------------------------------------------------------------- -- | A generalization of the 'Branch' type to allow a \"body\" of any type . data GBranch (a :: Hakaru) (r :: *) = forall xs. GBranch !(Pattern xs a) !(List1 Variable xs) r instance Functor (GBranch a) where fmap f (GBranch pat vars x) = GBranch pat vars (f x) instance F.Foldable (GBranch a) where foldMap f (GBranch _ _ x) = f x instance T.Traversable (GBranch a) where traverse f (GBranch pat vars x) = GBranch pat vars <$> f x ---------------------------------------------------------------- ----------------------------------------------------------- fin.
null
https://raw.githubusercontent.com/hakaru-dev/hakaru/94157c89ea136c3b654a85cce51f19351245a490/haskell/Language/Hakaru/Syntax/Datum.hs
haskell
# OPTIONS_GHC -Wall -fwarn-tabs # -------------------------------------------------------------- 2016.05.24 | License : BSD3 Maintainer : Stability : experimental At present we only support regular-recursive polynomial data types. Reduction of case analysis on data types is in don't actually work because of problems with matching existentially quantified types in the basis cases. For now I've left the partially-defined code in place, but turned it off with the either (a) remove this unused code, or (b) if the instances are truly necessary then we should add the 'Sing' arguments everywhere to make things work :( -------------------------------------------------------------- * Data constructors ** Some smart constructors for the \"built-in\" datatypes *** Variants which allow explicit type passing. * Pattern constructors ** Some smart constructors for the \"built-in\" datatypes ** Generalized branches -------------------------------------------------------------- -------------------------------------------------------------- TODO: change the kind to @(Hakaru -> *) -> HakaruCon -> *@ so should be called when pretty-printing, giving error messages, etc. Like the hints for variable names, its value is not actually used to decide which constructor is meant or which pattern matches. # UNPACK # jmEq on the singleton is sufficient. TODO: instance Read (Datum ast a) -------------------------------------------------------------- | The intermediate components of a data constructor. The intuition datatypes. But as we go along, we'll be doing induction on the @[[HakaruFun]]@ functor. <-dev/hakaru/issues/6> Skip rightwards along the sum. Inject into the sum. functions, because (1) we never existentially close over any a good enough inductive hypothesis from polymorphism alone. This instance works, but recurses into non-working instances. -------------------------------------------------------------- <-dev/hakaru/issues/6> Close off the product. HACK: to handle 'Done' in the cases where we can. TODO: instance Read (DatumStruct xs abt a) -------------------------------------------------------------- TODO: do we like those constructor names? Should we change them? <-dev/hakaru/issues/6> Hit a leaf which isn't a recursive component of the datatype. Hit a leaf which is a recursive component of the datatype. -------------------------------------------------------------- we can use functions to construct our Case_ statements, so library designers don't need pattern synonyms. Whereas, for the internal values, so the pattern synonyms wouldn't even be helpful. -------------------------------------------------------------- -------------------------------------------------------------- -------------------------------------------------------------- TODO: negative patterns? (to facilitate reordering of case branches) TODO: disjunctive patterns, a~la ML? TODO: exhaustiveness, non-overlap, dead-branch checking | We index patterns by the type they scrutinize. This requires the parser to be smart enough to build these patterns up, but then it guarantees that we can't have 'Case_' of patterns which can't possibly match according to our type system. In addition, we also index patterns by the type of what variables they bind, so that we can ensure that 'Branch' will never \"go wrong\". variants for pattern matching. <-dev/hakaru/issues/6> A pattern variable. # UNPACK # so @xss@ and @xss'@ aren't guaranteed to be the same TODO: instance Read (Pattern vars a) -------------------------------------------------------------- This instance works, but recurses into non-working instances. TODO: instance Read (PDatumCode xss vars a) -------------------------------------------------------------- we only return the equality proof for the penultimate index rather than both the penultimate and ultimate index. (Because xs vars)@ and @Eq1 (Branch a abt)@ instances, since we need to make sure the existential @vars@ match up. fact that the @a@ parameter is fixed to be the same in both patterns. TODO: instance Read (PDatumStruct xs vars a) -------------------------------------------------------------- TODO: instance Read (PDatumFun x vars a) -------------------------------------------------------------- the variant of eqAppendIdentity that actually needs the Sing... -------------------------------------------------------------- TODO: a pretty infix syntax, like (:=>) or something? TODO: this datatype is helpful for capturing the existential; but other than that, it should be replaced\/augmented with a type for pattern automata, so we can optimize case analysis. Also would possibly let us talk about branches as profunctors in practice for us? The type of the scrutinee. The type of the body. TODO: instance Read (Branch abt a b) -------------------------------------------------------------- | A generalization of the 'Branch' type to allow a \"body\" of -------------------------------------------------------------- --------------------------------------------------------- fin.
# LANGUAGE CPP , , PolyKinds , GADTs , TypeOperators , TypeFamilies , ExistentialQuantification # , DataKinds , PolyKinds , GADTs , TypeOperators , TypeFamilies , ExistentialQuantification #-} Module : Language . Hakaru . Syntax . Datum Copyright : Copyright ( c ) 2016 the Hakaru team Portability : GHC - only Haskell types and helpers for Hakaru 's user - defined data types . " Language . Hakaru . Syntax . Datum " . /Developers note:/ many of the ' JmEq1 ' instances in this file @__PARTIAL_DATUM_JMEQ__@ CPP macro . In the future we should module Language.Hakaru.Syntax.Datum ( Datum(..), datumHint, datumType , DatumCode(..) , DatumStruct(..) , DatumFun(..) , dTrue, dFalse, dBool , dUnit , dPair , dLeft, dRight , dNil, dCons , dNothing, dJust , dPair_ , dLeft_, dRight_ , dNil_, dCons_ , dNothing_, dJust_ , Branch(..) , Pattern(..) , PDatumCode(..) , PDatumStruct(..) , PDatumFun(..) , pTrue, pFalse , pUnit , pPair , pLeft, pRight , pNil, pCons , pNothing, pJust , GBranch(..) ) where import qualified Data.Text as Text import Data.Text (Text) #if __GLASGOW_HASKELL__ < 710 import Data.Monoid (Monoid(..)) import Control.Applicative #endif import qualified Data.Foldable as F import qualified Data.Traversable as T import Language.Hakaru.Syntax.IClasses import Language.Hakaru.Syntax.Variable (Variable(..)) TODO : make things polykinded so we can make our ABT implementation independent of Hakaru 's type system . import Language.Hakaru.Types.DataKind import Language.Hakaru.Types.Sing #if __PARTIAL_DATUM_JMEQ__ cannotProve :: String -> a cannotProve fun = error $ "Language.Hakaru.Syntax.Datum." ++ fun ++ ": Cannot prove Refl because of phantomness" #endif we can avoid the use of GADTs ? Would that allow us to actually UNPACK ? | A fully saturated data constructor , which recurses as @ast@. We define this type as separate from ' DatumCode ' for two reasons . First is to capture the fact that the datum is " ( i.e. , is a well - formed constructor ) . The second is to have a type which is indexed by its ' Hakaru ' type , whereas ' DatumCode ' involves non - Hakaru types . The first component is a hint for what the data constructor data Datum :: (Hakaru -> *) -> Hakaru -> * where Datum -> !(Sing (HData' t)) -> !(DatumCode (Code t) ast (HData' t)) -> Datum ast (HData' t) datumHint :: Datum ast (HData' t) -> Text datumHint (Datum hint _ _) = hint datumType :: Datum ast (HData' t) -> Sing (HData' t) datumType (Datum _ typ _) = typ N.B. , This does n't require jmEq on ' DatumCode ' nor on @ast@. The instance Eq1 ast => JmEq1 (Datum ast) where jmEq1 (Datum _ typ1 d1) (Datum _ typ2 d2) = case jmEq1 typ1 typ2 of Just proof@Refl | eq1 d1 d2 -> Just proof _ -> Nothing instance Eq1 ast => Eq1 (Datum ast) where eq1 (Datum _ _ d1) (Datum _ _ d2) = eq1 d1 d2 instance Eq1 ast => Eq (Datum ast a) where (==) = eq1 instance Show1 ast => Show1 (Datum ast) where showsPrec1 p (Datum hint typ d) = showParen_011 p "Datum" hint typ d instance Show1 ast => Show (Datum ast a) where showsPrec = showsPrec1 show = show1 instance Functor11 Datum where fmap11 f (Datum hint typ d) = Datum hint typ (fmap11 f d) instance Foldable11 Datum where foldMap11 f (Datum _ _ d) = foldMap11 f d instance Traversable11 Datum where traverse11 f (Datum hint typ d) = Datum hint typ <$> traverse11 f d infixr 7 `Et`, `PEt` behind the two indices is that the @[[HakaruFun]]@ is a functor applied to the Hakaru type . Initially the @[[HakaruFun]]@ functor will be the ' Code ' associated with the Hakaru type ; hence it 's the one - step unrolling of the fixed point for our recursive data DatumCode :: [[HakaruFun]] -> (Hakaru -> *) -> Hakaru -> * where BUG : haddock does n't like annotations on GADT constructors Inr :: !(DatumCode xss abt a) -> DatumCode (xs ': xss) abt a Inl :: !(DatumStruct xs abt a) -> DatumCode (xs ': xss) abt a N.B. , these " instances rely on polymorphic recursion , since the @code@ changes at each constructor . However , we do n't actually need to abstract over @code@ in order to define these codes , and ( 2 ) the code is always getting smaller ; so we have #if __PARTIAL_DATUM_JMEQ__ instance JmEq1 ast => JmEq1 (DatumCode xss ast) where jmEq1 (Inr c) (Inr d) = jmEq1 c d jmEq1 (Inl c) (Inl d) = jmEq1 c d jmEq1 _ _ = Nothing #endif instance Eq1 ast => Eq1 (DatumCode xss ast) where eq1 (Inr c) (Inr d) = eq1 c d eq1 (Inl c) (Inl d) = eq1 c d eq1 _ _ = False instance Eq1 ast => Eq (DatumCode xss ast a) where (==) = eq1 TODO : instance Read ( DatumCode xss abt a ) instance Show1 ast => Show1 (DatumCode xss ast) where showsPrec1 p (Inr d) = showParen_1 p "Inr" d showsPrec1 p (Inl d) = showParen_1 p "Inl" d instance Show1 ast => Show (DatumCode xss ast a) where showsPrec = showsPrec1 show = show1 instance Functor11 (DatumCode xss) where fmap11 f (Inr d) = Inr (fmap11 f d) fmap11 f (Inl d) = Inl (fmap11 f d) instance Foldable11 (DatumCode xss) where foldMap11 f (Inr d) = foldMap11 f d foldMap11 f (Inl d) = foldMap11 f d instance Traversable11 (DatumCode xss) where traverse11 f (Inr d) = Inr <$> traverse11 f d traverse11 f (Inl d) = Inl <$> traverse11 f d data DatumStruct :: [HakaruFun] -> (Hakaru -> *) -> Hakaru -> * where BUG : haddock does n't like annotations on GADT constructors Combine components of the product . ( \"et\ " means \"and\ " in Latin ) Et :: !(DatumFun x abt a) -> !(DatumStruct xs abt a) -> DatumStruct (x ': xs) abt a Done :: DatumStruct '[] abt a #if __PARTIAL_DATUM_JMEQ__ instance JmEq1 ast => JmEq1 (DatumStruct xs ast) where jmEq1 (Et c1 c2) (Et d1 d2) = do Refl <- jmEq1 c1 d1 Refl <- jmEq1 c2 d2 Just Refl jmEq1 Done Done = Just (cannotProve "jmEq1@DatumStruct{Done}") jmEq1 _ _ = Nothing #endif instance Eq1 ast => Eq1 (DatumStruct xs ast) where eq1 (Et c1 c2) (Et d1 d2) = eq1 c1 d1 && eq1 c2 d2 eq1 Done Done = True instance Eq1 ast => Eq (DatumStruct xs ast a) where (==) = eq1 instance Show1 ast => Show1 (DatumStruct xs ast) where showsPrec1 p (Et d1 d2) = showParen_11 p "Et" d1 d2 showsPrec1 _ Done = showString "Done" instance Show1 ast => Show (DatumStruct xs ast a) where showsPrec = showsPrec1 show = show1 instance Functor11 (DatumStruct xs) where fmap11 f (Et d1 d2) = Et (fmap11 f d1) (fmap11 f d2) fmap11 _ Done = Done instance Foldable11 (DatumStruct xs) where foldMap11 f (Et d1 d2) = foldMap11 f d1 `mappend` foldMap11 f d2 foldMap11 _ Done = mempty instance Traversable11 (DatumStruct xs) where traverse11 f (Et d1 d2) = Et <$> traverse11 f d1 <*> traverse11 f d2 traverse11 _ Done = pure Done data DatumFun :: HakaruFun -> (Hakaru -> *) -> Hakaru -> * where BUG : haddock does n't like annotations on GADT constructors Konst :: !(ast b) -> DatumFun ('K b) ast a Ident :: !(ast a) -> DatumFun 'I ast a #if __PARTIAL_DATUM_JMEQ__ instance JmEq1 ast => JmEq1 (DatumFun x ast) where jmEq1 (Konst e) (Konst f) = do This ' ' should be free because @x@ is fixed Just (cannotProve "jmEq1@DatumFun{Konst}") jmEq1 (Ident e) (Ident f) = jmEq1 e f jmEq1 _ _ = Nothing #endif instance Eq1 ast => Eq1 (DatumFun x ast) where eq1 (Konst e) (Konst f) = eq1 e f eq1 (Ident e) (Ident f) = eq1 e f instance Eq1 ast => Eq (DatumFun x ast a) where (==) = eq1 TODO : instance Read ( DatumFun x abt a ) instance Show1 ast => Show1 (DatumFun x ast) where showsPrec1 p (Konst e) = showParen_1 p "Konst" e showsPrec1 p (Ident e) = showParen_1 p "Ident" e instance Show1 ast => Show (DatumFun x ast a) where showsPrec = showsPrec1 show = show1 instance Functor11 (DatumFun x) where fmap11 f (Konst e) = Konst (f e) fmap11 f (Ident e) = Ident (f e) instance Foldable11 (DatumFun x) where foldMap11 f (Konst e) = f e foldMap11 f (Ident e) = f e instance Traversable11 (DatumFun x) where traverse11 f (Konst e) = Konst <$> f e traverse11 f (Ident e) = Ident <$> f e In GHC 7.8 we can make the monomorphic smart constructors into pattern synonyms , but 7.8 ca n't handle anything polymorphic ( but GHC 7.10 can ) . For libraries ( e.g. , " Language . Hakaru . Syntax . Prelude " ) aspects of the compiler , we need to handle all possible Datum dTrue, dFalse :: Datum ast HBool dTrue = Datum tdTrue sBool . Inl $ Done dFalse = Datum tdFalse sBool . Inr . Inl $ Done dBool :: Bool -> Datum ast HBool dBool b = if b then dTrue else dFalse dUnit :: Datum ast HUnit dUnit = Datum tdUnit sUnit . Inl $ Done dPair :: (SingI a, SingI b) => ast a -> ast b -> Datum ast (HPair a b) dPair = dPair_ sing sing dPair_ :: Sing a -> Sing b -> ast a -> ast b -> Datum ast (HPair a b) dPair_ a b x y = Datum tdPair (sPair a b) . Inl $ Konst x `Et` Konst y `Et` Done dLeft :: (SingI a, SingI b) => ast a -> Datum ast (HEither a b) dLeft = dLeft_ sing sing dLeft_ :: Sing a -> Sing b -> ast a -> Datum ast (HEither a b) dLeft_ a b = Datum tdLeft (sEither a b) . Inl . (`Et` Done) . Konst dRight :: (SingI a, SingI b) => ast b -> Datum ast (HEither a b) dRight = dRight_ sing sing dRight_ :: Sing a -> Sing b -> ast b -> Datum ast (HEither a b) dRight_ a b = Datum tdRight (sEither a b) . Inr . Inl . (`Et` Done) . Konst dNil :: (SingI a) => Datum ast (HList a) dNil = dNil_ sing dNil_ :: Sing a -> Datum ast (HList a) dNil_ a = Datum tdNil (sList a) . Inl $ Done dCons :: (SingI a) => ast a -> ast (HList a) -> Datum ast (HList a) dCons = dCons_ sing dCons_ :: Sing a -> ast a -> ast (HList a) -> Datum ast (HList a) dCons_ a x xs = Datum tdCons (sList a) . Inr . Inl $ Konst x `Et` Ident xs `Et` Done dNothing :: (SingI a) => Datum ast (HMaybe a) dNothing = dNothing_ sing dNothing_ :: Sing a -> Datum ast (HMaybe a) dNothing_ a = Datum tdNothing (sMaybe a) $ Inl Done dJust :: (SingI a) => ast a -> Datum ast (HMaybe a) dJust = dJust_ sing dJust_ :: Sing a -> ast a -> Datum ast (HMaybe a) dJust_ a = Datum tdJust (sMaybe a) . Inr . Inl . (`Et` Done) . Konst tdTrue, tdFalse, tdUnit, tdPair, tdLeft, tdRight, tdNil, tdCons, tdNothing, tdJust :: Text tdTrue = Text.pack "true" tdFalse = Text.pack "false" tdUnit = Text.pack "unit" tdPair = Text.pack "pair" tdLeft = Text.pack "left" tdRight = Text.pack "right" tdNil = Text.pack "nil" tdCons = Text.pack "cons" tdNothing = Text.pack "nothing" tdJust = Text.pack "just" TODO : equality patterns for Nat\/Int ? ( what about Prob\/Real ? ? ) Alas , this latter indexing means we ca n't use ' DatumCode ' , ' DatumStruct ' , and ' DatumFun ' but rather must define our own @P@ data Pattern :: [Hakaru] -> Hakaru -> * where BUG : haddock does n't like annotations on GADT constructors The \"don't care\ " wildcard pattern . PWild :: Pattern '[] a PVar :: Pattern '[ a ] a A data type constructor pattern . As with the ' Datum ' constructor , the first component is a hint . PDatum -> !(PDatumCode (Code t) vars (HData' t)) -> Pattern vars (HData' t) #if __PARTIAL_DATUM_JMEQ__ instance JmEq2 Pattern where jmEq2 PWild PWild = Just (Refl, cannotProve "jmEq2@Pattern{PWild}") jmEq2 PVar PVar = Just (cannotProve "jmEq2@Pattern{PVar}", cannotProve "jmEq2@Pattern{PVar}") jmEq2 (PDatum _ d1) (PDatum _ d2) = jmEq2_fake d1 d2 where jmEq2_fake :: PDatumCode xss vars1 a1 -> PDatumCode xss' vars2 a2 -> Maybe (TypeEq vars1 vars2, TypeEq a1 a2) jmEq2_fake = jmEq2 _ _ = Nothing instance JmEq1 (Pattern vars) where jmEq1 p1 p2 = jmEq2 p1 p2 >>= \(_,proof) -> Just proof #endif instance Eq2 Pattern where eq2 PWild PWild = True eq2 PVar PVar = True eq2 (PDatum _ d1) (PDatum _ d2) = eq2 d1 d2 eq2 _ _ = False instance Eq1 (Pattern vars) where eq1 = eq2 instance Eq (Pattern vars a) where (==) = eq1 instance Show2 Pattern where showsPrec2 _ PWild = showString "PWild" showsPrec2 _ PVar = showString "PVar" showsPrec2 p (PDatum hint d) = showParen_02 p "PDatum" hint d instance Show1 (Pattern vars) where showsPrec1 = showsPrec2 show1 = show2 instance Show (Pattern vars a) where showsPrec = showsPrec1 show = show1 TODO : as necessary Functor22 , Foldable22 , data PDatumCode :: [[HakaruFun]] -> [Hakaru] -> Hakaru -> * where PInr :: !(PDatumCode xss vars a) -> PDatumCode (xs ': xss) vars a PInl :: !(PDatumStruct xs vars a) -> PDatumCode (xs ': xss) vars a #if __PARTIAL_DATUM_JMEQ__ instance JmEq2 (PDatumCode xss) where jmEq2 (PInr c) (PInr d) = jmEq2 c d jmEq2 (PInl c) (PInl d) = jmEq2 c d jmEq2 _ _ = Nothing instance JmEq1 (PDatumCode xss vars) where jmEq1 (PInr c) (PInr d) = jmEq1 c d jmEq1 (PInl c) (PInl d) = jmEq1 c d jmEq1 _ _ = Nothing #endif instance Eq2 (PDatumCode xss) where eq2 (PInr c) (PInr d) = eq2 c d eq2 (PInl c) (PInl d) = eq2 c d eq2 _ _ = False instance Eq1 (PDatumCode xss vars) where eq1 = eq2 instance Eq (PDatumCode xss vars a) where (==) = eq1 instance Show2 (PDatumCode xss) where showsPrec2 p (PInr d) = showParen_2 p "PInr" d showsPrec2 p (PInl d) = showParen_2 p "PInl" d instance Show1 (PDatumCode xss vars) where showsPrec1 = showsPrec2 show1 = show2 instance Show (PDatumCode xss vars a) where showsPrec = showsPrec1 show = show1 TODO : as necessary Functor22 , Foldable22 , data PDatumStruct :: [HakaruFun] -> [Hakaru] -> Hakaru -> * where PEt :: !(PDatumFun x vars1 a) -> !(PDatumStruct xs vars2 a) -> PDatumStruct (x ': xs) (vars1 ++ vars2) a PDone :: PDatumStruct '[] '[] a This block of recursive functions are analogous to ' JmEq2 ' except we return proofs for the penultimate index , but not for the ultimate . ) This is necessary for defining the @Eq1 ( PDatumStruct N.B. , that we can use ' ' in the ' PVar ' case relies on the jmEq_P :: Pattern vs a -> Pattern ws a -> Maybe (TypeEq vs ws) jmEq_P PWild PWild = Just Refl jmEq_P PVar PVar = Just Refl jmEq_P (PDatum _ p1) (PDatum _ p2) = jmEq_PCode p1 p2 jmEq_P _ _ = Nothing jmEq_PCode :: PDatumCode xss vs a -> PDatumCode xss ws a -> Maybe (TypeEq vs ws) jmEq_PCode (PInr p1) (PInr p2) = jmEq_PCode p1 p2 jmEq_PCode (PInl p1) (PInl p2) = jmEq_PStruct p1 p2 jmEq_PCode _ _ = Nothing jmEq_PStruct :: PDatumStruct xs vs a -> PDatumStruct xs ws a -> Maybe (TypeEq vs ws) jmEq_PStruct (PEt c1 c2) (PEt d1 d2) = do Refl <- jmEq_PFun c1 d1 Refl <- jmEq_PStruct c2 d2 Just Refl jmEq_PStruct PDone PDone = Just Refl jmEq_PFun :: PDatumFun f vs a -> PDatumFun f ws a -> Maybe (TypeEq vs ws) jmEq_PFun (PKonst p1) (PKonst p2) = jmEq_P p1 p2 jmEq_PFun (PIdent p1) (PIdent p2) = jmEq_P p1 p2 #if __PARTIAL_DATUM_JMEQ__ instance JmEq2 (PDatumStruct xs) where jmEq2 (PEt c1 c2) (PEt d1 d2) = do (Refl, Refl) <- jmEq2 c1 d1 (Refl, Refl) <- jmEq2 c2 d2 Just (Refl, Refl) jmEq2 PDone PDone = Just (Refl, cannotProve "jmEq2@PDatumStruct{PDone}") jmEq2 _ _ = Nothing instance JmEq1 (PDatumStruct xs vars) where jmEq1 p1 p2 = jmEq2 p1 p2 >>= \(_,proof) -> Just proof #endif instance Eq2 (PDatumStruct xs) where eq2 p1 p2 = maybe False (const True) $ jmEq_PStruct p1 p2 instance Eq1 (PDatumStruct xs vars) where eq1 = eq2 instance Eq (PDatumStruct xs vars a) where (==) = eq1 instance Show2 (PDatumStruct xs) where showsPrec2 p (PEt d1 d2) = showParen_22 p "PEt" d1 d2 showsPrec2 _ PDone = showString "PDone" instance Show1 (PDatumStruct xs vars) where showsPrec1 = showsPrec2 show1 = show2 instance Show (PDatumStruct xs vars a) where showsPrec = showsPrec1 show = show1 TODO : as necessary Functor22 , Foldable22 , data PDatumFun :: HakaruFun -> [Hakaru] -> Hakaru -> * where PKonst :: !(Pattern vars b) -> PDatumFun ('K b) vars a PIdent :: !(Pattern vars a) -> PDatumFun 'I vars a #if __PARTIAL_DATUM_JMEQ__ instance JmEq2 (PDatumFun x) where jmEq2 (PKonst p1) (PKonst p2) = do (Refl, Refl) <- jmEq2 p1 p2 Just (Refl, cannotProve "jmEq2@PDatumFun{PKonst}") jmEq2 (PIdent p1) (PIdent p2) = jmEq2 p1 p2 jmEq2 _ _ = Nothing instance JmEq1 (PDatumFun x vars) where jmEq1 (PKonst e) (PKonst f) = do Refl <- jmEq1 e f Just (cannotProve "jmEq1@PDatumFun{PKonst}") jmEq1 (PIdent e) (PIdent f) = jmEq1 e f jmEq1 _ _ = Nothing #endif instance Eq2 (PDatumFun x) where eq2 (PKonst e) (PKonst f) = eq2 e f eq2 (PIdent e) (PIdent f) = eq2 e f instance Eq1 (PDatumFun x vars) where eq1 = eq2 instance Eq (PDatumFun x vars a) where (==) = eq1 instance Show2 (PDatumFun x) where showsPrec2 p (PKonst e) = showParen_2 p "PKonst" e showsPrec2 p (PIdent e) = showParen_2 p "PIdent" e instance Show1 (PDatumFun x vars) where showsPrec1 = showsPrec2 show1 = show2 instance Show (PDatumFun x vars a) where showsPrec = showsPrec1 show = show1 TODO : as necessary Functor22 , Foldable22 , pTrue, pFalse :: Pattern '[] HBool pTrue = PDatum tdTrue . PInl $ PDone pFalse = PDatum tdFalse . PInr . PInl $ PDone pUnit :: Pattern '[] HUnit pUnit = PDatum tdUnit . PInl $ PDone HACK : using undefined like that is n't going to help if we use varsOfPattern :: Pattern vars a -> proxy vars varsOfPattern _ = error "TODO: varsOfPattern" pPair :: Pattern vars1 a -> Pattern vars2 b -> Pattern (vars1 ++ vars2) (HPair a b) pPair x y = case eqAppendIdentity (varsOfPattern y) of Refl -> PDatum tdPair . PInl $ PKonst x `PEt` PKonst y `PEt` PDone pLeft :: Pattern vars a -> Pattern vars (HEither a b) pLeft x = case eqAppendIdentity (varsOfPattern x) of Refl -> PDatum tdLeft . PInl $ PKonst x `PEt` PDone pRight :: Pattern vars b -> Pattern vars (HEither a b) pRight y = case eqAppendIdentity (varsOfPattern y) of Refl -> PDatum tdRight . PInr . PInl $ PKonst y `PEt` PDone pNil :: Pattern '[] (HList a) pNil = PDatum tdNil . PInl $ PDone pCons :: Pattern vars1 a -> Pattern vars2 (HList a) -> Pattern (vars1 ++ vars2) (HList a) pCons x xs = case eqAppendIdentity (varsOfPattern xs) of Refl -> PDatum tdCons . PInr . PInl $ PKonst x `PEt` PIdent xs `PEt` PDone pNothing :: Pattern '[] (HMaybe a) pNothing = PDatum tdNothing . PInl $ PDone pJust :: Pattern vars a -> Pattern vars (HMaybe a) pJust x = case eqAppendIdentity (varsOfPattern x) of Refl -> PDatum tdJust . PInr . PInl $ PKonst x `PEt` PDone TODO : if we used the argument order @Branch abt a b@ then we could give @Foo2@ instances instead of just @Foo1@ instances . mapping @a@ to Would either of these actually be helpful data Branch The ' ABT ' of the body . = forall xs. Branch !(Pattern xs a) !(abt xs b) instance Eq2 abt => Eq1 (Branch a abt) where eq1 (Branch p1 e1) (Branch p2 e2) = case jmEq_P p1 p2 of Nothing -> False Just Refl -> eq2 e1 e2 instance Eq2 abt => Eq (Branch a abt b) where (==) = eq1 instance Show2 abt => Show1 (Branch a abt) where showsPrec1 p (Branch pat e) = showParen_22 p "Branch" pat e instance Show2 abt => Show (Branch a abt b) where showsPrec = showsPrec1 show = show1 instance Functor21 (Branch a) where fmap21 f (Branch p e) = Branch p (f e) instance Foldable21 (Branch a) where foldMap21 f (Branch _ e) = f e instance Traversable21 (Branch a) where traverse21 f (Branch pat e) = Branch pat <$> f e any type . data GBranch (a :: Hakaru) (r :: *) = forall xs. GBranch !(Pattern xs a) !(List1 Variable xs) r instance Functor (GBranch a) where fmap f (GBranch pat vars x) = GBranch pat vars (f x) instance F.Foldable (GBranch a) where foldMap f (GBranch _ _ x) = f x instance T.Traversable (GBranch a) where traverse f (GBranch pat vars x) = GBranch pat vars <$> f x
aff5227a4b7c13384bf919eb68531808bee2cde7ad3300d2561414fff6d49d98
lambdaisland/harvest
jdbc.clj
(ns scratch.jdbc) (ns lambdaisland.harvest.jdbc (:require [clojure.string :as str] [lambdaisland.harvest :as harvest] [lambdaisland.harvest.kernel :as hk]) (:import (java.sql DriverManager Statement))) (defn get-connection [url] (DriverManager/getConnection url)) (defn sql-ident [s] (str "\"" (str/replace s #"\"" "\"\"") "\"")) (defn insert-sql [{:keys [table columns]}] (str "INSERT INTO " (sql-ident table) " (" (str/join "," (map sql-ident columns)) ") " "VALUES " " (" (str/join "," (repeat (count columns) "?")) ") ")) (defn create-table-sql [{:keys [table columns]}] (str "CREATE TABLE " (sql-ident table) " (" (str/join "," (for [[k v] columns] (str (sql-ident k) " " v))) ")")) (defn insert-stmt [conn opts] (.prepareStatement conn (insert-sql opts) Statement/RETURN_GENERATED_KEYS)) (defn insert! [conn table m] (let [columns (keys m) stmt (insert-stmt conn {:table table :columns (map name columns)})] (doseq [[col idx] (map list columns (range))] (.setObject stmt (inc idx) (get m col))) (assert (= 1 (.executeUpdate stmt))) (merge m (first (resultset-seq (.getGeneratedKeys stmt)))))) (defn exec! [conn sql] (.executeUpdate (.createStatement conn) sql)) (defn drop! [conn table] (exec! conn (str "DROP TABLE " (sql-ident table)))) (defn create! ([conn factory] (create! conn factory nil)) ([conn factory rules] (create! conn factory rules nil)) ([conn factory rules opts] (let [{:keys [value] :as res} (hk/build (merge {:registry @harvest/registry :rules rules :hooks [{:map-entry (fn [result query ctx] (if (hk/ref? (val query)) (update result (key query) :id) result)) :map (fn [result query ctx] (if-let [table-name (some-> (:ref ctx) name)] (update result :value #(insert! conn table-name %)) result)) }]} opts) (harvest/refify @harvest/registry factory))] (with-meta value res)))) (comment (def conn (get-connection "jdbc:h2:./example")) (run! #(exec! conn (create-table-sql %)) #_ #(drop! conn (:table %)) [{:table "profile" :columns {"id" "INT AUTO_INCREMENT PRIMARY KEY" "handle" "VARCHAR(255)" "name" "VARCHAR(255)" "website" "VARCHAR(255)"}} {:table "article" :columns {"id" "INT AUTO_INCREMENT PRIMARY KEY" "title" "VARCHAR(255)" "profile_id" "INT"}} ]) (hk/build {:registry hk/registry :hooks [{:finalize-entity (fn [m {:keys [path] ::keys [conn]}] (if (seq path) (update m :value #(insert! conn (name (first path)) %)) m)) :handle-association (fn [acc k v value] (assoc-in acc [:value (str (name k) "_id")] (:id value)))}] ::conn conn} (hk/ref ::hk/article)))
null
https://raw.githubusercontent.com/lambdaisland/harvest/17e601ee9718ef2c915e469ed62ea963c43db17e/scratch/jdbc.clj
clojure
(ns scratch.jdbc) (ns lambdaisland.harvest.jdbc (:require [clojure.string :as str] [lambdaisland.harvest :as harvest] [lambdaisland.harvest.kernel :as hk]) (:import (java.sql DriverManager Statement))) (defn get-connection [url] (DriverManager/getConnection url)) (defn sql-ident [s] (str "\"" (str/replace s #"\"" "\"\"") "\"")) (defn insert-sql [{:keys [table columns]}] (str "INSERT INTO " (sql-ident table) " (" (str/join "," (map sql-ident columns)) ") " "VALUES " " (" (str/join "," (repeat (count columns) "?")) ") ")) (defn create-table-sql [{:keys [table columns]}] (str "CREATE TABLE " (sql-ident table) " (" (str/join "," (for [[k v] columns] (str (sql-ident k) " " v))) ")")) (defn insert-stmt [conn opts] (.prepareStatement conn (insert-sql opts) Statement/RETURN_GENERATED_KEYS)) (defn insert! [conn table m] (let [columns (keys m) stmt (insert-stmt conn {:table table :columns (map name columns)})] (doseq [[col idx] (map list columns (range))] (.setObject stmt (inc idx) (get m col))) (assert (= 1 (.executeUpdate stmt))) (merge m (first (resultset-seq (.getGeneratedKeys stmt)))))) (defn exec! [conn sql] (.executeUpdate (.createStatement conn) sql)) (defn drop! [conn table] (exec! conn (str "DROP TABLE " (sql-ident table)))) (defn create! ([conn factory] (create! conn factory nil)) ([conn factory rules] (create! conn factory rules nil)) ([conn factory rules opts] (let [{:keys [value] :as res} (hk/build (merge {:registry @harvest/registry :rules rules :hooks [{:map-entry (fn [result query ctx] (if (hk/ref? (val query)) (update result (key query) :id) result)) :map (fn [result query ctx] (if-let [table-name (some-> (:ref ctx) name)] (update result :value #(insert! conn table-name %)) result)) }]} opts) (harvest/refify @harvest/registry factory))] (with-meta value res)))) (comment (def conn (get-connection "jdbc:h2:./example")) (run! #(exec! conn (create-table-sql %)) #_ #(drop! conn (:table %)) [{:table "profile" :columns {"id" "INT AUTO_INCREMENT PRIMARY KEY" "handle" "VARCHAR(255)" "name" "VARCHAR(255)" "website" "VARCHAR(255)"}} {:table "article" :columns {"id" "INT AUTO_INCREMENT PRIMARY KEY" "title" "VARCHAR(255)" "profile_id" "INT"}} ]) (hk/build {:registry hk/registry :hooks [{:finalize-entity (fn [m {:keys [path] ::keys [conn]}] (if (seq path) (update m :value #(insert! conn (name (first path)) %)) m)) :handle-association (fn [acc k v value] (assoc-in acc [:value (str (name k) "_id")] (:id value)))}] ::conn conn} (hk/ref ::hk/article)))
490378d836399395cffd23ec784ce93f66525734f0e2b1e69e9814435e322baf
cmars/sks-keyserver
sksdump.ml
(***********************************************************************) sksdump.ml - takes content of SKS keyserver and creates key dump (* from that *) (* *) Copyright ( C ) 2002 , 2003 , 2004 , 2005 , 2006 , 2007 , 2008 , 2009 , 2010 , 2011 , 2012 , 2013 and Contributors (* *) This file is part of SKS . SKS is free software ; you can (* redistribute it and/or modify it under the terms of the GNU General *) Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . (* *) (* This program is distributed in the hope that it will be useful, but *) (* WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *) (* General Public License for more details. *) (* *) You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA or see < / > . (***********************************************************************) module F(M:sig end) = struct open StdLabels open MoreLabels open Printf open Common open Packet let settings = { Keydb.withtxn = !Settings.transactions; Keydb.cache_bytes = !Settings.cache_bytes; Keydb.pagesize = !Settings.pagesize; Keydb.keyid_pagesize = !Settings.keyid_pagesize; Keydb.meta_pagesize = !Settings.meta_pagesize; Keydb.subkeyid_pagesize = !Settings.subkeyid_pagesize; Keydb.time_pagesize = !Settings.time_pagesize; Keydb.tqueue_pagesize = !Settings.tqueue_pagesize; Keydb.word_pagesize = !Settings.word_pagesize; Keydb.dbdir = Lazy.force Settings.dbdir; Keydb.dumpdir = Lazy.force Settings.dumpdir; } module Keydb = Keydb.Unsafe let should_dump skey = match skey with | Keydb.KeyString _ | Keydb.Key _ -> true | Keydb.Offset _ | Keydb.LargeOffset _ -> if !Settings.dump_new then false else true let rec write_to_file size stream cout = if size <= 0 then () else match SStream.next stream with | None -> () | Some (hash,string) -> let remain = try let skey = Keydb.skey_of_string string in if should_dump skey then let keystring = Keydb.keystring_of_skey skey in output_string cout keystring; size - 1 else size with e -> eplerror 1 e "Failed attempt to extract key %s" (KeyHash.hexify hash); size in write_to_file remain stream cout let write_to_fname size stream fname = printf "Dumping keys to file %s\n" fname; flush stdout; let file = open_out fname in protect ~f:(fun () -> write_to_file size stream file) ~finally:(fun () -> close_out file) let time_to_string time = let tm = Unix.localtime time in sprintf "%04d-%02d-%02d %02d:%02d:%02d" (1900 + tm.Unix.tm_year) (1 + tm.Unix.tm_mon) tm.Unix.tm_mday tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec let dump_database_create_metadata dumpdir name size ctr start_time = let fname = Filename.concat dumpdir (sprintf "metadata-%s.txt" name) in let numkey = Keydb.get_num_keys () in let c = ref 0 in let file = open_out fname in fprintf file "#Metadata-for: %s\n" !Settings.hostname; fprintf file "#Dump-started: %s\n" (time_to_string start_time); fprintf file "#Files-Count: %d\n" ctr; fprintf file "#Key-Count: %d\n" numkey; fprintf file "#Digest-algo: md5\n"; while !c < ctr do fprintf file "%s %s-%04d.pgp\n" (Digest.to_hex( Digest.file (Filename.concat dumpdir (sprintf "%s-%04d.pgp" name !c)))) name !c; incr c done; fprintf file "#Dump-ended: %s\n" (time_to_string (Unix.gettimeofday())); close_out file; () let dump_database dumpdir size name = let (stream,close) = Keydb.create_hash_skey_stream () in let start_time = Unix.gettimeofday() in let () = if not (Sys.file_exists dumpdir) then Unix.mkdir dumpdir 0o700; in let run () = let ctr = ref 0 in while SStream.peek stream <> None do let fname = Filename.concat dumpdir (sprintf "%s-%04d.pgp" name !ctr) in write_to_fname size stream fname; incr ctr done; dump_database_create_metadata dumpdir name size !ctr start_time in protect ~f:run ~finally:close exception Argument_error (***************************************************************) let () = Sys.set_signal Sys.sigusr1 Sys.Signal_ignore let () = Sys.set_signal Sys.sigusr2 Sys.Signal_ignore (***************************************************************) let run () = try ( match !Settings.anonlist with | size::dumpdir::tl -> let name = match tl with | [] -> "sks-dump" | [name] -> name | _ -> raise Argument_error in set_logfile "dump"; perror "Running SKS %s%s" Common.version Common.version_suffix; Keydb.open_dbs settings; let size = int_of_string size in dump_database dumpdir size name | _ -> raise Argument_error ) with Argument_error -> eprintf "wrong number of arguments\n"; eprintf "usage: sks dump numkeys dumpdir [dumpname]\n"; flush stderr; exit (-1) end
null
https://raw.githubusercontent.com/cmars/sks-keyserver/d848c4852cb15585525772b6378670f8724a8f39/sksdump.ml
ocaml
********************************************************************* from that redistribute it and/or modify it under the terms of the GNU General This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ********************************************************************* ************************************************************* *************************************************************
sksdump.ml - takes content of SKS keyserver and creates key dump Copyright ( C ) 2002 , 2003 , 2004 , 2005 , 2006 , 2007 , 2008 , 2009 , 2010 , 2011 , 2012 , 2013 and Contributors This file is part of SKS . SKS is free software ; you can Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA or see < / > . module F(M:sig end) = struct open StdLabels open MoreLabels open Printf open Common open Packet let settings = { Keydb.withtxn = !Settings.transactions; Keydb.cache_bytes = !Settings.cache_bytes; Keydb.pagesize = !Settings.pagesize; Keydb.keyid_pagesize = !Settings.keyid_pagesize; Keydb.meta_pagesize = !Settings.meta_pagesize; Keydb.subkeyid_pagesize = !Settings.subkeyid_pagesize; Keydb.time_pagesize = !Settings.time_pagesize; Keydb.tqueue_pagesize = !Settings.tqueue_pagesize; Keydb.word_pagesize = !Settings.word_pagesize; Keydb.dbdir = Lazy.force Settings.dbdir; Keydb.dumpdir = Lazy.force Settings.dumpdir; } module Keydb = Keydb.Unsafe let should_dump skey = match skey with | Keydb.KeyString _ | Keydb.Key _ -> true | Keydb.Offset _ | Keydb.LargeOffset _ -> if !Settings.dump_new then false else true let rec write_to_file size stream cout = if size <= 0 then () else match SStream.next stream with | None -> () | Some (hash,string) -> let remain = try let skey = Keydb.skey_of_string string in if should_dump skey then let keystring = Keydb.keystring_of_skey skey in output_string cout keystring; size - 1 else size with e -> eplerror 1 e "Failed attempt to extract key %s" (KeyHash.hexify hash); size in write_to_file remain stream cout let write_to_fname size stream fname = printf "Dumping keys to file %s\n" fname; flush stdout; let file = open_out fname in protect ~f:(fun () -> write_to_file size stream file) ~finally:(fun () -> close_out file) let time_to_string time = let tm = Unix.localtime time in sprintf "%04d-%02d-%02d %02d:%02d:%02d" (1900 + tm.Unix.tm_year) (1 + tm.Unix.tm_mon) tm.Unix.tm_mday tm.Unix.tm_hour tm.Unix.tm_min tm.Unix.tm_sec let dump_database_create_metadata dumpdir name size ctr start_time = let fname = Filename.concat dumpdir (sprintf "metadata-%s.txt" name) in let numkey = Keydb.get_num_keys () in let c = ref 0 in let file = open_out fname in fprintf file "#Metadata-for: %s\n" !Settings.hostname; fprintf file "#Dump-started: %s\n" (time_to_string start_time); fprintf file "#Files-Count: %d\n" ctr; fprintf file "#Key-Count: %d\n" numkey; fprintf file "#Digest-algo: md5\n"; while !c < ctr do fprintf file "%s %s-%04d.pgp\n" (Digest.to_hex( Digest.file (Filename.concat dumpdir (sprintf "%s-%04d.pgp" name !c)))) name !c; incr c done; fprintf file "#Dump-ended: %s\n" (time_to_string (Unix.gettimeofday())); close_out file; () let dump_database dumpdir size name = let (stream,close) = Keydb.create_hash_skey_stream () in let start_time = Unix.gettimeofday() in let () = if not (Sys.file_exists dumpdir) then Unix.mkdir dumpdir 0o700; in let run () = let ctr = ref 0 in while SStream.peek stream <> None do let fname = Filename.concat dumpdir (sprintf "%s-%04d.pgp" name !ctr) in write_to_fname size stream fname; incr ctr done; dump_database_create_metadata dumpdir name size !ctr start_time in protect ~f:run ~finally:close exception Argument_error let () = Sys.set_signal Sys.sigusr1 Sys.Signal_ignore let () = Sys.set_signal Sys.sigusr2 Sys.Signal_ignore let run () = try ( match !Settings.anonlist with | size::dumpdir::tl -> let name = match tl with | [] -> "sks-dump" | [name] -> name | _ -> raise Argument_error in set_logfile "dump"; perror "Running SKS %s%s" Common.version Common.version_suffix; Keydb.open_dbs settings; let size = int_of_string size in dump_database dumpdir size name | _ -> raise Argument_error ) with Argument_error -> eprintf "wrong number of arguments\n"; eprintf "usage: sks dump numkeys dumpdir [dumpname]\n"; flush stderr; exit (-1) end
ac3f32552a88d1ba03c12d73de32d82a61b7b07cc8a35cb4c1749be3914af7fc
alavrik/piqi-erlang
piqic_erlang_types.erl
Copyright 2009 , 2010 , 2011 , 2012 , 2013 , 2014 %% 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. generation of -type ... and -record ( ... ) Erlang forms -module(piqic_erlang_types). -compile([export_all, nowarn_export_all]). -include("piqic.hrl"). -define(DEBUG,1). -include("debug.hrl"). gen_piqi(Context) -> Piqi = Context#context.piqi, excluding # piqi_any { } , because its definition will be included from piqi_any_piqi.hrl --- see % piqic_erlang:gen_include_piqi_any_piqi_hrl() for details Typedefs = [X || X <- Piqi#piqi.typedef, not piqic:is_piqi_any_record_typedef(X)], iod("\n\n", [ gen_imports(Context, Piqi#piqi.import), gen_typedefs(Context, Typedefs) ]). generate # piqi_any { } typedef , used only in with --cc when compiling self - spec as a part of the piqi application -- see % piqic_erlang:gen_piqi_any_piqi_hrl() for details gen_piqi_any(Context) -> Piqi = Context#context.piqi, PiqiAnyTypedef = piqic:find_piqi_any_record_typedef(Piqi), true = PiqiAnyTypedef =/= 'undefined', iod("\n\n", [ gen_typedefs(Context, [PiqiAnyTypedef]) ]). gen_imports(Context, Imports) -> generate the list of Erlang includes of .hrl files of imported modules Includes = [gen_import(Context, X) || X <- Imports], iod("\n", Includes). gen_import(Context, Import) -> ImportedIndex = piqic:resolve_import(Context, Import), ImportedPiqi = ImportedIndex#index.piqi, ErlMod = ImportedPiqi#piqi.erlang_module, IncludeLib = piqic:get_option(Context, include_lib), case find_include_lib(IncludeLib, ImportedPiqi#piqi.file) of 'undefined' -> ["-include(\"", ErlMod, ".hrl\")."]; {AppPath, _Path} -> ["-include_lib(\"", AppPath, "/", ErlMod, ".hrl\")."] end. find_include_lib(_IncludeLib, _File = 'undefined') -> backward compatibility : in older versions of piqi the " file " attribute may % not be present 'undefined'; find_include_lib([], _File) -> % not found 'undefined'; find_include_lib([H = {_AppPath, Path} |T], File) -> % was the .piqi module (File) found in Path? case lists:prefix(Path, binary_to_list(File)) of true -> % found H; false -> % not found => keep going through the list find_include_lib(T, File) end. gen_typedefs(Context, Typedefs) -> ErlDefs = [gen_typedef(Context, X) || X <- Typedefs], % generate -type(...) aliases for -record(...) definitions Records = [X || {piqi_record, X} <- Typedefs], ErlRecordTypes = [gen_record_type(Context, X) || X <- Records], iod("\n", ErlDefs ++ ErlRecordTypes). gen_typedef(Context, {Type, X}) -> case Type of piqi_record -> gen_record(Context, X); variant -> gen_variant(Context, X); piqi_list -> gen_list(Context, X); enum -> gen_enum(Context, X); alias -> % skip generation of aliases of built-in types (this matters only % for compiling self-spec); the reason we skip aliases of built-in % types is because we don't want other modules include on % piqi_piqi.hrl; on the other hand, we don't want to built-in type % definitions here, because we don't want to pollute the global % namespace when erlang_type_prefix = "" and with non-empty % erlan_type_prefix, aliases for pritimive types would look ugly case piqic:is_builtin_alias(X) of true -> []; false -> gen_alias(Context, X) end end. gen_alias(Context, X) -> TypeExpr = gen_out_alias_type(Context, X), make_typedef_1(Context, X#alias.erlang_name, TypeExpr). gen_list(Context, X) -> TypeExpr = [ "[", gen_out_type(Context, X#piqi_list.type), "]" ], make_typedef_1(Context, X#piqi_list.erlang_name, TypeExpr). gen_enum(Context, X) -> TypeExpr = gen_options(Context, X#enum.option), make_typedef(Context, X#enum.erlang_name, TypeExpr). gen_variant(Context, X) -> TypeExpr = gen_options(Context, X#variant.option), make_typedef(Context, X#variant.erlang_name, TypeExpr). gen_options(Context, Options) -> ErlOptions = [gen_option(Context, X) || X <- Options], [ "\n ", iod("\n | ", ErlOptions) ]. gen_option(Context, X) -> Name = erlname_of_option(Context, X), case X#option.type of 'undefined' -> Name; TypeName -> {_Piqi, Typedef} = resolve_type_name(Context, TypeName), case Typedef of {Type, _} when X#option.erlang_name =:= 'undefined', (Type =:= variant orelse Type =:= enum) -> % handle variant and enum subtyping cases by omitting the % option label gen_out_type(Context, TypeName); _ -> % general case [ "{", Name, ", ", gen_out_type(Context, TypeName), "}" ] end end. gen_record_type(Context, X) -> Name = X#piqi_record.erlang_name, make_typedef_1(Context, Name, ["#", piqic:scoped_erlname(Context, Name), "{}"]). make_typedef(Context, Name, TypeExpr) -> [ "-type ", piqic:scoped_erlname(Context, Name), "() ::", TypeExpr, ".\n" ]. fit it on one line make_typedef_1(Context, Name, TypeExpr) -> make_typedef(Context, Name, [" ", TypeExpr]). gen_record(Context, X) -> Name = X#piqi_record.erlang_name, ImplicitFields = case piqic:get_option(Context, gen_preserve_unknown_fields) of false -> []; true -> ["piqi_unknown_pb = [] :: [piqirun_parsed_field()]"] end, Fields = [gen_field(Context, F) || F <- X#piqi_record.field] ++ ImplicitFields, FieldsCode = case Fields of [] -> ""; _ -> [ "\n ", iod(",\n ", Fields), "\n" ] end, [ "-record(", piqic:scoped_erlname(Context, Name), ", {", FieldsCode, "}).\n" ]. gen_field(Context, X) -> Name = erlname_of_field(Context, X), % initialize repeated fields with [] & populate default values if they are defined in Piqi Default = gen_field_default(Context, X), [ Name, Default, " :: ", gen_field_type(Context, X#field.mode, X#field.type), case _CanBeUndefined = (X#field.mode =:= optional) of true -> " | 'undefined'"; false -> "" end ]. gen_field_default(Context, X0) -> % TODO: remove eventually -- keeping for backward compatibility with older piqi which expects flags to only be true if present , and never false X = piqic:transform_flag(X0), case X#field.mode of repeated -> " = []"; optional when X#field.default =/= 'undefined' -> Value = gen_field_default(Context, X#field.type, X#field.default, _WireType = 'undefined'), NOTE : we need ' undefined ' here , because otherwise wo n't % treat it as a valid field value [" = ", Value]; _ -> "" end. gen_field_default(Context, TypeName, Default, WireType) -> {ParentPiqi, Typedef} = resolve_type_name(Context, TypeName), case Typedef of {alias, A} -> % handing protobuf_wire_type override by a higher-level alias WireType2 = ?defined(WireType, A#alias.protobuf_wire_type), case A#alias.type of 'undefined' -> % we are dealing with built-in type gen_field_default_builtin_value(Context, A#alias.piqi_type, % must be defined when type is undefined A#alias.erlang_type, WireType2, Default); _ -> case A#alias.erlang_type =/= 'undefined' of custom Erlang type gen_field_default_value(ParentPiqi, Typedef, Default); false -> ParentContext = piqic:switch_context(Context, ParentPiqi), gen_field_default(ParentContext, A#alias.type, Default, WireType2) end end; {enum, E} -> gen_field_default_enum_value(E, Default); _ -> gen_field_default_value(ParentPiqi, Typedef, Default) end. % defaults for non-primitive and custom types are resolved by calling _ piqi : parse_X functions from the module generated by piqic_erlang_in.erl gen_field_default_value(ParentPiqi, Typedef, Default) -> ErlName = typedef_erlname(Typedef), format Erlang binary Value = io_lib:format("~p", [Default#piqi_any.protobuf]), [ParentPiqi#piqi.erlang_module, ":parse_", ErlName, "(", Value, ")"]. gen_field_default_builtin_value(Context, PiqiType, ErlType, WireType, Default) -> % construct the name of the function for parsing values of the built-in type TypeName = piqic_erlang_in:gen_builtin_type_name(Context, PiqiType, ErlType), WireTypeName = piqic:gen_wire_type_name(PiqiType, WireType), ConvertFun = list_to_atom(TypeName ++ "_of_" ++ WireTypeName), obtain Erlang term that corresponds to the default value Term = piqirun:ConvertFun(Default#piqi_any.protobuf), convert the term into Erlang lexical representation io_lib:format("~p", [Term]). gen_field_default_enum_value(Enum, Default) -> Code = piqirun:integer_of_signed_varint(Default#piqi_any.protobuf), % find the option by code Option = lists:keyfind(Code, #option.code, Enum#enum.option), Option#option.erlang_name. gen_field_type(Context, Mode, TypeName) -> case TypeName of 'undefined' -> "boolean()"; % flags are represented as booleans _ -> TypeExpr = gen_out_type(Context, TypeName), case Mode of repeated -> [ "[", TypeExpr, "]" ]; _ -> % required or optional TypeExpr end end. gen_out_type(Context, TypeName) -> T = gen_type(Context, TypeName), output_type(T). gen_out_typedef_type(Context, Typedef) -> T = gen_typedef_type(Context, Typedef), output_type(T). gen_out_alias_type(Context, Alias) -> T = gen_alias_type(Context, Alias), output_type(T). output_type(T) -> % allow more flexible typing for convenience case to_string(T) of "string" -> "string() | binary()"; "float" -> "number()"; S -> S ++ "()" end. gen_type(Context, TypeName) -> {ParentPiqi, Typedef} = resolve_type_name(Context, TypeName), ParentContext = piqic:switch_context(Context, ParentPiqi), gen_typedef_type(ParentContext, Typedef). gen_typedef_type(Context, Typedef) -> case Typedef of {alias, Alias} -> case piqic:is_builtin_alias(Alias) of true -> % we need to recurse, because we don't generate -type % definitions for built-in types (see below) gen_alias_type(Context, Alias); false -> gen_non_builtin_typedef_type(Context, Typedef) end; _ -> % piqi_record | variant | list | enum gen_non_builtin_typedef_type(Context, Typedef) end. gen_non_builtin_typedef_type(Context, Typedef) -> % make scoped name based on the parent module's type prefix Name = typedef_erlname(Typedef), piqic:scoped_erlname(Context, Name). gen_alias_type(Context, Alias) -> case {Alias#alias.erlang_type, Alias#alias.type} of {ErlType, _} when ErlType =/= 'undefined' -> ErlType; {'undefined', 'undefined'} -> this is an alias for a built - in type ( piqi_type field must be % defined when neither of type and erlang_type fields are present) gen_builtin_type(Alias#alias.piqi_type); {'undefined', TypeName} -> gen_type(Context, TypeName) end. gen_builtin_type(PiqiType) -> piqic:gen_builtin_type_name(PiqiType).
null
https://raw.githubusercontent.com/alavrik/piqi-erlang/063ecc4f8fd54543acf01953b0a63b2b7ebf17a9/src/piqic_erlang_types.erl
erlang
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. piqic_erlang:gen_include_piqi_any_piqi_hrl() for details piqic_erlang:gen_piqi_any_piqi_hrl() for details not be present not found was the .piqi module (File) found in Path? found not found => keep going through the list generate -type(...) aliases for -record(...) definitions skip generation of aliases of built-in types (this matters only for compiling self-spec); the reason we skip aliases of built-in types is because we don't want other modules include on piqi_piqi.hrl; on the other hand, we don't want to built-in type definitions here, because we don't want to pollute the global namespace when erlang_type_prefix = "" and with non-empty erlan_type_prefix, aliases for pritimive types would look ugly handle variant and enum subtyping cases by omitting the option label general case initialize repeated fields with [] & populate default values if they are TODO: remove eventually -- keeping for backward compatibility with older treat it as a valid field value handing protobuf_wire_type override by a higher-level alias we are dealing with built-in type must be defined when type is undefined defaults for non-primitive and custom types are resolved by calling construct the name of the function for parsing values of the built-in type find the option by code flags are represented as booleans required or optional allow more flexible typing for convenience we need to recurse, because we don't generate -type definitions for built-in types (see below) piqi_record | variant | list | enum make scoped name based on the parent module's type prefix defined when neither of type and erlang_type fields are present)
Copyright 2009 , 2010 , 2011 , 2012 , 2013 , 2014 Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , generation of -type ... and -record ( ... ) Erlang forms -module(piqic_erlang_types). -compile([export_all, nowarn_export_all]). -include("piqic.hrl"). -define(DEBUG,1). -include("debug.hrl"). gen_piqi(Context) -> Piqi = Context#context.piqi, excluding # piqi_any { } , because its definition will be included from piqi_any_piqi.hrl --- see Typedefs = [X || X <- Piqi#piqi.typedef, not piqic:is_piqi_any_record_typedef(X)], iod("\n\n", [ gen_imports(Context, Piqi#piqi.import), gen_typedefs(Context, Typedefs) ]). generate # piqi_any { } typedef , used only in with --cc when compiling self - spec as a part of the piqi application -- see gen_piqi_any(Context) -> Piqi = Context#context.piqi, PiqiAnyTypedef = piqic:find_piqi_any_record_typedef(Piqi), true = PiqiAnyTypedef =/= 'undefined', iod("\n\n", [ gen_typedefs(Context, [PiqiAnyTypedef]) ]). gen_imports(Context, Imports) -> generate the list of Erlang includes of .hrl files of imported modules Includes = [gen_import(Context, X) || X <- Imports], iod("\n", Includes). gen_import(Context, Import) -> ImportedIndex = piqic:resolve_import(Context, Import), ImportedPiqi = ImportedIndex#index.piqi, ErlMod = ImportedPiqi#piqi.erlang_module, IncludeLib = piqic:get_option(Context, include_lib), case find_include_lib(IncludeLib, ImportedPiqi#piqi.file) of 'undefined' -> ["-include(\"", ErlMod, ".hrl\")."]; {AppPath, _Path} -> ["-include_lib(\"", AppPath, "/", ErlMod, ".hrl\")."] end. find_include_lib(_IncludeLib, _File = 'undefined') -> backward compatibility : in older versions of piqi the " file " attribute may 'undefined'; find_include_lib([], _File) -> 'undefined'; find_include_lib([H = {_AppPath, Path} |T], File) -> case lists:prefix(Path, binary_to_list(File)) of H; find_include_lib(T, File) end. gen_typedefs(Context, Typedefs) -> ErlDefs = [gen_typedef(Context, X) || X <- Typedefs], Records = [X || {piqi_record, X} <- Typedefs], ErlRecordTypes = [gen_record_type(Context, X) || X <- Records], iod("\n", ErlDefs ++ ErlRecordTypes). gen_typedef(Context, {Type, X}) -> case Type of piqi_record -> gen_record(Context, X); variant -> gen_variant(Context, X); piqi_list -> gen_list(Context, X); enum -> gen_enum(Context, X); alias -> case piqic:is_builtin_alias(X) of true -> []; false -> gen_alias(Context, X) end end. gen_alias(Context, X) -> TypeExpr = gen_out_alias_type(Context, X), make_typedef_1(Context, X#alias.erlang_name, TypeExpr). gen_list(Context, X) -> TypeExpr = [ "[", gen_out_type(Context, X#piqi_list.type), "]" ], make_typedef_1(Context, X#piqi_list.erlang_name, TypeExpr). gen_enum(Context, X) -> TypeExpr = gen_options(Context, X#enum.option), make_typedef(Context, X#enum.erlang_name, TypeExpr). gen_variant(Context, X) -> TypeExpr = gen_options(Context, X#variant.option), make_typedef(Context, X#variant.erlang_name, TypeExpr). gen_options(Context, Options) -> ErlOptions = [gen_option(Context, X) || X <- Options], [ "\n ", iod("\n | ", ErlOptions) ]. gen_option(Context, X) -> Name = erlname_of_option(Context, X), case X#option.type of 'undefined' -> Name; TypeName -> {_Piqi, Typedef} = resolve_type_name(Context, TypeName), case Typedef of {Type, _} when X#option.erlang_name =:= 'undefined', (Type =:= variant orelse Type =:= enum) -> gen_out_type(Context, TypeName); _ -> [ "{", Name, ", ", gen_out_type(Context, TypeName), "}" ] end end. gen_record_type(Context, X) -> Name = X#piqi_record.erlang_name, make_typedef_1(Context, Name, ["#", piqic:scoped_erlname(Context, Name), "{}"]). make_typedef(Context, Name, TypeExpr) -> [ "-type ", piqic:scoped_erlname(Context, Name), "() ::", TypeExpr, ".\n" ]. fit it on one line make_typedef_1(Context, Name, TypeExpr) -> make_typedef(Context, Name, [" ", TypeExpr]). gen_record(Context, X) -> Name = X#piqi_record.erlang_name, ImplicitFields = case piqic:get_option(Context, gen_preserve_unknown_fields) of false -> []; true -> ["piqi_unknown_pb = [] :: [piqirun_parsed_field()]"] end, Fields = [gen_field(Context, F) || F <- X#piqi_record.field] ++ ImplicitFields, FieldsCode = case Fields of [] -> ""; _ -> [ "\n ", iod(",\n ", Fields), "\n" ] end, [ "-record(", piqic:scoped_erlname(Context, Name), ", {", FieldsCode, "}).\n" ]. gen_field(Context, X) -> Name = erlname_of_field(Context, X), defined in Piqi Default = gen_field_default(Context, X), [ Name, Default, " :: ", gen_field_type(Context, X#field.mode, X#field.type), case _CanBeUndefined = (X#field.mode =:= optional) of true -> " | 'undefined'"; false -> "" end ]. gen_field_default(Context, X0) -> piqi which expects flags to only be true if present , and never false X = piqic:transform_flag(X0), case X#field.mode of repeated -> " = []"; optional when X#field.default =/= 'undefined' -> Value = gen_field_default(Context, X#field.type, X#field.default, _WireType = 'undefined'), NOTE : we need ' undefined ' here , because otherwise wo n't [" = ", Value]; _ -> "" end. gen_field_default(Context, TypeName, Default, WireType) -> {ParentPiqi, Typedef} = resolve_type_name(Context, TypeName), case Typedef of {alias, A} -> WireType2 = ?defined(WireType, A#alias.protobuf_wire_type), case A#alias.type of gen_field_default_builtin_value(Context, A#alias.erlang_type, WireType2, Default); _ -> case A#alias.erlang_type =/= 'undefined' of custom Erlang type gen_field_default_value(ParentPiqi, Typedef, Default); false -> ParentContext = piqic:switch_context(Context, ParentPiqi), gen_field_default(ParentContext, A#alias.type, Default, WireType2) end end; {enum, E} -> gen_field_default_enum_value(E, Default); _ -> gen_field_default_value(ParentPiqi, Typedef, Default) end. _ piqi : parse_X functions from the module generated by piqic_erlang_in.erl gen_field_default_value(ParentPiqi, Typedef, Default) -> ErlName = typedef_erlname(Typedef), format Erlang binary Value = io_lib:format("~p", [Default#piqi_any.protobuf]), [ParentPiqi#piqi.erlang_module, ":parse_", ErlName, "(", Value, ")"]. gen_field_default_builtin_value(Context, PiqiType, ErlType, WireType, Default) -> TypeName = piqic_erlang_in:gen_builtin_type_name(Context, PiqiType, ErlType), WireTypeName = piqic:gen_wire_type_name(PiqiType, WireType), ConvertFun = list_to_atom(TypeName ++ "_of_" ++ WireTypeName), obtain Erlang term that corresponds to the default value Term = piqirun:ConvertFun(Default#piqi_any.protobuf), convert the term into Erlang lexical representation io_lib:format("~p", [Term]). gen_field_default_enum_value(Enum, Default) -> Code = piqirun:integer_of_signed_varint(Default#piqi_any.protobuf), Option = lists:keyfind(Code, #option.code, Enum#enum.option), Option#option.erlang_name. gen_field_type(Context, Mode, TypeName) -> case TypeName of 'undefined' -> _ -> TypeExpr = gen_out_type(Context, TypeName), case Mode of repeated -> [ "[", TypeExpr, "]" ]; TypeExpr end end. gen_out_type(Context, TypeName) -> T = gen_type(Context, TypeName), output_type(T). gen_out_typedef_type(Context, Typedef) -> T = gen_typedef_type(Context, Typedef), output_type(T). gen_out_alias_type(Context, Alias) -> T = gen_alias_type(Context, Alias), output_type(T). output_type(T) -> case to_string(T) of "string" -> "string() | binary()"; "float" -> "number()"; S -> S ++ "()" end. gen_type(Context, TypeName) -> {ParentPiqi, Typedef} = resolve_type_name(Context, TypeName), ParentContext = piqic:switch_context(Context, ParentPiqi), gen_typedef_type(ParentContext, Typedef). gen_typedef_type(Context, Typedef) -> case Typedef of {alias, Alias} -> case piqic:is_builtin_alias(Alias) of true -> gen_alias_type(Context, Alias); false -> gen_non_builtin_typedef_type(Context, Typedef) end; gen_non_builtin_typedef_type(Context, Typedef) end. gen_non_builtin_typedef_type(Context, Typedef) -> Name = typedef_erlname(Typedef), piqic:scoped_erlname(Context, Name). gen_alias_type(Context, Alias) -> case {Alias#alias.erlang_type, Alias#alias.type} of {ErlType, _} when ErlType =/= 'undefined' -> ErlType; {'undefined', 'undefined'} -> this is an alias for a built - in type ( piqi_type field must be gen_builtin_type(Alias#alias.piqi_type); {'undefined', TypeName} -> gen_type(Context, TypeName) end. gen_builtin_type(PiqiType) -> piqic:gen_builtin_type_name(PiqiType).
2050f25632f6759a5e9aeb04da9fa512363935d025f01d08c126cd59c59dfd7b
stchang/macrotypes
lin2-tests.rkt
#lang s-exp turnstile/examples/linear/lin2 (require rackunit/turnstile) ;; very basic tests ------------------------------------------------- 1 ) unused : err (typecheck-fail (λ ([x : Bool]) #t) #:with-msg "linear vars unused: \\(x\\)") 2 ) used once : ok (check-type (λ ([x : Bool]) x) : (→ Bool Bool)) 3 ) used twice : err (typecheck-fail (λ ([x : Bool]) (pair x x)) #:with-msg "attempting to use linear var twice: x") ;; other examples from atapl ---------------------------------------- (typecheck-fail (λ ([x : Bool]) ((λ ([y : Bool] [z : Bool]) (pair (free z) (free y))) x x)) #:with-msg "attempting to use linear var twice: x") this example fails on the second use of z , ;; but actual example from book demonstrates subtlety of allowing mixed ;; restricted/unrestricted vals: ;; - unrestricted data structures may not contain restricted vals (typecheck-fail (λ ([x : Bool]) (let [z (pair x #f)] (split z as (x1 y1) in (split z as (x2 y2) in (pair (pair x1 x2) (pair y1 y2)))))) #:with-msg "attempting to use linear var twice: z") ;; function should not discard linear var (typecheck-fail (λ ([x : Bool]) ((λ ([f : (→ Bool Bool)]) #t) (λ ([y : Bool]) x))) #:with-msg "linear vars unused: \\(f\\)") ;; use function twice (typecheck-fail (λ ([x : Bool]) ((λ ([f : (→ Bool Bool)]) (pair (f #f) (f #t))) (λ ([y : Bool]) x))) #:with-msg "var: attempting to use linear var twice: f") ;; other general tests ---------------------------------------------- ;; split -------------------- ;; unused (typecheck-fail (split (pair #t #f) as (x y) in x) #:with-msg "linear vars unused: \\(y\\)") (typecheck-fail (split (pair #t #f) as (x y) in y) #:with-msg "linear vars unused: \\(x\\)") (typecheck-fail (split (pair #t #f) as (x y) in #t) #:with-msg "linear vars unused: \\(x y\\)") ;; ok (check-type (split (pair #t #f) as (x y) in (pair y x)) : (× Bool Bool)) shadowing / hygiene , first split unused (typecheck-fail (split (pair #t #t) as (a b) in (λ ([a : Bool] [b : Bool]) (pair a b))) #:with-msg "split: linear vars unused: \\(a b\\)") (typecheck-fail (λ ([a : Bool] [b : Bool]) (split (pair #t #t) as (a b) in (pair a b))) #:with-msg "λ: linear vars unused: \\(a b\\)") ;; TODO: this passes due to let* shadowing but should this fail? (check-type (split (pair #t #t) as (x x) in x) : Bool) ;; used twice (typecheck-fail (split (pair #t #f) as (x y) in (pair x x)) #:with-msg "attempting to use linear var twice: x") (typecheck-fail (split (pair #t #f) as (x y) in (pair y y)) #:with-msg "attempting to use linear var twice: y") ;; nesting (check-type (split (pair #t #t) as (a b) in (split (pair a #t) as (c d) in (split (pair d #t) as (e f) in (split (pair b c) as (g h) in (pair (pair e f) (pair g h)))))) : (× (× Bool Bool) (× Bool Bool))) ;; let -------------------- ;; unused (typecheck-fail (let [x #f] #t) #:with-msg "linear vars unused: \\(x\\)") ;; if -------------------- (typecheck-fail (let [x #f] (if #t x #f)) #:with-msg "if branches must use the same variables, given \\(x\\) and \\(\\)") (typecheck-fail (let [x #f] (if #t #f x)) #:with-msg "if branches must use the same variables, given \\(\\) and \\(x\\)") (check-type (let [x #f] (if #t x x)) : Bool) (typecheck-fail (split (pair #t #t) as (x y) in (if #t x y)) #:with-msg "if branches must use the same variables, given \\(x\\) and \\(y\\)") (typecheck-fail (split (pair #t #t) as (x y) in (if x x y)) #:with-msg "attempting to use linear var twice: x") (check-type (split (pair #t #t) as (x y) in (if #t (pair x y) (pair y x))) : (× Bool Bool)) (check-type (split (pair #t #t) as (x y) in (if x y y)) : Bool) ;; used vars properly reach λ body (typecheck-fail (split (pair #t #t) as (x y) in (pair (pair x y) (λ ([z : Bool]) (pair x z)))) #:with-msg "attempting to use linear var twice: x")
null
https://raw.githubusercontent.com/stchang/macrotypes/05ec31f2e1fe0ddd653211e041e06c6c8071ffa6/turnstile-test/tests/turnstile/linear/lin2-tests.rkt
racket
very basic tests ------------------------------------------------- other examples from atapl ---------------------------------------- but actual example from book demonstrates subtlety of allowing mixed restricted/unrestricted vals: - unrestricted data structures may not contain restricted vals function should not discard linear var use function twice other general tests ---------------------------------------------- split -------------------- unused ok TODO: this passes due to let* shadowing but should this fail? used twice nesting let -------------------- unused if -------------------- used vars properly reach λ body
#lang s-exp turnstile/examples/linear/lin2 (require rackunit/turnstile) 1 ) unused : err (typecheck-fail (λ ([x : Bool]) #t) #:with-msg "linear vars unused: \\(x\\)") 2 ) used once : ok (check-type (λ ([x : Bool]) x) : (→ Bool Bool)) 3 ) used twice : err (typecheck-fail (λ ([x : Bool]) (pair x x)) #:with-msg "attempting to use linear var twice: x") (typecheck-fail (λ ([x : Bool]) ((λ ([y : Bool] [z : Bool]) (pair (free z) (free y))) x x)) #:with-msg "attempting to use linear var twice: x") this example fails on the second use of z , (typecheck-fail (λ ([x : Bool]) (let [z (pair x #f)] (split z as (x1 y1) in (split z as (x2 y2) in (pair (pair x1 x2) (pair y1 y2)))))) #:with-msg "attempting to use linear var twice: z") (typecheck-fail (λ ([x : Bool]) ((λ ([f : (→ Bool Bool)]) #t) (λ ([y : Bool]) x))) #:with-msg "linear vars unused: \\(f\\)") (typecheck-fail (λ ([x : Bool]) ((λ ([f : (→ Bool Bool)]) (pair (f #f) (f #t))) (λ ([y : Bool]) x))) #:with-msg "var: attempting to use linear var twice: f") (typecheck-fail (split (pair #t #f) as (x y) in x) #:with-msg "linear vars unused: \\(y\\)") (typecheck-fail (split (pair #t #f) as (x y) in y) #:with-msg "linear vars unused: \\(x\\)") (typecheck-fail (split (pair #t #f) as (x y) in #t) #:with-msg "linear vars unused: \\(x y\\)") (check-type (split (pair #t #f) as (x y) in (pair y x)) : (× Bool Bool)) shadowing / hygiene , first split unused (typecheck-fail (split (pair #t #t) as (a b) in (λ ([a : Bool] [b : Bool]) (pair a b))) #:with-msg "split: linear vars unused: \\(a b\\)") (typecheck-fail (λ ([a : Bool] [b : Bool]) (split (pair #t #t) as (a b) in (pair a b))) #:with-msg "λ: linear vars unused: \\(a b\\)") (check-type (split (pair #t #t) as (x x) in x) : Bool) (typecheck-fail (split (pair #t #f) as (x y) in (pair x x)) #:with-msg "attempting to use linear var twice: x") (typecheck-fail (split (pair #t #f) as (x y) in (pair y y)) #:with-msg "attempting to use linear var twice: y") (check-type (split (pair #t #t) as (a b) in (split (pair a #t) as (c d) in (split (pair d #t) as (e f) in (split (pair b c) as (g h) in (pair (pair e f) (pair g h)))))) : (× (× Bool Bool) (× Bool Bool))) (typecheck-fail (let [x #f] #t) #:with-msg "linear vars unused: \\(x\\)") (typecheck-fail (let [x #f] (if #t x #f)) #:with-msg "if branches must use the same variables, given \\(x\\) and \\(\\)") (typecheck-fail (let [x #f] (if #t #f x)) #:with-msg "if branches must use the same variables, given \\(\\) and \\(x\\)") (check-type (let [x #f] (if #t x x)) : Bool) (typecheck-fail (split (pair #t #t) as (x y) in (if #t x y)) #:with-msg "if branches must use the same variables, given \\(x\\) and \\(y\\)") (typecheck-fail (split (pair #t #t) as (x y) in (if x x y)) #:with-msg "attempting to use linear var twice: x") (check-type (split (pair #t #t) as (x y) in (if #t (pair x y) (pair y x))) : (× Bool Bool)) (check-type (split (pair #t #t) as (x y) in (if x y y)) : Bool) (typecheck-fail (split (pair #t #t) as (x y) in (pair (pair x y) (λ ([z : Bool]) (pair x z)))) #:with-msg "attempting to use linear var twice: x")
d926e37436aacf84787777f176214278c147320bf228a66cd0fbd9b89dcb7d24
tisnik/clojure-examples
dependencies.clj
{[clojure-complete "0.2.5" :exclusions [[org.clojure/clojure]]] nil, [nrepl "0.7.0" :exclusions [[org.clojure/clojure]]] nil, [org.clojure/clojure "1.10.1"] {[org.clojure/core.specs.alpha "0.2.44"] nil, [org.clojure/spec.alpha "0.2.176"] nil}, [rhizome "0.2.9"] nil, [venantius/ultra "0.6.0"] {[grimradical/clj-semver "0.3.0" :exclusions [[org.clojure/clojure]]] nil, [io.aviso/pretty "0.1.35"] nil, [mvxcvi/puget "1.1.0"] {[fipp "0.6.14"] {[org.clojure/core.rrb-vector "0.0.13"] nil}, [mvxcvi/arrangement "1.1.1"] nil}, [mvxcvi/whidbey "2.1.0"] {[org.clojure/data.codec "0.1.1"] nil}, [org.clojars.brenton/google-diff-match-patch "0.1"] nil, [robert/hooke "1.3.0"] nil, [venantius/glow "0.1.5" :exclusions [[hiccup] [garden]]] {[clj-antlr "0.2.3"] {[org.antlr/antlr4-runtime "4.5.3"] nil, [org.antlr/antlr4 "4.5.3"] nil}, [instaparse "1.4.1"] nil}}}
null
https://raw.githubusercontent.com/tisnik/clojure-examples/33a53a85eb1d381eeb2697d76e6ed2fc06eee6ec/rhizome-1/doc/dependencies.clj
clojure
{[clojure-complete "0.2.5" :exclusions [[org.clojure/clojure]]] nil, [nrepl "0.7.0" :exclusions [[org.clojure/clojure]]] nil, [org.clojure/clojure "1.10.1"] {[org.clojure/core.specs.alpha "0.2.44"] nil, [org.clojure/spec.alpha "0.2.176"] nil}, [rhizome "0.2.9"] nil, [venantius/ultra "0.6.0"] {[grimradical/clj-semver "0.3.0" :exclusions [[org.clojure/clojure]]] nil, [io.aviso/pretty "0.1.35"] nil, [mvxcvi/puget "1.1.0"] {[fipp "0.6.14"] {[org.clojure/core.rrb-vector "0.0.13"] nil}, [mvxcvi/arrangement "1.1.1"] nil}, [mvxcvi/whidbey "2.1.0"] {[org.clojure/data.codec "0.1.1"] nil}, [org.clojars.brenton/google-diff-match-patch "0.1"] nil, [robert/hooke "1.3.0"] nil, [venantius/glow "0.1.5" :exclusions [[hiccup] [garden]]] {[clj-antlr "0.2.3"] {[org.antlr/antlr4-runtime "4.5.3"] nil, [org.antlr/antlr4 "4.5.3"] nil}, [instaparse "1.4.1"] nil}}}
328a7e06f9e107aba069177f181792cf3c4092cc5b072ef930fe8bd30dd40b1d
greggigon/my-personal-kanban-server
core.clj
(ns mpk.core (:gen-class) (:use ring.middleware.params ring.util.response ring.adapter.jetty ring.middleware.session mpk.configuration) (:require [mpk.action-handlers :as handlers :refer :all] [clj-time.core :as t] [clj-time.format :as f])) (def mpk-formatter (f/formatter "yyyy-MM-dd HH:mm:ss")) (def valid-actions {"put" :put "get" :get "key" :key}) (def actions {:get (handlers/->ReadHandler) :put (handlers/->SaveHandler) :key (handlers/->KeyHandler)}) (defn valid-action? [request] (let [{action "action" :as params} (:params request)] (not (or (nil? action) (nil? (get valid-actions action)))))) (defn decorate-response-in-jsonp-callback [params response] (handlers/->Response (:status response) (str (get params "callback") "(" (:body response) ")") (:session response))) (defn mpk-response-to-response [resp] (-> (response (:body resp)) (status (:status resp)) (content-type "application/json") (assoc :session (:session resp)))) (defn check-callback-paramater [params session handler] (if (nil? (get params "callback")) (-> (response "This service responds only to JSONP request. You are missing callback parameter") (status 405)) (perform handler params session))) (defn handle-service-request [request] (let [{action "action" :as params} (:params request) session (:session request)] (if (or (nil? action) (nil? (get valid-actions action))) (-> (response "Invalid method") (status 405)) (let [the-action-handler ((get valid-actions action) actions)] (mpk-response-to-response (decorate-response-in-jsonp-callback params (check-callback-paramater params session the-action-handler))))))) (defn mpk-handler [request] (let [uri (:uri request)] (if (not (.contains (.toLowerCase uri) "/service/kanban")) (do (println (str "[" (f/unparse mpk-formatter (t/now)) "] " request)) (-> (response "Invalid method") (status 405))) (handle-service-request request)))) (def mpk-app (wrap-session (wrap-params mpk-handler))) (defn -main [& args] (do-build-configuration args) (run-jetty mpk-app @configuration))
null
https://raw.githubusercontent.com/greggigon/my-personal-kanban-server/1e6b8f293ca4541d4defff57b492152b4a9f6f0f/src/mpk/core.clj
clojure
(ns mpk.core (:gen-class) (:use ring.middleware.params ring.util.response ring.adapter.jetty ring.middleware.session mpk.configuration) (:require [mpk.action-handlers :as handlers :refer :all] [clj-time.core :as t] [clj-time.format :as f])) (def mpk-formatter (f/formatter "yyyy-MM-dd HH:mm:ss")) (def valid-actions {"put" :put "get" :get "key" :key}) (def actions {:get (handlers/->ReadHandler) :put (handlers/->SaveHandler) :key (handlers/->KeyHandler)}) (defn valid-action? [request] (let [{action "action" :as params} (:params request)] (not (or (nil? action) (nil? (get valid-actions action)))))) (defn decorate-response-in-jsonp-callback [params response] (handlers/->Response (:status response) (str (get params "callback") "(" (:body response) ")") (:session response))) (defn mpk-response-to-response [resp] (-> (response (:body resp)) (status (:status resp)) (content-type "application/json") (assoc :session (:session resp)))) (defn check-callback-paramater [params session handler] (if (nil? (get params "callback")) (-> (response "This service responds only to JSONP request. You are missing callback parameter") (status 405)) (perform handler params session))) (defn handle-service-request [request] (let [{action "action" :as params} (:params request) session (:session request)] (if (or (nil? action) (nil? (get valid-actions action))) (-> (response "Invalid method") (status 405)) (let [the-action-handler ((get valid-actions action) actions)] (mpk-response-to-response (decorate-response-in-jsonp-callback params (check-callback-paramater params session the-action-handler))))))) (defn mpk-handler [request] (let [uri (:uri request)] (if (not (.contains (.toLowerCase uri) "/service/kanban")) (do (println (str "[" (f/unparse mpk-formatter (t/now)) "] " request)) (-> (response "Invalid method") (status 405))) (handle-service-request request)))) (def mpk-app (wrap-session (wrap-params mpk-handler))) (defn -main [& args] (do-build-configuration args) (run-jetty mpk-app @configuration))
ec69088f3637cfafab91e4aa33c307bcda42662aa65b5e01ec7ac7fea68d450c
replikativ/datahike-server
core.clj
(ns datahike-server.core (:gen-class) (:require [mount.core :as mount] [taoensso.timbre :as log] [datahike-server.config :as config] [datahike-server.database] [datahike-server.server])) (defn -main [& args] (mount/start) (log/info "Successfully loaded configuration: " (str config/config)) (log/set-level! (get-in config/config [:server :loglevel])) (log/debugf "Datahike Server Running!"))
null
https://raw.githubusercontent.com/replikativ/datahike-server/ec87469832e017bfaff98e86046de85f8e365817/src/clj/datahike_server/core.clj
clojure
(ns datahike-server.core (:gen-class) (:require [mount.core :as mount] [taoensso.timbre :as log] [datahike-server.config :as config] [datahike-server.database] [datahike-server.server])) (defn -main [& args] (mount/start) (log/info "Successfully loaded configuration: " (str config/config)) (log/set-level! (get-in config/config [:server :loglevel])) (log/debugf "Datahike Server Running!"))
b3ce37ee22b6d581a7f7d0b0bbdbb7337ec7ea64f1499ee675b0729989e30f8a
willijar/LENS
signals.lisp
;; Signals and Listeners Copyright ( C ) 2013 Dr. Author : Dr. < > ;; Keywords: ;;; Copying: ;; This file is part of LENS ;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the ;; License, or (at your option) any later version. ;; LENS is distributed in the hope that it will be useful, but WITHOUT ;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY ;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public ;; License for more details. You should have received a copy of the GNU General Public License ;; along with this program. If not, see </>. ;;; Commentary: ;; ;;; Code: (in-package :lens) (defconstant +SIGNAL-CACHE-SIZE+ 64 "Length of bit vectors for caching signal listeners.") (defvar *signals* (make-array +SIGNAL-CACHE-SIZE+ :element-type 'symbol :fill-pointer 0 :adjustable t) "Array mapping signal index to a the signal symbols.") (defun register-signal(symbol &optional documentation) "*Arguments - symbol :: a =symbol= * Optional Arguments - documentation :: a =string= * Returns - signal-id :: an =integer= * Description Register signal denoted by /symbol/ and optionally recording the /documentation/. If the named signal has not previously been registered it will be allocated a new integer /signal-id/ stored in the =signal-id= property of the symbol and it will be added onto the end of the global [[*signals*]] array. /documentation/ is stored in the =signal-doc= symbol. [[register-signal]] is intended to be called as a top level form. The first [[+signal-cache-size+]] signals registered are cached by [[entity-with-signals]] objects and therefore the signals which are most heavily used should be registered first when loading the simulation code." (if documentation (setf (get symbol 'signal-doc) documentation) (remprop symbol 'signal-doc)) (setf (get symbol 'signal-id) (or (position symbol *signals*) (vector-push-extend symbol *signals*)))) (eval-when(:load-toplevel :execute) (register-signal 'PRE-MODEL-CHANGE "Signal emitted before a change in a simulation model") (register-signal 'POST-MODEL-CHANGE "Signal emitted after a change in a simulation model")) (declaim (inline signal-id)) (defun signal-id(symbol) "Return the integer id of the named signal." (get symbol 'signal-id)) (defgeneric receive-signal(listener signal source value) (:documentation "* Arguments - listener :: an [[entity-with-signals]] instance. - signal :: a signal designator (=symbol= or =integer=) - source :: an [[entity-with-signals]] instance. - value :: signalled value * Description A call of [[emit]] with signal value /signal/ from [entity-with-signals]] object/source/ and value /value/ will result in [[receive-signal]] being called in the /source/ object and all ancestor objects in the simulation heirarchy that have registered to receive this /signal/ using [[subscribe]] All objects which wish to receive signals must specialise this method. ") (:method :around(listener signal source-component value) (declare (ignore signal source-component value)) (let ((*context* listener)) (call-next-method)))) (defclass entity-with-signals(owned-object) ((signal-table :type hash-table :initform (make-hash-table) :reader signal-table :documentation "Hash by signal of lists of registered listeners for this entity.") (has-local-listeners :type simple-bit-vector :initform (make-array +SIGNAL-CACHE-SIZE+ :element-type 'bit :initial-element 0) :documentation "A bit map recording which signals have local listeners.") (has-ancestor-listeners :type simple-bit-vector :documentation "A bit map recording which signals have ancestor listeners.")) (:documentation "An entity which can [[subscribe]] to and [[emit]] and [[receive-signal]] signals.")) (defmethod initialize-instance :after ((instance entity-with-signals) &key &allow-other-keys) (let ((owner (owner instance))) (setf (slot-value instance 'has-ancestor-listeners) (if (typep owner 'entity-with-signals) (bit-ior (slot-value owner 'has-ancestor-listeners) (slot-value owner 'has-local-listeners)) (make-array +SIGNAL-CACHE-SIZE+ :element-type 'bit :initial-element 0))))) (defgeneric listeners(entity signal) (:documentation "* Arguments - entity :: a [[entity-with-signals]] - signal :: a =symbol= or =t= * Description Return list of local listeners to signal denoted by /signal/ for /entity/. If /signal/ is t return all listeners in /entity/.") (:method((entity entity-with-signals) (signal symbol)) (gethash signal (signal-table entity))) (:method((entity entity-with-signals) (signal (eql t))) (let ((listeners nil)) (maphash #'(lambda(k v) (declare (ignore k)) (setf listeners (union listeners v))) (signal-table entity)) listeners))) (defun may-have-listeners(entity signal-id) "* Arguments - entity :: an [[entity-with-signals]] - signal-id :: a positive =integer= or =symbol= signal identifier * Description Return true if /entity/ may have listeners for signal /signal-id/. That is if the corresponding signal has local or ancestor listeners according to the /entity/ cache/ or the signal is outside the cache range. It is intented that this is an efficient check that may be used to eliminate uneccessary calculations of values and calls to [[emit]]." (declare (fixnum signal-id)) (or (>= signal-id +SIGNAL-CACHE-SIZE+) (= 1 (bit (slot-value entity 'has-local-listeners) signal-id)) (= 1 (bit (slot-value entity 'has-ancestor-listeners) signal-id)))) (defun may-have-local-listeners(entity signal-id) "* Arguments - entity :: an [[entity-with-signals]] - signal-id :: a positive =integer= signal identifier * Description Return true if /entity/ may have local listeners for signal /signal-id/. That is if the corresponding signal has local or ancestor listeners according to the /entity/ cache/ or the signal is outside the cache range." (declare (fixnum signal-id)) (or (>= signal-id +SIGNAL-CACHE-SIZE+) (= 1 (bit (slot-value entity 'has-local-listeners) signal-id)))) (defun may-have-ancestor-listeners(entity signal-id) "* Arguments - entity :: an [[entity-with-signals]] - signal-id :: a positive =integer= signal identifier * Description Return true if /entity/ may have ancestor listeners for signal /signal-id/. That is if the corresponding signal has local or ancestor listeners according to the /entity/ cache/ or the signal is outside the cache range." (declare (fixnum signal-id)) (or (>= signal-id +SIGNAL-CACHE-SIZE+) (= 1 (bit (slot-value entity 'has-ancestor-listeners) signal-id)))) ;; this macro will convert a quoted symbol intoi its registered integer. (define-compiler-macro may-have-listeners(&whole form entity arg) (if (and (listp arg) (eql (first arg) 'quote) (symbolp (second arg))) `(may-have-listeners ,entity (load-time-value (symbol-id (second arg)))) form)) (defgeneric emit(entity signal &optional value) (:documentation "* Arguments - entity :: an [[entity-with-signals]] - signal-id :: a signal identifier * Optional Arguments - value :: a value * Description Emit the optional /value/ with a signal. If the given signal has listeners in this component /entity/ or in it's ancestor components, their appropriate [[receive-signal]] methods get called.") (:method((entity entity-with-signals) (signal symbol) &optional value) (let ((signalid (signal-id signal))) (when (may-have-listeners entity signalid) (let ((notification-stack nil)) ensure listener only receives one notification (labels ((fire(source) (when (may-have-local-listeners source signalid) (dolist(listener (gethash signal (slot-value source 'signal-table))) (unless (member listener notification-stack) (push listener notification-stack) (receive-signal listener signal entity value)))) (when (and (may-have-ancestor-listeners source signalid) (parent-module source)) (fire (parent-module source))))) (fire entity))))))) (defgeneric has-listeners(entity signal) (:documentation "* Arguments - entity :: an [[entity-with-signals]] - signal-id :: =symbol= signal identifier * Description Return true if /entity/ has any listeners for signal designated by /signal-id/. For some signals this method has a significant overhead (linear to the number of hierarchy levels in the network). [[may-have-listeners]] may be more appropriate in most cases.") (:method((entity entity-with-signals) (signal symbol)) (let ((signal-id (signal-id signal))) (if (< signal-id +SIGNAL-CACHE-SIZE+) (labels((compute-has-listeners(entity) (when entity (if (gethash signal (slot-value entity 'signal-table)) (return-from has-listeners t) (compute-has-listeners (parent-module entity)))))) (compute-has-listeners entity)) (or (= 1 (bit (slot-value entity 'has-local-listeners) signal-id)) (= 1 (bit (slot-value entity 'has-ancestor-listeners) signal-id))))))) (defgeneric subscribe(entity signal listener) (:documentation "* Arguments - entity :: an [[entity-with-signals]] - signal-id :: =symbol= signal identifier - listener :: an object * Description Adds a listener (callback object) that will be notified using the [[receive signal]] method when the given signal is emitted (see [[emit]] methods). It is an error to subscribe the same listener twice to the same signal. The order in which listeners will be notified is undefined.") (:method((entity entity-with-signals) (signal symbol) listener) (let ((signalid (signal-id signal))) (assert signalid () "~A not a valid signal" signal) (assert (not (member listener (gethash signal (slot-value entity 'signal-table)))) () "Listener ~A already subscribed to ~A" listener signal) (push listener (gethash signal (slot-value entity 'signal-table))) (when (< signalid +SIGNAL-CACHE-SIZE+) (setf (bit (slot-value entity 'has-local-listeners) signalid) 1) (labels ((ancestor-listener-added(ancestor) (for-each-child ancestor #'(lambda(child) (when (typep child 'entity-with-signals) (setf (bit (slot-value child 'has-ancestor-listeners) signalid) 1) (ancestor-listener-added child)))))) (ancestor-listener-added entity)))))) (defgeneric unsubscribe(entity signal listener) (:documentation "* Arguments - entity :: an [[entity-with-signals]] - signal-id :: =symbol= signal identifier - listener :: an object * Description Removes the given /listener/ from the subscription list for signal designated by /signal-id/ in /entity/ . It has no effect if the given listener was not subscribed using [[subscribe]].") (:method ((entity entity-with-signals) (signal symbol) listener) (let ((signalid (signal-id signal))) (assert signalid () "~A not a valid signal" signal) (with-slots(signal-table) entity (setf (gethash signal signal-table) (delete listener (gethash signal signal-table))) (unless (gethash signal signal-table) (remhash signal signal-table)) (when (< signalid +SIGNAL-CACHE-SIZE+) (setf (bit (slot-value entity 'has-local-listeners) signalid) 0) (labels ((ancestor-listener-removed(ancestor) (for-each-child ancestor #'(lambda(child) (setf (bit (slot-value entity 'has-ancestor-listeners) signalid) 0) (unless (gethash signal (slot-value child 'signal-table)) (ancestor-listener-removed child)))))) (ancestor-listener-removed entity))))))) (defgeneric subscribed-p(entity signal listener) (:documentation "* Arguments - entity :: an [[entity-with-signals]] - signal-id :: =symbol= signal identifier - listener :: an object * Description Removes the given /listener/ from the subscription list for signal designated by /signal-id/ in /entity/ . It has no effect if the given listener was not subscribed using [[subscribe]]. Returns true if the given /listener/ is subscribed to the signal designated by /signal-id/ at /entity/ component (i.e. it does not look at listeners subscribed at ancestor components).") (:method((entity entity-with-signals) (signal symbol) listener) (member listener (gethash signal (slot-value entity 'signal-table))))) (defgeneric repair-signal-flags(component) (:documentation "* Arguments - component :: an [[entity-with-signals]] * Description Adjusts has-ancestor-listeners bits in the component's subtree; It must be called when the component's ownership changes.") (:method((component entity-with-signals)) (let ((parent (parent-module component))) (when parent (setf (slot-value component 'has-ancestor-listeners) (map 'bit-vector #'logand (slot-value parent 'has-ancestor-listeners) (slot-value parent 'has-local-listeners))))))) (defmethod finish ((instance entity-with-signals)) ;; finish any listener that is not an entity with signals (map nil #'(lambda(l) (unless (typep l 'entity-with-signals) (finish l))) (listeners instance t)))
null
https://raw.githubusercontent.com/willijar/LENS/646bc4ca5d4add3fa7e0728f14128e96240a9f36/core/signals.lisp
lisp
Signals and Listeners Keywords: Copying: This file is part of LENS This program is free software: you can redistribute it and/or License, or (at your option) any later version. LENS 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 this program. If not, see </>. Commentary: Code: this macro will convert a quoted symbol intoi its registered integer. It finish any listener that is not an entity with signals
Copyright ( C ) 2013 Dr. Author : Dr. < > modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the You should have received a copy of the GNU General Public License (in-package :lens) (defconstant +SIGNAL-CACHE-SIZE+ 64 "Length of bit vectors for caching signal listeners.") (defvar *signals* (make-array +SIGNAL-CACHE-SIZE+ :element-type 'symbol :fill-pointer 0 :adjustable t) "Array mapping signal index to a the signal symbols.") (defun register-signal(symbol &optional documentation) "*Arguments - symbol :: a =symbol= * Optional Arguments - documentation :: a =string= * Returns - signal-id :: an =integer= * Description Register signal denoted by /symbol/ and optionally recording the /documentation/. If the named signal has not previously been registered it will be allocated a new integer /signal-id/ stored in the =signal-id= property of the symbol and it will be added onto the end of the global [[*signals*]] array. /documentation/ is stored in the =signal-doc= symbol. [[register-signal]] is intended to be called as a top level form. The first [[+signal-cache-size+]] signals registered are cached by [[entity-with-signals]] objects and therefore the signals which are most heavily used should be registered first when loading the simulation code." (if documentation (setf (get symbol 'signal-doc) documentation) (remprop symbol 'signal-doc)) (setf (get symbol 'signal-id) (or (position symbol *signals*) (vector-push-extend symbol *signals*)))) (eval-when(:load-toplevel :execute) (register-signal 'PRE-MODEL-CHANGE "Signal emitted before a change in a simulation model") (register-signal 'POST-MODEL-CHANGE "Signal emitted after a change in a simulation model")) (declaim (inline signal-id)) (defun signal-id(symbol) "Return the integer id of the named signal." (get symbol 'signal-id)) (defgeneric receive-signal(listener signal source value) (:documentation "* Arguments - listener :: an [[entity-with-signals]] instance. - signal :: a signal designator (=symbol= or =integer=) - source :: an [[entity-with-signals]] instance. - value :: signalled value * Description A call of [[emit]] with signal value /signal/ from [entity-with-signals]] object/source/ and value /value/ will result in [[receive-signal]] being called in the /source/ object and all ancestor objects in the simulation heirarchy that have registered to receive this /signal/ using [[subscribe]] All objects which wish to receive signals must specialise this method. ") (:method :around(listener signal source-component value) (declare (ignore signal source-component value)) (let ((*context* listener)) (call-next-method)))) (defclass entity-with-signals(owned-object) ((signal-table :type hash-table :initform (make-hash-table) :reader signal-table :documentation "Hash by signal of lists of registered listeners for this entity.") (has-local-listeners :type simple-bit-vector :initform (make-array +SIGNAL-CACHE-SIZE+ :element-type 'bit :initial-element 0) :documentation "A bit map recording which signals have local listeners.") (has-ancestor-listeners :type simple-bit-vector :documentation "A bit map recording which signals have ancestor listeners.")) (:documentation "An entity which can [[subscribe]] to and [[emit]] and [[receive-signal]] signals.")) (defmethod initialize-instance :after ((instance entity-with-signals) &key &allow-other-keys) (let ((owner (owner instance))) (setf (slot-value instance 'has-ancestor-listeners) (if (typep owner 'entity-with-signals) (bit-ior (slot-value owner 'has-ancestor-listeners) (slot-value owner 'has-local-listeners)) (make-array +SIGNAL-CACHE-SIZE+ :element-type 'bit :initial-element 0))))) (defgeneric listeners(entity signal) (:documentation "* Arguments - entity :: a [[entity-with-signals]] - signal :: a =symbol= or =t= * Description Return list of local listeners to signal denoted by /signal/ for /entity/. If /signal/ is t return all listeners in /entity/.") (:method((entity entity-with-signals) (signal symbol)) (gethash signal (signal-table entity))) (:method((entity entity-with-signals) (signal (eql t))) (let ((listeners nil)) (maphash #'(lambda(k v) (declare (ignore k)) (setf listeners (union listeners v))) (signal-table entity)) listeners))) (defun may-have-listeners(entity signal-id) "* Arguments - entity :: an [[entity-with-signals]] - signal-id :: a positive =integer= or =symbol= signal identifier * Description Return true if /entity/ may have listeners for signal /signal-id/. That is if the corresponding signal has local or ancestor listeners according to the /entity/ cache/ or the signal is outside the cache range. It is intented that this is an efficient check that may be used to eliminate uneccessary calculations of values and calls to [[emit]]." (declare (fixnum signal-id)) (or (>= signal-id +SIGNAL-CACHE-SIZE+) (= 1 (bit (slot-value entity 'has-local-listeners) signal-id)) (= 1 (bit (slot-value entity 'has-ancestor-listeners) signal-id)))) (defun may-have-local-listeners(entity signal-id) "* Arguments - entity :: an [[entity-with-signals]] - signal-id :: a positive =integer= signal identifier * Description Return true if /entity/ may have local listeners for signal /signal-id/. That is if the corresponding signal has local or ancestor listeners according to the /entity/ cache/ or the signal is outside the cache range." (declare (fixnum signal-id)) (or (>= signal-id +SIGNAL-CACHE-SIZE+) (= 1 (bit (slot-value entity 'has-local-listeners) signal-id)))) (defun may-have-ancestor-listeners(entity signal-id) "* Arguments - entity :: an [[entity-with-signals]] - signal-id :: a positive =integer= signal identifier * Description Return true if /entity/ may have ancestor listeners for signal /signal-id/. That is if the corresponding signal has local or ancestor listeners according to the /entity/ cache/ or the signal is outside the cache range." (declare (fixnum signal-id)) (or (>= signal-id +SIGNAL-CACHE-SIZE+) (= 1 (bit (slot-value entity 'has-ancestor-listeners) signal-id)))) (define-compiler-macro may-have-listeners(&whole form entity arg) (if (and (listp arg) (eql (first arg) 'quote) (symbolp (second arg))) `(may-have-listeners ,entity (load-time-value (symbol-id (second arg)))) form)) (defgeneric emit(entity signal &optional value) (:documentation "* Arguments - entity :: an [[entity-with-signals]] - signal-id :: a signal identifier * Optional Arguments - value :: a value * Description Emit the optional /value/ with a signal. If the given signal has listeners in this component /entity/ or in it's ancestor components, their appropriate [[receive-signal]] methods get called.") (:method((entity entity-with-signals) (signal symbol) &optional value) (let ((signalid (signal-id signal))) (when (may-have-listeners entity signalid) (let ((notification-stack nil)) ensure listener only receives one notification (labels ((fire(source) (when (may-have-local-listeners source signalid) (dolist(listener (gethash signal (slot-value source 'signal-table))) (unless (member listener notification-stack) (push listener notification-stack) (receive-signal listener signal entity value)))) (when (and (may-have-ancestor-listeners source signalid) (parent-module source)) (fire (parent-module source))))) (fire entity))))))) (defgeneric has-listeners(entity signal) (:documentation "* Arguments - entity :: an [[entity-with-signals]] - signal-id :: =symbol= signal identifier * Description Return true if /entity/ has any listeners for signal designated by /signal-id/. For some signals this method has a significant overhead (linear to the number of hierarchy levels in the network). [[may-have-listeners]] may be more appropriate in most cases.") (:method((entity entity-with-signals) (signal symbol)) (let ((signal-id (signal-id signal))) (if (< signal-id +SIGNAL-CACHE-SIZE+) (labels((compute-has-listeners(entity) (when entity (if (gethash signal (slot-value entity 'signal-table)) (return-from has-listeners t) (compute-has-listeners (parent-module entity)))))) (compute-has-listeners entity)) (or (= 1 (bit (slot-value entity 'has-local-listeners) signal-id)) (= 1 (bit (slot-value entity 'has-ancestor-listeners) signal-id))))))) (defgeneric subscribe(entity signal listener) (:documentation "* Arguments - entity :: an [[entity-with-signals]] - signal-id :: =symbol= signal identifier - listener :: an object * Description Adds a listener (callback object) that will be notified using the [[receive signal]] method when the given signal is emitted (see [[emit]] methods). It is an error to subscribe the same listener twice to the same signal. The order in which listeners will be notified is undefined.") (:method((entity entity-with-signals) (signal symbol) listener) (let ((signalid (signal-id signal))) (assert signalid () "~A not a valid signal" signal) (assert (not (member listener (gethash signal (slot-value entity 'signal-table)))) () "Listener ~A already subscribed to ~A" listener signal) (push listener (gethash signal (slot-value entity 'signal-table))) (when (< signalid +SIGNAL-CACHE-SIZE+) (setf (bit (slot-value entity 'has-local-listeners) signalid) 1) (labels ((ancestor-listener-added(ancestor) (for-each-child ancestor #'(lambda(child) (when (typep child 'entity-with-signals) (setf (bit (slot-value child 'has-ancestor-listeners) signalid) 1) (ancestor-listener-added child)))))) (ancestor-listener-added entity)))))) (defgeneric unsubscribe(entity signal listener) (:documentation "* Arguments - entity :: an [[entity-with-signals]] - signal-id :: =symbol= signal identifier - listener :: an object * Description Removes the given /listener/ from the subscription list for signal designated by /signal-id/ in /entity/ . It has no effect if the given listener was not subscribed using [[subscribe]].") (:method ((entity entity-with-signals) (signal symbol) listener) (let ((signalid (signal-id signal))) (assert signalid () "~A not a valid signal" signal) (with-slots(signal-table) entity (setf (gethash signal signal-table) (delete listener (gethash signal signal-table))) (unless (gethash signal signal-table) (remhash signal signal-table)) (when (< signalid +SIGNAL-CACHE-SIZE+) (setf (bit (slot-value entity 'has-local-listeners) signalid) 0) (labels ((ancestor-listener-removed(ancestor) (for-each-child ancestor #'(lambda(child) (setf (bit (slot-value entity 'has-ancestor-listeners) signalid) 0) (unless (gethash signal (slot-value child 'signal-table)) (ancestor-listener-removed child)))))) (ancestor-listener-removed entity))))))) (defgeneric subscribed-p(entity signal listener) (:documentation "* Arguments - entity :: an [[entity-with-signals]] - signal-id :: =symbol= signal identifier - listener :: an object * Description Removes the given /listener/ from the subscription list for signal designated by /signal-id/ in /entity/ . It has no effect if the given listener was not subscribed using [[subscribe]]. Returns true if the given /listener/ is subscribed to the signal designated by /signal-id/ at /entity/ component (i.e. it does not look at listeners subscribed at ancestor components).") (:method((entity entity-with-signals) (signal symbol) listener) (member listener (gethash signal (slot-value entity 'signal-table))))) (defgeneric repair-signal-flags(component) (:documentation "* Arguments - component :: an [[entity-with-signals]] * Description must be called when the component's ownership changes.") (:method((component entity-with-signals)) (let ((parent (parent-module component))) (when parent (setf (slot-value component 'has-ancestor-listeners) (map 'bit-vector #'logand (slot-value parent 'has-ancestor-listeners) (slot-value parent 'has-local-listeners))))))) (defmethod finish ((instance entity-with-signals)) (map nil #'(lambda(l) (unless (typep l 'entity-with-signals) (finish l))) (listeners instance t)))
6195abaeaa87adc38cdea12599b881e896fb37d66d8d0295ebc80f7ad77fd230
ninenines/cowboy
cowboy_sup.erl
Copyright ( c ) 2011 - 2017 , < > %% %% 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(cowboy_sup). -behaviour(supervisor). -export([start_link/0]). -export([init/1]). -spec start_link() -> {ok, pid()}. start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). -spec init([]) -> {ok, {{supervisor:strategy(), 10, 10}, [supervisor:child_spec()]}}. init([]) -> Procs = [{cowboy_clock, {cowboy_clock, start_link, []}, permanent, 5000, worker, [cowboy_clock]}], {ok, {{one_for_one, 10, 10}, Procs}}.
null
https://raw.githubusercontent.com/ninenines/cowboy/8795233c57f1f472781a22ffbf186ce38cc5b049/src/cowboy_sup.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.
Copyright ( c ) 2011 - 2017 , < > 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(cowboy_sup). -behaviour(supervisor). -export([start_link/0]). -export([init/1]). -spec start_link() -> {ok, pid()}. start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). -spec init([]) -> {ok, {{supervisor:strategy(), 10, 10}, [supervisor:child_spec()]}}. init([]) -> Procs = [{cowboy_clock, {cowboy_clock, start_link, []}, permanent, 5000, worker, [cowboy_clock]}], {ok, {{one_for_one, 10, 10}, Procs}}.
489ce43ed8942214f84f6a609853b5d1172446d7bf89f6256a6c8414d5e306cd
racket/macro-debugger
debug.rkt
#lang racket/base (require racket/pretty racket/class racket/class/iop "interfaces.rkt" macro-debugger/view/debug-format "view.rkt") (provide debug-file) (define (make-stepper) (define director (new macro-stepper-director%)) (send director new-stepper)) (define (debug-file file) (let-values ([(events msg ctx) (load-debug-file file)]) (pretty-print msg) (pretty-print ctx) (let* ([w (make-stepper)]) (send/i w widget<%> add-trace events) w)))
null
https://raw.githubusercontent.com/racket/macro-debugger/d4e2325e6d8eced81badf315048ff54f515110d5/macro-debugger/macro-debugger/view/debug.rkt
racket
#lang racket/base (require racket/pretty racket/class racket/class/iop "interfaces.rkt" macro-debugger/view/debug-format "view.rkt") (provide debug-file) (define (make-stepper) (define director (new macro-stepper-director%)) (send director new-stepper)) (define (debug-file file) (let-values ([(events msg ctx) (load-debug-file file)]) (pretty-print msg) (pretty-print ctx) (let* ([w (make-stepper)]) (send/i w widget<%> add-trace events) w)))
d9e7da07e1bb7526bdde27fe71af3639ba0e7c1d9ffa403c05bd404a29948397
slegrand45/mysql_protocol
bench_config.ml
let host = " 192.168.1.20 " let addr = Unix.inet_addr_of_string host let port = 3306 let addr = Unix.inet_addr_of_string host let port = 3306 *) let sockaddr = "/usr/jails/mariadb/var/run/mysql/mysql.sock" let db_user = "user_ocaml_ocmp" let db_password = "ocmp" let db_name = "test_ocaml_ocmp_utf8"
null
https://raw.githubusercontent.com/slegrand45/mysql_protocol/92905707c72b49bb0c22467e6cf1d862336c3e48/benchmarks/bench_config.ml
ocaml
let host = " 192.168.1.20 " let addr = Unix.inet_addr_of_string host let port = 3306 let addr = Unix.inet_addr_of_string host let port = 3306 *) let sockaddr = "/usr/jails/mariadb/var/run/mysql/mysql.sock" let db_user = "user_ocaml_ocmp" let db_password = "ocmp" let db_name = "test_ocaml_ocmp_utf8"
1041f9f7234a2d466807f6c000d8887469c4ab72262ec6fca29f59db040509c3
tmfg/mmtis-national-access-point
project.clj
(defproject napote-dashboard "0.1-SNAPSHOT" :dependencies [[org.clojure/clojure "1.9.0"] [org.clojure/clojurescript "1.9.946"] [http-kit "2.2.0"] [compojure "1.6.0"] [cheshire "5.8.0"] [amazonica "0.3.118"] [reagent "0.8.0-alpha2"] [figwheel "0.5.13"] [webjure/tuck "0.4.3"] [cljs-ajax "0.7.2" :exclusions [org.apache.httpcomponents/httpasyncclient]] [com.cognitect/transit-clj "0.8.300"] [com.cognitect/transit-cljs "0.8.243"] [com.atlassian.commonmark/commonmark "0.11.0"]] :profiles {:dev {:dependencies [[figwheel-sidecar "0.5.13"] [com.cemerick/piggieback "0.2.2"] [org.clojure/tools.nrepl "0.2.12"]]}} :plugins [[lein-cljsbuild "1.1.7"] [lein-figwheel "0.5.13"]] :source-paths ["src/clj"] :cljsbuild {:builds [{:id "dev" :source-paths ["src/cljs"] :figwheel {:on-jsload "dashboard.main/reload-hook"} :compiler {:optimizations :none :source-map true :output-to "resources/public/js/dashboard.js" :output-dir "resources/public/js/out"}} {:id "prod" :source-paths ["src/cljs"] :compiler {:optimizations :advanced :output-to "resources/public/js/dashboard.js"}}]} :clean-targets ^{:protect false} ["resources/public/js/dashboard.js" "resources/public/js" "target/classes"] :repl-options {:init-ns dashboard.main :init (dashboard.main/start)})
null
https://raw.githubusercontent.com/tmfg/mmtis-national-access-point/a86cc890ffa1fe4f773083be5d2556e87a93d975/tools/dashboard/project.clj
clojure
(defproject napote-dashboard "0.1-SNAPSHOT" :dependencies [[org.clojure/clojure "1.9.0"] [org.clojure/clojurescript "1.9.946"] [http-kit "2.2.0"] [compojure "1.6.0"] [cheshire "5.8.0"] [amazonica "0.3.118"] [reagent "0.8.0-alpha2"] [figwheel "0.5.13"] [webjure/tuck "0.4.3"] [cljs-ajax "0.7.2" :exclusions [org.apache.httpcomponents/httpasyncclient]] [com.cognitect/transit-clj "0.8.300"] [com.cognitect/transit-cljs "0.8.243"] [com.atlassian.commonmark/commonmark "0.11.0"]] :profiles {:dev {:dependencies [[figwheel-sidecar "0.5.13"] [com.cemerick/piggieback "0.2.2"] [org.clojure/tools.nrepl "0.2.12"]]}} :plugins [[lein-cljsbuild "1.1.7"] [lein-figwheel "0.5.13"]] :source-paths ["src/clj"] :cljsbuild {:builds [{:id "dev" :source-paths ["src/cljs"] :figwheel {:on-jsload "dashboard.main/reload-hook"} :compiler {:optimizations :none :source-map true :output-to "resources/public/js/dashboard.js" :output-dir "resources/public/js/out"}} {:id "prod" :source-paths ["src/cljs"] :compiler {:optimizations :advanced :output-to "resources/public/js/dashboard.js"}}]} :clean-targets ^{:protect false} ["resources/public/js/dashboard.js" "resources/public/js" "target/classes"] :repl-options {:init-ns dashboard.main :init (dashboard.main/start)})
ac45107a47ea068b33d07f90b68b808ad4aa22f13f78021a339eec84315dbd0e
fmi-lab/fp-elective-2017
sum-divisors.scm
(require rackunit rackunit/text-ui) (define (sum-divisors n) (define (helper counter result) (if (= counter 0) result (helper (- counter 1) (if (= (remainder n counter) 0) (+ result counter) result)))) (helper n 0)) (define sum-divisors-tests (test-suite "Tests for sum-divisors" 1 3 (check = (sum-divisors 12) 28) ; 1 2 3 4 6 12 (check = (sum-divisors 15) 24) ; 1 3 5 15 1 19 (check = (sum-divisors 42) 96) ; 1 2 3 6 7 14 21 42 1 661 1 2 3 6 9 18 37 74 111 222 333 666 1 7 191 1337 (check = (sum-divisors 65515) 78624) ; 1 5 13103 65515 1 127 9721 1234567 (run-tests sum-divisors-tests)
null
https://raw.githubusercontent.com/fmi-lab/fp-elective-2017/e88d5c0319b6d03c0ecd8a12a2856fb1bf5dcbf3/exercises/02/sum-divisors.scm
scheme
1 2 3 4 6 12 1 3 5 15 1 2 3 6 7 14 21 42 1 5 13103 65515
(require rackunit rackunit/text-ui) (define (sum-divisors n) (define (helper counter result) (if (= counter 0) result (helper (- counter 1) (if (= (remainder n counter) 0) (+ result counter) result)))) (helper n 0)) (define sum-divisors-tests (test-suite "Tests for sum-divisors" 1 3 1 19 1 661 1 2 3 6 9 18 37 74 111 222 333 666 1 7 191 1337 1 127 9721 1234567 (run-tests sum-divisors-tests)
b918b961900ed8a54ef10abe60f90d1cd72445baf1ca82636a6b8d7661818fe1
codingteam/Hyperspace
network.clj
(ns hyperspace.test.client.network (:import [java.io BufferedReader InputStreamReader PrintWriter]) (:use [clojure.test] [hyperspace.client.network]) (:require [clojure.contrib.server-socket :as socket] [clojure.data.json :as json] [clojure.java.io :as io])) (deftest network-test (def fake-server-port 10501) (def fake-server (socket/create-server fake-server-port (fn [in out] (binding [*in* (BufferedReader. (InputStreamReader. in)) *out* (PrintWriter. out)] (loop [] (println (read-line)) (recur)))))) (let [connection (connect "localhost" fake-server-port)] (testing "connect function" (is (:socket connection)) (is (:in connection)) (is (:out connection)) (is (not (.isClosed (:socket connection))))) (disconnect connection)) (let [connection (connect "localhost" fake-server-port)] (disconnect connection) (testing "disconnect function" (is (.isClosed (:socket connection))))) (socket/close-server fake-server) (def answer (promise)) (def mock-server-port 10502) (def mock-server (socket/create-server mock-server-port (fn [in out] (let [reader (io/reader in) writer (io/writer out)] (loop [] (let [message (json/read reader :key-fn keyword)] (deliver answer message)) (recur)))))) (let [connection (connect "localhost" mock-server-port) object {:test 1, :field "2"}] (send-message connection object) (testing "send-message function" (is (= (deref answer 15000 nil) object))) (println "finished1") (disconnect connection) (println "finished22")) (socket/close-server mock-server) (println "finished23") (def echo-server-port 10503) (def echo-server (socket/create-server echo-server-port (fn [in out] (let [reader (io/reader in) writer (io/writer out)] (loop [] (let [c (.read reader)] (if (not= c -1) (do (println "r" (char c)) (.write writer c) (.flush writer) (recur))))))))) (let [connection (connect "localhost" echo-server-port) message {:a 1, :b 2}] (println "finished11") (send-message connection message) (println "finished14") (testing "receive-message function" (is (= (receive-message connection) {:a 1, :b 2}))) (println "finished12") (disconnect connection)) (println "finished13") (socket/close-server echo-server))
null
https://raw.githubusercontent.com/codingteam/Hyperspace/b04ec588968f3a9c94b2992010a3a737afbe7eb5/client/src/test/clojure/hyperspace/test/client/network.clj
clojure
(ns hyperspace.test.client.network (:import [java.io BufferedReader InputStreamReader PrintWriter]) (:use [clojure.test] [hyperspace.client.network]) (:require [clojure.contrib.server-socket :as socket] [clojure.data.json :as json] [clojure.java.io :as io])) (deftest network-test (def fake-server-port 10501) (def fake-server (socket/create-server fake-server-port (fn [in out] (binding [*in* (BufferedReader. (InputStreamReader. in)) *out* (PrintWriter. out)] (loop [] (println (read-line)) (recur)))))) (let [connection (connect "localhost" fake-server-port)] (testing "connect function" (is (:socket connection)) (is (:in connection)) (is (:out connection)) (is (not (.isClosed (:socket connection))))) (disconnect connection)) (let [connection (connect "localhost" fake-server-port)] (disconnect connection) (testing "disconnect function" (is (.isClosed (:socket connection))))) (socket/close-server fake-server) (def answer (promise)) (def mock-server-port 10502) (def mock-server (socket/create-server mock-server-port (fn [in out] (let [reader (io/reader in) writer (io/writer out)] (loop [] (let [message (json/read reader :key-fn keyword)] (deliver answer message)) (recur)))))) (let [connection (connect "localhost" mock-server-port) object {:test 1, :field "2"}] (send-message connection object) (testing "send-message function" (is (= (deref answer 15000 nil) object))) (println "finished1") (disconnect connection) (println "finished22")) (socket/close-server mock-server) (println "finished23") (def echo-server-port 10503) (def echo-server (socket/create-server echo-server-port (fn [in out] (let [reader (io/reader in) writer (io/writer out)] (loop [] (let [c (.read reader)] (if (not= c -1) (do (println "r" (char c)) (.write writer c) (.flush writer) (recur))))))))) (let [connection (connect "localhost" echo-server-port) message {:a 1, :b 2}] (println "finished11") (send-message connection message) (println "finished14") (testing "receive-message function" (is (= (receive-message connection) {:a 1, :b 2}))) (println "finished12") (disconnect connection)) (println "finished13") (socket/close-server echo-server))
d44c770113ee88cc997ff74cafd7d9b50ca3f7ae9d21f9200a7dcb24d0015ee9
fragnix/fragnix
Network.Wai.Middleware.Gzip.hs
{-# LANGUAGE Haskell2010, OverloadedStrings #-} # LINE 1 " Network / Wai / Middleware / Gzip.hs " # {-# LANGUAGE Rank2Types, ScopedTypeVariables #-} --------------------------------------------------------- -- | Module : Network . Wai . Middleware . Copyright : -- License : BSD3 -- Maintainer : < > -- Stability : Unstable -- Portability : portable -- -- Automatic gzip compression of responses. -- --------------------------------------------------------- module Network.Wai.Middleware.Gzip ( gzip , GzipSettings , gzipFiles , GzipFiles (..) , gzipCheckMime , def , defaultCheckMime ) where import Network.Wai import Data.Maybe (fromMaybe, isJust) import qualified Data.ByteString.Char8 as S8 import qualified Data.ByteString as S import Data.Default.Class import Network.HTTP.Types ( Status, Header, hContentEncoding, hUserAgent , hContentType, hContentLength) import System.Directory (doesFileExist, createDirectoryIfMissing) import Blaze.ByteString.Builder (fromByteString) import Control.Exception (try, SomeException) import qualified Data.Set as Set import Network.Wai.Header import Network.Wai.Internal import qualified Data.Streaming.Blaze as B import qualified Data.Streaming.Zlib as Z import qualified Blaze.ByteString.Builder as Blaze import Control.Monad (unless) import Data.Function (fix) import Control.Exception (throwIO) import qualified System.IO as IO import Data.ByteString.Lazy.Internal (defaultChunkSize) import Data.Word8 (_semicolon) data GzipSettings = GzipSettings { gzipFiles :: GzipFiles , gzipCheckMime :: S.ByteString -> Bool } -- | Gzip behavior for files. data GzipFiles = GzipIgnore -- ^ Do not compress file responses. | GzipCompress -- ^ Compress files. Note that this may counteract zero - copy response optimizations on some -- platforms. | GzipCacheFolder FilePath -- ^ Compress files, caching them in -- some directory. ^ If we use compression then try to use the filename with " " -- appended to it, if the file is missing then try next action -- -- @since 3.0.17 deriving (Show, Eq, Read) | Use default MIME settings ; /do not/ compress files . instance Default GzipSettings where def = GzipSettings GzipIgnore defaultCheckMime -- | MIME types that will be compressed by default: @text/*@ , @application / json@ , @application / javascript@ , @application / ecmascript@ , @image / x - icon@. defaultCheckMime :: S.ByteString -> Bool defaultCheckMime bs = S8.isPrefixOf "text/" bs || bs' `Set.member` toCompress where bs' = fst $ S.break (== _semicolon) bs toCompress = Set.fromList [ "application/json" , "application/javascript" , "application/ecmascript" , "image/x-icon" ] -- | Use gzip to compress the body of the response. -- -- Analyzes the \"Accept-Encoding\" header from the client to determine if is supported . -- -- File responses will be compressed according to the 'GzipFiles' setting. gzip :: GzipSettings -> Middleware gzip set app env sendResponse = app env $ \res -> case res of ResponseRaw{} -> sendResponse res ResponseFile{} | gzipFiles set == GzipIgnore -> sendResponse res _ -> if "gzip" `elem` enc && not isMSIE6 && not (isEncoded res) && (bigEnough res) then let runAction x = case x of (ResponseFile s hs file Nothing, GzipPreCompressed nextAction) -> let compressedVersion = file ++ ".gz" in doesFileExist compressedVersion >>= \x -> if x then (sendResponse $ ResponseFile s (fixHeaders hs) compressedVersion Nothing) else (runAction (ResponseFile s hs file Nothing, nextAction)) (ResponseFile s hs file Nothing, GzipCacheFolder cache) -> case lookup hContentType hs of Just m | gzipCheckMime set m -> compressFile s hs file cache sendResponse _ -> sendResponse res (ResponseFile {}, GzipIgnore) -> sendResponse res _ -> compressE set res sendResponse in runAction (res, gzipFiles set) else sendResponse res where enc = fromMaybe [] $ (splitCommas . S8.unpack) `fmap` lookup "Accept-Encoding" (requestHeaders env) ua = fromMaybe "" $ lookup hUserAgent $ requestHeaders env isMSIE6 = "MSIE 6" `S.isInfixOf` ua isEncoded res = isJust $ lookup hContentEncoding $ responseHeaders res bigEnough rsp = case contentLength (responseHeaders rsp) of Nothing -> True -- This could be a streaming case Just len -> len >= minimumLength -- For a small enough response, gzipping will actually increase the size -- Potentially for anything less than 860 bytes gzipping could be a net loss -- The actual number is application specific though and may need to be adjusted -- -is-recommended-minimum-object-size-for-gzip-performance-benefits minimumLength = 860 compressFile :: Status -> [Header] -> FilePath -> FilePath -> (Response -> IO a) -> IO a compressFile s hs file cache sendResponse = do e <- doesFileExist tmpfile if e then onSucc else do createDirectoryIfMissing True cache x <- try $ IO.withBinaryFile file IO.ReadMode $ \inH -> IO.withBinaryFile tmpfile IO.WriteMode $ \outH -> do deflate <- Z.initDeflate 7 $ Z.WindowBits 31 FIXME this code should write to a temporary file , then -- rename to the final file let goPopper popper = fix $ \loop -> do res <- popper case res of Z.PRDone -> return () Z.PRNext bs -> do S.hPut outH bs loop Z.PRError ex -> throwIO ex fix $ \loop -> do bs <- S.hGetSome inH defaultChunkSize unless (S.null bs) $ do Z.feedDeflate deflate bs >>= goPopper loop goPopper $ Z.finishDeflate deflate FIXME bad ! do n't catch all exceptions like that ! where onSucc = sendResponse $ responseFile s (fixHeaders hs) tmpfile Nothing FIXME log the error message tmpfile = cache ++ '/' : map safe file safe c | 'A' <= c && c <= 'Z' = c | 'a' <= c && c <= 'z' = c | '0' <= c && c <= '9' = c safe '-' = '-' safe '_' = '_' safe _ = '_' compressE :: GzipSettings -> Response -> (Response -> IO a) -> IO a compressE set res sendResponse = case lookup hContentType hs of Just m | gzipCheckMime set m -> let hs' = fixHeaders hs in wb $ \body -> sendResponse $ responseStream s hs' $ \sendChunk flush -> do (blazeRecv, _) <- B.newBlazeRecv B.defaultStrategy deflate <- Z.initDeflate 1 (Z.WindowBits 31) let sendBuilder builder = do popper <- blazeRecv builder fix $ \loop -> do bs <- popper unless (S.null bs) $ do sendBS bs loop sendBS bs = Z.feedDeflate deflate bs >>= deflatePopper flushBuilder = do sendBuilder Blaze.flush deflatePopper $ Z.flushDeflate deflate flush deflatePopper popper = fix $ \loop -> do result <- popper case result of Z.PRDone -> return () Z.PRNext bs' -> do sendChunk $ fromByteString bs' loop Z.PRError e -> throwIO e body sendBuilder flushBuilder sendBuilder Blaze.flush deflatePopper $ Z.finishDeflate deflate _ -> sendResponse res where (s, hs, wb) = responseToStream res -- Remove Content-Length header, since we will certainly have a different length after . fixHeaders :: [Header] -> [Header] fixHeaders = ((hContentEncoding, "gzip") :) . filter notLength where notLength (x, _) = x /= hContentLength splitCommas :: String -> [String] splitCommas [] = [] splitCommas x = let (y, z) = break (== ',') x in y : splitCommas (dropWhile (== ' ') $ drop 1 z)
null
https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/tests/packages/application/Network.Wai.Middleware.Gzip.hs
haskell
# LANGUAGE Haskell2010, OverloadedStrings # # LANGUAGE Rank2Types, ScopedTypeVariables # ------------------------------------------------------- | License : BSD3 Stability : Unstable Portability : portable Automatic gzip compression of responses. ------------------------------------------------------- | Gzip behavior for files. ^ Do not compress file responses. ^ Compress files. Note that this may counteract platforms. ^ Compress files, caching them in some directory. appended to it, if the file is missing then try next action @since 3.0.17 | MIME types that will be compressed by default: | Use gzip to compress the body of the response. Analyzes the \"Accept-Encoding\" header from the client to determine File responses will be compressed according to the 'GzipFiles' setting. This could be a streaming case For a small enough response, gzipping will actually increase the size Potentially for anything less than 860 bytes gzipping could be a net loss The actual number is application specific though and may need to be adjusted -is-recommended-minimum-object-size-for-gzip-performance-benefits rename to the final file Remove Content-Length header, since we will certainly have a
# LINE 1 " Network / Wai / Middleware / Gzip.hs " # Module : Network . Wai . Middleware . Copyright : Maintainer : < > module Network.Wai.Middleware.Gzip ( gzip , GzipSettings , gzipFiles , GzipFiles (..) , gzipCheckMime , def , defaultCheckMime ) where import Network.Wai import Data.Maybe (fromMaybe, isJust) import qualified Data.ByteString.Char8 as S8 import qualified Data.ByteString as S import Data.Default.Class import Network.HTTP.Types ( Status, Header, hContentEncoding, hUserAgent , hContentType, hContentLength) import System.Directory (doesFileExist, createDirectoryIfMissing) import Blaze.ByteString.Builder (fromByteString) import Control.Exception (try, SomeException) import qualified Data.Set as Set import Network.Wai.Header import Network.Wai.Internal import qualified Data.Streaming.Blaze as B import qualified Data.Streaming.Zlib as Z import qualified Blaze.ByteString.Builder as Blaze import Control.Monad (unless) import Data.Function (fix) import Control.Exception (throwIO) import qualified System.IO as IO import Data.ByteString.Lazy.Internal (defaultChunkSize) import Data.Word8 (_semicolon) data GzipSettings = GzipSettings { gzipFiles :: GzipFiles , gzipCheckMime :: S.ByteString -> Bool } data GzipFiles zero - copy response optimizations on some ^ If we use compression then try to use the filename with " " deriving (Show, Eq, Read) | Use default MIME settings ; /do not/ compress files . instance Default GzipSettings where def = GzipSettings GzipIgnore defaultCheckMime @text/*@ , @application / json@ , @application / javascript@ , @application / ecmascript@ , @image / x - icon@. defaultCheckMime :: S.ByteString -> Bool defaultCheckMime bs = S8.isPrefixOf "text/" bs || bs' `Set.member` toCompress where bs' = fst $ S.break (== _semicolon) bs toCompress = Set.fromList [ "application/json" , "application/javascript" , "application/ecmascript" , "image/x-icon" ] if is supported . gzip :: GzipSettings -> Middleware gzip set app env sendResponse = app env $ \res -> case res of ResponseRaw{} -> sendResponse res ResponseFile{} | gzipFiles set == GzipIgnore -> sendResponse res _ -> if "gzip" `elem` enc && not isMSIE6 && not (isEncoded res) && (bigEnough res) then let runAction x = case x of (ResponseFile s hs file Nothing, GzipPreCompressed nextAction) -> let compressedVersion = file ++ ".gz" in doesFileExist compressedVersion >>= \x -> if x then (sendResponse $ ResponseFile s (fixHeaders hs) compressedVersion Nothing) else (runAction (ResponseFile s hs file Nothing, nextAction)) (ResponseFile s hs file Nothing, GzipCacheFolder cache) -> case lookup hContentType hs of Just m | gzipCheckMime set m -> compressFile s hs file cache sendResponse _ -> sendResponse res (ResponseFile {}, GzipIgnore) -> sendResponse res _ -> compressE set res sendResponse in runAction (res, gzipFiles set) else sendResponse res where enc = fromMaybe [] $ (splitCommas . S8.unpack) `fmap` lookup "Accept-Encoding" (requestHeaders env) ua = fromMaybe "" $ lookup hUserAgent $ requestHeaders env isMSIE6 = "MSIE 6" `S.isInfixOf` ua isEncoded res = isJust $ lookup hContentEncoding $ responseHeaders res bigEnough rsp = case contentLength (responseHeaders rsp) of Just len -> len >= minimumLength minimumLength = 860 compressFile :: Status -> [Header] -> FilePath -> FilePath -> (Response -> IO a) -> IO a compressFile s hs file cache sendResponse = do e <- doesFileExist tmpfile if e then onSucc else do createDirectoryIfMissing True cache x <- try $ IO.withBinaryFile file IO.ReadMode $ \inH -> IO.withBinaryFile tmpfile IO.WriteMode $ \outH -> do deflate <- Z.initDeflate 7 $ Z.WindowBits 31 FIXME this code should write to a temporary file , then let goPopper popper = fix $ \loop -> do res <- popper case res of Z.PRDone -> return () Z.PRNext bs -> do S.hPut outH bs loop Z.PRError ex -> throwIO ex fix $ \loop -> do bs <- S.hGetSome inH defaultChunkSize unless (S.null bs) $ do Z.feedDeflate deflate bs >>= goPopper loop goPopper $ Z.finishDeflate deflate FIXME bad ! do n't catch all exceptions like that ! where onSucc = sendResponse $ responseFile s (fixHeaders hs) tmpfile Nothing FIXME log the error message tmpfile = cache ++ '/' : map safe file safe c | 'A' <= c && c <= 'Z' = c | 'a' <= c && c <= 'z' = c | '0' <= c && c <= '9' = c safe '-' = '-' safe '_' = '_' safe _ = '_' compressE :: GzipSettings -> Response -> (Response -> IO a) -> IO a compressE set res sendResponse = case lookup hContentType hs of Just m | gzipCheckMime set m -> let hs' = fixHeaders hs in wb $ \body -> sendResponse $ responseStream s hs' $ \sendChunk flush -> do (blazeRecv, _) <- B.newBlazeRecv B.defaultStrategy deflate <- Z.initDeflate 1 (Z.WindowBits 31) let sendBuilder builder = do popper <- blazeRecv builder fix $ \loop -> do bs <- popper unless (S.null bs) $ do sendBS bs loop sendBS bs = Z.feedDeflate deflate bs >>= deflatePopper flushBuilder = do sendBuilder Blaze.flush deflatePopper $ Z.flushDeflate deflate flush deflatePopper popper = fix $ \loop -> do result <- popper case result of Z.PRDone -> return () Z.PRNext bs' -> do sendChunk $ fromByteString bs' loop Z.PRError e -> throwIO e body sendBuilder flushBuilder sendBuilder Blaze.flush deflatePopper $ Z.finishDeflate deflate _ -> sendResponse res where (s, hs, wb) = responseToStream res different length after . fixHeaders :: [Header] -> [Header] fixHeaders = ((hContentEncoding, "gzip") :) . filter notLength where notLength (x, _) = x /= hContentLength splitCommas :: String -> [String] splitCommas [] = [] splitCommas x = let (y, z) = break (== ',') x in y : splitCommas (dropWhile (== ' ') $ drop 1 z)
27a5c648c923264e933ae214b099f5b09f3de3ea2edfe92d698692d3c32fea1f
penpot/penpot
tmp.clj
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. ;; ;; Copyright (c) KALEIDOS INC (ns app.storage.tmp "Temporal files service all created files will be tried to clean after 1 hour after creation. This is a best effort, if this process fails, the operating system cleaning task should be responsible of permanently delete these files (look at systemd-tempfiles)." (:require [app.common.data :as d] [app.common.logging :as l] [app.storage :as-alias sto] [app.util.time :as dt] [app.worker :as wrk] [clojure.core.async :as a] [clojure.spec.alpha :as s] [datoteka.fs :as fs] [integrant.core :as ig] [promesa.exec :as px])) (declare remove-temp-file) (defonce queue (a/chan 128)) (defmethod ig/pre-init-spec ::cleaner [_] (s/keys :req [::sto/min-age ::wrk/scheduled-executor])) (defmethod ig/prep-key ::cleaner [_ cfg] (merge {::sto/min-age (dt/duration "30m")} (d/without-nils cfg))) (defmethod ig/init-key ::cleaner [_ {:keys [::sto/min-age ::wrk/scheduled-executor] :as cfg}] (px/thread {:name "penpot/storage-tmp-cleaner"} (try (l/info :hint "started tmp file cleaner") (loop [] (when-let [path (a/<!! queue)] (l/trace :hint "schedule tempfile deletion" :path path :expires-at (dt/plus (dt/now) min-age)) (px/schedule! scheduled-executor (inst-ms min-age) (partial remove-temp-file path)) (recur))) (catch InterruptedException _ (l/debug :hint "interrupted")) (finally (l/info :hint "terminated tmp file cleaner"))))) (defmethod ig/halt-key! ::cleaner [_ thread] (px/interrupt! thread)) (defn- remove-temp-file "Permanently delete tempfile" [path] (l/trace :hint "permanently delete tempfile" :path path) (when (fs/exists? path) (fs/delete path))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; API ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn tempfile "Returns a tmpfile candidate (without creating it)" [& {:keys [suffix prefix] :or {prefix "penpot." suffix ".tmp"}}] (let [candidate (fs/tempfile :suffix suffix :prefix prefix)] (a/offer! queue candidate) candidate)) (defn create-tempfile [& {:keys [suffix prefix] :or {prefix "penpot." suffix ".tmp"}}] (let [path (fs/create-tempfile :suffix suffix :prefix prefix)] (a/offer! queue path) path))
null
https://raw.githubusercontent.com/penpot/penpot/1c2a4621246e2a890ba9bae8176c32a6937c7c4d/backend/src/app/storage/tmp.clj
clojure
Copyright (c) KALEIDOS INC API
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. (ns app.storage.tmp "Temporal files service all created files will be tried to clean after 1 hour after creation. This is a best effort, if this process fails, the operating system cleaning task should be responsible of permanently delete these files (look at systemd-tempfiles)." (:require [app.common.data :as d] [app.common.logging :as l] [app.storage :as-alias sto] [app.util.time :as dt] [app.worker :as wrk] [clojure.core.async :as a] [clojure.spec.alpha :as s] [datoteka.fs :as fs] [integrant.core :as ig] [promesa.exec :as px])) (declare remove-temp-file) (defonce queue (a/chan 128)) (defmethod ig/pre-init-spec ::cleaner [_] (s/keys :req [::sto/min-age ::wrk/scheduled-executor])) (defmethod ig/prep-key ::cleaner [_ cfg] (merge {::sto/min-age (dt/duration "30m")} (d/without-nils cfg))) (defmethod ig/init-key ::cleaner [_ {:keys [::sto/min-age ::wrk/scheduled-executor] :as cfg}] (px/thread {:name "penpot/storage-tmp-cleaner"} (try (l/info :hint "started tmp file cleaner") (loop [] (when-let [path (a/<!! queue)] (l/trace :hint "schedule tempfile deletion" :path path :expires-at (dt/plus (dt/now) min-age)) (px/schedule! scheduled-executor (inst-ms min-age) (partial remove-temp-file path)) (recur))) (catch InterruptedException _ (l/debug :hint "interrupted")) (finally (l/info :hint "terminated tmp file cleaner"))))) (defmethod ig/halt-key! ::cleaner [_ thread] (px/interrupt! thread)) (defn- remove-temp-file "Permanently delete tempfile" [path] (l/trace :hint "permanently delete tempfile" :path path) (when (fs/exists? path) (fs/delete path))) (defn tempfile "Returns a tmpfile candidate (without creating it)" [& {:keys [suffix prefix] :or {prefix "penpot." suffix ".tmp"}}] (let [candidate (fs/tempfile :suffix suffix :prefix prefix)] (a/offer! queue candidate) candidate)) (defn create-tempfile [& {:keys [suffix prefix] :or {prefix "penpot." suffix ".tmp"}}] (let [path (fs/create-tempfile :suffix suffix :prefix prefix)] (a/offer! queue path) path))
eb4bd0bd78958ad893145f539c497cb0336ca19bccbc3c77a987401fb87e64f8
amatus/foofs
fuse.clj
Copyright ( C ) 2012 < > ; ; foofs 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. ; ; foofs is distributed in the hope that it will be useful, but ; WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ; See the GNU General Public License for more details. ; You should have received a copy of the GNU General Public License along ; with this program. If not, see </>. (ns foofs.fuse.fuse (:use (foofs.fuse jna protocol)) (:import com.sun.jna.Memory com.sun.jna.ptr.IntByReference)) (defn read-loop! [fuse] (let [fd (:fd fuse)] (try (loop [] (let [mem (Memory. 0x21000) ret (c-read fd mem (.size mem))] (process-buf! fuse (.getByteBuffer mem 0 ret))) (recur)) (catch Exception e (.printStackTrace e))))) (defn start-filesystem [filesystem fd] (let [fuse {:filesystem filesystem :fd fd :read-thread (atom nil) :connection {:proto-major (atom 0) :proto-minor (atom 0)}} read-thread (Thread. (partial read-loop! fuse))] (reset! (:read-thread fuse) read-thread) (.start read-thread) fuse)) (defn freebsd-mount [filesystem mountpoint] (try (let [fd (c-open "/dev/fuse" 0100002 0) pid (IntByReference.) ret (posix_spawn pid "/usr/sbin/mount_fusefs" nil nil ["mount_fusefs" "-o" "default_permissions" (str fd) mountpoint] ["MOUNT_FUSEFS_SAFE=1" "MOUNT_FUSEFS_CALL_BY_LIB=1"])] (if (== 0 ret) (let [stat_loc (IntByReference.)] (waitpid (.getValue pid) stat_loc 0) (if (== 0 (.getValue stat_loc)) (start-filesystem filesystem fd) (c-close fd))) (c-close fd))) (catch Exception e (.printStackTrace e) nil))) (defn linux-mount [filesystem mountpoint] (try (let [sv (Memory. 8)] (socketpair pf-unix sock-stream 0 sv) (let [sock0 (.getInt sv 0) sock1 (.getInt sv 4) pid (IntByReference.) ret (posix_spawnp pid "fusermount" nil nil ["fusermount" "--" mountpoint] [(str "_FUSE_COMMFD=" sock0)])] (when (== 0 ret) (when-let [rv (receive-fd sock1)] (start-filesystem filesystem rv))))) (catch Exception e (.printStackTrace e) nil)))
null
https://raw.githubusercontent.com/amatus/foofs/1d3754e72e09e5f395d5ace1b6bf91e4c7293a54/src/clojure/foofs/fuse/fuse.clj
clojure
foofs is free software: you can redistribute it and/or modify it (at your option) any later version. foofs 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. with this program. If not, see </>.
Copyright ( C ) 2012 < > 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 along (ns foofs.fuse.fuse (:use (foofs.fuse jna protocol)) (:import com.sun.jna.Memory com.sun.jna.ptr.IntByReference)) (defn read-loop! [fuse] (let [fd (:fd fuse)] (try (loop [] (let [mem (Memory. 0x21000) ret (c-read fd mem (.size mem))] (process-buf! fuse (.getByteBuffer mem 0 ret))) (recur)) (catch Exception e (.printStackTrace e))))) (defn start-filesystem [filesystem fd] (let [fuse {:filesystem filesystem :fd fd :read-thread (atom nil) :connection {:proto-major (atom 0) :proto-minor (atom 0)}} read-thread (Thread. (partial read-loop! fuse))] (reset! (:read-thread fuse) read-thread) (.start read-thread) fuse)) (defn freebsd-mount [filesystem mountpoint] (try (let [fd (c-open "/dev/fuse" 0100002 0) pid (IntByReference.) ret (posix_spawn pid "/usr/sbin/mount_fusefs" nil nil ["mount_fusefs" "-o" "default_permissions" (str fd) mountpoint] ["MOUNT_FUSEFS_SAFE=1" "MOUNT_FUSEFS_CALL_BY_LIB=1"])] (if (== 0 ret) (let [stat_loc (IntByReference.)] (waitpid (.getValue pid) stat_loc 0) (if (== 0 (.getValue stat_loc)) (start-filesystem filesystem fd) (c-close fd))) (c-close fd))) (catch Exception e (.printStackTrace e) nil))) (defn linux-mount [filesystem mountpoint] (try (let [sv (Memory. 8)] (socketpair pf-unix sock-stream 0 sv) (let [sock0 (.getInt sv 0) sock1 (.getInt sv 4) pid (IntByReference.) ret (posix_spawnp pid "fusermount" nil nil ["fusermount" "--" mountpoint] [(str "_FUSE_COMMFD=" sock0)])] (when (== 0 ret) (when-let [rv (receive-fd sock1)] (start-filesystem filesystem rv))))) (catch Exception e (.printStackTrace e) nil)))
e3d2f4767fb9d8c96ab728e27fd2c9e70d82ab549d4ccf8169d814993e10c5f1
NetComposer/nkmedia
nkmedia_kms_callbacks.erl
%% ------------------------------------------------------------------- %% Copyright ( c ) 2016 . All Rights Reserved . %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% %% ------------------------------------------------------------------- @doc Plugin implementig the Kurento backend -module(nkmedia_kms_callbacks). -author('Carlos Gonzalez <>'). -export([plugin_deps/0, plugin_group/0, plugin_syntax/0, plugin_config/2, plugin_start/2, plugin_stop/2]). -export([nkmedia_kms_get_mediaserver/1]). -export([error_code/1]). -export([nkmedia_session_start/3, nkmedia_session_stop/2, nkmedia_session_offer/4, nkmedia_session_answer/4, nkmedia_session_cmd/3, nkmedia_session_candidate/2, nkmedia_session_handle_call/3, nkmedia_session_handle_cast/2]). -export([nkmedia_room_init/2, nkmedia_room_terminate/2, nkmedia_room_timeout/2]). -export([api_cmd/2, api_syntax/4]). -export([nkdocker_notify/2]). -include_lib("nkservice/include/nkservice.hrl"). -include("../../include/nkmedia_room.hrl"). %% =================================================================== %% Types %% =================================================================== %% =================================================================== %% Plugin callbacks %% =================================================================== plugin_deps() -> [nkmedia, nkmedia_room]. plugin_group() -> nkmedia_backends. plugin_syntax() -> #{ kms_docker_image => fun parse_image/3 }. plugin_config(Config, _Service) -> Cache = case Config of #{kms_docker_image:=KmsConfig} -> KmsConfig; _ -> nkmedia_kms_build:defaults(#{}) end, {ok, Config, Cache}. plugin_start(Config, #{name:=Name}) -> lager:info("Plugin NkMEDIA Kurento (~s) starting", [Name]), case nkdocker_monitor:register(?MODULE) of {ok, DockerMonId} -> nkmedia_app:put(docker_kms_mon_id, DockerMonId), lager:info("Installed images: ~s", [nklib_util:bjoin(find_images(DockerMonId))]); {error, Error} -> lager:error("Could not start Docker Monitor: ~p", [Error]), error(docker_monitor) end, {ok, Config}. plugin_stop(Config, #{name:=Name}) -> lager:info("Plugin NkMEDIA Kurento (~p) stopping", [Name]), nkdocker_monitor:unregister(?MODULE), {ok, Config}. %% =================================================================== %% Offering Callbacks %% =================================================================== @private -spec nkmedia_kms_get_mediaserver(nkservice:id()) -> {ok, nkmedia_kms_engine:id()} | {error, term()}. nkmedia_kms_get_mediaserver(SrvId) -> case nkmedia_kms_engine:get_all(SrvId) of [{KmsId, _}|_] -> {ok, KmsId}; [] -> {error, no_mediaserver} end. %% =================================================================== %% Implemented Callbacks - error %% =================================================================== @private See nkservice_callbacks error_code({kms_error, Code, Txt})-> {303001, "Kurento error ~p: ~s", [Code, Txt]}; error_code(_) -> continue. %% =================================================================== %% Implemented Callbacks - nkmedia_session %% =================================================================== @private nkmedia_session_start(Type, Role, Session) -> case maps:get(backend, Session, nkmedia_kms) of nkmedia_kms -> nkmedia_kms_session:start(Type, Role, Session); _ -> continue end. @private nkmedia_session_offer(Type, Role, Offer, #{nkmedia_kms_id:=_}=Session) -> nkmedia_kms_session:offer(Type, Role, Offer, Session); nkmedia_session_offer(_Type, _Role, _Offer, _Session) -> continue. @private nkmedia_session_answer(Type, Role, Answer, #{nkmedia_kms_id:=_}=Session) -> nkmedia_kms_session:answer(Type, Role, Answer, Session); nkmedia_session_answer(_Type, _Role, _Answer, _Session) -> continue. @private nkmedia_session_cmd(Cmd, Opts, #{nkmedia_kms_id:=_}=Session) -> nkmedia_kms_session:cmd(Cmd, Opts, Session); nkmedia_session_cmd(_Cmd, _Opts, _Session) -> continue. @private nkmedia_session_candidate(Candidate, #{nkmedia_kms_id:=_}=Session) -> nkmedia_kms_session:candidate(Candidate, Session); nkmedia_session_candidate(_Candidate, _Session) -> continue. @private nkmedia_session_stop(Reason, #{nkmedia_kms_id:=_}=Session) -> nkmedia_kms_session:stop(Reason, Session); nkmedia_session_stop(_Reason, _Session) -> continue. @private nkmedia_session_handle_call({nkmedia_kms, Msg}, From, Session) -> nkmedia_kms_session:handle_call(Msg, From, Session); nkmedia_session_handle_call(_Msg, _From, _Session) -> continue. @private nkmedia_session_handle_cast({nkmedia_kms, Msg}, Session) -> nkmedia_kms_session:handle_cast(Msg, Session); nkmedia_session_handle_cast(_Msg, _Session) -> continue. %% =================================================================== %% Implemented Callbacks - nkmedia_room %% =================================================================== @private nkmedia_room_init(Id, Room) -> case maps:get(backend, Room, nkmedia_kms) of nkmedia_kms -> case maps:get(class, Room, sfu) of sfu -> nkmedia_kms_room:init(Id, Room); _ -> {ok, Room} end; _ -> {ok, Room} end. @private nkmedia_room_terminate(Reason, #{nkmedia_kms_id:=_}=Room) -> nkmedia_kms_room:terminate(Reason, Room); nkmedia_room_terminate(_Reason, Room) -> {ok, Room}. @private nkmedia_room_timeout(RoomId, #{nkmedia_kms_id:=_}=Room) -> nkmedia_kms_room:timeout(RoomId, Room); nkmedia_room_timeout(_RoomId, _Room) -> continue. % %% @private nkmedia_room_handle_cast({nkmedia_kms , Msg } , Room ) - > % nkmedia_kms_room:handle_cast(Msg, Room); % nkmedia_room_handle_cast(_Msg, _Room) -> % continue. %% =================================================================== %% API %% =================================================================== @private api_cmd(#api_req{class = <<"media">>}=Req, State) -> #api_req{subclass=Sub, cmd=Cmd} = Req, nkmedia_kms_api:cmd(Sub, Cmd, Req, State); api_cmd(_Req, _State) -> continue. @private api_syntax(#api_req{class = <<"media">>}=Req, Syntax, Defaults, Mandatory) -> #api_req{subclass=Sub, cmd=Cmd} = Req, {S2, D2, M2} = nkmedia_kms_api_syntax:syntax(Sub, Cmd, Syntax, Defaults, Mandatory), {continue, [Req, S2, D2, M2]}; api_syntax(_Req, _Syntax, _Defaults, _Mandatory) -> continue. %% =================================================================== %% Docker Monitor Callbacks %% =================================================================== nkdocker_notify(MonId, {Op, {<<"nk_kms_", _/binary>>=Name, Data}}) -> nkmedia_kms_docker:notify(MonId, Op, Name, Data); nkdocker_notify(_MonId, _Op) -> ok. %% =================================================================== Internal %% =================================================================== @private parse_image(_Key, Map, _Ctx) when is_map(Map) -> {ok, Map}; parse_image(_, Image, _Ctx) -> case binary:split(Image, <<"/">>) of [Comp, <<"nk_kms:", Tag/binary>>] -> [Vsn, Rel] = binary:split(Tag, <<"-">>), Def = #{comp=>Comp, vsn=>Vsn, rel=>Rel}, {ok, nkmedia_kms_build:defaults(Def)}; _ -> error end. @private find_images(MonId) -> {ok, Docker} = nkdocker_monitor:get_docker(MonId), {ok, Images} = nkdocker:images(Docker), Tags = lists:flatten([T || #{<<"RepoTags">>:=T} <- Images]), lists:filter( fun(Img) -> length(binary:split(Img, <<"/nk_kurento_">>))==2 end, Tags).
null
https://raw.githubusercontent.com/NetComposer/nkmedia/24480866a523bfd6490abfe90ea46c6130ffe51f/src/kms_backend/nkmedia_kms_callbacks.erl
erlang
------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- =================================================================== Types =================================================================== =================================================================== Plugin callbacks =================================================================== =================================================================== Offering Callbacks =================================================================== =================================================================== Implemented Callbacks - error =================================================================== =================================================================== Implemented Callbacks - nkmedia_session =================================================================== =================================================================== Implemented Callbacks - nkmedia_room =================================================================== %% @private nkmedia_kms_room:handle_cast(Msg, Room); nkmedia_room_handle_cast(_Msg, _Room) -> continue. =================================================================== API =================================================================== =================================================================== Docker Monitor Callbacks =================================================================== =================================================================== ===================================================================
Copyright ( c ) 2016 . All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY @doc Plugin implementig the Kurento backend -module(nkmedia_kms_callbacks). -author('Carlos Gonzalez <>'). -export([plugin_deps/0, plugin_group/0, plugin_syntax/0, plugin_config/2, plugin_start/2, plugin_stop/2]). -export([nkmedia_kms_get_mediaserver/1]). -export([error_code/1]). -export([nkmedia_session_start/3, nkmedia_session_stop/2, nkmedia_session_offer/4, nkmedia_session_answer/4, nkmedia_session_cmd/3, nkmedia_session_candidate/2, nkmedia_session_handle_call/3, nkmedia_session_handle_cast/2]). -export([nkmedia_room_init/2, nkmedia_room_terminate/2, nkmedia_room_timeout/2]). -export([api_cmd/2, api_syntax/4]). -export([nkdocker_notify/2]). -include_lib("nkservice/include/nkservice.hrl"). -include("../../include/nkmedia_room.hrl"). plugin_deps() -> [nkmedia, nkmedia_room]. plugin_group() -> nkmedia_backends. plugin_syntax() -> #{ kms_docker_image => fun parse_image/3 }. plugin_config(Config, _Service) -> Cache = case Config of #{kms_docker_image:=KmsConfig} -> KmsConfig; _ -> nkmedia_kms_build:defaults(#{}) end, {ok, Config, Cache}. plugin_start(Config, #{name:=Name}) -> lager:info("Plugin NkMEDIA Kurento (~s) starting", [Name]), case nkdocker_monitor:register(?MODULE) of {ok, DockerMonId} -> nkmedia_app:put(docker_kms_mon_id, DockerMonId), lager:info("Installed images: ~s", [nklib_util:bjoin(find_images(DockerMonId))]); {error, Error} -> lager:error("Could not start Docker Monitor: ~p", [Error]), error(docker_monitor) end, {ok, Config}. plugin_stop(Config, #{name:=Name}) -> lager:info("Plugin NkMEDIA Kurento (~p) stopping", [Name]), nkdocker_monitor:unregister(?MODULE), {ok, Config}. @private -spec nkmedia_kms_get_mediaserver(nkservice:id()) -> {ok, nkmedia_kms_engine:id()} | {error, term()}. nkmedia_kms_get_mediaserver(SrvId) -> case nkmedia_kms_engine:get_all(SrvId) of [{KmsId, _}|_] -> {ok, KmsId}; [] -> {error, no_mediaserver} end. @private See nkservice_callbacks error_code({kms_error, Code, Txt})-> {303001, "Kurento error ~p: ~s", [Code, Txt]}; error_code(_) -> continue. @private nkmedia_session_start(Type, Role, Session) -> case maps:get(backend, Session, nkmedia_kms) of nkmedia_kms -> nkmedia_kms_session:start(Type, Role, Session); _ -> continue end. @private nkmedia_session_offer(Type, Role, Offer, #{nkmedia_kms_id:=_}=Session) -> nkmedia_kms_session:offer(Type, Role, Offer, Session); nkmedia_session_offer(_Type, _Role, _Offer, _Session) -> continue. @private nkmedia_session_answer(Type, Role, Answer, #{nkmedia_kms_id:=_}=Session) -> nkmedia_kms_session:answer(Type, Role, Answer, Session); nkmedia_session_answer(_Type, _Role, _Answer, _Session) -> continue. @private nkmedia_session_cmd(Cmd, Opts, #{nkmedia_kms_id:=_}=Session) -> nkmedia_kms_session:cmd(Cmd, Opts, Session); nkmedia_session_cmd(_Cmd, _Opts, _Session) -> continue. @private nkmedia_session_candidate(Candidate, #{nkmedia_kms_id:=_}=Session) -> nkmedia_kms_session:candidate(Candidate, Session); nkmedia_session_candidate(_Candidate, _Session) -> continue. @private nkmedia_session_stop(Reason, #{nkmedia_kms_id:=_}=Session) -> nkmedia_kms_session:stop(Reason, Session); nkmedia_session_stop(_Reason, _Session) -> continue. @private nkmedia_session_handle_call({nkmedia_kms, Msg}, From, Session) -> nkmedia_kms_session:handle_call(Msg, From, Session); nkmedia_session_handle_call(_Msg, _From, _Session) -> continue. @private nkmedia_session_handle_cast({nkmedia_kms, Msg}, Session) -> nkmedia_kms_session:handle_cast(Msg, Session); nkmedia_session_handle_cast(_Msg, _Session) -> continue. @private nkmedia_room_init(Id, Room) -> case maps:get(backend, Room, nkmedia_kms) of nkmedia_kms -> case maps:get(class, Room, sfu) of sfu -> nkmedia_kms_room:init(Id, Room); _ -> {ok, Room} end; _ -> {ok, Room} end. @private nkmedia_room_terminate(Reason, #{nkmedia_kms_id:=_}=Room) -> nkmedia_kms_room:terminate(Reason, Room); nkmedia_room_terminate(_Reason, Room) -> {ok, Room}. @private nkmedia_room_timeout(RoomId, #{nkmedia_kms_id:=_}=Room) -> nkmedia_kms_room:timeout(RoomId, Room); nkmedia_room_timeout(_RoomId, _Room) -> continue. nkmedia_room_handle_cast({nkmedia_kms , Msg } , Room ) - > @private api_cmd(#api_req{class = <<"media">>}=Req, State) -> #api_req{subclass=Sub, cmd=Cmd} = Req, nkmedia_kms_api:cmd(Sub, Cmd, Req, State); api_cmd(_Req, _State) -> continue. @private api_syntax(#api_req{class = <<"media">>}=Req, Syntax, Defaults, Mandatory) -> #api_req{subclass=Sub, cmd=Cmd} = Req, {S2, D2, M2} = nkmedia_kms_api_syntax:syntax(Sub, Cmd, Syntax, Defaults, Mandatory), {continue, [Req, S2, D2, M2]}; api_syntax(_Req, _Syntax, _Defaults, _Mandatory) -> continue. nkdocker_notify(MonId, {Op, {<<"nk_kms_", _/binary>>=Name, Data}}) -> nkmedia_kms_docker:notify(MonId, Op, Name, Data); nkdocker_notify(_MonId, _Op) -> ok. Internal @private parse_image(_Key, Map, _Ctx) when is_map(Map) -> {ok, Map}; parse_image(_, Image, _Ctx) -> case binary:split(Image, <<"/">>) of [Comp, <<"nk_kms:", Tag/binary>>] -> [Vsn, Rel] = binary:split(Tag, <<"-">>), Def = #{comp=>Comp, vsn=>Vsn, rel=>Rel}, {ok, nkmedia_kms_build:defaults(Def)}; _ -> error end. @private find_images(MonId) -> {ok, Docker} = nkdocker_monitor:get_docker(MonId), {ok, Images} = nkdocker:images(Docker), Tags = lists:flatten([T || #{<<"RepoTags">>:=T} <- Images]), lists:filter( fun(Img) -> length(binary:split(Img, <<"/nk_kurento_">>))==2 end, Tags).
333f0c64e9617f6b206b02b94714d5ca5f851ee7540a6a5e798d8918061ffb2c
bitc/omegagb
CpuExecution.hs
OmegaGB Copyright 2007 Bit This program is distributed under the terms of the GNU General Public License ----------------------------------------------------------------------------- -- | Module : CpuExecution Copyright : ( c ) Bit Connor 2007 < > -- License : GPL -- Maintainer : -- Stability : in-progress -- -- OmegaGB -- Game Boy Emulator -- -- This module defines an abstract syntax tree CPU execution monad -- ----------------------------------------------------------------------------- {-# OPTIONS -fglasgow-exts #-} module CpuExecution where import Data.Word import Data.Bits data M_Register = M_A | M_B | M_C | M_D | M_E | M_F | M_H | M_L data M_Register2 = M_AF | M_BC | M_DE | M_HL | M_PC | M_SP data ExecutionAST result where Return :: result -> ExecutionAST result Bind :: (ExecutionAST oldres) -> (oldres -> ExecutionAST result) -> ExecutionAST result WriteRegister :: M_Register -> Word8 -> ExecutionAST () ReadRegister :: M_Register -> ExecutionAST Word8 WriteRegister2 :: M_Register2 -> Word16 -> ExecutionAST () ReadRegister2 :: M_Register2 -> ExecutionAST Word16 WriteMemory :: Word16 -> Word8 -> ExecutionAST () ReadMemory :: Word16 -> ExecutionAST Word8 instance Monad ExecutionAST where return = Return (>>=) = Bind writeRegister = WriteRegister readRegister = ReadRegister writeRegister2 = WriteRegister2 readRegister2 = ReadRegister2 writeMemory = WriteMemory readMemory = ReadMemory writeFlags :: Maybe Bool -> Maybe Bool -> Maybe Bool -> Maybe Bool -> ExecutionAST () writeFlags z n h c = do v0 <- readRegister M_F let v1 = case z of Nothing -> v0 Just True -> setBit v0 7 Just False -> clearBit v0 7 let v2 = case n of Nothing -> v1 Just True -> setBit v1 6 Just False -> clearBit v1 6 let v3 = case h of Nothing -> v2 Just True -> setBit v2 5 Just False -> clearBit v2 5 let v4 = case c of Nothing -> v3 Just True -> setBit v3 4 Just False -> clearBit v3 4 writeRegister M_F v4
null
https://raw.githubusercontent.com/bitc/omegagb/5ab9c3a22f5fc283906b8af53717d81fef96db7f/src/CpuExecution.hs
haskell
--------------------------------------------------------------------------- | License : GPL Maintainer : Stability : in-progress OmegaGB Game Boy Emulator This module defines an abstract syntax tree CPU execution monad --------------------------------------------------------------------------- # OPTIONS -fglasgow-exts #
OmegaGB Copyright 2007 Bit This program is distributed under the terms of the GNU General Public License Module : CpuExecution Copyright : ( c ) Bit Connor 2007 < > module CpuExecution where import Data.Word import Data.Bits data M_Register = M_A | M_B | M_C | M_D | M_E | M_F | M_H | M_L data M_Register2 = M_AF | M_BC | M_DE | M_HL | M_PC | M_SP data ExecutionAST result where Return :: result -> ExecutionAST result Bind :: (ExecutionAST oldres) -> (oldres -> ExecutionAST result) -> ExecutionAST result WriteRegister :: M_Register -> Word8 -> ExecutionAST () ReadRegister :: M_Register -> ExecutionAST Word8 WriteRegister2 :: M_Register2 -> Word16 -> ExecutionAST () ReadRegister2 :: M_Register2 -> ExecutionAST Word16 WriteMemory :: Word16 -> Word8 -> ExecutionAST () ReadMemory :: Word16 -> ExecutionAST Word8 instance Monad ExecutionAST where return = Return (>>=) = Bind writeRegister = WriteRegister readRegister = ReadRegister writeRegister2 = WriteRegister2 readRegister2 = ReadRegister2 writeMemory = WriteMemory readMemory = ReadMemory writeFlags :: Maybe Bool -> Maybe Bool -> Maybe Bool -> Maybe Bool -> ExecutionAST () writeFlags z n h c = do v0 <- readRegister M_F let v1 = case z of Nothing -> v0 Just True -> setBit v0 7 Just False -> clearBit v0 7 let v2 = case n of Nothing -> v1 Just True -> setBit v1 6 Just False -> clearBit v1 6 let v3 = case h of Nothing -> v2 Just True -> setBit v2 5 Just False -> clearBit v2 5 let v4 = case c of Nothing -> v3 Just True -> setBit v3 4 Just False -> clearBit v3 4 writeRegister M_F v4
ec6abeaf3c8c8bb5935cdbecb430636c1b595e6ce9e6486673057c97fd11c77a
jtdaugherty/dbmigrations
InMemoryStore.hs
module InMemoryStore (inMemoryStore) where import Data.Text ( Text ) import Data.String.Conversions ( cs ) import Control.Concurrent.MVar import Database.Schema.Migrations.Migration import Database.Schema.Migrations.Store type InMemoryData = [(Text, Migration)] |Builds simple in - memory store that uses ' MVar ' to preserve a list of -- migrations. inMemoryStore :: IO MigrationStore inMemoryStore = do store <- newMVar [] return MigrationStore { loadMigration = loadMigrationInMem store , saveMigration = saveMigrationInMem store , getMigrations = getMigrationsInMem store , fullMigrationName = return . cs } loadMigrationInMem :: MVar InMemoryData -> Text -> IO (Either String Migration) loadMigrationInMem store migId = withMVar store $ \migrations -> do let mig = lookup migId migrations return $ case mig of Just m -> Right m _ -> Left "Migration not found" saveMigrationInMem :: MVar InMemoryData -> Migration -> IO () saveMigrationInMem store m = modifyMVar_ store $ return . ((mId m, m):) getMigrationsInMem :: MVar InMemoryData -> IO [Text] getMigrationsInMem store = withMVar store $ return . fmap fst
null
https://raw.githubusercontent.com/jtdaugherty/dbmigrations/80336a736ac394a2d38c65661b249b2fae142b64/test/InMemoryStore.hs
haskell
migrations.
module InMemoryStore (inMemoryStore) where import Data.Text ( Text ) import Data.String.Conversions ( cs ) import Control.Concurrent.MVar import Database.Schema.Migrations.Migration import Database.Schema.Migrations.Store type InMemoryData = [(Text, Migration)] |Builds simple in - memory store that uses ' MVar ' to preserve a list of inMemoryStore :: IO MigrationStore inMemoryStore = do store <- newMVar [] return MigrationStore { loadMigration = loadMigrationInMem store , saveMigration = saveMigrationInMem store , getMigrations = getMigrationsInMem store , fullMigrationName = return . cs } loadMigrationInMem :: MVar InMemoryData -> Text -> IO (Either String Migration) loadMigrationInMem store migId = withMVar store $ \migrations -> do let mig = lookup migId migrations return $ case mig of Just m -> Right m _ -> Left "Migration not found" saveMigrationInMem :: MVar InMemoryData -> Migration -> IO () saveMigrationInMem store m = modifyMVar_ store $ return . ((mId m, m):) getMigrationsInMem :: MVar InMemoryData -> IO [Text] getMigrationsInMem store = withMVar store $ return . fmap fst
595a3b3d6aec6f0219df6c74be0a744011c8d91dd17d92a1b4b0c599d9964f11
Clojure2D/clojure2d-examples
camera.clj
(ns rt4.in-one-weekend.ch08c.camera (:require [rt4.in-one-weekend.ch08c.ray :as ray] [fastmath.vector :as v] [fastmath.core :as m])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (m/use-primitive-operators) (def ^:const ^double aspect-ratio (/ 16.0 9.0)) (defprotocol CameraProto (get-ray [camera s t])) (defrecord Camera [origin lower-left-corner horizontal vertical] CameraProto (get-ray [_ s t] (ray/ray origin (-> lower-left-corner (v/add (v/mult horizontal s)) (v/add (v/mult vertical t)) (v/sub origin))))) (defn camera [] (let [viewport-height 2.0 viewport-width (* aspect-ratio viewport-height) focal-length 1.0 origin (v/vec3 0.0 0.0 0.0) horizontal (v/vec3 viewport-width 0.0 0.0) vertical (v/vec3 0.0 viewport-height 0.0) lower-left-corner (-> origin (v/sub (v/div horizontal 2.0)) (v/sub (v/div vertical 2.0)) (v/sub (v/vec3 0.0 0.0 focal-length)))] (->Camera origin lower-left-corner horizontal vertical)))
null
https://raw.githubusercontent.com/Clojure2D/clojure2d-examples/ead92d6f17744b91070e6308157364ad4eab8a1b/src/rt4/in_one_weekend/ch08c/camera.clj
clojure
(ns rt4.in-one-weekend.ch08c.camera (:require [rt4.in-one-weekend.ch08c.ray :as ray] [fastmath.vector :as v] [fastmath.core :as m])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (m/use-primitive-operators) (def ^:const ^double aspect-ratio (/ 16.0 9.0)) (defprotocol CameraProto (get-ray [camera s t])) (defrecord Camera [origin lower-left-corner horizontal vertical] CameraProto (get-ray [_ s t] (ray/ray origin (-> lower-left-corner (v/add (v/mult horizontal s)) (v/add (v/mult vertical t)) (v/sub origin))))) (defn camera [] (let [viewport-height 2.0 viewport-width (* aspect-ratio viewport-height) focal-length 1.0 origin (v/vec3 0.0 0.0 0.0) horizontal (v/vec3 viewport-width 0.0 0.0) vertical (v/vec3 0.0 viewport-height 0.0) lower-left-corner (-> origin (v/sub (v/div horizontal 2.0)) (v/sub (v/div vertical 2.0)) (v/sub (v/vec3 0.0 0.0 focal-length)))] (->Camera origin lower-left-corner horizontal vertical)))
62939f61ad723dacf428ef3c9b6deaa15adb3729f052f0ff947d0f5c71882720
jserot/caph
caphmake.ml
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / / * * / / * This file is part of the CAPH Compiler distribution * / / * -bpclermont.fr * / / * * / / * Jocelyn SEROT * / / * * / / * * / / * Copyright 2011 - 2018 . All rights reserved . * / / * This file is distributed under the terms of the GNU Library General Public License * / / * with the special exception on linking described in file .. /LICENSE . * / / * * / / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /* */ /* This file is part of the CAPH Compiler distribution */ /* -bpclermont.fr */ /* */ /* Jocelyn SEROT */ /* */ /* */ /* Copyright 2011-2018 Jocelyn SEROT. All rights reserved. */ /* This file is distributed under the terms of the GNU Library General Public License */ /* with the special exception on linking described in file ../LICENSE. */ /* */ /***************************************************************************************) Top - level Makefile generator - since 2.8.1 open Printf type t_args = { mutable prefix: string; mutable main_file: string; mutable proj_file: string; mutable caph_dir: string; mutable output_file: string; } let args = { prefix="main"; main_file="main.cph"; proj_file="main.proj"; caph_dir=""; output_file="Makefile"; } let options_spec = [ "-main", Arg.String (function s -> args.main_file <- s), "set name of the top source file (default: main.cph)"; "-caph_dir", Arg.String (function s -> args.caph_dir <- s), "set path to the CAPH install directory (default: got from the CAPH environment variable)"; "-o", Arg.String (function s -> args.output_file <- s), "set name of the output file (default: Makefile)" ] let usage = "usage: caphmake [-main fname] [-caph_dir path] [-o fname] [proj_file]" let anonymous f = args.proj_file <- f let dump_banner oc = Printf.fprintf oc "## ###############################################################################\n"; Printf.fprintf oc "## This file has been automatically generated with command :\n"; Printf.fprintf oc "## %s\n" (Misc.string_of_list (function i -> i) " " (Array.to_list Sys.argv)); Printf.fprintf oc "## ###############################################################################\n\n" let dump_self_target oc args = let args' = Array.to_list Sys.argv in fprintf oc "caphmake:\n"; fprintf oc "\t%s %s\n" (Misc.string_of_list (fun i -> i) " " args') (if List.exists (fun s -> String.sub s 0 9 = "-caph_dir") args' then "" else "-caph_dir=" ^ args.caph_dir) let dump_makef_target oc args target = let mfile = sprintf "./%s/Makefile" target in let abbrev = function "systemc" -> "SC" | s -> String.uppercase_ascii s in fprintf oc "%s.makefile: %s\n" target mfile; fprintf oc "%s: %s $(GEN_CAPH_SRCS)\n" mfile args.main_file; fprintf oc "\t$(CAPHC) -target_dir ./%s -I %s/lib/caph -make -%s $(%s_OPTS) %s\n" target args.caph_dir target (abbrev target) args.main_file; fprintf oc "\t@echo \"Wrote file %s\"\n" mfile; fprintf oc "\n" let dump_dot_target oc args = let target = sprintf "./dot/%s.dot" args.prefix in fprintf oc "dot: %s\n\n" target; fprintf oc "%s: %s $(GEN_CAPH_SRCS)\n" target args.main_file; fprintf oc "\t$(CAPHC) -target_dir ./dot -prefix %s -I %s/lib/caph -dot $(DOT_OPTS) %s\n\n" args.prefix args.caph_dir args.main_file; fprintf oc "dot.show: %s\n" target; fprintf oc "\t$(GRAPHVIZ) %s\n\n" target let dump_xdf_target oc args = let target = sprintf "./xdf/%s.xdf" args.prefix in fprintf oc "xdf: %s\n\n" target; fprintf oc "%s: %s $(GEN_CAPH_SRCS)\n" target args.main_file; fprintf oc "\t$(CAPHC) -target_dir ./xdf -prefix %s -I %s/lib/caph -xdf $(XDF_OPTS) %s\n\n" args.prefix args.caph_dir args.main_file let dump_dif_target oc args = let target = sprintf "./dif/%s.dif" args.prefix in fprintf oc "dif: %s\n\n" target; fprintf oc "%s: %s $(GEN_CAPH_SRCS)\n" target args.main_file; fprintf oc "\t$(CAPHC) -target_dir ./dif -prefix %s -I %s/lib/caph -dif $(DIF_OPTS) %s\n\n" args.prefix args.caph_dir args.main_file let dump_relay_target oc args target sub = fprintf oc "%s.%s:\n" target sub; fprintf oc "\t(cd %s; make %s CAPH=%s)\n" target sub args.caph_dir let error msg = eprintf "** error: %s" msg; exit 1 let main () = Arg.parse options_spec anonymous usage; if args.caph_dir = "" then begin try args.caph_dir <- Sys.getenv "CAPH" with Not_found -> error "the CAPH environment variable is not set. Please set it or use the [-caph_dir] option\n" end; if args.proj_file = "" then error usage; if not (Sys.file_exists args.proj_file) then error ("cannot find file " ^ args.proj_file); if not (Sys.file_exists args.main_file) then error ("cannot find file " ^ args.main_file); try let oc = open_out args.output_file in dump_banner oc; args.prefix <- Filename.remove_extension (Filename.basename args.main_file); fprintf oc "include %s/lib/etc/Makefile.core\n\n" args.caph_dir; fprintf oc "-include %s\n\n" args.proj_file; dump_self_target oc args; fprintf oc "\n"; dump_dot_target oc args; fprintf oc ".PHONY: ./sim/Makefile ./systemc/Makefile ./vhdl/Makefile\n"; fprintf oc "makefiles: %s\n\n" (Misc.string_of_list (function t -> t ^ ".makefile") " " ["sim"; "systemc"; "vhdl"]); List.iter (dump_makef_target oc args) ["sim"; "systemc"; "vhdl"]; List.iter (dump_relay_target oc args "sim") ["run"; "show"; "save"; "clean"; "clobber"]; fprintf oc "\n"; List.iter (dump_relay_target oc args "systemc") ["code"; "exe"; "run"; "show"; "save"; "check"; "clean"; "clobber"]; fprintf oc "\n"; List.iter (dump_relay_target oc args "vhdl") ["bin"; "code"; "exe"; "run"; "show"; "save"; "check"; "viewtrace"; "viewvcdtrace"; "clean"; "clobber"]; fprintf oc "\n"; dump_xdf_target oc args; fprintf oc "\n"; dump_dif_target oc args; fprintf oc "\n"; fprintf oc "clean:\n"; List.iter (function t -> fprintf oc "\t@if [ -e %s/Makefile ]; then (cd %s; make clean CAPH=%s); fi\n" t t args.caph_dir) ["sim"; "systemc"; "vhdl"]; fprintf oc "\t@$(RM) caph.output\n"; fprintf oc "\t@$(RM) *_mocs.dat\n"; fprintf oc "\t@$(RM) dot/*\n"; fprintf oc "\t@$(RM) xdf/*\n"; fprintf oc "\t@$(RM) dif/*\n"; fprintf oc "\t@$(RM) $(GEN_CAPH_SRCS)\n"; fprintf oc "\n"; fprintf oc "clobber: clean\n"; List.iter (function t -> fprintf oc "\t@if [ -e %s/Makefile ]; then (cd %s; make clobber CAPH=%s); fi\n" t t args.caph_dir) ["sim";"systemc";"vhdl"]; List.iter (function t -> fprintf oc "\t@$(RM) Makefile.%s\n" t) ["sim"; "systemc"; "vhdl"]; fprintf oc "\t@$(RM) $(GEN_CAPH_SRCS)\n"; fprintf oc "\t@$(RM) fifo_stats.dat io_monitor.dat\n"; fprintf oc "\t@$(RMDIR) xdf dif\n"; fprintf oc "\t@$(RM) *~\n"; close_out oc; printf "Wrote file %s\n" args.output_file with | Sys.Break -> flush stderr; exit 5 | Sys_error msg -> eprintf "Input/output error: %s.\n" msg; flush stderr; exit 6 | e -> eprintf "Internal error: %s.\n" (Printexc.to_string e); flush stderr; exit 7 let _ = Printexc.print main ()
null
https://raw.githubusercontent.com/jserot/caph/2b3b241f0c32aa4fcaf60d4b8529956cca8aa6b1/tools/caphmake.ml
ocaml
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / / * * / / * This file is part of the CAPH Compiler distribution * / / * -bpclermont.fr * / / * * / / * Jocelyn SEROT * / / * * / / * * / / * Copyright 2011 - 2018 . All rights reserved . * / / * This file is distributed under the terms of the GNU Library General Public License * / / * with the special exception on linking described in file .. /LICENSE . * / / * * / / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /* */ /* This file is part of the CAPH Compiler distribution */ /* -bpclermont.fr */ /* */ /* Jocelyn SEROT */ /* */ /* */ /* Copyright 2011-2018 Jocelyn SEROT. All rights reserved. */ /* This file is distributed under the terms of the GNU Library General Public License */ /* with the special exception on linking described in file ../LICENSE. */ /* */ /***************************************************************************************) Top - level Makefile generator - since 2.8.1 open Printf type t_args = { mutable prefix: string; mutable main_file: string; mutable proj_file: string; mutable caph_dir: string; mutable output_file: string; } let args = { prefix="main"; main_file="main.cph"; proj_file="main.proj"; caph_dir=""; output_file="Makefile"; } let options_spec = [ "-main", Arg.String (function s -> args.main_file <- s), "set name of the top source file (default: main.cph)"; "-caph_dir", Arg.String (function s -> args.caph_dir <- s), "set path to the CAPH install directory (default: got from the CAPH environment variable)"; "-o", Arg.String (function s -> args.output_file <- s), "set name of the output file (default: Makefile)" ] let usage = "usage: caphmake [-main fname] [-caph_dir path] [-o fname] [proj_file]" let anonymous f = args.proj_file <- f let dump_banner oc = Printf.fprintf oc "## ###############################################################################\n"; Printf.fprintf oc "## This file has been automatically generated with command :\n"; Printf.fprintf oc "## %s\n" (Misc.string_of_list (function i -> i) " " (Array.to_list Sys.argv)); Printf.fprintf oc "## ###############################################################################\n\n" let dump_self_target oc args = let args' = Array.to_list Sys.argv in fprintf oc "caphmake:\n"; fprintf oc "\t%s %s\n" (Misc.string_of_list (fun i -> i) " " args') (if List.exists (fun s -> String.sub s 0 9 = "-caph_dir") args' then "" else "-caph_dir=" ^ args.caph_dir) let dump_makef_target oc args target = let mfile = sprintf "./%s/Makefile" target in let abbrev = function "systemc" -> "SC" | s -> String.uppercase_ascii s in fprintf oc "%s.makefile: %s\n" target mfile; fprintf oc "%s: %s $(GEN_CAPH_SRCS)\n" mfile args.main_file; fprintf oc "\t$(CAPHC) -target_dir ./%s -I %s/lib/caph -make -%s $(%s_OPTS) %s\n" target args.caph_dir target (abbrev target) args.main_file; fprintf oc "\t@echo \"Wrote file %s\"\n" mfile; fprintf oc "\n" let dump_dot_target oc args = let target = sprintf "./dot/%s.dot" args.prefix in fprintf oc "dot: %s\n\n" target; fprintf oc "%s: %s $(GEN_CAPH_SRCS)\n" target args.main_file; fprintf oc "\t$(CAPHC) -target_dir ./dot -prefix %s -I %s/lib/caph -dot $(DOT_OPTS) %s\n\n" args.prefix args.caph_dir args.main_file; fprintf oc "dot.show: %s\n" target; fprintf oc "\t$(GRAPHVIZ) %s\n\n" target let dump_xdf_target oc args = let target = sprintf "./xdf/%s.xdf" args.prefix in fprintf oc "xdf: %s\n\n" target; fprintf oc "%s: %s $(GEN_CAPH_SRCS)\n" target args.main_file; fprintf oc "\t$(CAPHC) -target_dir ./xdf -prefix %s -I %s/lib/caph -xdf $(XDF_OPTS) %s\n\n" args.prefix args.caph_dir args.main_file let dump_dif_target oc args = let target = sprintf "./dif/%s.dif" args.prefix in fprintf oc "dif: %s\n\n" target; fprintf oc "%s: %s $(GEN_CAPH_SRCS)\n" target args.main_file; fprintf oc "\t$(CAPHC) -target_dir ./dif -prefix %s -I %s/lib/caph -dif $(DIF_OPTS) %s\n\n" args.prefix args.caph_dir args.main_file let dump_relay_target oc args target sub = fprintf oc "%s.%s:\n" target sub; fprintf oc "\t(cd %s; make %s CAPH=%s)\n" target sub args.caph_dir let error msg = eprintf "** error: %s" msg; exit 1 let main () = Arg.parse options_spec anonymous usage; if args.caph_dir = "" then begin try args.caph_dir <- Sys.getenv "CAPH" with Not_found -> error "the CAPH environment variable is not set. Please set it or use the [-caph_dir] option\n" end; if args.proj_file = "" then error usage; if not (Sys.file_exists args.proj_file) then error ("cannot find file " ^ args.proj_file); if not (Sys.file_exists args.main_file) then error ("cannot find file " ^ args.main_file); try let oc = open_out args.output_file in dump_banner oc; args.prefix <- Filename.remove_extension (Filename.basename args.main_file); fprintf oc "include %s/lib/etc/Makefile.core\n\n" args.caph_dir; fprintf oc "-include %s\n\n" args.proj_file; dump_self_target oc args; fprintf oc "\n"; dump_dot_target oc args; fprintf oc ".PHONY: ./sim/Makefile ./systemc/Makefile ./vhdl/Makefile\n"; fprintf oc "makefiles: %s\n\n" (Misc.string_of_list (function t -> t ^ ".makefile") " " ["sim"; "systemc"; "vhdl"]); List.iter (dump_makef_target oc args) ["sim"; "systemc"; "vhdl"]; List.iter (dump_relay_target oc args "sim") ["run"; "show"; "save"; "clean"; "clobber"]; fprintf oc "\n"; List.iter (dump_relay_target oc args "systemc") ["code"; "exe"; "run"; "show"; "save"; "check"; "clean"; "clobber"]; fprintf oc "\n"; List.iter (dump_relay_target oc args "vhdl") ["bin"; "code"; "exe"; "run"; "show"; "save"; "check"; "viewtrace"; "viewvcdtrace"; "clean"; "clobber"]; fprintf oc "\n"; dump_xdf_target oc args; fprintf oc "\n"; dump_dif_target oc args; fprintf oc "\n"; fprintf oc "clean:\n"; List.iter (function t -> fprintf oc "\t@if [ -e %s/Makefile ]; then (cd %s; make clean CAPH=%s); fi\n" t t args.caph_dir) ["sim"; "systemc"; "vhdl"]; fprintf oc "\t@$(RM) caph.output\n"; fprintf oc "\t@$(RM) *_mocs.dat\n"; fprintf oc "\t@$(RM) dot/*\n"; fprintf oc "\t@$(RM) xdf/*\n"; fprintf oc "\t@$(RM) dif/*\n"; fprintf oc "\t@$(RM) $(GEN_CAPH_SRCS)\n"; fprintf oc "\n"; fprintf oc "clobber: clean\n"; List.iter (function t -> fprintf oc "\t@if [ -e %s/Makefile ]; then (cd %s; make clobber CAPH=%s); fi\n" t t args.caph_dir) ["sim";"systemc";"vhdl"]; List.iter (function t -> fprintf oc "\t@$(RM) Makefile.%s\n" t) ["sim"; "systemc"; "vhdl"]; fprintf oc "\t@$(RM) $(GEN_CAPH_SRCS)\n"; fprintf oc "\t@$(RM) fifo_stats.dat io_monitor.dat\n"; fprintf oc "\t@$(RMDIR) xdf dif\n"; fprintf oc "\t@$(RM) *~\n"; close_out oc; printf "Wrote file %s\n" args.output_file with | Sys.Break -> flush stderr; exit 5 | Sys_error msg -> eprintf "Input/output error: %s.\n" msg; flush stderr; exit 6 | e -> eprintf "Internal error: %s.\n" (Printexc.to_string e); flush stderr; exit 7 let _ = Printexc.print main ()
a6c03039ba5c2c643292379a4040c6e9ed4394238d720e606bdfda756b0685fe
ghc/packages-dph
Vectorised.hs
{-# LANGUAGE ParallelArrays #-} {-# OPTIONS -fvectorise #-} module Vectorised (treeReversePA) where import Data.Array.Parallel import Data.Array.Parallel.Prelude.Int as I import Data.Array.Parallel.Prelude.Bool import qualified Prelude as P treeReversePA :: PArray Int -> PArray Int # NOINLINE treeReversePA # treeReversePA ps = toPArrayP (treeReverse (fromPArrayP ps)) -- | Reverse the elements in an array using a tree. treeReverse :: [:Int:] -> [:Int:] # NOINLINE treeReverse # treeReverse xx | lengthP xx I.== 1 = xx | otherwise = let len = lengthP xx half = len `div` 2 s1 = sliceP 0 half xx s2 = sliceP half half xx in concatP (mapP treeReverse [: s2, s1 :])
null
https://raw.githubusercontent.com/ghc/packages-dph/64eca669f13f4d216af9024474a3fc73ce101793/dph-examples/examples/smoke/sharing/Reverse/Vectorised.hs
haskell
# LANGUAGE ParallelArrays # # OPTIONS -fvectorise # | Reverse the elements in an array using a tree.
module Vectorised (treeReversePA) where import Data.Array.Parallel import Data.Array.Parallel.Prelude.Int as I import Data.Array.Parallel.Prelude.Bool import qualified Prelude as P treeReversePA :: PArray Int -> PArray Int # NOINLINE treeReversePA # treeReversePA ps = toPArrayP (treeReverse (fromPArrayP ps)) treeReverse :: [:Int:] -> [:Int:] # NOINLINE treeReverse # treeReverse xx | lengthP xx I.== 1 = xx | otherwise = let len = lengthP xx half = len `div` 2 s1 = sliceP 0 half xx s2 = sliceP half half xx in concatP (mapP treeReverse [: s2, s1 :])
4a63f8a7d6e649f041aec46e2aeb998ac91e277b0d9148d3b44e6fc132c46476
static-analysis-engineering/codehawk
jCHInstruction.mli
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Java Analyzer Author : ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2005 - 2020 Kestrel Technology LLC 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 , 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 . = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Java Analyzer Author: Arnaud Venet ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2005-2020 Kestrel Technology LLC 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. ============================================================================= *) (* jchlib *) open JCHBasicTypesAPI open JCHRawClass val opcodes2code : constant_t array -> raw_opcode_t array -> opcode_t array val code2opcodes : constant_t DynArray.t -> opcode_t array -> raw_opcode_t array
null
https://raw.githubusercontent.com/static-analysis-engineering/codehawk/98ced4d5e6d7989575092df232759afc2cb851f6/CodeHawk/CHJ/jchlib/jCHInstruction.mli
ocaml
jchlib
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Java Analyzer Author : ------------------------------------------------------------------------------ The MIT License ( MIT ) Copyright ( c ) 2005 - 2020 Kestrel Technology LLC 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 , 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 . = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CodeHawk Java Analyzer Author: Arnaud Venet ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2005-2020 Kestrel Technology LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ============================================================================= *) open JCHBasicTypesAPI open JCHRawClass val opcodes2code : constant_t array -> raw_opcode_t array -> opcode_t array val code2opcodes : constant_t DynArray.t -> opcode_t array -> raw_opcode_t array
bcf4632b78b2e3c287a9d43a95ddf7b06c6d4af07fa3fe0cb01b8cbdd1d46d82
fumieval/witherable
tests.hs
# LANGUAGE CPP # # LANGUAGE GeneralizedNewtypeDeriving # {-# LANGUAGE DeriveTraversable #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # module Main (main) where import Control.Arrow (first) import Control.Monad ((<=<)) import Control.Monad.Trans.State (State, runState, state) import Data.Hashable (Hashable) import Data.Coerce (coerce) import Data.Function (on) import Data.Functor.Compose (Compose (..)) import Data.List (nub, nubBy) import Data.Maybe (fromMaybe) import Data.Proxy (Proxy (..)) import Data.Typeable (Typeable, typeRep) import Test.QuickCheck (Arbitrary (..), Fun, Property, applyFun, Function (..), functionMap, CoArbitrary, (===)) import Test.QuickCheck.Instances () import Test.Tasty (defaultMain, testGroup, TestTree) import Test.Tasty.QuickCheck (testProperty) import qualified Data.HashMap.Lazy as HashMap import qualified Data.IntMap as IntMap import qualified Data.Map.Lazy as Map import qualified Data.Vector as V import qualified Data.Sequence as Seq import Witherable import Prelude hiding (filter) main :: IO () main = defaultMain $ testGroup "witherable" [ testGroup "Filterable" [ filterableLaws (Proxy @[]) , filterableLaws (Proxy @Maybe) , filterableLaws (Proxy @(Either String)) , filterableLaws (Proxy @V.Vector) , filterableLaws (Proxy @Seq.Seq) , filterableLaws (Proxy @IntMap.IntMap) , filterableLaws (Proxy @(Map.Map K)) , filterableLaws (Proxy @(HashMap.HashMap K)) , filterableLaws (Proxy @Wicked) ] , testGroup "Witherable" [ witherableLaws (Proxy @[]) , witherableLaws (Proxy @Maybe) , witherableLaws (Proxy @(Either String)) , witherableLaws (Proxy @V.Vector) , witherableLaws (Proxy @Seq.Seq) #if MIN_VERSION_containers(0,6,3) -- traverse @IntMap is broken , witherableLaws (Proxy @IntMap.IntMap) #endif , witherableLaws (Proxy @(Map.Map K)) , witherableLaws (Proxy @(HashMap.HashMap K)) Wicked is not , see #issuecomment-834631975 -- , witherableLaws (Proxy @Wicked) ] , nubProperties ] ------------------------------------------------------------------------------- laws ------------------------------------------------------------------------------- filterableLaws :: forall f. ( Filterable f, Typeable f , Arbitrary (f A), Show (f A), Eq (f A) , Arbitrary (f (Maybe A)), Show (f (Maybe A)) , Show (f B), Eq (f B), Show (f C), Eq (f C) ) => Proxy f -> TestTree filterableLaws p = testGroup (show (typeRep p)) [ testProperty "conservation" prop_conservation , testProperty "composition" prop_composition , testProperty "default filter" prop_default_filter , testProperty "default mapMaybe" prop_default_mapMaybe , testProperty "default catMaybes" prop_default_catMaybes ] where prop_conservation :: Fun A B -> f A -> Property prop_conservation f' xs = mapMaybe (Just . f) xs === fmap f xs where f = applyFun f' prop_composition :: Fun B (Maybe C) -> Fun A (Maybe B) -> f A -> Property prop_composition f' g' xs = mapMaybe f (mapMaybe g xs) === mapMaybe (f <=< g) xs where f = applyFun f' g = applyFun g' prop_default_filter :: Fun A Bool -> f A -> Property prop_default_filter f' xs = filter f xs === mapMaybe (\a -> if f a then Just a else Nothing) xs where f = applyFun f' prop_default_mapMaybe :: Fun A (Maybe B) -> f A -> Property prop_default_mapMaybe f' xs = mapMaybe f xs === catMaybes (fmap f xs) where f = applyFun f' prop_default_catMaybes :: f (Maybe A) -> Property prop_default_catMaybes xs = catMaybes xs === mapMaybe id xs ------------------------------------------------------------------------------- -- Witherable laws ------------------------------------------------------------------------------- witherableLaws :: forall f. ( Witherable f, Typeable f , Arbitrary (f A), Show (f A), Eq (f A) , Arbitrary (f (Maybe A)), Show (f (Maybe A)) , Show (f B), Eq (f B), Show (f C), Eq (f C) ) => Proxy f -> TestTree witherableLaws p = testGroup (show (typeRep p)) [ testProperty "default wither" prop_default_wither , testProperty "default witherM" prop_default_witherM , testProperty "default filterA" prop_default_filterA , testProperty "identity" prop_identity , testProperty "composition" prop_composition ] where prop_default_wither :: S -> Fun (A, S) (Maybe B, S) -> f A -> Property prop_default_wither s0 f' xs = equalState s0 xs (wither f) (fmap catMaybes . traverse f) where f :: A -> State S (Maybe B) f a = state $ \s -> applyFun f' (a, s) prop_default_witherM :: S -> Fun (A, S) (Maybe B, S) -> f A -> Property prop_default_witherM s0 f' xs = equalState s0 xs (witherM f) (wither f) where f a = state $ \s -> applyFun f' (a, s) prop_default_filterA :: S -> Fun (A, S) (Bool, S) -> f A -> Property prop_default_filterA s0 f' xs = equalState s0 xs (filterA f) (wither (\a -> (\b -> if b then Just a else Nothing) <$> f a)) where f a = state $ \s -> applyFun f' (a, s) prop_identity :: S -> Fun (A, S) (B, S) -> f A -> Property prop_identity s0 f' xs = equalState s0 xs (wither (fmap Just . f)) (traverse f) where f a = state $ \s -> applyFun f' (a, s) prop_composition :: S -> S -> Fun (B, S) (Maybe C, S) -> Fun (A, S) (Maybe B, S) -> f A -> Property prop_composition s0 s1 f' g' xs = equalStateC s0 s1 xs (Compose . fmap (wither f) . wither g) (wither (Compose . fmap (wither f) . g)) where f a = state $ \s -> applyFun f' (a, s) g b = state $ \s -> applyFun g' (b, s) equalState :: (Eq b, Show b) => S -> a -> (a -> State S b) -> (a -> State S b) -> Property equalState s0 xs f g = runState (f xs) s0 === runState (g xs) s0 equalStateC :: forall a b. (Eq b, Show b) => S -> S -> a -> (a -> Compose (State S) (State S) b) -> (a -> Compose (State S) (State S) b) -> Property equalStateC s0 s1 xs f g = run (f xs) === run (g xs) where run :: Compose (State S) (State S) b -> ((b, S), S) run m = first (\x -> runState x s1) (runState (getCompose m) s0) ------------------------------------------------------------------------------- " laws " ------------------------------------------------------------------------------- nubProperties :: TestTree nubProperties = testGroup "nub" [ testProperty "ordNub" prop_ordNub , testProperty "ordNubOn" prop_ordNubOn , testProperty "hashNub" prop_hashNub , testProperty "hashNubOn" prop_hashNubOn , testProperty "ordNub is lazy" prop_lazy_ordNub , testProperty "hashNub is lazy" prop_lazy_hashNub ] where prop_ordNub :: [A] -> Property prop_ordNub xs = nub xs === ordNub xs prop_hashNub :: [A] -> Property prop_hashNub xs = nub xs === hashNub xs prop_ordNubOn :: Fun A B -> [A] -> Property prop_ordNubOn f' xs = nubBy ((==) `on` f) xs === ordNubOn f xs where f = applyFun f' prop_hashNubOn :: Fun A B -> [A] -> Property prop_hashNubOn f' xs = nubBy ((==) `on` f) xs === hashNubOn f xs where f = applyFun f' prop_lazy_ordNub :: Property prop_lazy_ordNub = take 3 (ordNub ('x' : 'y' : 'z' : 'z' : error "bottom")) === "xyz" prop_lazy_hashNub :: Property prop_lazy_hashNub = take 3 (hashNub ('x' : 'y' : 'z' : 'z' : error "bottom")) === "xyz" ------------------------------------------------------------------------------- -- "Poly" ------------------------------------------------------------------------------- newtype A = A Int deriving (Eq, Ord, Show, Hashable, Arbitrary, CoArbitrary) instance Function A where function = functionMap coerce A newtype B = B Int deriving (Eq, Ord, Show, Hashable, Arbitrary, CoArbitrary) instance Function B where function = functionMap coerce B newtype C = C Int deriving (Eq, Ord, Show, Hashable, Arbitrary, CoArbitrary) instance Function C where function = functionMap coerce C newtype K = K Int deriving (Eq, Ord, Show, Hashable, Arbitrary, CoArbitrary) instance Function K where function = functionMap coerce K newtype S = S Int deriving (Eq, Ord, Show, Hashable, Arbitrary, CoArbitrary) instance Function S where function = functionMap coerce S ------------------------------------------------------------------------------- -- Wicked ------------------------------------------------------------------------------- newtype Wicked a = W [a] deriving (Eq, Show, Functor, Foldable, Traversable) instance Filterable Wicked where mapMaybe f ( W [ a1,a2 , ... ] ) = W [ b1 , b2 , ... ] -- if all of [f a1, f a2, ...] are Just. Otherwise, it returns (W []). mapMaybe f = fromMaybe (W []) . traverse f default implementation in terms of instance Witherable Wicked instance Arbitrary a => Arbitrary (Wicked a) where arbitrary = W <$> arbitrary shrink (W xs) = map W (shrink xs)
null
https://raw.githubusercontent.com/fumieval/witherable/b2d475a5f9c2dd2c498350b50c20b0170ba32d3a/witherable/tests/tests.hs
haskell
# LANGUAGE DeriveTraversable # traverse @IntMap is broken , witherableLaws (Proxy @Wicked) ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- Witherable laws ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- "Poly" ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- Wicked ----------------------------------------------------------------------------- if all of [f a1, f a2, ...] are Just. Otherwise, it returns (W []).
# LANGUAGE CPP # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # module Main (main) where import Control.Arrow (first) import Control.Monad ((<=<)) import Control.Monad.Trans.State (State, runState, state) import Data.Hashable (Hashable) import Data.Coerce (coerce) import Data.Function (on) import Data.Functor.Compose (Compose (..)) import Data.List (nub, nubBy) import Data.Maybe (fromMaybe) import Data.Proxy (Proxy (..)) import Data.Typeable (Typeable, typeRep) import Test.QuickCheck (Arbitrary (..), Fun, Property, applyFun, Function (..), functionMap, CoArbitrary, (===)) import Test.QuickCheck.Instances () import Test.Tasty (defaultMain, testGroup, TestTree) import Test.Tasty.QuickCheck (testProperty) import qualified Data.HashMap.Lazy as HashMap import qualified Data.IntMap as IntMap import qualified Data.Map.Lazy as Map import qualified Data.Vector as V import qualified Data.Sequence as Seq import Witherable import Prelude hiding (filter) main :: IO () main = defaultMain $ testGroup "witherable" [ testGroup "Filterable" [ filterableLaws (Proxy @[]) , filterableLaws (Proxy @Maybe) , filterableLaws (Proxy @(Either String)) , filterableLaws (Proxy @V.Vector) , filterableLaws (Proxy @Seq.Seq) , filterableLaws (Proxy @IntMap.IntMap) , filterableLaws (Proxy @(Map.Map K)) , filterableLaws (Proxy @(HashMap.HashMap K)) , filterableLaws (Proxy @Wicked) ] , testGroup "Witherable" [ witherableLaws (Proxy @[]) , witherableLaws (Proxy @Maybe) , witherableLaws (Proxy @(Either String)) , witherableLaws (Proxy @V.Vector) , witherableLaws (Proxy @Seq.Seq) #if MIN_VERSION_containers(0,6,3) , witherableLaws (Proxy @IntMap.IntMap) #endif , witherableLaws (Proxy @(Map.Map K)) , witherableLaws (Proxy @(HashMap.HashMap K)) Wicked is not , see #issuecomment-834631975 ] , nubProperties ] laws filterableLaws :: forall f. ( Filterable f, Typeable f , Arbitrary (f A), Show (f A), Eq (f A) , Arbitrary (f (Maybe A)), Show (f (Maybe A)) , Show (f B), Eq (f B), Show (f C), Eq (f C) ) => Proxy f -> TestTree filterableLaws p = testGroup (show (typeRep p)) [ testProperty "conservation" prop_conservation , testProperty "composition" prop_composition , testProperty "default filter" prop_default_filter , testProperty "default mapMaybe" prop_default_mapMaybe , testProperty "default catMaybes" prop_default_catMaybes ] where prop_conservation :: Fun A B -> f A -> Property prop_conservation f' xs = mapMaybe (Just . f) xs === fmap f xs where f = applyFun f' prop_composition :: Fun B (Maybe C) -> Fun A (Maybe B) -> f A -> Property prop_composition f' g' xs = mapMaybe f (mapMaybe g xs) === mapMaybe (f <=< g) xs where f = applyFun f' g = applyFun g' prop_default_filter :: Fun A Bool -> f A -> Property prop_default_filter f' xs = filter f xs === mapMaybe (\a -> if f a then Just a else Nothing) xs where f = applyFun f' prop_default_mapMaybe :: Fun A (Maybe B) -> f A -> Property prop_default_mapMaybe f' xs = mapMaybe f xs === catMaybes (fmap f xs) where f = applyFun f' prop_default_catMaybes :: f (Maybe A) -> Property prop_default_catMaybes xs = catMaybes xs === mapMaybe id xs witherableLaws :: forall f. ( Witherable f, Typeable f , Arbitrary (f A), Show (f A), Eq (f A) , Arbitrary (f (Maybe A)), Show (f (Maybe A)) , Show (f B), Eq (f B), Show (f C), Eq (f C) ) => Proxy f -> TestTree witherableLaws p = testGroup (show (typeRep p)) [ testProperty "default wither" prop_default_wither , testProperty "default witherM" prop_default_witherM , testProperty "default filterA" prop_default_filterA , testProperty "identity" prop_identity , testProperty "composition" prop_composition ] where prop_default_wither :: S -> Fun (A, S) (Maybe B, S) -> f A -> Property prop_default_wither s0 f' xs = equalState s0 xs (wither f) (fmap catMaybes . traverse f) where f :: A -> State S (Maybe B) f a = state $ \s -> applyFun f' (a, s) prop_default_witherM :: S -> Fun (A, S) (Maybe B, S) -> f A -> Property prop_default_witherM s0 f' xs = equalState s0 xs (witherM f) (wither f) where f a = state $ \s -> applyFun f' (a, s) prop_default_filterA :: S -> Fun (A, S) (Bool, S) -> f A -> Property prop_default_filterA s0 f' xs = equalState s0 xs (filterA f) (wither (\a -> (\b -> if b then Just a else Nothing) <$> f a)) where f a = state $ \s -> applyFun f' (a, s) prop_identity :: S -> Fun (A, S) (B, S) -> f A -> Property prop_identity s0 f' xs = equalState s0 xs (wither (fmap Just . f)) (traverse f) where f a = state $ \s -> applyFun f' (a, s) prop_composition :: S -> S -> Fun (B, S) (Maybe C, S) -> Fun (A, S) (Maybe B, S) -> f A -> Property prop_composition s0 s1 f' g' xs = equalStateC s0 s1 xs (Compose . fmap (wither f) . wither g) (wither (Compose . fmap (wither f) . g)) where f a = state $ \s -> applyFun f' (a, s) g b = state $ \s -> applyFun g' (b, s) equalState :: (Eq b, Show b) => S -> a -> (a -> State S b) -> (a -> State S b) -> Property equalState s0 xs f g = runState (f xs) s0 === runState (g xs) s0 equalStateC :: forall a b. (Eq b, Show b) => S -> S -> a -> (a -> Compose (State S) (State S) b) -> (a -> Compose (State S) (State S) b) -> Property equalStateC s0 s1 xs f g = run (f xs) === run (g xs) where run :: Compose (State S) (State S) b -> ((b, S), S) run m = first (\x -> runState x s1) (runState (getCompose m) s0) " laws " nubProperties :: TestTree nubProperties = testGroup "nub" [ testProperty "ordNub" prop_ordNub , testProperty "ordNubOn" prop_ordNubOn , testProperty "hashNub" prop_hashNub , testProperty "hashNubOn" prop_hashNubOn , testProperty "ordNub is lazy" prop_lazy_ordNub , testProperty "hashNub is lazy" prop_lazy_hashNub ] where prop_ordNub :: [A] -> Property prop_ordNub xs = nub xs === ordNub xs prop_hashNub :: [A] -> Property prop_hashNub xs = nub xs === hashNub xs prop_ordNubOn :: Fun A B -> [A] -> Property prop_ordNubOn f' xs = nubBy ((==) `on` f) xs === ordNubOn f xs where f = applyFun f' prop_hashNubOn :: Fun A B -> [A] -> Property prop_hashNubOn f' xs = nubBy ((==) `on` f) xs === hashNubOn f xs where f = applyFun f' prop_lazy_ordNub :: Property prop_lazy_ordNub = take 3 (ordNub ('x' : 'y' : 'z' : 'z' : error "bottom")) === "xyz" prop_lazy_hashNub :: Property prop_lazy_hashNub = take 3 (hashNub ('x' : 'y' : 'z' : 'z' : error "bottom")) === "xyz" newtype A = A Int deriving (Eq, Ord, Show, Hashable, Arbitrary, CoArbitrary) instance Function A where function = functionMap coerce A newtype B = B Int deriving (Eq, Ord, Show, Hashable, Arbitrary, CoArbitrary) instance Function B where function = functionMap coerce B newtype C = C Int deriving (Eq, Ord, Show, Hashable, Arbitrary, CoArbitrary) instance Function C where function = functionMap coerce C newtype K = K Int deriving (Eq, Ord, Show, Hashable, Arbitrary, CoArbitrary) instance Function K where function = functionMap coerce K newtype S = S Int deriving (Eq, Ord, Show, Hashable, Arbitrary, CoArbitrary) instance Function S where function = functionMap coerce S newtype Wicked a = W [a] deriving (Eq, Show, Functor, Foldable, Traversable) instance Filterable Wicked where mapMaybe f ( W [ a1,a2 , ... ] ) = W [ b1 , b2 , ... ] mapMaybe f = fromMaybe (W []) . traverse f default implementation in terms of instance Witherable Wicked instance Arbitrary a => Arbitrary (Wicked a) where arbitrary = W <$> arbitrary shrink (W xs) = map W (shrink xs)
1e8fe42c851d09f590ff50bfb73c15ffbba80f074b4a842d9cf397480ed89145
mzp/coq-ruby
g_natsyntax.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 : g_natsyntax.mli 11087 2008 - 06 - 10 13:29:52Z letouzey $ i (* Nice syntax for naturals. *) open Notation val nat_of_int : Bigint.bigint prim_token_interpreter
null
https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/parsing/g_natsyntax.mli
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** Nice syntax for naturals.
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * i $ I d : g_natsyntax.mli 11087 2008 - 06 - 10 13:29:52Z letouzey $ i open Notation val nat_of_int : Bigint.bigint prim_token_interpreter
14dd51878dddd79a829d201e7349d3cb7a0efce31d40b36814547fe49d138037
clj-commons/seesaw
style.clj
Copyright ( c ) , 2011 . 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 seesaw.test.style (:use seesaw.style [seesaw.core :only [border-panel label button config text]] [seesaw.color :only [to-color]]) (:use [lazytest.describe :only (describe it testing)] [lazytest.expect :only (expect)])) (describe apply-stylesheet (it "returns its input" (let [lbl (label)] (expect (= lbl (apply-stylesheet lbl {}))))) (it "changes styles of widget for rules that match" (let [lbl (label :id :lbl) btn-a (button :class :btn) btn-b (button :class :btn :id :btn-b) p (border-panel :center lbl :north btn-a :south btn-b)] (apply-stylesheet p {[:#lbl] { :background :aliceblue :text "hi"} [:.btn] { :foreground :red } [:#btn-b] {:text "B"}}) (expect (= (to-color :aliceblue) (config lbl :background))) (expect (= "hi" (text lbl))) (expect (= "B" (text btn-b))) (expect (= (to-color :red) (config btn-a :foreground))) (expect (= (to-color :red) (config btn-b :foreground))))))
null
https://raw.githubusercontent.com/clj-commons/seesaw/4ca89d0dcdf0557d99d5fa84202b7cc6e2e92263/test/seesaw/test/style.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software.
Copyright ( c ) , 2011 . All rights reserved . (ns seesaw.test.style (:use seesaw.style [seesaw.core :only [border-panel label button config text]] [seesaw.color :only [to-color]]) (:use [lazytest.describe :only (describe it testing)] [lazytest.expect :only (expect)])) (describe apply-stylesheet (it "returns its input" (let [lbl (label)] (expect (= lbl (apply-stylesheet lbl {}))))) (it "changes styles of widget for rules that match" (let [lbl (label :id :lbl) btn-a (button :class :btn) btn-b (button :class :btn :id :btn-b) p (border-panel :center lbl :north btn-a :south btn-b)] (apply-stylesheet p {[:#lbl] { :background :aliceblue :text "hi"} [:.btn] { :foreground :red } [:#btn-b] {:text "B"}}) (expect (= (to-color :aliceblue) (config lbl :background))) (expect (= "hi" (text lbl))) (expect (= "B" (text btn-b))) (expect (= (to-color :red) (config btn-a :foreground))) (expect (= (to-color :red) (config btn-b :foreground))))))
19a3c6d89f181a1d51e2664768e78d981aa2ab46d7c16ffd5a701b9dce29dbea
Perry961002/SICP
exe4.11-new-frame.scm
;将框架表示为约束的表,每个约束是一个名字-值序对 (define (first-binding frame) (car frame)) (define (rest-binding frame) (cdr frame)) (define (add-binding-to-frame! var val frame) (cons (cons var val frame))) ;因为是序对的表,所以名字和值一定是对应的,添加新框架的话直接添加即可 (define (extend-environment new-frame base-env) (cons new-frame base-env)) 在环境中查找变量 (define (lookup-variable-value var env) (define (env-loop env) (define (scan frame) (cond ((null? frame) (env-loop (enclosing-environment env))) ((eq? val (car (first-binding frame))) (cdr (first-binding frame))) (else (scan (rest-binding frame))))) (if (eq? env the-empty-environment) (error "Unbound variable" var) (let ((frame (first-frame nev))) (scan frame)))) (env-loop env)) ;设置一个新值 (define (set-variable-value! var val env) (define (env-loop env) (define (scan frame) (cond ((null? frame) (env-loop (enclosing-environment env))) ((eq? var (car (first-binding frame))) (set-cdr! (first-binding frame) val)) (else (scan (rest-binding))))) (if (eq? env the-empty-environment) (error "Unbound variable -- SET" var) (let ((frame (first-frame env))) (scan frame)))) (env-loop env)) ;定义一个变量 (define (define-variable! var val env) (define (scan frame) (cond ((null? frame) (add-binding-to-frame! var val frame)) ((eq? var (first-binding frame)) (set-cdr! (first-binding frame) val)) (else (sacn (rest-binding frame))))) (scan (first-frame env)))
null
https://raw.githubusercontent.com/Perry961002/SICP/89d539e600a73bec42d350592f0ac626e041bf16/Chap4/exercise/exe4.11-new-frame.scm
scheme
将框架表示为约束的表,每个约束是一个名字-值序对 因为是序对的表,所以名字和值一定是对应的,添加新框架的话直接添加即可 设置一个新值 定义一个变量
(define (first-binding frame) (car frame)) (define (rest-binding frame) (cdr frame)) (define (add-binding-to-frame! var val frame) (cons (cons var val frame))) (define (extend-environment new-frame base-env) (cons new-frame base-env)) 在环境中查找变量 (define (lookup-variable-value var env) (define (env-loop env) (define (scan frame) (cond ((null? frame) (env-loop (enclosing-environment env))) ((eq? val (car (first-binding frame))) (cdr (first-binding frame))) (else (scan (rest-binding frame))))) (if (eq? env the-empty-environment) (error "Unbound variable" var) (let ((frame (first-frame nev))) (scan frame)))) (env-loop env)) (define (set-variable-value! var val env) (define (env-loop env) (define (scan frame) (cond ((null? frame) (env-loop (enclosing-environment env))) ((eq? var (car (first-binding frame))) (set-cdr! (first-binding frame) val)) (else (scan (rest-binding))))) (if (eq? env the-empty-environment) (error "Unbound variable -- SET" var) (let ((frame (first-frame env))) (scan frame)))) (env-loop env)) (define (define-variable! var val env) (define (scan frame) (cond ((null? frame) (add-binding-to-frame! var val frame)) ((eq? var (first-binding frame)) (set-cdr! (first-binding frame) val)) (else (sacn (rest-binding frame))))) (scan (first-frame env)))
cc4132a418d57810ba4eac43d091404fef12210dc964729cedd48ac7b67ada4a
na4zagin3/satyrographos
command_lockdown_save__invalid_opam_response.ml
module StdList = List open Satyrographos_testlib open TestLib open Shexp_process let files = Command_lockdown_save__opam.files let opam_response = { PrepareBin.list_result = {|***invalid,response,!!!|} } let env ~dest_dir:_ ~temp_dir : Satyrographos.Environment.t t = let open Shexp_process.Infix in let pkg_dir = FilePath.concat temp_dir "pkg" in let prepare_pkg = PrepareDist.empty pkg_dir >> prepare_files pkg_dir files in let empty_dist = FilePath.concat temp_dir "empty_dist" in let prepare_dist = PrepareDist.empty empty_dist in let opam_reg = FilePath.concat temp_dir "opam_reg" in let log_file = exec_log_file_path temp_dir in let prepare_opam_reg = PrepareOpamReg.(prepare opam_reg theanoFiles) >> PrepareOpamReg.(prepare opam_reg grcnumFiles) >> PrepareOpamReg.(prepare opam_reg classGreekFiles) >> PrepareOpamReg.(prepare opam_reg baseFiles) in let bin = FilePath.concat temp_dir "bin" in prepare_pkg >> prepare_dist >> prepare_opam_reg >> PrepareBin.prepare_bin ~opam_response bin log_file >>| read_env ~opam_reg ~dist_library_dir:empty_dist let () = let verbose = false in let main _env ~dest_dir:_ ~temp_dir ~outf:_ = let _name = Some "example-doc" in let dest_dir = FilePath.concat dest_dir " dest " in Satyrographos_command.Lockdown.save_lockdown ~verbose ~buildscript_path:(FilePath.concat temp_dir "pkg/Satyristes") in let post_dump_dirs ~dest_dir:_ ~temp_dir = let pkg_dir = FilePath.concat temp_dir "pkg" in [pkg_dir] in eval (test_install ~post_dump_dirs env main)
null
https://raw.githubusercontent.com/na4zagin3/satyrographos/9dbccf05138510c977a67c859bbbb48755470c7f/test/testcases/command_lockdown_save__invalid_opam_response.ml
ocaml
module StdList = List open Satyrographos_testlib open TestLib open Shexp_process let files = Command_lockdown_save__opam.files let opam_response = { PrepareBin.list_result = {|***invalid,response,!!!|} } let env ~dest_dir:_ ~temp_dir : Satyrographos.Environment.t t = let open Shexp_process.Infix in let pkg_dir = FilePath.concat temp_dir "pkg" in let prepare_pkg = PrepareDist.empty pkg_dir >> prepare_files pkg_dir files in let empty_dist = FilePath.concat temp_dir "empty_dist" in let prepare_dist = PrepareDist.empty empty_dist in let opam_reg = FilePath.concat temp_dir "opam_reg" in let log_file = exec_log_file_path temp_dir in let prepare_opam_reg = PrepareOpamReg.(prepare opam_reg theanoFiles) >> PrepareOpamReg.(prepare opam_reg grcnumFiles) >> PrepareOpamReg.(prepare opam_reg classGreekFiles) >> PrepareOpamReg.(prepare opam_reg baseFiles) in let bin = FilePath.concat temp_dir "bin" in prepare_pkg >> prepare_dist >> prepare_opam_reg >> PrepareBin.prepare_bin ~opam_response bin log_file >>| read_env ~opam_reg ~dist_library_dir:empty_dist let () = let verbose = false in let main _env ~dest_dir:_ ~temp_dir ~outf:_ = let _name = Some "example-doc" in let dest_dir = FilePath.concat dest_dir " dest " in Satyrographos_command.Lockdown.save_lockdown ~verbose ~buildscript_path:(FilePath.concat temp_dir "pkg/Satyristes") in let post_dump_dirs ~dest_dir:_ ~temp_dir = let pkg_dir = FilePath.concat temp_dir "pkg" in [pkg_dir] in eval (test_install ~post_dump_dirs env main)
a0d62eb98e5a07e2af1d53a2a807947f03a6c91e4b3bafb3120d85f82509ac93
haskell-tools/haskell-tools
StandaloneData.hs
# LANGUAGE DeriveDataTypeable , DeriveFunctor , DeriveFoldable , , DeriveGeneric , DeriveLift , DeriveAnyClass , StandaloneDeriving # DeriveFunctor, DeriveFoldable, DeriveTraversable, DeriveGeneric, DeriveLift, DeriveAnyClass, StandaloneDeriving #-} module StandaloneData where import SynonymDefinitions deriving instance Show (D0' a) {-* StandaloneDeriving *-} deriving instance Read (D0' a) {-* StandaloneDeriving *-} deriving instance Eq (D0' a) {-* StandaloneDeriving *-} deriving instance Enum (D0' a) {-* StandaloneDeriving *-} deriving instance Ord (D0' a) {-* StandaloneDeriving *-} deriving instance Bounded (D0' a) {-* StandaloneDeriving *-} deriving instance Ix (D0' a) {-* StandaloneDeriving *-} deriving instance Data a => Data (D0' a) {-* StandaloneDeriving, DeriveDataTypeable *-} deriving instance Typeable a => Typeable (D0' a) {-* StandaloneDeriving, DeriveDataTypeable *-} deriving instance Generic a => Generic (D0' a) {-* StandaloneDeriving, DeriveGeneric *-} deriving instance Lift a => Lift (D0' a) {-* StandaloneDeriving, DeriveLift *-} deriving instance Functor D0' {-* StandaloneDeriving, DeriveFunctor *-} deriving instance Foldable D0' {-* StandaloneDeriving, DeriveFoldable *-} deriving instance Traversable D0' {-* StandaloneDeriving, DeriveTraversable *-} deriving instance C1 (D0' a) {-* StandaloneDeriving, DeriveAnyClass *-}
null
https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/builtin-refactorings/test/ExtensionOrganizerTest/DerivingsTest/StandaloneData.hs
haskell
* StandaloneDeriving * * StandaloneDeriving * * StandaloneDeriving * * StandaloneDeriving * * StandaloneDeriving * * StandaloneDeriving * * StandaloneDeriving * * StandaloneDeriving, DeriveDataTypeable * * StandaloneDeriving, DeriveDataTypeable * * StandaloneDeriving, DeriveGeneric * * StandaloneDeriving, DeriveLift * * StandaloneDeriving, DeriveFunctor * * StandaloneDeriving, DeriveFoldable * * StandaloneDeriving, DeriveTraversable * * StandaloneDeriving, DeriveAnyClass *
# LANGUAGE DeriveDataTypeable , DeriveFunctor , DeriveFoldable , , DeriveGeneric , DeriveLift , DeriveAnyClass , StandaloneDeriving # DeriveFunctor, DeriveFoldable, DeriveTraversable, DeriveGeneric, DeriveLift, DeriveAnyClass, StandaloneDeriving #-} module StandaloneData where import SynonymDefinitions
5b4ce48e8abc800ab3da434ff5dd8cc7eebaa0c878685b6877b3aa7b6916cfa7
DrearyLisper/aoc-2021
Day06.hs
module Day06 where import qualified Data.Map as Map import qualified Data.List as List wordsWhen :: (Char -> Bool) -> String -> [String] wordsWhen p s = case dropWhile p s of "" -> [] s' -> w : wordsWhen p s'' where (w, s'') = break p s' parseInput :: String -> Map.Map Int Int parseInput c = foldl step (Map.fromList []) $ map read (wordsWhen (==',') c) where alterF :: Maybe Int -> Maybe Int alterF Nothing = Just 1 alterF (Just x) = Just (x+1) step :: Map.Map Int Int -> Int -> Map.Map Int Int step m k = Map.alter alterF k m part1 :: String -> Int part1 c = sum $ Map.elems $ ((iterate step (parseInput c)) !! 80) where nextDay :: (Int, Int) -> [(Int, Int)] nextDay (0, count) = [(6, count), (8, count)] nextDay (age, count) = [(age-1, count)] step :: Map.Map Int Int -> Map.Map Int Int step m = Map.fromAscListWith (\a b -> a + b) $ List.sort $ concat $ map nextDay (Map.assocs m) part2 :: String -> Int part2 c = sum $ Map.elems $ ((iterate step (parseInput c)) !! 256) where nextDay :: (Int, Int) -> [(Int, Int)] nextDay (0, count) = [(6, count), (8, count)] nextDay (age, count) = [(age-1, count)] step :: Map.Map Int Int -> Map.Map Int Int step m = Map.fromAscListWith (\a b -> a + b) $ List.sort $ concat $ map nextDay (Map.assocs m) solve :: String -> IO () solve filename = do c <- readFile filename print $ part1 c print $ part2 c main = solve "input.txt"
null
https://raw.githubusercontent.com/DrearyLisper/aoc-2021/e6e593750ccdfe920342d0216f7c7efc711b5396/06/Day06.hs
haskell
module Day06 where import qualified Data.Map as Map import qualified Data.List as List wordsWhen :: (Char -> Bool) -> String -> [String] wordsWhen p s = case dropWhile p s of "" -> [] s' -> w : wordsWhen p s'' where (w, s'') = break p s' parseInput :: String -> Map.Map Int Int parseInput c = foldl step (Map.fromList []) $ map read (wordsWhen (==',') c) where alterF :: Maybe Int -> Maybe Int alterF Nothing = Just 1 alterF (Just x) = Just (x+1) step :: Map.Map Int Int -> Int -> Map.Map Int Int step m k = Map.alter alterF k m part1 :: String -> Int part1 c = sum $ Map.elems $ ((iterate step (parseInput c)) !! 80) where nextDay :: (Int, Int) -> [(Int, Int)] nextDay (0, count) = [(6, count), (8, count)] nextDay (age, count) = [(age-1, count)] step :: Map.Map Int Int -> Map.Map Int Int step m = Map.fromAscListWith (\a b -> a + b) $ List.sort $ concat $ map nextDay (Map.assocs m) part2 :: String -> Int part2 c = sum $ Map.elems $ ((iterate step (parseInput c)) !! 256) where nextDay :: (Int, Int) -> [(Int, Int)] nextDay (0, count) = [(6, count), (8, count)] nextDay (age, count) = [(age-1, count)] step :: Map.Map Int Int -> Map.Map Int Int step m = Map.fromAscListWith (\a b -> a + b) $ List.sort $ concat $ map nextDay (Map.assocs m) solve :: String -> IO () solve filename = do c <- readFile filename print $ part1 c print $ part2 c main = solve "input.txt"
5c1c9dd902d6b6c6922b6039b13b023df8aef93d227464fac35e43e8d0a94141
Datomic/day-of-datomic
component_attributes.clj
Copyright ( c ) Cognitect , Inc. 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. (require '[datomic.api :as d] '[datomic.samples.repl :as repl]) (def conn (repl/scratch-conn)) (repl/transact-all conn (repl/resource "day-of-datomic/social-news.edn")) ;; create a story and some comments (let [[story comment-1 comment-2] (repeatedly #(d/tempid :db.part/user)) {:keys [tempids db-after]} @(d/transact conn [{:db/id story :story/title "Getting Started" :story/url "-started.html"} {:db/id comment-1 :comment/body "It woud be great to learn about component attributes." :_comments story} {:db/id comment-2 :comment/body "I agree." :_comments comment-1}])] (def story (d/resolve-tempid db-after tempids story)) (def comment-1 (d/resolve-tempid db-after tempids comment-1)) (def comment-2 (d/resolve-tempid db-after tempids comment-2)) (def db db-after)) ;; component attributes are automatically loaded by touch (-> db (d/entity story) d/touch) ;; what does db.fn/retractEntity do? (-> db (d/entity :db.fn/retractEntity) :db/doc) ;; retract the story (def retracted-es (->> (d/transact conn [[:db.fn/retractEntity story]]) deref :tx-data (remove :added) (map :e) (into #{}))) ;; retraction recursively retracts component comments (assert (= retracted-es #{story comment-1 comment-2})) (d/release conn)
null
https://raw.githubusercontent.com/Datomic/day-of-datomic/20c02d26fd2a12481903dd5347589456c74f8eeb/tutorial/component_attributes.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. create a story and some comments component attributes are automatically loaded by touch what does db.fn/retractEntity do? retract the story retraction recursively retracts component comments
Copyright ( c ) Cognitect , Inc. All rights reserved . (require '[datomic.api :as d] '[datomic.samples.repl :as repl]) (def conn (repl/scratch-conn)) (repl/transact-all conn (repl/resource "day-of-datomic/social-news.edn")) (let [[story comment-1 comment-2] (repeatedly #(d/tempid :db.part/user)) {:keys [tempids db-after]} @(d/transact conn [{:db/id story :story/title "Getting Started" :story/url "-started.html"} {:db/id comment-1 :comment/body "It woud be great to learn about component attributes." :_comments story} {:db/id comment-2 :comment/body "I agree." :_comments comment-1}])] (def story (d/resolve-tempid db-after tempids story)) (def comment-1 (d/resolve-tempid db-after tempids comment-1)) (def comment-2 (d/resolve-tempid db-after tempids comment-2)) (def db db-after)) (-> db (d/entity story) d/touch) (-> db (d/entity :db.fn/retractEntity) :db/doc) (def retracted-es (->> (d/transact conn [[:db.fn/retractEntity story]]) deref :tx-data (remove :added) (map :e) (into #{}))) (assert (= retracted-es #{story comment-1 comment-2})) (d/release conn)
aafbd4a4231e61ff3918ece1522c708e2d2d139e83c050ab9afd12fb47df41f4
kmi/irs
basic.lisp
Mode : Lisp ; Package : The Open University (in-package "OCML") (in-ontology akt-support-ontology2) ;;;Here we introduce a number of definitions, which provide ;;;the basic representational layer to define entities in the ontology. ;;;Here we include basic data types, such ;;;as strings, lists, sets and numbers, as well as basic logical concepts, such ;;;as FUNCTION and RELATION. It also provides equality constructs and a meta-level relation HOLDS , which takes a rel , say ? rel , and a number of args , say ? args ;;;and it is satisfied iff ?rel is satisfied by ?args. ;;;The advantage of expliciting including here the representational layer for the set of AKT ontologies is that these become completely self - contained : ;;;all the notions required to specify any concept in the ontology are themselves ;;;to be found in the ontologies ;;;BASIC UNIFICATION MECHANISMS ;;;RELATION = (def-relation = (?x ?y) "True if ?x and ?y do unify" :lisp-fun #'(lambda ( x y env) (Let ((result (unify x y env))) (if (eq result :fail) :fail (List result))))) ;;;RELATION == (def-relation == (?x ?y) "True if ?x and ?y do unify and they also have the same structure. This means that either they are both atoms, or they are lists with the same structure" :lisp-fun #'(lambda ( x y env) (Let ((result (unify-strong x y env))) (if (eq result :fail) :fail (List result))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def-class LIST (Intangible-Thing) ?x "A class representing lists." :iff-def (or (= ?x nil) (= ?x (?a . ?b))) :prove-by (or (= ?x nil) (and (variable-bound ?x) (= ?x (?a . ?b)))) :no-proofs-by (:iff-def)) (def-instance NIL list "The empty list") (def-relation NULL (?l) "True if ?l is the empty list" :iff-def (= ?l nil)) (def-function FIRST (?l) "Takes the first element of a list. If the list is empty the function returns :nothing" :constraint (list ?l) :body (if (== ?l (?a . ?b)) ?a :nothing)) (def-function REST (?l) "Takes a list as argument, say ?l, removes the first element of ?s and returns the resulting list. If ?l = nil, then :nothing is returned" :constraint (list ?l) :body (if (== ?l (?a . ?b)) ?b :nothing)) (def-function LIST-OF (&rest ?els) "This is the primitive list constructor. It is implemented in terms of the underlying LISP list construction primitive, LIST" :lisp-fun #'(lambda (&rest els) (apply #'list els))) (def-function APPEND (?l1 &rest ?ls) "Appends together a number of lists. I cannot be bothered giving its operational spec...so you only get a lisp attachment" :constraint (and (list ?l1)(every ?ls list)) :lisp-fun #'append) (def-function CONS (?el ?l) "Adds ?el to the beginning of list ?l. Note that this cons is less generic than the lisp function with the same name. Here the 2nd argument must be a list (in lisp, it can also be an atom)." :constraint (list ?l) :body (append (list-of ?el) ?l)) (def-function LENGTH (?l) "Computes the number of elements in a list" :constraint (list ?l) :body (if (= ?l nil) 0 (if (== ?l (?first . ?rest)) (+ 1 (length ?rest))))) (def-function REMOVE1 (?el ?l) "Removes the first occurrence of ?el in ?l and returns the resulting list. If ?el is not a member of ?l then the result is ?l" :constraint (list ?l) :body (if (= ?l nil) ?l (if (== ?l (?el . ?rest)) ?rest (if (== ?l (?first . ?rest)) (cons ?first (remove1 ?el ?rest)))))) (def-function REMOVE (?el ?l) "Removes all occurrences of ?el in ?l and returns the resulting list. If ?el is not a member of ?l then the result is ?l" :constraint (list ?l) :body (if (= ?l nil) ?l (if (== ?l (?el . ?rest)) (remove ?el ?rest) (if (== ?l (?first . ?rest)) (cons ?first (remove ?el ?rest)))))) (def-relation MEMBER (?el ?list) "A relation to check whether something is a member of a list" :constraint (list ?list) :iff-def (or (== ?list (?el . ?rest)) (and (== ?list (?first . ?rest)) (member ?el ?rest)))) (def-relation EVERY (?l ?rel) "True if for each term in ?l, say ?term, (holds ?rel ?term) is true. For instance, (every '(1 2 3) 'number) is satisfied, while (every '(1 2 pippo) 'number) is not" :constraint (unary-relation ?rel) :iff-def (or (= ?l nil) (and (== ?l (?first . ?rest)) (holds ?rel ?first) (every ?rest ?rel)))) ;;;FUNCTION BUTLAST (def-function BUTLAST (?list) "Returns all the element of ?list, except the last one. If ?list = NIL, then :nothing is returned. If ?list has length 1, then nil is returned" :constraint (list ?l) :body (cond ((null ?list) :nothing) ((null (rest ?list)) nil) ((true) (cons (first ?list) (butlast (rest ?list)))))) ;;;FUNCTION LAST (def-function LAST (?list) "Returns the last element of a list. If ?list is empty then :nothing is returned" :constraint (list ?list) :body (cond ((null ?list) :nothing) ((null (rest ?list)) (first ?list)) ((true) (last (rest ?list))))) ;;;;;;;;;;;;;;;;;;;;;;;; ;;;SET (def-class SET (Intangible-Thing) "A set is something which is not an individual. In cyc sets are distinguished from collections. Here we just use the term generically to refer to something which denotes a collection of elements, whether abstract or concrete. Functions and relations represent sets. ") (def-axiom BASIC-SET-TYPES-ARE-DISJOINT "There are three basic types of sets in our ontology, functions relations and enumerated sets and these do not intersect" (subclass-partition set (set-of function relation enumerated-set))) (def-function SET-OF (&rest ?args) "This is the basic set constructor to create a set by enumerating its elements. For instance, (setof 1 2) denotes the set {1 2}. We represent such a set as a list whose first item is :set" :body (cons :set ?args)) (def-class ENUMERATED-SET (set) ?x "A set represented as (:set-of el1 el_2...el_n), where no el_i is repeated" :constraint (list ?x) :iff-def (and (= ?x (:set . ?elements)) (not (exists ?el (and (member ?el ?elements) (member ?el (remove1 ?el ?elements)))))) :prove-by (and (variable-bound ?x) (= ?x (:set . ?elements)) (not (exists ?el (and (member ?el ?elements) (member ?el (remove1 ?el ?elements)))))) :no-proofs-by (:iff-def)) (def-relation ELEMENT-OF (?el ?set) "A relation to check whether something is an element of a set. Note that because functions and relations are sets, we can prove whether a tuple satisfies a relation or a function using ELEMENT-OF. For instance, (element-of '(1 2 3) '+) is satisfied because 1+2=3 - see definitions below for an operationalization of this approach") (def-rule ELEMENT-OF-ENUMERATED-SET "An operationalization of element-of, which works with sets represented as lists." ((element-of ?el ?l) if (enumerated-set ?l) (member ?el (rest ?l)))) (def-rule ELEMENT-OF-SET-AS-RELATION "A tuple, say <t1 t2 t3> is an element of relation r iff (holds r ti t2 t3) is satisfied" ((element-of ?tuple ?rel) if (relation ?rel) (List ?tuple) (sentence-holds (cons ?rel ?tuple)))) (def-rule ELEMENT-OF-SET-AS-FUNCTION "A tuple, say <t1 t2 t3> is an element of function f iff (= (apply f ti t2) t3) is satisfied" ((element-of ?el ?fun) if (function ?fun) (list ?el) (= (last ?el) (apply ?fun (butlast ?el))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;NUMBER (def-class NUMBER (Quantity) "The class of all numbers" :lisp-fun #'(lambda (x env) (let ((y (unbound-variable? x env))) (if y ;;if y is unbound we return a 'sample' number (list (cons (cons y 0) env)) (if (numberp (instantiate x env)) ;;;make sure to instantiate x (list env) :fail))))) (def-class REAL-NUMBER (number)) (def-class INTEGER (real-number)) ;;; RELATION < (def-relation < (?x ?y) "A predicate to test whether a number is less than another" :constraint (and (number ?x)(number ?y)) :lisp-fun #'(lambda (x y env) (if (< (instantiate x env) (instantiate y env)) (List env) :fail))) ;;;RELATION > (def-relation > (?x ?y) "A predicate to test whether a number is greater than another" :constraint (and (number ?x)(number ?y)) :lisp-fun #'(lambda (x y env) (if (> (instantiate x env) (instantiate y env)) (List env) :fail))) (def-class POSITIVE-NUMBER (number) ?x :iff-def (and (number ?x) (> ?x 0))) (def-class NEGATIVE-NUMBER (number) ?x :iff-def (and (number ?x) (< ?x 0))) (def-class NON-NEGATIVE-NUMBER (number) ?x :iff-def (and (number ?x) (not (negative-number ?x)))) (def-axiom POS-NEG-NUMBERS-EXHAUSTIVE-PARTITION (exhaustive-subclass-partition number (set-of positive-number negative-number))) (def-class POSITIVE-INTEGER (integer) ?x :iff-def (and (integer ?x) (> ?x 0))) (def-class NEGATIVE-INTEGER (integer) ?x :iff-def (and (integer ?x) (< ?x 0))) (def-class NON-NEGATIVE-INTEGER (integer) ?x :iff-def (and (integer ?x) (not (negative-integer ?x)))) (def-function + (?X &rest ?y) "Adds numbers" :constraint (and (number ?x) (number ?y)) :lisp-fun #'+) (def-function * (?X ?y) "Multiplies numbers" :constraint (and (number ?x) (number ?y)) :lisp-fun #'*) (def-function SQUARE (?X) :constraint (number ?x) :body (* ?X ?X)) (def-function - (?X &rest ?y) "Subtracts numbers" :constraint (and (number ?x) (number ?y)) :lisp-fun #'(lambda (x &rest y) (apply #'- x y))) (def-function / (?X ?y) "Divides numbers" :constraint (and (number ?x) (number ?y)) :lisp-fun #'/) ;;;;;;;;;;;;;;;;;;;;; (def-class STRING (individual intangible-thing) "A primitive class representing strings" :lisp-fun #'(lambda (x env) (let ((y (unbound-variable? x env))) (if y (list (cons (cons y "SAMPLE-STRING") env)) (if (stringp (instantiate x env)) (list env) :fail))))) ;;;;;;;;;;;;;;;;;;;;; (def-class RELATION (set) "The class of defined relations. We assume fixed arity" :lisp-fun #'(lambda (x env) (let ((y (unbound-variable? x env))) (if y (mapcar #'(lambda (rel) (cons (cons y rel) env)) (all-relations)) (if (get-relation (instantiate x env)) ;;;make sure to instantiate x (list env) :fail))))) (def-class UNARY-RELATION (relation) ?r :iff-def (and (relation ?r) (= (arity ?r) 1))) (def-class BINARY-RELATION (relation) ?r :iff-def (and (relation ?r) (= (arity ?r) 2))) (def-relation TRUE () "This is always satisfied" :lisp-fun #'(lambda (env) (list env))) (def-relation FALSE () "This is never satisfied" :lisp-fun #'(lambda (env) :fail)) (def-function ARITY (?x) "The arity of a function or relation. If a function or relation has variable arity, then we treat the last argument as if it were a sequence variable. For instance the argument list for + is (?x &rest ?y). In this case we say that + has arity 2. It is important to note that OCML does not support relations with variable arity. The only exception is HOLDS, which has variable arity and is built in the OCML proof system" :constraint (or (function ?X)(relation ?X)) :body (in-environment ((?l . (the-schema ?x)) (?n . (length ?l))) (if (every ?l variable) ?n ;we assume that the only non-var can be &rest (- ?n 1)))) (def-relation VARIABLE (?x) "True of an OCML variable" :lisp-fun #'(lambda (x env) (if (variable? (instantiate x env)) (list env) :fail))) (def-relation VARIABLE-BOUND (?var) "True if ?var is bound in teh current environment" :lisp-fun #'(lambda (x env) (if (unbound-variable? x env) :fail (list env)))) (def-function THE-SCHEMA (?x) "The schema of a function or relation" :constraint (or (function ?X)(relation ?X)) :body (if (relation ?x) (relation-schema ?x) (if (function ?x) (function-schema ?x) :nothing))) (def-function FUNCTION-SCHEMA (?f) :constraint (function ?f) :lisp-fun #'(lambda (x) (rename-variables (schema (get-function x))))) (def-function RELATION-SCHEMA (?rel) :constraint (relation ?rel) :lisp-fun #'(lambda (x) (rename-variables (schema (get-relation x))))) (def-relation HOLDS (?rel &rest ?args) "A meta-level relation which is true iff the sentence (?rel . ?args) is true. The length of ?args must be consistent with the arity of the relation" :constraint (and (relation ?r) (= (arity ?rel) (length ?args)))) (def-relation SENTENCE-HOLDS (?sentence) "The same as HOLDS, but takes only one argument, a sentence whose truth value is to be checked" :constraint (and (== ?sentence (?rel . ?args )) (relation ?rel) (= (arity ?rel) (length ?args))) :lisp-fun #'(lambda (sent env) (ask-top-level (cons 'holds (instantiate sent env)) :env env :all t))) (def-class FUNCTION (set) "The class of all defined functions" :lisp-fun #'(lambda (x env) (let ((y (unbound-variable? x env))) (if y (mapcar #'(lambda (rel) (cons (cons y rel) env)) (all-functions)) (if (ocml-function? (instantiate x env)) (list env) :fail))))) (def-function APPLY (?f ?args) "(apply f (arg1 .....argn)) is the same as (f arg1 ....argn)" :constraint (and (function ?f) (list ?args)))
null
https://raw.githubusercontent.com/kmi/irs/e1b8d696f61c6b6878c0e92d993ed549fee6e7dd/ontologies/domains/akt-support-ontology2/basic.lisp
lisp
Package : Here we introduce a number of definitions, which provide the basic representational layer to define entities in the ontology. Here we include basic data types, such as strings, lists, sets and numbers, as well as basic logical concepts, such as FUNCTION and RELATION. It also provides equality constructs and a meta-level and it is satisfied iff ?rel is satisfied by ?args. The advantage of expliciting including here the representational layer all the notions required to specify any concept in the ontology are themselves to be found in the ontologies BASIC UNIFICATION MECHANISMS RELATION = RELATION == FUNCTION BUTLAST FUNCTION LAST SET NUMBER if y is unbound we return a 'sample' number make sure to instantiate x RELATION < RELATION > make sure to instantiate x we assume that the only non-var can be &rest
The Open University (in-package "OCML") (in-ontology akt-support-ontology2) relation HOLDS , which takes a rel , say ? rel , and a number of args , say ? args for the set of AKT ontologies is that these become completely self - contained : (def-relation = (?x ?y) "True if ?x and ?y do unify" :lisp-fun #'(lambda ( x y env) (Let ((result (unify x y env))) (if (eq result :fail) :fail (List result))))) (def-relation == (?x ?y) "True if ?x and ?y do unify and they also have the same structure. This means that either they are both atoms, or they are lists with the same structure" :lisp-fun #'(lambda ( x y env) (Let ((result (unify-strong x y env))) (if (eq result :fail) :fail (List result))))) (def-class LIST (Intangible-Thing) ?x "A class representing lists." :iff-def (or (= ?x nil) (= ?x (?a . ?b))) :prove-by (or (= ?x nil) (and (variable-bound ?x) (= ?x (?a . ?b)))) :no-proofs-by (:iff-def)) (def-instance NIL list "The empty list") (def-relation NULL (?l) "True if ?l is the empty list" :iff-def (= ?l nil)) (def-function FIRST (?l) "Takes the first element of a list. If the list is empty the function returns :nothing" :constraint (list ?l) :body (if (== ?l (?a . ?b)) ?a :nothing)) (def-function REST (?l) "Takes a list as argument, say ?l, removes the first element of ?s and returns the resulting list. If ?l = nil, then :nothing is returned" :constraint (list ?l) :body (if (== ?l (?a . ?b)) ?b :nothing)) (def-function LIST-OF (&rest ?els) "This is the primitive list constructor. It is implemented in terms of the underlying LISP list construction primitive, LIST" :lisp-fun #'(lambda (&rest els) (apply #'list els))) (def-function APPEND (?l1 &rest ?ls) "Appends together a number of lists. I cannot be bothered giving its operational spec...so you only get a lisp attachment" :constraint (and (list ?l1)(every ?ls list)) :lisp-fun #'append) (def-function CONS (?el ?l) "Adds ?el to the beginning of list ?l. Note that this cons is less generic than the lisp function with the same name. Here the 2nd argument must be a list (in lisp, it can also be an atom)." :constraint (list ?l) :body (append (list-of ?el) ?l)) (def-function LENGTH (?l) "Computes the number of elements in a list" :constraint (list ?l) :body (if (= ?l nil) 0 (if (== ?l (?first . ?rest)) (+ 1 (length ?rest))))) (def-function REMOVE1 (?el ?l) "Removes the first occurrence of ?el in ?l and returns the resulting list. If ?el is not a member of ?l then the result is ?l" :constraint (list ?l) :body (if (= ?l nil) ?l (if (== ?l (?el . ?rest)) ?rest (if (== ?l (?first . ?rest)) (cons ?first (remove1 ?el ?rest)))))) (def-function REMOVE (?el ?l) "Removes all occurrences of ?el in ?l and returns the resulting list. If ?el is not a member of ?l then the result is ?l" :constraint (list ?l) :body (if (= ?l nil) ?l (if (== ?l (?el . ?rest)) (remove ?el ?rest) (if (== ?l (?first . ?rest)) (cons ?first (remove ?el ?rest)))))) (def-relation MEMBER (?el ?list) "A relation to check whether something is a member of a list" :constraint (list ?list) :iff-def (or (== ?list (?el . ?rest)) (and (== ?list (?first . ?rest)) (member ?el ?rest)))) (def-relation EVERY (?l ?rel) "True if for each term in ?l, say ?term, (holds ?rel ?term) is true. For instance, (every '(1 2 3) 'number) is satisfied, while (every '(1 2 pippo) 'number) is not" :constraint (unary-relation ?rel) :iff-def (or (= ?l nil) (and (== ?l (?first . ?rest)) (holds ?rel ?first) (every ?rest ?rel)))) (def-function BUTLAST (?list) "Returns all the element of ?list, except the last one. If ?list = NIL, then :nothing is returned. If ?list has length 1, then nil is returned" :constraint (list ?l) :body (cond ((null ?list) :nothing) ((null (rest ?list)) nil) ((true) (cons (first ?list) (butlast (rest ?list)))))) (def-function LAST (?list) "Returns the last element of a list. If ?list is empty then :nothing is returned" :constraint (list ?list) :body (cond ((null ?list) :nothing) ((null (rest ?list)) (first ?list)) ((true) (last (rest ?list))))) (def-class SET (Intangible-Thing) "A set is something which is not an individual. In cyc sets are distinguished from collections. Here we just use the term generically to refer to something which denotes a collection of elements, whether abstract or concrete. Functions and relations represent sets. ") (def-axiom BASIC-SET-TYPES-ARE-DISJOINT "There are three basic types of sets in our ontology, functions relations and enumerated sets and these do not intersect" (subclass-partition set (set-of function relation enumerated-set))) (def-function SET-OF (&rest ?args) "This is the basic set constructor to create a set by enumerating its elements. For instance, (setof 1 2) denotes the set {1 2}. We represent such a set as a list whose first item is :set" :body (cons :set ?args)) (def-class ENUMERATED-SET (set) ?x "A set represented as (:set-of el1 el_2...el_n), where no el_i is repeated" :constraint (list ?x) :iff-def (and (= ?x (:set . ?elements)) (not (exists ?el (and (member ?el ?elements) (member ?el (remove1 ?el ?elements)))))) :prove-by (and (variable-bound ?x) (= ?x (:set . ?elements)) (not (exists ?el (and (member ?el ?elements) (member ?el (remove1 ?el ?elements)))))) :no-proofs-by (:iff-def)) (def-relation ELEMENT-OF (?el ?set) "A relation to check whether something is an element of a set. Note that because functions and relations are sets, we can prove whether a tuple satisfies a relation or a function using ELEMENT-OF. For instance, (element-of '(1 2 3) '+) is satisfied because 1+2=3 - see definitions below for an operationalization of this approach") (def-rule ELEMENT-OF-ENUMERATED-SET "An operationalization of element-of, which works with sets represented as lists." ((element-of ?el ?l) if (enumerated-set ?l) (member ?el (rest ?l)))) (def-rule ELEMENT-OF-SET-AS-RELATION "A tuple, say <t1 t2 t3> is an element of relation r iff (holds r ti t2 t3) is satisfied" ((element-of ?tuple ?rel) if (relation ?rel) (List ?tuple) (sentence-holds (cons ?rel ?tuple)))) (def-rule ELEMENT-OF-SET-AS-FUNCTION "A tuple, say <t1 t2 t3> is an element of function f iff (= (apply f ti t2) t3) is satisfied" ((element-of ?el ?fun) if (function ?fun) (list ?el) (= (last ?el) (apply ?fun (butlast ?el))))) (def-class NUMBER (Quantity) "The class of all numbers" :lisp-fun #'(lambda (x env) (let ((y (unbound-variable? x env))) (list (cons (cons y 0) env)) (list env) :fail))))) (def-class REAL-NUMBER (number)) (def-class INTEGER (real-number)) (def-relation < (?x ?y) "A predicate to test whether a number is less than another" :constraint (and (number ?x)(number ?y)) :lisp-fun #'(lambda (x y env) (if (< (instantiate x env) (instantiate y env)) (List env) :fail))) (def-relation > (?x ?y) "A predicate to test whether a number is greater than another" :constraint (and (number ?x)(number ?y)) :lisp-fun #'(lambda (x y env) (if (> (instantiate x env) (instantiate y env)) (List env) :fail))) (def-class POSITIVE-NUMBER (number) ?x :iff-def (and (number ?x) (> ?x 0))) (def-class NEGATIVE-NUMBER (number) ?x :iff-def (and (number ?x) (< ?x 0))) (def-class NON-NEGATIVE-NUMBER (number) ?x :iff-def (and (number ?x) (not (negative-number ?x)))) (def-axiom POS-NEG-NUMBERS-EXHAUSTIVE-PARTITION (exhaustive-subclass-partition number (set-of positive-number negative-number))) (def-class POSITIVE-INTEGER (integer) ?x :iff-def (and (integer ?x) (> ?x 0))) (def-class NEGATIVE-INTEGER (integer) ?x :iff-def (and (integer ?x) (< ?x 0))) (def-class NON-NEGATIVE-INTEGER (integer) ?x :iff-def (and (integer ?x) (not (negative-integer ?x)))) (def-function + (?X &rest ?y) "Adds numbers" :constraint (and (number ?x) (number ?y)) :lisp-fun #'+) (def-function * (?X ?y) "Multiplies numbers" :constraint (and (number ?x) (number ?y)) :lisp-fun #'*) (def-function SQUARE (?X) :constraint (number ?x) :body (* ?X ?X)) (def-function - (?X &rest ?y) "Subtracts numbers" :constraint (and (number ?x) (number ?y)) :lisp-fun #'(lambda (x &rest y) (apply #'- x y))) (def-function / (?X ?y) "Divides numbers" :constraint (and (number ?x) (number ?y)) :lisp-fun #'/) (def-class STRING (individual intangible-thing) "A primitive class representing strings" :lisp-fun #'(lambda (x env) (let ((y (unbound-variable? x env))) (if y (list (cons (cons y "SAMPLE-STRING") env)) (if (stringp (instantiate x env)) (list env) :fail))))) (def-class RELATION (set) "The class of defined relations. We assume fixed arity" :lisp-fun #'(lambda (x env) (let ((y (unbound-variable? x env))) (if y (mapcar #'(lambda (rel) (cons (cons y rel) env)) (all-relations)) (list env) :fail))))) (def-class UNARY-RELATION (relation) ?r :iff-def (and (relation ?r) (= (arity ?r) 1))) (def-class BINARY-RELATION (relation) ?r :iff-def (and (relation ?r) (= (arity ?r) 2))) (def-relation TRUE () "This is always satisfied" :lisp-fun #'(lambda (env) (list env))) (def-relation FALSE () "This is never satisfied" :lisp-fun #'(lambda (env) :fail)) (def-function ARITY (?x) "The arity of a function or relation. If a function or relation has variable arity, then we treat the last argument as if it were a sequence variable. For instance the argument list for + is (?x &rest ?y). In this case we say that + has arity 2. It is important to note that OCML does not support relations with variable arity. The only exception is HOLDS, which has variable arity and is built in the OCML proof system" :constraint (or (function ?X)(relation ?X)) :body (in-environment ((?l . (the-schema ?x)) (?n . (length ?l))) (if (every ?l variable) ?n (- ?n 1)))) (def-relation VARIABLE (?x) "True of an OCML variable" :lisp-fun #'(lambda (x env) (if (variable? (instantiate x env)) (list env) :fail))) (def-relation VARIABLE-BOUND (?var) "True if ?var is bound in teh current environment" :lisp-fun #'(lambda (x env) (if (unbound-variable? x env) :fail (list env)))) (def-function THE-SCHEMA (?x) "The schema of a function or relation" :constraint (or (function ?X)(relation ?X)) :body (if (relation ?x) (relation-schema ?x) (if (function ?x) (function-schema ?x) :nothing))) (def-function FUNCTION-SCHEMA (?f) :constraint (function ?f) :lisp-fun #'(lambda (x) (rename-variables (schema (get-function x))))) (def-function RELATION-SCHEMA (?rel) :constraint (relation ?rel) :lisp-fun #'(lambda (x) (rename-variables (schema (get-relation x))))) (def-relation HOLDS (?rel &rest ?args) "A meta-level relation which is true iff the sentence (?rel . ?args) is true. The length of ?args must be consistent with the arity of the relation" :constraint (and (relation ?r) (= (arity ?rel) (length ?args)))) (def-relation SENTENCE-HOLDS (?sentence) "The same as HOLDS, but takes only one argument, a sentence whose truth value is to be checked" :constraint (and (== ?sentence (?rel . ?args )) (relation ?rel) (= (arity ?rel) (length ?args))) :lisp-fun #'(lambda (sent env) (ask-top-level (cons 'holds (instantiate sent env)) :env env :all t))) (def-class FUNCTION (set) "The class of all defined functions" :lisp-fun #'(lambda (x env) (let ((y (unbound-variable? x env))) (if y (mapcar #'(lambda (rel) (cons (cons y rel) env)) (all-functions)) (if (ocml-function? (instantiate x env)) (list env) :fail))))) (def-function APPLY (?f ?args) "(apply f (arg1 .....argn)) is the same as (f arg1 ....argn)" :constraint (and (function ?f) (list ?args)))
cd7599599f493be8b6def0ef3ce73ee67eeb9f4a89eefd5a724ca2b2352e863f
melange-re/melange
config2_test.mli
class type v = object method hey : int -> int -> int end [@bs] class type v2 = object method hey : int -> int -> int end [@bs] type vv = < hey : int -> int -> int [@bs] > Js.t type vv2 = < hey : int -> int -> int [@bs] > Js.t val test_v : v Js.t -> int val test_vv : vv -> int
null
https://raw.githubusercontent.com/melange-re/melange/246e6df78fe3b6cc124cb48e5a37fdffd99379ed/jscomp/test/config2_test.mli
ocaml
class type v = object method hey : int -> int -> int end [@bs] class type v2 = object method hey : int -> int -> int end [@bs] type vv = < hey : int -> int -> int [@bs] > Js.t type vv2 = < hey : int -> int -> int [@bs] > Js.t val test_v : v Js.t -> int val test_vv : vv -> int
b03c251ab14fda4b927966bba3e46b59fd87bdd8a661117b45df500a8e9af9fe
McCLIM/McCLIM
tooltips.lisp
Copyright ( C ) 1993 - 2004 by SRI International . All rights reserved . ;;; Permission granted by SRI for use in McClim under the license . ;;; $ I d : utils.lisp , v 1.8 2007/07/14 02:14:21 Exp $ ;;; (defpackage #:mcclim-tooltips (:use #:clim :clim-lisp) (:export #:*tooltip-color* #:*tooltip-ink* #:*tooltip-text-style* #:*tooltip-wrap-p* #:*tooltip-wrap-width* ;; #:*tooltip-wrap-slop* ;; #:*tooltip-max-height* ;; #:*tooltip-enforce-max-height-p* #:*tooltip-delay* #:draw-tooltip #:erase-tooltip #:orec-relative->absolute-region)) (in-package #:mcclim-tooltips) ;;;============================= CLIM Tooltips =============================== ;;; paley:Jun-19-2007 To use tooltips w/ clim presentations , define after methods for the clim presentation - method clim : highlight - presentation . When the state argument is ;;; :highlight, the method should call draw-tooltip. When the state argument is : , the method should call erase - tooltip . Here 's a sample call ( which assumes the fn get - tooltip - text returns a string or NIL ): ;;; #+ (or) (clim:define-presentation-method clim:highlight-presentation :after ((type t) record stream (state (eql :highlight))) (draw-tooltip stream (get-tooltip-text record) :region (orec-relative->absolute-region record stream))) #+ (or) (clim:define-presentation-method clim:highlight-presentation :after ((type t) record stream (state (eql :unhighlight))) (declare (ignore record)) (erase-tooltip stream)) ;;; ;;; At some point, we may want to extend the tooltip functionality to allow for ;;; arbitrary output w/in a tooltip (i.e. not just a string, maybe graphics ;;; too). ;;; Tooltip parameters. Intended to be globally customizable but ;;; overridable at the time DRAW-TOOLTIP is called. (defparameter *tooltip-color* (make-rgb-color 1.0 1.0 0.85)) (defparameter *tooltip-ink* +black+) (defparameter *tooltip-text-style* (make-text-style :sans-serif :roman :small)) (defparameter *tooltip-wrap-p* t) (defparameter *tooltip-wrap-width* 40) ; characters. #+ (or) (defparameter *tooltip-wrap-slop* 5) ; characters. #+ (or) (defparameter *tooltip-max-height* 200) #+ (or) (defparameter *tooltip-enforce-max-height-p* nil) (defparameter *tooltip-delay* 0.25) (defvar *tooltip-lock* (clim-sys:make-lock "tooltip")) (defvar *tooltip-process* nil) ; Current tooltip drawing process. (defvar *tooltip-orec* nil) ; The currently drawn tooltip. ;;; ============================================================== draw-tooltip ;;; [API] ;;; paley:Jun-19-2007 ;;; Description : Draw a box containing text, to be used as a tooltip. If x- ;;; and y-coordinates are supplied, the box will have its upper ;;; left corner at that position. If no coordinates are supplied but a clim region is , the box will be positioned ;;; close to that region, but not overlapping it. The entire box ;;; is positioned within the viewport. If no position and no ;;; region are supplied, the box is drawn "near" the pointer. We ;;; actually output the text twice, once to compute its size and the second time to actually render it -- we may be able to ;;; make this more efficient. ;;; Arguments : stream : the clim stream to output to text : a string or NIL region : a clim region ( optional ) -- the tooltip should be ;;; positioned near this region. ;;; x,y: integers (optional) -- if supplied, the tooltip will ;;; have its upper left corner at this position. ;;; Returns : nothing ;;; Side Effects : sets *tooltip-orec* Update History : : Jun-20 - 2007 ;;; Make text rendering function an argument to remove ;;; dependency on pathway tools code. ;;; : Jul-10 - 2007 ;;; More intelligent placement of tooltip. ;;; : Jul-13 - 2007 ;;; Even more intelligent placement of tooltip. ;;; ;;; Note that if the region has a large bounding box it may not ;;; be reasonable to avoid having the tooltip obscure part of ;;; it. ;;; : Jul-16 - 2007 ;;; Cleanup and additional fixes to deal properly with newlines ;;; in the string. ;;; : Aug-1 - 2007 ;;; Work around problem with weird coordinates in (we think) ;;; filling-output. Also, add a configurable delay before the ;;; tooltip is drawn. (defvar *whitespace-bag* '(#\space #\tab #\newline)) (defun split-string-by-length (string wrap-length) "Take a string and return the front of it up to a given length, splitting it at a whitespace character if possible. Return the string and the remainder of the string. The strings have whitespace trimmed." (let* ((string-length (length string)) (end wrap-length) (newline-position (position #\newline string :start 0 :end (min string-length end)))) Newlines are part of the formatting . So we split at newlines ;; even if the string is shorter than the wrap length. (if newline-position (setf end newline-position) (if (< string-length wrap-length) ;; No newline and the length of the string is less than the ;; wrap length. Return the original (trimmed) string and ;; nil. The nil can be used by the caller to detect that ;; the string has been used up. (return-from split-string-by-length (values (string-trim *whitespace-bag* string) nil)) ;; Look for whitespace. (let ((whitespace-position (position-if #'(lambda (char) (member char *whitespace-bag*)) string :end wrap-length :from-end t))) (when whitespace-position (setf end whitespace-position))))) ;; Note that the default (if no whitespace found) will be to have ;; the string violently split at the wrap-length. (values (string-trim *whitespace-bag* (subseq string 0 end)) (string-left-trim *whitespace-bag* (subseq string end string-length))))) (defun draw-tooltip (stream text &key region x y (text-render-fn #'draw-text*) (background *tooltip-color*) (ink *tooltip-ink*) (text-style *tooltip-text-style*) (wrap-p *tooltip-wrap-p*) (wrap-width *tooltip-wrap-width*) ;;(max-height *tooltip-max-height*) ;;(enforce-max-height-p *tooltip-enforce-max-height-p*) ) #+ (or) (declare (ignore max-height enforce-max-height-p)) ;; Suggested new args. Most or all should have defaults based on global vars. ;; To wrap or not to wrap, and width limit ;; Height limit, and whether or not to enforce a height limit ;; Background color Foreground color ;; Timeout after which tooltip disappears (only if it is easy to do) and Font size Can you figure out how to get the CLIM documentation text to appear as a tooltip ? ;; Use a really pale yellow if possible... (flet ((process-draw-tooltip () (sleep *tooltip-delay*) (when (and text (not (equal text ""))) (with-drawing-options (stream :text-style text-style :ink ink) (let ((margin 2) (text-height (+ (stream-line-height stream) 2)) tt-x tt-y strings wd ht) (if wrap-p ; Do it this way in case the text has newlines in it. ;; You are running a fast computer, right? (progn (multiple-value-setq (wd ht) (bounding-rectangle-size (with-output-to-output-record (stream) (let (this-line (left-over text) (i 0)) (loop (multiple-value-setq (this-line left-over) (split-string-by-length left-over wrap-width)) (unless (equal this-line "") ;; (format *error-output* "end ~A: ~A~%" i this-line) (push this-line strings) (funcall text-render-fn stream this-line 0 (+ (* i text-height) margin))) (incf i) ;; (format *error-output* "left-over: ~A~%" left-over) (unless left-over (return))) ) (setf strings (nreverse strings)))) ) (setf *tooltip-orec* (with-output-recording-options (stream :draw nil :record t) (with-new-output-record (stream) (draw-rectangle* stream (- margin) (- margin) (+ wd margin) (+ ht margin) :ink background) (draw-rectangle* stream (- margin) (- margin) (+ wd margin) (+ ht margin) :filled nil) (do* ((string-list strings (cdr string-list)) (string (car string-list) (car string-list)) (i 0 (1+ i)) ) ((endp string-list)) ;; (format *error-output* "~A~%" string) (funcall text-render-fn stream string 0 (* i text-height) :align-x :left :align-y :top) ))))) (progn (multiple-value-setq (wd ht) (bounding-rectangle-size (with-output-to-output-record (stream) (funcall text-render-fn stream text 0 0)))) (setf *tooltip-orec* (with-output-recording-options (stream :draw nil :record t) (with-new-output-record (stream) (draw-rectangle* stream (- margin) (- margin) (+ wd margin) (+ ht margin) :ink background) (draw-rectangle* stream (- margin) (- margin) (+ wd margin) (+ ht margin) :filled nil) (funcall text-render-fn stream text 0 0 :align-x :left :align-y :top)))))) ;; This tries to put the tool tip near the region and near the pointer. (when (and region (not (and x y))) (multiple-value-bind (ptr-x ptr-y) (stream-pointer-position stream) (let* ((viewport-br (window-viewport stream)) (viewport-max-x (bounding-rectangle-max-x viewport-br)) (viewport-min-x (bounding-rectangle-min-x viewport-br)) (viewport-max-y (bounding-rectangle-max-y viewport-br)) (viewport-min-y (bounding-rectangle-min-y viewport-br))) (with-bounding-rectangle* (tooltip-left tooltip-top tooltip-right tooltip-bottom) *tooltip-orec* (declare (ignore tooltip-left tooltip-top)) ;; gilham:Aug-1-2007 First , check to see if the bottom of the region is near the pointer . If not , two things might be the ;; case: ;; 1 ) The region is very large in height . 2 ) We are encountering the problem with ;; the coordinates of certain records being strange . ( This may be a CLIM bug ;; and is still being investigated.) ;; ;; In either case, we want to ignore the ;; region and just put the tool tip ;; 1 ) Near the pointer , and 2 ) In the viewport . ;; ;; The latter constraint is very ;; important---tooltips are useless if they ;; are not visible in the viewport. ;; (if (> (- (clim:bounding-rectangle-max-y region) ptr-y) 40) (progn (setf tt-x (+ ptr-x 10) tt-y (- ptr-y 30))) (progn ;; Make it seem as if the pointer hit the ;; record from the bottom every time. (setf ptr-y (bounding-rectangle-max-y region)) ;; ;; The idea is to not have the tooltip ;; cover either the pointer or the region ;; (that is, the text in the presentation ;; that is being highlighted). It may not ;; be possible to avoid the latter, if it ;; would put the tooltip too far from the ;; pointer, but at least we try to make ;; it not too egregious. (setf tt-x (+ ptr-x 10) tt-y (- (bounding-rectangle-min-y region) ht 10)) )) (when (< tt-y (- ptr-y (+ ht 40))) (setf tt-y (- ptr-y (+ ht 40)))) ;; Try to keep the tool tip in the viewport. (when (> (+ tt-x tooltip-right) viewport-max-x) (decf tt-x (+ (- (+ tt-x tooltip-right) viewport-max-x) margin)) (when (< tt-x viewport-min-x) (setf tt-x viewport-min-x))) ;; If the tooltip would go above the viewport, put it below the pointer. (when (< tt-y viewport-min-y) (setf tt-y (+ ptr-y 40)) (when (> tt-y viewport-max-y) (setf tt-y (- viewport-max-y tooltip-bottom)))))))) (setq x (or x tt-x 0) y (or y tt-y 0))))) (setf (output-record-position *tooltip-orec*) (values x y)) (tree-recompute-extent *tooltip-orec*) (replay *tooltip-orec* stream) (force-output stream) (setf *tooltip-process* nil))) clear previous tooltip , if there is one ;; gilham:Aug-1-2007 ;; We create a process that will wait a configurable delay period ;; before drawing the tooltip. If the unhighlight method runs ;; before this process wakes up, it kills the process off and so ;; prevents the tooltip from being drawn. (clim-sys:with-lock-held (*tooltip-lock*) (setf *tooltip-process* (clim-sys:make-process #'process-draw-tooltip :name "Draw-Tooltip"))))) ;;; paley:Jun-19-2007 Erase a tooltip drawn by draw-tooltip ;;; Side Effects : sets *tooltip-orec* to nil (defun erase-tooltip (stream) ;; gilham:Aug-1-2007 See if there's a process waiting to draw a ;; tooltip. If so, kill it. (clim-sys:with-lock-held (*tooltip-lock*) (when (and *tooltip-process* (clim-sys:process-state *tooltip-process*)) (clim-sys:destroy-process *tooltip-process*))) (when *tooltip-orec* (erase-output-record *tooltip-orec* stream nil) (setf *tooltip-orec* nil))) ;;; ============================================ orec-relative->absolute-region ;;; [API] paley : Jun-19 - 2007 Description : Given an output record , return a clim ;;; region that reflects its actual position in the window. ;;; Arguments : orec: an output-record ;;; stream: the stream on which orec was displayed Returns : a clim region ;;; Side Effects : none ;;; Update History : (defun orec-relative->absolute-region (orec stream) (declare (ignore stream)) (transform-region +identity-transformation+ orec))
null
https://raw.githubusercontent.com/McCLIM/McCLIM/47677157d2b12dbcad35f06847221b49fbd1eedb/Extensions/tooltips/tooltips.lisp
lisp
#:*tooltip-wrap-slop* #:*tooltip-max-height* #:*tooltip-enforce-max-height-p* ============================= CLIM Tooltips =============================== paley:Jun-19-2007 :highlight, the method should call draw-tooltip. When the state argument is At some point, we may want to extend the tooltip functionality to allow for arbitrary output w/in a tooltip (i.e. not just a string, maybe graphics too). Tooltip parameters. Intended to be globally customizable but overridable at the time DRAW-TOOLTIP is called. characters. characters. Current tooltip drawing process. The currently drawn tooltip. ============================================================== draw-tooltip [API] paley:Jun-19-2007 Description : Draw a box containing text, to be used as a tooltip. If x- and y-coordinates are supplied, the box will have its upper left corner at that position. If no coordinates are close to that region, but not overlapping it. The entire box is positioned within the viewport. If no position and no region are supplied, the box is drawn "near" the pointer. We actually output the text twice, once to compute its size and make this more efficient. positioned near this region. x,y: integers (optional) -- if supplied, the tooltip will have its upper left corner at this position. Returns : nothing Side Effects : sets *tooltip-orec* Make text rendering function an argument to remove dependency on pathway tools code. More intelligent placement of tooltip. Even more intelligent placement of tooltip. Note that if the region has a large bounding box it may not be reasonable to avoid having the tooltip obscure part of it. Cleanup and additional fixes to deal properly with newlines in the string. Work around problem with weird coordinates in (we think) filling-output. Also, add a configurable delay before the tooltip is drawn. even if the string is shorter than the wrap length. No newline and the length of the string is less than the wrap length. Return the original (trimmed) string and nil. The nil can be used by the caller to detect that the string has been used up. Look for whitespace. Note that the default (if no whitespace found) will be to have the string violently split at the wrap-length. (max-height *tooltip-max-height*) (enforce-max-height-p *tooltip-enforce-max-height-p*) Suggested new args. Most or all should have defaults based on global vars. To wrap or not to wrap, and width limit Height limit, and whether or not to enforce a height limit Background color Timeout after which tooltip disappears (only if it is easy to do) Use a really pale yellow if possible... Do it this way in case the text has newlines in it. You are running a fast computer, right? (format *error-output* "end ~A: ~A~%" i this-line) (format *error-output* "left-over: ~A~%" left-over) (format *error-output* "~A~%" string) This tries to put the tool tip near the region and near the pointer. gilham:Aug-1-2007 case: the coordinates of certain records and is still being investigated.) In either case, we want to ignore the region and just put the tool tip The latter constraint is very important---tooltips are useless if they are not visible in the viewport. Make it seem as if the pointer hit the record from the bottom every time. The idea is to not have the tooltip cover either the pointer or the region (that is, the text in the presentation that is being highlighted). It may not be possible to avoid the latter, if it would put the tooltip too far from the pointer, but at least we try to make it not too egregious. Try to keep the tool tip in the viewport. If the tooltip would go above the viewport, put it below the pointer. gilham:Aug-1-2007 We create a process that will wait a configurable delay period before drawing the tooltip. If the unhighlight method runs before this process wakes up, it kills the process off and so prevents the tooltip from being drawn. paley:Jun-19-2007 Erase a tooltip drawn by draw-tooltip Side Effects : sets *tooltip-orec* to nil gilham:Aug-1-2007 See if there's a process waiting to draw a tooltip. If so, kill it. ============================================ orec-relative->absolute-region [API] region that reflects its actual position in the window. Arguments : orec: an output-record stream: the stream on which orec was displayed Side Effects : none Update History :
Copyright ( C ) 1993 - 2004 by SRI International . All rights reserved . Permission granted by SRI for use in McClim under the license . $ I d : utils.lisp , v 1.8 2007/07/14 02:14:21 Exp $ (defpackage #:mcclim-tooltips (:use #:clim :clim-lisp) (:export #:*tooltip-color* #:*tooltip-ink* #:*tooltip-text-style* #:*tooltip-wrap-p* #:*tooltip-wrap-width* #:*tooltip-delay* #:draw-tooltip #:erase-tooltip #:orec-relative->absolute-region)) (in-package #:mcclim-tooltips) To use tooltips w/ clim presentations , define after methods for the clim presentation - method clim : highlight - presentation . When the state argument is : , the method should call erase - tooltip . Here 's a sample call ( which assumes the fn get - tooltip - text returns a string or NIL ): #+ (or) (clim:define-presentation-method clim:highlight-presentation :after ((type t) record stream (state (eql :highlight))) (draw-tooltip stream (get-tooltip-text record) :region (orec-relative->absolute-region record stream))) #+ (or) (clim:define-presentation-method clim:highlight-presentation :after ((type t) record stream (state (eql :unhighlight))) (declare (ignore record)) (erase-tooltip stream)) (defparameter *tooltip-color* (make-rgb-color 1.0 1.0 0.85)) (defparameter *tooltip-ink* +black+) (defparameter *tooltip-text-style* (make-text-style :sans-serif :roman :small)) (defparameter *tooltip-wrap-p* t) #+ (or) (defparameter *tooltip-max-height* 200) #+ (or) (defparameter *tooltip-enforce-max-height-p* nil) (defparameter *tooltip-delay* 0.25) (defvar *tooltip-lock* (clim-sys:make-lock "tooltip")) supplied but a clim region is , the box will be positioned the second time to actually render it -- we may be able to Arguments : stream : the clim stream to output to text : a string or NIL region : a clim region ( optional ) -- the tooltip should be Update History : : Jun-20 - 2007 : Jul-10 - 2007 : Jul-13 - 2007 : Jul-16 - 2007 : Aug-1 - 2007 (defvar *whitespace-bag* '(#\space #\tab #\newline)) (defun split-string-by-length (string wrap-length) "Take a string and return the front of it up to a given length, splitting it at a whitespace character if possible. Return the string and the remainder of the string. The strings have whitespace trimmed." (let* ((string-length (length string)) (end wrap-length) (newline-position (position #\newline string :start 0 :end (min string-length end)))) Newlines are part of the formatting . So we split at newlines (if newline-position (setf end newline-position) (if (< string-length wrap-length) (return-from split-string-by-length (values (string-trim *whitespace-bag* string) nil)) (let ((whitespace-position (position-if #'(lambda (char) (member char *whitespace-bag*)) string :end wrap-length :from-end t))) (when whitespace-position (setf end whitespace-position))))) (values (string-trim *whitespace-bag* (subseq string 0 end)) (string-left-trim *whitespace-bag* (subseq string end string-length))))) (defun draw-tooltip (stream text &key region x y (text-render-fn #'draw-text*) (background *tooltip-color*) (ink *tooltip-ink*) (text-style *tooltip-text-style*) (wrap-p *tooltip-wrap-p*) (wrap-width *tooltip-wrap-width*) ) #+ (or) (declare (ignore max-height enforce-max-height-p)) Foreground color and Font size Can you figure out how to get the CLIM documentation text to appear as a tooltip ? (flet ((process-draw-tooltip () (sleep *tooltip-delay*) (when (and text (not (equal text ""))) (with-drawing-options (stream :text-style text-style :ink ink) (let ((margin 2) (text-height (+ (stream-line-height stream) 2)) tt-x tt-y strings wd ht) (progn (multiple-value-setq (wd ht) (bounding-rectangle-size (with-output-to-output-record (stream) (let (this-line (left-over text) (i 0)) (loop (multiple-value-setq (this-line left-over) (split-string-by-length left-over wrap-width)) (unless (equal this-line "") (push this-line strings) (funcall text-render-fn stream this-line 0 (+ (* i text-height) margin))) (incf i) (unless left-over (return))) ) (setf strings (nreverse strings)))) ) (setf *tooltip-orec* (with-output-recording-options (stream :draw nil :record t) (with-new-output-record (stream) (draw-rectangle* stream (- margin) (- margin) (+ wd margin) (+ ht margin) :ink background) (draw-rectangle* stream (- margin) (- margin) (+ wd margin) (+ ht margin) :filled nil) (do* ((string-list strings (cdr string-list)) (string (car string-list) (car string-list)) (i 0 (1+ i)) ) ((endp string-list)) (funcall text-render-fn stream string 0 (* i text-height) :align-x :left :align-y :top) ))))) (progn (multiple-value-setq (wd ht) (bounding-rectangle-size (with-output-to-output-record (stream) (funcall text-render-fn stream text 0 0)))) (setf *tooltip-orec* (with-output-recording-options (stream :draw nil :record t) (with-new-output-record (stream) (draw-rectangle* stream (- margin) (- margin) (+ wd margin) (+ ht margin) :ink background) (draw-rectangle* stream (- margin) (- margin) (+ wd margin) (+ ht margin) :filled nil) (funcall text-render-fn stream text 0 0 :align-x :left :align-y :top)))))) (when (and region (not (and x y))) (multiple-value-bind (ptr-x ptr-y) (stream-pointer-position stream) (let* ((viewport-br (window-viewport stream)) (viewport-max-x (bounding-rectangle-max-x viewport-br)) (viewport-min-x (bounding-rectangle-min-x viewport-br)) (viewport-max-y (bounding-rectangle-max-y viewport-br)) (viewport-min-y (bounding-rectangle-min-y viewport-br))) (with-bounding-rectangle* (tooltip-left tooltip-top tooltip-right tooltip-bottom) *tooltip-orec* (declare (ignore tooltip-left tooltip-top)) First , check to see if the bottom of the region is near the pointer . If not , two things might be the 1 ) The region is very large in height . 2 ) We are encountering the problem with being strange . ( This may be a CLIM bug 1 ) Near the pointer , and 2 ) In the viewport . (if (> (- (clim:bounding-rectangle-max-y region) ptr-y) 40) (progn (setf tt-x (+ ptr-x 10) tt-y (- ptr-y 30))) (progn (setf ptr-y (bounding-rectangle-max-y region)) (setf tt-x (+ ptr-x 10) tt-y (- (bounding-rectangle-min-y region) ht 10)) )) (when (< tt-y (- ptr-y (+ ht 40))) (setf tt-y (- ptr-y (+ ht 40)))) (when (> (+ tt-x tooltip-right) viewport-max-x) (decf tt-x (+ (- (+ tt-x tooltip-right) viewport-max-x) margin)) (when (< tt-x viewport-min-x) (setf tt-x viewport-min-x))) (when (< tt-y viewport-min-y) (setf tt-y (+ ptr-y 40)) (when (> tt-y viewport-max-y) (setf tt-y (- viewport-max-y tooltip-bottom)))))))) (setq x (or x tt-x 0) y (or y tt-y 0))))) (setf (output-record-position *tooltip-orec*) (values x y)) (tree-recompute-extent *tooltip-orec*) (replay *tooltip-orec* stream) (force-output stream) (setf *tooltip-process* nil))) clear previous tooltip , if there is one (clim-sys:with-lock-held (*tooltip-lock*) (setf *tooltip-process* (clim-sys:make-process #'process-draw-tooltip :name "Draw-Tooltip"))))) (defun erase-tooltip (stream) (clim-sys:with-lock-held (*tooltip-lock*) (when (and *tooltip-process* (clim-sys:process-state *tooltip-process*)) (clim-sys:destroy-process *tooltip-process*))) (when *tooltip-orec* (erase-output-record *tooltip-orec* stream nil) (setf *tooltip-orec* nil))) paley : Jun-19 - 2007 Description : Given an output record , return a clim Returns : a clim region (defun orec-relative->absolute-region (orec stream) (declare (ignore stream)) (transform-region +identity-transformation+ orec))
70f60e989b1a0d160959bfd8f320869ab006c2185e55674e5bc31128a4c67e00
VisionsGlobalEmpowerment/webchange
views.cljs
(ns webchange.login.views (:require [re-frame.core :as re-frame] [reagent.core :as r] [webchange.login.header.views :refer [header]] [webchange.login.routes :as routes] [webchange.login.sign-in.views :refer [sign-in-form]] [webchange.login.pages.views :refer [registration-success]] [webchange.login.registration.views :refer [registration]] [webchange.login.reset-password.views :refer [provide-email-form reset-password-form]] [webchange.login.state :as state] [webchange.ui.index :as ui])) (defn index [] (r/create-class {:display-name "Log In Index" :component-did-mount (fn [this] (let [{:keys [route]} (r/props this)] (routes/init! (:path route)))) :reagent-render (fn [] (let [{:keys [handler props]} @(re-frame/subscribe [::state/current-page])] [:div#tabschool-login {:class-name (ui/get-class-name {"background-with-image" (= handler :sign-in)})} [header] (case handler :sign-up-success [registration-success props] :sign-up [registration props] :reset-password-email [provide-email-form props] :reset-password-code [reset-password-form props] [sign-in-form props])]))}))
null
https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/7eb09b19832693c4c1f3ee6efbaf587474bf9af8/src/cljs/webchange/login/views.cljs
clojure
(ns webchange.login.views (:require [re-frame.core :as re-frame] [reagent.core :as r] [webchange.login.header.views :refer [header]] [webchange.login.routes :as routes] [webchange.login.sign-in.views :refer [sign-in-form]] [webchange.login.pages.views :refer [registration-success]] [webchange.login.registration.views :refer [registration]] [webchange.login.reset-password.views :refer [provide-email-form reset-password-form]] [webchange.login.state :as state] [webchange.ui.index :as ui])) (defn index [] (r/create-class {:display-name "Log In Index" :component-did-mount (fn [this] (let [{:keys [route]} (r/props this)] (routes/init! (:path route)))) :reagent-render (fn [] (let [{:keys [handler props]} @(re-frame/subscribe [::state/current-page])] [:div#tabschool-login {:class-name (ui/get-class-name {"background-with-image" (= handler :sign-in)})} [header] (case handler :sign-up-success [registration-success props] :sign-up [registration props] :reset-password-email [provide-email-form props] :reset-password-code [reset-password-form props] [sign-in-form props])]))}))
d12d0364913c733e7bb4fbfdaa16137a494aca9ec5d1e96837f264f7eeae1240
spawnfest/eep49ers
wxGridCellFloatRenderer.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2009 - 2020 . All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %% %% %CopyrightEnd% %% This file is generated DO NOT EDIT -module(wxGridCellFloatRenderer). -include("wxe.hrl"). -export([destroy/1,getPrecision/1,getWidth/1,new/0,new/1,setParameters/2,setPrecision/2, setWidth/2]). %% inherited exports -export([draw/8,getBestSize/6,parent_class/1]). -type wxGridCellFloatRenderer() :: wx:wx_object(). -export_type([wxGridCellFloatRenderer/0]). %% @hidden parent_class(wxGridCellStringRenderer) -> true; parent_class(wxGridCellRenderer) -> true; parent_class(_Class) -> erlang:error({badtype, ?MODULE}). %% @equiv new([]) -spec new() -> wxGridCellFloatRenderer(). new() -> new([]). %% @doc See <a href="#wxgridcellfloatrendererwxgridcellfloatrenderer">external documentation</a>. -spec new([Option]) -> wxGridCellFloatRenderer() when Option :: {'width', integer()} | {'precision', integer()} | {'format', integer()}. new(Options) when is_list(Options) -> MOpts = fun({width, _width} = Arg) -> Arg; ({precision, _precision} = Arg) -> Arg; ({format, _format} = Arg) -> Arg; (BadOpt) -> erlang:error({badoption, BadOpt}) end, Opts = lists:map(MOpts, Options), wxe_util:queue_cmd(Opts,?get_env(),?wxGridCellFloatRenderer_new), wxe_util:rec(?wxGridCellFloatRenderer_new). %% @doc See <a href="#wxgridcellfloatrenderergetprecision">external documentation</a>. -spec getPrecision(This) -> integer() when This::wxGridCellFloatRenderer(). getPrecision(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxGridCellFloatRenderer), wxe_util:queue_cmd(This,?get_env(),?wxGridCellFloatRenderer_GetPrecision), wxe_util:rec(?wxGridCellFloatRenderer_GetPrecision). %% @doc See <a href="#wxgridcellfloatrenderergetwidth">external documentation</a>. -spec getWidth(This) -> integer() when This::wxGridCellFloatRenderer(). getWidth(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxGridCellFloatRenderer), wxe_util:queue_cmd(This,?get_env(),?wxGridCellFloatRenderer_GetWidth), wxe_util:rec(?wxGridCellFloatRenderer_GetWidth). %% @doc See <a href="#wxgridcellfloatrenderersetparameters">external documentation</a>. -spec setParameters(This, Params) -> 'ok' when This::wxGridCellFloatRenderer(), Params::unicode:chardata(). setParameters(#wx_ref{type=ThisT}=This,Params) when ?is_chardata(Params) -> ?CLASS(ThisT,wxGridCellFloatRenderer), Params_UC = unicode:characters_to_binary(Params), wxe_util:queue_cmd(This,Params_UC,?get_env(),?wxGridCellFloatRenderer_SetParameters). %% @doc See <a href="#wxgridcellfloatrenderersetprecision">external documentation</a>. -spec setPrecision(This, Precision) -> 'ok' when This::wxGridCellFloatRenderer(), Precision::integer(). setPrecision(#wx_ref{type=ThisT}=This,Precision) when is_integer(Precision) -> ?CLASS(ThisT,wxGridCellFloatRenderer), wxe_util:queue_cmd(This,Precision,?get_env(),?wxGridCellFloatRenderer_SetPrecision). %% @doc See <a href="#wxgridcellfloatrenderersetwidth">external documentation</a>. -spec setWidth(This, Width) -> 'ok' when This::wxGridCellFloatRenderer(), Width::integer(). setWidth(#wx_ref{type=ThisT}=This,Width) when is_integer(Width) -> ?CLASS(ThisT,wxGridCellFloatRenderer), wxe_util:queue_cmd(This,Width,?get_env(),?wxGridCellFloatRenderer_SetWidth). %% @doc Destroys this object, do not use object again -spec destroy(This::wxGridCellFloatRenderer()) -> 'ok'. destroy(Obj=#wx_ref{type=Type}) -> ?CLASS(Type,wxGridCellFloatRenderer), wxe_util:queue_cmd(Obj, ?get_env(), ?wxGridCellFloatRenderer_destroy), ok. %% From wxGridCellStringRenderer From wxGridCellRenderer %% @hidden getBestSize(This,Grid,Attr,Dc,Row,Col) -> wxGridCellRenderer:getBestSize(This,Grid,Attr,Dc,Row,Col). %% @hidden draw(This,Grid,Attr,Dc,Rect,Row,Col,IsSelected) -> wxGridCellRenderer:draw(This,Grid,Attr,Dc,Rect,Row,Col,IsSelected).
null
https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/wx/src/gen/wxGridCellFloatRenderer.erl
erlang
%CopyrightBegin% you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. %CopyrightEnd% This file is generated DO NOT EDIT inherited exports @hidden @equiv new([]) @doc See <a href="#wxgridcellfloatrendererwxgridcellfloatrenderer">external documentation</a>. @doc See <a href="#wxgridcellfloatrenderergetprecision">external documentation</a>. @doc See <a href="#wxgridcellfloatrenderergetwidth">external documentation</a>. @doc See <a href="#wxgridcellfloatrenderersetparameters">external documentation</a>. @doc See <a href="#wxgridcellfloatrenderersetprecision">external documentation</a>. @doc See <a href="#wxgridcellfloatrenderersetwidth">external documentation</a>. @doc Destroys this object, do not use object again From wxGridCellStringRenderer @hidden @hidden
Copyright Ericsson AB 2009 - 2020 . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(wxGridCellFloatRenderer). -include("wxe.hrl"). -export([destroy/1,getPrecision/1,getWidth/1,new/0,new/1,setParameters/2,setPrecision/2, setWidth/2]). -export([draw/8,getBestSize/6,parent_class/1]). -type wxGridCellFloatRenderer() :: wx:wx_object(). -export_type([wxGridCellFloatRenderer/0]). parent_class(wxGridCellStringRenderer) -> true; parent_class(wxGridCellRenderer) -> true; parent_class(_Class) -> erlang:error({badtype, ?MODULE}). -spec new() -> wxGridCellFloatRenderer(). new() -> new([]). -spec new([Option]) -> wxGridCellFloatRenderer() when Option :: {'width', integer()} | {'precision', integer()} | {'format', integer()}. new(Options) when is_list(Options) -> MOpts = fun({width, _width} = Arg) -> Arg; ({precision, _precision} = Arg) -> Arg; ({format, _format} = Arg) -> Arg; (BadOpt) -> erlang:error({badoption, BadOpt}) end, Opts = lists:map(MOpts, Options), wxe_util:queue_cmd(Opts,?get_env(),?wxGridCellFloatRenderer_new), wxe_util:rec(?wxGridCellFloatRenderer_new). -spec getPrecision(This) -> integer() when This::wxGridCellFloatRenderer(). getPrecision(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxGridCellFloatRenderer), wxe_util:queue_cmd(This,?get_env(),?wxGridCellFloatRenderer_GetPrecision), wxe_util:rec(?wxGridCellFloatRenderer_GetPrecision). -spec getWidth(This) -> integer() when This::wxGridCellFloatRenderer(). getWidth(#wx_ref{type=ThisT}=This) -> ?CLASS(ThisT,wxGridCellFloatRenderer), wxe_util:queue_cmd(This,?get_env(),?wxGridCellFloatRenderer_GetWidth), wxe_util:rec(?wxGridCellFloatRenderer_GetWidth). -spec setParameters(This, Params) -> 'ok' when This::wxGridCellFloatRenderer(), Params::unicode:chardata(). setParameters(#wx_ref{type=ThisT}=This,Params) when ?is_chardata(Params) -> ?CLASS(ThisT,wxGridCellFloatRenderer), Params_UC = unicode:characters_to_binary(Params), wxe_util:queue_cmd(This,Params_UC,?get_env(),?wxGridCellFloatRenderer_SetParameters). -spec setPrecision(This, Precision) -> 'ok' when This::wxGridCellFloatRenderer(), Precision::integer(). setPrecision(#wx_ref{type=ThisT}=This,Precision) when is_integer(Precision) -> ?CLASS(ThisT,wxGridCellFloatRenderer), wxe_util:queue_cmd(This,Precision,?get_env(),?wxGridCellFloatRenderer_SetPrecision). -spec setWidth(This, Width) -> 'ok' when This::wxGridCellFloatRenderer(), Width::integer(). setWidth(#wx_ref{type=ThisT}=This,Width) when is_integer(Width) -> ?CLASS(ThisT,wxGridCellFloatRenderer), wxe_util:queue_cmd(This,Width,?get_env(),?wxGridCellFloatRenderer_SetWidth). -spec destroy(This::wxGridCellFloatRenderer()) -> 'ok'. destroy(Obj=#wx_ref{type=Type}) -> ?CLASS(Type,wxGridCellFloatRenderer), wxe_util:queue_cmd(Obj, ?get_env(), ?wxGridCellFloatRenderer_destroy), ok. From wxGridCellRenderer getBestSize(This,Grid,Attr,Dc,Row,Col) -> wxGridCellRenderer:getBestSize(This,Grid,Attr,Dc,Row,Col). draw(This,Grid,Attr,Dc,Rect,Row,Col,IsSelected) -> wxGridCellRenderer:draw(This,Grid,Attr,Dc,Rect,Row,Col,IsSelected).
d0c4ab0d884d5d2bde3444af7dda77970ff323c035470e7d2dc2aaa5951a1f93
typeable/compaREST
TraceTree.hs
module Spec.Golden.TraceTree ( tests, ) where import Control.Category import Control.Exception import qualified Data.ByteString.Lazy as BSL import Data.Default import Data.OpenApi.Compare.Run import Data.OpenApi.Compare.Validate.OpenApi () import Data.Text (Text) import qualified Data.Text.Encoding as T import qualified Data.Yaml as Yaml import Spec.Golden.Extra import Test.Tasty (TestTree, testGroup) import Text.Pandoc.Builder import Text.Pandoc.Class import Text.Pandoc.Options import Text.Pandoc.Writers import Prelude hiding (id, (.)) tests :: IO TestTree tests = do traceTreeTests <- goldenInputsTreeUniform "TraceTree" "test/golden" "trace-tree.yaml" ("a.yaml", "b.yaml") Yaml.decodeFileThrow (pure . BSL.fromStrict . Yaml.encode . runChecker) reportTests <- goldenInputsTreeUniform "Report" "test/golden" "report.md" ("a.yaml", "b.yaml") Yaml.decodeFileThrow (runPandoc . writeMarkdown def {writerExtensions = githubMarkdownExtensions} . doc . fst . runReport def) return $ testGroup "Golden tests" [traceTreeTests, reportTests] runPandoc :: PandocPure Text -> IO BSL.ByteString runPandoc = either throwIO (pure . BSL.fromStrict . T.encodeUtf8) . runPure
null
https://raw.githubusercontent.com/typeable/compaREST/db716ee5b2d6e5649042fa32f4cff4d211d92064/test/Spec/Golden/TraceTree.hs
haskell
module Spec.Golden.TraceTree ( tests, ) where import Control.Category import Control.Exception import qualified Data.ByteString.Lazy as BSL import Data.Default import Data.OpenApi.Compare.Run import Data.OpenApi.Compare.Validate.OpenApi () import Data.Text (Text) import qualified Data.Text.Encoding as T import qualified Data.Yaml as Yaml import Spec.Golden.Extra import Test.Tasty (TestTree, testGroup) import Text.Pandoc.Builder import Text.Pandoc.Class import Text.Pandoc.Options import Text.Pandoc.Writers import Prelude hiding (id, (.)) tests :: IO TestTree tests = do traceTreeTests <- goldenInputsTreeUniform "TraceTree" "test/golden" "trace-tree.yaml" ("a.yaml", "b.yaml") Yaml.decodeFileThrow (pure . BSL.fromStrict . Yaml.encode . runChecker) reportTests <- goldenInputsTreeUniform "Report" "test/golden" "report.md" ("a.yaml", "b.yaml") Yaml.decodeFileThrow (runPandoc . writeMarkdown def {writerExtensions = githubMarkdownExtensions} . doc . fst . runReport def) return $ testGroup "Golden tests" [traceTreeTests, reportTests] runPandoc :: PandocPure Text -> IO BSL.ByteString runPandoc = either throwIO (pure . BSL.fromStrict . T.encodeUtf8) . runPure
492ef07adec15ec4a72b9a95edac10fe99b285601baef8b6557d030823746e9d
sgbj/MaximaSharp
nummod.lisp
Maxima functions for floor , ceiling , and friends Copyright ( C ) 2004 , 2005 , 2007 Barton Willis Department of Mathematics University of Nebraska at Kearney ;; Kearney NE 68847 ;; ;; This source code is licensed under the terms of the Lisp Lesser GNU Public License ( LLGPL ) . The LLGPL consists of a preamble , published by Franz Inc. ( ) , and the GNU Library General Public License ( LGPL ) , version 2 , or ( at your option ) ;; any later version. When the preamble conflicts with the LGPL, ;; the preamble takes precedence. ;; 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 Library General Public License for details . You should have received a copy of the GNU Library General Public ;; License along with this library; if not, write to the Free Software Foundation , Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 , USA . (in-package :maxima) (macsyma-module nummod) ;; Let's have version numbers 1,2,3,... (eval-when (:load-toplevel :execute) (mfuncall '$declare '$integervalued '$feature) ($put '$nummod 3 '$version)) (defmacro opcons (op &rest args) `(simplify (list (list ,op) ,@args))) charfun(pred ) evaluates to 1 when the predicate ' pred ' evaluates ;; to true; it evaluates to 0 when 'pred' evaluates to false; otherwise, ;; it evaluates to a noun form. (defprop $charfun simp-charfun operators) (defprop %charfun simp-charfun operators) (defun simp-charfun (e yy z) (declare (ignore yy)) (oneargcheck e) (setq e (take '($is) (simplifya (specrepcheck (second e)) z))) (let ((bool (mevalp e))) (cond ((eq t bool) 1) ((eq nil bool) 0) ((op-equalp e '$is) `(($charfun simp) ,(second e))) (t `(($charfun simp) ,e))))) (defun integer-part-of-sum (e) (let ((i-sum 0) (n-sum 0) (o-sum 0) (n)) (setq e (margs e)) (dolist (ei e) (cond ((maxima-integerp ei) (setq i-sum (add ei i-sum))) ((or (ratnump ei) (floatp ei) ($bfloatp ei)) (setq n-sum (add ei n-sum))) (t (setq o-sum (add ei o-sum))))) (setq n (opcons '$floor n-sum)) (setq i-sum (add i-sum n)) (setq o-sum (add o-sum (sub n-sum n))) (values i-sum o-sum))) (defprop $floor simp-floor operators) (defprop $floor tex-matchfix tex) (defprop $floor (("\\left \\lfloor " ) " \\right \\rfloor") texsym) ;; $floor distributes over lists, matrices, and equations (setf (get '$floor 'distribute_over) '(mlist $matrix mequal)) These for $ entier are copied from orthopoly / orthopoly - init.lisp . (defprop $entier tex-matchfix tex) (defprop $entier (("\\lfloor ") " \\rfloor") texsym) ;; $entier and $fix distributes over lists, matrices, and equations (setf (get '$entier 'distribute_over) '(mlist $matrix mequal)) (setf (get '$fix 'distribute_over) '(mlist $matrix mequal)) For an example , see pretty - good - floor - or - ceiling . Code courtesy of . (defmacro bind-fpprec (val &rest exprs) `(let (fpprec bigfloatzero bigfloatone bfhalf bfmhalf) (let (($fpprec (fpprec1 nil ,val))) ,@exprs))) Return true if the expression can be formed using rational numbers , logs , mplus , , or mtimes . (defun use-radcan-p (e) (or ($ratnump e) (and (op-equalp e '%log 'mexpt 'mplus 'mtimes) (every 'use-radcan-p (cdr e))))) ;; When constantp(x) is true, we use bfloat evaluation to try to determine ;; the ceiling or floor. If numerical evaluation of e is ill-conditioned, this function ;; can misbehave. I'm somewhat uncomfortable with this, but it is no worse than some other stuff . One safeguard -- the evaluation is done with three ;; values for fpprec. When the floating point evaluations are ;; inconsistent, bailout and return nil. I hope that this function is ;; much more likely to return nil than it is to return a bogus value. (defun pretty-good-floor-or-ceiling (x fn &optional digits) (let (($float2bf t) ($algebraic t) (f1) (f2) (f3) (eps) (lb) (ub) (n)) (setq digits (if (and (integerp digits) (> 0 digits)) digits 25)) (catch 'done ;; To handle ceiling(%i^%i), we need to apply rectform. If bfloat ;; is improved, it might be possible to remove this call to rectform. (setq x ($rectform x)) (if (not ($freeof '$%i '$minf '$inf '$und '$infinity x)) (throw 'done nil)) ;; When x doesn't evaluate to a bigfloat, bailout and return nil. This happens when , for example , x = asin(2 ) . For now , bfloatp ;; evaluates to nil for a complex big float. If this ever changes, ;; this code might need to be repaired. (bind-fpprec digits (setq f1 ($bfloat x)) (if (not ($bfloatp f1)) (throw 'done nil))) (incf digits 20) (setq f2 (bind-fpprec digits ($bfloat x))) (if (not ($bfloatp f2)) (throw 'done nil)) (incf digits 20) (bind-fpprec digits (setq f3 ($bfloat x)) (if (not ($bfloatp f3)) (throw 'done nil)) ;; Let's say that the true value of x is in the interval ;; [f3 - |f3| * eps, f3 + |f3| * eps], where eps = 10^(20 - digits). ;; Define n to be the number of integers in this interval; we have (setq eps (power ($bfloat 10) (- 20 digits))) (setq lb (sub f3 (mult (take '(mabs) f3) eps))) (setq ub (add f3 (mult (take '(mabs) f3) eps))) (setq n (sub (take '($ceiling) ub) (take '($ceiling) lb)))) (setq f1 (take (list fn) f1)) (setq f2 (take (list fn) f2)) (setq f3 (take (list fn) f3)) Provided f1 = f2 = f3 and n = 0 , return f1 ; if n = 1 and ( use - radcan - p e ) and ( $ radcan e ) ;; is a $ratnump, return floor / ceiling of radcan(x), (cond ((and (= f1 f2 f3) (= n 0)) f1) ((and (= f1 f2 f3) (= n 1) (use-radcan-p x)) (setq x ($radcan x)) (if ($ratnump x) (take (list fn) x) nil)) (t nil))))) ( a ) The function fpentier rounds a bigfloat towards zero -- we need to ;; check for that. ;; (b) Since limit(f(x))=(m)inf implies limit(floor(f(x)))=(m)inf, floor(inf / minf ) = inf / minf . Since implies ;; minf<limit(floor(f(x)))<inf, floor(ind)=ind ;; I think floor(complex number) should be undefined too. Some folks might like floor(a + % i b ) -- > floor(a ) + % i floor(b ) . But ;; this would violate the integer-valuedness of floor. ;; So floor(infinity) remains unsimplified (defun simp-floor (e e1 z) (oneargcheck e) (setq e (simplifya (specrepcheck (nth 1 e)) z)) (cond ((numberp e) (floor e)) ((ratnump e) (floor (cadr e) (caddr e))) (($bfloatp e) (setq e1 (fpentier e)) (if (and (minusp (cadr e)) (not (zerop1 (sub e1 e)))) (1- e1) e1)) ((maxima-integerp e) e) (($orderlessp e (neg e)) (sub 0 (opcons '$ceiling (neg e)))) ((and (setq e1 (mget e '$numer)) (floor e1))) ((or (member e infinities) (eq e '$und) (eq e '$ind)) '$und) ( ( member e ' ( $ inf $ minf $ ind $ und ) ) e ) ; Proposed code ;; leave floor(infinity) as is ((or (eq e '$zerob)) -1) ((or (eq e '$zeroa)) 0) ((and ($constantp e) (pretty-good-floor-or-ceiling e '$floor))) ((mplusp e) (let ((i-sum) (o-sum)) (multiple-value-setq (i-sum o-sum) (integer-part-of-sum e)) (setq o-sum (if (equal i-sum 0) `(($floor simp) ,o-sum) (opcons '$floor o-sum))) (add i-sum o-sum))) handle 0 < e < 1 implies floor(e ) = 0 and ;; -1 < e < 0 implies floor(e) = -1. ((and (equal ($compare 0 e) "<") (equal ($compare e 1) "<")) 0) ((and (equal ($compare -1 e) "<") (equal ($compare e 0) "<")) -1) (t `(($floor simp) ,e)))) (defun floor-integral (x) (let ((f (take '($floor) x))) (mul f (div 1 2) (add (mul 2 x) -1 (neg f))))) (defun ceiling-integral (x) (let ((f (take '($ceiling) x))) (mul f (div 1 2) (add 1 (mul 2 x) (neg f))))) (putprop '$floor `((x) ,#'floor-integral) 'integral) (putprop '$ceiling `((x) ,#'ceiling-integral) 'integral) (defprop $ceiling simp-ceiling operators) (defprop $ceiling tex-matchfix tex) (defprop $ceiling (("\\left \\lceil " ) " \\right \\rceil") texsym) ;; $ceiling distributes over lists, matrices, and equations. (setf (get '$ceiling 'distribute_over) '(mlist $matrix mequal)) (defun simp-ceiling (e e1 z) (oneargcheck e) (setq e (simplifya (specrepcheck (nth 1 e)) z)) (cond ((numberp e) (ceiling e)) ((ratnump e) (ceiling (cadr e) (caddr e))) (($bfloatp e) (sub 0 (opcons '$floor (sub 0 e)))) ((maxima-integerp e) e) (($orderlessp e (neg e)) (sub* 0 (opcons '$floor (neg e)))) ((and (setq e1 (mget e '$numer)) (ceiling e1))) ((or (member e infinities) (eq e '$und) (eq e '$ind)) '$und) ((or (eq e '$zerob)) 0) ((or (eq e '$zeroa)) 1) ((and ($constantp e) (pretty-good-floor-or-ceiling e '$ceiling))) ((mplusp e) (let ((i-sum) (o-sum)) (multiple-value-setq (i-sum o-sum) (integer-part-of-sum e)) (setq o-sum (if (equal i-sum 0) `(($ceiling simp) ,o-sum) (opcons '$ceiling o-sum))) (add i-sum o-sum))) handle 0 < e < 1 implies ceiling(e ) = 1 and ;; -1 < e < 0 implies ceiling(e) = 0. ((and (equal ($compare 0 e) "<") (equal ($compare e 1) "<")) 1) ((and (equal ($compare -1 e) "<") (equal ($compare e 0) "<")) 0) (t `(($ceiling simp) ,e)))) (defprop $mod simp-nummod operators) (defprop $mod tex-infix tex) (defprop $mod (" \\rm{mod} ") texsym) (defprop $mod 180. tex-rbp) (defprop $mod 180. tex-rbp) ;; $mod distributes over lists, matrices, and equations (setf (get '$mod 'distribute_over) '(mlist $matrix mequal)) See " Concrete Mathematics , " Section 3.21 . (defun simp-nummod (e e1 z) (twoargcheck e) (let ((x (simplifya (specrepcheck (cadr e)) z)) (y (simplifya (specrepcheck (caddr e)) z))) (cond ((or (equal 0 y) (equal 0 x)) x) ((equal 1 y) (sub x (opcons '$floor x))) ((and ($constantp x) ($constantp y)) (sub x (mul y (opcons '$floor (div x y))))) ((not (equal 1 (setq e1 ($gcd x y)))) (mul e1 (opcons '$mod (div x e1) (div y e1)))) (t `(($mod simp) ,x ,y))))) ;; The function 'round' rounds a number to the nearest integer. For a tie, round to the ;; nearest even integer. (defprop %round simp-round operators) (setf (get '%round 'integer-valued) t) (setf (get '%round 'reflection-rule) #'odd-function-reflect) (setf (get '$round 'alias) '%round) (setf (get '$round 'verb) '%round) (setf (get '%round 'noun) '$round) ;; $round distributes over lists, matrices, and equations. (setf (get '$round 'distribute_over) '(mlist $matrix mequal)) (defun simp-round (e yy z) (oneargcheck e) find a use for the otherwise unused YY . (setq e (simplifya (specrepcheck (second e)) z)) (cond (($featurep e '$integer) e) ;; takes care of round(round(x)) --> round(x). ((member e '($inf $minf $und $ind) :test #'eq) e) (t (let* ((lb (take '($floor) e)) (ub (take '($ceiling) e)) (sgn (csign (sub (sub ub e) (sub e lb))))) (cond ((eq sgn t) `((,yy simp) ,e)) ((eq sgn '$neg) ub) ((eq sgn '$pos) lb) ((alike lb ub) lb) ;; For floats that are integers, this can happen. Maybe featurep should catch this. ((and (eq sgn '$zero) ($featurep lb '$even)) lb) ((and (eq sgn '$zero) ($featurep ub '$even)) ub) ((apply-reflection-simp yy e t)) (t `((,yy simp) ,e))))))) Round a number towards zero . (defprop %truncate simp-truncate operators) (setf (get '%truncate 'integer-valued) t) (setf (get '%truncate 'reflection-rule) #'odd-function-reflect) (setf (get '$truncate 'alias) '%truncate) (setf (get '$truncate 'verb) '%truncate) (setf (get '%truncate 'noun) '$truncate) (defun simp-truncate (e yy z) (oneargcheck e) find a use for the otherwise unused YY . (setq e (simplifya (specrepcheck (second e)) z)) (cond (($featurep e '$integer) e) ;; takes care of truncate(truncate(x)) --> truncate(x). ((member e '($inf $minf $und $ind) :test #'eq) e) (t (let ((sgn (csign e))) (cond ((member sgn '($neg $nz) :test #'eq) (take '($ceiling) e)) ((member sgn '($zero $pz $pos) :test #'eq) (take '($floor) e)) ((apply-reflection-simp yy e t)) (t `((,yy simp) ,e)))))))
null
https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/src/nummod.lisp
lisp
Kearney NE 68847 This source code is licensed under the terms of the Lisp Lesser any later version. When the preamble conflicts with the LGPL, the preamble takes precedence. 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 License along with this library; if not, write to the Let's have version numbers 1,2,3,... to true; it evaluates to 0 when 'pred' evaluates to false; otherwise, it evaluates to a noun form. $floor distributes over lists, matrices, and equations $entier and $fix distributes over lists, matrices, and equations When constantp(x) is true, we use bfloat evaluation to try to determine the ceiling or floor. If numerical evaluation of e is ill-conditioned, this function can misbehave. I'm somewhat uncomfortable with this, but it is no worse values for fpprec. When the floating point evaluations are inconsistent, bailout and return nil. I hope that this function is much more likely to return nil than it is to return a bogus value. To handle ceiling(%i^%i), we need to apply rectform. If bfloat is improved, it might be possible to remove this call to rectform. When x doesn't evaluate to a bigfloat, bailout and return nil. evaluates to nil for a complex big float. If this ever changes, this code might need to be repaired. Let's say that the true value of x is in the interval [f3 - |f3| * eps, f3 + |f3| * eps], where eps = 10^(20 - digits). Define n to be the number of integers in this interval; we have if n = 1 and ( use - radcan - p e ) and ( $ radcan e ) is a $ratnump, return floor / ceiling of radcan(x), check for that. (b) Since limit(f(x))=(m)inf implies limit(floor(f(x)))=(m)inf, minf<limit(floor(f(x)))<inf, floor(ind)=ind I think floor(complex number) should be undefined too. Some folks this would violate the integer-valuedness of floor. So floor(infinity) remains unsimplified Proposed code leave floor(infinity) as is -1 < e < 0 implies floor(e) = -1. $ceiling distributes over lists, matrices, and equations. -1 < e < 0 implies ceiling(e) = 0. $mod distributes over lists, matrices, and equations The function 'round' rounds a number to the nearest integer. For a tie, round to the nearest even integer. $round distributes over lists, matrices, and equations. takes care of round(round(x)) --> round(x). For floats that are integers, this can happen. Maybe featurep should catch this. takes care of truncate(truncate(x)) --> truncate(x).
Maxima functions for floor , ceiling , and friends Copyright ( C ) 2004 , 2005 , 2007 Barton Willis Department of Mathematics University of Nebraska at Kearney GNU Public License ( LLGPL ) . The LLGPL consists of a preamble , published by Franz Inc. ( ) , and the GNU Library General Public License ( LGPL ) , version 2 , or ( at your option ) Library General Public License for details . You should have received a copy of the GNU Library General Public Free Software Foundation , Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 , USA . (in-package :maxima) (macsyma-module nummod) (eval-when (:load-toplevel :execute) (mfuncall '$declare '$integervalued '$feature) ($put '$nummod 3 '$version)) (defmacro opcons (op &rest args) `(simplify (list (list ,op) ,@args))) charfun(pred ) evaluates to 1 when the predicate ' pred ' evaluates (defprop $charfun simp-charfun operators) (defprop %charfun simp-charfun operators) (defun simp-charfun (e yy z) (declare (ignore yy)) (oneargcheck e) (setq e (take '($is) (simplifya (specrepcheck (second e)) z))) (let ((bool (mevalp e))) (cond ((eq t bool) 1) ((eq nil bool) 0) ((op-equalp e '$is) `(($charfun simp) ,(second e))) (t `(($charfun simp) ,e))))) (defun integer-part-of-sum (e) (let ((i-sum 0) (n-sum 0) (o-sum 0) (n)) (setq e (margs e)) (dolist (ei e) (cond ((maxima-integerp ei) (setq i-sum (add ei i-sum))) ((or (ratnump ei) (floatp ei) ($bfloatp ei)) (setq n-sum (add ei n-sum))) (t (setq o-sum (add ei o-sum))))) (setq n (opcons '$floor n-sum)) (setq i-sum (add i-sum n)) (setq o-sum (add o-sum (sub n-sum n))) (values i-sum o-sum))) (defprop $floor simp-floor operators) (defprop $floor tex-matchfix tex) (defprop $floor (("\\left \\lfloor " ) " \\right \\rfloor") texsym) (setf (get '$floor 'distribute_over) '(mlist $matrix mequal)) These for $ entier are copied from orthopoly / orthopoly - init.lisp . (defprop $entier tex-matchfix tex) (defprop $entier (("\\lfloor ") " \\rfloor") texsym) (setf (get '$entier 'distribute_over) '(mlist $matrix mequal)) (setf (get '$fix 'distribute_over) '(mlist $matrix mequal)) For an example , see pretty - good - floor - or - ceiling . Code courtesy of . (defmacro bind-fpprec (val &rest exprs) `(let (fpprec bigfloatzero bigfloatone bfhalf bfmhalf) (let (($fpprec (fpprec1 nil ,val))) ,@exprs))) Return true if the expression can be formed using rational numbers , logs , mplus , , or mtimes . (defun use-radcan-p (e) (or ($ratnump e) (and (op-equalp e '%log 'mexpt 'mplus 'mtimes) (every 'use-radcan-p (cdr e))))) than some other stuff . One safeguard -- the evaluation is done with three (defun pretty-good-floor-or-ceiling (x fn &optional digits) (let (($float2bf t) ($algebraic t) (f1) (f2) (f3) (eps) (lb) (ub) (n)) (setq digits (if (and (integerp digits) (> 0 digits)) digits 25)) (catch 'done (setq x ($rectform x)) (if (not ($freeof '$%i '$minf '$inf '$und '$infinity x)) (throw 'done nil)) This happens when , for example , x = asin(2 ) . For now , bfloatp (bind-fpprec digits (setq f1 ($bfloat x)) (if (not ($bfloatp f1)) (throw 'done nil))) (incf digits 20) (setq f2 (bind-fpprec digits ($bfloat x))) (if (not ($bfloatp f2)) (throw 'done nil)) (incf digits 20) (bind-fpprec digits (setq f3 ($bfloat x)) (if (not ($bfloatp f3)) (throw 'done nil)) (setq eps (power ($bfloat 10) (- 20 digits))) (setq lb (sub f3 (mult (take '(mabs) f3) eps))) (setq ub (add f3 (mult (take '(mabs) f3) eps))) (setq n (sub (take '($ceiling) ub) (take '($ceiling) lb)))) (setq f1 (take (list fn) f1)) (setq f2 (take (list fn) f2)) (setq f3 (take (list fn) f3)) (cond ((and (= f1 f2 f3) (= n 0)) f1) ((and (= f1 f2 f3) (= n 1) (use-radcan-p x)) (setq x ($radcan x)) (if ($ratnump x) (take (list fn) x) nil)) (t nil))))) ( a ) The function fpentier rounds a bigfloat towards zero -- we need to floor(inf / minf ) = inf / minf . Since implies might like floor(a + % i b ) -- > floor(a ) + % i floor(b ) . But (defun simp-floor (e e1 z) (oneargcheck e) (setq e (simplifya (specrepcheck (nth 1 e)) z)) (cond ((numberp e) (floor e)) ((ratnump e) (floor (cadr e) (caddr e))) (($bfloatp e) (setq e1 (fpentier e)) (if (and (minusp (cadr e)) (not (zerop1 (sub e1 e)))) (1- e1) e1)) ((maxima-integerp e) e) (($orderlessp e (neg e)) (sub 0 (opcons '$ceiling (neg e)))) ((and (setq e1 (mget e '$numer)) (floor e1))) ((or (member e infinities) (eq e '$und) (eq e '$ind)) '$und) ((or (eq e '$zerob)) -1) ((or (eq e '$zeroa)) 0) ((and ($constantp e) (pretty-good-floor-or-ceiling e '$floor))) ((mplusp e) (let ((i-sum) (o-sum)) (multiple-value-setq (i-sum o-sum) (integer-part-of-sum e)) (setq o-sum (if (equal i-sum 0) `(($floor simp) ,o-sum) (opcons '$floor o-sum))) (add i-sum o-sum))) handle 0 < e < 1 implies floor(e ) = 0 and ((and (equal ($compare 0 e) "<") (equal ($compare e 1) "<")) 0) ((and (equal ($compare -1 e) "<") (equal ($compare e 0) "<")) -1) (t `(($floor simp) ,e)))) (defun floor-integral (x) (let ((f (take '($floor) x))) (mul f (div 1 2) (add (mul 2 x) -1 (neg f))))) (defun ceiling-integral (x) (let ((f (take '($ceiling) x))) (mul f (div 1 2) (add 1 (mul 2 x) (neg f))))) (putprop '$floor `((x) ,#'floor-integral) 'integral) (putprop '$ceiling `((x) ,#'ceiling-integral) 'integral) (defprop $ceiling simp-ceiling operators) (defprop $ceiling tex-matchfix tex) (defprop $ceiling (("\\left \\lceil " ) " \\right \\rceil") texsym) (setf (get '$ceiling 'distribute_over) '(mlist $matrix mequal)) (defun simp-ceiling (e e1 z) (oneargcheck e) (setq e (simplifya (specrepcheck (nth 1 e)) z)) (cond ((numberp e) (ceiling e)) ((ratnump e) (ceiling (cadr e) (caddr e))) (($bfloatp e) (sub 0 (opcons '$floor (sub 0 e)))) ((maxima-integerp e) e) (($orderlessp e (neg e)) (sub* 0 (opcons '$floor (neg e)))) ((and (setq e1 (mget e '$numer)) (ceiling e1))) ((or (member e infinities) (eq e '$und) (eq e '$ind)) '$und) ((or (eq e '$zerob)) 0) ((or (eq e '$zeroa)) 1) ((and ($constantp e) (pretty-good-floor-or-ceiling e '$ceiling))) ((mplusp e) (let ((i-sum) (o-sum)) (multiple-value-setq (i-sum o-sum) (integer-part-of-sum e)) (setq o-sum (if (equal i-sum 0) `(($ceiling simp) ,o-sum) (opcons '$ceiling o-sum))) (add i-sum o-sum))) handle 0 < e < 1 implies ceiling(e ) = 1 and ((and (equal ($compare 0 e) "<") (equal ($compare e 1) "<")) 1) ((and (equal ($compare -1 e) "<") (equal ($compare e 0) "<")) 0) (t `(($ceiling simp) ,e)))) (defprop $mod simp-nummod operators) (defprop $mod tex-infix tex) (defprop $mod (" \\rm{mod} ") texsym) (defprop $mod 180. tex-rbp) (defprop $mod 180. tex-rbp) (setf (get '$mod 'distribute_over) '(mlist $matrix mequal)) See " Concrete Mathematics , " Section 3.21 . (defun simp-nummod (e e1 z) (twoargcheck e) (let ((x (simplifya (specrepcheck (cadr e)) z)) (y (simplifya (specrepcheck (caddr e)) z))) (cond ((or (equal 0 y) (equal 0 x)) x) ((equal 1 y) (sub x (opcons '$floor x))) ((and ($constantp x) ($constantp y)) (sub x (mul y (opcons '$floor (div x y))))) ((not (equal 1 (setq e1 ($gcd x y)))) (mul e1 (opcons '$mod (div x e1) (div y e1)))) (t `(($mod simp) ,x ,y))))) (defprop %round simp-round operators) (setf (get '%round 'integer-valued) t) (setf (get '%round 'reflection-rule) #'odd-function-reflect) (setf (get '$round 'alias) '%round) (setf (get '$round 'verb) '%round) (setf (get '%round 'noun) '$round) (setf (get '$round 'distribute_over) '(mlist $matrix mequal)) (defun simp-round (e yy z) (oneargcheck e) find a use for the otherwise unused YY . (setq e (simplifya (specrepcheck (second e)) z)) ((member e '($inf $minf $und $ind) :test #'eq) e) (t (let* ((lb (take '($floor) e)) (ub (take '($ceiling) e)) (sgn (csign (sub (sub ub e) (sub e lb))))) (cond ((eq sgn t) `((,yy simp) ,e)) ((eq sgn '$neg) ub) ((eq sgn '$pos) lb) ((and (eq sgn '$zero) ($featurep lb '$even)) lb) ((and (eq sgn '$zero) ($featurep ub '$even)) ub) ((apply-reflection-simp yy e t)) (t `((,yy simp) ,e))))))) Round a number towards zero . (defprop %truncate simp-truncate operators) (setf (get '%truncate 'integer-valued) t) (setf (get '%truncate 'reflection-rule) #'odd-function-reflect) (setf (get '$truncate 'alias) '%truncate) (setf (get '$truncate 'verb) '%truncate) (setf (get '%truncate 'noun) '$truncate) (defun simp-truncate (e yy z) (oneargcheck e) find a use for the otherwise unused YY . (setq e (simplifya (specrepcheck (second e)) z)) ((member e '($inf $minf $und $ind) :test #'eq) e) (t (let ((sgn (csign e))) (cond ((member sgn '($neg $nz) :test #'eq) (take '($ceiling) e)) ((member sgn '($zero $pz $pos) :test #'eq) (take '($floor) e)) ((apply-reflection-simp yy e t)) (t `((,yy simp) ,e)))))))
fb8d39fb6059ba102a385d30a9f201f49989849851defe89798eeec4139cc6cb
FlowerWrong/mblog
attrs.erl
%% --- Excerpted from " Programming Erlang , Second Edition " , published by The Pragmatic Bookshelf . %% Copyrights apply to this code. It may not be used to create training material, %% courses, books, articles, and the like. Contact us if you are in doubt. %% We make no guarantees that this code is fit for any purpose. %% Visit for more book information. %%--- -module(attrs). -vsn(1234). -author({joe,armstrong}). -purpose("example of attributes"). -export([fac/1]). fac(1) -> 1; fac(N) -> N * fac(N-1).
null
https://raw.githubusercontent.com/FlowerWrong/mblog/3233ede938d2019a7b57391405197ac19c805b27/categories/erlang/demo/jaerlang2_code/attrs.erl
erlang
--- Copyrights apply to this code. It may not be used to create training material, courses, books, articles, and the like. Contact us if you are in doubt. We make no guarantees that this code is fit for any purpose. Visit for more book information. ---
Excerpted from " Programming Erlang , Second Edition " , published by The Pragmatic Bookshelf . -module(attrs). -vsn(1234). -author({joe,armstrong}). -purpose("example of attributes"). -export([fac/1]). fac(1) -> 1; fac(N) -> N * fac(N-1).
1215aeb37503b2395331c93d9d2b18ff18bf1e71387062454218e12d5146e173
iand675/hs-opentelemetry
Cloudflare.hs
{-# LANGUAGE OverloadedStrings #-} module OpenTelemetry.Instrumentation.Cloudflare where import Control.Monad (forM_) import qualified Data.CaseInsensitive as CI import qualified Data.List import Data.Maybe import qualified Data.Text as T import qualified Data.Text.Encoding as T import Network.Wai import OpenTelemetry.Attributes (PrimitiveAttribute (..), ToAttribute (..)) import OpenTelemetry.Context import OpenTelemetry.Instrumentation.Wai (requestContext) import OpenTelemetry.Trace.Core (addAttributes) cloudflareInstrumentationMiddleware :: Middleware cloudflareInstrumentationMiddleware app req sendResp = do let mCtxt = requestContext req forM_ mCtxt $ \ctxt -> do forM_ (lookupSpan ctxt) $ \span_ -> do addAttributes span_ $ concatMap ( \hn -> case Data.List.lookup hn $ requestHeaders req of Nothing -> [] Just val -> [ ( "http.request.header." <> T.decodeUtf8 (CI.foldedCase hn) , toAttribute $ T.decodeUtf8 val ) ] ) headers app req sendResp where headers = [ "cf-connecting-ip" , "true-client-ip" , "cf-ray" CF - Visitor "cf-ipcountry" , -- CDN-Loop "cf-worker" ]
null
https://raw.githubusercontent.com/iand675/hs-opentelemetry/b08550db292ca0d8b9ce9156988e6d08dd6a2e61/instrumentation/cloudflare/src/OpenTelemetry/Instrumentation/Cloudflare.hs
haskell
# LANGUAGE OverloadedStrings # CDN-Loop
module OpenTelemetry.Instrumentation.Cloudflare where import Control.Monad (forM_) import qualified Data.CaseInsensitive as CI import qualified Data.List import Data.Maybe import qualified Data.Text as T import qualified Data.Text.Encoding as T import Network.Wai import OpenTelemetry.Attributes (PrimitiveAttribute (..), ToAttribute (..)) import OpenTelemetry.Context import OpenTelemetry.Instrumentation.Wai (requestContext) import OpenTelemetry.Trace.Core (addAttributes) cloudflareInstrumentationMiddleware :: Middleware cloudflareInstrumentationMiddleware app req sendResp = do let mCtxt = requestContext req forM_ mCtxt $ \ctxt -> do forM_ (lookupSpan ctxt) $ \span_ -> do addAttributes span_ $ concatMap ( \hn -> case Data.List.lookup hn $ requestHeaders req of Nothing -> [] Just val -> [ ( "http.request.header." <> T.decodeUtf8 (CI.foldedCase hn) , toAttribute $ T.decodeUtf8 val ) ] ) headers app req sendResp where headers = [ "cf-connecting-ip" , "true-client-ip" , "cf-ray" CF - Visitor "cf-ipcountry" "cf-worker" ]
a37f75de77c0682631c37d3688e97566ed29143272fa9fafd05f4d480d4f8b95
gfngfn/toy-macro-ml
richPrinting.ml
open Syntax let show_mono_type ty = let rec aux isdom (_, tymain) = match tymain with | BaseType(IntType) -> "int" | BaseType(BoolType) -> "bool" | CodeType(ty1) -> let s = aux true ty1 in "@" ^ s | FuncType(ty1, ty2) -> let s1 = aux true ty1 in let s2 = aux false ty2 in let s = s1 ^ " -> " ^ s2 in if isdom then "(" ^ s ^ ")" else s in aux false ty let pp_mono_type ppf ty = Format.fprintf ppf "%s" (show_mono_type ty) type level = | AppLeft | AppRight | Free let enclose_app_left ppf lev pp = match lev with | AppLeft -> Format.fprintf ppf "(%a)" pp () | AppRight | Free -> pp ppf () let enclose_app_right ppf lev pp = match lev with | AppLeft | AppRight -> Format.fprintf ppf "(%a)" pp () | Free -> pp ppf () let pp_ev_value ppf = function | ValInt(n) -> Format.fprintf ppf "%d" n | ValBool(b) -> Format.fprintf ppf "%B" b let rec pp_ev_value_1 lev ppf = function | V1Embed(c) -> pp_ev_value ppf c | V1Symbol(symb) -> Symbol.pp ppf symb | V1Apply(v1, v2) -> enclose_app_left ppf lev (fun ppf () -> Format.fprintf ppf "%a %a" (pp_ev_value_1 AppRight) v1 (pp_ev_value_1 AppLeft) v2 ) | V1Fix(None, sx, v0) -> enclose_app_right ppf lev (fun ppf () -> Format.fprintf ppf "fun %a -> %a" Symbol.pp sx (pp_ev_value_1 Free) v0 ) | V1Fix(Some(sf), sx, v0) -> enclose_app_right ppf lev (fun ppf () -> Format.fprintf ppf "fix %a fun %a -> %a" Symbol.pp sf Symbol.pp sx (pp_ev_value_1 Free) v0 ) | V1Primitive(x) -> Format.fprintf ppf "%s" x | V1If(v0, v1, v2) -> enclose_app_right ppf lev (fun ppf () -> Format.fprintf ppf "if %a then %a else %a" (pp_ev_value_1 Free) v0 (pp_ev_value_1 Free) v1 (pp_ev_value_1 Free) v2 ) and pp_ev_value_0 lev ppf = function | V0Embed(c) -> pp_ev_value ppf c | V0Closure(_) -> Format.fprintf ppf "<fun>" | V0Primitive(x) -> Format.fprintf ppf "%s" x | V0Next(v1) -> enclose_app_left ppf lev (fun ppf () -> Format.fprintf ppf "@@%a" (pp_ev_value_1 AppLeft) v1 ) let pp_ev_value_1_single = pp_ev_value_1 AppLeft let pp_ev_value_0_single = pp_ev_value_0 AppLeft
null
https://raw.githubusercontent.com/gfngfn/toy-macro-ml/7a5eecfc53691adbd91ceba78f8dac3ef8790054/src/richPrinting.ml
ocaml
open Syntax let show_mono_type ty = let rec aux isdom (_, tymain) = match tymain with | BaseType(IntType) -> "int" | BaseType(BoolType) -> "bool" | CodeType(ty1) -> let s = aux true ty1 in "@" ^ s | FuncType(ty1, ty2) -> let s1 = aux true ty1 in let s2 = aux false ty2 in let s = s1 ^ " -> " ^ s2 in if isdom then "(" ^ s ^ ")" else s in aux false ty let pp_mono_type ppf ty = Format.fprintf ppf "%s" (show_mono_type ty) type level = | AppLeft | AppRight | Free let enclose_app_left ppf lev pp = match lev with | AppLeft -> Format.fprintf ppf "(%a)" pp () | AppRight | Free -> pp ppf () let enclose_app_right ppf lev pp = match lev with | AppLeft | AppRight -> Format.fprintf ppf "(%a)" pp () | Free -> pp ppf () let pp_ev_value ppf = function | ValInt(n) -> Format.fprintf ppf "%d" n | ValBool(b) -> Format.fprintf ppf "%B" b let rec pp_ev_value_1 lev ppf = function | V1Embed(c) -> pp_ev_value ppf c | V1Symbol(symb) -> Symbol.pp ppf symb | V1Apply(v1, v2) -> enclose_app_left ppf lev (fun ppf () -> Format.fprintf ppf "%a %a" (pp_ev_value_1 AppRight) v1 (pp_ev_value_1 AppLeft) v2 ) | V1Fix(None, sx, v0) -> enclose_app_right ppf lev (fun ppf () -> Format.fprintf ppf "fun %a -> %a" Symbol.pp sx (pp_ev_value_1 Free) v0 ) | V1Fix(Some(sf), sx, v0) -> enclose_app_right ppf lev (fun ppf () -> Format.fprintf ppf "fix %a fun %a -> %a" Symbol.pp sf Symbol.pp sx (pp_ev_value_1 Free) v0 ) | V1Primitive(x) -> Format.fprintf ppf "%s" x | V1If(v0, v1, v2) -> enclose_app_right ppf lev (fun ppf () -> Format.fprintf ppf "if %a then %a else %a" (pp_ev_value_1 Free) v0 (pp_ev_value_1 Free) v1 (pp_ev_value_1 Free) v2 ) and pp_ev_value_0 lev ppf = function | V0Embed(c) -> pp_ev_value ppf c | V0Closure(_) -> Format.fprintf ppf "<fun>" | V0Primitive(x) -> Format.fprintf ppf "%s" x | V0Next(v1) -> enclose_app_left ppf lev (fun ppf () -> Format.fprintf ppf "@@%a" (pp_ev_value_1 AppLeft) v1 ) let pp_ev_value_1_single = pp_ev_value_1 AppLeft let pp_ev_value_0_single = pp_ev_value_0 AppLeft
ca9893dffae48c277ad6c8ba07cbe568058a078c8cc4495d5fae0072e7b0e131
yogthos/yuggoth
auth.clj
(ns yuggoth.routes.services.auth (:require [yuggoth.db.core :as db] [yuggoth.config :refer [text]] [noir.session :as session] [noir.util.crypt :as crypt]) (:import org.apache.commons.codec.binary.Base64 java.nio.charset.Charset)) (defn auth [req] (get-in req [:headers "authorization"])) (defn decode-auth [encoded] (let [auth (second (.split encoded " "))] (-> (Base64/decodeBase64 auth) (String. (Charset/forName "UTF-8")) (.split ":")))) (defn login! [req] (let [admin (db/get-admin) [user pass] (decode-auth (auth req))] (if (and (= user (:handle admin)) (crypt/compare pass (:pass admin))) (do (session/put! :admin admin) {:result "ok"}) {:error (text :wrong-password)}))) (defn logout! [] (session/clear!) {:result "ok"})
null
https://raw.githubusercontent.com/yogthos/yuggoth/901541c5809fb1e77c249f26a3aa5df894c88242/src/yuggoth/routes/services/auth.clj
clojure
(ns yuggoth.routes.services.auth (:require [yuggoth.db.core :as db] [yuggoth.config :refer [text]] [noir.session :as session] [noir.util.crypt :as crypt]) (:import org.apache.commons.codec.binary.Base64 java.nio.charset.Charset)) (defn auth [req] (get-in req [:headers "authorization"])) (defn decode-auth [encoded] (let [auth (second (.split encoded " "))] (-> (Base64/decodeBase64 auth) (String. (Charset/forName "UTF-8")) (.split ":")))) (defn login! [req] (let [admin (db/get-admin) [user pass] (decode-auth (auth req))] (if (and (= user (:handle admin)) (crypt/compare pass (:pass admin))) (do (session/put! :admin admin) {:result "ok"}) {:error (text :wrong-password)}))) (defn logout! [] (session/clear!) {:result "ok"})
db3fe1d3c7b6b03621f69bcf67825a9998ff4382fbaa83ced5584c45984f0204
bmeurer/ocaml-arm
camlinternalMod.mli
(***********************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 2004 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with (* the special exception on linking described in file ../LICENSE. *) (* *) (***********************************************************************) $ Id$ (** Run-time support for recursive modules. All functions in this module are for system use only, not for the casual user. *) type shape = | Function | Lazy | Class | Module of shape array val init_mod: string * int * int -> shape -> Obj.t val update_mod: shape -> Obj.t -> Obj.t -> unit
null
https://raw.githubusercontent.com/bmeurer/ocaml-arm/43f7689c76a349febe3d06ae7a4fc1d52984fd8b/stdlib/camlinternalMod.mli
ocaml
********************************************************************* OCaml the special exception on linking described in file ../LICENSE. ********************************************************************* * Run-time support for recursive modules. All functions in this module are for system use only, not for the casual user.
, projet Cristal , INRIA Rocquencourt Copyright 2004 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with $ Id$ type shape = | Function | Lazy | Class | Module of shape array val init_mod: string * int * int -> shape -> Obj.t val update_mod: shape -> Obj.t -> Obj.t -> unit
1a2a00bce79b24132d200673548fffe099b29baf66ee6cb04ef51df4827ea1a5
data61/Mirza
Users.hs
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE MultiParamTypeClasses # module Mirza.OrgRegistry.Handlers.Users ( addUserAuth , addUser , addUserOnlyId , addUserQuery , getUserByIdQuery ) where import qualified Mirza.OrgRegistry.Database.Schema as Schema import Mirza.OrgRegistry.Types as ORT import Servant.API (NoContent (..)) import Database.Beam as B import Database.Beam.Backend.SQL.BeamExtensions import GHC.Stack (HasCallStack, callStack) -- Nothing needs to be done by this endpoint, because by the time that this -- function is called the user will already be added to the users table (this happens via ` ( transformUser0 addUserAuth ) ` which calls ` oauthClaimsToAuthUser ` -- and adds the user to the database if not present). This could be achieved by -- calling any of the other private endpoints, but we have made this endpoint so -- that there is a well defined intuitive process for "regsitering" a user with -- the system. This function also acts as a placeholder incase we ever want to -- add any other associated metadata when adding a user to the system. addUserAuth :: AuthUser -> AppM context err NoContent addUserAuth _ = pure NoContent addUserOnlyId :: ( Member context '[HasDB] , Member err '[AsORError, AsSqlError]) => NewUser -> AppM context err OAuthSub addUserOnlyId user = Schema.user_oauth_sub <$> (addUser user) addUser :: ( Member context '[HasDB] , Member err '[AsORError, AsSqlError]) => NewUser -> AppM context err Schema.User addUser = runDb . addUserQuery -- | Inserts the user into the database. addUserQuery :: (AsORError err, HasCallStack) => NewUser -> DB context err Schema.User addUserQuery (ORT.NewUser oauthSub) = do TODO : use Database . Beam . Backend . SQL.runReturningOne ? res <- pg $ runInsertReturningList$ insert (Schema._users Schema.orgRegistryDB) $ insertValues [Schema.UserT oauthSub Nothing] case res of [r] -> pure $ r -- The user creation has failed, but we can't really think of what would lead to this case. _ -> throwing _UserCreationErrorORE ((show res), callStack) getUserByIdQuery :: OAuthSub -> DB context err (Maybe Schema.User) getUserByIdQuery oAuthSub = do r <- pg $ runSelectReturningList $ select $ do user <- all_ (Schema._users Schema.orgRegistryDB) guard_ (Schema.user_oauth_sub user ==. val_ oAuthSub) pure user case r of [user] -> pure $ Just user _ -> pure Nothing
null
https://raw.githubusercontent.com/data61/Mirza/24e5ccddfc307cceebcc5ce26d35e91020b8ee10/projects/or_scs/src/Mirza/OrgRegistry/Handlers/Users.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # Nothing needs to be done by this endpoint, because by the time that this function is called the user will already be added to the users table (this and adds the user to the database if not present). This could be achieved by calling any of the other private endpoints, but we have made this endpoint so that there is a well defined intuitive process for "regsitering" a user with the system. This function also acts as a placeholder incase we ever want to add any other associated metadata when adding a user to the system. | Inserts the user into the database. The user creation has failed, but we can't really think of what would lead to this case.
# LANGUAGE MultiParamTypeClasses # module Mirza.OrgRegistry.Handlers.Users ( addUserAuth , addUser , addUserOnlyId , addUserQuery , getUserByIdQuery ) where import qualified Mirza.OrgRegistry.Database.Schema as Schema import Mirza.OrgRegistry.Types as ORT import Servant.API (NoContent (..)) import Database.Beam as B import Database.Beam.Backend.SQL.BeamExtensions import GHC.Stack (HasCallStack, callStack) happens via ` ( transformUser0 addUserAuth ) ` which calls ` oauthClaimsToAuthUser ` addUserAuth :: AuthUser -> AppM context err NoContent addUserAuth _ = pure NoContent addUserOnlyId :: ( Member context '[HasDB] , Member err '[AsORError, AsSqlError]) => NewUser -> AppM context err OAuthSub addUserOnlyId user = Schema.user_oauth_sub <$> (addUser user) addUser :: ( Member context '[HasDB] , Member err '[AsORError, AsSqlError]) => NewUser -> AppM context err Schema.User addUser = runDb . addUserQuery addUserQuery :: (AsORError err, HasCallStack) => NewUser -> DB context err Schema.User addUserQuery (ORT.NewUser oauthSub) = do TODO : use Database . Beam . Backend . SQL.runReturningOne ? res <- pg $ runInsertReturningList$ insert (Schema._users Schema.orgRegistryDB) $ insertValues [Schema.UserT oauthSub Nothing] case res of [r] -> pure $ r _ -> throwing _UserCreationErrorORE ((show res), callStack) getUserByIdQuery :: OAuthSub -> DB context err (Maybe Schema.User) getUserByIdQuery oAuthSub = do r <- pg $ runSelectReturningList $ select $ do user <- all_ (Schema._users Schema.orgRegistryDB) guard_ (Schema.user_oauth_sub user ==. val_ oAuthSub) pure user case r of [user] -> pure $ Just user _ -> pure Nothing
9c815dbd397eccaf66d2c489f10d652d8fe0af64b20d28a2caa93d0beb57a8a5
babashka/pod-registry
filewatcher.clj
#!/usr/bin/env bb (require '[babashka.pods :as pods]) (pods/load-pod 'org.babashka/filewatcher "0.0.1") (require '[pod.babashka.filewatcher :as fw]) (fw/watch "." (fn [event] (prn event)) {:delay-ms 5000}) @(promise)
null
https://raw.githubusercontent.com/babashka/pod-registry/73a6ae926647cf22d10ff507be54a53b864b4a3b/examples/filewatcher.clj
clojure
#!/usr/bin/env bb (require '[babashka.pods :as pods]) (pods/load-pod 'org.babashka/filewatcher "0.0.1") (require '[pod.babashka.filewatcher :as fw]) (fw/watch "." (fn [event] (prn event)) {:delay-ms 5000}) @(promise)
68980685082eefdcd7bdd4449053b6638d3d14ca78b10aef580ddf636c4bfeb9
clojure/test.check
random.clj
Copyright ( c ) , , and contributors . ; 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 ^{:author "Gary Fredericks" :doc "Purely functional and splittable pseudo-random number generators."} clojure.test.check.random (:refer-clojure :exclude [unsigned-bit-shift-right])) (defprotocol IRandom (rand-long [rng] "Returns a random long based on the given immutable RNG. Note: to maintain independence you should not call more than one function in the IRandom protocol with the same argument") (rand-double [rng] "Returns a random double between 0.0 (inclusive) and 1.0 (exclusive) based on the given immutable RNG. Note: to maintain independence you should not call more than one function in the IRandom protocol with the same argument") (split [rng] "Returns two new RNGs [rng1 rng2], which should generate sufficiently independent random data. Note: to maintain independence you should not call more than one function in the IRandom protocol with the same argument") (split-n [rng n] "Returns a collection of `n` RNGs, which should generate sufficiently independent random data. Note: to maintain independence you should not call more than one function in the IRandom protocol with the same argument")) Immutable version of Java 8 's java.util . SplittableRandom ;; ;; Meant to give the same results as similar uses of ;; java.util.SplittableRandom, in particular: ;; (= ( - > ( make - java - util - splittable - random 42 ) ;; (rand-long)) ( .nextLong ( SplittableRandom . 42 ) ) ) ;; (= ( - > ( make - java - util - splittable - random 42 ) ;; (split) ( first ) ;; (rand-long)) ( .nextLong ( doto ( SplittableRandom . 42 ) ;; (.split)))) ;; (= ( - > ( make - java - util - splittable - random 42 ) ;; (split) ( second ) ;; (rand-long)) ( ( .split ( SplittableRandom . 42 ) ) ) ) ;; ;; Also see the spec that checks this equivalency. backwards compatibility for clojure 1.5 (def ^:private old-clojure? (not (resolve 'clojure.core/unsigned-bit-shift-right))) (defmacro ^:private unsigned-bit-shift-right [x n] {:pre [(<= 1 n 63)]} (if old-clojure? (let [mask (-> Long/MIN_VALUE (bit-shift-right (dec n)) (bit-not))] `(-> ~x (bit-shift-right ~n) (bit-and ~mask))) `(clojure.core/unsigned-bit-shift-right ~x ~n))) (defmacro ^:private longify "Macro for writing arbitrary longs in the java 0x syntax. E.g. 0x9e3779b97f4a7c15 (which is read as a bigint because it's out of range) becomes -7046029254386353131." [num] (if (> num Long/MAX_VALUE) (-> num (- 18446744073709551616N) (long) (bit-or -9223372036854775808)) num)) (set! *unchecked-math* :warn-on-boxed) (defmacro ^:private bxoubsr "Performs (-> x (unsigned-bit-shift-right n) (bit-xor x))." [x n] (vary-meta `(let [x# ~x] (-> x# (unsigned-bit-shift-right ~n) (bit-xor x#))) assoc :tag 'long)) (defmacro ^:private mix-64 [n] `(-> ~n (bxoubsr 30) (* (longify 0xbf58476d1ce4e5b9)) (bxoubsr 27) (* (longify 0x94d049bb133111eb)) (bxoubsr 31))) (defmacro ^:private mix-gamma [n] `(-> ~n (bxoubsr 33) (* (longify 0xff51afd7ed558ccd)) (bxoubsr 33) (* (longify 0xc4ceb9fe1a85ec53)) (bxoubsr 33) (bit-or 1) (as-> z# (cond-> z# (> 24 (-> z# (bxoubsr 1) (Long/bitCount))) (bit-xor (longify 0xaaaaaaaaaaaaaaaa)))))) (def ^:private ^:const double-unit (/ 1.0 (double (bit-set 0 53)))) Java : 0x1.0p-53 or ( 1.0 / ( 1L < < 53 ) ) (deftype JavaUtilSplittableRandom [^long gamma ^long state] IRandom (rand-long [_] (-> state (+ gamma) (mix-64))) (rand-double [this] (* double-unit (unsigned-bit-shift-right (long (rand-long this)) 11))) (split [this] (let [state' (+ gamma state) state'' (+ gamma state') gamma' (mix-gamma state'')] [(JavaUtilSplittableRandom. gamma state'') (JavaUtilSplittableRandom. gamma' (mix-64 state'))])) (split-n [this n] immitates a particular series of 2 - way splits , but avoids the ;; intermediate allocation. See the `split-n-spec` for a test of the equivalence to 2 - way splits . (let [n (long n)] (case n 0 [] 1 [this] (let [n-dec (dec n)] (loop [state state ret (transient [])] (if (= n-dec (count ret)) (-> ret (conj! (JavaUtilSplittableRandom. gamma state)) (persistent!)) (let [state' (+ gamma state) state'' (+ gamma state') gamma' (mix-gamma state'') new-rng (JavaUtilSplittableRandom. gamma' (mix-64 state'))] (recur state'' (conj! ret new-rng)))))))))) (def ^:private golden-gamma (longify 0x9e3779b97f4a7c15)) (defn make-java-util-splittable-random [^long seed] (JavaUtilSplittableRandom. golden-gamma seed)) ;; some global state to make sure that seedless calls to make-random ;; return independent results (def ^:private next-rng "Returns a random-number generator. Successive calls should return independent results." (let [a (atom (make-java-util-splittable-random (System/currentTimeMillis))) thread-local (proxy [ThreadLocal] [] (initialValue [] (first (split (swap! a #(second (split %)))))))] (fn [] (let [rng (.get thread-local) [rng1 rng2] (split rng)] (.set thread-local rng2) rng1)))) (defn make-random "Given an optional Long seed, returns an object that satisfies the IRandom protocol." ([] (next-rng)) ([seed] (make-java-util-splittable-random seed)))
null
https://raw.githubusercontent.com/clojure/test.check/c05034f911fa140913958b79aa51017d3f2f4426/src/main/clojure/clojure/test/check/random.clj
clojure
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. Meant to give the same results as similar uses of java.util.SplittableRandom, in particular: (rand-long)) (split) (rand-long)) (.split)))) (split) (rand-long)) Also see the spec that checks this equivalency. intermediate allocation. See the `split-n-spec` for a test of some global state to make sure that seedless calls to make-random return independent results
Copyright ( c ) , , and contributors . (ns ^{:author "Gary Fredericks" :doc "Purely functional and splittable pseudo-random number generators."} clojure.test.check.random (:refer-clojure :exclude [unsigned-bit-shift-right])) (defprotocol IRandom (rand-long [rng] "Returns a random long based on the given immutable RNG. Note: to maintain independence you should not call more than one function in the IRandom protocol with the same argument") (rand-double [rng] "Returns a random double between 0.0 (inclusive) and 1.0 (exclusive) based on the given immutable RNG. Note: to maintain independence you should not call more than one function in the IRandom protocol with the same argument") (split [rng] "Returns two new RNGs [rng1 rng2], which should generate sufficiently independent random data. Note: to maintain independence you should not call more than one function in the IRandom protocol with the same argument") (split-n [rng n] "Returns a collection of `n` RNGs, which should generate sufficiently independent random data. Note: to maintain independence you should not call more than one function in the IRandom protocol with the same argument")) Immutable version of Java 8 's java.util . SplittableRandom (= ( - > ( make - java - util - splittable - random 42 ) ( .nextLong ( SplittableRandom . 42 ) ) ) (= ( - > ( make - java - util - splittable - random 42 ) ( first ) ( .nextLong ( doto ( SplittableRandom . 42 ) (= ( - > ( make - java - util - splittable - random 42 ) ( second ) ( ( .split ( SplittableRandom . 42 ) ) ) ) backwards compatibility for clojure 1.5 (def ^:private old-clojure? (not (resolve 'clojure.core/unsigned-bit-shift-right))) (defmacro ^:private unsigned-bit-shift-right [x n] {:pre [(<= 1 n 63)]} (if old-clojure? (let [mask (-> Long/MIN_VALUE (bit-shift-right (dec n)) (bit-not))] `(-> ~x (bit-shift-right ~n) (bit-and ~mask))) `(clojure.core/unsigned-bit-shift-right ~x ~n))) (defmacro ^:private longify "Macro for writing arbitrary longs in the java 0x syntax. E.g. 0x9e3779b97f4a7c15 (which is read as a bigint because it's out of range) becomes -7046029254386353131." [num] (if (> num Long/MAX_VALUE) (-> num (- 18446744073709551616N) (long) (bit-or -9223372036854775808)) num)) (set! *unchecked-math* :warn-on-boxed) (defmacro ^:private bxoubsr "Performs (-> x (unsigned-bit-shift-right n) (bit-xor x))." [x n] (vary-meta `(let [x# ~x] (-> x# (unsigned-bit-shift-right ~n) (bit-xor x#))) assoc :tag 'long)) (defmacro ^:private mix-64 [n] `(-> ~n (bxoubsr 30) (* (longify 0xbf58476d1ce4e5b9)) (bxoubsr 27) (* (longify 0x94d049bb133111eb)) (bxoubsr 31))) (defmacro ^:private mix-gamma [n] `(-> ~n (bxoubsr 33) (* (longify 0xff51afd7ed558ccd)) (bxoubsr 33) (* (longify 0xc4ceb9fe1a85ec53)) (bxoubsr 33) (bit-or 1) (as-> z# (cond-> z# (> 24 (-> z# (bxoubsr 1) (Long/bitCount))) (bit-xor (longify 0xaaaaaaaaaaaaaaaa)))))) (def ^:private ^:const double-unit (/ 1.0 (double (bit-set 0 53)))) Java : 0x1.0p-53 or ( 1.0 / ( 1L < < 53 ) ) (deftype JavaUtilSplittableRandom [^long gamma ^long state] IRandom (rand-long [_] (-> state (+ gamma) (mix-64))) (rand-double [this] (* double-unit (unsigned-bit-shift-right (long (rand-long this)) 11))) (split [this] (let [state' (+ gamma state) state'' (+ gamma state') gamma' (mix-gamma state'')] [(JavaUtilSplittableRandom. gamma state'') (JavaUtilSplittableRandom. gamma' (mix-64 state'))])) (split-n [this n] immitates a particular series of 2 - way splits , but avoids the the equivalence to 2 - way splits . (let [n (long n)] (case n 0 [] 1 [this] (let [n-dec (dec n)] (loop [state state ret (transient [])] (if (= n-dec (count ret)) (-> ret (conj! (JavaUtilSplittableRandom. gamma state)) (persistent!)) (let [state' (+ gamma state) state'' (+ gamma state') gamma' (mix-gamma state'') new-rng (JavaUtilSplittableRandom. gamma' (mix-64 state'))] (recur state'' (conj! ret new-rng)))))))))) (def ^:private golden-gamma (longify 0x9e3779b97f4a7c15)) (defn make-java-util-splittable-random [^long seed] (JavaUtilSplittableRandom. golden-gamma seed)) (def ^:private next-rng "Returns a random-number generator. Successive calls should return independent results." (let [a (atom (make-java-util-splittable-random (System/currentTimeMillis))) thread-local (proxy [ThreadLocal] [] (initialValue [] (first (split (swap! a #(second (split %)))))))] (fn [] (let [rng (.get thread-local) [rng1 rng2] (split rng)] (.set thread-local rng2) rng1)))) (defn make-random "Given an optional Long seed, returns an object that satisfies the IRandom protocol." ([] (next-rng)) ([seed] (make-java-util-splittable-random seed)))
096d89f9790713dcaaf534e241fe1b68332cd0c08dca4d878337373b654cac8b
mokus0/junkbox
BananaUtils.hs
module FRP.BananaUtils where import Control.Arrow import Data.Either import Reactive.Banana -- interesting combinators reactive-banana could easily be extended with... -- (presumably using some more-efficient implementations) partitionE :: (a -> Bool) -> Event t a -> (Event t a, Event t a) partitionE p = filterE p &&& filterE (not . p) partitionEithersE :: Event t (Either a b) -> (Event t a, Event t b) partitionEithersE = (filterJust . fmap (either Just nothing)) &&& (filterJust . fmap (either nothing Just)) where nothing = const Nothing
null
https://raw.githubusercontent.com/mokus0/junkbox/151014bbef9db2b9205209df66c418d6d58b0d9e/Haskell/FRP/BananaUtils.hs
haskell
interesting combinators reactive-banana could easily be extended with... (presumably using some more-efficient implementations)
module FRP.BananaUtils where import Control.Arrow import Data.Either import Reactive.Banana partitionE :: (a -> Bool) -> Event t a -> (Event t a, Event t a) partitionE p = filterE p &&& filterE (not . p) partitionEithersE :: Event t (Either a b) -> (Event t a, Event t b) partitionEithersE = (filterJust . fmap (either Just nothing)) &&& (filterJust . fmap (either nothing Just)) where nothing = const Nothing
0cb979385cb474a60cd409bedc3c14caa7f01321faa38bcd5adba76a3681b740
haskell-works/hw-koans
Ord.hs
module Koan.Ord where import Prelude hiding (max, maximum, min, minimum) enrolled :: Bool enrolled = True -- Introduction to generics max :: Ord a => a -> a -> a max a b = if a > b then a else b min :: Ord a => a -> a -> a min a b = if a < b then a else b maximum :: Ord a => [a] -> a maximum (x:y:xs) = x `max` maximum (y:xs) maximum [x] = x minimum :: Ord a => [a] -> a minimum (x:y:xs) = x `min` minimum (y:xs) minimum [x] = x insert :: Ord a => a -> [a] -> [a] insert e ls = go (compare) e ls where go _ x [] = [x] go cmp x ys@(y:ys') = case cmp x y of GT -> y : go cmp x ys' _ -> x : ys sort :: Ord a => [a] -> [a] sort (pivot:xs) = sort [x | x <- xs, x < pivot] ++ [pivot] ++ sort [x | x <- xs, x >= pivot] sort [] = []
null
https://raw.githubusercontent.com/haskell-works/hw-koans/a807e72513d91ddf1c8aa445371b94bb169f22fd/solution/Koan/Ord.hs
haskell
Introduction to generics
module Koan.Ord where import Prelude hiding (max, maximum, min, minimum) enrolled :: Bool enrolled = True max :: Ord a => a -> a -> a max a b = if a > b then a else b min :: Ord a => a -> a -> a min a b = if a < b then a else b maximum :: Ord a => [a] -> a maximum (x:y:xs) = x `max` maximum (y:xs) maximum [x] = x minimum :: Ord a => [a] -> a minimum (x:y:xs) = x `min` minimum (y:xs) minimum [x] = x insert :: Ord a => a -> [a] -> [a] insert e ls = go (compare) e ls where go _ x [] = [x] go cmp x ys@(y:ys') = case cmp x y of GT -> y : go cmp x ys' _ -> x : ys sort :: Ord a => [a] -> [a] sort (pivot:xs) = sort [x | x <- xs, x < pivot] ++ [pivot] ++ sort [x | x <- xs, x >= pivot] sort [] = []
55e1a09d7e66a909935aa00b25dfcda8e485707b18ade4dada5f60c0fbe49bf2
samrushing/irken-compiler
t_fficonst.scm
;; -*- Mode: Irken -*- (include "lib/basis.scm") (include "lib/map.scm") (require-ffi 'posix) (%backend bytecode (update-sizeoff-table)) (%backend bytecode (printf "lookup O_TRUNC: " (int (lookup-constant 'O_TRUNC)) "\n")) (printf " O_TRUNC = " (int O_TRUNC) "\n")
null
https://raw.githubusercontent.com/samrushing/irken-compiler/690da48852d55497f873738df54f14e8e135d006/tests/t_fficonst.scm
scheme
-*- Mode: Irken -*-
(include "lib/basis.scm") (include "lib/map.scm") (require-ffi 'posix) (%backend bytecode (update-sizeoff-table)) (%backend bytecode (printf "lookup O_TRUNC: " (int (lookup-constant 'O_TRUNC)) "\n")) (printf " O_TRUNC = " (int O_TRUNC) "\n")
e98928cbba673cc56a2f0e68b3048f311061a6d5388b6fbbe2b127a1d9dedbd1
metawilm/cl-python
function-test.lisp
;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CLPYTHON.TEST -*- ;; This software is Copyright ( c ) Franz Inc. and . Franz Inc. and grant you the rights to ;; distribute and use this software as governed by the terms of the Lisp Lesser GNU Public License ;; (), ;; known as the LLGPL. ;;;; Python function test (in-package :clpython.test) (defun run-function-test () (run-no-error " def a(): pass c = a.func_code assert c.co_argcount == 0 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0 # *-arg assert c.co_flags & 0x08 == 0 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'a' assert c.co_names == () assert c.co_varnames == () print 'a: ok' def a2(): return 1 c = a2.func_code assert c.co_argcount == 0 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0 # *-arg assert c.co_flags & 0x08 == 0 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'a2' assert c.co_names == () assert c.co_varnames == () print 'a2: ok' def a3(): x = 5 return x c = a3.func_code assert c.co_argcount == 0 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0 # *-arg assert c.co_flags & 0x08 == 0 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'a3' assert c.co_names == () assert c.co_varnames == ('x',) print 'a3: ok' def b(x): pass c = b.func_code assert c.co_argcount == 1 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0 # *-arg assert c.co_flags & 0x08 == 0 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'b' assert c.co_names == () assert c.co_varnames == ('x',) print 'b: ok' def d(x, y): pass c = d.func_code assert c.co_argcount == 2 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0 # *-arg assert c.co_flags & 0x08 == 0 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'd' assert c.co_names == () assert c.co_varnames == ('x','y') print 'd: ok' def e((x, y)): pass c = e.func_code assert c.co_argcount == 1 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0 # *-arg assert c.co_flags & 0x08 == 0 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'e' assert c.co_names == () assert c.co_varnames == ('.0', 'x', 'y') print 'e: ok' def e2(a, (x, y)): pass c = e2.func_code assert c.co_argcount == 2 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0 # *-arg assert c.co_flags & 0x08 == 0 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'e2' assert c.co_names == () assert c.co_varnames == ('a', '.1', 'x', 'y') print 'e2: ok' def e3(a, (x, y), b, (p,(q,r))): pass c = e3.func_code assert c.co_argcount == 4 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0 # *-arg assert c.co_flags & 0x08 == 0 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'e3' assert c.co_names == () assert c.co_varnames == ('a', '.1', 'b', '.3', 'x', 'y', 'p', 'q', 'r') print 'e3: ok' def i(*args): pass c = i.func_code assert c.co_argcount == 0 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0x04 # *-arg assert c.co_flags & 0x08 == 0 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'i' assert c.co_names == () assert c.co_varnames == ('args',) print 'i: ok' def i2(**kwargs): pass c = i2.func_code assert c.co_argcount == 0 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0 # *-arg assert c.co_flags & 0x08 == 0x08 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'i2' assert c.co_names == () assert c.co_varnames == ('kwargs',) print 'i2: ok' def i3(*args, **kwargs): pass c = i3.func_code assert c.co_argcount == 0 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0x04 # *-arg assert c.co_flags & 0x08 == 0x08 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'i3' assert c.co_names == () assert c.co_varnames == ('args', 'kwargs',) print 'i3: ok' def i4(a,b, c=1, d=2, *args, **kwargs): pass c = i4.func_code assert c.co_argcount == 4 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0x04 # *-arg assert c.co_flags & 0x08 == 0x08 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'i4' assert c.co_names == () assert c.co_varnames == ('a', 'b', 'c', 'd', 'args', 'kwargs',) print 'i4: ok' def i5(a,(b1,b2), c=1, d=2, *args, **kwargs): pass c = i5.func_code assert c.co_argcount == 4 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0x04 # *-arg assert c.co_flags & 0x08 == 0x08 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'i5' assert c.co_names == () assert c.co_varnames == ('a', '.1', 'c', 'd', 'args', 'kwargs', 'b1', 'b2') print 'i5: ok' def j(a, (p,q)=(1,2), z=3): pass c = j.func_code assert c.co_argcount == 3 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0 # *-arg assert c.co_flags & 0x08 == 0 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'j' assert c.co_names == () assert c.co_varnames == ('a', '.1', 'z', 'p', 'q') print 'j: ok' def k(): yield 1 c = k.func_code assert c.co_argcount == 0 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0 # *-arg assert c.co_flags & 0x08 == 0 # **-arg assert c.co_flags & 0x20 == 0x20 # generator assert c.co_freevars == () assert c.co_name == 'k' assert c.co_names == () assert c.co_varnames == () print 'k: ok'"))
null
https://raw.githubusercontent.com/metawilm/cl-python/bce7f80b0c67d3c9f514556f2d14d098efecdde8/test/function-test.lisp
lisp
-*- Mode: LISP; Syntax: COMMON-LISP; Package: CLPYTHON.TEST -*- distribute and use this software as governed by the terms (), known as the LLGPL. Python function test
This software is Copyright ( c ) Franz Inc. and . Franz Inc. and grant you the rights to of the Lisp Lesser GNU Public License (in-package :clpython.test) (defun run-function-test () (run-no-error " def a(): pass c = a.func_code assert c.co_argcount == 0 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0 # *-arg assert c.co_flags & 0x08 == 0 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'a' assert c.co_names == () assert c.co_varnames == () print 'a: ok' def a2(): return 1 c = a2.func_code assert c.co_argcount == 0 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0 # *-arg assert c.co_flags & 0x08 == 0 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'a2' assert c.co_names == () assert c.co_varnames == () print 'a2: ok' def a3(): x = 5 return x c = a3.func_code assert c.co_argcount == 0 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0 # *-arg assert c.co_flags & 0x08 == 0 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'a3' assert c.co_names == () assert c.co_varnames == ('x',) print 'a3: ok' def b(x): pass c = b.func_code assert c.co_argcount == 1 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0 # *-arg assert c.co_flags & 0x08 == 0 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'b' assert c.co_names == () assert c.co_varnames == ('x',) print 'b: ok' def d(x, y): pass c = d.func_code assert c.co_argcount == 2 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0 # *-arg assert c.co_flags & 0x08 == 0 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'd' assert c.co_names == () assert c.co_varnames == ('x','y') print 'd: ok' def e((x, y)): pass c = e.func_code assert c.co_argcount == 1 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0 # *-arg assert c.co_flags & 0x08 == 0 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'e' assert c.co_names == () assert c.co_varnames == ('.0', 'x', 'y') print 'e: ok' def e2(a, (x, y)): pass c = e2.func_code assert c.co_argcount == 2 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0 # *-arg assert c.co_flags & 0x08 == 0 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'e2' assert c.co_names == () assert c.co_varnames == ('a', '.1', 'x', 'y') print 'e2: ok' def e3(a, (x, y), b, (p,(q,r))): pass c = e3.func_code assert c.co_argcount == 4 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0 # *-arg assert c.co_flags & 0x08 == 0 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'e3' assert c.co_names == () assert c.co_varnames == ('a', '.1', 'b', '.3', 'x', 'y', 'p', 'q', 'r') print 'e3: ok' def i(*args): pass c = i.func_code assert c.co_argcount == 0 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0x04 # *-arg assert c.co_flags & 0x08 == 0 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'i' assert c.co_names == () assert c.co_varnames == ('args',) print 'i: ok' def i2(**kwargs): pass c = i2.func_code assert c.co_argcount == 0 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0 # *-arg assert c.co_flags & 0x08 == 0x08 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'i2' assert c.co_names == () assert c.co_varnames == ('kwargs',) print 'i2: ok' def i3(*args, **kwargs): pass c = i3.func_code assert c.co_argcount == 0 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0x04 # *-arg assert c.co_flags & 0x08 == 0x08 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'i3' assert c.co_names == () assert c.co_varnames == ('args', 'kwargs',) print 'i3: ok' def i4(a,b, c=1, d=2, *args, **kwargs): pass c = i4.func_code assert c.co_argcount == 4 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0x04 # *-arg assert c.co_flags & 0x08 == 0x08 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'i4' assert c.co_names == () assert c.co_varnames == ('a', 'b', 'c', 'd', 'args', 'kwargs',) print 'i4: ok' def i5(a,(b1,b2), c=1, d=2, *args, **kwargs): pass c = i5.func_code assert c.co_argcount == 4 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0x04 # *-arg assert c.co_flags & 0x08 == 0x08 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'i5' assert c.co_names == () assert c.co_varnames == ('a', '.1', 'c', 'd', 'args', 'kwargs', 'b1', 'b2') print 'i5: ok' def j(a, (p,q)=(1,2), z=3): pass c = j.func_code assert c.co_argcount == 3 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0 # *-arg assert c.co_flags & 0x08 == 0 # **-arg assert c.co_flags & 0x20 == 0 # generator assert c.co_freevars == () assert c.co_name == 'j' assert c.co_names == () assert c.co_varnames == ('a', '.1', 'z', 'p', 'q') print 'j: ok' def k(): yield 1 c = k.func_code assert c.co_argcount == 0 assert c.co_cellvars == () assert c.co_flags & 0x04 == 0 # *-arg assert c.co_flags & 0x08 == 0 # **-arg assert c.co_flags & 0x20 == 0x20 # generator assert c.co_freevars == () assert c.co_name == 'k' assert c.co_names == () assert c.co_varnames == () print 'k: ok'"))
154a1b78ddeb56ff1effe6d849a7a72fb80c0347209ab246ee77e53cda252c61
digital-dj-tools/dj-data-converter
cli_profile.cljc
(ns converter.cli-profile (:require [clojure.data.xml :as xml] #?(:clj [clojure.java.io :as io] :cljs [cljs-node-io.core :as io :refer [slurp spit]]) #?(:clj [clojure.spec.alpha :as s] :cljs [cljs.spec.alpha :as s]) #?(:clj [clojure.spec.gen.alpha :as gen] :cljs [cljs.spec.gen.alpha :as gen]) [converter.app :as app] [converter.cli :as cli] [converter.config :as config] [converter.rekordbox.core :as r] [converter.spec :as spec] [converter.stats :as stats] [converter.str :as str] [converter.test-utils :as test] [converter.traktor.core :as t] [converter.universal.core :as u] [spec-tools.core :as st])) #?(:clj (defn setup [file spec item-spec xml-transformer n] (with-open [writer (io/writer file)] TODO make a library spec that does n't have a collection (as-> (test/library item-spec n) $ (do (println "Mean tempo count" (stats/mean-tempos $)) (println "Mean marker count" (stats/mean-markers $)) $) (st/encode spec $ xml-transformer) (xml/emit $ writer))))) #?(:cljs (defn setup [file spec item-spec xml-transformer n] TODO make a library spec that does n't have a collection (as-> (test/library item-spec n) $ (do (println "Mean tempo count" (stats/mean-tempos $)) (println "Mean marker count" (stats/mean-markers $)) $) (st/encode spec $ xml-transformer) (xml/emit-str $) (io/spit file $))))
null
https://raw.githubusercontent.com/digital-dj-tools/dj-data-converter/de1ae5cda60bc64ee3cca1a09b11e1808dd4738a/test/converter/cli_profile.cljc
clojure
(ns converter.cli-profile (:require [clojure.data.xml :as xml] #?(:clj [clojure.java.io :as io] :cljs [cljs-node-io.core :as io :refer [slurp spit]]) #?(:clj [clojure.spec.alpha :as s] :cljs [cljs.spec.alpha :as s]) #?(:clj [clojure.spec.gen.alpha :as gen] :cljs [cljs.spec.gen.alpha :as gen]) [converter.app :as app] [converter.cli :as cli] [converter.config :as config] [converter.rekordbox.core :as r] [converter.spec :as spec] [converter.stats :as stats] [converter.str :as str] [converter.test-utils :as test] [converter.traktor.core :as t] [converter.universal.core :as u] [spec-tools.core :as st])) #?(:clj (defn setup [file spec item-spec xml-transformer n] (with-open [writer (io/writer file)] TODO make a library spec that does n't have a collection (as-> (test/library item-spec n) $ (do (println "Mean tempo count" (stats/mean-tempos $)) (println "Mean marker count" (stats/mean-markers $)) $) (st/encode spec $ xml-transformer) (xml/emit $ writer))))) #?(:cljs (defn setup [file spec item-spec xml-transformer n] TODO make a library spec that does n't have a collection (as-> (test/library item-spec n) $ (do (println "Mean tempo count" (stats/mean-tempos $)) (println "Mean marker count" (stats/mean-markers $)) $) (st/encode spec $ xml-transformer) (xml/emit-str $) (io/spit file $))))
c2d441814593accb9b699ced2fa4bdc089eb278a55e9e77f41bd52298034c713
mentat-collective/MathBox.cljs
time.cljs
(ns mathbox.primitives.time (:require ["mathbox-react" :as box] [mathbox.macros :refer [defprim]])) (defprim box/Clock "*Relative clock that starts from zero.* - `:classes`: `[]` (string array) - Custom classes, e.g. `[\"big\"]` - `:delay`: `0` (number) - Play delay - `:from`: `0` (number) - Play from - `:id`: `null` (nullable string) - Unique ID, e.g. `\"sampler\"` - `:loop`: `false` (bool) - Loop - `:pace`: `1` (number) - Play pace - `:realtime`: `false` (bool) - Run on real time, not clock time - `:seek`: `null` (nullable number) - Seek to time, e.g. `4` - `:speed`: `1` (number) - Play speed - `:to`: `Infinity` (number) - Play until") (defprim box/Now "*Absolute UNIX time in seconds since 01/01/1970* - `:classes`: `[]` (string array) - Custom classes, e.g. `[\"big\"]` - `:id`: `null` (nullable string) - Unique ID, e.g. `\"sampler\"` - `:now`: `null` (nullable timestamp) - Current moment, e.g. `1444094929.619` - `:pace`: `1` (number) - Time pace - `:seek`: `null` (nullable number) - Seek to time - `:speed`: `1` (number) - Time speed")
null
https://raw.githubusercontent.com/mentat-collective/MathBox.cljs/281fc373ca2e2e05de7b789f0c1764ab5a66ea05/src/mathbox/primitives/time.cljs
clojure
(ns mathbox.primitives.time (:require ["mathbox-react" :as box] [mathbox.macros :refer [defprim]])) (defprim box/Clock "*Relative clock that starts from zero.* - `:classes`: `[]` (string array) - Custom classes, e.g. `[\"big\"]` - `:delay`: `0` (number) - Play delay - `:from`: `0` (number) - Play from - `:id`: `null` (nullable string) - Unique ID, e.g. `\"sampler\"` - `:loop`: `false` (bool) - Loop - `:pace`: `1` (number) - Play pace - `:realtime`: `false` (bool) - Run on real time, not clock time - `:seek`: `null` (nullable number) - Seek to time, e.g. `4` - `:speed`: `1` (number) - Play speed - `:to`: `Infinity` (number) - Play until") (defprim box/Now "*Absolute UNIX time in seconds since 01/01/1970* - `:classes`: `[]` (string array) - Custom classes, e.g. `[\"big\"]` - `:id`: `null` (nullable string) - Unique ID, e.g. `\"sampler\"` - `:now`: `null` (nullable timestamp) - Current moment, e.g. `1444094929.619` - `:pace`: `1` (number) - Time pace - `:seek`: `null` (nullable number) - Seek to time - `:speed`: `1` (number) - Time speed")
d42f0efb2d5668d35f794a5f78d5433fdcb3fa4d6f69d8259e964b5fca7a2ee1
nathell/clj-tagsoup
project.clj
(defproject clj-tagsoup "0.3.0" :description "A HTML parser for Clojure." :dependencies [[org.clojure/clojure "1.2.0"] [org.clojure/data.xml "0.0.8"] [org.clojars.nathell/tagsoup "1.2.1"] [net.java.dev.stax-utils/stax-utils "20040917"]])
null
https://raw.githubusercontent.com/nathell/clj-tagsoup/358358493f8c96b41e8fd30ad70becf146a310aa/project.clj
clojure
(defproject clj-tagsoup "0.3.0" :description "A HTML parser for Clojure." :dependencies [[org.clojure/clojure "1.2.0"] [org.clojure/data.xml "0.0.8"] [org.clojars.nathell/tagsoup "1.2.1"] [net.java.dev.stax-utils/stax-utils "20040917"]])
3670cebfd345c4921c9f85addf59297c116b3a79b21e448a306fdb5678735ee9
GaloisInc/cereal
MemBench.hs
# LANGUAGE ForeignFunctionInterface , BangPatterns # module MemBench (memBench) where import Foreign import Foreign.C import Control.Exception import System.CPUTime import Numeric memBench :: Int -> IO () memBench mb = do let bytes = mb * 2^20 allocaBytes bytes $ \ptr -> do let bench label test = do seconds <- time $ test (castPtr ptr) (fromIntegral bytes) let throughput = fromIntegral mb / seconds putStrLn $ show mb ++ "MB of " ++ label ++ " in " ++ showFFloat (Just 3) seconds "s, at: " ++ showFFloat (Just 1) throughput "MB/s" bench "setup " c_wordwrite putStrLn "" putStrLn "C memory throughput benchmarks:" bench "bytes written" c_bytewrite bench "bytes read " c_byteread bench "words written" c_wordwrite bench "words read " c_wordread putStrLn "" putStrLn "Haskell memory throughput benchmarks:" bench "bytes written" hs_bytewrite bench "bytes read " hs_byteread bench "words written" hs_wordwrite bench "words read " hs_wordread hs_bytewrite :: Ptr CUChar -> Int -> IO () hs_bytewrite !ptr bytes = loop 0 0 where iterations = bytes loop :: Int -> CUChar -> IO () loop !i !n | i == iterations = return () | otherwise = do pokeByteOff ptr i n loop (i+1) (n+1) hs_byteread :: Ptr CUChar -> Int -> IO CUChar hs_byteread !ptr bytes = loop 0 0 where iterations = bytes loop :: Int -> CUChar -> IO CUChar loop !i !n | i == iterations = return n | otherwise = do x <- peekByteOff ptr i loop (i+1) (n+x) hs_wordwrite :: Ptr CULong -> Int -> IO () hs_wordwrite !ptr bytes = loop 0 0 where iterations = bytes `div` sizeOf (undefined :: CULong) loop :: Int -> CULong -> IO () loop !i !n | i == iterations = return () | otherwise = do pokeByteOff ptr i n loop (i+1) (n+1) hs_wordread :: Ptr CULong -> Int -> IO CULong hs_wordread !ptr bytes = loop 0 0 where iterations = bytes `div` sizeOf (undefined :: CULong) loop :: Int -> CULong -> IO CULong loop !i !n | i == iterations = return n | otherwise = do x <- peekByteOff ptr i loop (i+1) (n+x) foreign import ccall unsafe "CBenchmark.h byteread" c_byteread :: Ptr CUChar -> CInt -> IO () foreign import ccall unsafe "CBenchmark.h bytewrite" c_bytewrite :: Ptr CUChar -> CInt -> IO () foreign import ccall unsafe "CBenchmark.h wordread" c_wordread :: Ptr CUInt -> CInt -> IO () foreign import ccall unsafe "CBenchmark.h wordwrite" c_wordwrite :: Ptr CUInt -> CInt -> IO () time :: IO a -> IO Double time action = do start <- getCPUTime action end <- getCPUTime return $! (fromIntegral (end - start)) / (10^12)
null
https://raw.githubusercontent.com/GaloisInc/cereal/b4fff04dc2fb28eb0ec5e6c63b53248a63eb4ca5/tests/MemBench.hs
haskell
# LANGUAGE ForeignFunctionInterface , BangPatterns # module MemBench (memBench) where import Foreign import Foreign.C import Control.Exception import System.CPUTime import Numeric memBench :: Int -> IO () memBench mb = do let bytes = mb * 2^20 allocaBytes bytes $ \ptr -> do let bench label test = do seconds <- time $ test (castPtr ptr) (fromIntegral bytes) let throughput = fromIntegral mb / seconds putStrLn $ show mb ++ "MB of " ++ label ++ " in " ++ showFFloat (Just 3) seconds "s, at: " ++ showFFloat (Just 1) throughput "MB/s" bench "setup " c_wordwrite putStrLn "" putStrLn "C memory throughput benchmarks:" bench "bytes written" c_bytewrite bench "bytes read " c_byteread bench "words written" c_wordwrite bench "words read " c_wordread putStrLn "" putStrLn "Haskell memory throughput benchmarks:" bench "bytes written" hs_bytewrite bench "bytes read " hs_byteread bench "words written" hs_wordwrite bench "words read " hs_wordread hs_bytewrite :: Ptr CUChar -> Int -> IO () hs_bytewrite !ptr bytes = loop 0 0 where iterations = bytes loop :: Int -> CUChar -> IO () loop !i !n | i == iterations = return () | otherwise = do pokeByteOff ptr i n loop (i+1) (n+1) hs_byteread :: Ptr CUChar -> Int -> IO CUChar hs_byteread !ptr bytes = loop 0 0 where iterations = bytes loop :: Int -> CUChar -> IO CUChar loop !i !n | i == iterations = return n | otherwise = do x <- peekByteOff ptr i loop (i+1) (n+x) hs_wordwrite :: Ptr CULong -> Int -> IO () hs_wordwrite !ptr bytes = loop 0 0 where iterations = bytes `div` sizeOf (undefined :: CULong) loop :: Int -> CULong -> IO () loop !i !n | i == iterations = return () | otherwise = do pokeByteOff ptr i n loop (i+1) (n+1) hs_wordread :: Ptr CULong -> Int -> IO CULong hs_wordread !ptr bytes = loop 0 0 where iterations = bytes `div` sizeOf (undefined :: CULong) loop :: Int -> CULong -> IO CULong loop !i !n | i == iterations = return n | otherwise = do x <- peekByteOff ptr i loop (i+1) (n+x) foreign import ccall unsafe "CBenchmark.h byteread" c_byteread :: Ptr CUChar -> CInt -> IO () foreign import ccall unsafe "CBenchmark.h bytewrite" c_bytewrite :: Ptr CUChar -> CInt -> IO () foreign import ccall unsafe "CBenchmark.h wordread" c_wordread :: Ptr CUInt -> CInt -> IO () foreign import ccall unsafe "CBenchmark.h wordwrite" c_wordwrite :: Ptr CUInt -> CInt -> IO () time :: IO a -> IO Double time action = do start <- getCPUTime action end <- getCPUTime return $! (fromIntegral (end - start)) / (10^12)
45eabc8b72dde78c929ea30e8346e3693df73260faf6595023eb6df8db5c8c93
potatosalad/erlang-jose
jose_curve448_unsupported.erl
-*- mode : erlang ; tab - width : 4 ; indent - tabs - mode : 1 ; st - rulers : [ 70 ] -*- %% vim: ts=4 sw=4 ft=erlang noet %%%------------------------------------------------------------------- @author < > 2014 - 2022 , %%% @doc %%% %%% @end Created : 02 Jan 2016 by < > %%%------------------------------------------------------------------- -module(jose_curve448_unsupported). -behaviour(jose_curve448). jose_curve448 callbacks -export([eddsa_keypair/0]). -export([eddsa_keypair/1]). -export([eddsa_secret_to_public/1]). -export([ed448_sign/2]). -export([ed448_sign/3]). -export([ed448_verify/3]). -export([ed448_verify/4]). -export([ed448ph_sign/2]). -export([ed448ph_sign/3]). -export([ed448ph_verify/3]). -export([ed448ph_verify/4]). -export([x448_keypair/0]). -export([x448_keypair/1]). -export([x448_secret_to_public/1]). -export([x448_shared_secret/2]). Macros -define(unsupported, erlang:error(operation_not_supported)). %%==================================================================== jose_curve448 callbacks %%==================================================================== EdDSA eddsa_keypair() -> ?unsupported. eddsa_keypair(_Seed) -> ?unsupported. eddsa_secret_to_public(_SecretKey) -> ?unsupported. % Ed448 ed448_sign(_Message, _SecretKey) -> ?unsupported. ed448_sign(_Message, _SecretKey, _Context) -> ?unsupported. ed448_verify(_Signature, _Message, _PublicKey) -> ?unsupported. ed448_verify(_Signature, _Message, _PublicKey, _Context) -> ?unsupported. % Ed448ph ed448ph_sign(_Message, _SecretKey) -> ?unsupported. ed448ph_sign(_Message, _SecretKey, _Context) -> ?unsupported. ed448ph_verify(_Signature, _Message, _PublicKey) -> ?unsupported. ed448ph_verify(_Signature, _Message, _PublicKey, _Context) -> ?unsupported. X448 x448_keypair() -> ?unsupported. x448_keypair(_Seed) -> ?unsupported. x448_secret_to_public(_SecretKey) -> ?unsupported. x448_shared_secret(_MySecretKey, _YourPublicKey) -> ?unsupported.
null
https://raw.githubusercontent.com/potatosalad/erlang-jose/dbc4074066080692246afe613345ef6becc2a3fe/src/jwa/curve448/jose_curve448_unsupported.erl
erlang
vim: ts=4 sw=4 ft=erlang noet ------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- ==================================================================== ==================================================================== Ed448 Ed448ph
-*- mode : erlang ; tab - width : 4 ; indent - tabs - mode : 1 ; st - rulers : [ 70 ] -*- @author < > 2014 - 2022 , Created : 02 Jan 2016 by < > -module(jose_curve448_unsupported). -behaviour(jose_curve448). jose_curve448 callbacks -export([eddsa_keypair/0]). -export([eddsa_keypair/1]). -export([eddsa_secret_to_public/1]). -export([ed448_sign/2]). -export([ed448_sign/3]). -export([ed448_verify/3]). -export([ed448_verify/4]). -export([ed448ph_sign/2]). -export([ed448ph_sign/3]). -export([ed448ph_verify/3]). -export([ed448ph_verify/4]). -export([x448_keypair/0]). -export([x448_keypair/1]). -export([x448_secret_to_public/1]). -export([x448_shared_secret/2]). Macros -define(unsupported, erlang:error(operation_not_supported)). jose_curve448 callbacks EdDSA eddsa_keypair() -> ?unsupported. eddsa_keypair(_Seed) -> ?unsupported. eddsa_secret_to_public(_SecretKey) -> ?unsupported. ed448_sign(_Message, _SecretKey) -> ?unsupported. ed448_sign(_Message, _SecretKey, _Context) -> ?unsupported. ed448_verify(_Signature, _Message, _PublicKey) -> ?unsupported. ed448_verify(_Signature, _Message, _PublicKey, _Context) -> ?unsupported. ed448ph_sign(_Message, _SecretKey) -> ?unsupported. ed448ph_sign(_Message, _SecretKey, _Context) -> ?unsupported. ed448ph_verify(_Signature, _Message, _PublicKey) -> ?unsupported. ed448ph_verify(_Signature, _Message, _PublicKey, _Context) -> ?unsupported. X448 x448_keypair() -> ?unsupported. x448_keypair(_Seed) -> ?unsupported. x448_secret_to_public(_SecretKey) -> ?unsupported. x448_shared_secret(_MySecretKey, _YourPublicKey) -> ?unsupported.
dbddafc0d1ed68eb60171f4c3c5fd52e425a3ee6b8a97c920595b38df12ae8fe
fulcro-legacy/fulcro-css
suite.cljs
(ns fulcro-css.suite (:require fulcro-css.tests-to-run [fulcro-spec.selectors :as sel] [fulcro-spec.suite :as suite])) (enable-console-print!) (suite/def-test-suite on-load {:ns-regex #"fulcro.css.*-spec"} {:default #{::sel/none :focused} :available #{:focused}})
null
https://raw.githubusercontent.com/fulcro-legacy/fulcro-css/fd5526b95d6dfdd2aa6d8fac2218b66709c0ca99/test/fulcro_css/suite.cljs
clojure
(ns fulcro-css.suite (:require fulcro-css.tests-to-run [fulcro-spec.selectors :as sel] [fulcro-spec.suite :as suite])) (enable-console-print!) (suite/def-test-suite on-load {:ns-regex #"fulcro.css.*-spec"} {:default #{::sel/none :focused} :available #{:focused}})
3fafe024978f3e17fbf3546ab4f27364a125793a8b2342b0ec2aaf8f4f2f59f8
jellelicht/guix
wordnet.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2013 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at ;;; your option) any later version. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu packages wordnet) #:use-module (guix packages) #:use-module (guix build-system gnu) #:use-module (guix licenses) #:use-module (guix download) #:use-module (gnu packages tcl)) (define-public wordnet (package (name "wordnet") (version "3.0") (source (origin (method url-fetch) (uri (string-append "/" version "/WordNet-" version ".tar.bz2")) (sha256 (base32 "08pgjvd2vvmqk3h641x63nxp7wqimb9r30889mkyfh2agc62sjbc")))) (build-system gnu-build-system) (arguments `(#:configure-flags (list (string-append "--with-tcl=" (assoc-ref %build-inputs "tcl") "/lib") (string-append "--with-tk=" (assoc-ref %build-inputs "tk") "/lib") Provide the ` result ' field in ` Tcl_Interp ' . ;; See <>. "CFLAGS=-DUSE_INTERP_RESULT") #:phases (alist-cons-after 'install 'post-install (lambda* (#:key inputs outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out")) (bin (assoc-ref outputs "tk")) (tk (assoc-ref inputs "tk")) (tkv ,(let ((v (package-version tk))) (string-take v (string-index-right v #\.))))) Move ` wishwn ' and ` wnb ' to BIN . (for-each (lambda (prog) (let ((orig (string-append out "/bin/" prog)) (dst (string-append bin "/bin/" prog)) (dir (string-append tk "/lib/tk" tkv))) (mkdir-p (dirname dst)) (copy-file orig dst) (delete-file orig) (wrap-program dst `("TK_LIBRARY" "" = (,dir)) `("PATH" ":" prefix (,(string-append out "/bin")))))) '("wishwn" "wnb")) #t)) %standard-phases))) (outputs '("out" for the Tcl / Tk GUI (inputs `(("tk" ,tk) ("tcl" ,tcl))) (home-page "/") (synopsis "Lexical database for the English language") (description "WordNet® is a large lexical database of English. Nouns, verbs, adjectives and adverbs are grouped into sets of cognitive synonyms (synsets), each expressing a distinct concept. Synsets are interlinked by means of conceptual-semantic and lexical relations. The resulting network of meaningfully related words and concepts can be navigated with the browser. WordNet is also freely and publicly available for download. WordNet's structure makes it a useful tool for computational linguistics and natural language processing.") (license x11)))
null
https://raw.githubusercontent.com/jellelicht/guix/83cfc9414fca3ab57c949e18c1ceb375a179b59c/gnu/packages/wordnet.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. See <>.
Copyright © 2013 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu packages wordnet) #:use-module (guix packages) #:use-module (guix build-system gnu) #:use-module (guix licenses) #:use-module (guix download) #:use-module (gnu packages tcl)) (define-public wordnet (package (name "wordnet") (version "3.0") (source (origin (method url-fetch) (uri (string-append "/" version "/WordNet-" version ".tar.bz2")) (sha256 (base32 "08pgjvd2vvmqk3h641x63nxp7wqimb9r30889mkyfh2agc62sjbc")))) (build-system gnu-build-system) (arguments `(#:configure-flags (list (string-append "--with-tcl=" (assoc-ref %build-inputs "tcl") "/lib") (string-append "--with-tk=" (assoc-ref %build-inputs "tk") "/lib") Provide the ` result ' field in ` Tcl_Interp ' . "CFLAGS=-DUSE_INTERP_RESULT") #:phases (alist-cons-after 'install 'post-install (lambda* (#:key inputs outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out")) (bin (assoc-ref outputs "tk")) (tk (assoc-ref inputs "tk")) (tkv ,(let ((v (package-version tk))) (string-take v (string-index-right v #\.))))) Move ` wishwn ' and ` wnb ' to BIN . (for-each (lambda (prog) (let ((orig (string-append out "/bin/" prog)) (dst (string-append bin "/bin/" prog)) (dir (string-append tk "/lib/tk" tkv))) (mkdir-p (dirname dst)) (copy-file orig dst) (delete-file orig) (wrap-program dst `("TK_LIBRARY" "" = (,dir)) `("PATH" ":" prefix (,(string-append out "/bin")))))) '("wishwn" "wnb")) #t)) %standard-phases))) (outputs '("out" for the Tcl / Tk GUI (inputs `(("tk" ,tk) ("tcl" ,tcl))) (home-page "/") (synopsis "Lexical database for the English language") (description "WordNet® is a large lexical database of English. Nouns, verbs, adjectives and adverbs are grouped into sets of cognitive synonyms (synsets), each expressing a distinct concept. Synsets are interlinked by means of conceptual-semantic and lexical relations. The resulting network of meaningfully related words and concepts can be navigated with the browser. WordNet is also freely and publicly available for download. WordNet's structure makes it a useful tool for computational linguistics and natural language processing.") (license x11)))
b6d067fc4532e9e86f461e2db3c9d3290dabfa471339d1346b8435d5a58dda98
nebogeo/weavingcodes
seq.scm
; lz/nz (synth-init 50 22050) (define (lz pat) (vector pat 0)) ;; . . . . . ;; . . . . . ;; . . . . ;; . . . . . ;; (define (lz-pat l) (vector-ref l 0)) (define (lz-pos l) (vector-ref l 1)) (define (lz-inc-pos! l) (vector-set! l 1 (+ (lz-pos l) 1))) (define (lz-set-pat! l v) (vector-set! l 0 v)) (define (safe-ref l i) (cond ((< i 0) #\.) ((>= i (length l)) #\.) (else (list-ref l i)))) (define (lz-tick l) (let ((a (safe-ref (list-ref (lz-pat l) 0) (modulo (lz-pos l) 8))) (b (safe-ref (list-ref (lz-pat l) 1) (modulo (- (lz-pos l) 2) 8))) (c (safe-ref (list-ref (lz-pat l) 2) (modulo (- (lz-pos l) 4) 8))) (d (safe-ref (list-ref (lz-pat l) 3) (modulo (- (lz-pos l) 6) 8)))) (lz-inc-pos! l) (list a b c d))) ; nz (define max-vals 16) (define (make-nz lz vals vx sz cur-t tk off) (vector lz vals vx sz cur-t tk off)) (define (nz-lz n) (vector-ref n 0)) (define (nz-vals n) (vector-ref n 1)) (define (nz-vx n) (vector-ref n 2)) (define (nz-sz n) (vector-ref n 3)) (define (nz-cur-t n) (vector-ref n 4)) (define (nz-tk n) (vector-ref n 5)) (define (nz-off n) (vector-ref n 6)) (define (set-nz-vals! n v) (vector-set! n 1 v)) (define (set-nz-vx! n v) (vector-set! n 2 v)) (define (set-nz-cur-t! n v) (vector-set! n 4 v)) (define (t) (ntp-time)) (define (build-nz lz sz tk) (make-nz lz '(40) 0 sz (ntp-time-add (t) 5) tk 1.0)) (define (nz-pop! nz) (let ((tmp (car (nz-vals nz)))) (when (not (eqv? (length (nz-vals nz)) 1)) (set-nz-vals! nz (cdr (nz-vals nz)))) tmp)) (define (nz-push! nz item) (when (< (length (nz-vals nz)) max-vals) (set-nz-vals! nz (cons item (nz-vals nz))))) (define (nz-dup! nz) (nz-push! nz (car (nz-vals nz)))) (define (ntp>? a b) (or (> (car a) (car b)) (and (eqv? (car a) (car b)) (> (cadr a) (cadr b))))) (define note-dec 1) (define random-drop-off #t) (define humanize #t) (define (nz-tick nz) (when (ntp>? (ntp-time-add (t) (nz-off nz)) (nz-cur-t nz)) (let ((t (lz-tick (nz-lz nz))) (v (car (nz-vals nz)))) (set-nz-cur-t! nz (ntp-time-add (nz-cur-t nz) (nz-tk nz))) (let ((ht (nz-cur-t nz))) (for-each (lambda (t) (when (or random-drop-off (< (random 10) 8)) (define hht ht) (when humanize (set! hht (ntp-time-add ht (* (rndf) 0.03)))) (cond ((char=? t #\+) (set-nz-vals! nz (cons (+ (car (nz-vals nz)) 1) (cdr (nz-vals nz))))) ((char=? t #\-) (set-nz-vals! nz (cons (- (car (nz-vals nz)) 1) (cdr (nz-vals nz))))) ((char=? t #\<) (set-nz-vx! nz (modulo (- (nz-vx nz) 1) (length (nz-sz nz))))) ((char=? t #\>) (set-nz-vx! nz (modulo (+ (nz-vx nz) 1) (length (nz-sz nz))))) ((char=? t #\a) (play hht ((list-ref (list-ref (nz-sz nz) (nz-vx nz)) 0) v) 0)) ((char=? t #\b) (play hht ((list-ref (list-ref (nz-sz nz) (nz-vx nz)) 1) v) 0)) ((char=? t #\c) (play hht ((list-ref (list-ref (nz-sz nz) (nz-vx nz)) 2) v) 0)) ((char=? t #\d) (play hht ((list-ref (list-ref (nz-sz nz) (nz-vx nz)) 3) v) 0)) ((char=? t #\[) (nz-dup! nz)) ((char=? t #\]) (nz-pop! nz)))) (set! v (- v note-dec)) ) t))))) ; -- (define l (lz (list (string->list ".b..b") (string->list ".aa..") (string->list "...b.") (string->list "aaa.a")))) (define ss (list (list (lambda (v) (mul (adsr 0 0.01 0.1 1) (sine (add (mul 20 (sine 4)) (note v))))) (lambda (v) (mul (adsr 0 0.1 0 0) (mul 0.2 (add (saw (* 1.5 (note v))) (saw (note v))))))) (list (lambda (v) (mul (adsr 0 0.03 0.1 1) (mooghp (saw (* (note v) 0.5)) (mul 0.2 (adsr 0.5 0 0 0)) 0.45))) (lambda (v) (mul (adsr 0 0.1 0.1 1) (mooglp (add (saw (* 1.5 (note v))) (saw (note v))) (* v 0.12) 0.4)))) (list (lambda (n) (mul (adsr 0 0.1 0 0) (moogbp (add (saw (note n)) (saw (* 0.333333 (note n)))) (adsr 0 0.1 0 0) 0.3))) (lambda (n) (mul (adsr 0 0.1 0 0) (mooglp (squ (* 0.25 (note n))) (adsr 0.1 0 0 0) 0.4)))) (list (lambda (n) (mul (adsr 0 0.1 0.1 1) (crush (sine (add (mul 100 (sine 0.3)) (note n))) 5 0.6))) (lambda (n) (mul (adsr 0 0.1 0 0) (moogbp (add (saw (note n)) (saw (* 0.333333 (note n)))) (* 0.1 (random 10)) 0.48)))) (list (lambda (n) (mul (adsr 0 0.1 0.05 1) (sine (add (mul 1000 (sine (* 0.3333 (note n)))) (note n))))) (lambda (n) (mul (adsr 0 0.1 0.05 1) (sine (add (mul 100 (sine (* 0.3333 (note n)))) (note n)))))) (list (lambda (n) (mul (adsr 0 0.1 0.05 1) (mul (sine (* 0.3333 (note n))) (sine (note n))))) (lambda (n) (mul (adsr 0 0.1 0 1) (mul (sine (* 1.3333 (note n))) (sine (note n)))))) (list (lambda (n) (mul (adsr 0 0.1 0.05 1) (mul (saw (* 0.3333 (note n))) (saw (note n))))) (lambda (n) (mul (adsr 0 0.1 0 1) (mul (saw (* 1.3333 (note n))) (saw (note n)))))) (list (lambda (n) (mul (adsr 0 0.1 0.05 1) (mul (squ (* 0.3333 (note n))) (sine (note n))))) (lambda (n) (mul (adsr 0 0.1 0 1) (mul (squ (* 1.3333 (note n))) (sine (note n)))))) ) ) ( define z ( build - nz ( vector 9 5 ' ( ( 4 2 ) ( 4 1 ) ( 6 0 ) ( 3 2 ) ( 4 1 ) ( 6 0 ) ) 8 3 ( list->vector ( string->list " BaaadBdcd -- C+++ --Aba+dd " ) ) ) ss 0.2 ) ) (define z (build-nz l ss 0.2)) (define minor '(2 1 2 2 1 2 2)) (define major '(2 2 1 2 2 2 1)) (define (update a b c d e) (lz-set-pat! l (list (map (lambda (i) (if (eqv? i 0) #\. #\b)) a) (map (lambda (i) (if (eqv? i 0) #\. #\a)) b) (map (lambda (i) (if (eqv? i 0) #\. #\b)) c) (map (lambda (i) (if (eqv? i 0) #\. #\a)) d))) (if (eqv? (list-ref e 0) 0) (set-scale minor) (set-scale major)) (set! note-dec (list-ref e 1)) (if (eqv? (list-ref e 2) 0) (set! random-drop-off #f) (set! random-drop-off #t)) (if (eqv? (list-ref e 3) 0) (set! humanize #f) (set! humanize #t)) (msg (list-ref e 4)) (set-nz-vx! z (modulo (list-ref e 4) (length ss))) ) ;; (set-nz-vx! z (modulo (- (nz-vx z) 1) 8)) (every-frame (nz-tick z)) (update (list 1 0 0 0 1) (list 0 1 1 1 0) (list 1 0 1 0 0) (list 0 1 0 1 0) (list 3 4 5 6 7))
null
https://raw.githubusercontent.com/nebogeo/weavingcodes/e305a28a38ef745ca31de3074c8aec3953a72aa2/pattern-matrix/sound/seq.scm
scheme
lz/nz . . . . . . . . . . . . . . . . . . . nz --
(synth-init 50 22050) (define (lz pat) (vector pat 0)) (define (lz-pat l) (vector-ref l 0)) (define (lz-pos l) (vector-ref l 1)) (define (lz-inc-pos! l) (vector-set! l 1 (+ (lz-pos l) 1))) (define (lz-set-pat! l v) (vector-set! l 0 v)) (define (safe-ref l i) (cond ((< i 0) #\.) ((>= i (length l)) #\.) (else (list-ref l i)))) (define (lz-tick l) (let ((a (safe-ref (list-ref (lz-pat l) 0) (modulo (lz-pos l) 8))) (b (safe-ref (list-ref (lz-pat l) 1) (modulo (- (lz-pos l) 2) 8))) (c (safe-ref (list-ref (lz-pat l) 2) (modulo (- (lz-pos l) 4) 8))) (d (safe-ref (list-ref (lz-pat l) 3) (modulo (- (lz-pos l) 6) 8)))) (lz-inc-pos! l) (list a b c d))) (define max-vals 16) (define (make-nz lz vals vx sz cur-t tk off) (vector lz vals vx sz cur-t tk off)) (define (nz-lz n) (vector-ref n 0)) (define (nz-vals n) (vector-ref n 1)) (define (nz-vx n) (vector-ref n 2)) (define (nz-sz n) (vector-ref n 3)) (define (nz-cur-t n) (vector-ref n 4)) (define (nz-tk n) (vector-ref n 5)) (define (nz-off n) (vector-ref n 6)) (define (set-nz-vals! n v) (vector-set! n 1 v)) (define (set-nz-vx! n v) (vector-set! n 2 v)) (define (set-nz-cur-t! n v) (vector-set! n 4 v)) (define (t) (ntp-time)) (define (build-nz lz sz tk) (make-nz lz '(40) 0 sz (ntp-time-add (t) 5) tk 1.0)) (define (nz-pop! nz) (let ((tmp (car (nz-vals nz)))) (when (not (eqv? (length (nz-vals nz)) 1)) (set-nz-vals! nz (cdr (nz-vals nz)))) tmp)) (define (nz-push! nz item) (when (< (length (nz-vals nz)) max-vals) (set-nz-vals! nz (cons item (nz-vals nz))))) (define (nz-dup! nz) (nz-push! nz (car (nz-vals nz)))) (define (ntp>? a b) (or (> (car a) (car b)) (and (eqv? (car a) (car b)) (> (cadr a) (cadr b))))) (define note-dec 1) (define random-drop-off #t) (define humanize #t) (define (nz-tick nz) (when (ntp>? (ntp-time-add (t) (nz-off nz)) (nz-cur-t nz)) (let ((t (lz-tick (nz-lz nz))) (v (car (nz-vals nz)))) (set-nz-cur-t! nz (ntp-time-add (nz-cur-t nz) (nz-tk nz))) (let ((ht (nz-cur-t nz))) (for-each (lambda (t) (when (or random-drop-off (< (random 10) 8)) (define hht ht) (when humanize (set! hht (ntp-time-add ht (* (rndf) 0.03)))) (cond ((char=? t #\+) (set-nz-vals! nz (cons (+ (car (nz-vals nz)) 1) (cdr (nz-vals nz))))) ((char=? t #\-) (set-nz-vals! nz (cons (- (car (nz-vals nz)) 1) (cdr (nz-vals nz))))) ((char=? t #\<) (set-nz-vx! nz (modulo (- (nz-vx nz) 1) (length (nz-sz nz))))) ((char=? t #\>) (set-nz-vx! nz (modulo (+ (nz-vx nz) 1) (length (nz-sz nz))))) ((char=? t #\a) (play hht ((list-ref (list-ref (nz-sz nz) (nz-vx nz)) 0) v) 0)) ((char=? t #\b) (play hht ((list-ref (list-ref (nz-sz nz) (nz-vx nz)) 1) v) 0)) ((char=? t #\c) (play hht ((list-ref (list-ref (nz-sz nz) (nz-vx nz)) 2) v) 0)) ((char=? t #\d) (play hht ((list-ref (list-ref (nz-sz nz) (nz-vx nz)) 3) v) 0)) ((char=? t #\[) (nz-dup! nz)) ((char=? t #\]) (nz-pop! nz)))) (set! v (- v note-dec)) ) t))))) (define l (lz (list (string->list ".b..b") (string->list ".aa..") (string->list "...b.") (string->list "aaa.a")))) (define ss (list (list (lambda (v) (mul (adsr 0 0.01 0.1 1) (sine (add (mul 20 (sine 4)) (note v))))) (lambda (v) (mul (adsr 0 0.1 0 0) (mul 0.2 (add (saw (* 1.5 (note v))) (saw (note v))))))) (list (lambda (v) (mul (adsr 0 0.03 0.1 1) (mooghp (saw (* (note v) 0.5)) (mul 0.2 (adsr 0.5 0 0 0)) 0.45))) (lambda (v) (mul (adsr 0 0.1 0.1 1) (mooglp (add (saw (* 1.5 (note v))) (saw (note v))) (* v 0.12) 0.4)))) (list (lambda (n) (mul (adsr 0 0.1 0 0) (moogbp (add (saw (note n)) (saw (* 0.333333 (note n)))) (adsr 0 0.1 0 0) 0.3))) (lambda (n) (mul (adsr 0 0.1 0 0) (mooglp (squ (* 0.25 (note n))) (adsr 0.1 0 0 0) 0.4)))) (list (lambda (n) (mul (adsr 0 0.1 0.1 1) (crush (sine (add (mul 100 (sine 0.3)) (note n))) 5 0.6))) (lambda (n) (mul (adsr 0 0.1 0 0) (moogbp (add (saw (note n)) (saw (* 0.333333 (note n)))) (* 0.1 (random 10)) 0.48)))) (list (lambda (n) (mul (adsr 0 0.1 0.05 1) (sine (add (mul 1000 (sine (* 0.3333 (note n)))) (note n))))) (lambda (n) (mul (adsr 0 0.1 0.05 1) (sine (add (mul 100 (sine (* 0.3333 (note n)))) (note n)))))) (list (lambda (n) (mul (adsr 0 0.1 0.05 1) (mul (sine (* 0.3333 (note n))) (sine (note n))))) (lambda (n) (mul (adsr 0 0.1 0 1) (mul (sine (* 1.3333 (note n))) (sine (note n)))))) (list (lambda (n) (mul (adsr 0 0.1 0.05 1) (mul (saw (* 0.3333 (note n))) (saw (note n))))) (lambda (n) (mul (adsr 0 0.1 0 1) (mul (saw (* 1.3333 (note n))) (saw (note n)))))) (list (lambda (n) (mul (adsr 0 0.1 0.05 1) (mul (squ (* 0.3333 (note n))) (sine (note n))))) (lambda (n) (mul (adsr 0 0.1 0 1) (mul (squ (* 1.3333 (note n))) (sine (note n)))))) ) ) ( define z ( build - nz ( vector 9 5 ' ( ( 4 2 ) ( 4 1 ) ( 6 0 ) ( 3 2 ) ( 4 1 ) ( 6 0 ) ) 8 3 ( list->vector ( string->list " BaaadBdcd -- C+++ --Aba+dd " ) ) ) ss 0.2 ) ) (define z (build-nz l ss 0.2)) (define minor '(2 1 2 2 1 2 2)) (define major '(2 2 1 2 2 2 1)) (define (update a b c d e) (lz-set-pat! l (list (map (lambda (i) (if (eqv? i 0) #\. #\b)) a) (map (lambda (i) (if (eqv? i 0) #\. #\a)) b) (map (lambda (i) (if (eqv? i 0) #\. #\b)) c) (map (lambda (i) (if (eqv? i 0) #\. #\a)) d))) (if (eqv? (list-ref e 0) 0) (set-scale minor) (set-scale major)) (set! note-dec (list-ref e 1)) (if (eqv? (list-ref e 2) 0) (set! random-drop-off #f) (set! random-drop-off #t)) (if (eqv? (list-ref e 3) 0) (set! humanize #f) (set! humanize #t)) (msg (list-ref e 4)) (set-nz-vx! z (modulo (list-ref e 4) (length ss))) ) (set-nz-vx! z (modulo (- (nz-vx z) 1) 8)) (every-frame (nz-tick z)) (update (list 1 0 0 0 1) (list 0 1 1 1 0) (list 1 0 1 0 0) (list 0 1 0 1 0) (list 3 4 5 6 7))
54587388a78da7b998923da25ada667c7f8ac6caa43b040d505c0f6b8266a838
zcaudate-me/lein-repack
common_test.clj
(ns leiningen.repack.manifest.common-test (:use midje.sweet) (:require [leiningen.repack.manifest.common :refer :all] [leiningen.repack.analyser [java]])) ^{:refer leiningen.repack.manifest.common/build-filemap :added "0.1.5"} (fact "builds manifest for resources and java folder" (build-filemap "example/repack.advance" {:subpackage "resources" :path "resources" :distribute {"common" #{"common"} "web" #{"web"}} :dependents #{"core"}}) { resources / common / b.txt resources / common / a.txt } , "resources" anything ;; {resources/stuff/y.edn resources/stuff/x.edn}, "web" anything ;; {resources/web/a.html resources/web/b.html} }) (build-filemap "example/repack.advance" {:subpackage "jvm" :path "java/im/chit/repack" :distribute {"common" #{"common"} "web" #{"web"}} :dependents #{"core"}}) => (contains {"common" anything ;; {java/im/chit/repack/common/Hello.java}, "jvm" anything ;; {java/im/chit/repack/native/Utils.java}, "web" anything ;; {java/im/chit/repack/web/Client.java} })) (-> (build-filemap "example/repack.advance" {:subpackage "jvm" :path "java/im/chit/repack" :distribute {"common" #{"common"} "web" #{"web"}} :dependents #{"core"}}) (get "web") first (#(into {} %)))
null
https://raw.githubusercontent.com/zcaudate-me/lein-repack/1eb542d66a77f55c4b5625783027c31fd2dddfe5/test/leiningen/repack/manifest/common_test.clj
clojure
{resources/stuff/y.edn resources/stuff/x.edn}, {resources/web/a.html resources/web/b.html} {java/im/chit/repack/common/Hello.java}, {java/im/chit/repack/native/Utils.java}, {java/im/chit/repack/web/Client.java}
(ns leiningen.repack.manifest.common-test (:use midje.sweet) (:require [leiningen.repack.manifest.common :refer :all] [leiningen.repack.analyser [java]])) ^{:refer leiningen.repack.manifest.common/build-filemap :added "0.1.5"} (fact "builds manifest for resources and java folder" (build-filemap "example/repack.advance" {:subpackage "resources" :path "resources" :distribute {"common" #{"common"} "web" #{"web"}} :dependents #{"core"}}) { resources / common / b.txt resources / common / a.txt } , }) (build-filemap "example/repack.advance" {:subpackage "jvm" :path "java/im/chit/repack" :distribute {"common" #{"common"} "web" #{"web"}} :dependents #{"core"}}) })) (-> (build-filemap "example/repack.advance" {:subpackage "jvm" :path "java/im/chit/repack" :distribute {"common" #{"common"} "web" #{"web"}} :dependents #{"core"}}) (get "web") first (#(into {} %)))
72019c13a0b0ab148817de1033ac8abffc7d4518975032e4ffb07f608ada99bd
silkapp/rest
Main.hs
{-# LANGUAGE OverloadedStrings #-} module Main (main) where import Control.Concurrent (forkIO, killThread) import Control.Monad.Trans (liftIO) import Happstack.Server.SimpleHTTP import Rest.Driver.Happstack (apiToHandler') import Api (api) import ApiTypes (ServerData (..), runBlogApi) import Example (exampleBlog) -- | Run the server main :: IO () main = do -- Set up the server state serverData <- exampleBlog -- Start happstack putStrLn "Starting happstack server on :3000" tid <- forkIO $ simpleHTTP (Conf 3000 Nothing Nothing 60 Nothing) (handle serverData) -- Exit gracefully waitForTermination killThread tid -- | Request handler handle :: ServerData -> ServerPartT IO Response handle serverData = apiToHandler' (liftIO . runBlogApi serverData) api
null
https://raw.githubusercontent.com/silkapp/rest/f0462fc36709407f236f57064d8e37c77bdf8a79/rest-example/happstack/Main.hs
haskell
# LANGUAGE OverloadedStrings # | Run the server Set up the server state Start happstack Exit gracefully | Request handler
module Main (main) where import Control.Concurrent (forkIO, killThread) import Control.Monad.Trans (liftIO) import Happstack.Server.SimpleHTTP import Rest.Driver.Happstack (apiToHandler') import Api (api) import ApiTypes (ServerData (..), runBlogApi) import Example (exampleBlog) main :: IO () main = do serverData <- exampleBlog putStrLn "Starting happstack server on :3000" tid <- forkIO $ simpleHTTP (Conf 3000 Nothing Nothing 60 Nothing) (handle serverData) waitForTermination killThread tid handle :: ServerData -> ServerPartT IO Response handle serverData = apiToHandler' (liftIO . runBlogApi serverData) api
55bfcb1fee9c66b3025705ba6ecdbc71c794861f8e32b912348f61082a86b572
ianmbloom/gudni
DeviceQuery.hs
{-# LANGUAGE TypeOperators #-} # LANGUAGE GADTs # # LANGUAGE ScopedTypeVariables # {-# LANGUAGE FlexibleContexts #-} # LANGUAGE LambdaCase # # LANGUAGE TemplateHaskell # ----------------------------------------------------------------------------- -- | Module : Graphics . Gudni . OpenCL.CallKernel Copyright : ( c ) 2019 -- License : BSD-style (see the file libraries/base/LICENSE) -- Maintainer : -- Stability : experimental -- Portability : portable -- Boilerplate galore for querying OpenCL device specifications . module Graphics.Gudni.OpenCL.DeviceQuery ( CLDeviceExtension(..) , CLDeviceProfile(..) , CLDeviceDetail(..) , clDeviceName , clDeviceDeviceId , clDevicePlatformDetail , clDeviceExecutionCapabilities , clDeviceAddressBits , clDeviceAvailable , clDeviceCompilerAvailable , clDeviceEndianLittle , clDeviceErrorCorrectionSupport , clDeviceExtensions , clDeviceGlobalMemCacheSize , clDeviceGlobalMemCachelineSize , clDeviceGlobalMemSize , clDeviceImageSupport , clDeviceImage2DMaxHeight , clDeviceImage2DMaxWidth , clDeviceImage3DMaxDepth , clDeviceImage3DMaxHeight , clDeviceImage3DMaxWidth , clDeviceLocalMemSize , clDeviceMaxClockFrequency , clDeviceMaxComputeUnits , clDeviceMaxConstantArgs , clDeviceMaxConstantBufferSize , clDeviceMaxMemAllocSize , clDeviceMaxParameterSize , clDeviceMaxReadImageArgs , clDeviceMaxSamplers , clDeviceMaxWorkGroupSize , clDeviceMaxWorkItemDimensions , clDeviceMaxWorkItemSizes , clDeviceMaxWriteImageArgs , clDeviceMemBaseAddrAlign , clDeviceMinDataTypeAlignSize , clDevicePreferredVectorWidthChar , clDevicePreferredVectorWidthShort , clDevicePreferredVectorWidthInt , clDevicePreferredVectorWidthLong , clDevicePreferredVectorWidthFloat , clDevicePreferredVectorWidthDouble , clDeviceProfile , clDeviceProfilingTimerResolution , clDeviceVendor , clDeviceVendorID , clDeviceVersion , clDeviceDriverVersion , clDeviceSingleFPConfig , clDeviceDoubleFPConfig --, clDeviceHalfFPConfig , clDeviceLocalMemType , clDeviceGlobalMemCacheType , clDeviceQueueProperties , clDeviceType , CLPlatformDetail(..) , clPlatformName , clPlatformProfile , clPlatformVersion , clPlatformVendor , clPlatformExtensions , queryOpenCL , dumpDeviceDetail ) where import CLUtil.CL import Control.Exception (handle, throw) import Control.Monad import Control.Parallel.OpenCL import Foreign.C.Types (CSize) import Graphics.Gudni.Util.Util import Data.List import Data.Maybe (catMaybes) import Control.Lens -- | Show a title line titleLine :: String -> String titleLine title = "======================== " ++ title ++ " ========================\n" -- | Pad a line of info for aligned display. infoLine :: (String, String) -> String infoLine (title, info) = (lpad 40 title) ++ ": " ++ info ++ "\n" data CLDeviceExtension = CL_KHR_FP64 | CL_KHR_SELECT_FPROUNDING_MODE | CL_KHR_GLOBAL_INT32_BASE_ATOMICS | CL_KHR_GLOBAL_INT32_EXTENDED_ATOMICS | CL_KHR_LOCAL_INT32_BASE_ATOMICS | CL_KHR_LOCAL_INT32_EXTENDED_ATOMICS | CL_KHR_INT64_BASE_ATOMICS | CL_KHR_INT64_EXTENDED_ATOMICS | CL_KHR_3D_IMAGE_WRITES | CL_KHR_BYTE_ADDRESSABLE_STORE | CL_KHR_FP16 deriving (Show, Eq) clExtensionMapping :: [(String, CLDeviceExtension)] clExtensionMapping = [ ("cl_khr_fp64" , CL_KHR_FP64 ) , ("cl_khr_select_fprounding_mode" , CL_KHR_SELECT_FPROUNDING_MODE ) , ("cl_khr_global_int32_base_atomics" , CL_KHR_GLOBAL_INT32_BASE_ATOMICS ) , ("cl_khr_global_int32_extended_atomics", CL_KHR_GLOBAL_INT32_EXTENDED_ATOMICS) , ("cl_khr_local_int32_base_atomics" , CL_KHR_LOCAL_INT32_BASE_ATOMICS ) , ("cl_khr_local_int32_extended_atomics" , CL_KHR_LOCAL_INT32_EXTENDED_ATOMICS ) , ("cl_khr_int64_base_atomics" , CL_KHR_INT64_BASE_ATOMICS ) , ("cl_khr_int64_extended_atomics" , CL_KHR_INT64_EXTENDED_ATOMICS ) , ("cl_khr_3d_image_writes" , CL_KHR_3D_IMAGE_WRITES ) , ("cl_khr_byte_addressable_store" , CL_KHR_BYTE_ADDRESSABLE_STORE ) , ("cl_khr_fp16" , CL_KHR_FP16 ) ] search :: Eq a => [(a,b)] -> a -> Maybe b search list a = fmap snd . find ((== a) . fst) $ list getExtensionList :: String -> [CLDeviceExtension] getExtensionList = catMaybes . map (search clExtensionMapping) . words data CLDeviceProfile = CL_FULL_PROFILE | CL_EMBEDDED_PROFILE deriving (Show, Eq) determineClDeviceProfile :: String -> CLDeviceProfile determineClDeviceProfile rawString = if rawString == "FULL_PROFILE" then CL_FULL_PROFILE else CL_EMBEDDED_PROFILE data CLPlatformDetail = CLPlatformDetail { _clPlatformName :: String , _clPlatformProfile :: String , _clPlatformVersion :: String , _clPlatformVendor :: String , _clPlatformExtensions :: String } deriving (Show) makeLenses ''CLPlatformDetail | Create a CLPlatformInfo record by querying openCL initCLPlatformInfo :: CLPlatformID -> IO CLPlatformDetail initCLPlatformInfo platformID = do name <- clGetPlatformInfo platformID CL_PLATFORM_NAME profile <- clGetPlatformInfo platformID CL_PLATFORM_PROFILE version <- clGetPlatformInfo platformID CL_PLATFORM_VERSION vendor <- clGetPlatformInfo platformID CL_PLATFORM_VENDOR extensions <- clGetPlatformInfo platformID CL_PLATFORM_EXTENSIONS return CLPlatformDetail { _clPlatformName = name , _clPlatformProfile = profile , _clPlatformVersion = version , _clPlatformVendor = vendor , _clPlatformExtensions = extensions } data CLDeviceDetail = CLDeviceDetail { _clDeviceName :: String , _clDeviceDeviceId :: CLDeviceID , _clDevicePlatformDetail :: CLPlatformDetail , _clDeviceExecutionCapabilities :: [CLDeviceExecCapability] , _clDeviceAddressBits :: CLuint , _clDeviceAvailable :: Bool , _clDeviceCompilerAvailable :: Bool , _clDeviceEndianLittle :: Bool , _clDeviceErrorCorrectionSupport :: Bool , _clDeviceExtensions :: [CLDeviceExtension] , _clDeviceGlobalMemCacheSize :: CLulong , _clDeviceGlobalMemCachelineSize :: CLuint , _clDeviceGlobalMemSize :: CLulong , _clDeviceImageSupport :: Bool , _clDeviceImage2DMaxHeight :: CSize , _clDeviceImage2DMaxWidth :: CSize , _clDeviceImage3DMaxDepth :: CSize , _clDeviceImage3DMaxHeight :: CSize , _clDeviceImage3DMaxWidth :: CSize , _clDeviceLocalMemSize :: CLulong , _clDeviceMaxClockFrequency :: CLuint , _clDeviceMaxComputeUnits :: CLuint , _clDeviceMaxConstantArgs :: CLuint , _clDeviceMaxConstantBufferSize :: CLulong , _clDeviceMaxMemAllocSize :: CLulong , _clDeviceMaxParameterSize :: CSize , _clDeviceMaxReadImageArgs :: CLuint , _clDeviceMaxSamplers :: CLuint , _clDeviceMaxWorkGroupSize :: CSize , _clDeviceMaxWorkItemDimensions :: CLuint , _clDeviceMaxWorkItemSizes :: [CSize] , _clDeviceMaxWriteImageArgs :: CLuint , _clDeviceMemBaseAddrAlign :: CLuint , _clDeviceMinDataTypeAlignSize :: CLuint , _clDevicePreferredVectorWidthChar :: CLuint , _clDevicePreferredVectorWidthShort :: CLuint , _clDevicePreferredVectorWidthInt :: CLuint , _clDevicePreferredVectorWidthLong :: CLuint , _clDevicePreferredVectorWidthFloat :: CLuint , _clDevicePreferredVectorWidthDouble :: CLuint , _clDeviceProfile :: CLDeviceProfile , _clDeviceProfilingTimerResolution :: CSize , _clDeviceVendor :: String , _clDeviceVendorID :: CLuint , _clDeviceVersion :: String , _clDeviceDriverVersion :: String , _clDeviceSingleFPConfig :: [CLDeviceFPConfig] , _clDeviceDoubleFPConfig :: [CLDeviceFPConfig] --, _clDeviceHalfFPConfig :: [CLDeviceFPConfig] , _clDeviceLocalMemType :: CLDeviceLocalMemType , _clDeviceGlobalMemCacheType :: CLDeviceMemCacheType , _clDeviceQueueProperties :: [CLCommandQueueProperty] , _clDeviceType :: [CLDeviceType] } deriving (Show) makeLenses ''CLDeviceDetail -- | Create a CLDeviceDetail record by querying an openCL device. initCLDeviceDetail :: CLPlatformID -> CLDeviceID -> IO CLDeviceDetail initCLDeviceDetail platformId deviceId = do deviceName <- clGetDeviceName deviceId platformInfo <- initCLPlatformInfo platformId deviceExecutionCapabilities <- clGetDeviceExecutionCapabilities deviceId deviceAddressBits <- clGetDeviceAddressBits deviceId deviceAvailable <- clGetDeviceAvailable deviceId deviceCompilerAvailable <- clGetDeviceCompilerAvailable deviceId deviceEndianLittle <- clGetDeviceEndianLittle deviceId deviceErrorCorrectionSupport <- clGetDeviceErrorCorrectionSupport deviceId deviceExtensions <- clGetDeviceExtensions deviceId deviceGlobalMemCacheSize <- clGetDeviceGlobalMemCacheSize deviceId deviceGlobalMemCachelineSize <- clGetDeviceGlobalMemCachelineSize deviceId deviceGlobalMemSize <- clGetDeviceGlobalMemSize deviceId deviceImageSupport <- clGetDeviceImageSupport deviceId deviceImage2DMaxHeight <- clGetDeviceImage2DMaxHeight deviceId deviceImage2DMaxWidth <- clGetDeviceImage2DMaxWidth deviceId deviceImage3DMaxDepth <- clGetDeviceImage3DMaxDepth deviceId deviceImage3DMaxHeight <- clGetDeviceImage3DMaxHeight deviceId deviceImage3DMaxWidth <- clGetDeviceImage3DMaxWidth deviceId deviceLocalMemSize <- clGetDeviceLocalMemSize deviceId deviceMaxClockFrequency <- clGetDeviceMaxClockFrequency deviceId deviceMaxComputeUnits <- clGetDeviceMaxComputeUnits deviceId deviceMaxConstantArgs <- clGetDeviceMaxConstantArgs deviceId deviceMaxConstantBufferSize <- clGetDeviceMaxConstantBufferSize deviceId deviceMaxMemAllocSize <- clGetDeviceMaxMemAllocSize deviceId deviceMaxParameterSize <- clGetDeviceMaxParameterSize deviceId deviceMaxReadImageArgs <- clGetDeviceMaxReadImageArgs deviceId deviceMaxSamplers <- clGetDeviceMaxSamplers deviceId deviceMaxWorkGroupSize <- clGetDeviceMaxWorkGroupSize deviceId deviceMaxWorkItemDimensions <- clGetDeviceMaxWorkItemDimensions deviceId deviceMaxWorkItemSizes <- clGetDeviceMaxWorkItemSizes deviceId deviceMaxWriteImageArgs <- clGetDeviceMaxWriteImageArgs deviceId deviceMemBaseAddrAlign <- clGetDeviceMemBaseAddrAlign deviceId deviceMinDataTypeAlignSize <- clGetDeviceMinDataTypeAlignSize deviceId devicePreferredVectorWidthChar <- clGetDevicePreferredVectorWidthChar deviceId devicePreferredVectorWidthShort <- clGetDevicePreferredVectorWidthShort deviceId devicePreferredVectorWidthInt <- clGetDevicePreferredVectorWidthInt deviceId devicePreferredVectorWidthLong <- clGetDevicePreferredVectorWidthLong deviceId devicePreferredVectorWidthFloat <- clGetDevicePreferredVectorWidthFloat deviceId devicePreferredVectorWidthDouble <- clGetDevicePreferredVectorWidthDouble deviceId deviceProfile <- clGetDeviceProfile deviceId deviceProfilingTimerResolution <- clGetDeviceProfilingTimerResolution deviceId deviceVendor <- clGetDeviceVendor deviceId deviceVendorID <- clGetDeviceVendorID deviceId deviceVersion <- clGetDeviceVersion deviceId deviceDriverVersion <- clGetDeviceDriverVersion deviceId deviceSingleFPConfig <- clGetDeviceSingleFPConfig deviceId deviceDoubleFPConfig <- clGetDeviceDoubleFPConfig deviceId < - clGetDeviceHalfFPConfig deviceId deviceLocalMemType <- clGetDeviceLocalMemType deviceId deviceGlobalMemCacheType <- clGetDeviceGlobalMemCacheType deviceId deviceQueueProperties <- clGetDeviceQueueProperties deviceId deviceType <- clGetDeviceType deviceId return CLDeviceDetail { _clDeviceName = deviceName , _clDeviceDeviceId = deviceId , _clDevicePlatformDetail = platformInfo , _clDeviceExecutionCapabilities = deviceExecutionCapabilities , _clDeviceAddressBits = deviceAddressBits , _clDeviceAvailable = deviceAvailable , _clDeviceCompilerAvailable = deviceCompilerAvailable , _clDeviceEndianLittle = deviceEndianLittle , _clDeviceErrorCorrectionSupport = deviceErrorCorrectionSupport , _clDeviceExtensions = getExtensionList $ deviceExtensions , _clDeviceGlobalMemCacheSize = deviceGlobalMemCacheSize , _clDeviceGlobalMemCachelineSize = deviceGlobalMemCachelineSize , _clDeviceGlobalMemSize = deviceGlobalMemSize , _clDeviceImageSupport = deviceImageSupport , _clDeviceImage2DMaxHeight = deviceImage2DMaxHeight , _clDeviceImage2DMaxWidth = deviceImage2DMaxWidth , _clDeviceImage3DMaxDepth = deviceImage3DMaxDepth , _clDeviceImage3DMaxHeight = deviceImage3DMaxHeight , _clDeviceImage3DMaxWidth = deviceImage3DMaxWidth , _clDeviceLocalMemSize = deviceLocalMemSize , _clDeviceMaxClockFrequency = deviceMaxClockFrequency , _clDeviceMaxComputeUnits = deviceMaxComputeUnits , _clDeviceMaxConstantArgs = deviceMaxConstantArgs , _clDeviceMaxConstantBufferSize = deviceMaxConstantBufferSize , _clDeviceMaxMemAllocSize = deviceMaxMemAllocSize , _clDeviceMaxParameterSize = deviceMaxParameterSize , _clDeviceMaxReadImageArgs = deviceMaxReadImageArgs , _clDeviceMaxSamplers = deviceMaxSamplers , _clDeviceMaxWorkGroupSize = deviceMaxWorkGroupSize , _clDeviceMaxWorkItemDimensions = deviceMaxWorkItemDimensions , _clDeviceMaxWorkItemSizes = deviceMaxWorkItemSizes , _clDeviceMaxWriteImageArgs = deviceMaxWriteImageArgs , _clDeviceMemBaseAddrAlign = deviceMemBaseAddrAlign , _clDeviceMinDataTypeAlignSize = deviceMinDataTypeAlignSize , _clDevicePreferredVectorWidthChar = devicePreferredVectorWidthChar , _clDevicePreferredVectorWidthShort = devicePreferredVectorWidthShort , _clDevicePreferredVectorWidthInt = devicePreferredVectorWidthInt , _clDevicePreferredVectorWidthLong = devicePreferredVectorWidthLong , _clDevicePreferredVectorWidthFloat = devicePreferredVectorWidthFloat , _clDevicePreferredVectorWidthDouble = devicePreferredVectorWidthDouble , _clDeviceProfile = determineClDeviceProfile deviceProfile , _clDeviceProfilingTimerResolution = deviceProfilingTimerResolution , _clDeviceVendor = deviceVendor , _clDeviceVendorID = deviceVendorID , _clDeviceVersion = deviceVersion , _clDeviceDriverVersion = deviceDriverVersion , _clDeviceSingleFPConfig = deviceSingleFPConfig , _clDeviceDoubleFPConfig = deviceDoubleFPConfig --, _clDeviceHalfFPConfig = deviceHalfFPConfig , _clDeviceLocalMemType = deviceLocalMemType , _clDeviceGlobalMemCacheType = deviceGlobalMemCacheType , _clDeviceQueueProperties = deviceQueueProperties , _clDeviceType = deviceType } dumpPlatformDetauk :: CLPlatformDetail -> String dumpPlatformDetauk platformInfo = (titleLine ("Platform " ++ show (platformInfo ^. clPlatformName)) ++) $ foldl1 (++) $ map infoLine $ [ ( "Profile", show $ platformInfo ^. clPlatformProfile ) , ( "Version", show $ platformInfo ^. clPlatformVersion ) , ( "Vendor", show $ platformInfo ^. clPlatformVendor ) , ( "Extensions", show $ platformInfo ^. clPlatformExtensions ) ] dumpDeviceDetail :: CLDeviceDetail -> String dumpDeviceDetail deviceDetail = (titleLine (show (deviceDetail ^. clDeviceName)) ++) $ foldl1 (++) $ map infoLine $ [ ( "ExecutionCapabilities" , show $ deviceDetail ^. clDeviceExecutionCapabilities ) , ( "DeviceAddressBits", show $ deviceDetail ^. clDeviceAddressBits ) , ( "Available", show $ deviceDetail ^. clDeviceAvailable ) , ( "CompilerAvailable", show $ deviceDetail ^. clDeviceCompilerAvailable ) , ( "EndianLittle", show $ deviceDetail ^. clDeviceEndianLittle ) , ( "ErrorCorrectionSupport", show $ deviceDetail ^. clDeviceErrorCorrectionSupport ) , ( "Extensions", show $ deviceDetail ^. clDeviceExtensions ) , ( "GlobalMemCacheSize", show $ deviceDetail ^. clDeviceGlobalMemCacheSize ) , ( "GlobalMemCachelineSize", show $ deviceDetail ^. clDeviceGlobalMemCachelineSize ) , ( "GlobalMemSize", show $ deviceDetail ^. clDeviceGlobalMemSize ) , ( "ImageSupport", show $ deviceDetail ^. clDeviceImageSupport ) , ( "Image2DMaxHeight", show $ deviceDetail ^. clDeviceImage2DMaxHeight ) , ( "Image2DMaxWidth", show $ deviceDetail ^. clDeviceImage2DMaxWidth ) , ( "Image3DMaxDepth", show $ deviceDetail ^. clDeviceImage3DMaxDepth ) , ( "Image3DMaxHeight", show $ deviceDetail ^. clDeviceImage3DMaxHeight ) , ( "Image3DMaxWidth", show $ deviceDetail ^. clDeviceImage3DMaxWidth ) , ( "LocalMemSize", show $ deviceDetail ^. clDeviceLocalMemSize ) , ( "MaxClockFrequency", show $ deviceDetail ^. clDeviceMaxClockFrequency ) , ( "MaxComputeUnits", show $ deviceDetail ^. clDeviceMaxComputeUnits ) , ( "MaxConstantArgs", show $ deviceDetail ^. clDeviceMaxConstantArgs ) , ( "MaxConstantBufferSize", show $ deviceDetail ^. clDeviceMaxConstantBufferSize ) , ( "MaxMemAllocSize", show $ deviceDetail ^. clDeviceMaxMemAllocSize ) , ( "MaxParameterSize", show $ deviceDetail ^. clDeviceMaxParameterSize ) , ( "MaxReadImageArgs", show $ deviceDetail ^. clDeviceMaxReadImageArgs ) , ( "MaxSamplers", show $ deviceDetail ^. clDeviceMaxSamplers ) , ( "MaxWorkGroupSize", show $ deviceDetail ^. clDeviceMaxWorkGroupSize ) , ( "MaxWorkItemDimensions", show $ deviceDetail ^. clDeviceMaxWorkItemDimensions ) , ( "MaxWorkItemSizes", show $ deviceDetail ^. clDeviceMaxWorkItemSizes ) , ( "MaxWriteImageArgs", show $ deviceDetail ^. clDeviceMaxWriteImageArgs ) , ( "MemBaseAddrAlign", show $ deviceDetail ^. clDeviceMemBaseAddrAlign ) , ( "MinDataTypeAlignSize", show $ deviceDetail ^. clDeviceMinDataTypeAlignSize ) , ( "PreferredVectorWidthChar", show $ deviceDetail ^. clDevicePreferredVectorWidthChar ) , ( "PreferredVectorWidthShort", show $ deviceDetail ^. clDevicePreferredVectorWidthShort ) , ( "PreferredVectorWidthInt", show $ deviceDetail ^. clDevicePreferredVectorWidthInt ) , ( "PreferredVectorWidthLong", show $ deviceDetail ^. clDevicePreferredVectorWidthLong ) , ( "PreferredVectorWidthFloat", show $ deviceDetail ^. clDevicePreferredVectorWidthFloat ) , ("PreferredVectorWidthDouble", show $ deviceDetail ^. clDevicePreferredVectorWidthDouble) , ( "Profile", show $ deviceDetail ^. clDeviceProfile ) , ( "ProfilingTimerResolution", show $ deviceDetail ^. clDeviceProfilingTimerResolution ) , ( "Vendor", show $ deviceDetail ^. clDeviceVendor ) , ( "VendorID", show $ deviceDetail ^. clDeviceVendorID ) , ( "Version", show $ deviceDetail ^. clDeviceVersion ) , ( "DriverVersion", show $ deviceDetail ^. clDeviceDriverVersion ) , ( "SingleFPConfig", show $ deviceDetail ^. clDeviceSingleFPConfig ) , ( "DoubleFPConfig", show $ deviceDetail ^. clDeviceDoubleFPConfig ) -- , ( "HalfFPConfig", show $ deviceDetail ^. clDeviceHalfFPConfig ) , ( "LocalMemType", show $ deviceDetail ^. clDeviceLocalMemType ) , ( "GlobalMemCacheType", show $ deviceDetail ^. clDeviceGlobalMemCacheType ) , ( "QueueProperties", show $ deviceDetail ^. clDeviceQueueProperties ) , ( "Type", show $ deviceDetail ^. clDeviceType ) ] | Query of all information about a every available OpenCL platform and -- every device on that platform and return a CLDeviceDetail structure for each one. queryOpenCL :: CLDeviceType -> IO [CLDeviceDetail] queryOpenCL deviceType = do platformIDs <- clGetPlatformIDs concat <$> mapM (\platformID -> do platformName <- clGetPlatformInfo platformID CL_PLATFORM_NAME putStrLn ("Found platform: " ++ platformName) deviceIDs <- clGetDeviceIDs platformID deviceType & handle (\err -> if err == CL_DEVICE_NOT_FOUND then return [] else throw err) putStrLn ("Found " ++ show (length deviceIDs) ++ " devices") deviceInfos <- mapM (initCLDeviceDetail platformID) deviceIDs return deviceInfos) platformIDs
null
https://raw.githubusercontent.com/ianmbloom/gudni/fa69f1bf08c194effca05753afe5455ebae51234/src/Graphics/Gudni/OpenCL/DeviceQuery.hs
haskell
# LANGUAGE TypeOperators # # LANGUAGE FlexibleContexts # --------------------------------------------------------------------------- | License : BSD-style (see the file libraries/base/LICENSE) Stability : experimental Portability : portable , clDeviceHalfFPConfig | Show a title line | Pad a line of info for aligned display. , _clDeviceHalfFPConfig :: [CLDeviceFPConfig] | Create a CLDeviceDetail record by querying an openCL device. , _clDeviceHalfFPConfig = deviceHalfFPConfig , ( "HalfFPConfig", show $ deviceDetail ^. clDeviceHalfFPConfig ) every device on that platform and return a CLDeviceDetail structure for each one.
# LANGUAGE GADTs # # LANGUAGE ScopedTypeVariables # # LANGUAGE LambdaCase # # LANGUAGE TemplateHaskell # Module : Graphics . Gudni . OpenCL.CallKernel Copyright : ( c ) 2019 Maintainer : Boilerplate galore for querying OpenCL device specifications . module Graphics.Gudni.OpenCL.DeviceQuery ( CLDeviceExtension(..) , CLDeviceProfile(..) , CLDeviceDetail(..) , clDeviceName , clDeviceDeviceId , clDevicePlatformDetail , clDeviceExecutionCapabilities , clDeviceAddressBits , clDeviceAvailable , clDeviceCompilerAvailable , clDeviceEndianLittle , clDeviceErrorCorrectionSupport , clDeviceExtensions , clDeviceGlobalMemCacheSize , clDeviceGlobalMemCachelineSize , clDeviceGlobalMemSize , clDeviceImageSupport , clDeviceImage2DMaxHeight , clDeviceImage2DMaxWidth , clDeviceImage3DMaxDepth , clDeviceImage3DMaxHeight , clDeviceImage3DMaxWidth , clDeviceLocalMemSize , clDeviceMaxClockFrequency , clDeviceMaxComputeUnits , clDeviceMaxConstantArgs , clDeviceMaxConstantBufferSize , clDeviceMaxMemAllocSize , clDeviceMaxParameterSize , clDeviceMaxReadImageArgs , clDeviceMaxSamplers , clDeviceMaxWorkGroupSize , clDeviceMaxWorkItemDimensions , clDeviceMaxWorkItemSizes , clDeviceMaxWriteImageArgs , clDeviceMemBaseAddrAlign , clDeviceMinDataTypeAlignSize , clDevicePreferredVectorWidthChar , clDevicePreferredVectorWidthShort , clDevicePreferredVectorWidthInt , clDevicePreferredVectorWidthLong , clDevicePreferredVectorWidthFloat , clDevicePreferredVectorWidthDouble , clDeviceProfile , clDeviceProfilingTimerResolution , clDeviceVendor , clDeviceVendorID , clDeviceVersion , clDeviceDriverVersion , clDeviceSingleFPConfig , clDeviceDoubleFPConfig , clDeviceLocalMemType , clDeviceGlobalMemCacheType , clDeviceQueueProperties , clDeviceType , CLPlatformDetail(..) , clPlatformName , clPlatformProfile , clPlatformVersion , clPlatformVendor , clPlatformExtensions , queryOpenCL , dumpDeviceDetail ) where import CLUtil.CL import Control.Exception (handle, throw) import Control.Monad import Control.Parallel.OpenCL import Foreign.C.Types (CSize) import Graphics.Gudni.Util.Util import Data.List import Data.Maybe (catMaybes) import Control.Lens titleLine :: String -> String titleLine title = "======================== " ++ title ++ " ========================\n" infoLine :: (String, String) -> String infoLine (title, info) = (lpad 40 title) ++ ": " ++ info ++ "\n" data CLDeviceExtension = CL_KHR_FP64 | CL_KHR_SELECT_FPROUNDING_MODE | CL_KHR_GLOBAL_INT32_BASE_ATOMICS | CL_KHR_GLOBAL_INT32_EXTENDED_ATOMICS | CL_KHR_LOCAL_INT32_BASE_ATOMICS | CL_KHR_LOCAL_INT32_EXTENDED_ATOMICS | CL_KHR_INT64_BASE_ATOMICS | CL_KHR_INT64_EXTENDED_ATOMICS | CL_KHR_3D_IMAGE_WRITES | CL_KHR_BYTE_ADDRESSABLE_STORE | CL_KHR_FP16 deriving (Show, Eq) clExtensionMapping :: [(String, CLDeviceExtension)] clExtensionMapping = [ ("cl_khr_fp64" , CL_KHR_FP64 ) , ("cl_khr_select_fprounding_mode" , CL_KHR_SELECT_FPROUNDING_MODE ) , ("cl_khr_global_int32_base_atomics" , CL_KHR_GLOBAL_INT32_BASE_ATOMICS ) , ("cl_khr_global_int32_extended_atomics", CL_KHR_GLOBAL_INT32_EXTENDED_ATOMICS) , ("cl_khr_local_int32_base_atomics" , CL_KHR_LOCAL_INT32_BASE_ATOMICS ) , ("cl_khr_local_int32_extended_atomics" , CL_KHR_LOCAL_INT32_EXTENDED_ATOMICS ) , ("cl_khr_int64_base_atomics" , CL_KHR_INT64_BASE_ATOMICS ) , ("cl_khr_int64_extended_atomics" , CL_KHR_INT64_EXTENDED_ATOMICS ) , ("cl_khr_3d_image_writes" , CL_KHR_3D_IMAGE_WRITES ) , ("cl_khr_byte_addressable_store" , CL_KHR_BYTE_ADDRESSABLE_STORE ) , ("cl_khr_fp16" , CL_KHR_FP16 ) ] search :: Eq a => [(a,b)] -> a -> Maybe b search list a = fmap snd . find ((== a) . fst) $ list getExtensionList :: String -> [CLDeviceExtension] getExtensionList = catMaybes . map (search clExtensionMapping) . words data CLDeviceProfile = CL_FULL_PROFILE | CL_EMBEDDED_PROFILE deriving (Show, Eq) determineClDeviceProfile :: String -> CLDeviceProfile determineClDeviceProfile rawString = if rawString == "FULL_PROFILE" then CL_FULL_PROFILE else CL_EMBEDDED_PROFILE data CLPlatformDetail = CLPlatformDetail { _clPlatformName :: String , _clPlatformProfile :: String , _clPlatformVersion :: String , _clPlatformVendor :: String , _clPlatformExtensions :: String } deriving (Show) makeLenses ''CLPlatformDetail | Create a CLPlatformInfo record by querying openCL initCLPlatformInfo :: CLPlatformID -> IO CLPlatformDetail initCLPlatformInfo platformID = do name <- clGetPlatformInfo platformID CL_PLATFORM_NAME profile <- clGetPlatformInfo platformID CL_PLATFORM_PROFILE version <- clGetPlatformInfo platformID CL_PLATFORM_VERSION vendor <- clGetPlatformInfo platformID CL_PLATFORM_VENDOR extensions <- clGetPlatformInfo platformID CL_PLATFORM_EXTENSIONS return CLPlatformDetail { _clPlatformName = name , _clPlatformProfile = profile , _clPlatformVersion = version , _clPlatformVendor = vendor , _clPlatformExtensions = extensions } data CLDeviceDetail = CLDeviceDetail { _clDeviceName :: String , _clDeviceDeviceId :: CLDeviceID , _clDevicePlatformDetail :: CLPlatformDetail , _clDeviceExecutionCapabilities :: [CLDeviceExecCapability] , _clDeviceAddressBits :: CLuint , _clDeviceAvailable :: Bool , _clDeviceCompilerAvailable :: Bool , _clDeviceEndianLittle :: Bool , _clDeviceErrorCorrectionSupport :: Bool , _clDeviceExtensions :: [CLDeviceExtension] , _clDeviceGlobalMemCacheSize :: CLulong , _clDeviceGlobalMemCachelineSize :: CLuint , _clDeviceGlobalMemSize :: CLulong , _clDeviceImageSupport :: Bool , _clDeviceImage2DMaxHeight :: CSize , _clDeviceImage2DMaxWidth :: CSize , _clDeviceImage3DMaxDepth :: CSize , _clDeviceImage3DMaxHeight :: CSize , _clDeviceImage3DMaxWidth :: CSize , _clDeviceLocalMemSize :: CLulong , _clDeviceMaxClockFrequency :: CLuint , _clDeviceMaxComputeUnits :: CLuint , _clDeviceMaxConstantArgs :: CLuint , _clDeviceMaxConstantBufferSize :: CLulong , _clDeviceMaxMemAllocSize :: CLulong , _clDeviceMaxParameterSize :: CSize , _clDeviceMaxReadImageArgs :: CLuint , _clDeviceMaxSamplers :: CLuint , _clDeviceMaxWorkGroupSize :: CSize , _clDeviceMaxWorkItemDimensions :: CLuint , _clDeviceMaxWorkItemSizes :: [CSize] , _clDeviceMaxWriteImageArgs :: CLuint , _clDeviceMemBaseAddrAlign :: CLuint , _clDeviceMinDataTypeAlignSize :: CLuint , _clDevicePreferredVectorWidthChar :: CLuint , _clDevicePreferredVectorWidthShort :: CLuint , _clDevicePreferredVectorWidthInt :: CLuint , _clDevicePreferredVectorWidthLong :: CLuint , _clDevicePreferredVectorWidthFloat :: CLuint , _clDevicePreferredVectorWidthDouble :: CLuint , _clDeviceProfile :: CLDeviceProfile , _clDeviceProfilingTimerResolution :: CSize , _clDeviceVendor :: String , _clDeviceVendorID :: CLuint , _clDeviceVersion :: String , _clDeviceDriverVersion :: String , _clDeviceSingleFPConfig :: [CLDeviceFPConfig] , _clDeviceDoubleFPConfig :: [CLDeviceFPConfig] , _clDeviceLocalMemType :: CLDeviceLocalMemType , _clDeviceGlobalMemCacheType :: CLDeviceMemCacheType , _clDeviceQueueProperties :: [CLCommandQueueProperty] , _clDeviceType :: [CLDeviceType] } deriving (Show) makeLenses ''CLDeviceDetail initCLDeviceDetail :: CLPlatformID -> CLDeviceID -> IO CLDeviceDetail initCLDeviceDetail platformId deviceId = do deviceName <- clGetDeviceName deviceId platformInfo <- initCLPlatformInfo platformId deviceExecutionCapabilities <- clGetDeviceExecutionCapabilities deviceId deviceAddressBits <- clGetDeviceAddressBits deviceId deviceAvailable <- clGetDeviceAvailable deviceId deviceCompilerAvailable <- clGetDeviceCompilerAvailable deviceId deviceEndianLittle <- clGetDeviceEndianLittle deviceId deviceErrorCorrectionSupport <- clGetDeviceErrorCorrectionSupport deviceId deviceExtensions <- clGetDeviceExtensions deviceId deviceGlobalMemCacheSize <- clGetDeviceGlobalMemCacheSize deviceId deviceGlobalMemCachelineSize <- clGetDeviceGlobalMemCachelineSize deviceId deviceGlobalMemSize <- clGetDeviceGlobalMemSize deviceId deviceImageSupport <- clGetDeviceImageSupport deviceId deviceImage2DMaxHeight <- clGetDeviceImage2DMaxHeight deviceId deviceImage2DMaxWidth <- clGetDeviceImage2DMaxWidth deviceId deviceImage3DMaxDepth <- clGetDeviceImage3DMaxDepth deviceId deviceImage3DMaxHeight <- clGetDeviceImage3DMaxHeight deviceId deviceImage3DMaxWidth <- clGetDeviceImage3DMaxWidth deviceId deviceLocalMemSize <- clGetDeviceLocalMemSize deviceId deviceMaxClockFrequency <- clGetDeviceMaxClockFrequency deviceId deviceMaxComputeUnits <- clGetDeviceMaxComputeUnits deviceId deviceMaxConstantArgs <- clGetDeviceMaxConstantArgs deviceId deviceMaxConstantBufferSize <- clGetDeviceMaxConstantBufferSize deviceId deviceMaxMemAllocSize <- clGetDeviceMaxMemAllocSize deviceId deviceMaxParameterSize <- clGetDeviceMaxParameterSize deviceId deviceMaxReadImageArgs <- clGetDeviceMaxReadImageArgs deviceId deviceMaxSamplers <- clGetDeviceMaxSamplers deviceId deviceMaxWorkGroupSize <- clGetDeviceMaxWorkGroupSize deviceId deviceMaxWorkItemDimensions <- clGetDeviceMaxWorkItemDimensions deviceId deviceMaxWorkItemSizes <- clGetDeviceMaxWorkItemSizes deviceId deviceMaxWriteImageArgs <- clGetDeviceMaxWriteImageArgs deviceId deviceMemBaseAddrAlign <- clGetDeviceMemBaseAddrAlign deviceId deviceMinDataTypeAlignSize <- clGetDeviceMinDataTypeAlignSize deviceId devicePreferredVectorWidthChar <- clGetDevicePreferredVectorWidthChar deviceId devicePreferredVectorWidthShort <- clGetDevicePreferredVectorWidthShort deviceId devicePreferredVectorWidthInt <- clGetDevicePreferredVectorWidthInt deviceId devicePreferredVectorWidthLong <- clGetDevicePreferredVectorWidthLong deviceId devicePreferredVectorWidthFloat <- clGetDevicePreferredVectorWidthFloat deviceId devicePreferredVectorWidthDouble <- clGetDevicePreferredVectorWidthDouble deviceId deviceProfile <- clGetDeviceProfile deviceId deviceProfilingTimerResolution <- clGetDeviceProfilingTimerResolution deviceId deviceVendor <- clGetDeviceVendor deviceId deviceVendorID <- clGetDeviceVendorID deviceId deviceVersion <- clGetDeviceVersion deviceId deviceDriverVersion <- clGetDeviceDriverVersion deviceId deviceSingleFPConfig <- clGetDeviceSingleFPConfig deviceId deviceDoubleFPConfig <- clGetDeviceDoubleFPConfig deviceId < - clGetDeviceHalfFPConfig deviceId deviceLocalMemType <- clGetDeviceLocalMemType deviceId deviceGlobalMemCacheType <- clGetDeviceGlobalMemCacheType deviceId deviceQueueProperties <- clGetDeviceQueueProperties deviceId deviceType <- clGetDeviceType deviceId return CLDeviceDetail { _clDeviceName = deviceName , _clDeviceDeviceId = deviceId , _clDevicePlatformDetail = platformInfo , _clDeviceExecutionCapabilities = deviceExecutionCapabilities , _clDeviceAddressBits = deviceAddressBits , _clDeviceAvailable = deviceAvailable , _clDeviceCompilerAvailable = deviceCompilerAvailable , _clDeviceEndianLittle = deviceEndianLittle , _clDeviceErrorCorrectionSupport = deviceErrorCorrectionSupport , _clDeviceExtensions = getExtensionList $ deviceExtensions , _clDeviceGlobalMemCacheSize = deviceGlobalMemCacheSize , _clDeviceGlobalMemCachelineSize = deviceGlobalMemCachelineSize , _clDeviceGlobalMemSize = deviceGlobalMemSize , _clDeviceImageSupport = deviceImageSupport , _clDeviceImage2DMaxHeight = deviceImage2DMaxHeight , _clDeviceImage2DMaxWidth = deviceImage2DMaxWidth , _clDeviceImage3DMaxDepth = deviceImage3DMaxDepth , _clDeviceImage3DMaxHeight = deviceImage3DMaxHeight , _clDeviceImage3DMaxWidth = deviceImage3DMaxWidth , _clDeviceLocalMemSize = deviceLocalMemSize , _clDeviceMaxClockFrequency = deviceMaxClockFrequency , _clDeviceMaxComputeUnits = deviceMaxComputeUnits , _clDeviceMaxConstantArgs = deviceMaxConstantArgs , _clDeviceMaxConstantBufferSize = deviceMaxConstantBufferSize , _clDeviceMaxMemAllocSize = deviceMaxMemAllocSize , _clDeviceMaxParameterSize = deviceMaxParameterSize , _clDeviceMaxReadImageArgs = deviceMaxReadImageArgs , _clDeviceMaxSamplers = deviceMaxSamplers , _clDeviceMaxWorkGroupSize = deviceMaxWorkGroupSize , _clDeviceMaxWorkItemDimensions = deviceMaxWorkItemDimensions , _clDeviceMaxWorkItemSizes = deviceMaxWorkItemSizes , _clDeviceMaxWriteImageArgs = deviceMaxWriteImageArgs , _clDeviceMemBaseAddrAlign = deviceMemBaseAddrAlign , _clDeviceMinDataTypeAlignSize = deviceMinDataTypeAlignSize , _clDevicePreferredVectorWidthChar = devicePreferredVectorWidthChar , _clDevicePreferredVectorWidthShort = devicePreferredVectorWidthShort , _clDevicePreferredVectorWidthInt = devicePreferredVectorWidthInt , _clDevicePreferredVectorWidthLong = devicePreferredVectorWidthLong , _clDevicePreferredVectorWidthFloat = devicePreferredVectorWidthFloat , _clDevicePreferredVectorWidthDouble = devicePreferredVectorWidthDouble , _clDeviceProfile = determineClDeviceProfile deviceProfile , _clDeviceProfilingTimerResolution = deviceProfilingTimerResolution , _clDeviceVendor = deviceVendor , _clDeviceVendorID = deviceVendorID , _clDeviceVersion = deviceVersion , _clDeviceDriverVersion = deviceDriverVersion , _clDeviceSingleFPConfig = deviceSingleFPConfig , _clDeviceDoubleFPConfig = deviceDoubleFPConfig , _clDeviceLocalMemType = deviceLocalMemType , _clDeviceGlobalMemCacheType = deviceGlobalMemCacheType , _clDeviceQueueProperties = deviceQueueProperties , _clDeviceType = deviceType } dumpPlatformDetauk :: CLPlatformDetail -> String dumpPlatformDetauk platformInfo = (titleLine ("Platform " ++ show (platformInfo ^. clPlatformName)) ++) $ foldl1 (++) $ map infoLine $ [ ( "Profile", show $ platformInfo ^. clPlatformProfile ) , ( "Version", show $ platformInfo ^. clPlatformVersion ) , ( "Vendor", show $ platformInfo ^. clPlatformVendor ) , ( "Extensions", show $ platformInfo ^. clPlatformExtensions ) ] dumpDeviceDetail :: CLDeviceDetail -> String dumpDeviceDetail deviceDetail = (titleLine (show (deviceDetail ^. clDeviceName)) ++) $ foldl1 (++) $ map infoLine $ [ ( "ExecutionCapabilities" , show $ deviceDetail ^. clDeviceExecutionCapabilities ) , ( "DeviceAddressBits", show $ deviceDetail ^. clDeviceAddressBits ) , ( "Available", show $ deviceDetail ^. clDeviceAvailable ) , ( "CompilerAvailable", show $ deviceDetail ^. clDeviceCompilerAvailable ) , ( "EndianLittle", show $ deviceDetail ^. clDeviceEndianLittle ) , ( "ErrorCorrectionSupport", show $ deviceDetail ^. clDeviceErrorCorrectionSupport ) , ( "Extensions", show $ deviceDetail ^. clDeviceExtensions ) , ( "GlobalMemCacheSize", show $ deviceDetail ^. clDeviceGlobalMemCacheSize ) , ( "GlobalMemCachelineSize", show $ deviceDetail ^. clDeviceGlobalMemCachelineSize ) , ( "GlobalMemSize", show $ deviceDetail ^. clDeviceGlobalMemSize ) , ( "ImageSupport", show $ deviceDetail ^. clDeviceImageSupport ) , ( "Image2DMaxHeight", show $ deviceDetail ^. clDeviceImage2DMaxHeight ) , ( "Image2DMaxWidth", show $ deviceDetail ^. clDeviceImage2DMaxWidth ) , ( "Image3DMaxDepth", show $ deviceDetail ^. clDeviceImage3DMaxDepth ) , ( "Image3DMaxHeight", show $ deviceDetail ^. clDeviceImage3DMaxHeight ) , ( "Image3DMaxWidth", show $ deviceDetail ^. clDeviceImage3DMaxWidth ) , ( "LocalMemSize", show $ deviceDetail ^. clDeviceLocalMemSize ) , ( "MaxClockFrequency", show $ deviceDetail ^. clDeviceMaxClockFrequency ) , ( "MaxComputeUnits", show $ deviceDetail ^. clDeviceMaxComputeUnits ) , ( "MaxConstantArgs", show $ deviceDetail ^. clDeviceMaxConstantArgs ) , ( "MaxConstantBufferSize", show $ deviceDetail ^. clDeviceMaxConstantBufferSize ) , ( "MaxMemAllocSize", show $ deviceDetail ^. clDeviceMaxMemAllocSize ) , ( "MaxParameterSize", show $ deviceDetail ^. clDeviceMaxParameterSize ) , ( "MaxReadImageArgs", show $ deviceDetail ^. clDeviceMaxReadImageArgs ) , ( "MaxSamplers", show $ deviceDetail ^. clDeviceMaxSamplers ) , ( "MaxWorkGroupSize", show $ deviceDetail ^. clDeviceMaxWorkGroupSize ) , ( "MaxWorkItemDimensions", show $ deviceDetail ^. clDeviceMaxWorkItemDimensions ) , ( "MaxWorkItemSizes", show $ deviceDetail ^. clDeviceMaxWorkItemSizes ) , ( "MaxWriteImageArgs", show $ deviceDetail ^. clDeviceMaxWriteImageArgs ) , ( "MemBaseAddrAlign", show $ deviceDetail ^. clDeviceMemBaseAddrAlign ) , ( "MinDataTypeAlignSize", show $ deviceDetail ^. clDeviceMinDataTypeAlignSize ) , ( "PreferredVectorWidthChar", show $ deviceDetail ^. clDevicePreferredVectorWidthChar ) , ( "PreferredVectorWidthShort", show $ deviceDetail ^. clDevicePreferredVectorWidthShort ) , ( "PreferredVectorWidthInt", show $ deviceDetail ^. clDevicePreferredVectorWidthInt ) , ( "PreferredVectorWidthLong", show $ deviceDetail ^. clDevicePreferredVectorWidthLong ) , ( "PreferredVectorWidthFloat", show $ deviceDetail ^. clDevicePreferredVectorWidthFloat ) , ("PreferredVectorWidthDouble", show $ deviceDetail ^. clDevicePreferredVectorWidthDouble) , ( "Profile", show $ deviceDetail ^. clDeviceProfile ) , ( "ProfilingTimerResolution", show $ deviceDetail ^. clDeviceProfilingTimerResolution ) , ( "Vendor", show $ deviceDetail ^. clDeviceVendor ) , ( "VendorID", show $ deviceDetail ^. clDeviceVendorID ) , ( "Version", show $ deviceDetail ^. clDeviceVersion ) , ( "DriverVersion", show $ deviceDetail ^. clDeviceDriverVersion ) , ( "SingleFPConfig", show $ deviceDetail ^. clDeviceSingleFPConfig ) , ( "DoubleFPConfig", show $ deviceDetail ^. clDeviceDoubleFPConfig ) , ( "LocalMemType", show $ deviceDetail ^. clDeviceLocalMemType ) , ( "GlobalMemCacheType", show $ deviceDetail ^. clDeviceGlobalMemCacheType ) , ( "QueueProperties", show $ deviceDetail ^. clDeviceQueueProperties ) , ( "Type", show $ deviceDetail ^. clDeviceType ) ] | Query of all information about a every available OpenCL platform and queryOpenCL :: CLDeviceType -> IO [CLDeviceDetail] queryOpenCL deviceType = do platformIDs <- clGetPlatformIDs concat <$> mapM (\platformID -> do platformName <- clGetPlatformInfo platformID CL_PLATFORM_NAME putStrLn ("Found platform: " ++ platformName) deviceIDs <- clGetDeviceIDs platformID deviceType & handle (\err -> if err == CL_DEVICE_NOT_FOUND then return [] else throw err) putStrLn ("Found " ++ show (length deviceIDs) ++ " devices") deviceInfos <- mapM (initCLDeviceDetail platformID) deviceIDs return deviceInfos) platformIDs
940b3a1ef63cc052cdfbfdff27eb2c6752ad0fdfcfdbc1d1d7fec15896c134b7
master/ejabberd
mod_vcard.erl
%%%---------------------------------------------------------------------- %%% File : mod_vcard.erl Author : < > Purpose : Vcard management in Created : 2 Jan 2003 by < > %%% %%% ejabberd , Copyright ( C ) 2002 - 2012 ProcessOne %%% %%% This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the %%% License, or (at your option) any later version. %%% %%% This program is distributed in the hope that it will be useful, %%% but WITHOUT ANY WARRANTY; without even the implied warranty of %%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU %%% General Public License for more details. %%% You should have received a copy of the GNU General Public License %%% along with this program; if not, write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA %%% %%%---------------------------------------------------------------------- -module(mod_vcard). -author(''). -behaviour(gen_mod). -export([start/2, init/3, stop/1, get_sm_features/5, process_local_iq/3, process_sm_iq/3, reindex_vcards/0, remove_user/2]). -include("ejabberd.hrl"). -include("jlib.hrl"). -define(JUD_MATCHES, 30). -record(vcard_search, {us, user, luser, fn, lfn, family, lfamily, given, lgiven, middle, lmiddle, nickname, lnickname, bday, lbday, ctry, lctry, locality, llocality, email, lemail, orgname, lorgname, orgunit, lorgunit }). -record(vcard, {us, vcard}). -define(PROCNAME, ejabberd_mod_vcard). start(Host, Opts) -> mnesia:create_table(vcard, [{disc_only_copies, [node()]}, {attributes, record_info(fields, vcard)}]), mnesia:create_table(vcard_search, [{disc_copies, [node()]}, {attributes, record_info(fields, vcard_search)}]), update_tables(), mnesia:add_table_index(vcard_search, luser), mnesia:add_table_index(vcard_search, lfn), mnesia:add_table_index(vcard_search, lfamily), mnesia:add_table_index(vcard_search, lgiven), mnesia:add_table_index(vcard_search, lmiddle), mnesia:add_table_index(vcard_search, lnickname), mnesia:add_table_index(vcard_search, lbday), mnesia:add_table_index(vcard_search, lctry), mnesia:add_table_index(vcard_search, llocality), mnesia:add_table_index(vcard_search, lemail), mnesia:add_table_index(vcard_search, lorgname), mnesia:add_table_index(vcard_search, lorgunit), ejabberd_hooks:add(remove_user, Host, ?MODULE, remove_user, 50), IQDisc = gen_mod:get_opt(iqdisc, Opts, one_queue), gen_iq_handler:add_iq_handler(ejabberd_local, Host, ?NS_VCARD, ?MODULE, process_local_iq, IQDisc), gen_iq_handler:add_iq_handler(ejabberd_sm, Host, ?NS_VCARD, ?MODULE, process_sm_iq, IQDisc), ejabberd_hooks:add(disco_sm_features, Host, ?MODULE, get_sm_features, 50), MyHost = gen_mod:get_opt_host(Host, Opts, "vjud.@HOST@"), Search = gen_mod:get_opt(search, Opts, true), register(gen_mod:get_module_proc(Host, ?PROCNAME), spawn(?MODULE, init, [MyHost, Host, Search])). init(Host, ServerHost, Search) -> case Search of false -> loop(Host, ServerHost); _ -> ejabberd_router:register_route(Host), loop(Host, ServerHost) end. loop(Host, ServerHost) -> receive {route, From, To, Packet} -> case catch do_route(ServerHost, From, To, Packet) of {'EXIT', Reason} -> ?ERROR_MSG("~p", [Reason]); _ -> ok end, loop(Host, ServerHost); stop -> ejabberd_router:unregister_route(Host), ok; _ -> loop(Host, ServerHost) end. stop(Host) -> ejabberd_hooks:delete(remove_user, Host, ?MODULE, remove_user, 50), gen_iq_handler:remove_iq_handler(ejabberd_local, Host, ?NS_VCARD), gen_iq_handler:remove_iq_handler(ejabberd_sm, Host, ?NS_VCARD), ejabberd_hooks:delete(disco_sm_features, Host, ?MODULE, get_sm_features, 50), Proc = gen_mod:get_module_proc(Host, ?PROCNAME), Proc ! stop, {wait, Proc}. get_sm_features({error, _Error} = Acc, _From, _To, _Node, _Lang) -> Acc; get_sm_features(Acc, _From, _To, Node, _Lang) -> case Node of [] -> case Acc of {result, Features} -> {result, [?NS_DISCO_INFO, ?NS_VCARD | Features]}; empty -> {result, [?NS_DISCO_INFO, ?NS_VCARD]} end; _ -> Acc end. process_local_iq(_From, _To, #iq{type = Type, lang = Lang, sub_el = SubEl} = IQ) -> case Type of set -> IQ#iq{type = error, sub_el = [SubEl, ?ERR_NOT_ALLOWED]}; get -> IQ#iq{type = result, sub_el = [{xmlelement, "vCard", [{"xmlns", ?NS_VCARD}], [{xmlelement, "FN", [], [{xmlcdata, "ejabberd"}]}, {xmlelement, "URL", [], [{xmlcdata, ?EJABBERD_URI}]}, {xmlelement, "DESC", [], [{xmlcdata, translate:translate( Lang, "Erlang Jabber Server") ++ "\nCopyright (c) 2002-2012 ProcessOne"}]}, {xmlelement, "BDAY", [], [{xmlcdata, "2002-11-16"}]} ]}]} end. process_sm_iq(From, To, #iq{type = Type, sub_el = SubEl} = IQ) -> case Type of set -> #jid{user = User, lserver = LServer} = From, case lists:member(LServer, ?MYHOSTS) of true -> set_vcard(User, LServer, SubEl), IQ#iq{type = result, sub_el = []}; false -> IQ#iq{type = error, sub_el = [SubEl, ?ERR_NOT_ALLOWED]} end; get -> #jid{luser = LUser, lserver = LServer} = To, US = {LUser, LServer}, F = fun() -> mnesia:read({vcard, US}) end, Els = case mnesia:transaction(F) of {atomic, Rs} -> lists:map(fun(R) -> R#vcard.vcard end, Rs); {aborted, _Reason} -> [] end, IQ#iq{type = result, sub_el = Els} end. set_vcard(User, LServer, VCARD) -> FN = xml:get_path_s(VCARD, [{elem, "FN"}, cdata]), Family = xml:get_path_s(VCARD, [{elem, "N"}, {elem, "FAMILY"}, cdata]), Given = xml:get_path_s(VCARD, [{elem, "N"}, {elem, "GIVEN"}, cdata]), Middle = xml:get_path_s(VCARD, [{elem, "N"}, {elem, "MIDDLE"}, cdata]), Nickname = xml:get_path_s(VCARD, [{elem, "NICKNAME"}, cdata]), BDay = xml:get_path_s(VCARD, [{elem, "BDAY"}, cdata]), CTRY = xml:get_path_s(VCARD, [{elem, "ADR"}, {elem, "CTRY"}, cdata]), Locality = xml:get_path_s(VCARD, [{elem, "ADR"}, {elem, "LOCALITY"},cdata]), EMail1 = xml:get_path_s(VCARD, [{elem, "EMAIL"}, {elem, "USERID"},cdata]), EMail2 = xml:get_path_s(VCARD, [{elem, "EMAIL"}, cdata]), OrgName = xml:get_path_s(VCARD, [{elem, "ORG"}, {elem, "ORGNAME"}, cdata]), OrgUnit = xml:get_path_s(VCARD, [{elem, "ORG"}, {elem, "ORGUNIT"}, cdata]), EMail = case EMail1 of "" -> EMail2; _ -> EMail1 end, LUser = jlib:nodeprep(User), LFN = string2lower(FN), LFamily = string2lower(Family), LGiven = string2lower(Given), LMiddle = string2lower(Middle), LNickname = string2lower(Nickname), LBDay = string2lower(BDay), LCTRY = string2lower(CTRY), LLocality = string2lower(Locality), LEMail = string2lower(EMail), LOrgName = string2lower(OrgName), LOrgUnit = string2lower(OrgUnit), US = {LUser, LServer}, if (LUser == error) or (LFN == error) or (LFamily == error) or (LGiven == error) or (LMiddle == error) or (LNickname == error) or (LBDay == error) or (LCTRY == error) or (LLocality == error) or (LEMail == error) or (LOrgName == error) or (LOrgUnit == error) -> {error, badarg}; true -> F = fun() -> mnesia:write(#vcard{us = US, vcard = VCARD}), mnesia:write( #vcard_search{us = US, user = {User, LServer}, luser = LUser, fn = FN, lfn = LFN, family = Family, lfamily = LFamily, given = Given, lgiven = LGiven, middle = Middle, lmiddle = LMiddle, nickname = Nickname, lnickname = LNickname, bday = BDay, lbday = LBDay, ctry = CTRY, lctry = LCTRY, locality = Locality, llocality = LLocality, email = EMail, lemail = LEMail, orgname = OrgName, lorgname = LOrgName, orgunit = OrgUnit, lorgunit = LOrgUnit }) end, mnesia:transaction(F), ejabberd_hooks:run(vcard_set, LServer, [LUser, LServer, VCARD]) end. string2lower(String) -> case stringprep:tolower(String) of Lower when is_list(Lower) -> Lower; error -> string:to_lower(String) end. -define(TLFIELD(Type, Label, Var), {xmlelement, "field", [{"type", Type}, {"label", translate:translate(Lang, Label)}, {"var", Var}], []}). -define(FORM(JID), [{xmlelement, "instructions", [], [{xmlcdata, translate:translate(Lang, "You need an x:data capable client to search")}]}, {xmlelement, "x", [{"xmlns", ?NS_XDATA}, {"type", "form"}], [{xmlelement, "title", [], [{xmlcdata, translate:translate(Lang, "Search users in ") ++ jlib:jid_to_string(JID)}]}, {xmlelement, "instructions", [], [{xmlcdata, translate:translate(Lang, "Fill in the form to search " "for any matching Jabber User " "(Add * to the end of field to " "match substring)")}]}, ?TLFIELD("text-single", "User", "user"), ?TLFIELD("text-single", "Full Name", "fn"), ?TLFIELD("text-single", "Name", "first"), ?TLFIELD("text-single", "Middle Name", "middle"), ?TLFIELD("text-single", "Family Name", "last"), ?TLFIELD("text-single", "Nickname", "nick"), ?TLFIELD("text-single", "Birthday", "bday"), ?TLFIELD("text-single", "Country", "ctry"), ?TLFIELD("text-single", "City", "locality"), ?TLFIELD("text-single", "Email", "email"), ?TLFIELD("text-single", "Organization Name", "orgname"), ?TLFIELD("text-single", "Organization Unit", "orgunit") ]}]). do_route(ServerHost, From, To, Packet) -> #jid{user = User, resource = Resource} = To, if (User /= "") or (Resource /= "") -> Err = jlib:make_error_reply(Packet, ?ERR_SERVICE_UNAVAILABLE), ejabberd_router:route(To, From, Err); true -> IQ = jlib:iq_query_info(Packet), case IQ of #iq{type = Type, xmlns = ?NS_SEARCH, lang = Lang, sub_el = SubEl} -> case Type of set -> XDataEl = find_xdata_el(SubEl), case XDataEl of false -> Err = jlib:make_error_reply( Packet, ?ERR_BAD_REQUEST), ejabberd_router:route(To, From, Err); _ -> XData = jlib:parse_xdata_submit(XDataEl), case XData of invalid -> Err = jlib:make_error_reply( Packet, ?ERR_BAD_REQUEST), ejabberd_router:route(To, From, Err); _ -> ResIQ = IQ#iq{ type = result, sub_el = [{xmlelement, "query", [{"xmlns", ?NS_SEARCH}], [{xmlelement, "x", [{"xmlns", ?NS_XDATA}, {"type", "result"}], search_result(Lang, To, ServerHost, XData) }]}]}, ejabberd_router:route( To, From, jlib:iq_to_xml(ResIQ)) end end; get -> ResIQ = IQ#iq{type = result, sub_el = [{xmlelement, "query", [{"xmlns", ?NS_SEARCH}], ?FORM(To) }]}, ejabberd_router:route(To, From, jlib:iq_to_xml(ResIQ)) end; #iq{type = Type, xmlns = ?NS_DISCO_INFO, lang = Lang} -> case Type of set -> Err = jlib:make_error_reply( Packet, ?ERR_NOT_ALLOWED), ejabberd_router:route(To, From, Err); get -> Info = ejabberd_hooks:run_fold( disco_info, ServerHost, [], [ServerHost, ?MODULE, "", ""]), ResIQ = IQ#iq{type = result, sub_el = [{xmlelement, "query", [{"xmlns", ?NS_DISCO_INFO}], [{xmlelement, "identity", [{"category", "directory"}, {"type", "user"}, {"name", translate:translate(Lang, "vCard User Search")}], []}, {xmlelement, "feature", [{"var", ?NS_DISCO_INFO}], []}, {xmlelement, "feature", [{"var", ?NS_SEARCH}], []}, {xmlelement, "feature", [{"var", ?NS_VCARD}], []} ] ++ Info }]}, ejabberd_router:route(To, From, jlib:iq_to_xml(ResIQ)) end; #iq{type = Type, xmlns = ?NS_DISCO_ITEMS} -> case Type of set -> Err = jlib:make_error_reply( Packet, ?ERR_NOT_ALLOWED), ejabberd_router:route(To, From, Err); get -> ResIQ = IQ#iq{type = result, sub_el = [{xmlelement, "query", [{"xmlns", ?NS_DISCO_ITEMS}], []}]}, ejabberd_router:route(To, From, jlib:iq_to_xml(ResIQ)) end; #iq{type = get, xmlns = ?NS_VCARD, lang = Lang} -> ResIQ = IQ#iq{type = result, sub_el = [{xmlelement, "vCard", [{"xmlns", ?NS_VCARD}], iq_get_vcard(Lang)}]}, ejabberd_router:route(To, From, jlib:iq_to_xml(ResIQ)); _ -> Err = jlib:make_error_reply(Packet, ?ERR_SERVICE_UNAVAILABLE), ejabberd_router:route(To, From, Err) end end. iq_get_vcard(Lang) -> [{xmlelement, "FN", [], [{xmlcdata, "ejabberd/mod_vcard"}]}, {xmlelement, "URL", [], [{xmlcdata, ?EJABBERD_URI}]}, {xmlelement, "DESC", [], [{xmlcdata, translate:translate( Lang, "ejabberd vCard module") ++ "\nCopyright (c) 2003-2012 ProcessOne"}]}]. find_xdata_el({xmlelement, _Name, _Attrs, SubEls}) -> find_xdata_el1(SubEls). find_xdata_el1([]) -> false; find_xdata_el1([{xmlelement, Name, Attrs, SubEls} | Els]) -> case xml:get_attr_s("xmlns", Attrs) of ?NS_XDATA -> {xmlelement, Name, Attrs, SubEls}; _ -> find_xdata_el1(Els) end; find_xdata_el1([_ | Els]) -> find_xdata_el1(Els). -define(LFIELD(Label, Var), {xmlelement, "field", [{"label", translate:translate(Lang, Label)}, {"var", Var}], []}). search_result(Lang, JID, ServerHost, Data) -> [{xmlelement, "title", [], [{xmlcdata, translate:translate(Lang, "Search Results for ") ++ jlib:jid_to_string(JID)}]}, {xmlelement, "reported", [], [?TLFIELD("text-single", "Jabber ID", "jid"), ?TLFIELD("text-single", "Full Name", "fn"), ?TLFIELD("text-single", "Name", "first"), ?TLFIELD("text-single", "Middle Name", "middle"), ?TLFIELD("text-single", "Family Name", "last"), ?TLFIELD("text-single", "Nickname", "nick"), ?TLFIELD("text-single", "Birthday", "bday"), ?TLFIELD("text-single", "Country", "ctry"), ?TLFIELD("text-single", "City", "locality"), ?TLFIELD("text-single", "Email", "email"), ?TLFIELD("text-single", "Organization Name", "orgname"), ?TLFIELD("text-single", "Organization Unit", "orgunit") ]}] ++ lists:map(fun record_to_item/1, search(ServerHost, Data)). -define(FIELD(Var, Val), {xmlelement, "field", [{"var", Var}], [{xmlelement, "value", [], [{xmlcdata, Val}]}]}). record_to_item(R) -> {User, Server} = R#vcard_search.user, {xmlelement, "item", [], [ ?FIELD("jid", User ++ "@" ++ Server), ?FIELD("fn", R#vcard_search.fn), ?FIELD("last", R#vcard_search.family), ?FIELD("first", R#vcard_search.given), ?FIELD("middle", R#vcard_search.middle), ?FIELD("nick", R#vcard_search.nickname), ?FIELD("bday", R#vcard_search.bday), ?FIELD("ctry", R#vcard_search.ctry), ?FIELD("locality", R#vcard_search.locality), ?FIELD("email", R#vcard_search.email), ?FIELD("orgname", R#vcard_search.orgname), ?FIELD("orgunit", R#vcard_search.orgunit) ] }. search(LServer, Data) -> MatchSpec = make_matchspec(LServer, Data), AllowReturnAll = gen_mod:get_module_opt(LServer, ?MODULE, allow_return_all, false), if (MatchSpec == #vcard_search{_ = '_'}) and (not AllowReturnAll) -> []; true -> case catch mnesia:dirty_select(vcard_search, [{MatchSpec, [], ['$_']}]) of {'EXIT', Reason} -> ?ERROR_MSG("~p", [Reason]), []; Rs -> case gen_mod:get_module_opt(LServer, ?MODULE, matches, ?JUD_MATCHES) of infinity -> Rs; Val when is_integer(Val) and (Val > 0) -> lists:sublist(Rs, Val); Val -> ?ERROR_MSG("Illegal option value ~p. " "Default value ~p substituted.", [{matches, Val}, ?JUD_MATCHES]), lists:sublist(Rs, ?JUD_MATCHES) end end end. make_matchspec(LServer, Data) -> GlobMatch = #vcard_search{_ = '_'}, Match = filter_fields(Data, GlobMatch, LServer), Match. filter_fields([], Match, _LServer) -> Match; filter_fields([{SVar, [Val]} | Ds], Match, LServer) when is_list(Val) and (Val /= "") -> LVal = string2lower(Val), NewMatch = case SVar of "user" -> case gen_mod:get_module_opt(LServer, ?MODULE, search_all_hosts, true) of true -> Match#vcard_search{luser = make_val(LVal)}; false -> Host = find_my_host(LServer), Match#vcard_search{us = {make_val(LVal), Host}} end; "fn" -> Match#vcard_search{lfn = make_val(LVal)}; "last" -> Match#vcard_search{lfamily = make_val(LVal)}; "first" -> Match#vcard_search{lgiven = make_val(LVal)}; "middle" -> Match#vcard_search{lmiddle = make_val(LVal)}; "nick" -> Match#vcard_search{lnickname = make_val(LVal)}; "bday" -> Match#vcard_search{lbday = make_val(LVal)}; "ctry" -> Match#vcard_search{lctry = make_val(LVal)}; "locality" -> Match#vcard_search{llocality = make_val(LVal)}; "email" -> Match#vcard_search{lemail = make_val(LVal)}; "orgname" -> Match#vcard_search{lorgname = make_val(LVal)}; "orgunit" -> Match#vcard_search{lorgunit = make_val(LVal)}; _ -> Match end, filter_fields(Ds, NewMatch, LServer); filter_fields([_ | Ds], Match, LServer) -> filter_fields(Ds, Match, LServer). make_val(Val) -> case lists:suffix("*", Val) of true -> lists:sublist(Val, length(Val) - 1) ++ '_'; _ -> Val end. find_my_host(LServer) -> Parts = string:tokens(LServer, "."), find_my_host(Parts, ?MYHOSTS). find_my_host([], _Hosts) -> ?MYNAME; find_my_host([_ | Tail] = Parts, Hosts) -> Domain = parts_to_string(Parts), case lists:member(Domain, Hosts) of true -> Domain; false -> find_my_host(Tail, Hosts) end. parts_to_string(Parts) -> string:strip(lists:flatten(lists:map(fun(S) -> [S, $.] end, Parts)), right, $.). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% set_vcard_t(R, _) -> US = R#vcard.us, User = US, VCARD = R#vcard.vcard, FN = xml:get_path_s(VCARD, [{elem, "FN"}, cdata]), Family = xml:get_path_s(VCARD, [{elem, "N"}, {elem, "FAMILY"}, cdata]), Given = xml:get_path_s(VCARD, [{elem, "N"}, {elem, "GIVEN"}, cdata]), Middle = xml:get_path_s(VCARD, [{elem, "N"}, {elem, "MIDDLE"}, cdata]), Nickname = xml:get_path_s(VCARD, [{elem, "NICKNAME"}, cdata]), BDay = xml:get_path_s(VCARD, [{elem, "BDAY"}, cdata]), CTRY = xml:get_path_s(VCARD, [{elem, "ADR"}, {elem, "CTRY"}, cdata]), Locality = xml:get_path_s(VCARD, [{elem, "ADR"}, {elem, "LOCALITY"},cdata]), EMail = xml:get_path_s(VCARD, [{elem, "EMAIL"}, cdata]), OrgName = xml:get_path_s(VCARD, [{elem, "ORG"}, {elem, "ORGNAME"}, cdata]), OrgUnit = xml:get_path_s(VCARD, [{elem, "ORG"}, {elem, "ORGUNIT"}, cdata]), {LUser, _LServer} = US, LFN = string2lower(FN), LFamily = string2lower(Family), LGiven = string2lower(Given), LMiddle = string2lower(Middle), LNickname = string2lower(Nickname), LBDay = string2lower(BDay), LCTRY = string2lower(CTRY), LLocality = string2lower(Locality), LEMail = string2lower(EMail), LOrgName = string2lower(OrgName), LOrgUnit = string2lower(OrgUnit), if (LUser == error) or (LFN == error) or (LFamily == error) or (LGiven == error) or (LMiddle == error) or (LNickname == error) or (LBDay == error) or (LCTRY == error) or (LLocality == error) or (LEMail == error) or (LOrgName == error) or (LOrgUnit == error) -> {error, badarg}; true -> mnesia:write( #vcard_search{us = US, user = User, luser = LUser, fn = FN, lfn = LFN, family = Family, lfamily = LFamily, given = Given, lgiven = LGiven, middle = Middle, lmiddle = LMiddle, nickname = Nickname, lnickname = LNickname, bday = BDay, lbday = LBDay, ctry = CTRY, lctry = LCTRY, locality = Locality, llocality = LLocality, email = EMail, lemail = LEMail, orgname = OrgName, lorgname = LOrgName, orgunit = OrgUnit, lorgunit = LOrgUnit }) end. reindex_vcards() -> F = fun() -> mnesia:foldl(fun set_vcard_t/2, [], vcard) end, mnesia:transaction(F). remove_user(User, Server) -> LUser = jlib:nodeprep(User), LServer = jlib:nameprep(Server), US = {LUser, LServer}, F = fun() -> mnesia:delete({vcard, US}), mnesia:delete({vcard_search, US}) end, mnesia:transaction(F). update_tables() -> update_vcard_table(), update_vcard_search_table(). update_vcard_table() -> Fields = record_info(fields, vcard), case mnesia:table_info(vcard, attributes) of Fields -> ok; [user, vcard] -> ?INFO_MSG("Converting vcard table from " "{user, vcard} format", []), Host = ?MYNAME, {atomic, ok} = mnesia:create_table( mod_vcard_tmp_table, [{disc_only_copies, [node()]}, {type, bag}, {local_content, true}, {record_name, vcard}, {attributes, record_info(fields, vcard)}]), mnesia:transform_table(vcard, ignore, Fields), F1 = fun() -> mnesia:write_lock_table(mod_vcard_tmp_table), mnesia:foldl( fun(#vcard{us = U} = R, _) -> mnesia:dirty_write( mod_vcard_tmp_table, R#vcard{us = {U, Host}}) end, ok, vcard) end, mnesia:transaction(F1), mnesia:clear_table(vcard), F2 = fun() -> mnesia:write_lock_table(vcard), mnesia:foldl( fun(R, _) -> mnesia:dirty_write(R) end, ok, mod_vcard_tmp_table) end, mnesia:transaction(F2), mnesia:delete_table(mod_vcard_tmp_table); _ -> ?INFO_MSG("Recreating vcard table", []), mnesia:transform_table(vcard, ignore, Fields) end. update_vcard_search_table() -> Fields = record_info(fields, vcard_search), case mnesia:table_info(vcard_search, attributes) of Fields -> ok; [user, luser, fn, lfn, family, lfamily, given, lgiven, middle, lmiddle, nickname, lnickname, bday, lbday, ctry, lctry, locality, llocality, email, lemail, orgname, lorgname, orgunit, lorgunit] -> ?INFO_MSG("Converting vcard_search table from " "{user, luser, fn, lfn, family, lfamily, given, lgiven, middle, lmiddle, nickname, lnickname, bday, lbday, ctry, lctry, locality, llocality, email, lemail, orgname, lorgname, orgunit, lorgunit} format", []), Host = ?MYNAME, {atomic, ok} = mnesia:create_table( mod_vcard_tmp_table, [{disc_only_copies, [node()]}, {type, bag}, {local_content, true}, {record_name, vcard_search}, {attributes, record_info(fields, vcard_search)}]), F1 = fun() -> mnesia:write_lock_table(mod_vcard_tmp_table), mnesia:foldl( fun({vcard_search, User, LUser, FN, LFN, Family, LFamily, Given, LGiven, Middle, LMiddle, Nickname, LNickname, BDay, LBDay, CTRY, LCTRY, Locality, LLocality, EMail, LEMail, OrgName, LOrgName, OrgUnit, LOrgUnit }, _) -> mnesia:dirty_write( mod_vcard_tmp_table, #vcard_search{ us = {LUser, Host}, user = {User, Host}, luser = LUser, fn = FN, lfn = LFN, family = Family, lfamily = LFamily, given = Given, lgiven = LGiven, middle = Middle, lmiddle = LMiddle, nickname = Nickname, lnickname = LNickname, bday = BDay, lbday = LBDay, ctry = CTRY, lctry = LCTRY, locality = Locality, llocality = LLocality, email = EMail, lemail = LEMail, orgname = OrgName, lorgname = LOrgName, orgunit = OrgUnit, lorgunit = LOrgUnit }) end, ok, vcard_search) end, mnesia:transaction(F1), lists:foreach(fun(I) -> mnesia:del_table_index( vcard_search, element(I, {vcard_search, user, luser, fn, lfn, family, lfamily, given, lgiven, middle, lmiddle, nickname, lnickname, bday, lbday, ctry, lctry, locality, llocality, email, lemail, orgname, lorgname, orgunit, lorgunit})) end, mnesia:table_info(vcard_search, index)), mnesia:clear_table(vcard_search), mnesia:transform_table(vcard_search, ignore, Fields), F2 = fun() -> mnesia:write_lock_table(vcard_search), mnesia:foldl( fun(R, _) -> mnesia:dirty_write(R) end, ok, mod_vcard_tmp_table) end, mnesia:transaction(F2), mnesia:delete_table(mod_vcard_tmp_table); _ -> ?INFO_MSG("Recreating vcard_search table", []), mnesia:transform_table(vcard_search, ignore, Fields) end.
null
https://raw.githubusercontent.com/master/ejabberd/9c31874d5a9d1852ece1b8ae70dd4b7e5eef7cf7/src/mod_vcard.erl
erlang
---------------------------------------------------------------------- File : mod_vcard.erl This program is free software; you can redistribute it and/or License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program; if not, write to the Free Software ----------------------------------------------------------------------
Author : < > Purpose : Vcard management in Created : 2 Jan 2003 by < > ejabberd , Copyright ( C ) 2002 - 2012 ProcessOne modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the You should have received a copy of the GNU General Public License Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA -module(mod_vcard). -author(''). -behaviour(gen_mod). -export([start/2, init/3, stop/1, get_sm_features/5, process_local_iq/3, process_sm_iq/3, reindex_vcards/0, remove_user/2]). -include("ejabberd.hrl"). -include("jlib.hrl"). -define(JUD_MATCHES, 30). -record(vcard_search, {us, user, luser, fn, lfn, family, lfamily, given, lgiven, middle, lmiddle, nickname, lnickname, bday, lbday, ctry, lctry, locality, llocality, email, lemail, orgname, lorgname, orgunit, lorgunit }). -record(vcard, {us, vcard}). -define(PROCNAME, ejabberd_mod_vcard). start(Host, Opts) -> mnesia:create_table(vcard, [{disc_only_copies, [node()]}, {attributes, record_info(fields, vcard)}]), mnesia:create_table(vcard_search, [{disc_copies, [node()]}, {attributes, record_info(fields, vcard_search)}]), update_tables(), mnesia:add_table_index(vcard_search, luser), mnesia:add_table_index(vcard_search, lfn), mnesia:add_table_index(vcard_search, lfamily), mnesia:add_table_index(vcard_search, lgiven), mnesia:add_table_index(vcard_search, lmiddle), mnesia:add_table_index(vcard_search, lnickname), mnesia:add_table_index(vcard_search, lbday), mnesia:add_table_index(vcard_search, lctry), mnesia:add_table_index(vcard_search, llocality), mnesia:add_table_index(vcard_search, lemail), mnesia:add_table_index(vcard_search, lorgname), mnesia:add_table_index(vcard_search, lorgunit), ejabberd_hooks:add(remove_user, Host, ?MODULE, remove_user, 50), IQDisc = gen_mod:get_opt(iqdisc, Opts, one_queue), gen_iq_handler:add_iq_handler(ejabberd_local, Host, ?NS_VCARD, ?MODULE, process_local_iq, IQDisc), gen_iq_handler:add_iq_handler(ejabberd_sm, Host, ?NS_VCARD, ?MODULE, process_sm_iq, IQDisc), ejabberd_hooks:add(disco_sm_features, Host, ?MODULE, get_sm_features, 50), MyHost = gen_mod:get_opt_host(Host, Opts, "vjud.@HOST@"), Search = gen_mod:get_opt(search, Opts, true), register(gen_mod:get_module_proc(Host, ?PROCNAME), spawn(?MODULE, init, [MyHost, Host, Search])). init(Host, ServerHost, Search) -> case Search of false -> loop(Host, ServerHost); _ -> ejabberd_router:register_route(Host), loop(Host, ServerHost) end. loop(Host, ServerHost) -> receive {route, From, To, Packet} -> case catch do_route(ServerHost, From, To, Packet) of {'EXIT', Reason} -> ?ERROR_MSG("~p", [Reason]); _ -> ok end, loop(Host, ServerHost); stop -> ejabberd_router:unregister_route(Host), ok; _ -> loop(Host, ServerHost) end. stop(Host) -> ejabberd_hooks:delete(remove_user, Host, ?MODULE, remove_user, 50), gen_iq_handler:remove_iq_handler(ejabberd_local, Host, ?NS_VCARD), gen_iq_handler:remove_iq_handler(ejabberd_sm, Host, ?NS_VCARD), ejabberd_hooks:delete(disco_sm_features, Host, ?MODULE, get_sm_features, 50), Proc = gen_mod:get_module_proc(Host, ?PROCNAME), Proc ! stop, {wait, Proc}. get_sm_features({error, _Error} = Acc, _From, _To, _Node, _Lang) -> Acc; get_sm_features(Acc, _From, _To, Node, _Lang) -> case Node of [] -> case Acc of {result, Features} -> {result, [?NS_DISCO_INFO, ?NS_VCARD | Features]}; empty -> {result, [?NS_DISCO_INFO, ?NS_VCARD]} end; _ -> Acc end. process_local_iq(_From, _To, #iq{type = Type, lang = Lang, sub_el = SubEl} = IQ) -> case Type of set -> IQ#iq{type = error, sub_el = [SubEl, ?ERR_NOT_ALLOWED]}; get -> IQ#iq{type = result, sub_el = [{xmlelement, "vCard", [{"xmlns", ?NS_VCARD}], [{xmlelement, "FN", [], [{xmlcdata, "ejabberd"}]}, {xmlelement, "URL", [], [{xmlcdata, ?EJABBERD_URI}]}, {xmlelement, "DESC", [], [{xmlcdata, translate:translate( Lang, "Erlang Jabber Server") ++ "\nCopyright (c) 2002-2012 ProcessOne"}]}, {xmlelement, "BDAY", [], [{xmlcdata, "2002-11-16"}]} ]}]} end. process_sm_iq(From, To, #iq{type = Type, sub_el = SubEl} = IQ) -> case Type of set -> #jid{user = User, lserver = LServer} = From, case lists:member(LServer, ?MYHOSTS) of true -> set_vcard(User, LServer, SubEl), IQ#iq{type = result, sub_el = []}; false -> IQ#iq{type = error, sub_el = [SubEl, ?ERR_NOT_ALLOWED]} end; get -> #jid{luser = LUser, lserver = LServer} = To, US = {LUser, LServer}, F = fun() -> mnesia:read({vcard, US}) end, Els = case mnesia:transaction(F) of {atomic, Rs} -> lists:map(fun(R) -> R#vcard.vcard end, Rs); {aborted, _Reason} -> [] end, IQ#iq{type = result, sub_el = Els} end. set_vcard(User, LServer, VCARD) -> FN = xml:get_path_s(VCARD, [{elem, "FN"}, cdata]), Family = xml:get_path_s(VCARD, [{elem, "N"}, {elem, "FAMILY"}, cdata]), Given = xml:get_path_s(VCARD, [{elem, "N"}, {elem, "GIVEN"}, cdata]), Middle = xml:get_path_s(VCARD, [{elem, "N"}, {elem, "MIDDLE"}, cdata]), Nickname = xml:get_path_s(VCARD, [{elem, "NICKNAME"}, cdata]), BDay = xml:get_path_s(VCARD, [{elem, "BDAY"}, cdata]), CTRY = xml:get_path_s(VCARD, [{elem, "ADR"}, {elem, "CTRY"}, cdata]), Locality = xml:get_path_s(VCARD, [{elem, "ADR"}, {elem, "LOCALITY"},cdata]), EMail1 = xml:get_path_s(VCARD, [{elem, "EMAIL"}, {elem, "USERID"},cdata]), EMail2 = xml:get_path_s(VCARD, [{elem, "EMAIL"}, cdata]), OrgName = xml:get_path_s(VCARD, [{elem, "ORG"}, {elem, "ORGNAME"}, cdata]), OrgUnit = xml:get_path_s(VCARD, [{elem, "ORG"}, {elem, "ORGUNIT"}, cdata]), EMail = case EMail1 of "" -> EMail2; _ -> EMail1 end, LUser = jlib:nodeprep(User), LFN = string2lower(FN), LFamily = string2lower(Family), LGiven = string2lower(Given), LMiddle = string2lower(Middle), LNickname = string2lower(Nickname), LBDay = string2lower(BDay), LCTRY = string2lower(CTRY), LLocality = string2lower(Locality), LEMail = string2lower(EMail), LOrgName = string2lower(OrgName), LOrgUnit = string2lower(OrgUnit), US = {LUser, LServer}, if (LUser == error) or (LFN == error) or (LFamily == error) or (LGiven == error) or (LMiddle == error) or (LNickname == error) or (LBDay == error) or (LCTRY == error) or (LLocality == error) or (LEMail == error) or (LOrgName == error) or (LOrgUnit == error) -> {error, badarg}; true -> F = fun() -> mnesia:write(#vcard{us = US, vcard = VCARD}), mnesia:write( #vcard_search{us = US, user = {User, LServer}, luser = LUser, fn = FN, lfn = LFN, family = Family, lfamily = LFamily, given = Given, lgiven = LGiven, middle = Middle, lmiddle = LMiddle, nickname = Nickname, lnickname = LNickname, bday = BDay, lbday = LBDay, ctry = CTRY, lctry = LCTRY, locality = Locality, llocality = LLocality, email = EMail, lemail = LEMail, orgname = OrgName, lorgname = LOrgName, orgunit = OrgUnit, lorgunit = LOrgUnit }) end, mnesia:transaction(F), ejabberd_hooks:run(vcard_set, LServer, [LUser, LServer, VCARD]) end. string2lower(String) -> case stringprep:tolower(String) of Lower when is_list(Lower) -> Lower; error -> string:to_lower(String) end. -define(TLFIELD(Type, Label, Var), {xmlelement, "field", [{"type", Type}, {"label", translate:translate(Lang, Label)}, {"var", Var}], []}). -define(FORM(JID), [{xmlelement, "instructions", [], [{xmlcdata, translate:translate(Lang, "You need an x:data capable client to search")}]}, {xmlelement, "x", [{"xmlns", ?NS_XDATA}, {"type", "form"}], [{xmlelement, "title", [], [{xmlcdata, translate:translate(Lang, "Search users in ") ++ jlib:jid_to_string(JID)}]}, {xmlelement, "instructions", [], [{xmlcdata, translate:translate(Lang, "Fill in the form to search " "for any matching Jabber User " "(Add * to the end of field to " "match substring)")}]}, ?TLFIELD("text-single", "User", "user"), ?TLFIELD("text-single", "Full Name", "fn"), ?TLFIELD("text-single", "Name", "first"), ?TLFIELD("text-single", "Middle Name", "middle"), ?TLFIELD("text-single", "Family Name", "last"), ?TLFIELD("text-single", "Nickname", "nick"), ?TLFIELD("text-single", "Birthday", "bday"), ?TLFIELD("text-single", "Country", "ctry"), ?TLFIELD("text-single", "City", "locality"), ?TLFIELD("text-single", "Email", "email"), ?TLFIELD("text-single", "Organization Name", "orgname"), ?TLFIELD("text-single", "Organization Unit", "orgunit") ]}]). do_route(ServerHost, From, To, Packet) -> #jid{user = User, resource = Resource} = To, if (User /= "") or (Resource /= "") -> Err = jlib:make_error_reply(Packet, ?ERR_SERVICE_UNAVAILABLE), ejabberd_router:route(To, From, Err); true -> IQ = jlib:iq_query_info(Packet), case IQ of #iq{type = Type, xmlns = ?NS_SEARCH, lang = Lang, sub_el = SubEl} -> case Type of set -> XDataEl = find_xdata_el(SubEl), case XDataEl of false -> Err = jlib:make_error_reply( Packet, ?ERR_BAD_REQUEST), ejabberd_router:route(To, From, Err); _ -> XData = jlib:parse_xdata_submit(XDataEl), case XData of invalid -> Err = jlib:make_error_reply( Packet, ?ERR_BAD_REQUEST), ejabberd_router:route(To, From, Err); _ -> ResIQ = IQ#iq{ type = result, sub_el = [{xmlelement, "query", [{"xmlns", ?NS_SEARCH}], [{xmlelement, "x", [{"xmlns", ?NS_XDATA}, {"type", "result"}], search_result(Lang, To, ServerHost, XData) }]}]}, ejabberd_router:route( To, From, jlib:iq_to_xml(ResIQ)) end end; get -> ResIQ = IQ#iq{type = result, sub_el = [{xmlelement, "query", [{"xmlns", ?NS_SEARCH}], ?FORM(To) }]}, ejabberd_router:route(To, From, jlib:iq_to_xml(ResIQ)) end; #iq{type = Type, xmlns = ?NS_DISCO_INFO, lang = Lang} -> case Type of set -> Err = jlib:make_error_reply( Packet, ?ERR_NOT_ALLOWED), ejabberd_router:route(To, From, Err); get -> Info = ejabberd_hooks:run_fold( disco_info, ServerHost, [], [ServerHost, ?MODULE, "", ""]), ResIQ = IQ#iq{type = result, sub_el = [{xmlelement, "query", [{"xmlns", ?NS_DISCO_INFO}], [{xmlelement, "identity", [{"category", "directory"}, {"type", "user"}, {"name", translate:translate(Lang, "vCard User Search")}], []}, {xmlelement, "feature", [{"var", ?NS_DISCO_INFO}], []}, {xmlelement, "feature", [{"var", ?NS_SEARCH}], []}, {xmlelement, "feature", [{"var", ?NS_VCARD}], []} ] ++ Info }]}, ejabberd_router:route(To, From, jlib:iq_to_xml(ResIQ)) end; #iq{type = Type, xmlns = ?NS_DISCO_ITEMS} -> case Type of set -> Err = jlib:make_error_reply( Packet, ?ERR_NOT_ALLOWED), ejabberd_router:route(To, From, Err); get -> ResIQ = IQ#iq{type = result, sub_el = [{xmlelement, "query", [{"xmlns", ?NS_DISCO_ITEMS}], []}]}, ejabberd_router:route(To, From, jlib:iq_to_xml(ResIQ)) end; #iq{type = get, xmlns = ?NS_VCARD, lang = Lang} -> ResIQ = IQ#iq{type = result, sub_el = [{xmlelement, "vCard", [{"xmlns", ?NS_VCARD}], iq_get_vcard(Lang)}]}, ejabberd_router:route(To, From, jlib:iq_to_xml(ResIQ)); _ -> Err = jlib:make_error_reply(Packet, ?ERR_SERVICE_UNAVAILABLE), ejabberd_router:route(To, From, Err) end end. iq_get_vcard(Lang) -> [{xmlelement, "FN", [], [{xmlcdata, "ejabberd/mod_vcard"}]}, {xmlelement, "URL", [], [{xmlcdata, ?EJABBERD_URI}]}, {xmlelement, "DESC", [], [{xmlcdata, translate:translate( Lang, "ejabberd vCard module") ++ "\nCopyright (c) 2003-2012 ProcessOne"}]}]. find_xdata_el({xmlelement, _Name, _Attrs, SubEls}) -> find_xdata_el1(SubEls). find_xdata_el1([]) -> false; find_xdata_el1([{xmlelement, Name, Attrs, SubEls} | Els]) -> case xml:get_attr_s("xmlns", Attrs) of ?NS_XDATA -> {xmlelement, Name, Attrs, SubEls}; _ -> find_xdata_el1(Els) end; find_xdata_el1([_ | Els]) -> find_xdata_el1(Els). -define(LFIELD(Label, Var), {xmlelement, "field", [{"label", translate:translate(Lang, Label)}, {"var", Var}], []}). search_result(Lang, JID, ServerHost, Data) -> [{xmlelement, "title", [], [{xmlcdata, translate:translate(Lang, "Search Results for ") ++ jlib:jid_to_string(JID)}]}, {xmlelement, "reported", [], [?TLFIELD("text-single", "Jabber ID", "jid"), ?TLFIELD("text-single", "Full Name", "fn"), ?TLFIELD("text-single", "Name", "first"), ?TLFIELD("text-single", "Middle Name", "middle"), ?TLFIELD("text-single", "Family Name", "last"), ?TLFIELD("text-single", "Nickname", "nick"), ?TLFIELD("text-single", "Birthday", "bday"), ?TLFIELD("text-single", "Country", "ctry"), ?TLFIELD("text-single", "City", "locality"), ?TLFIELD("text-single", "Email", "email"), ?TLFIELD("text-single", "Organization Name", "orgname"), ?TLFIELD("text-single", "Organization Unit", "orgunit") ]}] ++ lists:map(fun record_to_item/1, search(ServerHost, Data)). -define(FIELD(Var, Val), {xmlelement, "field", [{"var", Var}], [{xmlelement, "value", [], [{xmlcdata, Val}]}]}). record_to_item(R) -> {User, Server} = R#vcard_search.user, {xmlelement, "item", [], [ ?FIELD("jid", User ++ "@" ++ Server), ?FIELD("fn", R#vcard_search.fn), ?FIELD("last", R#vcard_search.family), ?FIELD("first", R#vcard_search.given), ?FIELD("middle", R#vcard_search.middle), ?FIELD("nick", R#vcard_search.nickname), ?FIELD("bday", R#vcard_search.bday), ?FIELD("ctry", R#vcard_search.ctry), ?FIELD("locality", R#vcard_search.locality), ?FIELD("email", R#vcard_search.email), ?FIELD("orgname", R#vcard_search.orgname), ?FIELD("orgunit", R#vcard_search.orgunit) ] }. search(LServer, Data) -> MatchSpec = make_matchspec(LServer, Data), AllowReturnAll = gen_mod:get_module_opt(LServer, ?MODULE, allow_return_all, false), if (MatchSpec == #vcard_search{_ = '_'}) and (not AllowReturnAll) -> []; true -> case catch mnesia:dirty_select(vcard_search, [{MatchSpec, [], ['$_']}]) of {'EXIT', Reason} -> ?ERROR_MSG("~p", [Reason]), []; Rs -> case gen_mod:get_module_opt(LServer, ?MODULE, matches, ?JUD_MATCHES) of infinity -> Rs; Val when is_integer(Val) and (Val > 0) -> lists:sublist(Rs, Val); Val -> ?ERROR_MSG("Illegal option value ~p. " "Default value ~p substituted.", [{matches, Val}, ?JUD_MATCHES]), lists:sublist(Rs, ?JUD_MATCHES) end end end. make_matchspec(LServer, Data) -> GlobMatch = #vcard_search{_ = '_'}, Match = filter_fields(Data, GlobMatch, LServer), Match. filter_fields([], Match, _LServer) -> Match; filter_fields([{SVar, [Val]} | Ds], Match, LServer) when is_list(Val) and (Val /= "") -> LVal = string2lower(Val), NewMatch = case SVar of "user" -> case gen_mod:get_module_opt(LServer, ?MODULE, search_all_hosts, true) of true -> Match#vcard_search{luser = make_val(LVal)}; false -> Host = find_my_host(LServer), Match#vcard_search{us = {make_val(LVal), Host}} end; "fn" -> Match#vcard_search{lfn = make_val(LVal)}; "last" -> Match#vcard_search{lfamily = make_val(LVal)}; "first" -> Match#vcard_search{lgiven = make_val(LVal)}; "middle" -> Match#vcard_search{lmiddle = make_val(LVal)}; "nick" -> Match#vcard_search{lnickname = make_val(LVal)}; "bday" -> Match#vcard_search{lbday = make_val(LVal)}; "ctry" -> Match#vcard_search{lctry = make_val(LVal)}; "locality" -> Match#vcard_search{llocality = make_val(LVal)}; "email" -> Match#vcard_search{lemail = make_val(LVal)}; "orgname" -> Match#vcard_search{lorgname = make_val(LVal)}; "orgunit" -> Match#vcard_search{lorgunit = make_val(LVal)}; _ -> Match end, filter_fields(Ds, NewMatch, LServer); filter_fields([_ | Ds], Match, LServer) -> filter_fields(Ds, Match, LServer). make_val(Val) -> case lists:suffix("*", Val) of true -> lists:sublist(Val, length(Val) - 1) ++ '_'; _ -> Val end. find_my_host(LServer) -> Parts = string:tokens(LServer, "."), find_my_host(Parts, ?MYHOSTS). find_my_host([], _Hosts) -> ?MYNAME; find_my_host([_ | Tail] = Parts, Hosts) -> Domain = parts_to_string(Parts), case lists:member(Domain, Hosts) of true -> Domain; false -> find_my_host(Tail, Hosts) end. parts_to_string(Parts) -> string:strip(lists:flatten(lists:map(fun(S) -> [S, $.] end, Parts)), right, $.). set_vcard_t(R, _) -> US = R#vcard.us, User = US, VCARD = R#vcard.vcard, FN = xml:get_path_s(VCARD, [{elem, "FN"}, cdata]), Family = xml:get_path_s(VCARD, [{elem, "N"}, {elem, "FAMILY"}, cdata]), Given = xml:get_path_s(VCARD, [{elem, "N"}, {elem, "GIVEN"}, cdata]), Middle = xml:get_path_s(VCARD, [{elem, "N"}, {elem, "MIDDLE"}, cdata]), Nickname = xml:get_path_s(VCARD, [{elem, "NICKNAME"}, cdata]), BDay = xml:get_path_s(VCARD, [{elem, "BDAY"}, cdata]), CTRY = xml:get_path_s(VCARD, [{elem, "ADR"}, {elem, "CTRY"}, cdata]), Locality = xml:get_path_s(VCARD, [{elem, "ADR"}, {elem, "LOCALITY"},cdata]), EMail = xml:get_path_s(VCARD, [{elem, "EMAIL"}, cdata]), OrgName = xml:get_path_s(VCARD, [{elem, "ORG"}, {elem, "ORGNAME"}, cdata]), OrgUnit = xml:get_path_s(VCARD, [{elem, "ORG"}, {elem, "ORGUNIT"}, cdata]), {LUser, _LServer} = US, LFN = string2lower(FN), LFamily = string2lower(Family), LGiven = string2lower(Given), LMiddle = string2lower(Middle), LNickname = string2lower(Nickname), LBDay = string2lower(BDay), LCTRY = string2lower(CTRY), LLocality = string2lower(Locality), LEMail = string2lower(EMail), LOrgName = string2lower(OrgName), LOrgUnit = string2lower(OrgUnit), if (LUser == error) or (LFN == error) or (LFamily == error) or (LGiven == error) or (LMiddle == error) or (LNickname == error) or (LBDay == error) or (LCTRY == error) or (LLocality == error) or (LEMail == error) or (LOrgName == error) or (LOrgUnit == error) -> {error, badarg}; true -> mnesia:write( #vcard_search{us = US, user = User, luser = LUser, fn = FN, lfn = LFN, family = Family, lfamily = LFamily, given = Given, lgiven = LGiven, middle = Middle, lmiddle = LMiddle, nickname = Nickname, lnickname = LNickname, bday = BDay, lbday = LBDay, ctry = CTRY, lctry = LCTRY, locality = Locality, llocality = LLocality, email = EMail, lemail = LEMail, orgname = OrgName, lorgname = LOrgName, orgunit = OrgUnit, lorgunit = LOrgUnit }) end. reindex_vcards() -> F = fun() -> mnesia:foldl(fun set_vcard_t/2, [], vcard) end, mnesia:transaction(F). remove_user(User, Server) -> LUser = jlib:nodeprep(User), LServer = jlib:nameprep(Server), US = {LUser, LServer}, F = fun() -> mnesia:delete({vcard, US}), mnesia:delete({vcard_search, US}) end, mnesia:transaction(F). update_tables() -> update_vcard_table(), update_vcard_search_table(). update_vcard_table() -> Fields = record_info(fields, vcard), case mnesia:table_info(vcard, attributes) of Fields -> ok; [user, vcard] -> ?INFO_MSG("Converting vcard table from " "{user, vcard} format", []), Host = ?MYNAME, {atomic, ok} = mnesia:create_table( mod_vcard_tmp_table, [{disc_only_copies, [node()]}, {type, bag}, {local_content, true}, {record_name, vcard}, {attributes, record_info(fields, vcard)}]), mnesia:transform_table(vcard, ignore, Fields), F1 = fun() -> mnesia:write_lock_table(mod_vcard_tmp_table), mnesia:foldl( fun(#vcard{us = U} = R, _) -> mnesia:dirty_write( mod_vcard_tmp_table, R#vcard{us = {U, Host}}) end, ok, vcard) end, mnesia:transaction(F1), mnesia:clear_table(vcard), F2 = fun() -> mnesia:write_lock_table(vcard), mnesia:foldl( fun(R, _) -> mnesia:dirty_write(R) end, ok, mod_vcard_tmp_table) end, mnesia:transaction(F2), mnesia:delete_table(mod_vcard_tmp_table); _ -> ?INFO_MSG("Recreating vcard table", []), mnesia:transform_table(vcard, ignore, Fields) end. update_vcard_search_table() -> Fields = record_info(fields, vcard_search), case mnesia:table_info(vcard_search, attributes) of Fields -> ok; [user, luser, fn, lfn, family, lfamily, given, lgiven, middle, lmiddle, nickname, lnickname, bday, lbday, ctry, lctry, locality, llocality, email, lemail, orgname, lorgname, orgunit, lorgunit] -> ?INFO_MSG("Converting vcard_search table from " "{user, luser, fn, lfn, family, lfamily, given, lgiven, middle, lmiddle, nickname, lnickname, bday, lbday, ctry, lctry, locality, llocality, email, lemail, orgname, lorgname, orgunit, lorgunit} format", []), Host = ?MYNAME, {atomic, ok} = mnesia:create_table( mod_vcard_tmp_table, [{disc_only_copies, [node()]}, {type, bag}, {local_content, true}, {record_name, vcard_search}, {attributes, record_info(fields, vcard_search)}]), F1 = fun() -> mnesia:write_lock_table(mod_vcard_tmp_table), mnesia:foldl( fun({vcard_search, User, LUser, FN, LFN, Family, LFamily, Given, LGiven, Middle, LMiddle, Nickname, LNickname, BDay, LBDay, CTRY, LCTRY, Locality, LLocality, EMail, LEMail, OrgName, LOrgName, OrgUnit, LOrgUnit }, _) -> mnesia:dirty_write( mod_vcard_tmp_table, #vcard_search{ us = {LUser, Host}, user = {User, Host}, luser = LUser, fn = FN, lfn = LFN, family = Family, lfamily = LFamily, given = Given, lgiven = LGiven, middle = Middle, lmiddle = LMiddle, nickname = Nickname, lnickname = LNickname, bday = BDay, lbday = LBDay, ctry = CTRY, lctry = LCTRY, locality = Locality, llocality = LLocality, email = EMail, lemail = LEMail, orgname = OrgName, lorgname = LOrgName, orgunit = OrgUnit, lorgunit = LOrgUnit }) end, ok, vcard_search) end, mnesia:transaction(F1), lists:foreach(fun(I) -> mnesia:del_table_index( vcard_search, element(I, {vcard_search, user, luser, fn, lfn, family, lfamily, given, lgiven, middle, lmiddle, nickname, lnickname, bday, lbday, ctry, lctry, locality, llocality, email, lemail, orgname, lorgname, orgunit, lorgunit})) end, mnesia:table_info(vcard_search, index)), mnesia:clear_table(vcard_search), mnesia:transform_table(vcard_search, ignore, Fields), F2 = fun() -> mnesia:write_lock_table(vcard_search), mnesia:foldl( fun(R, _) -> mnesia:dirty_write(R) end, ok, mod_vcard_tmp_table) end, mnesia:transaction(F2), mnesia:delete_table(mod_vcard_tmp_table); _ -> ?INFO_MSG("Recreating vcard_search table", []), mnesia:transform_table(vcard_search, ignore, Fields) end.
efc5e2becc19991276eda338241ecd1099fd6ad974fdc11aaf3ad5f0a0614a4d
lwhjp/racket-jni
env.rkt
#lang racket/base (require racket/class ffi/unsafe "error.rkt" "jni.rkt") (provide (all-defined-out) get-jni-env) (define local-jni-env (make-thread-cell #f #f)) (define current-jni-env (case-lambda [() (thread-cell-ref local-jni-env)] [(env) (unless (or (not env) (is-a? env JNIEnv<%>)) (raise-argument-error 'current-jni-env "instance of JNIEnv<%> or #f" env)) (thread-cell-set! local-jni-env env)])) (define (require-jni-env) (or (current-jni-env) (error "attempted to use JNI on an unattached thread"))) (define (with-jni-env env thunk) (define old-env #f) (dynamic-wind (λ () (set! old-env (current-jni-env)) (current-jni-env env)) thunk (λ () (current-jni-env old-env)))) (define-syntax-rule (let-jni-env env body0 body ...) (with-jni-env env (λ () body0 body ...))) ; scope (struct jni-scope (refs)) (define (make-jni-scope) (jni-scope (make-ephemeron-hasheq))) (define (jni-scope-register scope v proc) (hash-set! (jni-scope-refs scope) v proc)) (define (exit-jni-scope scope) (for ([proc (in-hash-values (jni-scope-refs scope))]) (proc))) (define global-jni-scope (make-jni-scope)) (define reference-cleanup-executor (make-will-executor)) (define local-jni-scope (make-thread-cell global-jni-scope #f)) (define (current-jni-scope) (or (thread-cell-ref local-jni-scope) (error "used outside of JNI scope"))) (define (with-jni-scope thunk) (define old-scope #f) (dynamic-wind (λ () (set! old-scope (thread-cell-ref local-jni-scope)) (thread-cell-set! local-jni-scope (make-jni-scope))) thunk (λ () (exit-jni-scope (thread-cell-ref local-jni-scope)) (thread-cell-set! local-jni-scope old-scope) (will-try-execute reference-cleanup-executor (void))))) (define (with-jni-frame capacity thunk) (define-values (old-ref new-ptr) (with-jni-scope (λ () (send (require-jni-env) PushLocalFrame capacity) (with-handlers ([exn:fail:jni:throw? (λ (e) (define old-throwable (exn:fail:jni:throw-object e)) (define new-throwable (send old-throwable clone-with-new-pointer (send (require-jni-env) PopLocalFrame (send old-throwable get-pointer)))) (raise (struct-copy exn:fail:jni:throw e [object new-throwable])))]) (define result (thunk)) (values result (send (require-jni-env) PopLocalFrame (and result (send result get-pointer)))))))) (and new-ptr (send old-ref clone-with-new-pointer new-ptr))) ; references (define reference<%> (interface () ->weak-reference ->local-reference ->global-reference delete get-pointer clone-with-new-pointer)) (define reference% (class* object% (reference<%>) (init-field _type) (init pointer) (super-new) (define ptr (box pointer)) (define (make-ref ref% p) (and p (new ref% [_type _type] [pointer (cast p _type)]))) (define/public (->weak-reference) (make-ref weak-reference% (send (require-jni-env) NewWeakGlobalRef (get-pointer)))) (define/public (->local-reference) (make-ref local-reference% (send (require-jni-env) NewLocalRef (get-pointer)))) (define/public (->global-reference) (make-ref global-reference% (send (require-jni-env) NewGlobalRef (get-pointer)))) (define/public (get-pointer) (or (unbox ptr) (error "invalid reference"))) (define/public (clone-with-new-pointer p) (new this% [_type _type] [pointer p])) (define/public (clear) (set-box! ptr #f)) (define/pubment (delete) (when (unbox ptr) (inner (void) delete) (clear))))) (define weak-reference% (class* reference% () (super-new) (define/override (->weak-reference) this) (define/augment (delete) (send (require-jni-env) DeleteWeakGlobalRef (super get-pointer))) (define/override (get-pointer) (error "access through weak reference")))) (define local-reference% (class* reference% () (inherit get-pointer) (super-new) (jni-scope-register (current-jni-scope) this (λ () (send this clear))) (define/override (->local-reference) this) (define/augment (delete) (send (require-jni-env) DeleteLocalRef (get-pointer))))) (define global-reference% (class* reference% () (inherit get-pointer) (super-new) (will-register reference-cleanup-executor this (λ () (send this delete))) (define/override (->global-reference) this) (define/augment (delete) (send (require-jni-env) DeleteGlobalRef (get-pointer)))))
null
https://raw.githubusercontent.com/lwhjp/racket-jni/ad76ef596d9e1702bffc9ab2141616b628f72b4d/private/env.rkt
racket
scope references
#lang racket/base (require racket/class ffi/unsafe "error.rkt" "jni.rkt") (provide (all-defined-out) get-jni-env) (define local-jni-env (make-thread-cell #f #f)) (define current-jni-env (case-lambda [() (thread-cell-ref local-jni-env)] [(env) (unless (or (not env) (is-a? env JNIEnv<%>)) (raise-argument-error 'current-jni-env "instance of JNIEnv<%> or #f" env)) (thread-cell-set! local-jni-env env)])) (define (require-jni-env) (or (current-jni-env) (error "attempted to use JNI on an unattached thread"))) (define (with-jni-env env thunk) (define old-env #f) (dynamic-wind (λ () (set! old-env (current-jni-env)) (current-jni-env env)) thunk (λ () (current-jni-env old-env)))) (define-syntax-rule (let-jni-env env body0 body ...) (with-jni-env env (λ () body0 body ...))) (struct jni-scope (refs)) (define (make-jni-scope) (jni-scope (make-ephemeron-hasheq))) (define (jni-scope-register scope v proc) (hash-set! (jni-scope-refs scope) v proc)) (define (exit-jni-scope scope) (for ([proc (in-hash-values (jni-scope-refs scope))]) (proc))) (define global-jni-scope (make-jni-scope)) (define reference-cleanup-executor (make-will-executor)) (define local-jni-scope (make-thread-cell global-jni-scope #f)) (define (current-jni-scope) (or (thread-cell-ref local-jni-scope) (error "used outside of JNI scope"))) (define (with-jni-scope thunk) (define old-scope #f) (dynamic-wind (λ () (set! old-scope (thread-cell-ref local-jni-scope)) (thread-cell-set! local-jni-scope (make-jni-scope))) thunk (λ () (exit-jni-scope (thread-cell-ref local-jni-scope)) (thread-cell-set! local-jni-scope old-scope) (will-try-execute reference-cleanup-executor (void))))) (define (with-jni-frame capacity thunk) (define-values (old-ref new-ptr) (with-jni-scope (λ () (send (require-jni-env) PushLocalFrame capacity) (with-handlers ([exn:fail:jni:throw? (λ (e) (define old-throwable (exn:fail:jni:throw-object e)) (define new-throwable (send old-throwable clone-with-new-pointer (send (require-jni-env) PopLocalFrame (send old-throwable get-pointer)))) (raise (struct-copy exn:fail:jni:throw e [object new-throwable])))]) (define result (thunk)) (values result (send (require-jni-env) PopLocalFrame (and result (send result get-pointer)))))))) (and new-ptr (send old-ref clone-with-new-pointer new-ptr))) (define reference<%> (interface () ->weak-reference ->local-reference ->global-reference delete get-pointer clone-with-new-pointer)) (define reference% (class* object% (reference<%>) (init-field _type) (init pointer) (super-new) (define ptr (box pointer)) (define (make-ref ref% p) (and p (new ref% [_type _type] [pointer (cast p _type)]))) (define/public (->weak-reference) (make-ref weak-reference% (send (require-jni-env) NewWeakGlobalRef (get-pointer)))) (define/public (->local-reference) (make-ref local-reference% (send (require-jni-env) NewLocalRef (get-pointer)))) (define/public (->global-reference) (make-ref global-reference% (send (require-jni-env) NewGlobalRef (get-pointer)))) (define/public (get-pointer) (or (unbox ptr) (error "invalid reference"))) (define/public (clone-with-new-pointer p) (new this% [_type _type] [pointer p])) (define/public (clear) (set-box! ptr #f)) (define/pubment (delete) (when (unbox ptr) (inner (void) delete) (clear))))) (define weak-reference% (class* reference% () (super-new) (define/override (->weak-reference) this) (define/augment (delete) (send (require-jni-env) DeleteWeakGlobalRef (super get-pointer))) (define/override (get-pointer) (error "access through weak reference")))) (define local-reference% (class* reference% () (inherit get-pointer) (super-new) (jni-scope-register (current-jni-scope) this (λ () (send this clear))) (define/override (->local-reference) this) (define/augment (delete) (send (require-jni-env) DeleteLocalRef (get-pointer))))) (define global-reference% (class* reference% () (inherit get-pointer) (super-new) (will-register reference-cleanup-executor this (λ () (send this delete))) (define/override (->global-reference) this) (define/augment (delete) (send (require-jni-env) DeleteGlobalRef (get-pointer)))))
bbc535ed01128e5b81a357e2fe410f53fe6d9801a0b57dfcabbe868e4385cb54
massung/r-cade
derby.rkt
#lang racket (require r-cade) (require racket/random) ;; ---------------------------------------------------- (define horse-sprite #((#x001c #x003e #x007e #x7ff0 #x8fe0 #x0fe0 #x1ff8 #x2836 #xc809 #x1008 #x2000) (#x000c #x001e #x003f #x3ff2 #xcfe0 #x0fe0 #x1fe0 #x1820 #x2850 #xc890 #x1110) (#x0006 #x000f #x001f #x1ff8 #xeff0 #x0fe0 #x1fe0 #x2860 #x1850 #x0de0 #x0840) (#x000c #x001e #x003f #x9ff2 #x6fe0 #x0fe0 #x0ff0 #x1c30 #x1418 #x22e4 #x2100))) ;; ---------------------------------------------------- (define jockey-sprite '(#x06 #x06 #x7c #xf6 #xf0 #x38 #x08 #x10 #x38)) ;; ---------------------------------------------------- (define rail-sprite #((#xff #xff #x18 #x18 #x18 #x18 #x18) (#xff #xff) (#xff #xff) (#xff #xff))) ;; ---------------------------------------------------- (define bush-sprite '(#x34 #x7e #xff #xff #x7e)) ;; ---------------------------------------------------- (define berries-sprite #((#x00 #x20 #x04 #x10) (#x00 #x14 #x40 #x08))) ;; ---------------------------------------------------- (define ribbon-sprite '(#x3c #x7e #xff #xff #xff #xff #x7e #x3c #x18 #x3c #x3c #x66 #x66 #x66 #x66)) ;; ---------------------------------------------------- (define trumpet (synth (sin 1) (triangle-wave 0.2) (noise-wave 0.15))) ;; ---------------------------------------------------- (define call-to-post (music "A3---D4---F---A---A-A--F---F-F---D---F---D---A3---------------" #:tempo 900 #:voice (voice trumpet (envelope 0 1 0.7 0.7 0.2 0.8 0.2 0.8 0)))) ;; ---------------------------------------------------- (define clop-sound (tone 50 0.05 (voice square-wave (envelope 0 0.2 0.15 0)))) ;; ---------------------------------------------------- (define gun-sound (tone 600 1 (voice (synth (triangle-wave 0.7) (noise-wave 0.4)) z-envelope))) ;; ---------------------------------------------------- (define positions #("1st" "2nd" "3rd" "4th" "5th" "6th" "7th" "8th" "9th")) ;; ---------------------------------------------------- (struct horse [color jockey lane aggro min-stamina (time #:mutable) (stamina #:mutable) (recover #:mutable) (frame #:mutable) (x #:mutable) (vel #:mutable) (fps #:mutable) (position #:mutable)]) ;; ---------------------------------------------------- (struct bush [x berries color]) ;; ---------------------------------------------------- (define player #f) (define recover-timer 0) (define horses null) (define bushes null) (define start-x -36) (define start-vel 16) (define start-fps 10) (define finish-line 640) (define score 0) (define ribbons null) (define race-started #f) ;; ---------------------------------------------------- (define action-btn btn-z) ;; ---------------------------------------------------- (define (track-offset) (max (inexact->exact (floor (- (* (horse-x player) 4) 32))) 0)) ;; ---------------------------------------------------- (define (railing-offset) (- (remainder (track-offset) 32))) ;; ---------------------------------------------------- (define (draw-railing) (for ([segment (range (+ (quotient (width) 32) 2))]) (for ([sprite rail-sprite] [offset (in-naturals)]) (let ([x (+ (railing-offset) (* segment 32) (* offset 8))]) (color (if (odd? offset) 8 7)) (draw x 19 sprite) (draw x 103 sprite))))) ;; ---------------------------------------------------- (define (draw-finish-line) (let ([x (+ (- (* finish-line 4) (track-offset)) 4)]) (color 8) (rect x 26 0 77))) ;; ---------------------------------------------------- (define (draw-bushes) (for ([b bushes]) (let ([x (+ (- (* (bush-x b) 4) (track-offset)) 4)]) (color 11) (draw x 12 bush-sprite) (color (bush-color b)) (draw x 12 (bush-berries b))))) ;; ---------------------------------------------------- (define (draw-track) (color 4) (rect 0 0 (width) 8 #:fill #t) (color 15) (rect 0 7 (width) 9 #:fill #t) ; back grass (color 3) (rect 0 16 (width) 4 #:fill #t) ; railing lane (color 11) (rect 0 20 (width) 8 #:fill #t) ; racing lanes (for ([lane (range 9)]) (let ([y (+ 28 (* lane 8))]) (color (if (odd? lane) 11 3)) (rect 0 y (width) 8 #:fill #t))) ; railing lane (color 11) (rect 0 100 (width) 8 #:fill #t) ; front grass (color 3) (rect 0 108 (width) 4 #:fill #t)) ;; ---------------------------------------------------- (define (horse-anim-frame h) (bitwise-and (inexact->exact (floor (horse-frame h))) 3)) ;; ---------------------------------------------------- (define (draw-horse h) (let* ([frame (horse-anim-frame h)] [y (+ 22 (* (horse-lane h) 8))] [x (cond [(< (horse-x h) 32) (horse-x h)] [(eq? h player) 32] [else (+ 32 (- (horse-x h) (horse-x player)))])]) (color (horse-color h)) (draw-ex x y (vector-ref horse-sprite frame)) (color (horse-jockey h)) (draw (+ x 5) (- y 3) jockey-sprite))) ;; ---------------------------------------------------- (define (draw-horses) (for ([h horses]) (draw-horse h)) (draw-horse player)) ;; ---------------------------------------------------- (define (draw-stamina) (let ([stamina (horse-stamina player)]) (color 7) (text 1 1 "Stamina:") (rect 33 1 stamina 5 #:fill #t) (color 8) (rect (+ stamina 33) 1 (- 100 stamina) 5 #:fill #t))) ;; ---------------------------------------------------- (define (draw-place) (color 7) (text (- (width) 12) 1 (if (not race-started) "-" (vector-ref positions (horse-position player))))) ;; ---------------------------------------------------- (define (use-crop h) (let ([ds (/ (horse-vel h) 5)]) (set-horse-stamina! h (max (- (horse-stamina h) ds) 0)) ( / ( - 100 ( horse - stamina h ) ) 50 ) ) ) ; reset timer (set-horse-time! h 0.0) ; increase velocity of player's horse (let ([m (/ (min (horse-stamina h) 50) 50)]) (set-horse-vel! h (+ (horse-vel h) (* (frametime) 25 m))) (set-horse-fps! h (+ (horse-fps h) (* (frametime) 20 m))))) ;; ---------------------------------------------------- (define (recover-stamina h) (if (> (horse-recover h) 0) (set-horse-recover! h (max (- (horse-recover h) (frametime)) 0.0)) (set-horse-stamina! h (min (+ (horse-stamina h) (* (frametime) 50)) 100)))) ;; ---------------------------------------------------- (define (place-horses) (let ([order (sort (cons player horses) > #:key horse-x)]) (for ([h (cons player horses)]) (unless (> (+ (horse-x h) 16) finish-line) (set-horse-position! h (index-of order h eq?)))))) ;; ---------------------------------------------------- (define (advance-horse h) (set-horse-x! h (+ (horse-x h) (* (horse-vel h) (frametime)))) (set-horse-frame! h (+ (horse-frame h) (* (horse-fps h) (frametime)))) (set-horse-time! h (+ (horse-time h) (frametime))) ; slow down horse (let ([decay (* (frametime) (if (eq? h player) 0.75 (- 0.90 (* (random) 0.2) (* (length ribbons) 0.01))))]) (set-horse-fps! h (max (- (horse-fps h) decay) start-fps)) (set-horse-vel! h (max (- (horse-vel h) decay) start-vel)))) ;; ---------------------------------------------------- (define (advance-horses) (for ([h horses]) (advance-horse h) ; randomly use the crop (when (> (horse-x h) 32) (let ([r (horse-recover h)] [m (horse-min-stamina h)] [a (horse-aggro h)]) (if (or (and (> r 0.0) (> (horse-stamina h) m) (> (horse-time h) a)) (and (= r 0.0) (> (horse-stamina h) (- 100 m)))) (use-crop h) (recover-stamina h))))) (advance-horse player)) ;; ---------------------------------------------------- (define (spawn-horse color jockey lane) (let* ([level (+ (length ribbons) 1)] [aggro (* 1/60 (+ 4 (* (random) 3)))] [min-sta (apply min (for/list ([_ (range level)]) (* (random) 100)))]) (horse color jockey lane aggro min-sta 0.0 100 0.0 0 start-x start-vel start-fps 0))) ;; ---------------------------------------------------- (define (spawn-bushes [offset (random 10)]) (if (> offset (+ finish-line (width))) null (let ([berries (random-ref berries-sprite)]) (cons (bush offset berries (vector-ref #(8 12 14 10) (random 4))) (spawn-bushes (+ offset (random 10) 4)))))) ;; ---------------------------------------------------- (define (next-race) (cls) (play-music call-to-post #:loop #f) ; ready the next level... (set! race-started #f) (set! player (spawn-horse 9 10 8)) (set! bushes (spawn-bushes)) (set! horses (for/list ([lane (range 8)] [color (list 1 4 6 8 10 12 13 14)] [jockey (list 12 9 1 14 0 5 7 2)]) (spawn-horse color jockey lane)))) ;; ---------------------------------------------------- (define (ribbon-color pos) (vector-ref #(12 8 10 7 14 11) pos)) ;; ---------------------------------------------------- (define (award-ribbon) (cls) ; draw past ribbons at bottom (for ([r ribbons] [n (in-naturals)]) (let-values ([(y x) (quotient/remainder n 14)]) (color (ribbon-color r)) (draw (+ 6 (* x 12)) (+ 48 (* y 18)) ribbon-sprite))) ; draw the ribbon and award $$ (let ([pos (horse-position player)]) (if (< pos 6) (let ([winnings (vector-ref #(1000 500 400 250 100 50) pos)]) (color (ribbon-color pos)) (draw (- (/ (width) 2) 4) 10 ribbon-sprite) ; award $$ based on position (set! score (+ score winnings)) (set! ribbons (cons pos ribbons)) ; show current winnings (color 7) (text 50 30 (format "You won $~a !!" winnings)) (text 50 38 (format "Total winnings: $~a" score)) (text 40 104 "Press START for next race...") ; wait to advance to the next race (wait btn-start) (next-race)) ; game over (begin (color 7) (text 6 10 "GAME OVER") (text 6 18 "Better luck next time!") (text 6 34 (format "Final winnings: $~a" score)) (text 71 104 "My ribbons") (wait) (quit))))) ;; ---------------------------------------------------- (define (game-loop) (draw-track) (draw-bushes) (draw-railing) (draw-finish-line) (draw-horses) (draw-stamina) (draw-place) ; advance horses (advance-horses) (place-horses) ; hoof sounds (when (= (horse-anim-frame player) 1) (play-sound clop-sound)) ; gun sound (unless race-started (when (> (horse-x player) 32) (play-sound gun-sound) (set! race-started #t))) ; player controls (when (> finish-line (horse-x player) 32) (if (action-btn) (begin (use-crop player) (set! action-btn (if (eq? action-btn btn-z) btn-x btn-z))) (recover-stamina player))) ; end of race? (when (> (horse-x player) (+ finish-line 100)) (award-ribbon)) ; quit game? (when (btn-quit) (quit))) ;; ---------------------------------------------------- (define (play) (run game-loop 180 112 #:init next-race #:scale 3 #:title "R-cade: Derby")) ;; ---------------------------------------------------- (module+ main (play))
null
https://raw.githubusercontent.com/massung/r-cade/0cce22885aad28234d3f6e1d88568cdc16daf3e6/examples/derby.rkt
racket
---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- back grass railing lane racing lanes railing lane front grass ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- reset timer increase velocity of player's horse ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- slow down horse ---------------------------------------------------- randomly use the crop ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ready the next level... ---------------------------------------------------- ---------------------------------------------------- draw past ribbons at bottom draw the ribbon and award $$ award $$ based on position show current winnings wait to advance to the next race game over ---------------------------------------------------- advance horses hoof sounds gun sound player controls end of race? quit game? ---------------------------------------------------- ----------------------------------------------------
#lang racket (require r-cade) (require racket/random) (define horse-sprite #((#x001c #x003e #x007e #x7ff0 #x8fe0 #x0fe0 #x1ff8 #x2836 #xc809 #x1008 #x2000) (#x000c #x001e #x003f #x3ff2 #xcfe0 #x0fe0 #x1fe0 #x1820 #x2850 #xc890 #x1110) (#x0006 #x000f #x001f #x1ff8 #xeff0 #x0fe0 #x1fe0 #x2860 #x1850 #x0de0 #x0840) (#x000c #x001e #x003f #x9ff2 #x6fe0 #x0fe0 #x0ff0 #x1c30 #x1418 #x22e4 #x2100))) (define jockey-sprite '(#x06 #x06 #x7c #xf6 #xf0 #x38 #x08 #x10 #x38)) (define rail-sprite #((#xff #xff #x18 #x18 #x18 #x18 #x18) (#xff #xff) (#xff #xff) (#xff #xff))) (define bush-sprite '(#x34 #x7e #xff #xff #x7e)) (define berries-sprite #((#x00 #x20 #x04 #x10) (#x00 #x14 #x40 #x08))) (define ribbon-sprite '(#x3c #x7e #xff #xff #xff #xff #x7e #x3c #x18 #x3c #x3c #x66 #x66 #x66 #x66)) (define trumpet (synth (sin 1) (triangle-wave 0.2) (noise-wave 0.15))) (define call-to-post (music "A3---D4---F---A---A-A--F---F-F---D---F---D---A3---------------" #:tempo 900 #:voice (voice trumpet (envelope 0 1 0.7 0.7 0.2 0.8 0.2 0.8 0)))) (define clop-sound (tone 50 0.05 (voice square-wave (envelope 0 0.2 0.15 0)))) (define gun-sound (tone 600 1 (voice (synth (triangle-wave 0.7) (noise-wave 0.4)) z-envelope))) (define positions #("1st" "2nd" "3rd" "4th" "5th" "6th" "7th" "8th" "9th")) (struct horse [color jockey lane aggro min-stamina (time #:mutable) (stamina #:mutable) (recover #:mutable) (frame #:mutable) (x #:mutable) (vel #:mutable) (fps #:mutable) (position #:mutable)]) (struct bush [x berries color]) (define player #f) (define recover-timer 0) (define horses null) (define bushes null) (define start-x -36) (define start-vel 16) (define start-fps 10) (define finish-line 640) (define score 0) (define ribbons null) (define race-started #f) (define action-btn btn-z) (define (track-offset) (max (inexact->exact (floor (- (* (horse-x player) 4) 32))) 0)) (define (railing-offset) (- (remainder (track-offset) 32))) (define (draw-railing) (for ([segment (range (+ (quotient (width) 32) 2))]) (for ([sprite rail-sprite] [offset (in-naturals)]) (let ([x (+ (railing-offset) (* segment 32) (* offset 8))]) (color (if (odd? offset) 8 7)) (draw x 19 sprite) (draw x 103 sprite))))) (define (draw-finish-line) (let ([x (+ (- (* finish-line 4) (track-offset)) 4)]) (color 8) (rect x 26 0 77))) (define (draw-bushes) (for ([b bushes]) (let ([x (+ (- (* (bush-x b) 4) (track-offset)) 4)]) (color 11) (draw x 12 bush-sprite) (color (bush-color b)) (draw x 12 (bush-berries b))))) (define (draw-track) (color 4) (rect 0 0 (width) 8 #:fill #t) (color 15) (rect 0 7 (width) 9 #:fill #t) (color 3) (rect 0 16 (width) 4 #:fill #t) (color 11) (rect 0 20 (width) 8 #:fill #t) (for ([lane (range 9)]) (let ([y (+ 28 (* lane 8))]) (color (if (odd? lane) 11 3)) (rect 0 y (width) 8 #:fill #t))) (color 11) (rect 0 100 (width) 8 #:fill #t) (color 3) (rect 0 108 (width) 4 #:fill #t)) (define (horse-anim-frame h) (bitwise-and (inexact->exact (floor (horse-frame h))) 3)) (define (draw-horse h) (let* ([frame (horse-anim-frame h)] [y (+ 22 (* (horse-lane h) 8))] [x (cond [(< (horse-x h) 32) (horse-x h)] [(eq? h player) 32] [else (+ 32 (- (horse-x h) (horse-x player)))])]) (color (horse-color h)) (draw-ex x y (vector-ref horse-sprite frame)) (color (horse-jockey h)) (draw (+ x 5) (- y 3) jockey-sprite))) (define (draw-horses) (for ([h horses]) (draw-horse h)) (draw-horse player)) (define (draw-stamina) (let ([stamina (horse-stamina player)]) (color 7) (text 1 1 "Stamina:") (rect 33 1 stamina 5 #:fill #t) (color 8) (rect (+ stamina 33) 1 (- 100 stamina) 5 #:fill #t))) (define (draw-place) (color 7) (text (- (width) 12) 1 (if (not race-started) "-" (vector-ref positions (horse-position player))))) (define (use-crop h) (let ([ds (/ (horse-vel h) 5)]) (set-horse-stamina! h (max (- (horse-stamina h) ds) 0)) ( / ( - 100 ( horse - stamina h ) ) 50 ) ) ) (set-horse-time! h 0.0) (let ([m (/ (min (horse-stamina h) 50) 50)]) (set-horse-vel! h (+ (horse-vel h) (* (frametime) 25 m))) (set-horse-fps! h (+ (horse-fps h) (* (frametime) 20 m))))) (define (recover-stamina h) (if (> (horse-recover h) 0) (set-horse-recover! h (max (- (horse-recover h) (frametime)) 0.0)) (set-horse-stamina! h (min (+ (horse-stamina h) (* (frametime) 50)) 100)))) (define (place-horses) (let ([order (sort (cons player horses) > #:key horse-x)]) (for ([h (cons player horses)]) (unless (> (+ (horse-x h) 16) finish-line) (set-horse-position! h (index-of order h eq?)))))) (define (advance-horse h) (set-horse-x! h (+ (horse-x h) (* (horse-vel h) (frametime)))) (set-horse-frame! h (+ (horse-frame h) (* (horse-fps h) (frametime)))) (set-horse-time! h (+ (horse-time h) (frametime))) (let ([decay (* (frametime) (if (eq? h player) 0.75 (- 0.90 (* (random) 0.2) (* (length ribbons) 0.01))))]) (set-horse-fps! h (max (- (horse-fps h) decay) start-fps)) (set-horse-vel! h (max (- (horse-vel h) decay) start-vel)))) (define (advance-horses) (for ([h horses]) (advance-horse h) (when (> (horse-x h) 32) (let ([r (horse-recover h)] [m (horse-min-stamina h)] [a (horse-aggro h)]) (if (or (and (> r 0.0) (> (horse-stamina h) m) (> (horse-time h) a)) (and (= r 0.0) (> (horse-stamina h) (- 100 m)))) (use-crop h) (recover-stamina h))))) (advance-horse player)) (define (spawn-horse color jockey lane) (let* ([level (+ (length ribbons) 1)] [aggro (* 1/60 (+ 4 (* (random) 3)))] [min-sta (apply min (for/list ([_ (range level)]) (* (random) 100)))]) (horse color jockey lane aggro min-sta 0.0 100 0.0 0 start-x start-vel start-fps 0))) (define (spawn-bushes [offset (random 10)]) (if (> offset (+ finish-line (width))) null (let ([berries (random-ref berries-sprite)]) (cons (bush offset berries (vector-ref #(8 12 14 10) (random 4))) (spawn-bushes (+ offset (random 10) 4)))))) (define (next-race) (cls) (play-music call-to-post #:loop #f) (set! race-started #f) (set! player (spawn-horse 9 10 8)) (set! bushes (spawn-bushes)) (set! horses (for/list ([lane (range 8)] [color (list 1 4 6 8 10 12 13 14)] [jockey (list 12 9 1 14 0 5 7 2)]) (spawn-horse color jockey lane)))) (define (ribbon-color pos) (vector-ref #(12 8 10 7 14 11) pos)) (define (award-ribbon) (cls) (for ([r ribbons] [n (in-naturals)]) (let-values ([(y x) (quotient/remainder n 14)]) (color (ribbon-color r)) (draw (+ 6 (* x 12)) (+ 48 (* y 18)) ribbon-sprite))) (let ([pos (horse-position player)]) (if (< pos 6) (let ([winnings (vector-ref #(1000 500 400 250 100 50) pos)]) (color (ribbon-color pos)) (draw (- (/ (width) 2) 4) 10 ribbon-sprite) (set! score (+ score winnings)) (set! ribbons (cons pos ribbons)) (color 7) (text 50 30 (format "You won $~a !!" winnings)) (text 50 38 (format "Total winnings: $~a" score)) (text 40 104 "Press START for next race...") (wait btn-start) (next-race)) (begin (color 7) (text 6 10 "GAME OVER") (text 6 18 "Better luck next time!") (text 6 34 (format "Final winnings: $~a" score)) (text 71 104 "My ribbons") (wait) (quit))))) (define (game-loop) (draw-track) (draw-bushes) (draw-railing) (draw-finish-line) (draw-horses) (draw-stamina) (draw-place) (advance-horses) (place-horses) (when (= (horse-anim-frame player) 1) (play-sound clop-sound)) (unless race-started (when (> (horse-x player) 32) (play-sound gun-sound) (set! race-started #t))) (when (> finish-line (horse-x player) 32) (if (action-btn) (begin (use-crop player) (set! action-btn (if (eq? action-btn btn-z) btn-x btn-z))) (recover-stamina player))) (when (> (horse-x player) (+ finish-line 100)) (award-ribbon)) (when (btn-quit) (quit))) (define (play) (run game-loop 180 112 #:init next-race #:scale 3 #:title "R-cade: Derby")) (module+ main (play))
be90df97e40fa1dee30c70f388a96df1d946d200c03e90f5fce349ed4c8f9c5d
Kappa-Dev/KappaTools
counters_domain_type.mli
type comparison_op = LTEQ | LT | GT | GTEQ | EQ type restriction = { tests: (Occu1.trans * comparison_op * int) list ; invertible_assignments : (Occu1.trans * int) list ; non_invertible_assignments : (Occu1.trans * int) list ; } val empty_restriction: restriction type static = { counters: Ckappa_sig.AgentSite_map_and_set.Set.t ; packs: Ckappa_sig.Site_map_and_set.Set.t Ckappa_sig.Site_type_nearly_Inf_Int_storage_Imperatif.t Ckappa_sig.Agent_type_nearly_Inf_Int_storage_Imperatif.t ; backward_pointers: Ckappa_sig.Site_map_and_set.Set.t Ckappa_sig.Agent_type_site_nearly_Inf_Int_Int_storage_Imperatif_Imperatif.t ; rule_restrictions: restriction Ckappa_sig.Site_type_quick_nearly_Inf_Int_storage_Imperatif.t Ckappa_sig.Agent_id_nearly_Inf_Int_storage_Imperatif.t Ckappa_sig.Rule_id_quick_nearly_Inf_Int_storage_Imperatif.t ; rule_creation: (Occu1.trans * int) list list Ckappa_sig.Agent_type_site_quick_nearly_Inf_Int_Int_storage_Imperatif_Imperatif.t Ckappa_sig.Rule_id_quick_nearly_Inf_Int_storage_Imperatif.t; } val print_restriction: Remanent_parameters_sig.parameters -> Cckappa_sig.kappa_handler -> Exception.method_handler -> restriction -> Exception.method_handler val print_agent_restriction: Remanent_parameters_sig.parameters -> Cckappa_sig.kappa_handler -> Exception.method_handler -> restriction Ckappa_sig.Site_type_quick_nearly_Inf_Int_storage_Imperatif.t -> Exception.method_handler val print_rule_restriction: Remanent_parameters_sig.parameters -> Cckappa_sig.kappa_handler -> Exception.method_handler -> restriction Ckappa_sig.Site_type_quick_nearly_Inf_Int_storage_Imperatif.t Ckappa_sig.Agent_id_nearly_Inf_Int_storage_Imperatif.t-> Exception.method_handler val print_restrictions: Remanent_parameters_sig.parameters -> Cckappa_sig.kappa_handler -> Exception.method_handler -> restriction Ckappa_sig.Site_type_quick_nearly_Inf_Int_storage_Imperatif.t Ckappa_sig.Agent_id_nearly_Inf_Int_storage_Imperatif.t Ckappa_sig.Rule_id_quick_nearly_Inf_Int_storage_Imperatif.t -> Exception.method_handler val print: Remanent_parameters_sig.parameters -> Cckappa_sig.kappa_handler -> Exception.method_handler -> static -> Exception.method_handler
null
https://raw.githubusercontent.com/Kappa-Dev/KappaTools/eef2337e8688018eda47ccc838aea809cae68de7/core/KaSa_rep/abstract_domains/numerical_domains/counters_domain_type.mli
ocaml
type comparison_op = LTEQ | LT | GT | GTEQ | EQ type restriction = { tests: (Occu1.trans * comparison_op * int) list ; invertible_assignments : (Occu1.trans * int) list ; non_invertible_assignments : (Occu1.trans * int) list ; } val empty_restriction: restriction type static = { counters: Ckappa_sig.AgentSite_map_and_set.Set.t ; packs: Ckappa_sig.Site_map_and_set.Set.t Ckappa_sig.Site_type_nearly_Inf_Int_storage_Imperatif.t Ckappa_sig.Agent_type_nearly_Inf_Int_storage_Imperatif.t ; backward_pointers: Ckappa_sig.Site_map_and_set.Set.t Ckappa_sig.Agent_type_site_nearly_Inf_Int_Int_storage_Imperatif_Imperatif.t ; rule_restrictions: restriction Ckappa_sig.Site_type_quick_nearly_Inf_Int_storage_Imperatif.t Ckappa_sig.Agent_id_nearly_Inf_Int_storage_Imperatif.t Ckappa_sig.Rule_id_quick_nearly_Inf_Int_storage_Imperatif.t ; rule_creation: (Occu1.trans * int) list list Ckappa_sig.Agent_type_site_quick_nearly_Inf_Int_Int_storage_Imperatif_Imperatif.t Ckappa_sig.Rule_id_quick_nearly_Inf_Int_storage_Imperatif.t; } val print_restriction: Remanent_parameters_sig.parameters -> Cckappa_sig.kappa_handler -> Exception.method_handler -> restriction -> Exception.method_handler val print_agent_restriction: Remanent_parameters_sig.parameters -> Cckappa_sig.kappa_handler -> Exception.method_handler -> restriction Ckappa_sig.Site_type_quick_nearly_Inf_Int_storage_Imperatif.t -> Exception.method_handler val print_rule_restriction: Remanent_parameters_sig.parameters -> Cckappa_sig.kappa_handler -> Exception.method_handler -> restriction Ckappa_sig.Site_type_quick_nearly_Inf_Int_storage_Imperatif.t Ckappa_sig.Agent_id_nearly_Inf_Int_storage_Imperatif.t-> Exception.method_handler val print_restrictions: Remanent_parameters_sig.parameters -> Cckappa_sig.kappa_handler -> Exception.method_handler -> restriction Ckappa_sig.Site_type_quick_nearly_Inf_Int_storage_Imperatif.t Ckappa_sig.Agent_id_nearly_Inf_Int_storage_Imperatif.t Ckappa_sig.Rule_id_quick_nearly_Inf_Int_storage_Imperatif.t -> Exception.method_handler val print: Remanent_parameters_sig.parameters -> Cckappa_sig.kappa_handler -> Exception.method_handler -> static -> Exception.method_handler
9bab23a6269f26ab544efd9f4497829ce2ce395ee7b7fa44c357be1591068d9b
1Jajen1/Brokkr
Handler.hs
module Network.Handler ( handleConnection ) where import Data.IORef import Chunk.Position import IO.Chunkloading import Control.Concurrent (threadDelay) import Control.Concurrent.MVar import Control.Exception import qualified Chronos import qualified Control.Concurrent.Async as Async import Control.Monad import Control.Monad.IO.Class import qualified Data.ByteString.Lazy as LBS import Data.Text (Text) import Util.UUID import qualified Data.Vector as V import Dimension (Dimension, DimensionType(Overworld)) import qualified Dimension import Network.Connection (Connection, Command(..)) import qualified Network.Connection as Conn import Network.Monad import Network.Protocol import qualified Network.Packet.Client.Login as Client.Login import qualified Network.Packet.Client.Play as Client.Play import qualified Network.Packet.Server.Handshake as Server.Handshake import qualified Network.Packet.Server.Login as Server.Login import qualified Network.Packet.Server.Play as Server.Play import Network.Packet.Client.Play.ChunkData (mkChunkData) import Network.Util.Builder import Util.Binary import Data.Coerce import Control.Monad.Trans.Control import Util.Position import Util.Rotation import qualified Data.Text as T import qualified Network.Packet.Client.Play as C import qualified Network.Packet.Client.Play.Login as C import Registry.Biome import Registry.Dimension import Client.GameMode import Block.Position import qualified Data.Bitfield as Bitfield import qualified Server as Hecs import qualified Hecs import Hecs.Entity.Internal (Entity(..)) -- handleConnection :: Network () handleConnection = do LoginRes uid uName prot <- readPacket (Protocol NoCompression NoEncryption) >>= \case Server.Handshake.Handshake _ _ _ Server.Handshake.Status -> handleStatus Server.Handshake.Handshake _ _ _ Server.Handshake.Login -> handleLogin handlePlay uid uName prot handleStatus :: Network a handleStatus = closeConnection handleLogin :: Network LoginResult handleLogin = do uName <- readPacket (Protocol NoCompression NoEncryption) >>= \case Server.Login.LoginStart uName _ -> pure uName TODO Check for other packets and throw InvalidProtocol on those TODO generate proper uid let uid = nil TODO Have a config check if we use compression and what the threshold is let thresh = 512 sendPackets (Protocol NoCompression NoEncryption) 10 [Client.Login.SetCompression thresh] let finalProtocol = Protocol (Threshold thresh) NoEncryption sendPackets finalProtocol 64 [Client.Login.LoginSuccess uid uName] pure $ LoginRes uid uName finalProtocol data LoginResult = LoginRes UUID Text Protocol handlePlay :: UUID -> Text -> Protocol -> Network a handlePlay _playerUUID _playerName finalProtocol = do !conn <- liftIO Conn.new let send = go where go = do _ <- liftBaseWith $ \runInBase -> Conn.flushPackets conn $ \ps -> do runInBase . sendBytes . LBS.fromChunks $! fmap (\(Conn.SendPacket szHint packet) -> let !bs = toStrictSizePrefixedByteString finalProtocol szHint $ put packet in bs) $ V.toList ps go keepAlive = go where TODO make a config option so testing is a little easier delay = fromIntegral $ ((Chronos.getTimespan Chronos.second) * 20) `div` 1000 go = do threadDelay delay t' <- Chronos.getTime <$> Chronos.now Conn.sendKeepAlive conn t' go _ <- liftBaseWith $ \runInBase -> -- TODO Label these threads Async.withAsync (runInBase send) $ \sendAs -> Async.withAsync keepAlive $ \keepAliveAs -> do -- If any of the linked threads crash, we must also crash since the connection will no longer work Async.link sendAs Async.link keepAliveAs -- Actually create the player entity, from that point on the connection is visible globally bracket (do bracketOnError (runInBase $ Hecs.newEntity) (\eidSt -> runInBase $ restoreM eidSt >>= Hecs.freeEntity) -- TODO Log (\eidSt -> runInBase $ restoreM eidSt >>= \eid -> joinPlayer conn eid >> pure eid) TODO $ \clientSt -> runInBase $ restoreM clientSt >>= \_client -> do -- packet loop let handlePlayPackets = do readPacket finalProtocol >>= handlePacket conn handlePlayPackets handlePlayPackets -- The packet loop in the bracket already diverges, but if for whatever reason we end up here, just kill the connection closeConnection joinPlayer :: Connection -> Hecs.EntityId -> Network () joinPlayer conn eid = do Create / Load player data -- SYNC Because we need to know where to join the player -- TODO Move let initialPosition = Position 0 150 0 initialRotation = Rotation 0 0 initialVelocity = Position 0 0 0 initialWorld <- Hecs.get @Dimension (coerce $ Hecs.getComponentId @Dimension.Overworld) pure (error "World singleton missing") Sync with PlayerMovement until I store it as a component let loginData = C.LoginData (fromIntegral . Bitfield.get @"eid" $ Hecs.unEntityId eid) (C.IsHardcore False) Creative C.Undefined (V.fromList ["minecraft:overworld", "minecraft:nether", "minecraft:the_end"]) (C.RegistryCodec dimRegistry biomeRegistry chatRegistry) TODO proper type "minecraft:overworld" (C.HashedSeed 0) (C.MaxPlayers 5) (C.ViewDistance viewDistance) (C.SimulationDistance 8) (C.ReducedDebugInfo False) (C.EnableRespawnScreen False) (C.IsDebug False) (C.IsFlat False) C.NoDeathLocation dimRegistry = C.DimensionTypeRegistry "minecraft:dimension_type" (V.fromList [ C.DimensionRegistryEntry "minecraft:overworld" 0 overworld , C.DimensionRegistryEntry "minecraft:nether" 1 nether , C.DimensionRegistryEntry "minecraft:the_end" 2 end ] ) biomeRegistry = C.BiomeRegistry "minecraft:worldgen/biome" . V.fromList $ do (bid, (name, settings)) <- zip [0..] all_biome_settings return $ C.BiomeRegistryEntry ("minecraft:" <> T.pack name) bid settings chatRegistry = C.ChatRegistry "minecraft:chat_type" mempty liftIO . Conn.sendPacket conn $ Conn.SendPacket 65536 (C.Login loginData) liftIO . Conn.sendPacket conn $ Conn.SendPacket 10 (C.SetDefaultSpawnPosition (BlockPos 0 130 0) 0) -- Preload chunks for this player -- SYNC Because we don't want to wait for this on the main thread and this will join the -- player with chunks loaded and not in some void chunkloading <- Hecs.getSingleton @Chunkloading let chunksToLoad = [ChunkPos x z | x <- [-viewDistance..viewDistance], z <- [-viewDistance..viewDistance] ] numChunksToLoad = (viewDistance * 2 + 1) * (viewDistance * 2 + 1) rPath <- Hecs.get @Dimension.RegionFilePath (Dimension.entityId initialWorld) pure (error "TODO") doneRef <- liftIO $ newEmptyMVar numDoneRef <- liftIO $ newIORef numChunksToLoad liftIO $ putStrLn $ "Loading " <> show numChunksToLoad <> " chunks" --liftIO $ print chunksToLoad liftIO $ loadChunks (coerce rPath) chunksToLoad chunkloading $ \mvar -> void . Async.async $ takeMVar mvar >>= \c -> do let !(!sz, !cData) = mkChunkData c Conn.sendPacket conn . Conn.SendPacket sz $! Client.Play.ChunkDataAndUpdateLight cData done <- atomicModifyIORef' numDoneRef $ \(i :: Int) -> (i - 1, i - 1) when (done == 0) $ putMVar doneRef () liftIO $ takeMVar doneRef liftIO $ putStrLn "Done sending chunks" liftIO . Conn.sendPacket conn $ Conn.SendPacket 10 (C.SetCenterChunk 0 0) liftIO . Conn.sendPacket conn $ Conn.SendPacket 64 (C.SynchronizePlayerPosition (Position 0 130 0) (Rotation 180 0) (C.TeleportId 0) C.NoDismount) Hecs.set eid initialPosition Hecs.set eid initialRotation Hecs.set eid initialVelocity Hecs.set eid initialWorld This is the write that exposes us to the global state proper because that is what the JoinPlayer system queries on Hecs.set eid conn -- Handle play packets handlePacket :: Connection -> Server.Play.Packet -> Network () handlePacket conn (Server.Play.KeepAlive res) = liftIO $ Conn.ackKeepAlive conn res handlePacket conn (Server.Play.SetPlayerPositionAndRotation pos rot onGround) = liftIO . Conn.pushCommand conn $ MoveAndRotateClient pos rot onGround handlePacket conn (Server.Play.SetPlayerPosition pos onGround) = liftIO . Conn.pushCommand conn $ MoveClient pos onGround handlePacket conn (Server.Play.SetPlayerRotation rot onGround) = liftIO . Conn.pushCommand conn $ RotateClient rot onGround handlePacket conn (Server.Play.SetPlayerOnGround onGround) = liftIO . Conn.pushCommand conn $ SetOnGround onGround handlePacket _ p = liftIO $ putStrLn ("Unhandled packet: " <> show p)
null
https://raw.githubusercontent.com/1Jajen1/Brokkr/5c128a47c7123e576b4e415048d58c2ab3f4a0aa/src/Network/Handler.hs
haskell
TODO Label these threads If any of the linked threads crash, we must also crash since the connection will no longer work Actually create the player entity, from that point on the connection is visible globally TODO Log packet loop The packet loop in the bracket already diverges, but if for whatever reason we end up here, just kill the connection SYNC Because we need to know where to join the player TODO Move Preload chunks for this player -- SYNC Because we don't want to wait for this on the main thread and this will join the player with chunks loaded and not in some void liftIO $ print chunksToLoad Handle play packets
module Network.Handler ( handleConnection ) where import Data.IORef import Chunk.Position import IO.Chunkloading import Control.Concurrent (threadDelay) import Control.Concurrent.MVar import Control.Exception import qualified Chronos import qualified Control.Concurrent.Async as Async import Control.Monad import Control.Monad.IO.Class import qualified Data.ByteString.Lazy as LBS import Data.Text (Text) import Util.UUID import qualified Data.Vector as V import Dimension (Dimension, DimensionType(Overworld)) import qualified Dimension import Network.Connection (Connection, Command(..)) import qualified Network.Connection as Conn import Network.Monad import Network.Protocol import qualified Network.Packet.Client.Login as Client.Login import qualified Network.Packet.Client.Play as Client.Play import qualified Network.Packet.Server.Handshake as Server.Handshake import qualified Network.Packet.Server.Login as Server.Login import qualified Network.Packet.Server.Play as Server.Play import Network.Packet.Client.Play.ChunkData (mkChunkData) import Network.Util.Builder import Util.Binary import Data.Coerce import Control.Monad.Trans.Control import Util.Position import Util.Rotation import qualified Data.Text as T import qualified Network.Packet.Client.Play as C import qualified Network.Packet.Client.Play.Login as C import Registry.Biome import Registry.Dimension import Client.GameMode import Block.Position import qualified Data.Bitfield as Bitfield import qualified Server as Hecs import qualified Hecs import Hecs.Entity.Internal (Entity(..)) handleConnection :: Network () handleConnection = do LoginRes uid uName prot <- readPacket (Protocol NoCompression NoEncryption) >>= \case Server.Handshake.Handshake _ _ _ Server.Handshake.Status -> handleStatus Server.Handshake.Handshake _ _ _ Server.Handshake.Login -> handleLogin handlePlay uid uName prot handleStatus :: Network a handleStatus = closeConnection handleLogin :: Network LoginResult handleLogin = do uName <- readPacket (Protocol NoCompression NoEncryption) >>= \case Server.Login.LoginStart uName _ -> pure uName TODO Check for other packets and throw InvalidProtocol on those TODO generate proper uid let uid = nil TODO Have a config check if we use compression and what the threshold is let thresh = 512 sendPackets (Protocol NoCompression NoEncryption) 10 [Client.Login.SetCompression thresh] let finalProtocol = Protocol (Threshold thresh) NoEncryption sendPackets finalProtocol 64 [Client.Login.LoginSuccess uid uName] pure $ LoginRes uid uName finalProtocol data LoginResult = LoginRes UUID Text Protocol handlePlay :: UUID -> Text -> Protocol -> Network a handlePlay _playerUUID _playerName finalProtocol = do !conn <- liftIO Conn.new let send = go where go = do _ <- liftBaseWith $ \runInBase -> Conn.flushPackets conn $ \ps -> do runInBase . sendBytes . LBS.fromChunks $! fmap (\(Conn.SendPacket szHint packet) -> let !bs = toStrictSizePrefixedByteString finalProtocol szHint $ put packet in bs) $ V.toList ps go keepAlive = go where TODO make a config option so testing is a little easier delay = fromIntegral $ ((Chronos.getTimespan Chronos.second) * 20) `div` 1000 go = do threadDelay delay t' <- Chronos.getTime <$> Chronos.now Conn.sendKeepAlive conn t' go _ <- liftBaseWith $ \runInBase -> Async.withAsync (runInBase send) $ \sendAs -> Async.withAsync keepAlive $ \keepAliveAs -> do Async.link sendAs Async.link keepAliveAs bracket (do bracketOnError (runInBase $ Hecs.newEntity) (\eidSt -> runInBase $ restoreM eidSt >>= \eid -> joinPlayer conn eid >> pure eid) TODO $ \clientSt -> runInBase $ restoreM clientSt >>= \_client -> do let handlePlayPackets = do readPacket finalProtocol >>= handlePacket conn handlePlayPackets handlePlayPackets closeConnection joinPlayer :: Connection -> Hecs.EntityId -> Network () joinPlayer conn eid = do let initialPosition = Position 0 150 0 initialRotation = Rotation 0 0 initialVelocity = Position 0 0 0 initialWorld <- Hecs.get @Dimension (coerce $ Hecs.getComponentId @Dimension.Overworld) pure (error "World singleton missing") Sync with PlayerMovement until I store it as a component let loginData = C.LoginData (fromIntegral . Bitfield.get @"eid" $ Hecs.unEntityId eid) (C.IsHardcore False) Creative C.Undefined (V.fromList ["minecraft:overworld", "minecraft:nether", "minecraft:the_end"]) (C.RegistryCodec dimRegistry biomeRegistry chatRegistry) TODO proper type "minecraft:overworld" (C.HashedSeed 0) (C.MaxPlayers 5) (C.ViewDistance viewDistance) (C.SimulationDistance 8) (C.ReducedDebugInfo False) (C.EnableRespawnScreen False) (C.IsDebug False) (C.IsFlat False) C.NoDeathLocation dimRegistry = C.DimensionTypeRegistry "minecraft:dimension_type" (V.fromList [ C.DimensionRegistryEntry "minecraft:overworld" 0 overworld , C.DimensionRegistryEntry "minecraft:nether" 1 nether , C.DimensionRegistryEntry "minecraft:the_end" 2 end ] ) biomeRegistry = C.BiomeRegistry "minecraft:worldgen/biome" . V.fromList $ do (bid, (name, settings)) <- zip [0..] all_biome_settings return $ C.BiomeRegistryEntry ("minecraft:" <> T.pack name) bid settings chatRegistry = C.ChatRegistry "minecraft:chat_type" mempty liftIO . Conn.sendPacket conn $ Conn.SendPacket 65536 (C.Login loginData) liftIO . Conn.sendPacket conn $ Conn.SendPacket 10 (C.SetDefaultSpawnPosition (BlockPos 0 130 0) 0) chunkloading <- Hecs.getSingleton @Chunkloading let chunksToLoad = [ChunkPos x z | x <- [-viewDistance..viewDistance], z <- [-viewDistance..viewDistance] ] numChunksToLoad = (viewDistance * 2 + 1) * (viewDistance * 2 + 1) rPath <- Hecs.get @Dimension.RegionFilePath (Dimension.entityId initialWorld) pure (error "TODO") doneRef <- liftIO $ newEmptyMVar numDoneRef <- liftIO $ newIORef numChunksToLoad liftIO $ putStrLn $ "Loading " <> show numChunksToLoad <> " chunks" liftIO $ loadChunks (coerce rPath) chunksToLoad chunkloading $ \mvar -> void . Async.async $ takeMVar mvar >>= \c -> do let !(!sz, !cData) = mkChunkData c Conn.sendPacket conn . Conn.SendPacket sz $! Client.Play.ChunkDataAndUpdateLight cData done <- atomicModifyIORef' numDoneRef $ \(i :: Int) -> (i - 1, i - 1) when (done == 0) $ putMVar doneRef () liftIO $ takeMVar doneRef liftIO $ putStrLn "Done sending chunks" liftIO . Conn.sendPacket conn $ Conn.SendPacket 10 (C.SetCenterChunk 0 0) liftIO . Conn.sendPacket conn $ Conn.SendPacket 64 (C.SynchronizePlayerPosition (Position 0 130 0) (Rotation 180 0) (C.TeleportId 0) C.NoDismount) Hecs.set eid initialPosition Hecs.set eid initialRotation Hecs.set eid initialVelocity Hecs.set eid initialWorld This is the write that exposes us to the global state proper because that is what the JoinPlayer system queries on Hecs.set eid conn handlePacket :: Connection -> Server.Play.Packet -> Network () handlePacket conn (Server.Play.KeepAlive res) = liftIO $ Conn.ackKeepAlive conn res handlePacket conn (Server.Play.SetPlayerPositionAndRotation pos rot onGround) = liftIO . Conn.pushCommand conn $ MoveAndRotateClient pos rot onGround handlePacket conn (Server.Play.SetPlayerPosition pos onGround) = liftIO . Conn.pushCommand conn $ MoveClient pos onGround handlePacket conn (Server.Play.SetPlayerRotation rot onGround) = liftIO . Conn.pushCommand conn $ RotateClient rot onGround handlePacket conn (Server.Play.SetPlayerOnGround onGround) = liftIO . Conn.pushCommand conn $ SetOnGround onGround handlePacket _ p = liftIO $ putStrLn ("Unhandled packet: " <> show p)
74c6a3b6cdf20af1843565a5263f7b44dc1cc63752adbe4880f35260a6bff5bb
inhabitedtype/ocaml-aws
deleteCacheSecurityGroup.mli
open Types type input = DeleteCacheSecurityGroupMessage.t type output = unit type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
null
https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/b6d5554c5d201202b5de8d0b0253871f7b66dab6/libraries/elasticache/lib/deleteCacheSecurityGroup.mli
ocaml
open Types type input = DeleteCacheSecurityGroupMessage.t type output = unit type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
6cb14f6ac75b8270425422fc5342db16fec96fbc0d427f237d1e913fbdb98e90
zwizwa/staapl
picstamp_new.rkt
#lang racket/base (require staapl/pic18) Code for the USBPicStamp by . ;; -j/1350651639/ ;; staaplc -u -d pk2 picstamp.f (words-org-flat (#x300000 ;; Address of configuration bits in code space. ;; FIXME: this is code, and not a data table -- add sugar. #x21 |,| #x02 |,| #x3A |,| #x1E |,| #x00 |,| #x81 |,| #x85 |,| #x00 |,| ;; extended instruction set disabled #x0F |,| #xC0 |,| #x0F |,| #xE0 |,| #x0F |,| #x40 |,| )) (require ; target code and macros staapl/pic18/shift / pic18 / interpreter staapl/pic18/route staapl/pic18/ramblock staapl/pic18/template ) (macros MHz ; 4 clock cycles per instruction cycle gives 12 MIPS . (baud 230400) ) ; load monitor-serial.f \ boot block + serial monitor code (UART) # sh # pk2cmd -I -M -R -p PIC18F2550 -f $ 1
null
https://raw.githubusercontent.com/zwizwa/staapl/e30e6ae6ac45de7141b97ad3cebf9b5a51bcda52/app/picstamp_new.rkt
racket
-j/1350651639/ staaplc -u -d pk2 picstamp.f Address of configuration bits in code space. FIXME: this is code, and not a data table -- add sugar. extended instruction set disabled target code and macros 4 clock cycles per instruction cycle gives 12 MIPS . load monitor-serial.f \ boot block + serial monitor code (UART)
#lang racket/base (require staapl/pic18) Code for the USBPicStamp by . (words-org-flat #x21 |,| #x02 |,| #x3A |,| #x1E |,| #x0F |,| #xC0 |,| #x0F |,| #xE0 |,| #x0F |,| #x40 |,| )) (require staapl/pic18/shift / pic18 / interpreter staapl/pic18/route staapl/pic18/ramblock staapl/pic18/template ) (macros (baud 230400) ) # sh # pk2cmd -I -M -R -p PIC18F2550 -f $ 1
38f455d2a22ce3f658a8f34bb74a7e904e765b0c7658abb1e0fc36f0946dca40
elastic/eui-cljs
split_panel.cljs
(ns eui.split-panel (:require ["@elastic/eui/lib/components/panel/split_panel/split_panel.js" :as eui])) (def _EuiSplitPanelInner eui/_EuiSplitPanelInner) (def _EuiSplitPanelOuter eui/_EuiSplitPanelOuter) (def EuiSplitPanel eui/EuiSplitPanel)
null
https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/split_panel.cljs
clojure
(ns eui.split-panel (:require ["@elastic/eui/lib/components/panel/split_panel/split_panel.js" :as eui])) (def _EuiSplitPanelInner eui/_EuiSplitPanelInner) (def _EuiSplitPanelOuter eui/_EuiSplitPanelOuter) (def EuiSplitPanel eui/EuiSplitPanel)
5ad2bb1b6c897eb71c87b2cc570949f73322b4c54b0e826bdb490b77110b8b0d
LaurentMazare/tensorflow-ocaml
wrapper.mli
type data_type = | TF_FLOAT | TF_DOUBLE | TF_INT32 | TF_UINT8 | TF_INT16 | TF_INT8 | TF_STRING | TF_COMPLEX | TF_INT64 | TF_BOOL | TF_QINT8 | TF_QUINT8 | TF_QINT32 | TF_BFLOAT16 | TF_QINT16 | TF_QUINT16 | TF_UINT16 | Unknown of int module Session_options : sig type t val create : unit -> t end module Status : sig type t type code = | TF_OK | TF_CANCELLED | TF_UNKNOWN | TF_INVALID_ARGUMENT | TF_DEADLINE_EXCEEDED | TF_NOT_FOUND | TF_ALREADY_EXISTS | TF_PERMISSION_DENIED | TF_UNAUTHENTICATED | TF_RESOURCE_EXHAUSTED | TF_FAILED_PRECONDITION | TF_ABORTED | TF_OUT_OF_RANGE | TF_UNIMPLEMENTED | TF_INTERNAL | TF_UNAVAILABLE | TF_DATA_LOSS | Unknown of int val code : t -> code val message : t -> string type 'a result = | Ok of 'a | Error of t val ok_exn : 'a result -> 'a end module Graph : sig type t type operation type operation_description type output val create : unit -> t val new_operation : t -> op_name:string -> name:string -> operation_description val finish_operation : operation_description -> operation Status.result val add_control_input : operation_description -> operation -> unit val add_input : operation_description -> operation -> index:int -> unit val add_inputs : operation_description -> (operation * int) list -> unit val create_output : operation -> index:int -> output val output_op_and_index : t -> output -> operation * int val set_attr_int : operation_description -> attr_name:string -> int -> unit val set_attr_int_list : operation_description -> attr_name:string -> int list -> unit val set_attr_float : operation_description -> attr_name:string -> float -> unit val set_attr_float_list : operation_description -> attr_name:string -> float list -> unit val set_attr_bool : operation_description -> attr_name:string -> bool -> unit val set_attr_bool_list : operation_description -> attr_name:string -> bool list -> unit val set_attr_string : operation_description -> attr_name:string -> string -> unit val set_attr_type : operation_description -> attr_name:string -> data_type -> unit val set_attr_type_list : operation_description -> attr_name:string -> data_type list -> unit val set_attr_tensor : operation_description -> attr_name:string -> Tensor.p -> unit Status.result val set_attr_tensor_string : operation_description -> attr_name:string -> shape:int list -> string list -> unit Status.result val set_attr_tensors : operation_description -> attr_name:string -> Tensor.p list -> unit Status.result val set_attr_shape : operation_description -> attr_name:string -> int list -> unit val import : t -> string -> unit Status.result val find_operation : t -> string -> operation option val shape : t -> output -> int list Status.result val add_gradients : t -> output list -> xs:output list -> output list Status.result val graph : operation -> t end module Session : sig type t val create : ?session_options:Session_options.t -> Graph.t -> t Status.result val run : ?inputs:(Graph.output * Tensor.p) list -> ?outputs:Graph.output list -> ?targets:Graph.operation list -> t -> Tensor.p list Status.result end
null
https://raw.githubusercontent.com/LaurentMazare/tensorflow-ocaml/52c5f1dec1a8b7dc9bc6ef06abbc07da6cd90d39/src/wrapper/wrapper.mli
ocaml
type data_type = | TF_FLOAT | TF_DOUBLE | TF_INT32 | TF_UINT8 | TF_INT16 | TF_INT8 | TF_STRING | TF_COMPLEX | TF_INT64 | TF_BOOL | TF_QINT8 | TF_QUINT8 | TF_QINT32 | TF_BFLOAT16 | TF_QINT16 | TF_QUINT16 | TF_UINT16 | Unknown of int module Session_options : sig type t val create : unit -> t end module Status : sig type t type code = | TF_OK | TF_CANCELLED | TF_UNKNOWN | TF_INVALID_ARGUMENT | TF_DEADLINE_EXCEEDED | TF_NOT_FOUND | TF_ALREADY_EXISTS | TF_PERMISSION_DENIED | TF_UNAUTHENTICATED | TF_RESOURCE_EXHAUSTED | TF_FAILED_PRECONDITION | TF_ABORTED | TF_OUT_OF_RANGE | TF_UNIMPLEMENTED | TF_INTERNAL | TF_UNAVAILABLE | TF_DATA_LOSS | Unknown of int val code : t -> code val message : t -> string type 'a result = | Ok of 'a | Error of t val ok_exn : 'a result -> 'a end module Graph : sig type t type operation type operation_description type output val create : unit -> t val new_operation : t -> op_name:string -> name:string -> operation_description val finish_operation : operation_description -> operation Status.result val add_control_input : operation_description -> operation -> unit val add_input : operation_description -> operation -> index:int -> unit val add_inputs : operation_description -> (operation * int) list -> unit val create_output : operation -> index:int -> output val output_op_and_index : t -> output -> operation * int val set_attr_int : operation_description -> attr_name:string -> int -> unit val set_attr_int_list : operation_description -> attr_name:string -> int list -> unit val set_attr_float : operation_description -> attr_name:string -> float -> unit val set_attr_float_list : operation_description -> attr_name:string -> float list -> unit val set_attr_bool : operation_description -> attr_name:string -> bool -> unit val set_attr_bool_list : operation_description -> attr_name:string -> bool list -> unit val set_attr_string : operation_description -> attr_name:string -> string -> unit val set_attr_type : operation_description -> attr_name:string -> data_type -> unit val set_attr_type_list : operation_description -> attr_name:string -> data_type list -> unit val set_attr_tensor : operation_description -> attr_name:string -> Tensor.p -> unit Status.result val set_attr_tensor_string : operation_description -> attr_name:string -> shape:int list -> string list -> unit Status.result val set_attr_tensors : operation_description -> attr_name:string -> Tensor.p list -> unit Status.result val set_attr_shape : operation_description -> attr_name:string -> int list -> unit val import : t -> string -> unit Status.result val find_operation : t -> string -> operation option val shape : t -> output -> int list Status.result val add_gradients : t -> output list -> xs:output list -> output list Status.result val graph : operation -> t end module Session : sig type t val create : ?session_options:Session_options.t -> Graph.t -> t Status.result val run : ?inputs:(Graph.output * Tensor.p) list -> ?outputs:Graph.output list -> ?targets:Graph.operation list -> t -> Tensor.p list Status.result end
2a70c5a75e81715bb19b297bb7d77424d4a678f1978cf7d3c214854a0cb85257
cljdoc/cljdoc
ns_tree_test.clj
(ns cljdoc.util.ns-tree-test (:require [cljdoc.util.ns-tree :as ns-tree] [clojure.test :as t])) (t/deftest replant-ns-test (t/is (= "my.app.routes" (ns-tree/replant-ns "my.app.core" "routes"))) (t/is (= "my.app.api.routes" (ns-tree/replant-ns "my.app.core" "api.routes"))) (t/is (= "my.app.api.handlers" (ns-tree/replant-ns "my.app.core" "my.app.api.handlers"))) (t/is (= "my.different.ns.here" (ns-tree/replant-ns "my.app.core" "my.different.ns.here"))) (t/is (= "my.app.ns2" (ns-tree/replant-ns "my.app.ns1" "ns2"))))
null
https://raw.githubusercontent.com/cljdoc/cljdoc/266153cac0df618df1ad6e1d946f0bc466bc8f6c/test/cljdoc/util/ns_tree_test.clj
clojure
(ns cljdoc.util.ns-tree-test (:require [cljdoc.util.ns-tree :as ns-tree] [clojure.test :as t])) (t/deftest replant-ns-test (t/is (= "my.app.routes" (ns-tree/replant-ns "my.app.core" "routes"))) (t/is (= "my.app.api.routes" (ns-tree/replant-ns "my.app.core" "api.routes"))) (t/is (= "my.app.api.handlers" (ns-tree/replant-ns "my.app.core" "my.app.api.handlers"))) (t/is (= "my.different.ns.here" (ns-tree/replant-ns "my.app.core" "my.different.ns.here"))) (t/is (= "my.app.ns2" (ns-tree/replant-ns "my.app.ns1" "ns2"))))
b033438bc858a1a07d32e9bcf873b542a9fd58c6220fcadfd33961f4007ea5bc
ian-ross/hnetcdf
test-put.hs
# LANGUAGE ScopedTypeVariables # import qualified Data.Map as M import Data.Maybe import qualified Data.Vector.Storable as SV import Control.Error import Control.Monad import Foreign.C import Data.NetCDF import Data.NetCDF.Vector main :: IO () main = do let xdim = NcDim "x" 10 False ydim = NcDim "y" 10 False xattrs = M.fromList [("attr", NcAttrFloat [0.1, 0.2]), ("name", NcAttrChar "xvar")] nc = emptyNcInfo "tst-put.nc" # addNcDim xdim # addNcDim ydim # addNcVar (NcVar "x" NcDouble [xdim] xattrs) # addNcVar (NcVar "y" NcDouble [ydim] M.empty) # addNcVar (NcVar "z" NcDouble [xdim, ydim] M.empty) let write nc = do let xvar = fromJust $ ncVar nc "x" yvar = fromJust $ ncVar nc "y" zvar = fromJust $ ncVar nc "z" put nc xvar $ SV.fromList [1..10 :: CDouble] put nc yvar $ SV.fromList [1..10 :: CDouble] put nc zvar $ SV.fromList [ 100 * x + y | x <- [1..10 :: CDouble], y <- [1..10 :: CDouble] ] return () withCreateFile nc write (putStrLn . ("ERROR: " ++) . show)
null
https://raw.githubusercontent.com/ian-ross/hnetcdf/d334efc0b0b4f39a1ed4f45a8b75663c2171af6a/test/test-put.hs
haskell
# LANGUAGE ScopedTypeVariables # import qualified Data.Map as M import Data.Maybe import qualified Data.Vector.Storable as SV import Control.Error import Control.Monad import Foreign.C import Data.NetCDF import Data.NetCDF.Vector main :: IO () main = do let xdim = NcDim "x" 10 False ydim = NcDim "y" 10 False xattrs = M.fromList [("attr", NcAttrFloat [0.1, 0.2]), ("name", NcAttrChar "xvar")] nc = emptyNcInfo "tst-put.nc" # addNcDim xdim # addNcDim ydim # addNcVar (NcVar "x" NcDouble [xdim] xattrs) # addNcVar (NcVar "y" NcDouble [ydim] M.empty) # addNcVar (NcVar "z" NcDouble [xdim, ydim] M.empty) let write nc = do let xvar = fromJust $ ncVar nc "x" yvar = fromJust $ ncVar nc "y" zvar = fromJust $ ncVar nc "z" put nc xvar $ SV.fromList [1..10 :: CDouble] put nc yvar $ SV.fromList [1..10 :: CDouble] put nc zvar $ SV.fromList [ 100 * x + y | x <- [1..10 :: CDouble], y <- [1..10 :: CDouble] ] return () withCreateFile nc write (putStrLn . ("ERROR: " ++) . show)
a1902cc089acda5ee970bc44c56358a16b8f0629e206f5f9e079a3a2e4b00b4a
helium/blockchain-http
bh_pool_watcher.erl
-module(bh_pool_watcher). -behaviour(gen_server). -export([start_link/1]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2]). start_link(Pools) -> gen_server:start_link(?MODULE, Pools, []). init(Pools) -> Monitors = maps:from_list([ {erlang:monitor(process, get_name(PoolName)), PoolName} || PoolName <- Pools ]), {ok, Monitors}. handle_call(Msg, From, State) -> lager:warning("Unexpected call ~p from ~p", [Msg, From]), {reply, error, State}. handle_cast(Msg, State) -> lager:warning("Unexpected cast ~p", [Msg]), {noreply, State}. handle_info({monitor, Name}, State) -> Ref = erlang:monitor(process, get_name(Name)), try dispcount:dispatcher_info(Name) of {ok, PoolInfo} -> lager:info("dispcount is back"), %% it's back, update the persistent term persistent_term:put(Name, PoolInfo), {noreply, maps:put(Ref, Name, State)} catch What:Why -> lager:info("dispcount still not ready ~p:~p", [What, Why]), %% likely things have not finished restarting, try again shortly erlang:demonitor(Ref, [flush]), erlang:send_after(500, self(), {monitor, Name}), {noreply, State} end; handle_info({'DOWN', Ref, process, _Pid, noproc}, State) -> case maps:find(Ref, State) of {ok, Name} -> lager:notice("Pool ~p monitor failed with noproc, retrying", [Name]), %% noproc means the process wasn't alive when we tried to monitor it %% we should probably wait a bit and retry erlang:send_after(5000, self(), {monitor, Name}), {noreply, maps:remove(Ref, State)}; error -> lager:warning("unknown ref ~p exited with reason noproc", [Ref]), {noreply, State} end; handle_info({'DOWN', Ref, process, _Pid, Reason}, State) -> case maps:find(Ref, State) of {ok, Name} -> self() ! {monitor, Name}, lager:notice("Pool ~p exited with reason ~p", [Name, Reason]), {noreply, maps:remove(Ref, State)}; error -> lager:warning("unknown ref ~p exited with reason ~p", [Ref, Reason]), {noreply, State} end; handle_info(Msg, State) -> lager:warning("Unexpected info ~p", [Msg]), {noreply, State}. get_name(Name) -> list_to_atom(atom_to_list(Name) ++ "_serv").
null
https://raw.githubusercontent.com/helium/blockchain-http/96f66286eb05a4607a3a11f602ec3d65732244a9/src/bh_pool_watcher.erl
erlang
it's back, update the persistent term likely things have not finished restarting, try again shortly noproc means the process wasn't alive when we tried to monitor it we should probably wait a bit and retry
-module(bh_pool_watcher). -behaviour(gen_server). -export([start_link/1]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2]). start_link(Pools) -> gen_server:start_link(?MODULE, Pools, []). init(Pools) -> Monitors = maps:from_list([ {erlang:monitor(process, get_name(PoolName)), PoolName} || PoolName <- Pools ]), {ok, Monitors}. handle_call(Msg, From, State) -> lager:warning("Unexpected call ~p from ~p", [Msg, From]), {reply, error, State}. handle_cast(Msg, State) -> lager:warning("Unexpected cast ~p", [Msg]), {noreply, State}. handle_info({monitor, Name}, State) -> Ref = erlang:monitor(process, get_name(Name)), try dispcount:dispatcher_info(Name) of {ok, PoolInfo} -> lager:info("dispcount is back"), persistent_term:put(Name, PoolInfo), {noreply, maps:put(Ref, Name, State)} catch What:Why -> lager:info("dispcount still not ready ~p:~p", [What, Why]), erlang:demonitor(Ref, [flush]), erlang:send_after(500, self(), {monitor, Name}), {noreply, State} end; handle_info({'DOWN', Ref, process, _Pid, noproc}, State) -> case maps:find(Ref, State) of {ok, Name} -> lager:notice("Pool ~p monitor failed with noproc, retrying", [Name]), erlang:send_after(5000, self(), {monitor, Name}), {noreply, maps:remove(Ref, State)}; error -> lager:warning("unknown ref ~p exited with reason noproc", [Ref]), {noreply, State} end; handle_info({'DOWN', Ref, process, _Pid, Reason}, State) -> case maps:find(Ref, State) of {ok, Name} -> self() ! {monitor, Name}, lager:notice("Pool ~p exited with reason ~p", [Name, Reason]), {noreply, maps:remove(Ref, State)}; error -> lager:warning("unknown ref ~p exited with reason ~p", [Ref, Reason]), {noreply, State} end; handle_info(Msg, State) -> lager:warning("Unexpected info ~p", [Msg]), {noreply, State}. get_name(Name) -> list_to_atom(atom_to_list(Name) ++ "_serv").