_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
d29e852399cf5bc2d03bd829218a700aca8db810b1685480bfadcca2211810c4
Octachron/phantom_algebra
flat_array.ml
#if OCAML_MAJOR>=4 && OCAML_MINOR>=6 type elt = float type t = floatarray let len = Array.Floatarray.length let get = Array.Floatarray.unsafe_get let set = Array.Floatarray.unsafe_set let create = Array.Floatarray.create #else type elt = float type t = elt array let len = Array.length let get = Array.unsafe_get let set = Array.unsafe_set #if OCAML_MAJOR>=4 && OCAML_MINOR>=3 let create = Array.create_float #else let create n = Array.make n 0. #endif #endif
null
https://raw.githubusercontent.com/Octachron/phantom_algebra/9733dad74e010642bdd500afe987440558d5608b/src/flat_array.ml
ocaml
#if OCAML_MAJOR>=4 && OCAML_MINOR>=6 type elt = float type t = floatarray let len = Array.Floatarray.length let get = Array.Floatarray.unsafe_get let set = Array.Floatarray.unsafe_set let create = Array.Floatarray.create #else type elt = float type t = elt array let len = Array.length let get = Array.unsafe_get let set = Array.unsafe_set #if OCAML_MAJOR>=4 && OCAML_MINOR>=3 let create = Array.create_float #else let create n = Array.make n 0. #endif #endif
0c04f0becc5ab9ed75247da19aec3e2dbb27a3fbf92ceb01b80ac20762a65abe
michaelklishin/langohr
core.clj
This source code is dual - licensed under the Apache License , version 2.0 , and the Eclipse Public License , version 1.0 . ;; ;; The APL v2.0: ;; ;; ---------------------------------------------------------------------------------- Copyright ( c ) 2011 - 2020 , , and the ClojureWerkz Team ;; 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. ;; ---------------------------------------------------------------------------------- ;; The EPL v1.0 : ;; ;; ---------------------------------------------------------------------------------- Copyright ( c ) 2011 - 2020 , , and the ClojureWerkz Team . ;; All rights reserved. ;; ;; This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0 , ;; which accompanies this distribution and is available at -v10.html . ;; ---------------------------------------------------------------------------------- (ns langohr.core "Functions that work with connections and shared features between connections and channels (e.g. shutdown listeners). Relevant guides: * * " (:import [com.rabbitmq.client Connection Channel Address ConnectionFactory ShutdownListener BlockedListener Consumer TopologyRecoveryException ExceptionHandler Recoverable RecoveryListener DefaultSaslConfig] [com.rabbitmq.client.impl ForgivingExceptionHandler AMQConnection] [com.rabbitmq.client.impl.recovery AutorecoveringConnection QueueRecoveryListener] clojure.lang.IFn java.util.concurrent.ThreadFactory) (:require langohr.channel [clojure.string :as s] [clojure.walk :as walk])) ;; ;; Implementation ;; (def ^{:dynamic true :doc "Default connection settings."} *default-config* {:username "guest" :password "guest" :vhost "/" :host "localhost" :port ConnectionFactory/DEFAULT_AMQP_PORT}) ;; ;; API ;; (defprotocol Closeable (close [c] "Closes given entity")) (extend-protocol Closeable com.rabbitmq.client.Connection (close [this] (.close this)) com.rabbitmq.client.Channel (close [this] (.close this))) (defprotocol Openable (open? [this] "Checks whether given entity is open") (closed? [this] "Checks whether given entity is closed")) (extend-protocol Openable com.rabbitmq.client.Connection (open? [conn] (.isOpen conn)) (closed? [conn] (not (.isOpen conn))) com.rabbitmq.client.Channel (open? [ch] (.isOpen ch)) (closed? [ch] (not (.isOpen ch)))) (declare create-connection-factory normalize-settings) (defn- address-array-from [addresses port] (into-array Address (map (fn [arg] (let [[host port] (if (coll? arg) [(first arg) (second arg)] [arg port])] (Address. host port))) (remove nil? addresses)))) (defn ^Connection connect "Creates and returns a new connection to RabbitMQ." ;; defaults ([] (let [^ConnectionFactory cf (create-connection-factory {})] (doto (com.novemberain.langohr.Connection. cf) .init))) ;; settings ([settings] (let [settings' (normalize-settings settings) tls (get settings' :ssl false) default-port (if tls ConnectionFactory/DEFAULT_AMQP_OVER_SSL_PORT ConnectionFactory/DEFAULT_AMQP_PORT) ^ConnectionFactory cf (create-connection-factory settings') xs (address-array-from (get settings' :hosts #{}) (get settings' :port default-port))] (doto (com.novemberain.langohr.Connection. cf (dissoc settings' :password :username)) (.init xs))))) (defn ^Channel create-channel "Delegates to langohr.channel/open, kept for backwards compatibility" [& args] (apply langohr.channel/open args)) (defn ^ShutdownListener shutdown-listener "Adds new shutdown signal listener that delegates to given function" [^clojure.lang.IFn f] (reify ShutdownListener (shutdownCompleted [this cause] (f cause)))) (defn ^ShutdownListener add-shutdown-listener "Adds a shutdown listener on connection and returns it" [^Connection c ^IFn f] (let [lnr (shutdown-listener f)] (.addShutdownListener c lnr) lnr)) (defn ^BlockedListener blocked-listener "Reifies connection.blocked and connection.unblocked listener from Clojure functions" [^IFn on-blocked ^IFn on-unblocked] (reify BlockedListener (^void handleBlocked [this ^String reason] (on-blocked reason)) (^void handleUnblocked [this] (on-unblocked)))) (defn ^BlockedListener add-blocked-listener "Adds a connection.blocked and connection.unblocked listener on connection and returns it" [^Connection c ^IFn on-blocked ^IFn on-unblocked] (let [lnr (blocked-listener on-blocked on-unblocked)] (.addBlockedListener c lnr) lnr)) (defn settings-from "Parses AMQP connection URI and returns a persistent map of settings" [^String uri] (if uri (let [cf (doto (ConnectionFactory.) (.setUri uri))] {:host (.getHost cf) :port (.getPort cf) :vhost (.getVirtualHost cf) :username (.getUsername cf) :password (.getPassword cf)}) *default-config*)) (defn capabilities-of "Returns capabilities of the broker on the other side of the connection" [^Connection conn] (walk/keywordize-keys (into {} (-> conn .getServerProperties (get "capabilities"))))) ;; ;; Recovery ;; (defn automatic-recovery-enabled? "Returns true if provided connection uses automatic connection recovery mode, false otherwise" [^com.novemberain.langohr.Connection conn] (.automaticRecoveryEnabled conn)) (defn ^{:deprecated true} automatically-recover? "See automatic-recovery-enabled?" [^com.novemberain.langohr.Connection c] (automatic-recovery-enabled? c)) (defn automatic-topology-recovery-enabled? "Returns true if provided connection uses automatic topology recovery mode, false otherwise" [^com.novemberain.langohr.Connection conn] (.automaticTopologyRecoveryEnabled conn)) (defn on-recovery "Registers a network recovery callback on a (Langohr) connection or channel" ([^Recoverable target ^IFn recovery-finished-fn] (.addRecoveryListener target (reify RecoveryListener (^void handleRecovery [this ^Recoverable it] (recovery-finished-fn it)) (^void handleRecoveryStarted [this ^Recoverable it] ;; intentionally no-op (fn [this ^Recoverable it] ))))) ([^Recoverable target ^IFn recovery-started-fn ^IFn recovery-finished-fn] (.addRecoveryListener target (reify RecoveryListener (^void handleRecoveryStarted [this ^Recoverable it] (recovery-started-fn it)) (^void handleRecovery [this ^Recoverable it] (recovery-finished-fn it)))))) (defn ^QueueRecoveryListener queue-recovery-listener "Reifies a new queue recovery listener that delegates to a Clojure function." [^IFn f] (reify QueueRecoveryListener (^void queueRecovered [this ^String old-name ^String new-name] (f old-name new-name)))) (defn on-queue-recovery "Called when server named queue gets a new name on recovery" [^com.novemberain.langohr.Connection conn ^IFn f] (.addQueueRecoveryListener (cast AutorecoveringConnection (.getDelegate conn)) (queue-recovery-listener f))) ;; ;; Advanced Customization ;; (defn thread-factory-from "Instantiates a java.util.concurrent.ThreadFactory that delegates #newThread to provided Clojure function" [f] (reify java.util.concurrent.ThreadFactory (^Thread newThread [this ^Runnable r] (f r)))) (defn exception-handler [{:keys [handle-connection-exception-fn handle-return-listener-exception-fn handle-flow-listener-exception-fn handle-confirm-listener-exception-fn handle-blocked-listener-exception-fn handle-consumer-exception-fn handle-connection-recovery-exception-fn handle-channel-recovery-exception-fn handle-topology-recovery-exception-fn]}] (proxy [ForgivingExceptionHandler] [] (handleUnexpectedConnectionDriverException [^Connection conn ^Throwable t] (when handle-connection-exception-fn (handle-connection-exception-fn conn t))) (handleReturnListenerException [^Channel ch ^Throwable t] (when handle-return-listener-exception-fn (handle-return-listener-exception-fn ch t))) (handleFlowListenerException [^Channel ch ^Throwable t] (when handle-flow-listener-exception-fn (handle-flow-listener-exception-fn ch t))) (handleConfirmListenerException [^Channel ch ^Throwable t] (when handle-confirm-listener-exception-fn (handle-confirm-listener-exception-fn ch t))) (handleBlockedListenerException [^Connection conn ^Throwable t] (when handle-blocked-listener-exception-fn (handle-blocked-listener-exception-fn conn t))) (handleConsumerException [^Channel ch ^Throwable t ^Consumer consumer ^String consumer-tag ^String method-name] (when handle-consumer-exception-fn (handle-consumer-exception-fn ch t consumer consumer-tag method-name))) (handleConnectionRecoveryException [^Connection conn ^Throwable t] (when handle-connection-recovery-exception-fn (handle-connection-recovery-exception-fn conn t))) (handleChannelRecoveryException [^Channel ch ^Throwable t] (when handle-channel-recovery-exception-fn (handle-channel-recovery-exception-fn ch t))) (handleTopologyRecoveryException [^Connection conn ^Channel ch ^TopologyRecoveryException t] (when handle-topology-recovery-exception-fn (handle-topology-recovery-exception-fn conn ch t))))) ;; ;; Implementation ;; (defn normalize-settings "For setting maps that contain keys such as :host, :username, :vhost, returns the argument" [config] (let [{:keys [host hosts]} config hosts' (into #{} (remove nil? (or hosts #{host})))] (merge (settings-from (:uri config (System/getenv "RABBITMQ_URL"))) {:hosts hosts'} config))) (defn- platform-string [] (let [] (format "Clojure %s on %s %s" (clojure-version) (System/getProperty "java.vm.name") (System/getProperty "java.version")))) (def ^{:private true} client-properties {"product" "Langohr" "information" "See /" "platform" (platform-string) "capabilities" (get (AMQConnection/defaultClientProperties) "capabilities") "copyright" "Copyright (C) 2011-2020 Michael S. Klishin, Alex Petrov" "version" "5.3.0-SNAPSHOT"}) (defn- auth-mechanism->sasl-config [{:keys [authentication-mechanism]}] (case authentication-mechanism "PLAIN" DefaultSaslConfig/PLAIN "EXTERNAL" DefaultSaslConfig/EXTERNAL nil)) (defn- ^ConnectionFactory create-connection-factory "Creates connection factory from given attributes" [settings] (let [{:keys [host port username password vhost requested-heartbeat connection-timeout ssl ssl-context verify-hostname socket-factory sasl-config requested-channel-max thread-factory exception-handler connection-name update-client-properties] :or {requested-heartbeat ConnectionFactory/DEFAULT_HEARTBEAT connection-timeout ConnectionFactory/DEFAULT_CONNECTION_TIMEOUT requested-channel-max ConnectionFactory/DEFAULT_CHANNEL_MAX sasl-config (auth-mechanism->sasl-config settings)}} (normalize-settings settings) cf (ConnectionFactory.) final-port (if (and ssl (= port ConnectionFactory/DEFAULT_AMQP_PORT)) ConnectionFactory/DEFAULT_AMQP_OVER_SSL_PORT port) final-properties (cond-> client-properties connection-name (assoc "connection_name" connection-name) update-client-properties update-client-properties)] (when (or ssl (= port ConnectionFactory/DEFAULT_AMQP_OVER_SSL_PORT)) (.useSslProtocol cf)) (doto cf (.setClientProperties final-properties) (.setUsername username) (.setPassword password) (.setVirtualHost vhost) (.setHost host) (.setPort final-port) (.setRequestedHeartbeat requested-heartbeat) (.setConnectionTimeout connection-timeout) (.setRequestedChannelMax requested-channel-max)) (when sasl-config (.setSaslConfig cf sasl-config)) (when ssl-context (do (.useSslProtocol cf ^javax.net.ssl.SSLContext ssl-context) (.setPort cf final-port))) (when verify-hostname (.enableHostnameVerification cf)) (when thread-factory (.setThreadFactory cf ^ThreadFactory thread-factory)) (if exception-handler (.setExceptionHandler cf ^ExceptionHandler exception-handler) (.setExceptionHandler cf (ForgivingExceptionHandler.))) cf))
null
https://raw.githubusercontent.com/michaelklishin/langohr/0c63ac3c6bc97d73e290ed366e9e97e07d39dedb/src/clojure/langohr/core.clj
clojure
The APL v2.0: ---------------------------------------------------------------------------------- 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. ---------------------------------------------------------------------------------- ---------------------------------------------------------------------------------- All rights reserved. This program and the accompanying materials are made available under the terms of which accompanies this distribution and is available at ---------------------------------------------------------------------------------- Implementation API defaults settings Recovery intentionally no-op Advanced Customization Implementation
This source code is dual - licensed under the Apache License , version 2.0 , and the Eclipse Public License , version 1.0 . Copyright ( c ) 2011 - 2020 , , and the ClojureWerkz Team distributed under the License is distributed on an " AS IS " BASIS , The EPL v1.0 : Copyright ( c ) 2011 - 2020 , , and the ClojureWerkz Team . the Eclipse Public License Version 1.0 , -v10.html . (ns langohr.core "Functions that work with connections and shared features between connections and channels (e.g. shutdown listeners). Relevant guides: * * " (:import [com.rabbitmq.client Connection Channel Address ConnectionFactory ShutdownListener BlockedListener Consumer TopologyRecoveryException ExceptionHandler Recoverable RecoveryListener DefaultSaslConfig] [com.rabbitmq.client.impl ForgivingExceptionHandler AMQConnection] [com.rabbitmq.client.impl.recovery AutorecoveringConnection QueueRecoveryListener] clojure.lang.IFn java.util.concurrent.ThreadFactory) (:require langohr.channel [clojure.string :as s] [clojure.walk :as walk])) (def ^{:dynamic true :doc "Default connection settings."} *default-config* {:username "guest" :password "guest" :vhost "/" :host "localhost" :port ConnectionFactory/DEFAULT_AMQP_PORT}) (defprotocol Closeable (close [c] "Closes given entity")) (extend-protocol Closeable com.rabbitmq.client.Connection (close [this] (.close this)) com.rabbitmq.client.Channel (close [this] (.close this))) (defprotocol Openable (open? [this] "Checks whether given entity is open") (closed? [this] "Checks whether given entity is closed")) (extend-protocol Openable com.rabbitmq.client.Connection (open? [conn] (.isOpen conn)) (closed? [conn] (not (.isOpen conn))) com.rabbitmq.client.Channel (open? [ch] (.isOpen ch)) (closed? [ch] (not (.isOpen ch)))) (declare create-connection-factory normalize-settings) (defn- address-array-from [addresses port] (into-array Address (map (fn [arg] (let [[host port] (if (coll? arg) [(first arg) (second arg)] [arg port])] (Address. host port))) (remove nil? addresses)))) (defn ^Connection connect "Creates and returns a new connection to RabbitMQ." ([] (let [^ConnectionFactory cf (create-connection-factory {})] (doto (com.novemberain.langohr.Connection. cf) .init))) ([settings] (let [settings' (normalize-settings settings) tls (get settings' :ssl false) default-port (if tls ConnectionFactory/DEFAULT_AMQP_OVER_SSL_PORT ConnectionFactory/DEFAULT_AMQP_PORT) ^ConnectionFactory cf (create-connection-factory settings') xs (address-array-from (get settings' :hosts #{}) (get settings' :port default-port))] (doto (com.novemberain.langohr.Connection. cf (dissoc settings' :password :username)) (.init xs))))) (defn ^Channel create-channel "Delegates to langohr.channel/open, kept for backwards compatibility" [& args] (apply langohr.channel/open args)) (defn ^ShutdownListener shutdown-listener "Adds new shutdown signal listener that delegates to given function" [^clojure.lang.IFn f] (reify ShutdownListener (shutdownCompleted [this cause] (f cause)))) (defn ^ShutdownListener add-shutdown-listener "Adds a shutdown listener on connection and returns it" [^Connection c ^IFn f] (let [lnr (shutdown-listener f)] (.addShutdownListener c lnr) lnr)) (defn ^BlockedListener blocked-listener "Reifies connection.blocked and connection.unblocked listener from Clojure functions" [^IFn on-blocked ^IFn on-unblocked] (reify BlockedListener (^void handleBlocked [this ^String reason] (on-blocked reason)) (^void handleUnblocked [this] (on-unblocked)))) (defn ^BlockedListener add-blocked-listener "Adds a connection.blocked and connection.unblocked listener on connection and returns it" [^Connection c ^IFn on-blocked ^IFn on-unblocked] (let [lnr (blocked-listener on-blocked on-unblocked)] (.addBlockedListener c lnr) lnr)) (defn settings-from "Parses AMQP connection URI and returns a persistent map of settings" [^String uri] (if uri (let [cf (doto (ConnectionFactory.) (.setUri uri))] {:host (.getHost cf) :port (.getPort cf) :vhost (.getVirtualHost cf) :username (.getUsername cf) :password (.getPassword cf)}) *default-config*)) (defn capabilities-of "Returns capabilities of the broker on the other side of the connection" [^Connection conn] (walk/keywordize-keys (into {} (-> conn .getServerProperties (get "capabilities"))))) (defn automatic-recovery-enabled? "Returns true if provided connection uses automatic connection recovery mode, false otherwise" [^com.novemberain.langohr.Connection conn] (.automaticRecoveryEnabled conn)) (defn ^{:deprecated true} automatically-recover? "See automatic-recovery-enabled?" [^com.novemberain.langohr.Connection c] (automatic-recovery-enabled? c)) (defn automatic-topology-recovery-enabled? "Returns true if provided connection uses automatic topology recovery mode, false otherwise" [^com.novemberain.langohr.Connection conn] (.automaticTopologyRecoveryEnabled conn)) (defn on-recovery "Registers a network recovery callback on a (Langohr) connection or channel" ([^Recoverable target ^IFn recovery-finished-fn] (.addRecoveryListener target (reify RecoveryListener (^void handleRecovery [this ^Recoverable it] (recovery-finished-fn it)) (^void handleRecoveryStarted [this ^Recoverable it] (fn [this ^Recoverable it] ))))) ([^Recoverable target ^IFn recovery-started-fn ^IFn recovery-finished-fn] (.addRecoveryListener target (reify RecoveryListener (^void handleRecoveryStarted [this ^Recoverable it] (recovery-started-fn it)) (^void handleRecovery [this ^Recoverable it] (recovery-finished-fn it)))))) (defn ^QueueRecoveryListener queue-recovery-listener "Reifies a new queue recovery listener that delegates to a Clojure function." [^IFn f] (reify QueueRecoveryListener (^void queueRecovered [this ^String old-name ^String new-name] (f old-name new-name)))) (defn on-queue-recovery "Called when server named queue gets a new name on recovery" [^com.novemberain.langohr.Connection conn ^IFn f] (.addQueueRecoveryListener (cast AutorecoveringConnection (.getDelegate conn)) (queue-recovery-listener f))) (defn thread-factory-from "Instantiates a java.util.concurrent.ThreadFactory that delegates #newThread to provided Clojure function" [f] (reify java.util.concurrent.ThreadFactory (^Thread newThread [this ^Runnable r] (f r)))) (defn exception-handler [{:keys [handle-connection-exception-fn handle-return-listener-exception-fn handle-flow-listener-exception-fn handle-confirm-listener-exception-fn handle-blocked-listener-exception-fn handle-consumer-exception-fn handle-connection-recovery-exception-fn handle-channel-recovery-exception-fn handle-topology-recovery-exception-fn]}] (proxy [ForgivingExceptionHandler] [] (handleUnexpectedConnectionDriverException [^Connection conn ^Throwable t] (when handle-connection-exception-fn (handle-connection-exception-fn conn t))) (handleReturnListenerException [^Channel ch ^Throwable t] (when handle-return-listener-exception-fn (handle-return-listener-exception-fn ch t))) (handleFlowListenerException [^Channel ch ^Throwable t] (when handle-flow-listener-exception-fn (handle-flow-listener-exception-fn ch t))) (handleConfirmListenerException [^Channel ch ^Throwable t] (when handle-confirm-listener-exception-fn (handle-confirm-listener-exception-fn ch t))) (handleBlockedListenerException [^Connection conn ^Throwable t] (when handle-blocked-listener-exception-fn (handle-blocked-listener-exception-fn conn t))) (handleConsumerException [^Channel ch ^Throwable t ^Consumer consumer ^String consumer-tag ^String method-name] (when handle-consumer-exception-fn (handle-consumer-exception-fn ch t consumer consumer-tag method-name))) (handleConnectionRecoveryException [^Connection conn ^Throwable t] (when handle-connection-recovery-exception-fn (handle-connection-recovery-exception-fn conn t))) (handleChannelRecoveryException [^Channel ch ^Throwable t] (when handle-channel-recovery-exception-fn (handle-channel-recovery-exception-fn ch t))) (handleTopologyRecoveryException [^Connection conn ^Channel ch ^TopologyRecoveryException t] (when handle-topology-recovery-exception-fn (handle-topology-recovery-exception-fn conn ch t))))) (defn normalize-settings "For setting maps that contain keys such as :host, :username, :vhost, returns the argument" [config] (let [{:keys [host hosts]} config hosts' (into #{} (remove nil? (or hosts #{host})))] (merge (settings-from (:uri config (System/getenv "RABBITMQ_URL"))) {:hosts hosts'} config))) (defn- platform-string [] (let [] (format "Clojure %s on %s %s" (clojure-version) (System/getProperty "java.vm.name") (System/getProperty "java.version")))) (def ^{:private true} client-properties {"product" "Langohr" "information" "See /" "platform" (platform-string) "capabilities" (get (AMQConnection/defaultClientProperties) "capabilities") "copyright" "Copyright (C) 2011-2020 Michael S. Klishin, Alex Petrov" "version" "5.3.0-SNAPSHOT"}) (defn- auth-mechanism->sasl-config [{:keys [authentication-mechanism]}] (case authentication-mechanism "PLAIN" DefaultSaslConfig/PLAIN "EXTERNAL" DefaultSaslConfig/EXTERNAL nil)) (defn- ^ConnectionFactory create-connection-factory "Creates connection factory from given attributes" [settings] (let [{:keys [host port username password vhost requested-heartbeat connection-timeout ssl ssl-context verify-hostname socket-factory sasl-config requested-channel-max thread-factory exception-handler connection-name update-client-properties] :or {requested-heartbeat ConnectionFactory/DEFAULT_HEARTBEAT connection-timeout ConnectionFactory/DEFAULT_CONNECTION_TIMEOUT requested-channel-max ConnectionFactory/DEFAULT_CHANNEL_MAX sasl-config (auth-mechanism->sasl-config settings)}} (normalize-settings settings) cf (ConnectionFactory.) final-port (if (and ssl (= port ConnectionFactory/DEFAULT_AMQP_PORT)) ConnectionFactory/DEFAULT_AMQP_OVER_SSL_PORT port) final-properties (cond-> client-properties connection-name (assoc "connection_name" connection-name) update-client-properties update-client-properties)] (when (or ssl (= port ConnectionFactory/DEFAULT_AMQP_OVER_SSL_PORT)) (.useSslProtocol cf)) (doto cf (.setClientProperties final-properties) (.setUsername username) (.setPassword password) (.setVirtualHost vhost) (.setHost host) (.setPort final-port) (.setRequestedHeartbeat requested-heartbeat) (.setConnectionTimeout connection-timeout) (.setRequestedChannelMax requested-channel-max)) (when sasl-config (.setSaslConfig cf sasl-config)) (when ssl-context (do (.useSslProtocol cf ^javax.net.ssl.SSLContext ssl-context) (.setPort cf final-port))) (when verify-hostname (.enableHostnameVerification cf)) (when thread-factory (.setThreadFactory cf ^ThreadFactory thread-factory)) (if exception-handler (.setExceptionHandler cf ^ExceptionHandler exception-handler) (.setExceptionHandler cf (ForgivingExceptionHandler.))) cf))
4dc447948986fb9f9f68b6a911d1fd93381486f9862bd7d67f742a2817e2965a
jyh/metaprl
itt_hoas_bterm.ml
doc <:doc< @module[Itt_hoas_bterm] The @tt[Itt_hoas_bterm] module defines the inductive type <<BTerm>> and establishes the appropriate induction rules for this type. @docoff ---------------------------------------------------------------- @begin[license] This file is part of MetaPRL, a modular, higher order logical framework that provides a logical programming environment for OCaml and other languages. See the file doc/htmlman/default.html or visit / for more information. Copyright (C) 2005-2006, MetaPRL Group, California Institute of Technology 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., 675 Mass Ave, Cambridge, MA 02139, USA. Author: Aleksey Kopylov @email{} Xin Yu @email{} @end[license] >> doc <:doc< @parents >> extends Itt_hoas_destterm extends Itt_image2 extends Itt_tunion extends Itt_subset doc docoff open Basic_tactics open Itt_equal open Itt_struct open Itt_squash open Itt_sqsimple open Itt_list2 open Itt_hoas_destterm let resource private select += intensional_wf_option, OptionAllow doc terms doc <:doc< We define the type <<BTerm>> as a recursive type. The << compatible_shapes{'depth; 'shape; 'subterms} >> predicate defines when a list of subterms << 'subterms >> is compatible with a specific operator. >> define unfold_compatible_shapes: compatible_shapes{'depth; 'shape; 'btl} <--> all2{'shape; 'btl; x, y. ('depth +@ 'x) = bdepth{'y} in int} (*private*) define unfold_dom: dom{'BT} <--> nat * nat + depth:nat * op: Operator * {subterms:list{'BT} | compatible_shapes{'depth;shape{'op};'subterms} } (*private*) define unfold_mk: mk{'x} <--> decide{'x; v.spread{'v;left,right. var{'left;'right}}; t.spread{'t;d,op,st. mk_bterm{'d;'op;'st}}} (*private*) define unfold_dest: dest{'bt} <--> dest_bterm{'bt; l,r. inl{('l,'r)}; d,op,ts. inr{('d,('op,'ts))}} (*private*) define unfold_Iter: Iter{'X} <--> Img{dom{'X};x.mk{'x}} (*private*) define unfold_BT: BT{'n} <--> ind{'n; void; X.Iter{'X}} define opaque const unfold_BTerm: BTerm <--> Union n:nat. BT{'n} define unfold_BTerm2 : BTerm{'i} <--> { e: BTerm | bdepth{'e} = 'i in nat } (*private*) define unfold_ndepth: ndepth{'t} <--> fix{ndepth. lambda{t. dest_bterm{'t; l,r.1; bdepth,op,subterms. list_max{map{x.'ndepth 'x;'subterms}}+@ 1 } }} 't doc docoff let fold_compatible_shapes = makeFoldC << compatible_shapes{'depth; 'shape; 'btl} >> unfold_compatible_shapes let fold_dom = makeFoldC << dom{'BT} >> unfold_dom let fold_mk = makeFoldC << mk{'x} >> unfold_mk let fold_dest = makeFoldC << dest{'bt} >> unfold_dest let fold_Iter = makeFoldC << Iter{'X} >> unfold_Iter let fold_BT = makeFoldC << BT{'n} >> unfold_BT let fold_BTerm = makeFoldC << BTerm >> unfold_BTerm let fold_BTerm2 = makeFoldC << BTerm{'i} >> unfold_BTerm2 let fold_ndepth = makeFoldC << ndepth{'t} >> unfold_ndepth doc <:doc< @rewrites Basic facts about @tt[compatible_shapes] >> interactive_rw compatible_shapes_nil_nil {| reduce |} : compatible_shapes{'depth; nil; nil} <--> "true" interactive_rw compatible_shapes_nil_cons {| reduce |} : compatible_shapes{'depth; nil; 'h2 :: 't2} <--> "false" interactive_rw compatible_shapes_cons_nil {| reduce |} : compatible_shapes{'depth; 'h1 :: 't1; nil} <--> "false" interactive_rw compatible_shapes_cons_cons {| reduce |} : compatible_shapes{'depth; 'h1 :: 't1; 'h2 :: 't2} <--> (('depth +@ 'h1) = bdepth{'h2} in int) & compatible_shapes{'depth; 't1; 't2} interactive_rw bt_reduce_base {| reduce |}: BT{0} <--> void interactive_rw bt_reduce_step {| reduce |}: 'n in nat --> BT{'n +@ 1} <--> Iter{BT{'n}} doc rules (*private*) interactive bt_elim_squash {| elim [] |} 'H : [wf] sequent { <H>; <J> >- 'n in nat } --> [base] sequent { <H>; <J>; l: nat; r:nat >- squash{'P[var{'l;'r}]} } --> [step] sequent { <H>; <J>; depth: nat; op:Operator; subterms:list{BT{'n}}; compatible_shapes{'depth; shape{'op}; 'subterms} >- squash{'P[mk_bterm{'depth; 'op; 'subterms}]} } --> sequent { <H>; t: BT{'n+@1}; <J> >- squash{'P['t]} } (*private*) interactive bt_elim_squash0 {| nth_hyp |} 'H : sequent { <H>; t: BT{0}; <J> >- 'P['t] } (*private*) interactive bt_wf_and_bdepth_univ {| intro[] |}: [wf] sequent { <H> >- 'n in nat } --> sequent { <H> >- BT{'n} in univ[l:l] & all t: BT{'n}. bdepth{'t} in nat } (*private*) interactive bt_wf_and_bdepth_wf {| intro [] |}: [wf] sequent{ <H> >- 'n in nat } --> sequent{ <H> >- BT{'n} Type & all t: BT{'n}. bdepth{'t} in nat } (*private*) interactive bt_univ {| intro[] |}: [wf] sequent { <H> >- 'n in nat } --> sequent { <H> >- BT{'n} in univ[l:l] } (*private*) interactive bt_wf {| intro [] |}: [wf] sequent{ <H> >- 'n in nat } --> sequent{ <H> >- BT{'n} Type } interactive bterm_univ {| intro[] |} : sequent { <H> >- BTerm in univ[l:l] } interactive bterm_wf {| intro [] |}: sequent{ <H> >- BTerm Type } (* Optimization *) interactive nil_in_list_bterm {| intro [] |}: sequent{ <H> >- nil in list{BTerm} } interactive bdepth_wf {| intro [] |}: [wf] sequent{ <H> >- 't in BTerm } --> sequent{ <H> >- bdepth{'t} in nat } interactive bdepth_wf_int {| intro [] |}: [wf] sequent{ <H> >- 't in BTerm } --> sequent{ <H> >- bdepth{'t} in int } interactive bdepth_wf_positive {| intro [] |}: [wf] sequent{ <H> >- 't in BTerm } --> sequent{ <H> >- bdepth{'t} >= 0 } interactive bterm2_wf {| intro [] |} : [wf] sequent { <H> >- 'n in nat } --> sequent { <H> >- BTerm{'n} Type } interactive bterm2_forward {| forward []; nth_hyp |} 'H : <:xrule< <H>; x: e in BTerm{d}; <J[x]>; e in BTerm; bdepth{e} = d in nat >- C[x] --> <H>; x: e in BTerm{d}; <J[x]> >- C[x] >> interactive bterm2_is_bterm {| nth_hyp |} 'H : sequent { <H>; x: BTerm{'d}; <J['x]> >- 'x in BTerm } interactive compatible_shapes_univ {| intro [] |} : [wf] sequent { <H> >- 'bdepth in nat } --> [wf] sequent { <H> >- 'shape in list{int} } --> [wf] sequent { <H> >- 'btl in list{BTerm} } --> sequent { <H> >- compatible_shapes{'bdepth; 'shape; 'btl} in univ[l:l] } interactive compatible_shapes_wf {| intro [] |} : [wf] sequent{ <H> >- 'bdepth in nat } --> [wf] sequent{ <H> >- 'shape in list{int} } --> [wf] sequent{ <H> >- 'btl in list{BTerm} } --> sequent{ <H> >- compatible_shapes{'bdepth; 'shape; 'btl} Type } (*private*) interactive bt_subtype_bterm {| intro[] |} : [wf] sequent { <H> >- 'n in nat} --> sequent { <H> >- BT{'n} subtype BTerm } (*private*) interactive dom_wf1 {| intro[] |}: [wf] sequent { <H> >- 'n in nat} --> sequent { <H> >- dom{BT{'n}} Type } interactive compatible_shapes_sqstable (*{| squash |}*) : [wf] sequent { <H> >- 'bdepth in int } --> [wf] sequent{ <H> >- 'shape in list{int} } --> [wf] sequent{ <H> >- 'btl in list{BTerm} } --> sequent{ <H> >- squash{compatible_shapes{'bdepth; 'shape; 'btl}} } --> sequent{ <H> >- compatible_shapes{'bdepth; 'shape; 'btl} } doc docoff let resource elim += [ << squash{compatible_shapes{'bdepth; 'shape; 'btl}} >>, wrap_elim_auto_ok (fun i -> unsquashHypGoalStable i thenAT (compatible_shapes_sqstable thenMT hypothesis i)); <<BTerm{'i}>>, wrap_elim_auto_ok thinT; <<nil in list{BTerm}>>, wrap_elim_auto_ok thinT; ] doc docon (*private*) interactive dom_wf {| intro [] |}: sequent{ <H> >- 'T subtype BTerm } --> sequent{ <H> >- dom{'T} Type } (*private*) interactive dom_monotone {| intro[] |}: sequent{ <H> >- 'T subtype 'S } --> sequent { <H> >- 'S subtype BTerm } --> sequent{ <H> >- dom{'T} subtype dom{'S} } (*private*) interactive dom_monotone_set {| intro[] |}: sequent{ <H> >- 'T subset 'S } --> sequent { <H> >- 'S subtype BTerm } --> sequent{ <H> >- dom{'T} subset dom{'S} } (*private*) interactive iter_monotone {| intro[] |}: sequent{ <H> >- 'T subtype 'S } --> sequent { <H> >- 'S subtype BTerm } --> sequent{ <H> >- Iter{'T} subtype Iter{'S} } (*private*) interactive bt_monotone {| intro [] |} : [wf] sequent{ <H> >- 'n in nat} --> sequent{ <H> >- BT{'n} subtype BT{'n+@1} } (*private*) interactive var_wf0 {| intro[] |}: sequent { <H> >- 'X subtype BTerm } --> [wf] sequent { <H> >- 'l in nat } --> [wf] sequent { <H> >- 'r in nat } --> sequent { <H> >- var{'l;'r} in Iter{'X} } interactive var_wf {| intro [] |}: [wf] sequent{ <H> >- 'l in nat } --> [wf] sequent{ <H> >- 'r in nat } --> sequent{ <H> >- var{'l;'r} in BTerm } (*private*) interactive mk_bterm_bt_wf {| intro [] |} : [wf] sequent{ <H> >- 'n in nat } --> [wf] sequent{ <H> >- 'depth in nat } --> [wf] sequent{ <H> >- 'op in Operator } --> [wf] sequent{ <H> >- 'subterms in list{BT{'n}} } --> sequent{ <H> >- compatible_shapes{'depth; shape{'op}; 'subterms} } --> sequent{ <H> >- mk_bterm{'depth; 'op; 'subterms} in BT{'n+@1} } interactive mk_bterm_wf {| intro [] |} : [wf] sequent{ <H> >- 'depth in nat } --> [wf] sequent{ <H> >- 'op in Operator } --> [wf] sequent{ <H> >- 'subterms in list{BTerm} } --> sequent{ <H> >- compatible_shapes{'depth; shape{'op}; 'subterms} } --> sequent{ <H> >- mk_bterm{'depth; 'op; 'subterms} in BTerm } interactive mk_bterm_wf2 {| intro [] |} : [wf] sequent{ <H> >- 'd1 = 'd2 in nat } --> [wf] sequent{ <H> >- 'op in Operator } --> [wf] sequent{ <H> >- 'subterms in list{BTerm} } --> sequent{ <H> >- compatible_shapes{'d1; shape{'op}; 'subterms} } --> sequent{ <H> >- mk_bterm{'d1; 'op; 'subterms} in BTerm{'d2} } interactive mk_term_wf {| intro [] |} : [wf] sequent{ <H> >- 'op in Operator } --> [wf] sequent{ <H> >- 'subterms in list{BTerm} } --> sequent{ <H> >- compatible_shapes{0; shape{'op}; 'subterms} } --> sequent{ <H> >- mk_term{'op; 'subterms} in BTerm } interactive mk_term_wf2 {| intro [] |} : [wf] sequent { <H> >- 'd = 0 in nat } --> [wf] sequent { <H> >- 'op in Operator } --> [wf] sequent { <H> >- 'subterms in list{BTerm} } --> sequent { <H> >- compatible_shapes{0; shape{'op}; 'subterms} } --> sequent { <H> >- mk_term{'op; 'subterms} in BTerm{'d} } (*private*) interactive bt_elim_squash2 {| elim [] |} 'H : [wf] sequent { <H>; <J> >- 'n in nat } --> [base] sequent { <H>; <J>; l: nat; r:nat >- squash{'P[var{'l;'r}]} } --> [step] sequent { <H>; 'n>0; <J>; depth: nat; op:Operator; subterms:list{BT{'n-@1}}; compatible_shapes{'depth;shape{'op};'subterms} >- squash{'P[mk_bterm{'depth;'op;'subterms}]} } --> sequent { <H>; t: BT{'n}; <J> >- squash{'P['t]} } interactive bterm_elim_squash {| elim [ThinFirst thinT] |} 'H : sequent { <H>; <J>; l: nat; r:nat >- squash{'P[var{'l;'r}]} } --> sequent { <H>; <J>; depth: nat; op:Operator; subterms:list{BTerm}; compatible_shapes{'depth;shape{'op};'subterms} >- squash{'P[mk_bterm{'depth;'op;'subterms}]} } --> sequent { <H>; t: BTerm; <J> >- squash{'P['t]} } interactive bterm_induction_squash1 'H : sequent { <H>; <J>; l: nat; r:nat >- squash{'P[var{'l;'r}]} } --> sequent { <H>; <J>; n: nat; depth: nat; op:Operator; subterms:list{BT{'n}}; compatible_shapes{'depth;shape{'op};'subterms}; all_list{'subterms;t.squash{'P['t]}} >- squash{'P[mk_bterm{'depth;'op;'subterms}]} } --> sequent { <H>; t: BTerm; <J> >- squash{'P['t]} } interactive_rw bind_eta {| reduce |} : 'bt in BTerm --> bdepth{'bt} > 0 --> bind{x. subst{'bt; 'x}} <--> 'bt interactive_rw bind_vec_eta {| reduce |} : 'n in nat --> 'bt in BTerm --> bdepth{'bt} >= 'n --> bind{'n; gamma. substl{'bt; 'gamma}} <--> 'bt interactive_rw subterms_lemma {| reduce |} : 'n in nat --> 'subterms in list{BTerm} --> all i:Index{'subterms}. bdepth{nth{'subterms;'i}} >= 'n --> map{bt. bind{'n; v. substl{'bt; 'v}};'subterms} <--> 'subterms interactive subterms_depth {| intro [] |} 'shape : [wf] sequent{ <H> >- 'bdepth in nat } --> [wf] sequent{ <H> >- 'shape in list{nat} } --> [wf] sequent{ <H> >- 'btl in list{BTerm} } --> sequent{ <H> >- compatible_shapes{'bdepth; 'shape; 'btl} } --> sequent{ <H> >- all i:Index{'btl}. bdepth{nth{'btl;'i}} >= 'bdepth } interactive subterms_depth2 {| intro [] |} 'shape : [wf] sequent{ <H> >- 'bdepth in nat } --> [wf] sequent{ <H> >- 'shape in list{nat} } --> [wf] sequent{ <H> >- 'btl in list{BTerm} } --> sequent{ <H> >- compatible_shapes{'bdepth; 'shape; 'btl} } --> sequent{ <H> >- all i:Index{'btl}. 'bdepth <= bdepth{nth{'btl;'i}} } interactive subterms_depth3 {| intro [] |} 'shape : [wf] sequent{ <H> >- 'bdepth in nat } --> [wf] sequent{ <H> >- 'shape in list{nat} } --> [wf] sequent{ <H> >- 'btl in list{BTerm} } --> sequent{ <H> >- compatible_shapes{'bdepth; 'shape; 'btl} } --> sequent{ <H> >- all_list{'btl; x. bdepth{'x} >= 'bdepth} } interactive_rw dest_bterm_mk_bterm2 {| reduce |} : 'n in nat --> 'op in Operator --> 'subterms in list{BTerm} --> compatible_shapes{'n;shape{'op};'subterms} --> dest_bterm{ mk_bterm{'n; 'op; 'subterms}; l,r.'var_case['l; 'r]; bdepth,op,subterms. 'op_case['bdepth; 'op; 'subterms] } <--> 'op_case['n; 'op; 'subterms] interactive_rw dest_bterm_mk_term {| reduce |} : 'op in Operator --> 'subterms in list --> dest_bterm{mk_term{'op; 'subterms}; l, r.'var_case['l; 'r]; bdepth, op, subterms. 'op_case['bdepth; 'op; 'subterms] } <--> 'op_case[0; 'op; 'subterms] interactive_rw mk_dest_reduce {| reduce |}: 't in BTerm --> mk{dest{'t}} <--> 't interactive_rw reduce_ndepth1 {| reduce |}: ('l in nat) --> ('r in nat) --> ndepth{var{'l;'r}} <--> 1 interactive_rw reduce_ndepth2 {| reduce |}: 'op in Operator --> 'bdepth in nat --> 'subs in list{BTerm} --> compatible_shapes{'bdepth;shape{'op};'subs} --> ndepth{mk_bterm{'bdepth;'op;'subs}} <--> list_max{map{x.ndepth{'x};'subs}}+@ 1 interactive iter_monotone_set {| intro[] |}: sequent{ <H> >- 'T subset 'S } --> sequent { <H> >- 'S subtype BTerm } --> sequent{ <H> >- Iter{'T} subset Iter{'S} } interactive bt_monotone_set {| intro[] |} : [wf] sequent { <H> >- 'n in nat} --> sequent { <H> >- BT{'n} subset BT{'n+@1} } interactive bt_monotone_set2 {| intro[] |} : [wf] sequent { <H> >- 'k in nat} --> [wf] sequent { <H> >- 'n in nat} --> sequent { <H> >- 'k <= 'n} --> sequent { <H> >- BT{'k} subset BT{'n} } interactive ndepth_wf {| intro[] |}: [wf] sequent{ <H> >- 't in BTerm } --> sequent { <H> >- ndepth{'t} in nat } interactive ndepth_correct {| intro[] |} : [wf] sequent{ <H> >- 't in BTerm } --> sequent { <H> >- 't in BT{ndepth{'t}} } interactive bt_subset_bterm {| intro [] |} : [wf] sequent{ <H> >- 'n in nat} --> sequent{ <H> >- BT{'n} subset BTerm } interactive dest_bterm_wf {| intro [] |}: [wf] sequent{ <H> >- 'bt in BTerm } --> [wf] sequent{ <H>; l:nat; r:nat >- 'var_case['l;'r] in 'T } --> [wf] sequent{ <H>; bdepth: nat; op:Operator; subterms:list{BTerm}; compatible_shapes{'bdepth;shape{'op};'subterms} >- 'op_case['bdepth; 'op; 'subterms] in 'T } --> sequent{ <H> >- dest_bterm{'bt; l,r.'var_case['l; 'r]; bdepth,op,subterms. 'op_case['bdepth; 'op; 'subterms]} in 'T } interactive dest_wf {| intro [] |}: [wf] sequent{ <H> >- 't in BTerm } --> sequent{ <H> >- dest{'t} in dom{BTerm} } interactive bterm_elim {| elim [] |} 'H : sequent { <H>; <J>; l: nat; r:nat >- 'P[var{'l;'r}] } --> sequent { <H>; <J>; bdepth: nat; op:Operator; subterms:list{BTerm}; compatible_shapes{'bdepth;shape{'op};'subterms} >- 'P[mk_bterm{'bdepth;'op;'subterms}] } --> sequent { <H>; t: BTerm; <J> >- 'P['t] } (* *** *) interactive dom_elim {| elim [] |} 'H : sequent { <H>; t: dom{'T}; u: nat*nat; <J[inl{'u}]> >- 'P[inl{'u}] } --> sequent { <H>; t: dom{'T}; v: depth:nat * op:Operator * {subterms:list{'T} | compatible_shapes{'depth;shape{'op};'subterms}}; <J[inr{'v}]> >- 'P[inr{'v}] } --> sequent { <H>; t: dom{'T}; <J['t]> >- 'P['t] } (*private*) interactive_rw dest_mk_reduce 'n : 'n in nat --> 't in dom{BT{'n}} --> dest{mk{'t}} <--> 't (*private*) interactive bt_elim1 {| elim [] |} 'H : [wf] sequent { <H>; t: BT{'n+@1}; <J['t]> >- 'n in nat } --> [step] sequent { <H>; x: dom{BT{'n}}; <J[mk{'x}]> >- 'P[mk{'x}] } --> sequent { <H>; t: BT{'n+@1}; <J['t]> >- 'P['t] } (*private*) interactive bterm_elim_squash1 {| elim [] |} 'H : sequent { <H>; t: BTerm; <J['t]>; l: nat; r:nat >- squash{'P[var{'l;'r}]} } --> sequent { <H>; t: BTerm; <J['t]>; depth: nat; op:Operator; subterms:list{BTerm}; compatible_shapes{'depth;shape{'op};'subterms} >- squash{'P[mk_bterm{'depth;'op;'subterms}]} } --> sequent { <H>; t: BTerm; <J['t]> >- squash{'P['t]} } (*private*) interactive bterm_elim2 {| elim [] |} 'H : sequent { <H>; t: BTerm; <J['t]>; l: nat; r:nat >- 'P[var{'l;'r}] } --> sequent { <H>; t: BTerm; <J['t]>; bdepth: nat; op:Operator; subterms:list{BTerm}; compatible_shapes{'bdepth;shape{'op};'subterms} >- 'P[mk_bterm{'bdepth;'op;'subterms}] } --> sequent { <H>; t: BTerm; <J['t]> >- 'P['t] } interactive bterm_elim3 'H : sequent { <H>; l: nat; r:nat; <J[var{'l; 'r}]> >- 'P[var{'l;'r}] } --> sequent { <H>; bdepth: nat; op: Operator; subterms: list{BTerm}; compatible_shapes{'bdepth; shape{'op}; 'subterms}; <J[mk_bterm{'bdepth; 'op; 'subterms}]> >- 'P[mk_bterm{'bdepth; 'op; 'subterms}] } --> sequent { <H>; t: BTerm; <J['t]> >- 'P['t] } doc <:doc< The following is the actual induction principle (the previous rules are just elimination rules). >> interactive bterm_induction {| elim [] |} 'H : [base] sequent { <H>; t: BTerm; <J['t]>; l: nat; r:nat >- 'P[var{'l;'r}] } --> [step] sequent { <H>; t: BTerm; <J['t]>; bdepth: nat; op: Operator; subterms: list{BTerm}; compatible_shapes{'bdepth; shape{'op}; 'subterms}; all_list{'subterms; t. 'P['t]} >- 'P[mk_bterm{'bdepth;'op;'subterms}] } --> sequent { <H>; t: BTerm; <J['t]> >- 'P['t] } interactive is_var_wf {| intro [] |}: [wf] sequent{ <H> >- 't in BTerm } --> sequent{ <H> >- is_var{'t} in bool } interactive subterms_wf1 {| intro [] |}: [wf] sequent{ <H> >- 't in BTerm } --> sequent{ <H> >- not{"assert"{is_var{'t}}} } --> sequent{ <H> >- subterms{'t} in list{BTerm} } doc docoff dform compatible_shapes_df: compatible_shapes{'bdepth;'op;'btl} = tt["compatible_shapes"] `"(" slot{'bdepth} `";" slot{'op} `";" slot{'btl} `")" dform bterm_df : BTerm = keyword["BTerm"] * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Fold up 's dummy term . * Fold up Aleksey's dummy term. *) define unfold_dummy : dummy <--> mk_term{it; nil} let fold_dummy = makeFoldC << dummy >> unfold_dummy (************************************************************************ * Conversions. *) interactive_rw reduce_bdepth_bind {| reduce |} : 'e in BTerm --> bdepth{'e} > 0 --> bdepth{subst{'e; dummy}} <--> bdepth{'e} -@ 1 (************************************************************************ * Eta-expansion. *) doc <:doc< When proving facts about specific terms and languages, we often need eta-expansion because the representation of specific terms with binders uses an explicit bind term. >> let bind_opname = opname_of_term << bind{x. 'e} >> let mk_bind_term = mk_dep1_term bind_opname let dest_bind_term = dest_dep1_term bind_opname let subst_opname = opname_of_term << subst{'e1; 'e2} >> let mk_subst_term = mk_dep0_dep0_term subst_opname let dest_subst_term = dest_dep0_dep0_term subst_opname let var_x = Lm_symbol.add "x" let eta_expand e t = if alpha_equal t e then (* The result term *) let x = maybe_new_var_set var_x (free_vars_set e) in let bind = mk_bind_term x (mk_subst_term e (mk_var_term x)) in foldC bind bind_eta else failC let etaExpandC e = termC (eta_expand e) (************************************************************************ * Squiggle equality. *) doc docoff interactive var_squiggle : [wf] sequent { <H> >- 'x in Var } --> [wf] sequent { <H> >- 'y in Var } --> [aux] sequent { <H> >- 'x = 'y in BTerm } --> sequent { <H> >- 'x ~ 'y } interactive var_neq_bterm {| elim |} 'H : [wf] sequent { <H>; <J[it]> >- 'l in nat } --> [wf] sequent { <H>; <J[it]> >- 'r in nat } --> [wf] sequent { <H>; <J[it]> >- 'depth in nat } --> [wf] sequent { <H>; <J[it]> >- 'op in Operator } --> sequent { <H>; u: var{'l; 'r} = mk_bterm{'depth; 'op; 'subterms} in BTerm; <J['u]> >- 'C['u] } interactive bterm_neq_var {| elim |} 'H : [wf] sequent { <H>; <J[it]> >- 'l in nat } --> [wf] sequent { <H>; <J[it]> >- 'r in nat } --> [wf] sequent { <H>; <J[it]> >- 'depth in nat } --> [wf] sequent { <H>; <J[it]> >- 'op in Operator } --> sequent { <H>; u: mk_bterm{'depth; 'op; 'subterms} = var{'l; 'r} in BTerm; <J['u]> >- 'C['u] } interactive subs_equal 'depth 'op : [wf] sequent { <H> >- 'depth in nat } --> [wf] sequent { <H> >- 'op in Operator } --> [wf] sequent { <H> >- 's1 in list{BTerm} } --> [wf] sequent { <H> >- 's2 in list{BTerm} } --> [aux] sequent { <H> >- compatible_shapes{'depth; shape{'op}; 's1} } --> [aux] sequent { <H> >- compatible_shapes{'depth; shape{'op}; 's2} } --> sequent { <H> >- mk_bterm{'depth; 'op; 's1} = mk_bterm{'depth; 'op; 's2} in BTerm } --> sequent { <H> >- 's1 = 's2 in list{BTerm} } doc <:doc< << BTerm >> has a trivial squiggle equality. >> interactive bterm_sqsimple {| intro []; sqsimple |} : sequent { <H> >- sqsimple{BTerm} } interactive bterm_sqsimple2 {| intro []; sqsimple |} : [wf] sequent { <H> >- 'n in nat } --> sequent { <H> >- sqsimple{BTerm{'n}} } doc <:doc< Define a Boolean equality (alpha equality) on BTerms. >> define unfold_beq_bterm : beq_bterm{'t1; 't2} <--> fix{beq_bterm. lambda{t1. lambda{t2. dest_bterm{'t1; l1, r1. dest_bterm{'t2; l2, r2. beq_var{var{'l1; 'r1}; var{'l2; 'r2}}; d1, o1, s1. bfalse}; d1, o1, s1. dest_bterm{'t2; l2, r2. bfalse; d2, o2, s2. band{beq_int{'d1; 'd2}; band{is_same_op{'o1; 'o2}; ball2{'s1; 's2; t1, t2. 'beq_bterm 't1 't2}}}}}}}} 't1 't2 doc docoff let fold_beq_bterm = makeFoldC << beq_bterm{'t1; 't2} >> unfold_beq_bterm doc docon interactive_rw reduce_beq_bterm_var_var {| reduce |} : 'l1 in nat --> 'r1 in nat --> 'l2 in nat --> 'r2 in nat --> beq_bterm{var{'l1; 'r1}; var{'l2; 'r2}} <--> beq_var{var{'l1; 'r1}; var{'l2; 'r2}} interactive_rw reduce_beq_bterm_var_bterm {| reduce |} : 'l in nat --> 'r in nat --> 'd in nat --> 'o in Operator --> 's in list --> beq_bterm{var{'l; 'r}; mk_bterm{'d; 'o; 's}} <--> bfalse interactive_rw reduce_beq_bterm_bterm_var {| reduce |} : 'l in nat --> 'r in nat --> 'd in nat --> 'o in Operator --> 's in list --> beq_bterm{mk_bterm{'d; 'o; 's}; var{'l; 'r}} <--> bfalse interactive_rw reduce_beq_bterm_bterm_bterm {| reduce |} : 'd1 in nat --> 'o1 in Operator --> 's1 in list{BTerm} --> 'd2 in nat --> 'o2 in Operator --> 's2 in list{BTerm} --> compatible_shapes{'d1; shape{'o1}; 's1} --> compatible_shapes{'d2; shape{'o2}; 's2} --> beq_bterm{mk_bterm{'d1; 'o1; 's1}; mk_bterm{'d2; 'o2; 's2}} <--> band{beq_int{'d1; 'd2}; band{is_same_op{'o1; 'o2}; ball2{'s1; 's2; t1, t2. beq_bterm{'t1; 't2}}}} interactive beq_bterm_wf {| intro [] |} : [wf] sequent { <H> >- 't1 in BTerm } --> [wf] sequent { <H> >- 't2 in BTerm } --> sequent { <H> >- beq_bterm{'t1; 't2} in bool } interactive beq_bterm_intro {| intro [] |} : sequent { <H> >- 't1 = 't2 in BTerm } --> sequent { <H> >- "assert"{beq_bterm{'t1; 't2}} } interactive beq_bterm_elim {| elim [] |} 'H : [wf] sequent { <H>; u: "assert"{beq_bterm{'t1; 't2}}; <J['u]> >- 't1 in BTerm } --> [wf] sequent { <H>; u: "assert"{beq_bterm{'t1; 't2}}; <J['u]> >- 't2 in BTerm } --> sequent { <H>; u: 't1 = 't2 in BTerm; <J['u]> >- 'C['u] } --> sequent { <H>; u: "assert"{beq_bterm{'t1; 't2}}; <J['u]> >- 'C['u] } (* * Equality on lists of BTerms. *) define unfold_beq_bterm_list : beq_bterm_list{'l1; 'l2} <--> ball2{'l1; 'l2; t1, t2. beq_bterm{'t1; 't2}} doc docoff let fold_beq_bterm_list = makeFoldC << beq_bterm_list{'l1; 'l2} >> unfold_beq_bterm_list doc docon interactive_rw reduce_beq_bterm_list_nil_nil {| reduce |} : beq_bterm_list{nil; nil} <--> btrue interactive_rw reduce_beq_bterm_list_nil_cons {| reduce |} : beq_bterm_list{nil; 'u::'v} <--> bfalse interactive_rw reduce_beq_bterm_list_cons_nil {| reduce |} : beq_bterm_list{'u::'v; nil} <--> bfalse interactive_rw reduce_beq_bterm_list_cons_cons {| reduce |} : beq_bterm_list{'u1::'v1; 'u2::'v2} <--> band{beq_bterm{'u1; 'u2}; beq_bterm_list{'v1; 'v2}} interactive beq_bterm_list_wf {| intro [] |} : [wf] sequent { <H> >- 'l1 in list{BTerm} } --> [wf] sequent { <H> >- 'l2 in list{BTerm} } --> sequent { <H> >- beq_bterm_list{'l1; 'l2} in bool } interactive beq_bterm_list_intro {| intro [] |} : sequent { <H> >- 't1 = 't2 in list{BTerm} } --> sequent { <H> >- "assert"{beq_bterm_list{'t1; 't2}} } interactive beq_bterm_list_elim {| elim [] |} 'H : [wf] sequent { <H>; u: "assert"{beq_bterm_list{'t1; 't2}}; <J['u]> >- 't1 in list{BTerm} } --> [wf] sequent { <H>; u: "assert"{beq_bterm_list{'t1; 't2}}; <J['u]> >- 't2 in list{BTerm} } --> sequent { <H>; u: 't1 = 't2 in list{BTerm}; <J['u]> >- 'C['u] } --> sequent { <H>; u: "assert"{beq_bterm_list{'t1; 't2}}; <J['u]> >- 'C['u] } (************************************************************************ * Forward-chaining. *) doc <:doc< Simple rules for forward chaining. >> interactive beq_bterm_forward {| forward |} 'H : [wf] sequent { <H>; <J[it]> >- 't1 in BTerm } --> [wf] sequent { <H>; <J[it]> >- 't2 in BTerm } --> sequent { <H>; <J[it]>; 't1 = 't2 in BTerm >- 'C[it] } --> sequent { <H>; x: "assert"{beq_bterm{'t1; 't2}}; <J['x]> >- 'C['x] } interactive beq_bterm_list_forward {| forward |} 'H : [wf] sequent { <H>; <J[it]> >- 't1 in list{BTerm} } --> [wf] sequent { <H>; <J[it]> >- 't2 in list{BTerm} } --> sequent { <H>; <J[it]>; 't1 = 't2 in list{BTerm} >- 'C[it] } --> sequent { <H>; x: "assert"{beq_bterm_list{'t1; 't2}}; <J['x]> >- 'C['x] } (************************************************************************ * Equality. *) doc <:doc< Equality reasoning. >> interactive mk_bterm_simple_eq {| intro [] |} : [wf] sequent{ <H> >- 'd1 = 'd2 in nat } --> [wf] sequent{ <H> >- 'op1 = 'op2 in Operator } --> [wf] sequent{ <H> >- 'subterms1 = 'subterms2 in list{BTerm} } --> sequent{ <H> >- compatible_shapes{'d1; shape{'op1}; 'subterms1} } --> sequent{ <H> >- mk_bterm{'d1; 'op1; 'subterms1} = mk_bterm{'d2; 'op2; 'subterms2} in BTerm } interactive mk_bterm_eq {| intro [] |} : [wf] sequent{ <H> >- 'd1 = 'd3 in nat } --> [wf] sequent{ <H> >- 'd2 = 'd3 in nat } --> [wf] sequent{ <H> >- 'op1 = 'op2 in Operator } --> [wf] sequent{ <H> >- 'subterms1 = 'subterms2 in list{BTerm} } --> sequent{ <H> >- compatible_shapes{'d1; shape{'op1}; 'subterms1} } --> sequent{ <H> >- mk_bterm{'d1; 'op1; 'subterms1} = mk_bterm{'d2; 'op2; 'subterms2} in BTerm{'d3} } interactive bterm_depth_eq {| nth_hyp |} : sequent{ <H> >- 't in BTerm{'d} } --> sequent{ <H> >- 'd = bdepth{'t} in int } interactive bterm_depth_ge {| nth_hyp |} : sequent{ <H> >- 't in BTerm{'d} } --> sequent{ <H> >- bdepth{'t} >= 'd } doc docoff let resource nth_hyp += [<<BTerm{'d}>>, << 'd = bdepth{!t} in int >>, wrap_nth_hyp_uncertain (fun i -> bterm_depth_eq thenT equalityAxiom i); <<BTerm{'d}>>, << bdepth{!t} >= 'd >>, wrap_nth_hyp_uncertain (fun i -> bterm_depth_ge thenT equalityAxiom i)] (************************************************************************ * Terms. *) let t_BTerm = << BTerm >> let opname_BTerm = opname_of_term t_BTerm let is_BTerm_term = is_no_subterms_term opname_BTerm let t_BTerm2 = << BTerm{'n} >> let opname_BTerm2 = opname_of_term t_BTerm2 let is_BTerm2_term = is_dep0_term opname_BTerm2
null
https://raw.githubusercontent.com/jyh/metaprl/51ba0bbbf409ecb7f96f5abbeb91902fdec47a19/theories/itt/reflection/experimental/itt_hoas_bterm.ml
ocaml
private private private private private private private private private private private private Optimization private private {| squash |} private private private private private private private private *** private private private private *********************************************************************** * Conversions. *********************************************************************** * Eta-expansion. The result term *********************************************************************** * Squiggle equality. * Equality on lists of BTerms. *********************************************************************** * Forward-chaining. *********************************************************************** * Equality. *********************************************************************** * Terms.
doc <:doc< @module[Itt_hoas_bterm] The @tt[Itt_hoas_bterm] module defines the inductive type <<BTerm>> and establishes the appropriate induction rules for this type. @docoff ---------------------------------------------------------------- @begin[license] This file is part of MetaPRL, a modular, higher order logical framework that provides a logical programming environment for OCaml and other languages. See the file doc/htmlman/default.html or visit / for more information. Copyright (C) 2005-2006, MetaPRL Group, California Institute of Technology 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., 675 Mass Ave, Cambridge, MA 02139, USA. Author: Aleksey Kopylov @email{} Xin Yu @email{} @end[license] >> doc <:doc< @parents >> extends Itt_hoas_destterm extends Itt_image2 extends Itt_tunion extends Itt_subset doc docoff open Basic_tactics open Itt_equal open Itt_struct open Itt_squash open Itt_sqsimple open Itt_list2 open Itt_hoas_destterm let resource private select += intensional_wf_option, OptionAllow doc terms doc <:doc< We define the type <<BTerm>> as a recursive type. The << compatible_shapes{'depth; 'shape; 'subterms} >> predicate defines when a list of subterms << 'subterms >> is compatible with a specific operator. >> define unfold_compatible_shapes: compatible_shapes{'depth; 'shape; 'btl} <--> all2{'shape; 'btl; x, y. ('depth +@ 'x) = bdepth{'y} in int} dom{'BT} <--> nat * nat + depth:nat * op: Operator * {subterms:list{'BT} | compatible_shapes{'depth;shape{'op};'subterms} } v.spread{'v;left,right. var{'left;'right}}; t.spread{'t;d,op,st. mk_bterm{'d;'op;'st}}} define opaque const unfold_BTerm: BTerm <--> Union n:nat. BT{'n} define unfold_BTerm2 : BTerm{'i} <--> { e: BTerm | bdepth{'e} = 'i in nat } ndepth{'t} <--> fix{ndepth. lambda{t. dest_bterm{'t; l,r.1; bdepth,op,subterms. list_max{map{x.'ndepth 'x;'subterms}}+@ 1 } }} 't doc docoff let fold_compatible_shapes = makeFoldC << compatible_shapes{'depth; 'shape; 'btl} >> unfold_compatible_shapes let fold_dom = makeFoldC << dom{'BT} >> unfold_dom let fold_mk = makeFoldC << mk{'x} >> unfold_mk let fold_dest = makeFoldC << dest{'bt} >> unfold_dest let fold_Iter = makeFoldC << Iter{'X} >> unfold_Iter let fold_BT = makeFoldC << BT{'n} >> unfold_BT let fold_BTerm = makeFoldC << BTerm >> unfold_BTerm let fold_BTerm2 = makeFoldC << BTerm{'i} >> unfold_BTerm2 let fold_ndepth = makeFoldC << ndepth{'t} >> unfold_ndepth doc <:doc< @rewrites Basic facts about @tt[compatible_shapes] >> interactive_rw compatible_shapes_nil_nil {| reduce |} : compatible_shapes{'depth; nil; nil} <--> "true" interactive_rw compatible_shapes_nil_cons {| reduce |} : compatible_shapes{'depth; nil; 'h2 :: 't2} <--> "false" interactive_rw compatible_shapes_cons_nil {| reduce |} : compatible_shapes{'depth; 'h1 :: 't1; nil} <--> "false" interactive_rw compatible_shapes_cons_cons {| reduce |} : compatible_shapes{'depth; 'h1 :: 't1; 'h2 :: 't2} <--> (('depth +@ 'h1) = bdepth{'h2} in int) & compatible_shapes{'depth; 't1; 't2} interactive_rw bt_reduce_base {| reduce |}: BT{0} <--> void interactive_rw bt_reduce_step {| reduce |}: 'n in nat --> BT{'n +@ 1} <--> Iter{BT{'n}} doc rules [wf] sequent { <H>; <J> >- 'n in nat } --> [base] sequent { <H>; <J>; l: nat; r:nat >- squash{'P[var{'l;'r}]} } --> [step] sequent { <H>; <J>; depth: nat; op:Operator; subterms:list{BT{'n}}; compatible_shapes{'depth; shape{'op}; 'subterms} >- squash{'P[mk_bterm{'depth; 'op; 'subterms}]} } --> sequent { <H>; t: BT{'n+@1}; <J> >- squash{'P['t]} } sequent { <H>; t: BT{0}; <J> >- 'P['t] } [wf] sequent { <H> >- 'n in nat } --> sequent { <H> >- BT{'n} in univ[l:l] & all t: BT{'n}. bdepth{'t} in nat } [wf] sequent{ <H> >- 'n in nat } --> sequent{ <H> >- BT{'n} Type & all t: BT{'n}. bdepth{'t} in nat } [wf] sequent { <H> >- 'n in nat } --> sequent { <H> >- BT{'n} in univ[l:l] } [wf] sequent{ <H> >- 'n in nat } --> sequent{ <H> >- BT{'n} Type } interactive bterm_univ {| intro[] |} : sequent { <H> >- BTerm in univ[l:l] } interactive bterm_wf {| intro [] |}: sequent{ <H> >- BTerm Type } interactive nil_in_list_bterm {| intro [] |}: sequent{ <H> >- nil in list{BTerm} } interactive bdepth_wf {| intro [] |}: [wf] sequent{ <H> >- 't in BTerm } --> sequent{ <H> >- bdepth{'t} in nat } interactive bdepth_wf_int {| intro [] |}: [wf] sequent{ <H> >- 't in BTerm } --> sequent{ <H> >- bdepth{'t} in int } interactive bdepth_wf_positive {| intro [] |}: [wf] sequent{ <H> >- 't in BTerm } --> sequent{ <H> >- bdepth{'t} >= 0 } interactive bterm2_wf {| intro [] |} : [wf] sequent { <H> >- 'n in nat } --> sequent { <H> >- BTerm{'n} Type } interactive bterm2_forward {| forward []; nth_hyp |} 'H : <:xrule< <H>; x: e in BTerm{d}; <J[x]>; e in BTerm; bdepth{e} = d in nat >- C[x] --> <H>; x: e in BTerm{d}; <J[x]> >- C[x] >> interactive bterm2_is_bterm {| nth_hyp |} 'H : sequent { <H>; x: BTerm{'d}; <J['x]> >- 'x in BTerm } interactive compatible_shapes_univ {| intro [] |} : [wf] sequent { <H> >- 'bdepth in nat } --> [wf] sequent { <H> >- 'shape in list{int} } --> [wf] sequent { <H> >- 'btl in list{BTerm} } --> sequent { <H> >- compatible_shapes{'bdepth; 'shape; 'btl} in univ[l:l] } interactive compatible_shapes_wf {| intro [] |} : [wf] sequent{ <H> >- 'bdepth in nat } --> [wf] sequent{ <H> >- 'shape in list{int} } --> [wf] sequent{ <H> >- 'btl in list{BTerm} } --> sequent{ <H> >- compatible_shapes{'bdepth; 'shape; 'btl} Type } [wf] sequent { <H> >- 'n in nat} --> sequent { <H> >- BT{'n} subtype BTerm } [wf] sequent { <H> >- 'n in nat} --> sequent { <H> >- dom{BT{'n}} Type } [wf] sequent { <H> >- 'bdepth in int } --> [wf] sequent{ <H> >- 'shape in list{int} } --> [wf] sequent{ <H> >- 'btl in list{BTerm} } --> sequent{ <H> >- squash{compatible_shapes{'bdepth; 'shape; 'btl}} } --> sequent{ <H> >- compatible_shapes{'bdepth; 'shape; 'btl} } doc docoff let resource elim += [ << squash{compatible_shapes{'bdepth; 'shape; 'btl}} >>, wrap_elim_auto_ok (fun i -> unsquashHypGoalStable i thenAT (compatible_shapes_sqstable thenMT hypothesis i)); <<BTerm{'i}>>, wrap_elim_auto_ok thinT; <<nil in list{BTerm}>>, wrap_elim_auto_ok thinT; ] doc docon sequent{ <H> >- 'T subtype BTerm } --> sequent{ <H> >- dom{'T} Type } sequent{ <H> >- 'T subtype 'S } --> sequent { <H> >- 'S subtype BTerm } --> sequent{ <H> >- dom{'T} subtype dom{'S} } sequent{ <H> >- 'T subset 'S } --> sequent { <H> >- 'S subtype BTerm } --> sequent{ <H> >- dom{'T} subset dom{'S} } sequent{ <H> >- 'T subtype 'S } --> sequent { <H> >- 'S subtype BTerm } --> sequent{ <H> >- Iter{'T} subtype Iter{'S} } [wf] sequent{ <H> >- 'n in nat} --> sequent{ <H> >- BT{'n} subtype BT{'n+@1} } sequent { <H> >- 'X subtype BTerm } --> [wf] sequent { <H> >- 'l in nat } --> [wf] sequent { <H> >- 'r in nat } --> sequent { <H> >- var{'l;'r} in Iter{'X} } interactive var_wf {| intro [] |}: [wf] sequent{ <H> >- 'l in nat } --> [wf] sequent{ <H> >- 'r in nat } --> sequent{ <H> >- var{'l;'r} in BTerm } [wf] sequent{ <H> >- 'n in nat } --> [wf] sequent{ <H> >- 'depth in nat } --> [wf] sequent{ <H> >- 'op in Operator } --> [wf] sequent{ <H> >- 'subterms in list{BT{'n}} } --> sequent{ <H> >- compatible_shapes{'depth; shape{'op}; 'subterms} } --> sequent{ <H> >- mk_bterm{'depth; 'op; 'subterms} in BT{'n+@1} } interactive mk_bterm_wf {| intro [] |} : [wf] sequent{ <H> >- 'depth in nat } --> [wf] sequent{ <H> >- 'op in Operator } --> [wf] sequent{ <H> >- 'subterms in list{BTerm} } --> sequent{ <H> >- compatible_shapes{'depth; shape{'op}; 'subterms} } --> sequent{ <H> >- mk_bterm{'depth; 'op; 'subterms} in BTerm } interactive mk_bterm_wf2 {| intro [] |} : [wf] sequent{ <H> >- 'd1 = 'd2 in nat } --> [wf] sequent{ <H> >- 'op in Operator } --> [wf] sequent{ <H> >- 'subterms in list{BTerm} } --> sequent{ <H> >- compatible_shapes{'d1; shape{'op}; 'subterms} } --> sequent{ <H> >- mk_bterm{'d1; 'op; 'subterms} in BTerm{'d2} } interactive mk_term_wf {| intro [] |} : [wf] sequent{ <H> >- 'op in Operator } --> [wf] sequent{ <H> >- 'subterms in list{BTerm} } --> sequent{ <H> >- compatible_shapes{0; shape{'op}; 'subterms} } --> sequent{ <H> >- mk_term{'op; 'subterms} in BTerm } interactive mk_term_wf2 {| intro [] |} : [wf] sequent { <H> >- 'd = 0 in nat } --> [wf] sequent { <H> >- 'op in Operator } --> [wf] sequent { <H> >- 'subterms in list{BTerm} } --> sequent { <H> >- compatible_shapes{0; shape{'op}; 'subterms} } --> sequent { <H> >- mk_term{'op; 'subterms} in BTerm{'d} } [wf] sequent { <H>; <J> >- 'n in nat } --> [base] sequent { <H>; <J>; l: nat; r:nat >- squash{'P[var{'l;'r}]} } --> [step] sequent { <H>; 'n>0; <J>; depth: nat; op:Operator; subterms:list{BT{'n-@1}}; compatible_shapes{'depth;shape{'op};'subterms} >- squash{'P[mk_bterm{'depth;'op;'subterms}]} } --> sequent { <H>; t: BT{'n}; <J> >- squash{'P['t]} } interactive bterm_elim_squash {| elim [ThinFirst thinT] |} 'H : sequent { <H>; <J>; l: nat; r:nat >- squash{'P[var{'l;'r}]} } --> sequent { <H>; <J>; depth: nat; op:Operator; subterms:list{BTerm}; compatible_shapes{'depth;shape{'op};'subterms} >- squash{'P[mk_bterm{'depth;'op;'subterms}]} } --> sequent { <H>; t: BTerm; <J> >- squash{'P['t]} } interactive bterm_induction_squash1 'H : sequent { <H>; <J>; l: nat; r:nat >- squash{'P[var{'l;'r}]} } --> sequent { <H>; <J>; n: nat; depth: nat; op:Operator; subterms:list{BT{'n}}; compatible_shapes{'depth;shape{'op};'subterms}; all_list{'subterms;t.squash{'P['t]}} >- squash{'P[mk_bterm{'depth;'op;'subterms}]} } --> sequent { <H>; t: BTerm; <J> >- squash{'P['t]} } interactive_rw bind_eta {| reduce |} : 'bt in BTerm --> bdepth{'bt} > 0 --> bind{x. subst{'bt; 'x}} <--> 'bt interactive_rw bind_vec_eta {| reduce |} : 'n in nat --> 'bt in BTerm --> bdepth{'bt} >= 'n --> bind{'n; gamma. substl{'bt; 'gamma}} <--> 'bt interactive_rw subterms_lemma {| reduce |} : 'n in nat --> 'subterms in list{BTerm} --> all i:Index{'subterms}. bdepth{nth{'subterms;'i}} >= 'n --> map{bt. bind{'n; v. substl{'bt; 'v}};'subterms} <--> 'subterms interactive subterms_depth {| intro [] |} 'shape : [wf] sequent{ <H> >- 'bdepth in nat } --> [wf] sequent{ <H> >- 'shape in list{nat} } --> [wf] sequent{ <H> >- 'btl in list{BTerm} } --> sequent{ <H> >- compatible_shapes{'bdepth; 'shape; 'btl} } --> sequent{ <H> >- all i:Index{'btl}. bdepth{nth{'btl;'i}} >= 'bdepth } interactive subterms_depth2 {| intro [] |} 'shape : [wf] sequent{ <H> >- 'bdepth in nat } --> [wf] sequent{ <H> >- 'shape in list{nat} } --> [wf] sequent{ <H> >- 'btl in list{BTerm} } --> sequent{ <H> >- compatible_shapes{'bdepth; 'shape; 'btl} } --> sequent{ <H> >- all i:Index{'btl}. 'bdepth <= bdepth{nth{'btl;'i}} } interactive subterms_depth3 {| intro [] |} 'shape : [wf] sequent{ <H> >- 'bdepth in nat } --> [wf] sequent{ <H> >- 'shape in list{nat} } --> [wf] sequent{ <H> >- 'btl in list{BTerm} } --> sequent{ <H> >- compatible_shapes{'bdepth; 'shape; 'btl} } --> sequent{ <H> >- all_list{'btl; x. bdepth{'x} >= 'bdepth} } interactive_rw dest_bterm_mk_bterm2 {| reduce |} : 'n in nat --> 'op in Operator --> 'subterms in list{BTerm} --> compatible_shapes{'n;shape{'op};'subterms} --> dest_bterm{ mk_bterm{'n; 'op; 'subterms}; l,r.'var_case['l; 'r]; bdepth,op,subterms. 'op_case['bdepth; 'op; 'subterms] } <--> 'op_case['n; 'op; 'subterms] interactive_rw dest_bterm_mk_term {| reduce |} : 'op in Operator --> 'subterms in list --> dest_bterm{mk_term{'op; 'subterms}; l, r.'var_case['l; 'r]; bdepth, op, subterms. 'op_case['bdepth; 'op; 'subterms] } <--> 'op_case[0; 'op; 'subterms] interactive_rw mk_dest_reduce {| reduce |}: 't in BTerm --> mk{dest{'t}} <--> 't interactive_rw reduce_ndepth1 {| reduce |}: ('l in nat) --> ('r in nat) --> ndepth{var{'l;'r}} <--> 1 interactive_rw reduce_ndepth2 {| reduce |}: 'op in Operator --> 'bdepth in nat --> 'subs in list{BTerm} --> compatible_shapes{'bdepth;shape{'op};'subs} --> ndepth{mk_bterm{'bdepth;'op;'subs}} <--> list_max{map{x.ndepth{'x};'subs}}+@ 1 interactive iter_monotone_set {| intro[] |}: sequent{ <H> >- 'T subset 'S } --> sequent { <H> >- 'S subtype BTerm } --> sequent{ <H> >- Iter{'T} subset Iter{'S} } interactive bt_monotone_set {| intro[] |} : [wf] sequent { <H> >- 'n in nat} --> sequent { <H> >- BT{'n} subset BT{'n+@1} } interactive bt_monotone_set2 {| intro[] |} : [wf] sequent { <H> >- 'k in nat} --> [wf] sequent { <H> >- 'n in nat} --> sequent { <H> >- 'k <= 'n} --> sequent { <H> >- BT{'k} subset BT{'n} } interactive ndepth_wf {| intro[] |}: [wf] sequent{ <H> >- 't in BTerm } --> sequent { <H> >- ndepth{'t} in nat } interactive ndepth_correct {| intro[] |} : [wf] sequent{ <H> >- 't in BTerm } --> sequent { <H> >- 't in BT{ndepth{'t}} } interactive bt_subset_bterm {| intro [] |} : [wf] sequent{ <H> >- 'n in nat} --> sequent{ <H> >- BT{'n} subset BTerm } interactive dest_bterm_wf {| intro [] |}: [wf] sequent{ <H> >- 'bt in BTerm } --> [wf] sequent{ <H>; l:nat; r:nat >- 'var_case['l;'r] in 'T } --> [wf] sequent{ <H>; bdepth: nat; op:Operator; subterms:list{BTerm}; compatible_shapes{'bdepth;shape{'op};'subterms} >- 'op_case['bdepth; 'op; 'subterms] in 'T } --> sequent{ <H> >- dest_bterm{'bt; l,r.'var_case['l; 'r]; bdepth,op,subterms. 'op_case['bdepth; 'op; 'subterms]} in 'T } interactive dest_wf {| intro [] |}: [wf] sequent{ <H> >- 't in BTerm } --> sequent{ <H> >- dest{'t} in dom{BTerm} } interactive bterm_elim {| elim [] |} 'H : sequent { <H>; <J>; l: nat; r:nat >- 'P[var{'l;'r}] } --> sequent { <H>; <J>; bdepth: nat; op:Operator; subterms:list{BTerm}; compatible_shapes{'bdepth;shape{'op};'subterms} >- 'P[mk_bterm{'bdepth;'op;'subterms}] } --> sequent { <H>; t: BTerm; <J> >- 'P['t] } interactive dom_elim {| elim [] |} 'H : sequent { <H>; t: dom{'T}; u: nat*nat; <J[inl{'u}]> >- 'P[inl{'u}] } --> sequent { <H>; t: dom{'T}; v: depth:nat * op:Operator * {subterms:list{'T} | compatible_shapes{'depth;shape{'op};'subterms}}; <J[inr{'v}]> >- 'P[inr{'v}] } --> sequent { <H>; t: dom{'T}; <J['t]> >- 'P['t] } 'n in nat --> 't in dom{BT{'n}} --> dest{mk{'t}} <--> 't [wf] sequent { <H>; t: BT{'n+@1}; <J['t]> >- 'n in nat } --> [step] sequent { <H>; x: dom{BT{'n}}; <J[mk{'x}]> >- 'P[mk{'x}] } --> sequent { <H>; t: BT{'n+@1}; <J['t]> >- 'P['t] } sequent { <H>; t: BTerm; <J['t]>; l: nat; r:nat >- squash{'P[var{'l;'r}]} } --> sequent { <H>; t: BTerm; <J['t]>; depth: nat; op:Operator; subterms:list{BTerm}; compatible_shapes{'depth;shape{'op};'subterms} >- squash{'P[mk_bterm{'depth;'op;'subterms}]} } --> sequent { <H>; t: BTerm; <J['t]> >- squash{'P['t]} } sequent { <H>; t: BTerm; <J['t]>; l: nat; r:nat >- 'P[var{'l;'r}] } --> sequent { <H>; t: BTerm; <J['t]>; bdepth: nat; op:Operator; subterms:list{BTerm}; compatible_shapes{'bdepth;shape{'op};'subterms} >- 'P[mk_bterm{'bdepth;'op;'subterms}] } --> sequent { <H>; t: BTerm; <J['t]> >- 'P['t] } interactive bterm_elim3 'H : sequent { <H>; l: nat; r:nat; <J[var{'l; 'r}]> >- 'P[var{'l;'r}] } --> sequent { <H>; bdepth: nat; op: Operator; subterms: list{BTerm}; compatible_shapes{'bdepth; shape{'op}; 'subterms}; <J[mk_bterm{'bdepth; 'op; 'subterms}]> >- 'P[mk_bterm{'bdepth; 'op; 'subterms}] } --> sequent { <H>; t: BTerm; <J['t]> >- 'P['t] } doc <:doc< The following is the actual induction principle (the previous rules are just elimination rules). >> interactive bterm_induction {| elim [] |} 'H : [base] sequent { <H>; t: BTerm; <J['t]>; l: nat; r:nat >- 'P[var{'l;'r}] } --> [step] sequent { <H>; t: BTerm; <J['t]>; bdepth: nat; op: Operator; subterms: list{BTerm}; compatible_shapes{'bdepth; shape{'op}; 'subterms}; all_list{'subterms; t. 'P['t]} >- 'P[mk_bterm{'bdepth;'op;'subterms}] } --> sequent { <H>; t: BTerm; <J['t]> >- 'P['t] } interactive is_var_wf {| intro [] |}: [wf] sequent{ <H> >- 't in BTerm } --> sequent{ <H> >- is_var{'t} in bool } interactive subterms_wf1 {| intro [] |}: [wf] sequent{ <H> >- 't in BTerm } --> sequent{ <H> >- not{"assert"{is_var{'t}}} } --> sequent{ <H> >- subterms{'t} in list{BTerm} } doc docoff dform compatible_shapes_df: compatible_shapes{'bdepth;'op;'btl} = tt["compatible_shapes"] `"(" slot{'bdepth} `";" slot{'op} `";" slot{'btl} `")" dform bterm_df : BTerm = keyword["BTerm"] * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Fold up 's dummy term . * Fold up Aleksey's dummy term. *) define unfold_dummy : dummy <--> mk_term{it; nil} let fold_dummy = makeFoldC << dummy >> unfold_dummy interactive_rw reduce_bdepth_bind {| reduce |} : 'e in BTerm --> bdepth{'e} > 0 --> bdepth{subst{'e; dummy}} <--> bdepth{'e} -@ 1 doc <:doc< When proving facts about specific terms and languages, we often need eta-expansion because the representation of specific terms with binders uses an explicit bind term. >> let bind_opname = opname_of_term << bind{x. 'e} >> let mk_bind_term = mk_dep1_term bind_opname let dest_bind_term = dest_dep1_term bind_opname let subst_opname = opname_of_term << subst{'e1; 'e2} >> let mk_subst_term = mk_dep0_dep0_term subst_opname let dest_subst_term = dest_dep0_dep0_term subst_opname let var_x = Lm_symbol.add "x" let eta_expand e t = if alpha_equal t e then let x = maybe_new_var_set var_x (free_vars_set e) in let bind = mk_bind_term x (mk_subst_term e (mk_var_term x)) in foldC bind bind_eta else failC let etaExpandC e = termC (eta_expand e) doc docoff interactive var_squiggle : [wf] sequent { <H> >- 'x in Var } --> [wf] sequent { <H> >- 'y in Var } --> [aux] sequent { <H> >- 'x = 'y in BTerm } --> sequent { <H> >- 'x ~ 'y } interactive var_neq_bterm {| elim |} 'H : [wf] sequent { <H>; <J[it]> >- 'l in nat } --> [wf] sequent { <H>; <J[it]> >- 'r in nat } --> [wf] sequent { <H>; <J[it]> >- 'depth in nat } --> [wf] sequent { <H>; <J[it]> >- 'op in Operator } --> sequent { <H>; u: var{'l; 'r} = mk_bterm{'depth; 'op; 'subterms} in BTerm; <J['u]> >- 'C['u] } interactive bterm_neq_var {| elim |} 'H : [wf] sequent { <H>; <J[it]> >- 'l in nat } --> [wf] sequent { <H>; <J[it]> >- 'r in nat } --> [wf] sequent { <H>; <J[it]> >- 'depth in nat } --> [wf] sequent { <H>; <J[it]> >- 'op in Operator } --> sequent { <H>; u: mk_bterm{'depth; 'op; 'subterms} = var{'l; 'r} in BTerm; <J['u]> >- 'C['u] } interactive subs_equal 'depth 'op : [wf] sequent { <H> >- 'depth in nat } --> [wf] sequent { <H> >- 'op in Operator } --> [wf] sequent { <H> >- 's1 in list{BTerm} } --> [wf] sequent { <H> >- 's2 in list{BTerm} } --> [aux] sequent { <H> >- compatible_shapes{'depth; shape{'op}; 's1} } --> [aux] sequent { <H> >- compatible_shapes{'depth; shape{'op}; 's2} } --> sequent { <H> >- mk_bterm{'depth; 'op; 's1} = mk_bterm{'depth; 'op; 's2} in BTerm } --> sequent { <H> >- 's1 = 's2 in list{BTerm} } doc <:doc< << BTerm >> has a trivial squiggle equality. >> interactive bterm_sqsimple {| intro []; sqsimple |} : sequent { <H> >- sqsimple{BTerm} } interactive bterm_sqsimple2 {| intro []; sqsimple |} : [wf] sequent { <H> >- 'n in nat } --> sequent { <H> >- sqsimple{BTerm{'n}} } doc <:doc< Define a Boolean equality (alpha equality) on BTerms. >> define unfold_beq_bterm : beq_bterm{'t1; 't2} <--> fix{beq_bterm. lambda{t1. lambda{t2. dest_bterm{'t1; l1, r1. dest_bterm{'t2; l2, r2. beq_var{var{'l1; 'r1}; var{'l2; 'r2}}; d1, o1, s1. bfalse}; d1, o1, s1. dest_bterm{'t2; l2, r2. bfalse; d2, o2, s2. band{beq_int{'d1; 'd2}; band{is_same_op{'o1; 'o2}; ball2{'s1; 's2; t1, t2. 'beq_bterm 't1 't2}}}}}}}} 't1 't2 doc docoff let fold_beq_bterm = makeFoldC << beq_bterm{'t1; 't2} >> unfold_beq_bterm doc docon interactive_rw reduce_beq_bterm_var_var {| reduce |} : 'l1 in nat --> 'r1 in nat --> 'l2 in nat --> 'r2 in nat --> beq_bterm{var{'l1; 'r1}; var{'l2; 'r2}} <--> beq_var{var{'l1; 'r1}; var{'l2; 'r2}} interactive_rw reduce_beq_bterm_var_bterm {| reduce |} : 'l in nat --> 'r in nat --> 'd in nat --> 'o in Operator --> 's in list --> beq_bterm{var{'l; 'r}; mk_bterm{'d; 'o; 's}} <--> bfalse interactive_rw reduce_beq_bterm_bterm_var {| reduce |} : 'l in nat --> 'r in nat --> 'd in nat --> 'o in Operator --> 's in list --> beq_bterm{mk_bterm{'d; 'o; 's}; var{'l; 'r}} <--> bfalse interactive_rw reduce_beq_bterm_bterm_bterm {| reduce |} : 'd1 in nat --> 'o1 in Operator --> 's1 in list{BTerm} --> 'd2 in nat --> 'o2 in Operator --> 's2 in list{BTerm} --> compatible_shapes{'d1; shape{'o1}; 's1} --> compatible_shapes{'d2; shape{'o2}; 's2} --> beq_bterm{mk_bterm{'d1; 'o1; 's1}; mk_bterm{'d2; 'o2; 's2}} <--> band{beq_int{'d1; 'd2}; band{is_same_op{'o1; 'o2}; ball2{'s1; 's2; t1, t2. beq_bterm{'t1; 't2}}}} interactive beq_bterm_wf {| intro [] |} : [wf] sequent { <H> >- 't1 in BTerm } --> [wf] sequent { <H> >- 't2 in BTerm } --> sequent { <H> >- beq_bterm{'t1; 't2} in bool } interactive beq_bterm_intro {| intro [] |} : sequent { <H> >- 't1 = 't2 in BTerm } --> sequent { <H> >- "assert"{beq_bterm{'t1; 't2}} } interactive beq_bterm_elim {| elim [] |} 'H : [wf] sequent { <H>; u: "assert"{beq_bterm{'t1; 't2}}; <J['u]> >- 't1 in BTerm } --> [wf] sequent { <H>; u: "assert"{beq_bterm{'t1; 't2}}; <J['u]> >- 't2 in BTerm } --> sequent { <H>; u: 't1 = 't2 in BTerm; <J['u]> >- 'C['u] } --> sequent { <H>; u: "assert"{beq_bterm{'t1; 't2}}; <J['u]> >- 'C['u] } define unfold_beq_bterm_list : beq_bterm_list{'l1; 'l2} <--> ball2{'l1; 'l2; t1, t2. beq_bterm{'t1; 't2}} doc docoff let fold_beq_bterm_list = makeFoldC << beq_bterm_list{'l1; 'l2} >> unfold_beq_bterm_list doc docon interactive_rw reduce_beq_bterm_list_nil_nil {| reduce |} : beq_bterm_list{nil; nil} <--> btrue interactive_rw reduce_beq_bterm_list_nil_cons {| reduce |} : beq_bterm_list{nil; 'u::'v} <--> bfalse interactive_rw reduce_beq_bterm_list_cons_nil {| reduce |} : beq_bterm_list{'u::'v; nil} <--> bfalse interactive_rw reduce_beq_bterm_list_cons_cons {| reduce |} : beq_bterm_list{'u1::'v1; 'u2::'v2} <--> band{beq_bterm{'u1; 'u2}; beq_bterm_list{'v1; 'v2}} interactive beq_bterm_list_wf {| intro [] |} : [wf] sequent { <H> >- 'l1 in list{BTerm} } --> [wf] sequent { <H> >- 'l2 in list{BTerm} } --> sequent { <H> >- beq_bterm_list{'l1; 'l2} in bool } interactive beq_bterm_list_intro {| intro [] |} : sequent { <H> >- 't1 = 't2 in list{BTerm} } --> sequent { <H> >- "assert"{beq_bterm_list{'t1; 't2}} } interactive beq_bterm_list_elim {| elim [] |} 'H : [wf] sequent { <H>; u: "assert"{beq_bterm_list{'t1; 't2}}; <J['u]> >- 't1 in list{BTerm} } --> [wf] sequent { <H>; u: "assert"{beq_bterm_list{'t1; 't2}}; <J['u]> >- 't2 in list{BTerm} } --> sequent { <H>; u: 't1 = 't2 in list{BTerm}; <J['u]> >- 'C['u] } --> sequent { <H>; u: "assert"{beq_bterm_list{'t1; 't2}}; <J['u]> >- 'C['u] } doc <:doc< Simple rules for forward chaining. >> interactive beq_bterm_forward {| forward |} 'H : [wf] sequent { <H>; <J[it]> >- 't1 in BTerm } --> [wf] sequent { <H>; <J[it]> >- 't2 in BTerm } --> sequent { <H>; <J[it]>; 't1 = 't2 in BTerm >- 'C[it] } --> sequent { <H>; x: "assert"{beq_bterm{'t1; 't2}}; <J['x]> >- 'C['x] } interactive beq_bterm_list_forward {| forward |} 'H : [wf] sequent { <H>; <J[it]> >- 't1 in list{BTerm} } --> [wf] sequent { <H>; <J[it]> >- 't2 in list{BTerm} } --> sequent { <H>; <J[it]>; 't1 = 't2 in list{BTerm} >- 'C[it] } --> sequent { <H>; x: "assert"{beq_bterm_list{'t1; 't2}}; <J['x]> >- 'C['x] } doc <:doc< Equality reasoning. >> interactive mk_bterm_simple_eq {| intro [] |} : [wf] sequent{ <H> >- 'd1 = 'd2 in nat } --> [wf] sequent{ <H> >- 'op1 = 'op2 in Operator } --> [wf] sequent{ <H> >- 'subterms1 = 'subterms2 in list{BTerm} } --> sequent{ <H> >- compatible_shapes{'d1; shape{'op1}; 'subterms1} } --> sequent{ <H> >- mk_bterm{'d1; 'op1; 'subterms1} = mk_bterm{'d2; 'op2; 'subterms2} in BTerm } interactive mk_bterm_eq {| intro [] |} : [wf] sequent{ <H> >- 'd1 = 'd3 in nat } --> [wf] sequent{ <H> >- 'd2 = 'd3 in nat } --> [wf] sequent{ <H> >- 'op1 = 'op2 in Operator } --> [wf] sequent{ <H> >- 'subterms1 = 'subterms2 in list{BTerm} } --> sequent{ <H> >- compatible_shapes{'d1; shape{'op1}; 'subterms1} } --> sequent{ <H> >- mk_bterm{'d1; 'op1; 'subterms1} = mk_bterm{'d2; 'op2; 'subterms2} in BTerm{'d3} } interactive bterm_depth_eq {| nth_hyp |} : sequent{ <H> >- 't in BTerm{'d} } --> sequent{ <H> >- 'd = bdepth{'t} in int } interactive bterm_depth_ge {| nth_hyp |} : sequent{ <H> >- 't in BTerm{'d} } --> sequent{ <H> >- bdepth{'t} >= 'd } doc docoff let resource nth_hyp += [<<BTerm{'d}>>, << 'd = bdepth{!t} in int >>, wrap_nth_hyp_uncertain (fun i -> bterm_depth_eq thenT equalityAxiom i); <<BTerm{'d}>>, << bdepth{!t} >= 'd >>, wrap_nth_hyp_uncertain (fun i -> bterm_depth_ge thenT equalityAxiom i)] let t_BTerm = << BTerm >> let opname_BTerm = opname_of_term t_BTerm let is_BTerm_term = is_no_subterms_term opname_BTerm let t_BTerm2 = << BTerm{'n} >> let opname_BTerm2 = opname_of_term t_BTerm2 let is_BTerm2_term = is_dep0_term opname_BTerm2
05b2652f39b71d3a4b8ad163d49fc66746cb7410edb8a588d270ce6517c2de80
zack-bitcoin/amoveo
blacklist_peer.erl
-module(blacklist_peer). -behaviour(gen_server). -export([start_link/0,code_change/3,handle_call/3,handle_cast/2,handle_info/2,init/1,terminate/2, add/1, check/1, remove/1]). -define(Limit, 300). init(ok) -> {ok, dict:new()}. start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, ok, []). code_change(_OldVsn, State, _Extra) -> {ok, State}. terminate(_, _) -> io:format("died!"), ok. handle_info(_, X) -> {noreply, X}. handle_cast({remove, Peer}, X) -> X2 = case dict:find(Peer, X) of error -> X; {ok, _} -> dict:erase(Peer, X) end, {noreply, X2}; handle_cast({add, Peer, Now}, X) -> X2 = dict:store(Peer, Now, X), {noreply, X2}; handle_cast(_, X) -> {noreply, X}. handle_call({check, Peer}, _From, X) -> A = case dict:find(Peer, X) of error -> false; {ok, N} -> N2 = now(), D = time_diff(N2, N), B = D < ?Limit, B end, {reply, A, X}; handle_call(_, _From, X) -> {reply, X, X}. remove(Peer) -> {{_,_,_,_},_} = Peer, gen_server:cast(?MODULE, {remove, Peer}). add(Peer) -> {{_,_,_,_},_} = Peer, gen_server:cast(?MODULE, {add, Peer, now()}). check(Peer) -> gen_server:call(?MODULE, {check, Peer}). time_diff({N1, N2, _N3}, {O1, O2, _O3}) -> A1 = N1 - O1, A2 = N2 - O2, (A1 * 1000000) + A2.
null
https://raw.githubusercontent.com/zack-bitcoin/amoveo/257f3e8cc07f1bae9df1a7252b8bc67a0dad3262/apps/amoveo_http/src/blacklist_peer.erl
erlang
-module(blacklist_peer). -behaviour(gen_server). -export([start_link/0,code_change/3,handle_call/3,handle_cast/2,handle_info/2,init/1,terminate/2, add/1, check/1, remove/1]). -define(Limit, 300). init(ok) -> {ok, dict:new()}. start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, ok, []). code_change(_OldVsn, State, _Extra) -> {ok, State}. terminate(_, _) -> io:format("died!"), ok. handle_info(_, X) -> {noreply, X}. handle_cast({remove, Peer}, X) -> X2 = case dict:find(Peer, X) of error -> X; {ok, _} -> dict:erase(Peer, X) end, {noreply, X2}; handle_cast({add, Peer, Now}, X) -> X2 = dict:store(Peer, Now, X), {noreply, X2}; handle_cast(_, X) -> {noreply, X}. handle_call({check, Peer}, _From, X) -> A = case dict:find(Peer, X) of error -> false; {ok, N} -> N2 = now(), D = time_diff(N2, N), B = D < ?Limit, B end, {reply, A, X}; handle_call(_, _From, X) -> {reply, X, X}. remove(Peer) -> {{_,_,_,_},_} = Peer, gen_server:cast(?MODULE, {remove, Peer}). add(Peer) -> {{_,_,_,_},_} = Peer, gen_server:cast(?MODULE, {add, Peer, now()}). check(Peer) -> gen_server:call(?MODULE, {check, Peer}). time_diff({N1, N2, _N3}, {O1, O2, _O3}) -> A1 = N1 - O1, A2 = N2 - O2, (A1 * 1000000) + A2.
e71123501f8b947c767ad283158c421894d38f202ca2bcbca677ffdc8dbf20cc
leo-project/leo_object_storage
leo_compact_fsm_worker.erl
%%====================================================================== %% %% Leo Object Storage %% Copyright ( c ) 2012 - 2017 Rakuten , Inc. %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% @doc FSM of the data - compaction worker , which handles removing unnecessary objects from a object container . -project/leo_object_storage/blob/master/src/leo_compact_fsm_controller.erl %% @end %%====================================================================== -module(leo_compact_fsm_worker). -author('Yosuke Hara'). -behaviour(gen_fsm). -include("leo_object_storage.hrl"). -include_lib("leo_logger/include/leo_logger.hrl"). -include_lib("eunit/include/eunit.hrl"). %% API -export([start_link/5, stop/1]). -export([run/3, run/5, forced_run/3, suspend/1, resume/1, state/2, increase/1, decrease/1 ]). %% gen_fsm callbacks -export([init/1, handle_event/3, handle_sync_event/4, handle_info/3, terminate/3, code_change/4, format_status/2]). -export([idling/2, idling/3, running/2, running/3, suspending/2, suspending/3]). -define(DEF_TIMEOUT, timer:seconds(30)). %%==================================================================== %% API %%==================================================================== %% @doc Creates a gen_fsm process as part of a supervision tree -spec(start_link(Id, ObjStorageId, ObjStorageIdRead, MetaDBId, LoggerId) -> {ok, pid()} | {error, any()} when Id::atom(), ObjStorageId::atom(), ObjStorageIdRead::atom(), MetaDBId::atom(), LoggerId::atom()). start_link(Id, ObjStorageId, ObjStorageIdRead, MetaDBId, LoggerId) -> gen_fsm:start_link({local, Id}, ?MODULE, [Id, ObjStorageId, ObjStorageIdRead, MetaDBId, LoggerId], []). %% @doc Stop this server %% -spec(stop(Id) -> ok when Id::atom()). stop(Id) -> error_logger:info_msg("~p,~p,~p,~p~n", [{module, ?MODULE_STRING}, {function, "stop/1"}, {line, ?LINE}, {body, Id}]), gen_fsm:sync_send_all_state_event(Id, stop, ?DEF_TIMEOUT). %% @doc Run the process %% -spec(run(Id, IsDiagnosing, IsRecovering) -> ok | {error, any()} when Id::atom(), IsDiagnosing::boolean(), IsRecovering::boolean()). run(Id, IsDiagnosing, IsRecovering) -> gen_fsm:send_event(Id, #compaction_event_info{event = ?EVENT_RUN, is_diagnosing = IsDiagnosing, is_recovering = IsRecovering, is_forced_run = false}). -spec(run(Id, ControllerPid, IsDiagnosing, IsRecovering, CallbackFun) -> ok | {error, any()} when Id::atom(), ControllerPid::pid(), IsDiagnosing::boolean(), IsRecovering::boolean(), CallbackFun::function()). run(Id, ControllerPid, IsDiagnosing, IsRecovering, CallbackFun) -> gen_fsm:sync_send_event(Id, #compaction_event_info{event = ?EVENT_RUN, controller_pid = ControllerPid, is_diagnosing = IsDiagnosing, is_recovering = IsRecovering, is_forced_run = false, callback = CallbackFun}, ?DEF_TIMEOUT). -spec(forced_run(Id, IsDiagnosing, IsRecovering) -> ok | {error, any()} when Id::atom(), IsDiagnosing::boolean(), IsRecovering::boolean()). forced_run(Id, IsDiagnosing, IsRecovering) -> gen_fsm:send_event(Id, #compaction_event_info{event = ?EVENT_RUN, is_diagnosing = IsDiagnosing, is_recovering = IsRecovering, is_forced_run = true}). %% @doc Retrieve an object from the object-storage %% -spec(suspend(Id) -> ok | {error, any()} when Id::atom()). suspend(Id) -> gen_fsm:send_event(Id, #compaction_event_info{event = ?EVENT_SUSPEND}). %% @doc Remove an object from the object-storage - (logical-delete) %% -spec(resume(Id) -> ok | {error, any()} when Id::atom()). resume(Id) -> gen_fsm:sync_send_event(Id, #compaction_event_info{event = ?EVENT_RESUME}, ?DEF_TIMEOUT). %% @doc Retrieve the storage stats specfied by Id %% which contains number of objects and so on. %% -spec(state(Id, Client) -> ok | {error, any()} when Id::atom(), Client::pid()). state(Id, Client) -> gen_fsm:send_event(Id, #compaction_event_info{event = ?EVENT_STATE, client_pid = Client}). %% @doc Increase performance of the data-compaction processing %% -spec(increase(Id) -> ok when Id::atom()). increase(Id) -> gen_fsm:send_event(Id, #compaction_event_info{event = ?EVENT_INCREASE}). %% @doc Decrease performance of the data-compaction processing %% %% -spec(decrease(Id) -> ok when Id::atom()). decrease(Id) -> gen_fsm:send_event(Id, #compaction_event_info{event = ?EVENT_DECREASE}). %%==================================================================== GEN_SERVER %%==================================================================== %% @doc Initiates the server %% init([Id, ObjStorageId, ObjStorageIdRead, MetaDBId, LoggerId]) -> {ok, ?ST_IDLING, #compaction_worker_state{ id = Id, obj_storage_id = ObjStorageId, obj_storage_id_read = ObjStorageIdRead, meta_db_id = MetaDBId, diagnosis_log_id = LoggerId, interval = ?env_compaction_interval_reg(), max_interval = ?env_compaction_interval_max(), num_of_batch_procs = ?env_compaction_num_of_batch_procs_reg(), max_num_of_batch_procs = ?env_compaction_num_of_batch_procs_max(), compaction_prms = #compaction_prms{ key_bin = <<>>, body_bin = <<>>, metadata = #?METADATA{}, next_offset = 0, num_of_active_objs = 0, size_of_active_objs = 0}}}. %% @doc Handle events handle_event(_Event, StateName, State) -> {next_state, StateName, State}. %% @doc Handle 'status' event handle_sync_event(state, _From, StateName, State) -> {reply, {ok, StateName}, StateName, State}; %% @doc Handle 'stop' event handle_sync_event(stop, _From, _StateName, Status) -> {stop, shutdown, ok, Status}. %% @doc Handling all non call/cast messages handle_info(_Info, StateName, State) -> {next_state, StateName, State}. %% @doc This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any necessary %% cleaning up. When it returns, the gen_server terminates with Reason. %% The return value is ignored. terminate(Reason, _StateName, _State) -> error_logger:info_msg("~p,~p,~p,~p~n", [{module, ?MODULE_STRING}, {function, "terminate/2"}, {line, ?LINE}, {body, Reason}]), ok. %% @doc Convert process state when code is changed code_change(_OldVsn, StateName, State, _Extra) -> {ok, StateName, State}. %% @doc This function is called by a gen_fsm when it should update %% its internal state data during a release upgrade/downgrade format_status(_Opt, [_PDict, State]) -> State. %%==================================================================== CALLBACKS %%==================================================================== %% @doc State of 'idle' %% -spec(idling(EventInfo, From, State) -> {next_state, ?ST_IDLING | ?ST_RUNNING, State} when EventInfo::#compaction_event_info{}, From::{pid(),Tag::atom()}, State::#compaction_worker_state{}). idling(#compaction_event_info{event = ?EVENT_RUN, controller_pid = ControllerPid, is_diagnosing = IsDiagnosing, is_recovering = IsRecovering, is_forced_run = false, callback = CallbackFun}, From, #compaction_worker_state{id = Id, compaction_skip_garbage = SkipInfo, compaction_prms = CompactionPrms} = State) -> NextStatus = ?ST_RUNNING, State_1 = State#compaction_worker_state{ compact_cntl_pid = ControllerPid, status = NextStatus, is_diagnosing = IsDiagnosing, is_recovering = IsRecovering, is_skipping_garbage = false, skipped_bytes = 0, error_pos = 0, set_errors = sets:new(), acc_errors = [], interval = ?env_compaction_interval_reg(), max_interval = ?env_compaction_interval_max(), num_of_batch_procs = ?env_compaction_num_of_batch_procs_reg(), max_num_of_batch_procs = ?env_compaction_num_of_batch_procs_max(), compaction_skip_garbage = SkipInfo#compaction_skip_garbage{ buf = <<>>, read_pos = 0, prefetch_size = ?env_compaction_skip_prefetch_size(), is_skipping = false, is_close_eof = false }, compaction_prms = CompactionPrms#compaction_prms{ num_of_active_objs = 0, size_of_active_objs = 0, next_offset = ?AVS_SUPER_BLOCK_LEN, callback_fun = CallbackFun }, start_datetime = leo_date:now()}, case prepare(State_1) of {ok, State_2} -> gen_fsm:reply(From, ok), ok = run(Id, IsDiagnosing, IsRecovering), {next_state, NextStatus, State_2}; {{error, Cause}, #compaction_worker_state{obj_storage_info = #backend_info{write_handler = WriteHandler, read_handler = ReadHandler}}} -> catch leo_object_storage_haystack:close(WriteHandler, ReadHandler), gen_fsm:reply(From, {error, Cause}), {next_state, ?ST_IDLING, State_1} end; idling(_, From, State) -> gen_fsm:reply(From, {error, badstate}), NextStatus = ?ST_IDLING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}. -spec(idling(EventInfo, State) -> {next_state, ?ST_IDLING, State} when EventInfo::#compaction_event_info{}, State::#compaction_worker_state{}). idling(#compaction_event_info{event = ?EVENT_STATE, client_pid = Client}, State) -> NextStatus = ?ST_IDLING, erlang:send(Client, NextStatus), {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}; idling(#compaction_event_info{event = ?EVENT_INCREASE}, State) -> NextStatus = ?ST_IDLING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}; idling(#compaction_event_info{event = ?EVENT_DECREASE}, State) -> NextStatus = ?ST_IDLING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}; idling(_, State) -> NextStatus = ?ST_IDLING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}. %% @doc State of 'running' -spec(running(EventInfo, State) -> {next_state, ?ST_RUNNING, State} when EventInfo::#compaction_event_info{}, State::#compaction_worker_state{}). running(#compaction_event_info{event = ?EVENT_RUN}, #compaction_worker_state{obj_storage_info = #backend_info{linked_path = []}} = State) -> NextStatus = ?ST_IDLING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}; running(#compaction_event_info{event = ?EVENT_RUN, is_diagnosing = IsDiagnosing, is_recovering = IsRecovering}, #compaction_worker_state{id = Id, obj_storage_id = ObjStorageId, compact_cntl_pid = CompactCntlPid, interval = Interval, count_procs = CountProcs, num_of_batch_procs = BatchProcs, is_skipping_garbage = IsSkipping, compaction_prms = #compaction_prms{ start_lock_offset = StartLockOffset}} = State) -> %% Temporally suspend the compaction %% in order to decrease i/o load CountProcs_1 = case (CountProcs < 1) of true -> Interval_1 = case (Interval < 1) of true -> ?DEF_MAX_COMPACTION_WT; false -> Interval end, timer:sleep(Interval_1), BatchProcs; false when IsSkipping == true -> keep during skipping a garbage CountProcs; false -> CountProcs - 1 end, {NextStatus, State_3} = case catch execute(State#compaction_worker_state{ is_diagnosing = IsDiagnosing, is_recovering = IsRecovering}) of %% Lock the object-storage in order to %% reject requests during the data-compaction {ok, {next, #compaction_worker_state{ is_locked = IsLocked, compaction_prms = #compaction_prms{next_offset = NextOffset} } = State_1}} when NextOffset > StartLockOffset -> State_2 = case IsLocked of true -> erlang:send(CompactCntlPid, run), State_1; false -> ok = leo_object_storage_server:lock(ObjStorageId), erlang:send(CompactCntlPid, {lock, Id}), State_1#compaction_worker_state{is_locked = true} end, ok = run(Id, IsDiagnosing, IsRecovering), {?ST_RUNNING, State_2}; %% Execute the data-compaction repeatedly {ok, {next, State_1}} -> ok = run(Id, IsDiagnosing, IsRecovering), erlang:send(CompactCntlPid, run), {?ST_RUNNING, State_1}; %% An unxepected error has occured {'EXIT', Cause} -> error_logger:info_msg("~p,~p,~p,~p~n", [{module, ?MODULE_STRING}, {function, "running/2"}, {line, ?LINE}, {body, {Id, Cause}}]), {ok, State_1} = after_execute({error, Cause}, State#compaction_worker_state{result = ?RET_FAIL}), {?ST_IDLING, State_1}; %% Reached end of the object-container {ok, {eof, State_1}} -> {ok, State_2} = after_execute(ok, State_1#compaction_worker_state{result = ?RET_SUCCESS}), {?ST_IDLING, State_2}; %% An epected error has occured {{error, Cause}, State_1} -> error_logger:info_msg("~p,~p,~p,~p~n", [{module, ?MODULE_STRING}, {function, "running/2"}, {line, ?LINE}, {body, {Id, Cause}}]), {ok, State_2} = after_execute({error, Cause}, State_1#compaction_worker_state{result = ?RET_FAIL}), {?ST_IDLING, State_2} end, {next_state, NextStatus, State_3#compaction_worker_state{status = NextStatus, count_procs = CountProcs_1}}; running(#compaction_event_info{event = ?EVENT_SUSPEND}, State) -> NextStatus = ?ST_SUSPENDING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus, is_forced_suspending = true}}; running(#compaction_event_info{event = ?EVENT_STATE, client_pid = Client}, State) -> NextStatus = ?ST_RUNNING, erlang:send(Client, NextStatus), {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}; running(#compaction_event_info{event = ?EVENT_INCREASE}, #compaction_worker_state{num_of_batch_procs = BatchProcs, max_num_of_batch_procs = MaxBatchProcs, interval = Interval, num_of_steps = NumOfSteps} = State) -> {ok, {StepBatchProcs, StepInterval}} = ?step_compaction_proc_values(?env_compaction_num_of_batch_procs_reg(), ?env_compaction_interval_reg(), NumOfSteps), BatchProcs_1 = incr_batch_of_msgs_fun(BatchProcs, MaxBatchProcs, StepBatchProcs), Interval_1 = decr_interval_fun(Interval, StepInterval), NextStatus = ?ST_RUNNING, {next_state, NextStatus, State#compaction_worker_state{ num_of_batch_procs = BatchProcs_1, interval = Interval_1, status = NextStatus}}; running(#compaction_event_info{event = ?EVENT_DECREASE}, #compaction_worker_state{num_of_batch_procs = BatchProcs, interval = Interval, max_interval = MaxInterval, num_of_steps = NumOfSteps} = State) -> {ok, {StepBatchProcs, StepInterval}} = ?step_compaction_proc_values(?env_compaction_num_of_batch_procs_reg(), ?env_compaction_interval_reg(), NumOfSteps), Interval_1 = incr_interval_fun(Interval, MaxInterval, StepInterval), {NextStatus, BatchProcs_1} = case (BatchProcs =< 0) of true -> {?ST_SUSPENDING, 0}; false -> {?ST_RUNNING, decr_batch_of_msgs_fun(BatchProcs, StepBatchProcs)} end, {next_state, NextStatus, State#compaction_worker_state{ num_of_batch_procs = BatchProcs_1, interval = Interval_1, status = NextStatus}}; running(_, State) -> NextStatus = ?ST_RUNNING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}. -spec(running( _, _, #compaction_worker_state{}) -> {next_state, ?ST_SUSPENDING|?ST_RUNNING, #compaction_worker_state{}}). running(_, From, State) -> gen_fsm:reply(From, {error, badstate}), NextStatus = ?ST_RUNNING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}. %% @doc State of 'suspend' %% -spec(suspending(EventInfo, State) -> {next_state, ?ST_SUSPENDING, State} when EventInfo::#compaction_event_info{}, State::#compaction_worker_state{}). suspending(#compaction_event_info{event = ?EVENT_RUN}, State) -> NextStatus = ?ST_SUSPENDING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}; suspending(#compaction_event_info{event = ?EVENT_STATE, client_pid = Client}, State) -> NextStatus = ?ST_SUSPENDING, erlang:send(Client, NextStatus), {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}; suspending(#compaction_event_info{event = ?EVENT_INCREASE}, #compaction_worker_state{is_forced_suspending = true} = State) -> NextStatus = ?ST_SUSPENDING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}; suspending(#compaction_event_info{event = ?EVENT_INCREASE}, #compaction_worker_state{id = Id, is_diagnosing = IsDiagnosing, is_recovering = IsRecovering, num_of_batch_procs = BatchProcs, max_num_of_batch_procs = MaxBatchProcs, interval = Interval, num_of_steps = NumOfSteps} = State) -> {ok, {StepBatchProcs, StepInterval}} = ?step_compaction_proc_values(?env_compaction_num_of_batch_procs_reg(), ?env_compaction_interval_reg(), NumOfSteps), BatchProcs_1 = incr_batch_of_msgs_fun(BatchProcs, MaxBatchProcs, StepBatchProcs), Interval_1 = decr_interval_fun(Interval, StepInterval), NextStatus = ?ST_RUNNING, timer:apply_after(timer:seconds(1), ?MODULE, run, [Id, IsDiagnosing, IsRecovering]), {next_state, NextStatus, State#compaction_worker_state{ num_of_batch_procs = BatchProcs_1, interval = Interval_1, status = NextStatus}}; suspending(_, State) -> NextStatus = ?ST_SUSPENDING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}. -spec(suspending(EventInfo, From, State) -> {next_state, ?ST_SUSPENDING | ?ST_RUNNING, State} when EventInfo::#compaction_event_info{}, From::{pid(),Tag::atom()}, State::#compaction_worker_state{}). suspending(#compaction_event_info{event = ?EVENT_RESUME}, From, #compaction_worker_state{id = Id, is_diagnosing = IsDiagnosing, is_recovering = IsRecovering} = State) -> %% resume the data-compaction gen_fsm:reply(From, ok), NextStatus = ?ST_RUNNING, timer:apply_after( timer:seconds(1), ?MODULE, run, [Id, IsDiagnosing, IsRecovering]), {next_state, NextStatus, State#compaction_worker_state{ status = NextStatus, is_forced_suspending = false}}; suspending(_, From, State) -> gen_fsm:reply(From, {error, badstate}), NextStatus = ?ST_SUSPENDING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}. %%-------------------------------------------------------------------- %% Inner Functions %%-------------------------------------------------------------------- %% @doc Calculate remain disk-sizes. @private -spec(calc_remain_disksize(MetaDBId, FilePath) -> {ok, integer()} | {error, any()} when MetaDBId::atom(), FilePath::string()). calc_remain_disksize(MetaDBId, FilePath) -> case leo_file:file_get_mount_path(FilePath) of {ok, MountPath} -> case leo_backend_db_api:get_db_raw_filepath(MetaDBId) of {ok, MetaDir} -> case catch leo_file:file_get_total_size(MetaDir) of {'EXIT', Reason} -> {error, Reason}; MetaSize -> AvsSize = filelib:file_size(FilePath), Remain = leo_file:file_get_remain_disk(MountPath), {ok, erlang:round(Remain - (AvsSize + MetaSize))} end; _ -> {error, ?ERROR_COULD_NOT_GET_MOUNT_PATH} end; Error -> Error end. %% @doc compact objects from the object-container on a independent process. @private -spec(prepare(State) -> {ok, State} | {{error, any()}, State} when State::#compaction_worker_state{}). prepare(#compaction_worker_state{obj_storage_id = ObjStorageId, meta_db_id = MetaDBId} = State) -> %% Retrieve the current container's path {ok, #backend_info{ linked_path = LinkedPath, file_path = FilePath}} = ?get_obj_storage_info(ObjStorageId), %% Retrieve the remain disk-size case calc_remain_disksize(MetaDBId, LinkedPath) of {ok, RemainSize} -> case (RemainSize > 0) of true -> %% Open the current object-container %% and a new object-container prepare_1(LinkedPath, FilePath, State); false -> {{error, system_limit}, State} end; Error -> {Error, State} end. prepare_1(LinkedPath, FilePath, #compaction_worker_state{compaction_prms = CompactionPrms, is_diagnosing = true} = State) -> case leo_object_storage_haystack:open(FilePath, read) of {ok, [_, ReadHandler, AVSVsnBinPrv]} -> FileSize = filelib:file_size(FilePath), ok = file:advise(ReadHandler, 0, FileSize, sequential), {ok, State#compaction_worker_state{ obj_storage_info = #backend_info{ avs_ver_cur = <<>>, avs_ver_prv = AVSVsnBinPrv, write_handler = undefined, read_handler = ReadHandler, linked_path = LinkedPath, file_path = [] }, compaction_prms = CompactionPrms#compaction_prms{ start_lock_offset = FileSize } } }; Error -> {Error, State} end; prepare_1(LinkedPath, FilePath, #compaction_worker_state{meta_db_id = MetaDBId, compaction_prms = CompactionPrms} = State) -> %% Create the new container NewFilePath = ?gen_raw_file_path(LinkedPath), case leo_object_storage_haystack:open(NewFilePath, write) of {ok, [WriteHandler, _, AVSVsnBinCur]} -> %% Open the current container case leo_object_storage_haystack:open(FilePath, read) of {ok, [_, ReadHandler, AVSVsnBinPrv]} -> FileSize = filelib:file_size(FilePath), ok = file:advise(WriteHandler, 0, FileSize, dont_need), ok = file:advise(ReadHandler, 0, FileSize, sequential), case leo_backend_db_api:run_compaction(MetaDBId) of ok -> {ok, State#compaction_worker_state{ obj_storage_info = #backend_info{ avs_ver_cur = AVSVsnBinCur, avs_ver_prv = AVSVsnBinPrv, write_handler = WriteHandler, read_handler = ReadHandler, linked_path = LinkedPath, file_path = NewFilePath }, compaction_prms = CompactionPrms#compaction_prms{ start_lock_offset = FileSize } } }; Error -> {Error, State} end; Error -> {Error, State} end; Error -> {Error, State} end. %% @doc Reduce unnecessary objects from object-container. @private -spec(execute(State) -> {ok, State} | {{error, any()}, State} when State::#compaction_worker_state{}). execute(#compaction_worker_state{meta_db_id = MetaDBId, diagnosis_log_id = LoggerId, obj_storage_info = StorageInfo, is_skipping_garbage = IsSkipping, is_diagnosing = IsDiagnosing, is_recovering = IsRecovering, compaction_prms = CompactionPrms} = State) -> State_1 = case IsSkipping of true -> %% keep set_errors during skipping a garbage State; false -> Initialize set - error property State#compaction_worker_state{set_errors = sets:new()} end, Offset = CompactionPrms#compaction_prms.next_offset, Metadata = CompactionPrms#compaction_prms.metadata, %% Execute compaction case (Offset == ?AVS_SUPER_BLOCK_LEN orelse IsSkipping) of true -> execute_1(State_1); false -> #compaction_prms{key_bin = Key, body_bin = Body, callback_fun = CallbackFun, num_of_active_objs = NumOfActiveObjs, size_of_active_objs = ActiveSize, total_num_of_objs = TotalObjs, total_size_of_objs = TotaSize} = CompactionPrms, NumOfReplicas = Metadata#?METADATA.num_of_replicas, HasChargeOfNode = case (CallbackFun == undefined) of true -> true; false -> CallbackFun(Key, NumOfReplicas) end, case (is_removed_obj(MetaDBId, StorageInfo, Metadata, IsRecovering) orelse HasChargeOfNode == false) of true when IsDiagnosing == false -> execute_1(State_1); true when IsDiagnosing == true -> ok = output_diagnosis_log(LoggerId, Metadata), execute_1(State_1#compaction_worker_state{ compaction_prms = CompactionPrms#compaction_prms{ total_num_of_objs = TotalObjs + 1, total_size_of_objs = TotaSize + leo_object_storage_haystack:calc_obj_size(Metadata) }}); %% %% For data-compaction processing %% false when IsDiagnosing == false -> %% Insert into the temporary object-container. {Ret_1, NewState} = case leo_object_storage_haystack:put_obj_to_new_cntnr( StorageInfo#backend_info.write_handler, Metadata, Key, Body) of {ok, Offset_1} -> Metadata_1 = Metadata#?METADATA{offset = Offset_1}, KeyOfMeta = ?gen_backend_key(StorageInfo#backend_info.avs_ver_cur, Metadata#?METADATA.addr_id, Metadata#?METADATA.key), Ret = leo_backend_db_api:put_value_to_new_db( MetaDBId, KeyOfMeta, term_to_binary(Metadata_1)), %% Calculate num of objects and total size of objects execute_2(Ret, CompactionPrms, Metadata_1, NumOfActiveObjs, ActiveSize, State_1); Error -> {Error, State_1#compaction_worker_state{compaction_prms = CompactionPrms#compaction_prms{ metadata = Metadata}}} end, execute_1(Ret_1, NewState); %% %% For diagnosis processing %% false when IsDiagnosing == true -> ok = output_diagnosis_log(LoggerId, Metadata), {Ret_1, NewState} = execute_2( ok, CompactionPrms, Metadata, NumOfActiveObjs, ActiveSize, State_1), CompactionPrms_1 = NewState#compaction_worker_state.compaction_prms, execute_1(Ret_1, NewState#compaction_worker_state{ compaction_prms = CompactionPrms_1#compaction_prms{ total_num_of_objs = TotalObjs + 1, total_size_of_objs = TotaSize + leo_object_storage_haystack:calc_obj_size(Metadata) }}) end end. %% @doc Reduce unnecessary objects from object-container. @private -spec(execute_1(State) -> {ok, {next|eof, State}} | {{error, any()}, State} when State::#compaction_worker_state{}). execute_1(State) -> execute_1(ok, State). execute_1(Ret, State) -> execute_1(Ret, State, 1). -spec(execute_1(Ret, State, RetryTimes) -> {ok, {next|eof, State}} | {{error, any()}, State} when Ret::ok|{error,any()}, State::#compaction_worker_state{}, RetryTimes::non_neg_integer()). execute_1(ok = Ret, #compaction_worker_state{meta_db_id = MetaDBId, obj_storage_info = StorageInfo, compaction_prms = CompactionPrms, compaction_skip_garbage = SkipInfo, skipped_bytes = SkippedBytes, is_skipping_garbage = IsSkipping, is_recovering = IsRecovering} = State, RetryTimes) -> ReadHandler = StorageInfo#backend_info.read_handler, NextOffset = CompactionPrms#compaction_prms.next_offset, case leo_object_storage_haystack:get_obj_for_new_cntnr( ReadHandler, NextOffset, SkipInfo) of {ok, NewMetadata, [_HeaderValue, NewKeyValue, NewBodyValue, NewNextOffset]} -> %% If is-recovering is true, put a metadata to the backend-db case IsRecovering of true -> #?METADATA{key = Key, addr_id = AddrId} = NewMetadata, KeyOfMetadata = ?gen_backend_key( StorageInfo#backend_info.avs_ver_prv, AddrId, Key), case leo_backend_db_api:put( MetaDBId, KeyOfMetadata, term_to_binary(NewMetadata)) of ok -> ok; {error, Cause} -> error_logger:error_msg("~p,~p,~p,~p~n", [{module, ?MODULE_STRING}, {function, "execute_1/2"}, {line, ?LINE}, {body, Cause}]), throw("unexpected_error happened at backend-db") end; false -> void end, next object {ok, State_1} = output_accumulated_errors(State, NextOffset), {ok, {next, State_1#compaction_worker_state{ error_pos = 0, set_errors = sets:new(), is_skipping_garbage = false, skipped_bytes = 0, compaction_skip_garbage = SkipInfo#compaction_skip_garbage{ is_skipping = false, is_close_eof = false, read_pos = 0, buf = <<>> }, compaction_prms = CompactionPrms#compaction_prms{ key_bin = NewKeyValue, body_bin = NewBodyValue, metadata = NewMetadata, next_offset = NewNextOffset} }}}; %% Reached tail of the object-container {error, eof = Cause} -> {ok, State_1} = output_accumulated_errors(State, NextOffset), NumOfAcriveObjs = CompactionPrms#compaction_prms.num_of_active_objs, SizeOfActiveObjs = CompactionPrms#compaction_prms.size_of_active_objs, {ok, {Cause, State_1#compaction_worker_state{ error_pos = 0, set_errors = sets:new(), is_skipping_garbage = false, skipped_bytes = 0, compaction_skip_garbage = SkipInfo#compaction_skip_garbage{ is_skipping = false, is_close_eof = false, read_pos = 0, buf = <<>> }, compaction_prms = CompactionPrms#compaction_prms{ num_of_active_objs = NumOfAcriveObjs, size_of_active_objs = SizeOfActiveObjs, next_offset = Cause} }}}; Aan issue of unexpected length happened , %% then need to rollback the data-compaction {error, {abort, unexpected_len = Cause}} when RetryTimes == ?MAX_RETRY_TIMES -> erlang:error(Cause); {error, {abort, unexpected_len = Cause}} -> error_logger:error_msg("~p,~p,~p,~p~n", [{module, ?MODULE_STRING}, {function, "execute_1/3"}, {line, ?LINE}, [{offset, NextOffset}, {body, Cause}]]), timer:sleep(?WAIT_TIME_AFTER_ERROR), execute_1(Ret, State, RetryTimes + 1); %% It found this object is broken, %% then it seeks a regular object, %% finally it reports a collapsed object to the error-log {skip, NewSkipInfo, Cause} -> SetErrors = sets:add_element(Cause, State#compaction_worker_state.set_errors), SkippedBytesNew = case IsSkipping of true -> SkippedBytes + 1; false -> 1 end, case SkippedBytes > ?env_compaction_force_quit_in_bytes() of true -> erlang:error(garbage_too_long); false -> nop end, {ok, {next, State#compaction_worker_state{ set_errors = SetErrors, is_skipping_garbage = true, skipped_bytes = SkippedBytesNew, compaction_skip_garbage = NewSkipInfo, compaction_prms = CompactionPrms#compaction_prms{ next_offset = NextOffset + 1} }}}; {_, Cause} -> ErrorPosCur = State#compaction_worker_state.error_pos, ErrorPosNew = case (State#compaction_worker_state.error_pos == 0) of true -> NextOffset; false -> ErrorPosCur end, SetErrors = sets:add_element(Cause, State#compaction_worker_state.set_errors), SkippedBytesNew = case IsSkipping of true -> SkippedBytes + 1; false -> 1 end, case SkippedBytes > ?env_compaction_force_quit_in_bytes() of true -> erlang:error(garbage_too_long); false -> nop end, {ok, {next, State#compaction_worker_state{ error_pos = ErrorPosNew, set_errors = SetErrors, is_skipping_garbage = true, skipped_bytes = SkippedBytesNew, compaction_skip_garbage = SkipInfo#compaction_skip_garbage{ is_skipping = true }, compaction_prms = CompactionPrms#compaction_prms{ next_offset = NextOffset + 1} }}} end; execute_1(Error, State,_) -> {Error, State}. %% @doc Calculate num of objects and total size of objects @private execute_2(Ret, CompactionPrms, Metadata, NumOfActiveObjs, ActiveSize, State) -> ObjectSize = leo_object_storage_haystack:calc_obj_size(Metadata), {Ret, State#compaction_worker_state{ compaction_prms = CompactionPrms#compaction_prms{ metadata = Metadata, num_of_active_objs = NumOfActiveObjs + 1, size_of_active_objs = ActiveSize + ObjectSize}}}. @private finish(#compaction_worker_state{obj_storage_id = ObjStorageId, compact_cntl_pid = CntlPid, compaction_prms = CompactionPrms} = State) -> %% Generate the compaction report {ok, Report} = gen_compaction_report(State), %% Notify a message to the compaction-manager erlang:send(CntlPid, {finish, {ObjStorageId, Report}}), Unlock handling request ok = leo_object_storage_server:unlock(ObjStorageId), {ok, State#compaction_worker_state{start_datetime = 0, error_pos = 0, set_errors = sets:new(), acc_errors = [], obj_storage_info = #backend_info{}, compaction_prms = CompactionPrms#compaction_prms{ key_bin = <<>>, body_bin = <<>>, metadata = #?METADATA{}, next_offset = 0, start_lock_offset = 0, num_of_active_objs = 0, size_of_active_objs = 0, total_num_of_objs = 0, total_size_of_objs = 0}, result = undefined}}. @private after_execute(Ret, #compaction_worker_state{obj_storage_info = StorageInfo, is_diagnosing = IsDiagnosing, is_recovering = _IsRecovering, diagnosis_log_id = LoggerId} = State) -> %% Close file handlers ReadHandler = StorageInfo#backend_info.read_handler, WriteHandler = StorageInfo#backend_info.write_handler, catch leo_object_storage_haystack:close(WriteHandler, ReadHandler), %% rotate the diagnosis-log case IsDiagnosing of true when LoggerId /= undefined -> leo_logger_client_base:force_rotation(LoggerId); _ -> void end, %% Finish compaction ok = after_execute_1({Ret, State}), finish(State). %% @doc Reduce objects from the object-container. @private after_execute_1({_, #compaction_worker_state{ is_diagnosing = true, compaction_prms = #compaction_prms{ num_of_active_objs = _NumActiveObjs, size_of_active_objs = _SizeActiveObjs}}}) -> ok; after_execute_1({ok, #compaction_worker_state{ meta_db_id = MetaDBId, obj_storage_id = ObjStorageId, obj_storage_id_read = ObjStorageId_R, obj_storage_info = StorageInfo, compaction_prms = #compaction_prms{ num_of_active_objs = NumActiveObjs, size_of_active_objs = SizeActiveObjs}}}) -> the symbol LinkedPath = StorageInfo#backend_info.linked_path, FilePath = StorageInfo#backend_info.file_path, catch file:delete(LinkedPath), %% Migrate the filepath case file:make_symlink(FilePath, LinkedPath) of ok -> ok = leo_object_storage_server:switch_container( ObjStorageId, FilePath, NumActiveObjs, SizeActiveObjs), NumOfObjStorageReadProcs = ?env_num_of_obj_storage_read_procs(), ok = after_execute_2(NumOfObjStorageReadProcs - 1, ObjStorageId_R, FilePath, NumActiveObjs, SizeActiveObjs), ok = leo_backend_db_api:finish_compaction(MetaDBId, true), ok; {error,_Cause} -> leo_backend_db_api:finish_compaction(MetaDBId, false), ok end; %% @doc Rollback - delete the tmp-files @private after_execute_1({_Error, #compaction_worker_state{ meta_db_id = MetaDBId, obj_storage_info = StorageInfo}}) -> %% must reopen the original file when handling at another process: catch file:delete(StorageInfo#backend_info.file_path), leo_backend_db_api:finish_compaction(MetaDBId, false), ok. @doc Switch an avs container for obj - storage - read @private after_execute_2(-1,_,_,_,_) -> ok; after_execute_2(ChildIndex, ObjStorageId_R, FilePath, NumActiveObjs, SizeActiveObjs) -> ObjStorageId_R_Child = list_to_atom( lists:append([atom_to_list(ObjStorageId_R), "_", integer_to_list(ChildIndex) ])), ok = leo_object_storage_server:switch_container( ObjStorageId_R_Child, FilePath, NumActiveObjs, SizeActiveObjs), after_execute_2(ChildIndex - 1, ObjStorageId_R, FilePath, NumActiveObjs, SizeActiveObjs). %% @doc Output the diagnosis log @private output_diagnosis_log(undefined,_Metadata) -> ok; output_diagnosis_log(LoggerId, Metadata) -> ?output_diagnosis_log(Metadata). %% @doc Output accumulated errors to logger @private -spec(output_accumulated_errors(State, ErrorPosEnd) -> {ok, State} when State::#compaction_worker_state{}, ErrorPosEnd::non_neg_integer()). output_accumulated_errors(#compaction_worker_state{ obj_storage_id = ObjStorageId, error_pos = ErrorPosStart, set_errors = SetErrors, acc_errors = AccErrors} = State, ErrorPosEnd) -> case sets:size(SetErrors) of 0 -> {ok, State}; _ -> {ok, StorageInfo} = ?get_obj_storage_info(ObjStorageId), Errors = sets:to_list(SetErrors), error_logger:warning_msg( "~p,~p,~p,~p~n", [{module, ?MODULE_STRING}, {function, "execute_1/4"}, {line, ?LINE}, {body, [{obj_container_path, StorageInfo#backend_info.file_path}, {error_pos_start, ErrorPosStart}, {error_pos_end, ErrorPosEnd}, {errors, Errors}]} ]), {ok, State#compaction_worker_state{ acc_errors = [{ErrorPosStart, ErrorPosEnd}|AccErrors]}} end. %% @doc Is deleted a record ? @private -spec(is_removed_obj(MetaDBId, StorageInfo, Metadata, IsRecovering) -> boolean() when MetaDBId::atom(), StorageInfo::#backend_info{}, Metadata::#?METADATA{}, IsRecovering::boolean()). is_removed_obj(_MetaDBId,_StorageInfo,_Metdata, true) -> false; is_removed_obj(MetaDBId, #backend_info{avs_ver_prv = AVSVsnBinPrv} = StorageInfo, #?METADATA{key = Key, addr_id = AddrId} = MetaFromAvs,_IsRecovering) -> KeyOfMetadata = ?gen_backend_key(AVSVsnBinPrv, AddrId, Key), case leo_backend_db_api:get(MetaDBId, KeyOfMetadata) of {ok, MetaBin} -> case binary_to_term(MetaBin) of #?METADATA{del = ?DEL_TRUE} -> true; Metadata -> is_removed_obj_1(MetaDBId, StorageInfo, MetaFromAvs, Metadata) end; not_found -> true; _Other -> false end. @private -spec(is_removed_obj_1(MetaDBId, StorageInfo, Metadata_1, Metadata_2) -> boolean() when MetaDBId::atom(), StorageInfo::#backend_info{}, Metadata_1::#?METADATA{}, Metadata_2::#?METADATA{}). is_removed_obj_1(_MetaDBId,_StorageInfo, #?METADATA{offset = Offset_1}, #?METADATA{offset = Offset_2}) when Offset_1 /= Offset_2 -> true; is_removed_obj_1(_MetaDBId,_StorageInfo,_Meta_1,_Meta_2) -> false. %% @doc Generate compaction report @private gen_compaction_report(State) -> #compaction_worker_state{obj_storage_id = ObjStorageId, compaction_prms = CompactionPrms, obj_storage_info = #backend_info{file_path = FilePath, linked_path = LinkedPath, avs_ver_prv = AVSVerPrev, avs_ver_cur = AVSVerCur}, start_datetime = StartDateTime, is_diagnosing = IsDiagnosing, is_recovering = _IsRecovering, acc_errors = AccErrors, result = Ret} = State, %% Append the compaction history EndDateTime = leo_date:now(), Duration = EndDateTime - StartDateTime, StartDateTime_1 = lists:flatten(leo_date:date_format(StartDateTime)), EndDateTime_1 = lists:flatten(leo_date:date_format(EndDateTime)), ok = leo_object_storage_server:append_compaction_history( ObjStorageId, #compaction_hist{start_datetime = StartDateTime, end_datetime = EndDateTime, duration = Duration, result = Ret}), %% Generate a report of the results #compaction_prms{num_of_active_objs = ActiveObjs, size_of_active_objs = ActiveSize, total_num_of_objs = TotalObjs, total_size_of_objs = TotalSize} = CompactionPrms, CntnrVer = case IsDiagnosing of true -> AVSVerPrev; false -> AVSVerCur end, CntnrPath = case IsDiagnosing of true -> LinkedPath; false -> FilePath end, TotalObjs_1 = case IsDiagnosing of true -> TotalObjs; false -> ActiveObjs end, TotalSize_1 = case IsDiagnosing of true -> TotalSize; false -> ActiveSize end, Report = #compaction_report{ file_path = CntnrPath, avs_ver = CntnrVer, num_of_active_objs = ActiveObjs, size_of_active_objs = ActiveSize, total_num_of_objs = TotalObjs_1, total_size_of_objs = TotalSize_1, start_datetime = StartDateTime_1, end_datetime = EndDateTime_1, errors = lists:reverse(AccErrors), duration = Duration, result = Ret }, case leo_object_storage_server:get_stats(ObjStorageId) of {ok, #storage_stats{file_path = ObjDir} = CurStats} -> %% Update the storage-state ok = leo_object_storage_server:set_stats(ObjStorageId, CurStats#storage_stats{ total_sizes = TotalSize_1, active_sizes = ActiveSize, total_num = TotalObjs_1, active_num = ActiveObjs}), %% Output report of the storage-container Tokens = string:tokens(ObjDir, "/"), case (length(Tokens) > 2) of true -> LogFilePath = filename:join(["/"] ++ lists:sublist(Tokens, length(Tokens) - 2) ++ [?DEF_LOG_SUB_DIR ++ atom_to_list(ObjStorageId) ++ ?DIAGNOSIS_REP_SUFFIX ++ "." ++ integer_to_list(leo_date:now()) ]), Report_1 = lists:zip(record_info(fields, compaction_report), tl(tuple_to_list(Report))), catch leo_file:file_unconsult(LogFilePath, Report_1), error_logger:info_msg("~p,~p,~p,~p~n", [{module, ?MODULE_STRING}, {function, "gen_compaction_report/1"}, {line, ?LINE}, {body, [Report_1]}]), ok; false -> void end; _ -> void end, {ok, Report}. %% @doc Increase the waiting time @private -spec(incr_interval_fun(Interval, MaxInterval, StepInterval) -> NewInterval when Interval::non_neg_integer(), MaxInterval::non_neg_integer(), StepInterval::non_neg_integer(), NewInterval::non_neg_integer()). incr_interval_fun(Interval, MaxInterval, StepInterval) -> Interval_1 = Interval + StepInterval, case (Interval_1 >= MaxInterval) of true -> MaxInterval; false -> Interval_1 end. %% @doc Decrease the waiting time @private -spec(decr_interval_fun(Interval, StepInterval) -> NewInterval when Interval::non_neg_integer(), StepInterval::non_neg_integer(), NewInterval::non_neg_integer()). decr_interval_fun(Interval, StepInterval) -> Interval_1 = Interval - StepInterval, case (Interval_1 =< ?DEF_MIN_COMPACTION_WT) of true -> ?DEF_MIN_COMPACTION_WT; false -> Interval_1 end. %% @doc Increase the batch procs @private -spec(incr_batch_of_msgs_fun(BatchProcs, MaxBatchProcs, StepBatchProcs) -> NewBatchProcs when BatchProcs::non_neg_integer(), MaxBatchProcs::non_neg_integer(), StepBatchProcs::non_neg_integer(), NewBatchProcs::non_neg_integer()). incr_batch_of_msgs_fun(BatchProcs, MaxBatchProcs, StepBatchProcs) -> BatchProcs_1 = BatchProcs + StepBatchProcs, case (BatchProcs_1 > MaxBatchProcs) of true -> MaxBatchProcs; false -> BatchProcs_1 end. %% @doc Increase the batch procs @private -spec(decr_batch_of_msgs_fun(BatchProcs, StepBatchProcs) -> NewBatchProcs when BatchProcs::non_neg_integer(), StepBatchProcs::non_neg_integer(), NewBatchProcs::non_neg_integer()). decr_batch_of_msgs_fun(BatchProcs, StepBatchProcs) -> BatchProcs_1 = BatchProcs - StepBatchProcs, case (BatchProcs_1 < 0) of true -> ?DEF_MIN_COMPACTION_BP; false -> BatchProcs_1 end.
null
https://raw.githubusercontent.com/leo-project/leo_object_storage/139a3d8f174e334aaf54f4e53d2f4fb8db04fc83/src/leo_compact_fsm_worker.erl
erlang
====================================================================== Leo Object Storage 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. @end ====================================================================== API gen_fsm callbacks ==================================================================== API ==================================================================== @doc Creates a gen_fsm process as part of a supervision tree @doc Stop this server @doc Run the process @doc Retrieve an object from the object-storage @doc Remove an object from the object-storage - (logical-delete) @doc Retrieve the storage stats specfied by Id which contains number of objects and so on. @doc Increase performance of the data-compaction processing @doc Decrease performance of the data-compaction processing ==================================================================== ==================================================================== @doc Initiates the server @doc Handle events @doc Handle 'status' event @doc Handle 'stop' event @doc Handling all non call/cast messages @doc This function is called by a gen_server when it is about to terminate. It should be the opposite of Module:init/1 and do any necessary cleaning up. When it returns, the gen_server terminates with Reason. The return value is ignored. @doc Convert process state when code is changed @doc This function is called by a gen_fsm when it should update its internal state data during a release upgrade/downgrade ==================================================================== ==================================================================== @doc State of 'idle' @doc State of 'running' Temporally suspend the compaction in order to decrease i/o load Lock the object-storage in order to reject requests during the data-compaction Execute the data-compaction repeatedly An unxepected error has occured Reached end of the object-container An epected error has occured @doc State of 'suspend' resume the data-compaction -------------------------------------------------------------------- Inner Functions -------------------------------------------------------------------- @doc Calculate remain disk-sizes. @doc compact objects from the object-container on a independent process. Retrieve the current container's path Retrieve the remain disk-size Open the current object-container and a new object-container Create the new container Open the current container @doc Reduce unnecessary objects from object-container. keep set_errors during skipping a garbage Execute compaction For data-compaction processing Insert into the temporary object-container. Calculate num of objects and total size of objects For diagnosis processing @doc Reduce unnecessary objects from object-container. If is-recovering is true, put a metadata to the backend-db Reached tail of the object-container then need to rollback the data-compaction It found this object is broken, then it seeks a regular object, finally it reports a collapsed object to the error-log @doc Calculate num of objects and total size of objects Generate the compaction report Notify a message to the compaction-manager Close file handlers rotate the diagnosis-log Finish compaction @doc Reduce objects from the object-container. Migrate the filepath @doc Rollback - delete the tmp-files must reopen the original file when handling at another process: @doc Output the diagnosis log @doc Output accumulated errors to logger @doc Is deleted a record ? @doc Generate compaction report Append the compaction history Generate a report of the results Update the storage-state Output report of the storage-container @doc Increase the waiting time @doc Decrease the waiting time @doc Increase the batch procs @doc Increase the batch procs
Copyright ( c ) 2012 - 2017 Rakuten , Inc. This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY @doc FSM of the data - compaction worker , which handles removing unnecessary objects from a object container . -project/leo_object_storage/blob/master/src/leo_compact_fsm_controller.erl -module(leo_compact_fsm_worker). -author('Yosuke Hara'). -behaviour(gen_fsm). -include("leo_object_storage.hrl"). -include_lib("leo_logger/include/leo_logger.hrl"). -include_lib("eunit/include/eunit.hrl"). -export([start_link/5, stop/1]). -export([run/3, run/5, forced_run/3, suspend/1, resume/1, state/2, increase/1, decrease/1 ]). -export([init/1, handle_event/3, handle_sync_event/4, handle_info/3, terminate/3, code_change/4, format_status/2]). -export([idling/2, idling/3, running/2, running/3, suspending/2, suspending/3]). -define(DEF_TIMEOUT, timer:seconds(30)). -spec(start_link(Id, ObjStorageId, ObjStorageIdRead, MetaDBId, LoggerId) -> {ok, pid()} | {error, any()} when Id::atom(), ObjStorageId::atom(), ObjStorageIdRead::atom(), MetaDBId::atom(), LoggerId::atom()). start_link(Id, ObjStorageId, ObjStorageIdRead, MetaDBId, LoggerId) -> gen_fsm:start_link({local, Id}, ?MODULE, [Id, ObjStorageId, ObjStorageIdRead, MetaDBId, LoggerId], []). -spec(stop(Id) -> ok when Id::atom()). stop(Id) -> error_logger:info_msg("~p,~p,~p,~p~n", [{module, ?MODULE_STRING}, {function, "stop/1"}, {line, ?LINE}, {body, Id}]), gen_fsm:sync_send_all_state_event(Id, stop, ?DEF_TIMEOUT). -spec(run(Id, IsDiagnosing, IsRecovering) -> ok | {error, any()} when Id::atom(), IsDiagnosing::boolean(), IsRecovering::boolean()). run(Id, IsDiagnosing, IsRecovering) -> gen_fsm:send_event(Id, #compaction_event_info{event = ?EVENT_RUN, is_diagnosing = IsDiagnosing, is_recovering = IsRecovering, is_forced_run = false}). -spec(run(Id, ControllerPid, IsDiagnosing, IsRecovering, CallbackFun) -> ok | {error, any()} when Id::atom(), ControllerPid::pid(), IsDiagnosing::boolean(), IsRecovering::boolean(), CallbackFun::function()). run(Id, ControllerPid, IsDiagnosing, IsRecovering, CallbackFun) -> gen_fsm:sync_send_event(Id, #compaction_event_info{event = ?EVENT_RUN, controller_pid = ControllerPid, is_diagnosing = IsDiagnosing, is_recovering = IsRecovering, is_forced_run = false, callback = CallbackFun}, ?DEF_TIMEOUT). -spec(forced_run(Id, IsDiagnosing, IsRecovering) -> ok | {error, any()} when Id::atom(), IsDiagnosing::boolean(), IsRecovering::boolean()). forced_run(Id, IsDiagnosing, IsRecovering) -> gen_fsm:send_event(Id, #compaction_event_info{event = ?EVENT_RUN, is_diagnosing = IsDiagnosing, is_recovering = IsRecovering, is_forced_run = true}). -spec(suspend(Id) -> ok | {error, any()} when Id::atom()). suspend(Id) -> gen_fsm:send_event(Id, #compaction_event_info{event = ?EVENT_SUSPEND}). -spec(resume(Id) -> ok | {error, any()} when Id::atom()). resume(Id) -> gen_fsm:sync_send_event(Id, #compaction_event_info{event = ?EVENT_RESUME}, ?DEF_TIMEOUT). -spec(state(Id, Client) -> ok | {error, any()} when Id::atom(), Client::pid()). state(Id, Client) -> gen_fsm:send_event(Id, #compaction_event_info{event = ?EVENT_STATE, client_pid = Client}). -spec(increase(Id) -> ok when Id::atom()). increase(Id) -> gen_fsm:send_event(Id, #compaction_event_info{event = ?EVENT_INCREASE}). -spec(decrease(Id) -> ok when Id::atom()). decrease(Id) -> gen_fsm:send_event(Id, #compaction_event_info{event = ?EVENT_DECREASE}). GEN_SERVER init([Id, ObjStorageId, ObjStorageIdRead, MetaDBId, LoggerId]) -> {ok, ?ST_IDLING, #compaction_worker_state{ id = Id, obj_storage_id = ObjStorageId, obj_storage_id_read = ObjStorageIdRead, meta_db_id = MetaDBId, diagnosis_log_id = LoggerId, interval = ?env_compaction_interval_reg(), max_interval = ?env_compaction_interval_max(), num_of_batch_procs = ?env_compaction_num_of_batch_procs_reg(), max_num_of_batch_procs = ?env_compaction_num_of_batch_procs_max(), compaction_prms = #compaction_prms{ key_bin = <<>>, body_bin = <<>>, metadata = #?METADATA{}, next_offset = 0, num_of_active_objs = 0, size_of_active_objs = 0}}}. handle_event(_Event, StateName, State) -> {next_state, StateName, State}. handle_sync_event(state, _From, StateName, State) -> {reply, {ok, StateName}, StateName, State}; handle_sync_event(stop, _From, _StateName, Status) -> {stop, shutdown, ok, Status}. handle_info(_Info, StateName, State) -> {next_state, StateName, State}. terminate(Reason, _StateName, _State) -> error_logger:info_msg("~p,~p,~p,~p~n", [{module, ?MODULE_STRING}, {function, "terminate/2"}, {line, ?LINE}, {body, Reason}]), ok. code_change(_OldVsn, StateName, State, _Extra) -> {ok, StateName, State}. format_status(_Opt, [_PDict, State]) -> State. CALLBACKS -spec(idling(EventInfo, From, State) -> {next_state, ?ST_IDLING | ?ST_RUNNING, State} when EventInfo::#compaction_event_info{}, From::{pid(),Tag::atom()}, State::#compaction_worker_state{}). idling(#compaction_event_info{event = ?EVENT_RUN, controller_pid = ControllerPid, is_diagnosing = IsDiagnosing, is_recovering = IsRecovering, is_forced_run = false, callback = CallbackFun}, From, #compaction_worker_state{id = Id, compaction_skip_garbage = SkipInfo, compaction_prms = CompactionPrms} = State) -> NextStatus = ?ST_RUNNING, State_1 = State#compaction_worker_state{ compact_cntl_pid = ControllerPid, status = NextStatus, is_diagnosing = IsDiagnosing, is_recovering = IsRecovering, is_skipping_garbage = false, skipped_bytes = 0, error_pos = 0, set_errors = sets:new(), acc_errors = [], interval = ?env_compaction_interval_reg(), max_interval = ?env_compaction_interval_max(), num_of_batch_procs = ?env_compaction_num_of_batch_procs_reg(), max_num_of_batch_procs = ?env_compaction_num_of_batch_procs_max(), compaction_skip_garbage = SkipInfo#compaction_skip_garbage{ buf = <<>>, read_pos = 0, prefetch_size = ?env_compaction_skip_prefetch_size(), is_skipping = false, is_close_eof = false }, compaction_prms = CompactionPrms#compaction_prms{ num_of_active_objs = 0, size_of_active_objs = 0, next_offset = ?AVS_SUPER_BLOCK_LEN, callback_fun = CallbackFun }, start_datetime = leo_date:now()}, case prepare(State_1) of {ok, State_2} -> gen_fsm:reply(From, ok), ok = run(Id, IsDiagnosing, IsRecovering), {next_state, NextStatus, State_2}; {{error, Cause}, #compaction_worker_state{obj_storage_info = #backend_info{write_handler = WriteHandler, read_handler = ReadHandler}}} -> catch leo_object_storage_haystack:close(WriteHandler, ReadHandler), gen_fsm:reply(From, {error, Cause}), {next_state, ?ST_IDLING, State_1} end; idling(_, From, State) -> gen_fsm:reply(From, {error, badstate}), NextStatus = ?ST_IDLING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}. -spec(idling(EventInfo, State) -> {next_state, ?ST_IDLING, State} when EventInfo::#compaction_event_info{}, State::#compaction_worker_state{}). idling(#compaction_event_info{event = ?EVENT_STATE, client_pid = Client}, State) -> NextStatus = ?ST_IDLING, erlang:send(Client, NextStatus), {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}; idling(#compaction_event_info{event = ?EVENT_INCREASE}, State) -> NextStatus = ?ST_IDLING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}; idling(#compaction_event_info{event = ?EVENT_DECREASE}, State) -> NextStatus = ?ST_IDLING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}; idling(_, State) -> NextStatus = ?ST_IDLING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}. -spec(running(EventInfo, State) -> {next_state, ?ST_RUNNING, State} when EventInfo::#compaction_event_info{}, State::#compaction_worker_state{}). running(#compaction_event_info{event = ?EVENT_RUN}, #compaction_worker_state{obj_storage_info = #backend_info{linked_path = []}} = State) -> NextStatus = ?ST_IDLING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}; running(#compaction_event_info{event = ?EVENT_RUN, is_diagnosing = IsDiagnosing, is_recovering = IsRecovering}, #compaction_worker_state{id = Id, obj_storage_id = ObjStorageId, compact_cntl_pid = CompactCntlPid, interval = Interval, count_procs = CountProcs, num_of_batch_procs = BatchProcs, is_skipping_garbage = IsSkipping, compaction_prms = #compaction_prms{ start_lock_offset = StartLockOffset}} = State) -> CountProcs_1 = case (CountProcs < 1) of true -> Interval_1 = case (Interval < 1) of true -> ?DEF_MAX_COMPACTION_WT; false -> Interval end, timer:sleep(Interval_1), BatchProcs; false when IsSkipping == true -> keep during skipping a garbage CountProcs; false -> CountProcs - 1 end, {NextStatus, State_3} = case catch execute(State#compaction_worker_state{ is_diagnosing = IsDiagnosing, is_recovering = IsRecovering}) of {ok, {next, #compaction_worker_state{ is_locked = IsLocked, compaction_prms = #compaction_prms{next_offset = NextOffset} } = State_1}} when NextOffset > StartLockOffset -> State_2 = case IsLocked of true -> erlang:send(CompactCntlPid, run), State_1; false -> ok = leo_object_storage_server:lock(ObjStorageId), erlang:send(CompactCntlPid, {lock, Id}), State_1#compaction_worker_state{is_locked = true} end, ok = run(Id, IsDiagnosing, IsRecovering), {?ST_RUNNING, State_2}; {ok, {next, State_1}} -> ok = run(Id, IsDiagnosing, IsRecovering), erlang:send(CompactCntlPid, run), {?ST_RUNNING, State_1}; {'EXIT', Cause} -> error_logger:info_msg("~p,~p,~p,~p~n", [{module, ?MODULE_STRING}, {function, "running/2"}, {line, ?LINE}, {body, {Id, Cause}}]), {ok, State_1} = after_execute({error, Cause}, State#compaction_worker_state{result = ?RET_FAIL}), {?ST_IDLING, State_1}; {ok, {eof, State_1}} -> {ok, State_2} = after_execute(ok, State_1#compaction_worker_state{result = ?RET_SUCCESS}), {?ST_IDLING, State_2}; {{error, Cause}, State_1} -> error_logger:info_msg("~p,~p,~p,~p~n", [{module, ?MODULE_STRING}, {function, "running/2"}, {line, ?LINE}, {body, {Id, Cause}}]), {ok, State_2} = after_execute({error, Cause}, State_1#compaction_worker_state{result = ?RET_FAIL}), {?ST_IDLING, State_2} end, {next_state, NextStatus, State_3#compaction_worker_state{status = NextStatus, count_procs = CountProcs_1}}; running(#compaction_event_info{event = ?EVENT_SUSPEND}, State) -> NextStatus = ?ST_SUSPENDING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus, is_forced_suspending = true}}; running(#compaction_event_info{event = ?EVENT_STATE, client_pid = Client}, State) -> NextStatus = ?ST_RUNNING, erlang:send(Client, NextStatus), {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}; running(#compaction_event_info{event = ?EVENT_INCREASE}, #compaction_worker_state{num_of_batch_procs = BatchProcs, max_num_of_batch_procs = MaxBatchProcs, interval = Interval, num_of_steps = NumOfSteps} = State) -> {ok, {StepBatchProcs, StepInterval}} = ?step_compaction_proc_values(?env_compaction_num_of_batch_procs_reg(), ?env_compaction_interval_reg(), NumOfSteps), BatchProcs_1 = incr_batch_of_msgs_fun(BatchProcs, MaxBatchProcs, StepBatchProcs), Interval_1 = decr_interval_fun(Interval, StepInterval), NextStatus = ?ST_RUNNING, {next_state, NextStatus, State#compaction_worker_state{ num_of_batch_procs = BatchProcs_1, interval = Interval_1, status = NextStatus}}; running(#compaction_event_info{event = ?EVENT_DECREASE}, #compaction_worker_state{num_of_batch_procs = BatchProcs, interval = Interval, max_interval = MaxInterval, num_of_steps = NumOfSteps} = State) -> {ok, {StepBatchProcs, StepInterval}} = ?step_compaction_proc_values(?env_compaction_num_of_batch_procs_reg(), ?env_compaction_interval_reg(), NumOfSteps), Interval_1 = incr_interval_fun(Interval, MaxInterval, StepInterval), {NextStatus, BatchProcs_1} = case (BatchProcs =< 0) of true -> {?ST_SUSPENDING, 0}; false -> {?ST_RUNNING, decr_batch_of_msgs_fun(BatchProcs, StepBatchProcs)} end, {next_state, NextStatus, State#compaction_worker_state{ num_of_batch_procs = BatchProcs_1, interval = Interval_1, status = NextStatus}}; running(_, State) -> NextStatus = ?ST_RUNNING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}. -spec(running( _, _, #compaction_worker_state{}) -> {next_state, ?ST_SUSPENDING|?ST_RUNNING, #compaction_worker_state{}}). running(_, From, State) -> gen_fsm:reply(From, {error, badstate}), NextStatus = ?ST_RUNNING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}. -spec(suspending(EventInfo, State) -> {next_state, ?ST_SUSPENDING, State} when EventInfo::#compaction_event_info{}, State::#compaction_worker_state{}). suspending(#compaction_event_info{event = ?EVENT_RUN}, State) -> NextStatus = ?ST_SUSPENDING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}; suspending(#compaction_event_info{event = ?EVENT_STATE, client_pid = Client}, State) -> NextStatus = ?ST_SUSPENDING, erlang:send(Client, NextStatus), {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}; suspending(#compaction_event_info{event = ?EVENT_INCREASE}, #compaction_worker_state{is_forced_suspending = true} = State) -> NextStatus = ?ST_SUSPENDING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}; suspending(#compaction_event_info{event = ?EVENT_INCREASE}, #compaction_worker_state{id = Id, is_diagnosing = IsDiagnosing, is_recovering = IsRecovering, num_of_batch_procs = BatchProcs, max_num_of_batch_procs = MaxBatchProcs, interval = Interval, num_of_steps = NumOfSteps} = State) -> {ok, {StepBatchProcs, StepInterval}} = ?step_compaction_proc_values(?env_compaction_num_of_batch_procs_reg(), ?env_compaction_interval_reg(), NumOfSteps), BatchProcs_1 = incr_batch_of_msgs_fun(BatchProcs, MaxBatchProcs, StepBatchProcs), Interval_1 = decr_interval_fun(Interval, StepInterval), NextStatus = ?ST_RUNNING, timer:apply_after(timer:seconds(1), ?MODULE, run, [Id, IsDiagnosing, IsRecovering]), {next_state, NextStatus, State#compaction_worker_state{ num_of_batch_procs = BatchProcs_1, interval = Interval_1, status = NextStatus}}; suspending(_, State) -> NextStatus = ?ST_SUSPENDING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}. -spec(suspending(EventInfo, From, State) -> {next_state, ?ST_SUSPENDING | ?ST_RUNNING, State} when EventInfo::#compaction_event_info{}, From::{pid(),Tag::atom()}, State::#compaction_worker_state{}). suspending(#compaction_event_info{event = ?EVENT_RESUME}, From, #compaction_worker_state{id = Id, is_diagnosing = IsDiagnosing, is_recovering = IsRecovering} = State) -> gen_fsm:reply(From, ok), NextStatus = ?ST_RUNNING, timer:apply_after( timer:seconds(1), ?MODULE, run, [Id, IsDiagnosing, IsRecovering]), {next_state, NextStatus, State#compaction_worker_state{ status = NextStatus, is_forced_suspending = false}}; suspending(_, From, State) -> gen_fsm:reply(From, {error, badstate}), NextStatus = ?ST_SUSPENDING, {next_state, NextStatus, State#compaction_worker_state{status = NextStatus}}. @private -spec(calc_remain_disksize(MetaDBId, FilePath) -> {ok, integer()} | {error, any()} when MetaDBId::atom(), FilePath::string()). calc_remain_disksize(MetaDBId, FilePath) -> case leo_file:file_get_mount_path(FilePath) of {ok, MountPath} -> case leo_backend_db_api:get_db_raw_filepath(MetaDBId) of {ok, MetaDir} -> case catch leo_file:file_get_total_size(MetaDir) of {'EXIT', Reason} -> {error, Reason}; MetaSize -> AvsSize = filelib:file_size(FilePath), Remain = leo_file:file_get_remain_disk(MountPath), {ok, erlang:round(Remain - (AvsSize + MetaSize))} end; _ -> {error, ?ERROR_COULD_NOT_GET_MOUNT_PATH} end; Error -> Error end. @private -spec(prepare(State) -> {ok, State} | {{error, any()}, State} when State::#compaction_worker_state{}). prepare(#compaction_worker_state{obj_storage_id = ObjStorageId, meta_db_id = MetaDBId} = State) -> {ok, #backend_info{ linked_path = LinkedPath, file_path = FilePath}} = ?get_obj_storage_info(ObjStorageId), case calc_remain_disksize(MetaDBId, LinkedPath) of {ok, RemainSize} -> case (RemainSize > 0) of true -> prepare_1(LinkedPath, FilePath, State); false -> {{error, system_limit}, State} end; Error -> {Error, State} end. prepare_1(LinkedPath, FilePath, #compaction_worker_state{compaction_prms = CompactionPrms, is_diagnosing = true} = State) -> case leo_object_storage_haystack:open(FilePath, read) of {ok, [_, ReadHandler, AVSVsnBinPrv]} -> FileSize = filelib:file_size(FilePath), ok = file:advise(ReadHandler, 0, FileSize, sequential), {ok, State#compaction_worker_state{ obj_storage_info = #backend_info{ avs_ver_cur = <<>>, avs_ver_prv = AVSVsnBinPrv, write_handler = undefined, read_handler = ReadHandler, linked_path = LinkedPath, file_path = [] }, compaction_prms = CompactionPrms#compaction_prms{ start_lock_offset = FileSize } } }; Error -> {Error, State} end; prepare_1(LinkedPath, FilePath, #compaction_worker_state{meta_db_id = MetaDBId, compaction_prms = CompactionPrms} = State) -> NewFilePath = ?gen_raw_file_path(LinkedPath), case leo_object_storage_haystack:open(NewFilePath, write) of {ok, [WriteHandler, _, AVSVsnBinCur]} -> case leo_object_storage_haystack:open(FilePath, read) of {ok, [_, ReadHandler, AVSVsnBinPrv]} -> FileSize = filelib:file_size(FilePath), ok = file:advise(WriteHandler, 0, FileSize, dont_need), ok = file:advise(ReadHandler, 0, FileSize, sequential), case leo_backend_db_api:run_compaction(MetaDBId) of ok -> {ok, State#compaction_worker_state{ obj_storage_info = #backend_info{ avs_ver_cur = AVSVsnBinCur, avs_ver_prv = AVSVsnBinPrv, write_handler = WriteHandler, read_handler = ReadHandler, linked_path = LinkedPath, file_path = NewFilePath }, compaction_prms = CompactionPrms#compaction_prms{ start_lock_offset = FileSize } } }; Error -> {Error, State} end; Error -> {Error, State} end; Error -> {Error, State} end. @private -spec(execute(State) -> {ok, State} | {{error, any()}, State} when State::#compaction_worker_state{}). execute(#compaction_worker_state{meta_db_id = MetaDBId, diagnosis_log_id = LoggerId, obj_storage_info = StorageInfo, is_skipping_garbage = IsSkipping, is_diagnosing = IsDiagnosing, is_recovering = IsRecovering, compaction_prms = CompactionPrms} = State) -> State_1 = case IsSkipping of true -> State; false -> Initialize set - error property State#compaction_worker_state{set_errors = sets:new()} end, Offset = CompactionPrms#compaction_prms.next_offset, Metadata = CompactionPrms#compaction_prms.metadata, case (Offset == ?AVS_SUPER_BLOCK_LEN orelse IsSkipping) of true -> execute_1(State_1); false -> #compaction_prms{key_bin = Key, body_bin = Body, callback_fun = CallbackFun, num_of_active_objs = NumOfActiveObjs, size_of_active_objs = ActiveSize, total_num_of_objs = TotalObjs, total_size_of_objs = TotaSize} = CompactionPrms, NumOfReplicas = Metadata#?METADATA.num_of_replicas, HasChargeOfNode = case (CallbackFun == undefined) of true -> true; false -> CallbackFun(Key, NumOfReplicas) end, case (is_removed_obj(MetaDBId, StorageInfo, Metadata, IsRecovering) orelse HasChargeOfNode == false) of true when IsDiagnosing == false -> execute_1(State_1); true when IsDiagnosing == true -> ok = output_diagnosis_log(LoggerId, Metadata), execute_1(State_1#compaction_worker_state{ compaction_prms = CompactionPrms#compaction_prms{ total_num_of_objs = TotalObjs + 1, total_size_of_objs = TotaSize + leo_object_storage_haystack:calc_obj_size(Metadata) }}); false when IsDiagnosing == false -> {Ret_1, NewState} = case leo_object_storage_haystack:put_obj_to_new_cntnr( StorageInfo#backend_info.write_handler, Metadata, Key, Body) of {ok, Offset_1} -> Metadata_1 = Metadata#?METADATA{offset = Offset_1}, KeyOfMeta = ?gen_backend_key(StorageInfo#backend_info.avs_ver_cur, Metadata#?METADATA.addr_id, Metadata#?METADATA.key), Ret = leo_backend_db_api:put_value_to_new_db( MetaDBId, KeyOfMeta, term_to_binary(Metadata_1)), execute_2(Ret, CompactionPrms, Metadata_1, NumOfActiveObjs, ActiveSize, State_1); Error -> {Error, State_1#compaction_worker_state{compaction_prms = CompactionPrms#compaction_prms{ metadata = Metadata}}} end, execute_1(Ret_1, NewState); false when IsDiagnosing == true -> ok = output_diagnosis_log(LoggerId, Metadata), {Ret_1, NewState} = execute_2( ok, CompactionPrms, Metadata, NumOfActiveObjs, ActiveSize, State_1), CompactionPrms_1 = NewState#compaction_worker_state.compaction_prms, execute_1(Ret_1, NewState#compaction_worker_state{ compaction_prms = CompactionPrms_1#compaction_prms{ total_num_of_objs = TotalObjs + 1, total_size_of_objs = TotaSize + leo_object_storage_haystack:calc_obj_size(Metadata) }}) end end. @private -spec(execute_1(State) -> {ok, {next|eof, State}} | {{error, any()}, State} when State::#compaction_worker_state{}). execute_1(State) -> execute_1(ok, State). execute_1(Ret, State) -> execute_1(Ret, State, 1). -spec(execute_1(Ret, State, RetryTimes) -> {ok, {next|eof, State}} | {{error, any()}, State} when Ret::ok|{error,any()}, State::#compaction_worker_state{}, RetryTimes::non_neg_integer()). execute_1(ok = Ret, #compaction_worker_state{meta_db_id = MetaDBId, obj_storage_info = StorageInfo, compaction_prms = CompactionPrms, compaction_skip_garbage = SkipInfo, skipped_bytes = SkippedBytes, is_skipping_garbage = IsSkipping, is_recovering = IsRecovering} = State, RetryTimes) -> ReadHandler = StorageInfo#backend_info.read_handler, NextOffset = CompactionPrms#compaction_prms.next_offset, case leo_object_storage_haystack:get_obj_for_new_cntnr( ReadHandler, NextOffset, SkipInfo) of {ok, NewMetadata, [_HeaderValue, NewKeyValue, NewBodyValue, NewNextOffset]} -> case IsRecovering of true -> #?METADATA{key = Key, addr_id = AddrId} = NewMetadata, KeyOfMetadata = ?gen_backend_key( StorageInfo#backend_info.avs_ver_prv, AddrId, Key), case leo_backend_db_api:put( MetaDBId, KeyOfMetadata, term_to_binary(NewMetadata)) of ok -> ok; {error, Cause} -> error_logger:error_msg("~p,~p,~p,~p~n", [{module, ?MODULE_STRING}, {function, "execute_1/2"}, {line, ?LINE}, {body, Cause}]), throw("unexpected_error happened at backend-db") end; false -> void end, next object {ok, State_1} = output_accumulated_errors(State, NextOffset), {ok, {next, State_1#compaction_worker_state{ error_pos = 0, set_errors = sets:new(), is_skipping_garbage = false, skipped_bytes = 0, compaction_skip_garbage = SkipInfo#compaction_skip_garbage{ is_skipping = false, is_close_eof = false, read_pos = 0, buf = <<>> }, compaction_prms = CompactionPrms#compaction_prms{ key_bin = NewKeyValue, body_bin = NewBodyValue, metadata = NewMetadata, next_offset = NewNextOffset} }}}; {error, eof = Cause} -> {ok, State_1} = output_accumulated_errors(State, NextOffset), NumOfAcriveObjs = CompactionPrms#compaction_prms.num_of_active_objs, SizeOfActiveObjs = CompactionPrms#compaction_prms.size_of_active_objs, {ok, {Cause, State_1#compaction_worker_state{ error_pos = 0, set_errors = sets:new(), is_skipping_garbage = false, skipped_bytes = 0, compaction_skip_garbage = SkipInfo#compaction_skip_garbage{ is_skipping = false, is_close_eof = false, read_pos = 0, buf = <<>> }, compaction_prms = CompactionPrms#compaction_prms{ num_of_active_objs = NumOfAcriveObjs, size_of_active_objs = SizeOfActiveObjs, next_offset = Cause} }}}; Aan issue of unexpected length happened , {error, {abort, unexpected_len = Cause}} when RetryTimes == ?MAX_RETRY_TIMES -> erlang:error(Cause); {error, {abort, unexpected_len = Cause}} -> error_logger:error_msg("~p,~p,~p,~p~n", [{module, ?MODULE_STRING}, {function, "execute_1/3"}, {line, ?LINE}, [{offset, NextOffset}, {body, Cause}]]), timer:sleep(?WAIT_TIME_AFTER_ERROR), execute_1(Ret, State, RetryTimes + 1); {skip, NewSkipInfo, Cause} -> SetErrors = sets:add_element(Cause, State#compaction_worker_state.set_errors), SkippedBytesNew = case IsSkipping of true -> SkippedBytes + 1; false -> 1 end, case SkippedBytes > ?env_compaction_force_quit_in_bytes() of true -> erlang:error(garbage_too_long); false -> nop end, {ok, {next, State#compaction_worker_state{ set_errors = SetErrors, is_skipping_garbage = true, skipped_bytes = SkippedBytesNew, compaction_skip_garbage = NewSkipInfo, compaction_prms = CompactionPrms#compaction_prms{ next_offset = NextOffset + 1} }}}; {_, Cause} -> ErrorPosCur = State#compaction_worker_state.error_pos, ErrorPosNew = case (State#compaction_worker_state.error_pos == 0) of true -> NextOffset; false -> ErrorPosCur end, SetErrors = sets:add_element(Cause, State#compaction_worker_state.set_errors), SkippedBytesNew = case IsSkipping of true -> SkippedBytes + 1; false -> 1 end, case SkippedBytes > ?env_compaction_force_quit_in_bytes() of true -> erlang:error(garbage_too_long); false -> nop end, {ok, {next, State#compaction_worker_state{ error_pos = ErrorPosNew, set_errors = SetErrors, is_skipping_garbage = true, skipped_bytes = SkippedBytesNew, compaction_skip_garbage = SkipInfo#compaction_skip_garbage{ is_skipping = true }, compaction_prms = CompactionPrms#compaction_prms{ next_offset = NextOffset + 1} }}} end; execute_1(Error, State,_) -> {Error, State}. @private execute_2(Ret, CompactionPrms, Metadata, NumOfActiveObjs, ActiveSize, State) -> ObjectSize = leo_object_storage_haystack:calc_obj_size(Metadata), {Ret, State#compaction_worker_state{ compaction_prms = CompactionPrms#compaction_prms{ metadata = Metadata, num_of_active_objs = NumOfActiveObjs + 1, size_of_active_objs = ActiveSize + ObjectSize}}}. @private finish(#compaction_worker_state{obj_storage_id = ObjStorageId, compact_cntl_pid = CntlPid, compaction_prms = CompactionPrms} = State) -> {ok, Report} = gen_compaction_report(State), erlang:send(CntlPid, {finish, {ObjStorageId, Report}}), Unlock handling request ok = leo_object_storage_server:unlock(ObjStorageId), {ok, State#compaction_worker_state{start_datetime = 0, error_pos = 0, set_errors = sets:new(), acc_errors = [], obj_storage_info = #backend_info{}, compaction_prms = CompactionPrms#compaction_prms{ key_bin = <<>>, body_bin = <<>>, metadata = #?METADATA{}, next_offset = 0, start_lock_offset = 0, num_of_active_objs = 0, size_of_active_objs = 0, total_num_of_objs = 0, total_size_of_objs = 0}, result = undefined}}. @private after_execute(Ret, #compaction_worker_state{obj_storage_info = StorageInfo, is_diagnosing = IsDiagnosing, is_recovering = _IsRecovering, diagnosis_log_id = LoggerId} = State) -> ReadHandler = StorageInfo#backend_info.read_handler, WriteHandler = StorageInfo#backend_info.write_handler, catch leo_object_storage_haystack:close(WriteHandler, ReadHandler), case IsDiagnosing of true when LoggerId /= undefined -> leo_logger_client_base:force_rotation(LoggerId); _ -> void end, ok = after_execute_1({Ret, State}), finish(State). @private after_execute_1({_, #compaction_worker_state{ is_diagnosing = true, compaction_prms = #compaction_prms{ num_of_active_objs = _NumActiveObjs, size_of_active_objs = _SizeActiveObjs}}}) -> ok; after_execute_1({ok, #compaction_worker_state{ meta_db_id = MetaDBId, obj_storage_id = ObjStorageId, obj_storage_id_read = ObjStorageId_R, obj_storage_info = StorageInfo, compaction_prms = #compaction_prms{ num_of_active_objs = NumActiveObjs, size_of_active_objs = SizeActiveObjs}}}) -> the symbol LinkedPath = StorageInfo#backend_info.linked_path, FilePath = StorageInfo#backend_info.file_path, catch file:delete(LinkedPath), case file:make_symlink(FilePath, LinkedPath) of ok -> ok = leo_object_storage_server:switch_container( ObjStorageId, FilePath, NumActiveObjs, SizeActiveObjs), NumOfObjStorageReadProcs = ?env_num_of_obj_storage_read_procs(), ok = after_execute_2(NumOfObjStorageReadProcs - 1, ObjStorageId_R, FilePath, NumActiveObjs, SizeActiveObjs), ok = leo_backend_db_api:finish_compaction(MetaDBId, true), ok; {error,_Cause} -> leo_backend_db_api:finish_compaction(MetaDBId, false), ok end; @private after_execute_1({_Error, #compaction_worker_state{ meta_db_id = MetaDBId, obj_storage_info = StorageInfo}}) -> catch file:delete(StorageInfo#backend_info.file_path), leo_backend_db_api:finish_compaction(MetaDBId, false), ok. @doc Switch an avs container for obj - storage - read @private after_execute_2(-1,_,_,_,_) -> ok; after_execute_2(ChildIndex, ObjStorageId_R, FilePath, NumActiveObjs, SizeActiveObjs) -> ObjStorageId_R_Child = list_to_atom( lists:append([atom_to_list(ObjStorageId_R), "_", integer_to_list(ChildIndex) ])), ok = leo_object_storage_server:switch_container( ObjStorageId_R_Child, FilePath, NumActiveObjs, SizeActiveObjs), after_execute_2(ChildIndex - 1, ObjStorageId_R, FilePath, NumActiveObjs, SizeActiveObjs). @private output_diagnosis_log(undefined,_Metadata) -> ok; output_diagnosis_log(LoggerId, Metadata) -> ?output_diagnosis_log(Metadata). @private -spec(output_accumulated_errors(State, ErrorPosEnd) -> {ok, State} when State::#compaction_worker_state{}, ErrorPosEnd::non_neg_integer()). output_accumulated_errors(#compaction_worker_state{ obj_storage_id = ObjStorageId, error_pos = ErrorPosStart, set_errors = SetErrors, acc_errors = AccErrors} = State, ErrorPosEnd) -> case sets:size(SetErrors) of 0 -> {ok, State}; _ -> {ok, StorageInfo} = ?get_obj_storage_info(ObjStorageId), Errors = sets:to_list(SetErrors), error_logger:warning_msg( "~p,~p,~p,~p~n", [{module, ?MODULE_STRING}, {function, "execute_1/4"}, {line, ?LINE}, {body, [{obj_container_path, StorageInfo#backend_info.file_path}, {error_pos_start, ErrorPosStart}, {error_pos_end, ErrorPosEnd}, {errors, Errors}]} ]), {ok, State#compaction_worker_state{ acc_errors = [{ErrorPosStart, ErrorPosEnd}|AccErrors]}} end. @private -spec(is_removed_obj(MetaDBId, StorageInfo, Metadata, IsRecovering) -> boolean() when MetaDBId::atom(), StorageInfo::#backend_info{}, Metadata::#?METADATA{}, IsRecovering::boolean()). is_removed_obj(_MetaDBId,_StorageInfo,_Metdata, true) -> false; is_removed_obj(MetaDBId, #backend_info{avs_ver_prv = AVSVsnBinPrv} = StorageInfo, #?METADATA{key = Key, addr_id = AddrId} = MetaFromAvs,_IsRecovering) -> KeyOfMetadata = ?gen_backend_key(AVSVsnBinPrv, AddrId, Key), case leo_backend_db_api:get(MetaDBId, KeyOfMetadata) of {ok, MetaBin} -> case binary_to_term(MetaBin) of #?METADATA{del = ?DEL_TRUE} -> true; Metadata -> is_removed_obj_1(MetaDBId, StorageInfo, MetaFromAvs, Metadata) end; not_found -> true; _Other -> false end. @private -spec(is_removed_obj_1(MetaDBId, StorageInfo, Metadata_1, Metadata_2) -> boolean() when MetaDBId::atom(), StorageInfo::#backend_info{}, Metadata_1::#?METADATA{}, Metadata_2::#?METADATA{}). is_removed_obj_1(_MetaDBId,_StorageInfo, #?METADATA{offset = Offset_1}, #?METADATA{offset = Offset_2}) when Offset_1 /= Offset_2 -> true; is_removed_obj_1(_MetaDBId,_StorageInfo,_Meta_1,_Meta_2) -> false. @private gen_compaction_report(State) -> #compaction_worker_state{obj_storage_id = ObjStorageId, compaction_prms = CompactionPrms, obj_storage_info = #backend_info{file_path = FilePath, linked_path = LinkedPath, avs_ver_prv = AVSVerPrev, avs_ver_cur = AVSVerCur}, start_datetime = StartDateTime, is_diagnosing = IsDiagnosing, is_recovering = _IsRecovering, acc_errors = AccErrors, result = Ret} = State, EndDateTime = leo_date:now(), Duration = EndDateTime - StartDateTime, StartDateTime_1 = lists:flatten(leo_date:date_format(StartDateTime)), EndDateTime_1 = lists:flatten(leo_date:date_format(EndDateTime)), ok = leo_object_storage_server:append_compaction_history( ObjStorageId, #compaction_hist{start_datetime = StartDateTime, end_datetime = EndDateTime, duration = Duration, result = Ret}), #compaction_prms{num_of_active_objs = ActiveObjs, size_of_active_objs = ActiveSize, total_num_of_objs = TotalObjs, total_size_of_objs = TotalSize} = CompactionPrms, CntnrVer = case IsDiagnosing of true -> AVSVerPrev; false -> AVSVerCur end, CntnrPath = case IsDiagnosing of true -> LinkedPath; false -> FilePath end, TotalObjs_1 = case IsDiagnosing of true -> TotalObjs; false -> ActiveObjs end, TotalSize_1 = case IsDiagnosing of true -> TotalSize; false -> ActiveSize end, Report = #compaction_report{ file_path = CntnrPath, avs_ver = CntnrVer, num_of_active_objs = ActiveObjs, size_of_active_objs = ActiveSize, total_num_of_objs = TotalObjs_1, total_size_of_objs = TotalSize_1, start_datetime = StartDateTime_1, end_datetime = EndDateTime_1, errors = lists:reverse(AccErrors), duration = Duration, result = Ret }, case leo_object_storage_server:get_stats(ObjStorageId) of {ok, #storage_stats{file_path = ObjDir} = CurStats} -> ok = leo_object_storage_server:set_stats(ObjStorageId, CurStats#storage_stats{ total_sizes = TotalSize_1, active_sizes = ActiveSize, total_num = TotalObjs_1, active_num = ActiveObjs}), Tokens = string:tokens(ObjDir, "/"), case (length(Tokens) > 2) of true -> LogFilePath = filename:join(["/"] ++ lists:sublist(Tokens, length(Tokens) - 2) ++ [?DEF_LOG_SUB_DIR ++ atom_to_list(ObjStorageId) ++ ?DIAGNOSIS_REP_SUFFIX ++ "." ++ integer_to_list(leo_date:now()) ]), Report_1 = lists:zip(record_info(fields, compaction_report), tl(tuple_to_list(Report))), catch leo_file:file_unconsult(LogFilePath, Report_1), error_logger:info_msg("~p,~p,~p,~p~n", [{module, ?MODULE_STRING}, {function, "gen_compaction_report/1"}, {line, ?LINE}, {body, [Report_1]}]), ok; false -> void end; _ -> void end, {ok, Report}. @private -spec(incr_interval_fun(Interval, MaxInterval, StepInterval) -> NewInterval when Interval::non_neg_integer(), MaxInterval::non_neg_integer(), StepInterval::non_neg_integer(), NewInterval::non_neg_integer()). incr_interval_fun(Interval, MaxInterval, StepInterval) -> Interval_1 = Interval + StepInterval, case (Interval_1 >= MaxInterval) of true -> MaxInterval; false -> Interval_1 end. @private -spec(decr_interval_fun(Interval, StepInterval) -> NewInterval when Interval::non_neg_integer(), StepInterval::non_neg_integer(), NewInterval::non_neg_integer()). decr_interval_fun(Interval, StepInterval) -> Interval_1 = Interval - StepInterval, case (Interval_1 =< ?DEF_MIN_COMPACTION_WT) of true -> ?DEF_MIN_COMPACTION_WT; false -> Interval_1 end. @private -spec(incr_batch_of_msgs_fun(BatchProcs, MaxBatchProcs, StepBatchProcs) -> NewBatchProcs when BatchProcs::non_neg_integer(), MaxBatchProcs::non_neg_integer(), StepBatchProcs::non_neg_integer(), NewBatchProcs::non_neg_integer()). incr_batch_of_msgs_fun(BatchProcs, MaxBatchProcs, StepBatchProcs) -> BatchProcs_1 = BatchProcs + StepBatchProcs, case (BatchProcs_1 > MaxBatchProcs) of true -> MaxBatchProcs; false -> BatchProcs_1 end. @private -spec(decr_batch_of_msgs_fun(BatchProcs, StepBatchProcs) -> NewBatchProcs when BatchProcs::non_neg_integer(), StepBatchProcs::non_neg_integer(), NewBatchProcs::non_neg_integer()). decr_batch_of_msgs_fun(BatchProcs, StepBatchProcs) -> BatchProcs_1 = BatchProcs - StepBatchProcs, case (BatchProcs_1 < 0) of true -> ?DEF_MIN_COMPACTION_BP; false -> BatchProcs_1 end.
edfb27a00e8a554534408459f7ebb38cf04d17595da598871e2000c30544d915
antono/guix-debian
rsync.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2012 , 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 rsync) #:use-module (gnu packages) #:use-module (gnu packages perl) #:use-module (gnu packages acl) #:use-module (gnu packages which) #:use-module (guix licenses) #:use-module (guix packages) #:use-module (guix download) #:use-module (guix build-system gnu)) (define-public rsync (package (name "rsync") (version "3.1.0") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.gz")) (sha256 (base32 "0kirw8wglqvwi1v8bwxp373g03xg857h59j5k3mmgff9gzvj7jl1")))) (build-system gnu-build-system) (inputs `(("perl" ,perl) ("acl" ,acl))) (synopsis "rsync, a remote (and local) file copying tool") (description "rsync is a fast and versatile file copying tool. It can copy locally, to/from another host over any remote shell, or to/from a remote rsync daemon. Its delta-transfer algorithm reduces the amount of data sent over the network by sending only the differences between the source files and the existing files in the destination.") (license gpl3+) (home-page "/"))) (define-public librsync (package (name "librsync") (version "0.9.7") (source (origin (method url-fetch) (uri (string-append "mirror/" version "/librsync-" version ".tar.gz")) (sha256 (base32 "1mj1pj99mgf1a59q9f2mxjli2fzxpnf55233pc1klxk2arhf8cv6")))) (build-system gnu-build-system) (native-inputs `(("which" ,which) ("perl" ,perl))) (arguments '(#:configure-flags '("--enable-shared"))) (home-page "/") (synopsis "Implementation of the rsync remote-delta algorithm") (description "Librsync is a free software library that implements the rsync remote-delta algorithm. This algorithm allows efficient remote updates of a file, without requiring the old and new versions to both be present at the sending end. The library uses a \"streaming\" design similar to that of zlib with the aim of allowing it to be embedded into many different applications.") (license lgpl2.1+)))
null
https://raw.githubusercontent.com/antono/guix-debian/85ef443788f0788a62010a942973d4f7714d10b4/gnu/packages/rsync.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.
Copyright © 2012 , 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 rsync) #:use-module (gnu packages) #:use-module (gnu packages perl) #:use-module (gnu packages acl) #:use-module (gnu packages which) #:use-module (guix licenses) #:use-module (guix packages) #:use-module (guix download) #:use-module (guix build-system gnu)) (define-public rsync (package (name "rsync") (version "3.1.0") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.gz")) (sha256 (base32 "0kirw8wglqvwi1v8bwxp373g03xg857h59j5k3mmgff9gzvj7jl1")))) (build-system gnu-build-system) (inputs `(("perl" ,perl) ("acl" ,acl))) (synopsis "rsync, a remote (and local) file copying tool") (description "rsync is a fast and versatile file copying tool. It can copy locally, to/from another host over any remote shell, or to/from a remote rsync daemon. Its delta-transfer algorithm reduces the amount of data sent over the network by sending only the differences between the source files and the existing files in the destination.") (license gpl3+) (home-page "/"))) (define-public librsync (package (name "librsync") (version "0.9.7") (source (origin (method url-fetch) (uri (string-append "mirror/" version "/librsync-" version ".tar.gz")) (sha256 (base32 "1mj1pj99mgf1a59q9f2mxjli2fzxpnf55233pc1klxk2arhf8cv6")))) (build-system gnu-build-system) (native-inputs `(("which" ,which) ("perl" ,perl))) (arguments '(#:configure-flags '("--enable-shared"))) (home-page "/") (synopsis "Implementation of the rsync remote-delta algorithm") (description "Librsync is a free software library that implements the rsync remote-delta algorithm. This algorithm allows efficient remote updates of a file, without requiring the old and new versions to both be present at the sending end. The library uses a \"streaming\" design similar to that of zlib with the aim of allowing it to be embedded into many different applications.") (license lgpl2.1+)))
a1882598fe1a74120bc3cebde07c7678345c8d6a301953f4723637ec166e5b11
clojure-interop/java-jdk
MultiPanelUI.clj
(ns javax.swing.plaf.multi.MultiPanelUI "A multiplexing UI used to combine PanelUIs. This file was automatically generated by AutoMulti." (:refer-clojure :only [require comment defn ->]) (:import [javax.swing.plaf.multi MultiPanelUI])) (defn ->multi-panel-ui "Constructor." (^MultiPanelUI [] (new MultiPanelUI ))) (defn *create-ui "Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel. a - `javax.swing.JComponent` returns: `javax.swing.plaf.ComponentUI`" (^javax.swing.plaf.ComponentUI [^javax.swing.JComponent a] (MultiPanelUI/createUI a))) (defn install-ui "Invokes the installUI method on each UI handled by this object. a - the component where this UI delegate is being installed - `javax.swing.JComponent`" ([^MultiPanelUI this ^javax.swing.JComponent a] (-> this (.installUI a)))) (defn get-minimum-size "Invokes the getMinimumSize method on each UI handled by this object. this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent ` returns: the value obtained from the first UI, which is the UI obtained from the default LookAndFeel - `java.awt.Dimension`" (^java.awt.Dimension [^MultiPanelUI this ^javax.swing.JComponent a] (-> this (.getMinimumSize a)))) (defn get-maximum-size "Invokes the getMaximumSize method on each UI handled by this object. this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent ` returns: the value obtained from the first UI, which is the UI obtained from the default LookAndFeel - `java.awt.Dimension`" (^java.awt.Dimension [^MultiPanelUI this ^javax.swing.JComponent a] (-> this (.getMaximumSize a)))) (defn get-accessible-child "Invokes the getAccessibleChild method on each UI handled by this object. a - `javax.swing.JComponent` b - `int` returns: the value obtained from the first UI, which is the UI obtained from the default LookAndFeel - `javax.accessibility.Accessible`" (^javax.accessibility.Accessible [^MultiPanelUI this ^javax.swing.JComponent a ^Integer b] (-> this (.getAccessibleChild a b)))) (defn get-u-is "Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components. returns: `javax.swing.plaf.ComponentUI[]`" ([^MultiPanelUI this] (-> this (.getUIs)))) (defn uninstall-ui "Invokes the uninstallUI method on each UI handled by this object. this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . ` " ([^MultiPanelUI this ^javax.swing.JComponent a] (-> this (.uninstallUI a)))) (defn contains "Invokes the contains method on each UI handled by this object. this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent ` b - the x coordinate of the point - `int` c - the y coordinate of the point - `int` returns: the value obtained from the first UI, which is the UI obtained from the default LookAndFeel - `boolean`" (^Boolean [^MultiPanelUI this ^javax.swing.JComponent a ^Integer b ^Integer c] (-> this (.contains a b c)))) (defn update "Invokes the update method on each UI handled by this object. a - the Graphics context in which to paint - `java.awt.Graphics` this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . ` " ([^MultiPanelUI this ^java.awt.Graphics a ^javax.swing.JComponent b] (-> this (.update a b)))) (defn get-accessible-children-count "Invokes the getAccessibleChildrenCount method on each UI handled by this object. a - `javax.swing.JComponent` returns: the value obtained from the first UI, which is the UI obtained from the default LookAndFeel - `int`" (^Integer [^MultiPanelUI this ^javax.swing.JComponent a] (-> this (.getAccessibleChildrenCount a)))) (defn paint "Invokes the paint method on each UI handled by this object. a - the Graphics context in which to paint - `java.awt.Graphics` this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . ` " ([^MultiPanelUI this ^java.awt.Graphics a ^javax.swing.JComponent b] (-> this (.paint a b)))) (defn get-preferred-size "Invokes the getPreferredSize method on each UI handled by this object. this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent ` returns: the value obtained from the first UI, which is the UI obtained from the default LookAndFeel - `java.awt.Dimension`" (^java.awt.Dimension [^MultiPanelUI this ^javax.swing.JComponent a] (-> this (.getPreferredSize a))))
null
https://raw.githubusercontent.com/clojure-interop/java-jdk/8d7a223e0f9a0965eb0332fad595cf7649d9d96e/javax.swing/src/javax/swing/plaf/multi/MultiPanelUI.clj
clojure
(ns javax.swing.plaf.multi.MultiPanelUI "A multiplexing UI used to combine PanelUIs. This file was automatically generated by AutoMulti." (:refer-clojure :only [require comment defn ->]) (:import [javax.swing.plaf.multi MultiPanelUI])) (defn ->multi-panel-ui "Constructor." (^MultiPanelUI [] (new MultiPanelUI ))) (defn *create-ui "Returns a multiplexing UI instance if any of the auxiliary LookAndFeels supports this UI. Otherwise, just returns the UI object obtained from the default LookAndFeel. a - `javax.swing.JComponent` returns: `javax.swing.plaf.ComponentUI`" (^javax.swing.plaf.ComponentUI [^javax.swing.JComponent a] (MultiPanelUI/createUI a))) (defn install-ui "Invokes the installUI method on each UI handled by this object. a - the component where this UI delegate is being installed - `javax.swing.JComponent`" ([^MultiPanelUI this ^javax.swing.JComponent a] (-> this (.installUI a)))) (defn get-minimum-size "Invokes the getMinimumSize method on each UI handled by this object. this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent ` returns: the value obtained from the first UI, which is the UI obtained from the default LookAndFeel - `java.awt.Dimension`" (^java.awt.Dimension [^MultiPanelUI this ^javax.swing.JComponent a] (-> this (.getMinimumSize a)))) (defn get-maximum-size "Invokes the getMaximumSize method on each UI handled by this object. this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent ` returns: the value obtained from the first UI, which is the UI obtained from the default LookAndFeel - `java.awt.Dimension`" (^java.awt.Dimension [^MultiPanelUI this ^javax.swing.JComponent a] (-> this (.getMaximumSize a)))) (defn get-accessible-child "Invokes the getAccessibleChild method on each UI handled by this object. a - `javax.swing.JComponent` b - `int` returns: the value obtained from the first UI, which is the UI obtained from the default LookAndFeel - `javax.accessibility.Accessible`" (^javax.accessibility.Accessible [^MultiPanelUI this ^javax.swing.JComponent a ^Integer b] (-> this (.getAccessibleChild a b)))) (defn get-u-is "Returns the list of UIs associated with this multiplexing UI. This allows processing of the UIs by an application aware of multiplexing UIs on components. returns: `javax.swing.plaf.ComponentUI[]`" ([^MultiPanelUI this] (-> this (.getUIs)))) (defn uninstall-ui "Invokes the uninstallUI method on each UI handled by this object. this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . ` " ([^MultiPanelUI this ^javax.swing.JComponent a] (-> this (.uninstallUI a)))) (defn contains "Invokes the contains method on each UI handled by this object. this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent ` b - the x coordinate of the point - `int` c - the y coordinate of the point - `int` returns: the value obtained from the first UI, which is the UI obtained from the default LookAndFeel - `boolean`" (^Boolean [^MultiPanelUI this ^javax.swing.JComponent a ^Integer b ^Integer c] (-> this (.contains a b c)))) (defn update "Invokes the update method on each UI handled by this object. a - the Graphics context in which to paint - `java.awt.Graphics` this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . ` " ([^MultiPanelUI this ^java.awt.Graphics a ^javax.swing.JComponent b] (-> this (.update a b)))) (defn get-accessible-children-count "Invokes the getAccessibleChildrenCount method on each UI handled by this object. a - `javax.swing.JComponent` returns: the value obtained from the first UI, which is the UI obtained from the default LookAndFeel - `int`" (^Integer [^MultiPanelUI this ^javax.swing.JComponent a] (-> this (.getAccessibleChildrenCount a)))) (defn paint "Invokes the paint method on each UI handled by this object. a - the Graphics context in which to paint - `java.awt.Graphics` this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . ` " ([^MultiPanelUI this ^java.awt.Graphics a ^javax.swing.JComponent b] (-> this (.paint a b)))) (defn get-preferred-size "Invokes the getPreferredSize method on each UI handled by this object. this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent ` returns: the value obtained from the first UI, which is the UI obtained from the default LookAndFeel - `java.awt.Dimension`" (^java.awt.Dimension [^MultiPanelUI this ^javax.swing.JComponent a] (-> this (.getPreferredSize a))))
f54f0898af95f070bcbacae1e118502b1d7e0c7c12e77702f8165bb41dacf5f7
haskell-tools/haskell-tools
CanCaptureVariable_res.hs
# LANGUAGE ScopedTypeVariables # module Refactor.GenerateTypeSignature.CanCaptureVariable where import qualified Data.Map as Map insertMany :: forall k v . (Ord k) => (v -> v -> v) -> [(k,v)] -> Map.Map k v -> Map.Map k v insertMany accf vs m = foldr f1 m vs where f1 :: Ord k => (k, v) -> Map.Map k v -> Map.Map k v f1 (k,v) m = Map.insertWith accf k v m
null
https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/builtin-refactorings/examples/Refactor/GenerateTypeSignature/CanCaptureVariable_res.hs
haskell
# LANGUAGE ScopedTypeVariables # module Refactor.GenerateTypeSignature.CanCaptureVariable where import qualified Data.Map as Map insertMany :: forall k v . (Ord k) => (v -> v -> v) -> [(k,v)] -> Map.Map k v -> Map.Map k v insertMany accf vs m = foldr f1 m vs where f1 :: Ord k => (k, v) -> Map.Map k v -> Map.Map k v f1 (k,v) m = Map.insertWith accf k v m
3d02e7d9df0973ed3c2a232efc2d5ade9d92eeb58a062223e17357ddebbd127c
composewell/streamly
MutArray.hs
-- | Module : Streamly . Data . MutArray Copyright : ( c ) 2022 Composewell Technologies -- -- License : BSD3 -- Maintainer : -- Stability : released Portability : GHC -- Mutable version of " Streamly . Data . Array " . Please refer to that module for -- general documentation. The contents of mutable ararys can be modified -- in-place. -- See " Streamly . Data . MutArray . Generic " for mutable arrays that work for boxed -- types i.e. not requiring the 'Unbox' constraint. module Streamly.Data.MutArray ( -- * Types MutArray -- * Construction -- Uninitialized Arrays , new , newPinned -- From containers , fromListN , fromList , writeN -- drop new , write -- full buffer -- writeLastN -- * Appending elements , snoc -- * Appending streams , writeAppendN , writeAppend * Inplace mutation , putIndex -- * Random access , getIndex -- * Conversion , toList -- * Unfolds , reader , readerRev -- * Casting , cast , asBytes -- * Size , length -- * Unbox Type Class , Unbox (..) ) where import Prelude hiding (length, read) import Streamly.Internal.Data.Array.Mut import Streamly.Internal.Data.Unboxed (Unbox (..))
null
https://raw.githubusercontent.com/composewell/streamly/ba0d42aec0dffda628a4872063f63d90e6ccb1ad/core/src/Streamly/Data/MutArray.hs
haskell
| License : BSD3 Maintainer : Stability : released general documentation. The contents of mutable ararys can be modified in-place. types i.e. not requiring the 'Unbox' constraint. * Types * Construction Uninitialized Arrays From containers drop new full buffer writeLastN * Appending elements * Appending streams * Random access * Conversion * Unfolds * Casting * Size * Unbox Type Class
Module : Streamly . Data . MutArray Copyright : ( c ) 2022 Composewell Technologies Portability : GHC Mutable version of " Streamly . Data . Array " . Please refer to that module for See " Streamly . Data . MutArray . Generic " for mutable arrays that work for boxed module Streamly.Data.MutArray ( MutArray , new , newPinned , fromListN , fromList , snoc , writeAppendN , writeAppend * Inplace mutation , putIndex , getIndex , toList , reader , readerRev , cast , asBytes , length , Unbox (..) ) where import Prelude hiding (length, read) import Streamly.Internal.Data.Array.Mut import Streamly.Internal.Data.Unboxed (Unbox (..))
23b52723c5dd8c6f09f158d0eea66c0a9f1f79b21a14e8e47383af90114912e1
colis-anr/colis-language
mkdir.ml
open Format open Colis_constraints open SymbolicUtility.Mixed let name = "mkdir" let interp_mkdir1 cwd path_str = let path = Path.strip_trailing_slashes path_str in let p = Path.from_string path in match Path.split_last p with | None -> specification_cases [ error_case ~descr:"mkdir: cannot create directory ''" noop ] | Some (q, (Here|Up)) -> specification_cases [ error_case ~descr:(asprintf "mkdir %a: target already exists" Path.pp q) (case_spec ~constraints:begin fun root root' -> exists @@ fun x -> resolve root cwd q x & dir x & eq root root' end ()); error_case ~descr:(asprintf "mkdir %a: path does not resolve" Path.pp q) (case_spec ~constraints:begin fun root root' -> exists @@ fun x -> maybe_resolve root cwd q x & ndir x & eq root root' end ()); ] | Some (q, Down f) -> specification_cases [ success_case ~descr:(asprintf "mkdir %a: create directory" Path.pp p) (case_spec ~transducers:() ~constraints:begin fun root root' -> exists3 @@ fun x x' y -> resolve root cwd q x & dir x & abs x f & similar root root' cwd q x x' & sim x (Feat.Set.singleton f) x' & dir x' & feat x' f y & dir y & fen y Feat.Set.empty end ()); error_case ~descr:(asprintf "mkdir %a: target already exists" Path.pp p) (case_spec ~constraints:begin fun root root' -> exists @@ fun x -> resolve root cwd q x & dir x & nabs x f & eq root root' end ()); error_case ~descr:(asprintf "mkdir %a: parent path is file or does not resolve" Path.pp p) (case_spec ~constraints:begin fun root root' -> exists @@ fun x -> maybe_resolve root cwd q x & ndir x & eq root root' end ()); ] let interprete parents ctx args : utility = if parents then incomplete ~utility:name "option -p" else multiple_times (interp_mkdir1 ctx.cwd) args let interprete ctx : utility = let parents = Cmdliner.Arg.(value & flag & info ["p"; "parents"]) in cmdliner_eval_utility ~utility:name Cmdliner.Term.(const interprete $ parents) ctx
null
https://raw.githubusercontent.com/colis-anr/colis-language/b4082a65302a6f164ab6f873a6da1206b6b6afd1/src/symbolic/utilities/mkdir.ml
ocaml
open Format open Colis_constraints open SymbolicUtility.Mixed let name = "mkdir" let interp_mkdir1 cwd path_str = let path = Path.strip_trailing_slashes path_str in let p = Path.from_string path in match Path.split_last p with | None -> specification_cases [ error_case ~descr:"mkdir: cannot create directory ''" noop ] | Some (q, (Here|Up)) -> specification_cases [ error_case ~descr:(asprintf "mkdir %a: target already exists" Path.pp q) (case_spec ~constraints:begin fun root root' -> exists @@ fun x -> resolve root cwd q x & dir x & eq root root' end ()); error_case ~descr:(asprintf "mkdir %a: path does not resolve" Path.pp q) (case_spec ~constraints:begin fun root root' -> exists @@ fun x -> maybe_resolve root cwd q x & ndir x & eq root root' end ()); ] | Some (q, Down f) -> specification_cases [ success_case ~descr:(asprintf "mkdir %a: create directory" Path.pp p) (case_spec ~transducers:() ~constraints:begin fun root root' -> exists3 @@ fun x x' y -> resolve root cwd q x & dir x & abs x f & similar root root' cwd q x x' & sim x (Feat.Set.singleton f) x' & dir x' & feat x' f y & dir y & fen y Feat.Set.empty end ()); error_case ~descr:(asprintf "mkdir %a: target already exists" Path.pp p) (case_spec ~constraints:begin fun root root' -> exists @@ fun x -> resolve root cwd q x & dir x & nabs x f & eq root root' end ()); error_case ~descr:(asprintf "mkdir %a: parent path is file or does not resolve" Path.pp p) (case_spec ~constraints:begin fun root root' -> exists @@ fun x -> maybe_resolve root cwd q x & ndir x & eq root root' end ()); ] let interprete parents ctx args : utility = if parents then incomplete ~utility:name "option -p" else multiple_times (interp_mkdir1 ctx.cwd) args let interprete ctx : utility = let parents = Cmdliner.Arg.(value & flag & info ["p"; "parents"]) in cmdliner_eval_utility ~utility:name Cmdliner.Term.(const interprete $ parents) ctx
59b67dc8f85ae504aec10b5d2ea0bc0b90bcdf121e3a3dfefe3bb748c6a52f41
hawkir/calispel
package.lisp
(in-package #:common-lisp-user) (defpackage #:calispel (:export ;; Basic functionality. #:channel #:? #:! #:fair-alt #:pri-alt #:otherwise #:null-queue #:+null-queue+ ;; Provided for dynamic alternation. #:operation-alternate #:operation #:direction #:value #:send #:receive ;; Testing. #:test-channel #:test-concurrency) (:shadowing-import-from #:jpl-util #:sort #:nsort #:stable-sort #:nstable-sort) (:use #:common-lisp))
null
https://raw.githubusercontent.com/hawkir/calispel/e9f2f9c1af97f4d7bb4c8ac25fb2a8f3e8fada7a/package.lisp
lisp
Basic functionality. Provided for dynamic alternation. Testing.
(in-package #:common-lisp-user) (defpackage #:calispel #:channel #:? #:! #:fair-alt #:pri-alt #:otherwise #:null-queue #:+null-queue+ #:operation-alternate #:operation #:direction #:value #:send #:receive #:test-channel #:test-concurrency) (:shadowing-import-from #:jpl-util #:sort #:nsort #:stable-sort #:nstable-sort) (:use #:common-lisp))
26c5da67c127a046410bf434975a49129ea5d446d0bcce2489eef1940163958b
phantomics/seed
graph.garden-path.lisp
graph.garden-path.lisp (in-package #:seed.generate) (specify-media media-spec-graph-garden-path (graph-garden-path-content (follows reagent graph-id) `((set-branch-meta branch :change nil) (cond ((eq :node (caar data)) (labels ((transcribe (target items) (if (not items) target (progn (setf (getf (getf target :meta) (first items)) (second items)) (transcribe target (cddr items)))))) (setf (branch-image branch) (loop for item in (branch-image branch) collect (if (eq (getf item :id) (of-branch-meta branch :point)) (transcribe item (cdar data)) item))) (set-branch-meta branch :change (list :node-changed t :node-id (string-upcase (of-branch-meta branch :point)))) (branch-image branch))) ((get-param :set-point) (set-branch-meta branch :point (intern (get-param :node-id) "KEYWORD")) (branch-image branch)) ((get-param :add-node) (multiple-value-bind (output-data new-node-id) (add-blank-node (branch-image branch) (get-param :object-type) (get-param :object-meta)) (set-branch-meta branch :change (list :node-added t :new-id (string-upcase new-node-id))) (setf (branch-image branch) output-data))) ((get-param :add-link) (add-blank-link (branch-image branch) (intern (get-param :node-id) "KEYWORD") (get-param :object-meta)) (set-branch-meta branch :change (list :link-added t :node-id (get-param :node-id))) (branch-image branch)) ((get-param :connect-link) (connect-link (branch-image branch) (intern (get-param :node-id) "KEYWORD") (intern (get-param :link-id) "KEYWORD") (intern (get-param :destination-node-id) "KEYWORD") (get-param :object-meta)) (set-branch-meta branch :change (list :link-connected t :node-id (string-upcase (get-param :node-id)) :link-id (string-upcase (get-param :link-id)))) (branch-image branch)) ((get-param :remove-object) (setf (branch-image branch) (remove-graph-element (branch-image branch) (intern (get-param :node-id) "KEYWORD") (if (get-param :link-id) (intern (get-param :link-id) "KEYWORD")))) (set-branch-meta branch :change (list :object-removed t :node-id (get-param :node-id) :link-id (if (get-param :link-id) (get-param :link-id) ""))) (branch-image branch)) (t (set-branch-meta branch :change nil) (branch-image branch)))) `((let ((to-return nil)) (loop for item in ,reagent while (not to-return) do (if (string= (string-upcase ,graph-id) (string-upcase (second item))) (setq to-return (cddr item)))) to-return))) (graph-garden-path-display (follows reagent) `((if (not (of-branch-meta branch :point)) (set-branch-meta branch :point (getf (first (branch-image branch)) :id))) (preprocess-nodes ,(if reagent reagent `(branch-image branch))))) (graph-garden-path-node-content (follows reagent point) `((let ((to-return nil)) ;; (print (list :reg reagent ,point)) (loop for item in ,reagent while (not to-return) do (if (string= (string-upcase ,point) (string-upcase (getf item :id))) (setq to-return item))) `((:node ,@(getf to-return :meta) ,@(if (getf to-return :do) (list :action (getf to-return :do)))))))) )
null
https://raw.githubusercontent.com/phantomics/seed/f128969c671c078543574395d6b23a1a5f2723f8/seed.media.graph.garden-path/graph.garden-path.lisp
lisp
(print (list :reg reagent ,point))
graph.garden-path.lisp (in-package #:seed.generate) (specify-media media-spec-graph-garden-path (graph-garden-path-content (follows reagent graph-id) `((set-branch-meta branch :change nil) (cond ((eq :node (caar data)) (labels ((transcribe (target items) (if (not items) target (progn (setf (getf (getf target :meta) (first items)) (second items)) (transcribe target (cddr items)))))) (setf (branch-image branch) (loop for item in (branch-image branch) collect (if (eq (getf item :id) (of-branch-meta branch :point)) (transcribe item (cdar data)) item))) (set-branch-meta branch :change (list :node-changed t :node-id (string-upcase (of-branch-meta branch :point)))) (branch-image branch))) ((get-param :set-point) (set-branch-meta branch :point (intern (get-param :node-id) "KEYWORD")) (branch-image branch)) ((get-param :add-node) (multiple-value-bind (output-data new-node-id) (add-blank-node (branch-image branch) (get-param :object-type) (get-param :object-meta)) (set-branch-meta branch :change (list :node-added t :new-id (string-upcase new-node-id))) (setf (branch-image branch) output-data))) ((get-param :add-link) (add-blank-link (branch-image branch) (intern (get-param :node-id) "KEYWORD") (get-param :object-meta)) (set-branch-meta branch :change (list :link-added t :node-id (get-param :node-id))) (branch-image branch)) ((get-param :connect-link) (connect-link (branch-image branch) (intern (get-param :node-id) "KEYWORD") (intern (get-param :link-id) "KEYWORD") (intern (get-param :destination-node-id) "KEYWORD") (get-param :object-meta)) (set-branch-meta branch :change (list :link-connected t :node-id (string-upcase (get-param :node-id)) :link-id (string-upcase (get-param :link-id)))) (branch-image branch)) ((get-param :remove-object) (setf (branch-image branch) (remove-graph-element (branch-image branch) (intern (get-param :node-id) "KEYWORD") (if (get-param :link-id) (intern (get-param :link-id) "KEYWORD")))) (set-branch-meta branch :change (list :object-removed t :node-id (get-param :node-id) :link-id (if (get-param :link-id) (get-param :link-id) ""))) (branch-image branch)) (t (set-branch-meta branch :change nil) (branch-image branch)))) `((let ((to-return nil)) (loop for item in ,reagent while (not to-return) do (if (string= (string-upcase ,graph-id) (string-upcase (second item))) (setq to-return (cddr item)))) to-return))) (graph-garden-path-display (follows reagent) `((if (not (of-branch-meta branch :point)) (set-branch-meta branch :point (getf (first (branch-image branch)) :id))) (preprocess-nodes ,(if reagent reagent `(branch-image branch))))) (graph-garden-path-node-content (follows reagent point) `((let ((to-return nil)) (loop for item in ,reagent while (not to-return) do (if (string= (string-upcase ,point) (string-upcase (getf item :id))) (setq to-return item))) `((:node ,@(getf to-return :meta) ,@(if (getf to-return :do) (list :action (getf to-return :do)))))))) )
52612e8c482df5662cf18e0123bb90983216e1f640692680b1f7d4102dc17ab2
jeromesimeon/Galax
print_type_core.mli
(***********************************************************************) (* *) (* GALAX *) (* XQuery Engine *) (* *) Copyright 2001 - 2007 . (* Distributed only by permission. *) (* *) (***********************************************************************) $ I d : print_type_core.mli , v 1.4 2007/02/01 22:08:45 simeon Exp $ (* Module: Print_core_type Description: This module implements pretty-printing for the core variant of the XQuery type system. *) val print_celem_decl : Format.formatter -> Xquery_type_core_ast.celem_declaration -> unit val print_cattr_decl : Format.formatter -> Xquery_type_core_ast.cattr_declaration -> unit val print_ctype_decl : Format.formatter -> Xquery_type_core_ast.ctype_declaration -> unit val print_cxtype : Format.formatter -> Xquery_type_core_ast.cxtype -> unit val bprint_cxtype : Xquery_type_core_ast.cxtype -> string val print_cxschema : Format.formatter -> Xquery_type_core_ast.cxschema -> unit val print_letter_mappings : Format.formatter -> Xquery_type_core_ast_annotation.letter_mappings -> unit
null
https://raw.githubusercontent.com/jeromesimeon/Galax/bc565acf782c140291911d08c1c784c9ac09b432/ast_printer/print_type_core.mli
ocaml
********************************************************************* GALAX XQuery Engine Distributed only by permission. ********************************************************************* Module: Print_core_type Description: This module implements pretty-printing for the core variant of the XQuery type system.
Copyright 2001 - 2007 . $ I d : print_type_core.mli , v 1.4 2007/02/01 22:08:45 simeon Exp $ val print_celem_decl : Format.formatter -> Xquery_type_core_ast.celem_declaration -> unit val print_cattr_decl : Format.formatter -> Xquery_type_core_ast.cattr_declaration -> unit val print_ctype_decl : Format.formatter -> Xquery_type_core_ast.ctype_declaration -> unit val print_cxtype : Format.formatter -> Xquery_type_core_ast.cxtype -> unit val bprint_cxtype : Xquery_type_core_ast.cxtype -> string val print_cxschema : Format.formatter -> Xquery_type_core_ast.cxschema -> unit val print_letter_mappings : Format.formatter -> Xquery_type_core_ast_annotation.letter_mappings -> unit
00a748bdb490c2af6526ec0b109bcb1da229dabfa7bf2eb0cc1b903bc1441088
kronkltd/jiksnu
domain_actions_test.clj
(ns jiksnu.modules.core.actions.domain-actions-test (:require [clj-factory.core :refer [factory fseq]] [jiksnu.modules.core.actions.domain-actions :as actions.domain] [jiksnu.mock :as mock] [jiksnu.modules.core.model.domain :as model.domain] [jiksnu.test-helper :as th] [midje.sweet :refer :all]) (:import jiksnu.modules.core.model.Domain)) (th/module-test ["jiksnu.modules.core"]) (fact "#'actions.domain/create" (fact "when given valid options" (fact "and the domain does not already exist" (model.domain/drop!) (let [options (actions.domain/prepare-create {:_id (fseq :domain)})] (actions.domain/create options) => (partial instance? Domain))))) (fact "#'actions.domain/delete" ;; There is no reason this shouldn't be a success (fact "when the domain does not exist" (model.domain/drop!) (let [domain (factory :domain {:_id (fseq :domain)})] (actions.domain/delete domain) => nil?)) (fact "when the domain exists" (let [domain (mock/a-domain-exists) id (:_id domain)] ;; Returns the domain, if deleted (actions.domain/delete domain) => domain ;; Should be deleted (model.domain/fetch-by-id id) => nil?))) (fact "#'actions.domain/show" (actions.domain/show .domain.) => .domain.)
null
https://raw.githubusercontent.com/kronkltd/jiksnu/8c91e9b1fddcc0224b028e573f7c3ca2f227e516/test/jiksnu/modules/core/actions/domain_actions_test.clj
clojure
There is no reason this shouldn't be a success Returns the domain, if deleted Should be deleted
(ns jiksnu.modules.core.actions.domain-actions-test (:require [clj-factory.core :refer [factory fseq]] [jiksnu.modules.core.actions.domain-actions :as actions.domain] [jiksnu.mock :as mock] [jiksnu.modules.core.model.domain :as model.domain] [jiksnu.test-helper :as th] [midje.sweet :refer :all]) (:import jiksnu.modules.core.model.Domain)) (th/module-test ["jiksnu.modules.core"]) (fact "#'actions.domain/create" (fact "when given valid options" (fact "and the domain does not already exist" (model.domain/drop!) (let [options (actions.domain/prepare-create {:_id (fseq :domain)})] (actions.domain/create options) => (partial instance? Domain))))) (fact "#'actions.domain/delete" (fact "when the domain does not exist" (model.domain/drop!) (let [domain (factory :domain {:_id (fseq :domain)})] (actions.domain/delete domain) => nil?)) (fact "when the domain exists" (let [domain (mock/a-domain-exists) id (:_id domain)] (actions.domain/delete domain) => domain (model.domain/fetch-by-id id) => nil?))) (fact "#'actions.domain/show" (actions.domain/show .domain.) => .domain.)
9e075070374ab0a0e1e7108c0390bca5cb213e48a83ed2ce0972cb45ddfddf00
lem-project/lem
editor-variables.lisp
(in-package :lem-base) (define-editor-variable tab-width +default-tab-size+)
null
https://raw.githubusercontent.com/lem-project/lem/3b9b92690b48710135a946b1d3754f64d2bfdaf1/src/base/editor-variables.lisp
lisp
(in-package :lem-base) (define-editor-variable tab-width +default-tab-size+)
5f08eb0239c04b4654c00e8e0dfe1f219f83e0473c7c4c6bfcb213eac9e665b3
clojure-interop/aws-api
AbstractAWSResourceGroupsTaggingAPI.clj
(ns com.amazonaws.services.resourcegroupstaggingapi.AbstractAWSResourceGroupsTaggingAPI "Abstract implementation of AWSResourceGroupsTaggingAPI. Convenient method forms pass through to the corresponding overload that takes a request object, which throws an UnsupportedOperationException." (:refer-clojure :only [require comment defn ->]) (:import [com.amazonaws.services.resourcegroupstaggingapi AbstractAWSResourceGroupsTaggingAPI])) (defn get-resources "Description copied from interface: AWSResourceGroupsTaggingAPI request - `com.amazonaws.services.resourcegroupstaggingapi.model.GetResourcesRequest` returns: Result of the GetResources operation returned by the service. - `com.amazonaws.services.resourcegroupstaggingapi.model.GetResourcesResult`" (^com.amazonaws.services.resourcegroupstaggingapi.model.GetResourcesResult [^AbstractAWSResourceGroupsTaggingAPI this ^com.amazonaws.services.resourcegroupstaggingapi.model.GetResourcesRequest request] (-> this (.getResources request)))) (defn get-tag-keys "Description copied from interface: AWSResourceGroupsTaggingAPI request - `com.amazonaws.services.resourcegroupstaggingapi.model.GetTagKeysRequest` returns: Result of the GetTagKeys operation returned by the service. - `com.amazonaws.services.resourcegroupstaggingapi.model.GetTagKeysResult`" (^com.amazonaws.services.resourcegroupstaggingapi.model.GetTagKeysResult [^AbstractAWSResourceGroupsTaggingAPI this ^com.amazonaws.services.resourcegroupstaggingapi.model.GetTagKeysRequest request] (-> this (.getTagKeys request)))) (defn get-tag-values "Description copied from interface: AWSResourceGroupsTaggingAPI request - `com.amazonaws.services.resourcegroupstaggingapi.model.GetTagValuesRequest` returns: Result of the GetTagValues operation returned by the service. - `com.amazonaws.services.resourcegroupstaggingapi.model.GetTagValuesResult`" (^com.amazonaws.services.resourcegroupstaggingapi.model.GetTagValuesResult [^AbstractAWSResourceGroupsTaggingAPI this ^com.amazonaws.services.resourcegroupstaggingapi.model.GetTagValuesRequest request] (-> this (.getTagValues request)))) (defn tag-resources "Description copied from interface: AWSResourceGroupsTaggingAPI request - `com.amazonaws.services.resourcegroupstaggingapi.model.TagResourcesRequest` returns: Result of the TagResources operation returned by the service. - `com.amazonaws.services.resourcegroupstaggingapi.model.TagResourcesResult`" (^com.amazonaws.services.resourcegroupstaggingapi.model.TagResourcesResult [^AbstractAWSResourceGroupsTaggingAPI this ^com.amazonaws.services.resourcegroupstaggingapi.model.TagResourcesRequest request] (-> this (.tagResources request)))) (defn untag-resources "Description copied from interface: AWSResourceGroupsTaggingAPI request - `com.amazonaws.services.resourcegroupstaggingapi.model.UntagResourcesRequest` returns: Result of the UntagResources operation returned by the service. - `com.amazonaws.services.resourcegroupstaggingapi.model.UntagResourcesResult`" (^com.amazonaws.services.resourcegroupstaggingapi.model.UntagResourcesResult [^AbstractAWSResourceGroupsTaggingAPI this ^com.amazonaws.services.resourcegroupstaggingapi.model.UntagResourcesRequest request] (-> this (.untagResources request)))) (defn shutdown "Description copied from interface: AWSResourceGroupsTaggingAPI" ([^AbstractAWSResourceGroupsTaggingAPI this] (-> this (.shutdown)))) (defn get-cached-response-metadata "Description copied from interface: AWSResourceGroupsTaggingAPI request - The originally executed request. - `com.amazonaws.AmazonWebServiceRequest` returns: The response metadata for the specified request, or null if none is available. - `com.amazonaws.ResponseMetadata`" (^com.amazonaws.ResponseMetadata [^AbstractAWSResourceGroupsTaggingAPI this ^com.amazonaws.AmazonWebServiceRequest request] (-> this (.getCachedResponseMetadata request))))
null
https://raw.githubusercontent.com/clojure-interop/aws-api/59249b43d3bfaff0a79f5f4f8b7bc22518a3bf14/com.amazonaws.services.resourcegroupstaggingapi/src/com/amazonaws/services/resourcegroupstaggingapi/AbstractAWSResourceGroupsTaggingAPI.clj
clojure
(ns com.amazonaws.services.resourcegroupstaggingapi.AbstractAWSResourceGroupsTaggingAPI "Abstract implementation of AWSResourceGroupsTaggingAPI. Convenient method forms pass through to the corresponding overload that takes a request object, which throws an UnsupportedOperationException." (:refer-clojure :only [require comment defn ->]) (:import [com.amazonaws.services.resourcegroupstaggingapi AbstractAWSResourceGroupsTaggingAPI])) (defn get-resources "Description copied from interface: AWSResourceGroupsTaggingAPI request - `com.amazonaws.services.resourcegroupstaggingapi.model.GetResourcesRequest` returns: Result of the GetResources operation returned by the service. - `com.amazonaws.services.resourcegroupstaggingapi.model.GetResourcesResult`" (^com.amazonaws.services.resourcegroupstaggingapi.model.GetResourcesResult [^AbstractAWSResourceGroupsTaggingAPI this ^com.amazonaws.services.resourcegroupstaggingapi.model.GetResourcesRequest request] (-> this (.getResources request)))) (defn get-tag-keys "Description copied from interface: AWSResourceGroupsTaggingAPI request - `com.amazonaws.services.resourcegroupstaggingapi.model.GetTagKeysRequest` returns: Result of the GetTagKeys operation returned by the service. - `com.amazonaws.services.resourcegroupstaggingapi.model.GetTagKeysResult`" (^com.amazonaws.services.resourcegroupstaggingapi.model.GetTagKeysResult [^AbstractAWSResourceGroupsTaggingAPI this ^com.amazonaws.services.resourcegroupstaggingapi.model.GetTagKeysRequest request] (-> this (.getTagKeys request)))) (defn get-tag-values "Description copied from interface: AWSResourceGroupsTaggingAPI request - `com.amazonaws.services.resourcegroupstaggingapi.model.GetTagValuesRequest` returns: Result of the GetTagValues operation returned by the service. - `com.amazonaws.services.resourcegroupstaggingapi.model.GetTagValuesResult`" (^com.amazonaws.services.resourcegroupstaggingapi.model.GetTagValuesResult [^AbstractAWSResourceGroupsTaggingAPI this ^com.amazonaws.services.resourcegroupstaggingapi.model.GetTagValuesRequest request] (-> this (.getTagValues request)))) (defn tag-resources "Description copied from interface: AWSResourceGroupsTaggingAPI request - `com.amazonaws.services.resourcegroupstaggingapi.model.TagResourcesRequest` returns: Result of the TagResources operation returned by the service. - `com.amazonaws.services.resourcegroupstaggingapi.model.TagResourcesResult`" (^com.amazonaws.services.resourcegroupstaggingapi.model.TagResourcesResult [^AbstractAWSResourceGroupsTaggingAPI this ^com.amazonaws.services.resourcegroupstaggingapi.model.TagResourcesRequest request] (-> this (.tagResources request)))) (defn untag-resources "Description copied from interface: AWSResourceGroupsTaggingAPI request - `com.amazonaws.services.resourcegroupstaggingapi.model.UntagResourcesRequest` returns: Result of the UntagResources operation returned by the service. - `com.amazonaws.services.resourcegroupstaggingapi.model.UntagResourcesResult`" (^com.amazonaws.services.resourcegroupstaggingapi.model.UntagResourcesResult [^AbstractAWSResourceGroupsTaggingAPI this ^com.amazonaws.services.resourcegroupstaggingapi.model.UntagResourcesRequest request] (-> this (.untagResources request)))) (defn shutdown "Description copied from interface: AWSResourceGroupsTaggingAPI" ([^AbstractAWSResourceGroupsTaggingAPI this] (-> this (.shutdown)))) (defn get-cached-response-metadata "Description copied from interface: AWSResourceGroupsTaggingAPI request - The originally executed request. - `com.amazonaws.AmazonWebServiceRequest` returns: The response metadata for the specified request, or null if none is available. - `com.amazonaws.ResponseMetadata`" (^com.amazonaws.ResponseMetadata [^AbstractAWSResourceGroupsTaggingAPI this ^com.amazonaws.AmazonWebServiceRequest request] (-> this (.getCachedResponseMetadata request))))
98b4e0250ec32be8a7813309f690c65516dfa470c4115bcea08d419c7e0ccbb0
scheme/scsh
lib-dirs.scm
;;; More imports for the new library-search facility: ;;; HANDLE: with-handler ;;; LIST-LIB: any ;;; SCSH-LEVEL-0: directory-files open-input-file file-directory? SCSH - LEVEL-0 : ;;; SCSH-LEVEL-0: the file-name procs (define default-lib-dirs '("/usr/local/lib/scsh/modules/")) (define (set-default-lib-dirs! path-list) (set! default-lib-dirs path-list)) Search library dirs for FILE . (define (find-library-file file lib-dirs script-file) (letrec ((recur (lambda (dir) ( format ( error - output - port ) " flf -- entering ~a\n " dir ) (let* ((f (string-append dir file))) ; Resolve it. (or (check-file-for-open f) ; Found it. (any (lambda (f) ; Search subdirs. (let ((dir (string-append dir f "/"))) (and (file-directory?/safe dir) (recur dir)))) (directory-files/safe dir))))))) (any (lambda (dir) (cond ((eq? dir 'script-dir) (let* ((script-dir (file-name-directory script-file)) (fname (string-append script-dir file))) (check-file-for-open fname))) ;; Ends in / means recursive search. ((file-name-directory? dir) (recur dir)) (else (check-file-for-open (absolute-file-name file dir))))) lib-dirs))) ;;; (in-any-event abort-exp body ...) ;;; If *anything* goes wrong, bag the BODY forms, and eval ABORT-EXP instead. (define-syntax in-any-event (syntax-rules () ((in-any-event abort-exp body ...) (call-with-current-continuation (lambda (ret) (with-handler (lambda (condition more) (ret abort-exp)) (lambda () body ...))))))) (define (check-file-for-open f) (in-any-event #f (let ((iport (open-input-file f))) (close-input-port iport) f))) ; Any error, say false. (define (directory-files/safe dir) (in-any-event '() (directory-files dir))) ; Any error, say (). (define (file-directory?/safe f) (in-any-event #f (file-directory? f))) ; Any error, say false. (define (resolve-dir-name dir) (if (file-name-directory? dir) (file-name-as-directory (resolve-file-name dir)) (resolve-file-name dir))) ;;; Expand out env vars & ~user home dir prefixes. (define (expand-lib-dir dir) (substitute-env-vars (resolve-dir-name dir))) Parse up the $ SCSH_LIB_DIRS path list . (define (parse-lib-dirs-env-var) (let ((s (getenv "SCSH_LIB_DIRS"))) (if (not s) default-lib-dirs (with-current-input-port (make-string-input-port s) (let recur () (let ((val (read))) (cond ((eof-object? val) '()) ((string? val) (cons val (recur))) ((not val) (append default-lib-dirs (recur))) (else (error (format #f (string-append "Illegal path element in $SCSH_LIB_DIRS\n" "$SCSH_LIB_DIRS: ~a\n" "The following element is not a string or #f: ~a") s val)))))))))) We do n't want to try to parse $ SCSH_LIB_DIRS until we actually ;; need the value -- if the user is using the -lp-default switch, ;; for example, a parse error shouldn't effect the startup. (define %lib-dirs #f) (define reinit-lib-dirs (make-reinitializer (lambda () (set! %lib-dirs #f)))) (define (lib-dirs) (if (not %lib-dirs) (set! %lib-dirs (parse-lib-dirs-env-var))) %lib-dirs) ;; Don't export -- direct modification of %lib-dirs (define (set-lib-dirs! val) (set! %lib-dirs val)) (define (lib-dirs-append-script-dir!) (set-lib-dirs! (append (lib-dirs) '(script-dir)))) (define (lib-dirs-prepend-script-dir!) (set-lib-dirs! (cons 'script-dir (lib-dirs)))) (define (reset-lib-dirs!) (set-lib-dirs! default-lib-dirs)) (define (clear-lib-dirs!) (set-lib-dirs! '())) (define (lib-dirs-prepend! dir) (set-lib-dirs! (cons dir (lib-dirs)))) (define (lib-dirs-append! dir) (set-lib-dirs! (append (lib-dirs) (list dir))))
null
https://raw.githubusercontent.com/scheme/scsh/114432435e4eadd54334df6b37fcae505079b49f/scheme/lib-dirs.scm
scheme
More imports for the new library-search facility: HANDLE: with-handler LIST-LIB: any SCSH-LEVEL-0: directory-files open-input-file file-directory? SCSH-LEVEL-0: the file-name procs Resolve it. Found it. Search subdirs. Ends in / means recursive search. (in-any-event abort-exp body ...) If *anything* goes wrong, bag the BODY forms, and eval ABORT-EXP instead. Any error, say false. Any error, say (). Any error, say false. Expand out env vars & ~user home dir prefixes. need the value -- if the user is using the -lp-default switch, for example, a parse error shouldn't effect the startup. Don't export -- direct modification of %lib-dirs
SCSH - LEVEL-0 : (define default-lib-dirs '("/usr/local/lib/scsh/modules/")) (define (set-default-lib-dirs! path-list) (set! default-lib-dirs path-list)) Search library dirs for FILE . (define (find-library-file file lib-dirs script-file) (letrec ((recur (lambda (dir) ( format ( error - output - port ) " flf -- entering ~a\n " dir ) (let ((dir (string-append dir f "/"))) (and (file-directory?/safe dir) (recur dir)))) (directory-files/safe dir))))))) (any (lambda (dir) (cond ((eq? dir 'script-dir) (let* ((script-dir (file-name-directory script-file)) (fname (string-append script-dir file))) (check-file-for-open fname))) ((file-name-directory? dir) (recur dir)) (else (check-file-for-open (absolute-file-name file dir))))) lib-dirs))) (define-syntax in-any-event (syntax-rules () ((in-any-event abort-exp body ...) (call-with-current-continuation (lambda (ret) (with-handler (lambda (condition more) (ret abort-exp)) (lambda () body ...))))))) (define (check-file-for-open f) (in-any-event #f (let ((iport (open-input-file f))) (close-input-port iport) (define (directory-files/safe dir) (define (file-directory?/safe f) (define (resolve-dir-name dir) (if (file-name-directory? dir) (file-name-as-directory (resolve-file-name dir)) (resolve-file-name dir))) (define (expand-lib-dir dir) (substitute-env-vars (resolve-dir-name dir))) Parse up the $ SCSH_LIB_DIRS path list . (define (parse-lib-dirs-env-var) (let ((s (getenv "SCSH_LIB_DIRS"))) (if (not s) default-lib-dirs (with-current-input-port (make-string-input-port s) (let recur () (let ((val (read))) (cond ((eof-object? val) '()) ((string? val) (cons val (recur))) ((not val) (append default-lib-dirs (recur))) (else (error (format #f (string-append "Illegal path element in $SCSH_LIB_DIRS\n" "$SCSH_LIB_DIRS: ~a\n" "The following element is not a string or #f: ~a") s val)))))))))) We do n't want to try to parse $ SCSH_LIB_DIRS until we actually (define %lib-dirs #f) (define reinit-lib-dirs (make-reinitializer (lambda () (set! %lib-dirs #f)))) (define (lib-dirs) (if (not %lib-dirs) (set! %lib-dirs (parse-lib-dirs-env-var))) %lib-dirs) (define (set-lib-dirs! val) (set! %lib-dirs val)) (define (lib-dirs-append-script-dir!) (set-lib-dirs! (append (lib-dirs) '(script-dir)))) (define (lib-dirs-prepend-script-dir!) (set-lib-dirs! (cons 'script-dir (lib-dirs)))) (define (reset-lib-dirs!) (set-lib-dirs! default-lib-dirs)) (define (clear-lib-dirs!) (set-lib-dirs! '())) (define (lib-dirs-prepend! dir) (set-lib-dirs! (cons dir (lib-dirs)))) (define (lib-dirs-append! dir) (set-lib-dirs! (append (lib-dirs) (list dir))))
0b56ec9124e65fa2317a0410e4493026021e7959e346e291d41f5556791a7c84
janestreet/universe
grammar.ml
open Core open Sexp_app module S = Syntax let atom x = S.Template.Atom x let qcmds = let etc = S.Quote (atom "...") in let t = S.Quote (atom "xxx") in let r = Re2.create_exn "R" in let temp n = atom (sprintf "T[%d]" n) in let sexp = Sexp.Atom "SEXP" in let num = 999 in List.map ~f:S.Query.sexp_of_t [ S.Index num ; S.Field "FIELDNAME" ; S.Each ; S.Smash ; S.pipe [ t; t; etc ] ; S.cat [ t; t; etc ] ; S.This ; S.Die ; S.Atomic ; S.Variant ("TAG", None) ; S.Variant ("TAG", Some num) ; S.Equals (Sexp_app.Sexps.of_list [ sexp ]) ; S.Equals (Sexp_app.Sexps.of_list [ sexp; sexp; Sexp.Atom "..." ]) ; S.Regex r ; S.Test t ; S.Not t ; S.and_ [ t; t; etc ] ; S.or_ [ t; t; etc ] ; S.If (t, t, t) ; S.Branch (t, t, t) ; S.Wrap t ; S.Quote (temp 0) ; S.Change S.Id ; S.Restructure ] ;; let ccmds = let t = S.Query S.This in let etc = S.Query (S.Quote (atom "...")) in List.map ~f:S.Change.sexp_of_t [ S.Rewrite (atom "P", atom "P") ; S.seq [ t; t; etc ] ; S.alt [ t; t; etc ] ; S.Record String.Map.empty ; S.Id ; S.Fail ; S.Delete ; S.const (Sexp.Atom "SEXP") ; S.try_ t ; S.Children t ; S.Topdown t ; S.Bottomup t ; S.Lowercase ; S.Concat ; S.Query (S.Quote (atom "xxx")) ] ;; let cprgm x = S.Change.t_of_sexp (Sexp.of_string x) let qprgm x = S.Query.t_of_sexp (Sexp.of_string x) module P = S.Template let munge = let change = cprgm {| (seq (topdown (try lowercase)) (topdown ( try ( alt (rewrite 999 NUM) (rewrite t[0] T[0]) (rewrite p P) (rewrite r R) (rewrite (record ()) (record (FIELDNAME [OPTIONS] C) ...)) (rewrite fieldname FIELDNAME) (rewrite (quote xxx) Q) (rewrite (quote ...) ...) (rewrite (query this) C) (rewrite (query (quote ...)) ...) (rewrite (rewrite $X sexp) (const SEXP)) (rewrite ($cmd ($_ $A $B) $C) ($cmd $A $B $C)) (rewrite (variant $tag ()) (variant $tag)) (rewrite (variant $tag ($num)) (variant $tag $num)) (rewrite (change $_) (change C)) (rewrite (query $_) (query Q)) (rewrite (alt $C id) (try $C)))))) |} in fun sexp -> match Semantics.change change sexp with | None -> assert false | Some sexp -> sexp ;; let make_lead x ~print_string = let flag = ref true in fun () -> let str = if !flag then ( flag := false; " " ^ x ^ " ::= ") else " | " in print_string str ;; let grammar_for_readme () = let buf = Buffer.create 0 in let print_string s = Buffer.add_string buf s in let print_endline s = Buffer.add_string buf s; Buffer.add_string buf "\n" in print_string "=== Grammar summary for query expressions ===\n"; print_string "See '-grammar' for a more complete grammar.\n"; print_string "See 'sexp pat-query' for simpler regular-expression-like language.\n\n"; let lead = make_lead "Q" ~print_string in List.iter qcmds ~f:(fun cmd -> lead (); print_string (Sexp.to_string_hum (munge cmd)); print_endline ""); Buffer.contents buf ;; let print () = (print_string "\n--- grammar for query expressions ---\n\n"; let lead = make_lead "Q" ~print_string in List.iter qcmds ~f:(fun cmd -> lead (); Sexp.output_hum stdout (munge cmd); print_endline "")); (print_string "\n--- grammar for change expressions ---\n\n"; let lead = make_lead "C" ~print_string in List.iter ccmds ~f:(fun cmd -> lead (); Sexp.output_hum stdout (munge cmd); print_endline "")); print_string "\n--- grammar for patterns ---\n\n"; print_endline " P ::= ATOM"; print_endline " | (P ... P)"; print_endline " | $VAR"; print_endline " | @VAR"; print_string "\n--- grammar for templates ---\n\n"; print_endline " T[0] ::= ATOM"; print_endline " | (T[0] ... T[0])"; print_endline " | (quote T[1])"; print_endline " | (unquote Q)"; print_endline " | (splice Q)"; print_endline ""; print_endline " T[n+1] ::= ATOM"; print_endline " | (T[n+1] ... T[n+1])"; print_endline " | (quote T[n+2])"; print_endline " | (unquote T[n])"; print_endline " | (splice T[n])"; print_endline "" ;; let commands () = let munge = Semantics.query (qprgm "(or (index 0) this)") in List.map qcmds ~f:(fun cmd -> match Lazy_list.to_list (munge cmd) with | [ Sexp.Atom x ] -> x | _ -> failwith ("error: " ^ Sexp.to_string cmd)) ;;
null
https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/sexp/bin/grammar.ml
ocaml
open Core open Sexp_app module S = Syntax let atom x = S.Template.Atom x let qcmds = let etc = S.Quote (atom "...") in let t = S.Quote (atom "xxx") in let r = Re2.create_exn "R" in let temp n = atom (sprintf "T[%d]" n) in let sexp = Sexp.Atom "SEXP" in let num = 999 in List.map ~f:S.Query.sexp_of_t [ S.Index num ; S.Field "FIELDNAME" ; S.Each ; S.Smash ; S.pipe [ t; t; etc ] ; S.cat [ t; t; etc ] ; S.This ; S.Die ; S.Atomic ; S.Variant ("TAG", None) ; S.Variant ("TAG", Some num) ; S.Equals (Sexp_app.Sexps.of_list [ sexp ]) ; S.Equals (Sexp_app.Sexps.of_list [ sexp; sexp; Sexp.Atom "..." ]) ; S.Regex r ; S.Test t ; S.Not t ; S.and_ [ t; t; etc ] ; S.or_ [ t; t; etc ] ; S.If (t, t, t) ; S.Branch (t, t, t) ; S.Wrap t ; S.Quote (temp 0) ; S.Change S.Id ; S.Restructure ] ;; let ccmds = let t = S.Query S.This in let etc = S.Query (S.Quote (atom "...")) in List.map ~f:S.Change.sexp_of_t [ S.Rewrite (atom "P", atom "P") ; S.seq [ t; t; etc ] ; S.alt [ t; t; etc ] ; S.Record String.Map.empty ; S.Id ; S.Fail ; S.Delete ; S.const (Sexp.Atom "SEXP") ; S.try_ t ; S.Children t ; S.Topdown t ; S.Bottomup t ; S.Lowercase ; S.Concat ; S.Query (S.Quote (atom "xxx")) ] ;; let cprgm x = S.Change.t_of_sexp (Sexp.of_string x) let qprgm x = S.Query.t_of_sexp (Sexp.of_string x) module P = S.Template let munge = let change = cprgm {| (seq (topdown (try lowercase)) (topdown ( try ( alt (rewrite 999 NUM) (rewrite t[0] T[0]) (rewrite p P) (rewrite r R) (rewrite (record ()) (record (FIELDNAME [OPTIONS] C) ...)) (rewrite fieldname FIELDNAME) (rewrite (quote xxx) Q) (rewrite (quote ...) ...) (rewrite (query this) C) (rewrite (query (quote ...)) ...) (rewrite (rewrite $X sexp) (const SEXP)) (rewrite ($cmd ($_ $A $B) $C) ($cmd $A $B $C)) (rewrite (variant $tag ()) (variant $tag)) (rewrite (variant $tag ($num)) (variant $tag $num)) (rewrite (change $_) (change C)) (rewrite (query $_) (query Q)) (rewrite (alt $C id) (try $C)))))) |} in fun sexp -> match Semantics.change change sexp with | None -> assert false | Some sexp -> sexp ;; let make_lead x ~print_string = let flag = ref true in fun () -> let str = if !flag then ( flag := false; " " ^ x ^ " ::= ") else " | " in print_string str ;; let grammar_for_readme () = let buf = Buffer.create 0 in let print_string s = Buffer.add_string buf s in let print_endline s = Buffer.add_string buf s; Buffer.add_string buf "\n" in print_string "=== Grammar summary for query expressions ===\n"; print_string "See '-grammar' for a more complete grammar.\n"; print_string "See 'sexp pat-query' for simpler regular-expression-like language.\n\n"; let lead = make_lead "Q" ~print_string in List.iter qcmds ~f:(fun cmd -> lead (); print_string (Sexp.to_string_hum (munge cmd)); print_endline ""); Buffer.contents buf ;; let print () = (print_string "\n--- grammar for query expressions ---\n\n"; let lead = make_lead "Q" ~print_string in List.iter qcmds ~f:(fun cmd -> lead (); Sexp.output_hum stdout (munge cmd); print_endline "")); (print_string "\n--- grammar for change expressions ---\n\n"; let lead = make_lead "C" ~print_string in List.iter ccmds ~f:(fun cmd -> lead (); Sexp.output_hum stdout (munge cmd); print_endline "")); print_string "\n--- grammar for patterns ---\n\n"; print_endline " P ::= ATOM"; print_endline " | (P ... P)"; print_endline " | $VAR"; print_endline " | @VAR"; print_string "\n--- grammar for templates ---\n\n"; print_endline " T[0] ::= ATOM"; print_endline " | (T[0] ... T[0])"; print_endline " | (quote T[1])"; print_endline " | (unquote Q)"; print_endline " | (splice Q)"; print_endline ""; print_endline " T[n+1] ::= ATOM"; print_endline " | (T[n+1] ... T[n+1])"; print_endline " | (quote T[n+2])"; print_endline " | (unquote T[n])"; print_endline " | (splice T[n])"; print_endline "" ;; let commands () = let munge = Semantics.query (qprgm "(or (index 0) this)") in List.map qcmds ~f:(fun cmd -> match Lazy_list.to_list (munge cmd) with | [ Sexp.Atom x ] -> x | _ -> failwith ("error: " ^ Sexp.to_string cmd)) ;;
5434249853e8ee2e794d01ae78624049195036fba8660c31bfc29b1a73b9ebeb
ucsd-progsys/nate
frx_entry.mli
(***********************************************************************) (* *) MLTk , Tcl / Tk interface of Objective Caml (* *) , , and projet Cristal , INRIA Rocquencourt , Kyoto University RIMS (* *) Copyright 2002 Institut National de Recherche en Informatique et en Automatique and Kyoto University . 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 found in the Objective Caml source tree. *) (* *) (***********************************************************************) open Camltk val new_label_entry : Widget.widget -> string -> (string -> unit) -> Widget.widget * Widget.widget (* [new_label_entry parent label action] creates a "labelled" entry widget where [action] will be invoked when the user types Return in the widget. Returns (frame widget, entry widget) *) val new_labelm_entry : Widget.widget -> string -> Textvariable.textVariable -> Widget.widget * Widget.widget (* [new_labelm_entry parent label variable] creates a "labelled" entry widget whose contents is [variable]. Returns (frame widget, entry widget) *)
null
https://raw.githubusercontent.com/ucsd-progsys/nate/8b1267cd8b10283d8bc239d16a28c654a4cb8942/eval/sherrloc/easyocaml%2B%2B/otherlibs/labltk/frx/frx_entry.mli
ocaml
********************************************************************* described in file LICENSE found in the Objective Caml source tree. ********************************************************************* [new_label_entry parent label action] creates a "labelled" entry widget where [action] will be invoked when the user types Return in the widget. Returns (frame widget, entry widget) [new_labelm_entry parent label variable] creates a "labelled" entry widget whose contents is [variable]. Returns (frame widget, entry widget)
MLTk , Tcl / Tk interface of Objective Caml , , and projet Cristal , INRIA Rocquencourt , Kyoto University RIMS Copyright 2002 Institut National de Recherche en Informatique et en Automatique and Kyoto University . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with the special exception on linking open Camltk val new_label_entry : Widget.widget -> string -> (string -> unit) -> Widget.widget * Widget.widget val new_labelm_entry : Widget.widget -> string -> Textvariable.textVariable -> Widget.widget * Widget.widget
4c972cff4ec4cbd7f827e3610e2ae1b5040ba4f4e09447d786b4089bcfbf3f79
argp/bap
piqic_ocaml_defaults.ml
pp camlp4o -I ` ocamlfind query piqi.syntax ` pa_labelscope.cmo pa_openin.cmo Copyright 2009 , 2010 , 2011 , 2012 , 2013 Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Copyright 2009, 2010, 2011, 2012, 2013 Anton Lavrik 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. *) * This module generates default values for all OCaml types generated by * * This module generates default values for all OCaml types generated by * Piqic_ocaml_types *) open Piqi_common open Iolist (* reuse several functions *) open Piqic_ocaml_types open Piqic_ocaml_out let rec gen_default_type ocaml_type wire_type x = match x with | `any -> if !Piqic_common.is_self_spec then ios "default_any ()" else ios "Piqi_piqi.default_any ()" | `alias a when wire_type <> None -> (* need special handing for wire_type override *) gen_default_type a.A#ocaml_type wire_type (some_of a.A#piqtype) | (#T.typedef as x) -> let modname = gen_parent x in modname ^^ ios "default_" ^^ ios (typedef_mlname x) ^^ ios "()" | _ -> (* gen parsers for built-in types *) let default = Piqic_common.gen_builtin_default_value wire_type x in let default_expr = iod " " [ ios "(Piqirun.parse_default"; ioq (String.escaped default); ios ")"; ] in iol [ ios "Piqirun."; ios (gen_ocaml_type_name x ocaml_type); ios "_of_"; ios (W.get_wire_type_name x wire_type); default_expr; ] let gen_default_piqtype ?ocaml_type ?wire_type (t:T.piqtype) = gen_default_type ocaml_type wire_type t let gen_field_cons rname f = let open Field in let fname = mlname_of_field f in let ffname = (* fully-qualified field name *) iol [ios rname; ios "."; ios fname] in let value = match f.mode with | `required -> gen_default_piqtype (some_of f.piqtype) | `optional when f.piqtype = None -> ios "false" (* flag *) | `optional when f.default <> None && (not f.ocaml_optional) -> let pb = Piqobj.pb_of_piqi_any (some_of f.default) in let default_str = String.escaped pb in iod " " [ Piqic_ocaml_in.gen_parse_piqtype (some_of f.piqtype); ios "(Piqirun.parse_default"; ioq default_str; ios ")"; ] | `optional -> ios "None" | `repeated -> if f.ocaml_array then ios "[||]" else ios "[]" in (* field construction code *) iod " " [ ffname; ios "="; value; ios ";" ] let gen_record r = (* fully-qualified capitalized record name *) let rname = capitalize (some_of r.R#ocaml_name) in let fields = r.R#wire_field in let fconsl = (* field constructor list *) if fields <> [] then List.map (gen_field_cons rname) fields else [ios rname; ios "."; ios "_dummy = ()"] in (* fake_<record-name> function delcaration *) iod " " [ ios "default_" ^^ ios (some_of r.R#ocaml_name); ios "() ="; ios "{"; iol fconsl; ios "}"; ] let gen_enum e = let open Enum in there must be at least one option let const = List.hd e.option in iod " " [ ios "default_" ^^ ios (some_of e.ocaml_name); ios "() ="; gen_pvar_name (some_of const.O#ocaml_name) ] let rec gen_option varname o = let open Option in match o.ocaml_name, o.piqtype with | Some mln, None -> gen_pvar_name mln | None, Some ((`variant _) as t) | None, Some ((`enum _) as t) -> iod " " [ ios "("; gen_default_piqtype t; ios ":>"; ios varname; ios ")" ] | _, Some t -> let n = mlname_of_option o in iod " " [ gen_pvar_name n; ios "("; gen_default_piqtype t; ios ")"; ] | None, None -> assert false let gen_variant v = let open Variant in there must be at least one option let opt = gen_option (some_of v.ocaml_name) (List.hd v.option) in iod " " [ ios "default_" ^^ ios (some_of v.ocaml_name); ios "() ="; opt; ] let gen_alias a = let open Alias in let piqtype = some_of a.piqtype in iod " " [ ios "default_" ^^ ios (some_of a.ocaml_name); ios "() ="; Piqic_ocaml_in.gen_convert_of piqtype a.ocaml_type ( gen_default_piqtype piqtype ?ocaml_type:a.ocaml_type ?wire_type:a.protobuf_wire_type; ); ] let gen_list l = let open L in iod " " [ ios "default_" ^^ ios (some_of l.ocaml_name); ios "() = "; if l.ocaml_array then ios "[||]" else ios "[]"; ] let gen_def = function | `record t -> gen_record t | `variant t -> gen_variant t | `enum t -> gen_enum t | `list t -> gen_list t | `alias t -> gen_alias t let gen_defs (defs:T.typedef list) = let defs = List.map gen_def defs in if defs = [] then iol [] else iod " " [ ios "let rec"; iod " and " defs; ios "\n"; ] let gen_piqi (piqi:T.piqi) = gen_defs piqi.P#resolved_typedef
null
https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/libtracewrap/libtrace/piqi/piqi/piqic/piqic_ocaml_defaults.ml
ocaml
reuse several functions need special handing for wire_type override gen parsers for built-in types fully-qualified field name flag field construction code fully-qualified capitalized record name field constructor list fake_<record-name> function delcaration
pp camlp4o -I ` ocamlfind query piqi.syntax ` pa_labelscope.cmo pa_openin.cmo Copyright 2009 , 2010 , 2011 , 2012 , 2013 Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Copyright 2009, 2010, 2011, 2012, 2013 Anton Lavrik 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. *) * This module generates default values for all OCaml types generated by * * This module generates default values for all OCaml types generated by * Piqic_ocaml_types *) open Piqi_common open Iolist open Piqic_ocaml_types open Piqic_ocaml_out let rec gen_default_type ocaml_type wire_type x = match x with | `any -> if !Piqic_common.is_self_spec then ios "default_any ()" else ios "Piqi_piqi.default_any ()" | `alias a when wire_type <> None -> gen_default_type a.A#ocaml_type wire_type (some_of a.A#piqtype) | (#T.typedef as x) -> let modname = gen_parent x in modname ^^ ios "default_" ^^ ios (typedef_mlname x) ^^ ios "()" let default = Piqic_common.gen_builtin_default_value wire_type x in let default_expr = iod " " [ ios "(Piqirun.parse_default"; ioq (String.escaped default); ios ")"; ] in iol [ ios "Piqirun."; ios (gen_ocaml_type_name x ocaml_type); ios "_of_"; ios (W.get_wire_type_name x wire_type); default_expr; ] let gen_default_piqtype ?ocaml_type ?wire_type (t:T.piqtype) = gen_default_type ocaml_type wire_type t let gen_field_cons rname f = let open Field in let fname = mlname_of_field f in iol [ios rname; ios "."; ios fname] in let value = match f.mode with | `required -> gen_default_piqtype (some_of f.piqtype) | `optional when f.default <> None && (not f.ocaml_optional) -> let pb = Piqobj.pb_of_piqi_any (some_of f.default) in let default_str = String.escaped pb in iod " " [ Piqic_ocaml_in.gen_parse_piqtype (some_of f.piqtype); ios "(Piqirun.parse_default"; ioq default_str; ios ")"; ] | `optional -> ios "None" | `repeated -> if f.ocaml_array then ios "[||]" else ios "[]" in iod " " [ ffname; ios "="; value; ios ";" ] let gen_record r = let rname = capitalize (some_of r.R#ocaml_name) in let fields = r.R#wire_field in if fields <> [] then List.map (gen_field_cons rname) fields else [ios rname; ios "."; ios "_dummy = ()"] iod " " [ ios "default_" ^^ ios (some_of r.R#ocaml_name); ios "() ="; ios "{"; iol fconsl; ios "}"; ] let gen_enum e = let open Enum in there must be at least one option let const = List.hd e.option in iod " " [ ios "default_" ^^ ios (some_of e.ocaml_name); ios "() ="; gen_pvar_name (some_of const.O#ocaml_name) ] let rec gen_option varname o = let open Option in match o.ocaml_name, o.piqtype with | Some mln, None -> gen_pvar_name mln | None, Some ((`variant _) as t) | None, Some ((`enum _) as t) -> iod " " [ ios "("; gen_default_piqtype t; ios ":>"; ios varname; ios ")" ] | _, Some t -> let n = mlname_of_option o in iod " " [ gen_pvar_name n; ios "("; gen_default_piqtype t; ios ")"; ] | None, None -> assert false let gen_variant v = let open Variant in there must be at least one option let opt = gen_option (some_of v.ocaml_name) (List.hd v.option) in iod " " [ ios "default_" ^^ ios (some_of v.ocaml_name); ios "() ="; opt; ] let gen_alias a = let open Alias in let piqtype = some_of a.piqtype in iod " " [ ios "default_" ^^ ios (some_of a.ocaml_name); ios "() ="; Piqic_ocaml_in.gen_convert_of piqtype a.ocaml_type ( gen_default_piqtype piqtype ?ocaml_type:a.ocaml_type ?wire_type:a.protobuf_wire_type; ); ] let gen_list l = let open L in iod " " [ ios "default_" ^^ ios (some_of l.ocaml_name); ios "() = "; if l.ocaml_array then ios "[||]" else ios "[]"; ] let gen_def = function | `record t -> gen_record t | `variant t -> gen_variant t | `enum t -> gen_enum t | `list t -> gen_list t | `alias t -> gen_alias t let gen_defs (defs:T.typedef list) = let defs = List.map gen_def defs in if defs = [] then iol [] else iod " " [ ios "let rec"; iod " and " defs; ios "\n"; ] let gen_piqi (piqi:T.piqi) = gen_defs piqi.P#resolved_typedef
c5bb74d7d78b718ac4b3720526193469e88c94dd69310f5e61f583eaadb7f463
ahrefs/atd
test_classic_inline_record_t.expected.mli
(* Auto-generated from "test_classic_inline_record.atd" *) [@@@ocaml.warning "-27-32-33-35-39"] type foo = Foo of { x: int }
null
https://raw.githubusercontent.com/ahrefs/atd/03386f2ffa5aea981ebd1c25346b157db78f986b/atdgen/test/test_classic_inline_record_t.expected.mli
ocaml
Auto-generated from "test_classic_inline_record.atd"
[@@@ocaml.warning "-27-32-33-35-39"] type foo = Foo of { x: int }
aaf3eaa2b3050909e9d8cc5131ba57b41995624c9264d3a1cb6481e1459b2c71
D00mch/DartClojure
build.clj
(ns build (:require [clojure.string :as str] [clojure.tools.build.api :as b] [clojure.java.shell :refer [sh]])) (def target "target") (def class-dir (str target "/classes")) (def basis (b/create-basis {:project "deps.edn"})) (defn cmd! [cmd] (sh "sh" "-c" cmd)) (defn cmd-prn! [cmd] (println (cmd! cmd))) ;; # Versions (def version-files ["README.md" "pom.xml" "package.json"]) (defn set-version [s v] (-> s (str/replace #"\d+.\d+.\d+-SNAPSHOT" (str v "-SNAPSHOT")) (str/replace #"tag/\d+.\d+.\d+" (str "tag/" v)) (str/replace #"\"version\": \"\d+.\d+.\d+\"" (str "\"version\": \"" v \")) (str/replace #"\"dartclojure\": \"\^\d+.\d+.\d+\"" (str "\"dartclojure\": \"^" v \")))) (defn update-versions [v] (println "about to update versions") (letfn [(update-file! [fname] (spit fname (set-version (slurp fname) v)))] (doseq [f version-files] (update-file! f))) (println "versions updated")) ;; # Uberjar (defn publish-clojars [psw] (println "about to publish to clojars") (cmd! "cp target/dartclj*.jar dartclj.jar") (cmd-prn! (str "env CLOJARS_USERNAME=liverm0r" " CLOJARS_PASSWORD=" psw " clj -X:deploy")) (println "published to clojars")) (defn uber-file [name version] (format "target/%s-%s-standalone.jar" name version)) (defn clean [_] (b/delete {:path target})) (defn uber [{:keys [version] :as params}] (println "getting params: " params) (b/copy-dir {:src-dirs ["src" "resources"] :target-dir class-dir}) (b/compile-clj {:basis basis :src-dirs ["src"] :class-dir class-dir}) (b/uber {:class-dir class-dir :uber-file (uber-file "dartclj" version) :basis basis :main 'dumch.dartclojure})) # Native (defn open-docker [] (cmd-prn! "open -a Docker") (while (-> (cmd! "docker stats --no-stream") :out empty?) (Thread/sleep 1500)) (Thread/sleep 5000)) (defn build-aar64-linux [version] (open-docker) (cmd-prn! "docker image rm -f dartclojure") (cmd-prn! "docker rm -f dc") (cmd-prn! "docker build --pull --no-cache --tag dartclojure .") (println "test command") (cmd-prn! "docker run --name dc -i dartclojure ./dartclj \"1+1;\"") (cmd-prn! (str "docker cp dc:/usr/src/app/dartclj \"target/dartclj-" version "-aarch64-linux\""))) (defn build-aaar64-darwin [version] (cmd! "pwd") (cmd! "cp target/dartclj*.jar dartclj.jar") (cmd! "chmod +x compile.sh") (cmd-prn! "./compile.sh") (cmd-prn! (str "mv dartclj target/dartclj-" version "-aarch64-darwin"))) (defn native [{:keys [version]}] (build-aaar64-darwin version) (build-aar64-linux version)) ;; # NPM (defn rebuild-and-publish-npm [] (println "about to clean") (cmd! "rm -rf .shadow-cljs") (cmd-prn! "npm run clean") (println "clean finished; about to build release") (cmd-prn! "clj -M:shadow-cljs release :app :lib") (cmd-prn! "npm publish") (println "published")) (defn npm [_] (rebuild-and-publish-npm)) ;; # All (defn release [{:keys [version clojarspass] :as params}] (clean nil) (update-versions version) (uber params) (publish-clojars clojarspass) (native params) (rebuild-and-publish-npm)) (comment (require '[clojure.tools.deps.alpha.repl :refer [add-libs]]) (add-libs '{io.github.clojure/tools.build {:git/tag "v0.8.3" :git/sha "0d20256"}}) (def version "0.2.14") (update-versions version) (uber {:version version}) (native {:version version}) ,)
null
https://raw.githubusercontent.com/D00mch/DartClojure/07de92ea08f6bf44262e22c3d7d469f5bfbe284f/build.clj
clojure
# Versions # Uberjar \"") # NPM # All
(ns build (:require [clojure.string :as str] [clojure.tools.build.api :as b] [clojure.java.shell :refer [sh]])) (def target "target") (def class-dir (str target "/classes")) (def basis (b/create-basis {:project "deps.edn"})) (defn cmd! [cmd] (sh "sh" "-c" cmd)) (defn cmd-prn! [cmd] (println (cmd! cmd))) (def version-files ["README.md" "pom.xml" "package.json"]) (defn set-version [s v] (-> s (str/replace #"\d+.\d+.\d+-SNAPSHOT" (str v "-SNAPSHOT")) (str/replace #"tag/\d+.\d+.\d+" (str "tag/" v)) (str/replace #"\"version\": \"\d+.\d+.\d+\"" (str "\"version\": \"" v \")) (str/replace #"\"dartclojure\": \"\^\d+.\d+.\d+\"" (str "\"dartclojure\": \"^" v \")))) (defn update-versions [v] (println "about to update versions") (letfn [(update-file! [fname] (spit fname (set-version (slurp fname) v)))] (doseq [f version-files] (update-file! f))) (println "versions updated")) (defn publish-clojars [psw] (println "about to publish to clojars") (cmd! "cp target/dartclj*.jar dartclj.jar") (cmd-prn! (str "env CLOJARS_USERNAME=liverm0r" " CLOJARS_PASSWORD=" psw " clj -X:deploy")) (println "published to clojars")) (defn uber-file [name version] (format "target/%s-%s-standalone.jar" name version)) (defn clean [_] (b/delete {:path target})) (defn uber [{:keys [version] :as params}] (println "getting params: " params) (b/copy-dir {:src-dirs ["src" "resources"] :target-dir class-dir}) (b/compile-clj {:basis basis :src-dirs ["src"] :class-dir class-dir}) (b/uber {:class-dir class-dir :uber-file (uber-file "dartclj" version) :basis basis :main 'dumch.dartclojure})) # Native (defn open-docker [] (cmd-prn! "open -a Docker") (while (-> (cmd! "docker stats --no-stream") :out empty?) (Thread/sleep 1500)) (Thread/sleep 5000)) (defn build-aar64-linux [version] (open-docker) (cmd-prn! "docker image rm -f dartclojure") (cmd-prn! "docker rm -f dc") (cmd-prn! "docker build --pull --no-cache --tag dartclojure .") (println "test command") (cmd-prn! (str "docker cp dc:/usr/src/app/dartclj \"target/dartclj-" version "-aarch64-linux\""))) (defn build-aaar64-darwin [version] (cmd! "pwd") (cmd! "cp target/dartclj*.jar dartclj.jar") (cmd! "chmod +x compile.sh") (cmd-prn! "./compile.sh") (cmd-prn! (str "mv dartclj target/dartclj-" version "-aarch64-darwin"))) (defn native [{:keys [version]}] (build-aaar64-darwin version) (build-aar64-linux version)) (defn rebuild-and-publish-npm [] (println "about to clean") (cmd! "rm -rf .shadow-cljs") (cmd-prn! "npm run clean") (println "clean finished; about to build release") (cmd-prn! "clj -M:shadow-cljs release :app :lib") (cmd-prn! "npm publish") (println "published")) (defn npm [_] (rebuild-and-publish-npm)) (defn release [{:keys [version clojarspass] :as params}] (clean nil) (update-versions version) (uber params) (publish-clojars clojarspass) (native params) (rebuild-and-publish-npm)) (comment (require '[clojure.tools.deps.alpha.repl :refer [add-libs]]) (add-libs '{io.github.clojure/tools.build {:git/tag "v0.8.3" :git/sha "0d20256"}}) (def version "0.2.14") (update-versions version) (uber {:version version}) (native {:version version}) ,)
1e6f2da9e5150e1526451892c870b11ed5ef4f35637b5bc2d8a715bd5c7afd41
katydid/katydid-haskell
UserDefinedFuncs.hs
module UserDefinedFuncs ( userLib , incExpr , concatExpr , isPrimeExpr ) where import qualified Data.Text import Data.Numbers.Primes ( isPrime ) import Data.Katydid.Relapse.Expr -- | -- userLib is a library of user defined functions that can be passed to the parser. userLib :: String -> [AnyExpr] -> Either String AnyExpr userLib "inc" args = mkIncExpr args userLib "concat" args = mkConcatExpr args userLib "isPrime" args = mkIsPrime args userLib n _ = Left $ "undefined function: " ++ n -- | mkIncExpr tries to create an incExpr from a variable number and dynamically types arguments . -- This function is used by the Relapse parser to insert your user defined expression into the expression tree. mkIncExpr :: [AnyExpr] -> Either String AnyExpr mkIncExpr args = do arg <- assertArgs1 "inc" args mkIntExpr . incExpr <$> assertInt arg -- | incExpr creates an expression that increases its input argument by 1 . -- This function is also useful if we want to build up our own well typed expression tree, -- bypassing the Relapse parser. incExpr :: Expr Int -> Expr Int incExpr intArg = trimInt Expr { desc = mkDesc "inc" [desc intArg] , eval = \fieldValue -> (+ 1) <$> eval intArg fieldValue } -- | tries to create an concatExpr from a variable number and dynamically types arguments . mkConcatExpr :: [AnyExpr] -> Either String AnyExpr mkConcatExpr args = do (arg1, arg2) <- assertArgs2 "inc" args strArg1 <- assertString arg1 strArg2 <- assertString arg2 return $ mkStringExpr $ concatExpr strArg1 strArg2 -- | concatExpr creates an expression that concatenates two string together . concatExpr :: Expr Data.Text.Text -> Expr Data.Text.Text -> Expr Data.Text.Text concatExpr strExpr1 strExpr2 = trimString Expr { desc = mkDesc "concat" [desc strExpr1, desc strExpr2] , eval = \fieldValue -> do str1 <- eval strExpr1 fieldValue str2 <- eval strExpr2 fieldValue return $ Data.Text.concat [str1, str2] } -- | mkIsPrimeExpr tries to create an isPrimeExpr from a variable number and dynamically types arguments . mkIsPrime :: [AnyExpr] -> Either String AnyExpr mkIsPrime args = do arg <- assertArgs1 "isPrime" args case arg of (AnyExpr _ (IntFunc _)) -> mkBoolExpr . isPrimeExpr <$> assertInt arg (AnyExpr _ (UintFunc _)) -> mkBoolExpr . isPrimeExpr <$> assertUint arg -- | -- isPrime creates an expression checks whether a number is prime. isPrimeExpr :: Integral a => Expr a -> Expr Bool isPrimeExpr numExpr = trimBool Expr { desc = mkDesc "isPrime" [desc numExpr] , eval = \fieldValue -> isPrime <$> eval numExpr fieldValue }
null
https://raw.githubusercontent.com/katydid/katydid-haskell/4588cd8676628cd15c671d61b65bdc2f3a199a38/test/UserDefinedFuncs.hs
haskell
| userLib is a library of user defined functions that can be passed to the parser. | This function is used by the Relapse parser to insert your user defined expression into the expression tree. | This function is also useful if we want to build up our own well typed expression tree, bypassing the Relapse parser. | | | | isPrime creates an expression checks whether a number is prime.
module UserDefinedFuncs ( userLib , incExpr , concatExpr , isPrimeExpr ) where import qualified Data.Text import Data.Numbers.Primes ( isPrime ) import Data.Katydid.Relapse.Expr userLib :: String -> [AnyExpr] -> Either String AnyExpr userLib "inc" args = mkIncExpr args userLib "concat" args = mkConcatExpr args userLib "isPrime" args = mkIsPrime args userLib n _ = Left $ "undefined function: " ++ n mkIncExpr tries to create an incExpr from a variable number and dynamically types arguments . mkIncExpr :: [AnyExpr] -> Either String AnyExpr mkIncExpr args = do arg <- assertArgs1 "inc" args mkIntExpr . incExpr <$> assertInt arg incExpr creates an expression that increases its input argument by 1 . incExpr :: Expr Int -> Expr Int incExpr intArg = trimInt Expr { desc = mkDesc "inc" [desc intArg] , eval = \fieldValue -> (+ 1) <$> eval intArg fieldValue } tries to create an concatExpr from a variable number and dynamically types arguments . mkConcatExpr :: [AnyExpr] -> Either String AnyExpr mkConcatExpr args = do (arg1, arg2) <- assertArgs2 "inc" args strArg1 <- assertString arg1 strArg2 <- assertString arg2 return $ mkStringExpr $ concatExpr strArg1 strArg2 concatExpr creates an expression that concatenates two string together . concatExpr :: Expr Data.Text.Text -> Expr Data.Text.Text -> Expr Data.Text.Text concatExpr strExpr1 strExpr2 = trimString Expr { desc = mkDesc "concat" [desc strExpr1, desc strExpr2] , eval = \fieldValue -> do str1 <- eval strExpr1 fieldValue str2 <- eval strExpr2 fieldValue return $ Data.Text.concat [str1, str2] } mkIsPrimeExpr tries to create an isPrimeExpr from a variable number and dynamically types arguments . mkIsPrime :: [AnyExpr] -> Either String AnyExpr mkIsPrime args = do arg <- assertArgs1 "isPrime" args case arg of (AnyExpr _ (IntFunc _)) -> mkBoolExpr . isPrimeExpr <$> assertInt arg (AnyExpr _ (UintFunc _)) -> mkBoolExpr . isPrimeExpr <$> assertUint arg isPrimeExpr :: Integral a => Expr a -> Expr Bool isPrimeExpr numExpr = trimBool Expr { desc = mkDesc "isPrime" [desc numExpr] , eval = \fieldValue -> isPrime <$> eval numExpr fieldValue }
16ad0328a1f7032767ee6bad82d433fbadc6811f2d098add4fccacf9601721e3
well-typed/large-records
R100.hs
{-# LANGUAGE DataKinds #-} # LANGUAGE PatternSynonyms # {-# LANGUAGE ViewPatterns #-} #if __GLASGOW_HASKELL__ >= 902 # LANGUAGE NoFieldSelectors # #endif #if PROFILE_CORESIZE {-# OPTIONS_GHC -ddump-to-file -ddump-ds-preopt -ddump-ds -ddump-simpl #-} #endif #if PROFILE_TIMING {-# OPTIONS_GHC -ddump-to-file -ddump-timings #-} #endif module Experiment.PatternSynonym_NFS.Sized.R100 where import Bench.Types data R viewR :: R -> ( (T 00, T 01, T 02, T 03, T 04, T 05, T 06, T 07, T 08, T 09) , (T 10, T 11, T 12, T 13, T 14, T 15, T 16, T 17, T 18, T 19) , (T 20, T 21, T 22, T 23, T 24, T 25, T 26, T 27, T 28, T 29) , (T 30, T 31, T 32, T 33, T 34, T 35, T 36, T 37, T 38, T 39) , (T 40, T 41, T 42, T 43, T 44, T 45, T 46, T 47, T 48, T 49) , (T 50, T 51, T 52, T 53, T 54, T 55, T 56, T 57, T 58, T 59) , (T 60, T 61, T 62, T 63, T 64, T 65, T 66, T 67, T 68, T 69) , (T 70, T 71, T 72, T 73, T 74, T 75, T 76, T 77, T 78, T 79) , (T 80, T 81, T 82, T 83, T 84, T 85, T 86, T 87, T 88, T 89) , (T 90, T 91, T 92, T 93, T 94, T 95, T 96, T 97, T 98, T 99) ) viewR = undefined pattern MkR :: T 00 -> T 01 -> T 02 -> T 03 -> T 04 -> T 05 -> T 06 -> T 07 -> T 08 -> T 09 -> T 10 -> T 11 -> T 12 -> T 13 -> T 14 -> T 15 -> T 16 -> T 17 -> T 18 -> T 19 -> T 20 -> T 21 -> T 22 -> T 23 -> T 24 -> T 25 -> T 26 -> T 27 -> T 28 -> T 29 -> T 30 -> T 31 -> T 32 -> T 33 -> T 34 -> T 35 -> T 36 -> T 37 -> T 38 -> T 39 -> T 40 -> T 41 -> T 42 -> T 43 -> T 44 -> T 45 -> T 46 -> T 47 -> T 48 -> T 49 -> T 50 -> T 51 -> T 52 -> T 53 -> T 54 -> T 55 -> T 56 -> T 57 -> T 58 -> T 59 -> T 60 -> T 61 -> T 62 -> T 63 -> T 64 -> T 65 -> T 66 -> T 67 -> T 68 -> T 69 -> T 70 -> T 71 -> T 72 -> T 73 -> T 74 -> T 75 -> T 76 -> T 77 -> T 78 -> T 79 -> T 80 -> T 81 -> T 82 -> T 83 -> T 84 -> T 85 -> T 86 -> T 87 -> T 88 -> T 89 -> T 90 -> T 91 -> T 92 -> T 93 -> T 94 -> T 95 -> T 96 -> T 97 -> T 98 -> T 99 -> R pattern MkR { x00, x01, x02, x03, x04, x05, x06, x07, x08, x09 , x10, x11, x12, x13, x14, x15, x16, x17, x18, x19 , x20, x21, x22, x23, x24, x25, x26, x27, x28, x29 , x30, x31, x32, x33, x34, x35, x36, x37, x38, x39 , x40, x41, x42, x43, x44, x45, x46, x47, x48, x49 , x50, x51, x52, x53, x54, x55, x56, x57, x58, x59 , x60, x61, x62, x63, x64, x65, x66, x67, x68, x69 , x70, x71, x72, x73, x74, x75, x76, x77, x78, x79 , x80, x81, x82, x83, x84, x85, x86, x87, x88, x89 , x90, x91, x92, x93, x94, x95, x96, x97, x98, x99 } <- (viewR -> ( (x00, x01, x02, x03, x04, x05, x06, x07, x08, x09) , (x10, x11, x12, x13, x14, x15, x16, x17, x18, x19) , (x20, x21, x22, x23, x24, x25, x26, x27, x28, x29) , (x30, x31, x32, x33, x34, x35, x36, x37, x38, x39) , (x40, x41, x42, x43, x44, x45, x46, x47, x48, x49) , (x50, x51, x52, x53, x54, x55, x56, x57, x58, x59) , (x60, x61, x62, x63, x64, x65, x66, x67, x68, x69) , (x70, x71, x72, x73, x74, x75, x76, x77, x78, x79) , (x80, x81, x82, x83, x84, x85, x86, x87, x88, x89) , (x90, x91, x92, x93, x94, x95, x96, x97, x98, x99) ) )
null
https://raw.githubusercontent.com/well-typed/large-records/c6c2b51af11e90f30822543d7ce4d1cb28cee294/large-records-benchmarks/bench/experiments/Experiment/PatternSynonym_NFS/Sized/R100.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE ViewPatterns # # OPTIONS_GHC -ddump-to-file -ddump-ds-preopt -ddump-ds -ddump-simpl # # OPTIONS_GHC -ddump-to-file -ddump-timings #
# LANGUAGE PatternSynonyms # #if __GLASGOW_HASKELL__ >= 902 # LANGUAGE NoFieldSelectors # #endif #if PROFILE_CORESIZE #endif #if PROFILE_TIMING #endif module Experiment.PatternSynonym_NFS.Sized.R100 where import Bench.Types data R viewR :: R -> ( (T 00, T 01, T 02, T 03, T 04, T 05, T 06, T 07, T 08, T 09) , (T 10, T 11, T 12, T 13, T 14, T 15, T 16, T 17, T 18, T 19) , (T 20, T 21, T 22, T 23, T 24, T 25, T 26, T 27, T 28, T 29) , (T 30, T 31, T 32, T 33, T 34, T 35, T 36, T 37, T 38, T 39) , (T 40, T 41, T 42, T 43, T 44, T 45, T 46, T 47, T 48, T 49) , (T 50, T 51, T 52, T 53, T 54, T 55, T 56, T 57, T 58, T 59) , (T 60, T 61, T 62, T 63, T 64, T 65, T 66, T 67, T 68, T 69) , (T 70, T 71, T 72, T 73, T 74, T 75, T 76, T 77, T 78, T 79) , (T 80, T 81, T 82, T 83, T 84, T 85, T 86, T 87, T 88, T 89) , (T 90, T 91, T 92, T 93, T 94, T 95, T 96, T 97, T 98, T 99) ) viewR = undefined pattern MkR :: T 00 -> T 01 -> T 02 -> T 03 -> T 04 -> T 05 -> T 06 -> T 07 -> T 08 -> T 09 -> T 10 -> T 11 -> T 12 -> T 13 -> T 14 -> T 15 -> T 16 -> T 17 -> T 18 -> T 19 -> T 20 -> T 21 -> T 22 -> T 23 -> T 24 -> T 25 -> T 26 -> T 27 -> T 28 -> T 29 -> T 30 -> T 31 -> T 32 -> T 33 -> T 34 -> T 35 -> T 36 -> T 37 -> T 38 -> T 39 -> T 40 -> T 41 -> T 42 -> T 43 -> T 44 -> T 45 -> T 46 -> T 47 -> T 48 -> T 49 -> T 50 -> T 51 -> T 52 -> T 53 -> T 54 -> T 55 -> T 56 -> T 57 -> T 58 -> T 59 -> T 60 -> T 61 -> T 62 -> T 63 -> T 64 -> T 65 -> T 66 -> T 67 -> T 68 -> T 69 -> T 70 -> T 71 -> T 72 -> T 73 -> T 74 -> T 75 -> T 76 -> T 77 -> T 78 -> T 79 -> T 80 -> T 81 -> T 82 -> T 83 -> T 84 -> T 85 -> T 86 -> T 87 -> T 88 -> T 89 -> T 90 -> T 91 -> T 92 -> T 93 -> T 94 -> T 95 -> T 96 -> T 97 -> T 98 -> T 99 -> R pattern MkR { x00, x01, x02, x03, x04, x05, x06, x07, x08, x09 , x10, x11, x12, x13, x14, x15, x16, x17, x18, x19 , x20, x21, x22, x23, x24, x25, x26, x27, x28, x29 , x30, x31, x32, x33, x34, x35, x36, x37, x38, x39 , x40, x41, x42, x43, x44, x45, x46, x47, x48, x49 , x50, x51, x52, x53, x54, x55, x56, x57, x58, x59 , x60, x61, x62, x63, x64, x65, x66, x67, x68, x69 , x70, x71, x72, x73, x74, x75, x76, x77, x78, x79 , x80, x81, x82, x83, x84, x85, x86, x87, x88, x89 , x90, x91, x92, x93, x94, x95, x96, x97, x98, x99 } <- (viewR -> ( (x00, x01, x02, x03, x04, x05, x06, x07, x08, x09) , (x10, x11, x12, x13, x14, x15, x16, x17, x18, x19) , (x20, x21, x22, x23, x24, x25, x26, x27, x28, x29) , (x30, x31, x32, x33, x34, x35, x36, x37, x38, x39) , (x40, x41, x42, x43, x44, x45, x46, x47, x48, x49) , (x50, x51, x52, x53, x54, x55, x56, x57, x58, x59) , (x60, x61, x62, x63, x64, x65, x66, x67, x68, x69) , (x70, x71, x72, x73, x74, x75, x76, x77, x78, x79) , (x80, x81, x82, x83, x84, x85, x86, x87, x88, x89) , (x90, x91, x92, x93, x94, x95, x96, x97, x98, x99) ) )
67e92f3d17d855d85105ad94a91a29a68b85ca7bdfe8b53a740e41fe9a01b6b6
hiroshi-unno/coar
problem.ml
open Core open Common.Ext open Ast type logic_type = Any | Lia | BV | Reals | Arrays let logic_type_of_str = function | "LIA" | "SAT" -> Lia | "BV" -> BV | "Reals" -> Reals | "Arrays" -> Arrays | _ -> Any type symbol = string type sort = symbol * Logic.Sort.t module type TermType = sig val logic_of: unit -> logic_type val str_of: Logic.term -> string val str_of_sym: Logic.sym -> string val str_of_sort: Logic.Sort.t -> string end module CFG (Term : TermType) : sig type identifier = Identifier of Logic.term type bfTerm = Id of identifier | Lit of Logic.term | Fun of identifier * bfTerm list type gTerm = Constant of Logic.Sort.t | Variable of Logic.Sort.t | BfTerm of bfTerm type rule = gTerm list type t = symbol * (symbol, (Logic.Sort.t * rule)) Map.Poly.t (* constructor *) val mk_cfg: symbol -> (symbol, (Logic.Sort.t * rule)) Map.Poly.t -> t val mk_gTerm_constant: Logic.Sort.t -> gTerm val mk_gTerm_variable: Logic.Sort.t -> gTerm val mk_gTerm_bfTerm: bfTerm -> gTerm val mk_identifier: Logic.term -> identifier val mk_bfTerm_identifier: identifier -> bfTerm val mk_bfTerm_identifier_of_term: Logic.term -> bfTerm val mk_bfTerm_literal: Logic.term -> bfTerm val mk_bfTerm_fun: identifier -> bfTerm list -> bfTerm val mk_symbol: string -> symbol val starting_symbol: t -> symbol val sort_of_symbol: t -> symbol -> Logic.Sort.t val rule_of_symbol: t -> symbol -> rule val str_of_rule: rule -> string val str_of: t -> string end = struct type identifier = Identifier of Logic.term type bfTerm = Id of identifier | Lit of Logic.term | Fun of identifier * bfTerm list type gTerm = Constant of Logic.Sort.t | Variable of Logic.Sort.t | BfTerm of bfTerm type rule = gTerm list type t = symbol * (symbol, (Logic.Sort.t * rule)) Map.Poly.t let mk_cfg start symbols = (start, symbols) let mk_gTerm_constant sort = Constant sort let mk_gTerm_variable sort = Variable sort let mk_gTerm_bfTerm bfTerm = BfTerm bfTerm let mk_identifier term = Identifier term let mk_bfTerm_identifier id = Id id let mk_bfTerm_identifier_of_term term = Id (Identifier term) let mk_bfTerm_literal term = Lit term let mk_bfTerm_fun id bfterms = Fun (id, bfterms) let mk_symbol symbol = symbol let starting_symbol = function | sym, _ -> sym let sort_of_symbol cfg symbol = match cfg with | _, map -> begin match Map.Poly.find map symbol with | Some (sort, _) -> sort | None -> failwith @@ Printf.sprintf "%s is not defined in the grammar" symbol end let rule_of_symbol cfg symbol = match cfg with | _, map -> begin match Map.Poly.find map symbol with | Some (_, rule) -> rule | None -> failwith @@ Printf.sprintf "%s is not defined in the grammar" symbol end let rec str_of_bfTerm = function | Id (Identifier term) | Lit term -> Term.str_of term | Fun ((Identifier sym), bfTerms) -> Printf.sprintf "(%s %s)" (Term.str_of sym) (String.concat_map_list ~sep:" " ~f:str_of_bfTerm bfTerms) let str_of_gTerm = function | Constant sort -> Printf.sprintf "Constant %s" (Term.str_of_sort sort) | Variable sort -> Printf.sprintf "Variable %s" (Term.str_of_sort sort) | BfTerm bfTerm -> Printf.sprintf "%s" (str_of_bfTerm bfTerm) let str_of_rule rule = String.concat_map_list ~sep:"\n " ~f:str_of_gTerm rule |> Printf.sprintf " %s" let str_of = function | sym, map -> Map.Poly.to_alist map |> String.concat_map_list ~sep:"\n" ~f:(fun (sym, (sort, rule)) -> Printf.sprintf "%s : %s\n%s" sym (Term.str_of_sort sort) (str_of_rule rule)) |> Printf.sprintf "starting symbol : %s\n%s" sym end module Make (Term : TermType) : sig type t = (Ident.tvar, Logic.Sort.t * CFG(Term).t option) Map.Poly.t * Logic.sort_env_map * Logic.term list (* constructor *) val mk_problem: (Ident.tvar, Logic.Sort.t * CFG(Term).t option) Map.Poly.t -> Logic.sort_env_map -> Logic.term list -> t val add_synth_fun: t -> Ident.tvar -> Logic.Sort.t -> CFG(Term).t option -> t val add_declared_var: t -> Ident.tvar -> Logic.Sort.t -> t val add_constraint: t -> Logic.term -> t val logic_of: unit -> logic_type val find_synth_fun_of: t -> Ident.tvar -> (Logic.Sort.t * CFG(Term).t option) option val str_of: t -> string end = struct module CFG = CFG(Term) type t = (Ident.tvar, Logic.Sort.t * CFG.t option) Map.Poly.t * Logic.sort_env_map * Logic.term list let mk_problem synth_funs declared_vars constraints = synth_funs, declared_vars, constraints let add_synth_fun (synth_funs, declared_vars, constraints) sym sort cfg = Map.Poly.add_exn synth_funs ~key:sym ~data:(sort, cfg), declared_vars, constraints let add_declared_var (synth_funs, declared_vars, constraints) sym sort = synth_funs, Map.Poly.add_exn declared_vars ~key:sym ~data:sort, constraints let add_constraint (synth_funs, declared_vars, constraints) constr = synth_funs, declared_vars, constr :: constraints let logic_of = Term.logic_of let find_synth_fun_of (synth_funs, _declared_vars, _constraints) symbol = Map.Poly.find synth_funs symbol let str_of_synth_funs map = Map.Poly.to_alist map |> List.fold ~init:"" ~f:(fun acc (sym, (sort, cfg)) -> Printf.sprintf "%s\n%s, (%s) %s" acc (Ident.name_of_tvar sym) (Term.str_of_sort sort) (match cfg with Some cfg -> CFG.str_of cfg | None -> "")) let str_of_declared_vars map = Map.Poly.to_alist map |> List.fold ~init:"" ~f:(fun acc (sym, sort) -> Printf.sprintf "%s\n%s, (%s)" acc (Ident.name_of_tvar sym) (Term.str_of_sort sort)) let str_of_constraints constraints = List.fold ~init:"" constraints ~f:(fun acc constr -> Printf.sprintf "%s\nconstraint : %s" acc (Term.str_of constr)) let str_of = function | synth_funs, declared_vars, constraints -> Printf.sprintf "***** synth_funs *****\n%s\n\n***** declared_vars *****\n%s\n\n***** constraints *****\n%s\n\n ***************\n" (str_of_synth_funs synth_funs) (str_of_declared_vars declared_vars) (str_of_constraints constraints) end module ExtTerm : TermType = struct let logic_of () = Lia let str_of = Logic.ExtTerm.str_of let str_of_sym = Logic.ExtTerm.str_of_sym let str_of_sort = Logic.ExtTerm.str_of_sort end
null
https://raw.githubusercontent.com/hiroshi-unno/coar/90a23a09332c68f380efd4115b3f6fdc825f413d/lib/SyGuS/problem.ml
ocaml
constructor constructor
open Core open Common.Ext open Ast type logic_type = Any | Lia | BV | Reals | Arrays let logic_type_of_str = function | "LIA" | "SAT" -> Lia | "BV" -> BV | "Reals" -> Reals | "Arrays" -> Arrays | _ -> Any type symbol = string type sort = symbol * Logic.Sort.t module type TermType = sig val logic_of: unit -> logic_type val str_of: Logic.term -> string val str_of_sym: Logic.sym -> string val str_of_sort: Logic.Sort.t -> string end module CFG (Term : TermType) : sig type identifier = Identifier of Logic.term type bfTerm = Id of identifier | Lit of Logic.term | Fun of identifier * bfTerm list type gTerm = Constant of Logic.Sort.t | Variable of Logic.Sort.t | BfTerm of bfTerm type rule = gTerm list type t = symbol * (symbol, (Logic.Sort.t * rule)) Map.Poly.t val mk_cfg: symbol -> (symbol, (Logic.Sort.t * rule)) Map.Poly.t -> t val mk_gTerm_constant: Logic.Sort.t -> gTerm val mk_gTerm_variable: Logic.Sort.t -> gTerm val mk_gTerm_bfTerm: bfTerm -> gTerm val mk_identifier: Logic.term -> identifier val mk_bfTerm_identifier: identifier -> bfTerm val mk_bfTerm_identifier_of_term: Logic.term -> bfTerm val mk_bfTerm_literal: Logic.term -> bfTerm val mk_bfTerm_fun: identifier -> bfTerm list -> bfTerm val mk_symbol: string -> symbol val starting_symbol: t -> symbol val sort_of_symbol: t -> symbol -> Logic.Sort.t val rule_of_symbol: t -> symbol -> rule val str_of_rule: rule -> string val str_of: t -> string end = struct type identifier = Identifier of Logic.term type bfTerm = Id of identifier | Lit of Logic.term | Fun of identifier * bfTerm list type gTerm = Constant of Logic.Sort.t | Variable of Logic.Sort.t | BfTerm of bfTerm type rule = gTerm list type t = symbol * (symbol, (Logic.Sort.t * rule)) Map.Poly.t let mk_cfg start symbols = (start, symbols) let mk_gTerm_constant sort = Constant sort let mk_gTerm_variable sort = Variable sort let mk_gTerm_bfTerm bfTerm = BfTerm bfTerm let mk_identifier term = Identifier term let mk_bfTerm_identifier id = Id id let mk_bfTerm_identifier_of_term term = Id (Identifier term) let mk_bfTerm_literal term = Lit term let mk_bfTerm_fun id bfterms = Fun (id, bfterms) let mk_symbol symbol = symbol let starting_symbol = function | sym, _ -> sym let sort_of_symbol cfg symbol = match cfg with | _, map -> begin match Map.Poly.find map symbol with | Some (sort, _) -> sort | None -> failwith @@ Printf.sprintf "%s is not defined in the grammar" symbol end let rule_of_symbol cfg symbol = match cfg with | _, map -> begin match Map.Poly.find map symbol with | Some (_, rule) -> rule | None -> failwith @@ Printf.sprintf "%s is not defined in the grammar" symbol end let rec str_of_bfTerm = function | Id (Identifier term) | Lit term -> Term.str_of term | Fun ((Identifier sym), bfTerms) -> Printf.sprintf "(%s %s)" (Term.str_of sym) (String.concat_map_list ~sep:" " ~f:str_of_bfTerm bfTerms) let str_of_gTerm = function | Constant sort -> Printf.sprintf "Constant %s" (Term.str_of_sort sort) | Variable sort -> Printf.sprintf "Variable %s" (Term.str_of_sort sort) | BfTerm bfTerm -> Printf.sprintf "%s" (str_of_bfTerm bfTerm) let str_of_rule rule = String.concat_map_list ~sep:"\n " ~f:str_of_gTerm rule |> Printf.sprintf " %s" let str_of = function | sym, map -> Map.Poly.to_alist map |> String.concat_map_list ~sep:"\n" ~f:(fun (sym, (sort, rule)) -> Printf.sprintf "%s : %s\n%s" sym (Term.str_of_sort sort) (str_of_rule rule)) |> Printf.sprintf "starting symbol : %s\n%s" sym end module Make (Term : TermType) : sig type t = (Ident.tvar, Logic.Sort.t * CFG(Term).t option) Map.Poly.t * Logic.sort_env_map * Logic.term list val mk_problem: (Ident.tvar, Logic.Sort.t * CFG(Term).t option) Map.Poly.t -> Logic.sort_env_map -> Logic.term list -> t val add_synth_fun: t -> Ident.tvar -> Logic.Sort.t -> CFG(Term).t option -> t val add_declared_var: t -> Ident.tvar -> Logic.Sort.t -> t val add_constraint: t -> Logic.term -> t val logic_of: unit -> logic_type val find_synth_fun_of: t -> Ident.tvar -> (Logic.Sort.t * CFG(Term).t option) option val str_of: t -> string end = struct module CFG = CFG(Term) type t = (Ident.tvar, Logic.Sort.t * CFG.t option) Map.Poly.t * Logic.sort_env_map * Logic.term list let mk_problem synth_funs declared_vars constraints = synth_funs, declared_vars, constraints let add_synth_fun (synth_funs, declared_vars, constraints) sym sort cfg = Map.Poly.add_exn synth_funs ~key:sym ~data:(sort, cfg), declared_vars, constraints let add_declared_var (synth_funs, declared_vars, constraints) sym sort = synth_funs, Map.Poly.add_exn declared_vars ~key:sym ~data:sort, constraints let add_constraint (synth_funs, declared_vars, constraints) constr = synth_funs, declared_vars, constr :: constraints let logic_of = Term.logic_of let find_synth_fun_of (synth_funs, _declared_vars, _constraints) symbol = Map.Poly.find synth_funs symbol let str_of_synth_funs map = Map.Poly.to_alist map |> List.fold ~init:"" ~f:(fun acc (sym, (sort, cfg)) -> Printf.sprintf "%s\n%s, (%s) %s" acc (Ident.name_of_tvar sym) (Term.str_of_sort sort) (match cfg with Some cfg -> CFG.str_of cfg | None -> "")) let str_of_declared_vars map = Map.Poly.to_alist map |> List.fold ~init:"" ~f:(fun acc (sym, sort) -> Printf.sprintf "%s\n%s, (%s)" acc (Ident.name_of_tvar sym) (Term.str_of_sort sort)) let str_of_constraints constraints = List.fold ~init:"" constraints ~f:(fun acc constr -> Printf.sprintf "%s\nconstraint : %s" acc (Term.str_of constr)) let str_of = function | synth_funs, declared_vars, constraints -> Printf.sprintf "***** synth_funs *****\n%s\n\n***** declared_vars *****\n%s\n\n***** constraints *****\n%s\n\n ***************\n" (str_of_synth_funs synth_funs) (str_of_declared_vars declared_vars) (str_of_constraints constraints) end module ExtTerm : TermType = struct let logic_of () = Lia let str_of = Logic.ExtTerm.str_of let str_of_sym = Logic.ExtTerm.str_of_sym let str_of_sort = Logic.ExtTerm.str_of_sort end
5c31529918efcdfa22a0c61272821c5a3d97875bd7f2e76b3e18d3ad5cc727ab
scicloj/wadogo
log.clj
(ns wadogo.ticks.log (:require [fastmath.core :as m] [wadogo.ticks.linear :refer [linear-ticks]])) (set! *unchecked-math* :warn-on-boxed) (m/use-primitive-operators) (defn- logp [^double base] (cond (m/one? base) identity (== base m/E) (fn ^double [^double x] (m/log x)) (== base 2.0) m/log2 (== base 10.0) (fn ^double [^double x] (m/log10 x)) :else (fn ^double [^double x] (m/logb base x)))) (defn- powp [^double base] (cond (m/one? base) identity (== base m/E) (fn ^double [^double x] (m/exp x)) :else (fn ^double [^double x] (m/pow base x)))) (defn log-ticks [^double start ^double end cnt ^double base] (let [negative? (neg? start) logs (logp base) pows (powp base) ^double lstart (logs (m/abs start)) ^double lend (logs (m/abs end)) ^long c (or cnt (max 1 (- lend lstart)))] (map (fn [^double v] (let [^double pv (pows v)] (if negative? (- pv) pv))) (linear-ticks lstart lend c))))
null
https://raw.githubusercontent.com/scicloj/wadogo/4076820f55c1b6413b055611ad49be4de392cdb7/src/wadogo/ticks/log.clj
clojure
(ns wadogo.ticks.log (:require [fastmath.core :as m] [wadogo.ticks.linear :refer [linear-ticks]])) (set! *unchecked-math* :warn-on-boxed) (m/use-primitive-operators) (defn- logp [^double base] (cond (m/one? base) identity (== base m/E) (fn ^double [^double x] (m/log x)) (== base 2.0) m/log2 (== base 10.0) (fn ^double [^double x] (m/log10 x)) :else (fn ^double [^double x] (m/logb base x)))) (defn- powp [^double base] (cond (m/one? base) identity (== base m/E) (fn ^double [^double x] (m/exp x)) :else (fn ^double [^double x] (m/pow base x)))) (defn log-ticks [^double start ^double end cnt ^double base] (let [negative? (neg? start) logs (logp base) pows (powp base) ^double lstart (logs (m/abs start)) ^double lend (logs (m/abs end)) ^long c (or cnt (max 1 (- lend lstart)))] (map (fn [^double v] (let [^double pv (pows v)] (if negative? (- pv) pv))) (linear-ticks lstart lend c))))
8cc628929d9cc264dde92f5b24fb5b3261549d3bee388f82280aaf7547e5b411
bobatkey/CS316-17
Lec08.hs
module Lec08 where import Test.QuickCheck LECTURE 08 : QUICKCHECK {- PART I : WRITING INDIVIDUAL TEST CASES -} -- artisanal testing, one at a time append_test_1 :: Bool append_test_1 = [1,2,3] ++ [4,5,6] == [1,2,3,4,5,6] append_test_2 :: Bool append_test_2 = [4,5,6] ++ [1,2,3] == [4,5,6,1,2,3] append_test_3 :: Bool append_test_3 = [] ++ [1,2,3] == [1,2,3] append_test_4 :: Bool append_test_4 = [1,2,3] ++ [] == [1,2,3] append_tests :: Bool append_tests = and [ append_test_1 , append_test_2 , append_test_3 , append_test_4 ] insert :: Ord a => a -> [a] -> [a] insert x [] = [x] insert x (y:ys) | x <= y = x : y : ys | otherwise = y : insert x ys insert_test_1 :: Bool insert_test_1 = insert 3 [1,2,4,5] == [1,2,3,4,5] {- PART II : PROPERTY BASED TESTING WITH QUICKCHECK -} -- /~nr/cs257/archive/john-hughes/quick.pdf -- Why not test with lots of examples, not just one? append_left_nil_prop :: [Int] -> Bool append_left_nil_prop xs = [] ++ xs == xs append_right_nil_prop :: [Int] -> Bool append_right_nil_prop xs = xs ++ [] == xs append_faulty_prop :: [Int] -> Bool append_faulty_prop xs = xs ++ [0] == xs -- (x + y) + z = x + (y + z) append_assoc :: [Int] -> [Int] -> [Int] -> Bool append_assoc xs ys zs = (xs ++ ys) ++ zs == xs ++ (ys ++ zs) reverse_reverse_prop :: [Int] -> Bool reverse_reverse_prop xs = reverse (reverse xs) == xs reverse_does_nothing :: [Int] -> Bool reverse_does_nothing xs = reverse xs == xs reverse_append :: [Int] -> [Int] -> Bool reverse_append xs ys = reverse (xs ++ ys) == reverse ys ++ reverse xs slow_reverse :: [a] -> [a] slow_reverse [] = [] slow_reverse (x:xs) = slow_reverse xs ++ [x] reverse_eq_slow_reverse :: [Int] -> Bool reverse_eq_slow_reverse xs = reverse xs == slow_reverse xs ---------------------------------------------------------------------- isSorted :: Ord a => [a] -> Bool isSorted [] = True isSorted [x] = True isSorted (x:y:ys) = x <= y && isSorted (y:ys) insert_preserves_sortedness :: Int -> [Int] -> Bool insert_preserves_sortedness x xs = isSorted (insert x (makeSorted 0 xs)) makeSorted :: Int -> [Int] -> [Int] makeSorted i [] = [] makeSorted i (x:xs) = y : makeSorted y xs where y = i + abs x makeSorted_prop :: [Int] -> Bool makeSorted_prop xs = isSorted (makeSorted 0 xs) ---------------------------------------------------------------------- data CS316Staff = Bob | Fred | Ben deriving Show instance Arbitrary CS316Staff where arbitrary = frequency [ (1, return Bob) , (1, return Fred) , (3, return Ben) ] heightRank :: CS316Staff -> Int heightRank Bob = 3 heightRank Fred = 2 heightRank Ben = 1 heightRank_prop :: CS316Staff -> Bool heightRank_prop staffMember = heightRank staffMember <= heightRank Bob ---------------------------------------------------------------------- data Tree a = TLeaf | TNode (Tree a) a (Tree a) deriving (Show, Eq) instance Arbitrary a => Arbitrary (Tree a) where arbitrary = genTree 3 genTree :: Arbitrary a => Int -> Gen (Tree a) genTree 0 = return TLeaf genTree n = frequency [ (3, do l <- genTree (n-1) x <- arbitrary r <- genTree (n-1) return (TNode l x r)) , (1, return TLeaf) ]
null
https://raw.githubusercontent.com/bobatkey/CS316-17/36eb67c335cd0e6f5b7a4b8eafdea3cd4b715e0c/lectures/Lec08.hs
haskell
PART I : WRITING INDIVIDUAL TEST CASES artisanal testing, one at a time PART II : PROPERTY BASED TESTING WITH QUICKCHECK /~nr/cs257/archive/john-hughes/quick.pdf Why not test with lots of examples, not just one? (x + y) + z = x + (y + z) -------------------------------------------------------------------- -------------------------------------------------------------------- --------------------------------------------------------------------
module Lec08 where import Test.QuickCheck LECTURE 08 : QUICKCHECK append_test_1 :: Bool append_test_1 = [1,2,3] ++ [4,5,6] == [1,2,3,4,5,6] append_test_2 :: Bool append_test_2 = [4,5,6] ++ [1,2,3] == [4,5,6,1,2,3] append_test_3 :: Bool append_test_3 = [] ++ [1,2,3] == [1,2,3] append_test_4 :: Bool append_test_4 = [1,2,3] ++ [] == [1,2,3] append_tests :: Bool append_tests = and [ append_test_1 , append_test_2 , append_test_3 , append_test_4 ] insert :: Ord a => a -> [a] -> [a] insert x [] = [x] insert x (y:ys) | x <= y = x : y : ys | otherwise = y : insert x ys insert_test_1 :: Bool insert_test_1 = insert 3 [1,2,4,5] == [1,2,3,4,5] append_left_nil_prop :: [Int] -> Bool append_left_nil_prop xs = [] ++ xs == xs append_right_nil_prop :: [Int] -> Bool append_right_nil_prop xs = xs ++ [] == xs append_faulty_prop :: [Int] -> Bool append_faulty_prop xs = xs ++ [0] == xs append_assoc :: [Int] -> [Int] -> [Int] -> Bool append_assoc xs ys zs = (xs ++ ys) ++ zs == xs ++ (ys ++ zs) reverse_reverse_prop :: [Int] -> Bool reverse_reverse_prop xs = reverse (reverse xs) == xs reverse_does_nothing :: [Int] -> Bool reverse_does_nothing xs = reverse xs == xs reverse_append :: [Int] -> [Int] -> Bool reverse_append xs ys = reverse (xs ++ ys) == reverse ys ++ reverse xs slow_reverse :: [a] -> [a] slow_reverse [] = [] slow_reverse (x:xs) = slow_reverse xs ++ [x] reverse_eq_slow_reverse :: [Int] -> Bool reverse_eq_slow_reverse xs = reverse xs == slow_reverse xs isSorted :: Ord a => [a] -> Bool isSorted [] = True isSorted [x] = True isSorted (x:y:ys) = x <= y && isSorted (y:ys) insert_preserves_sortedness :: Int -> [Int] -> Bool insert_preserves_sortedness x xs = isSorted (insert x (makeSorted 0 xs)) makeSorted :: Int -> [Int] -> [Int] makeSorted i [] = [] makeSorted i (x:xs) = y : makeSorted y xs where y = i + abs x makeSorted_prop :: [Int] -> Bool makeSorted_prop xs = isSorted (makeSorted 0 xs) data CS316Staff = Bob | Fred | Ben deriving Show instance Arbitrary CS316Staff where arbitrary = frequency [ (1, return Bob) , (1, return Fred) , (3, return Ben) ] heightRank :: CS316Staff -> Int heightRank Bob = 3 heightRank Fred = 2 heightRank Ben = 1 heightRank_prop :: CS316Staff -> Bool heightRank_prop staffMember = heightRank staffMember <= heightRank Bob data Tree a = TLeaf | TNode (Tree a) a (Tree a) deriving (Show, Eq) instance Arbitrary a => Arbitrary (Tree a) where arbitrary = genTree 3 genTree :: Arbitrary a => Int -> Gen (Tree a) genTree 0 = return TLeaf genTree n = frequency [ (3, do l <- genTree (n-1) x <- arbitrary r <- genTree (n-1) return (TNode l x r)) , (1, return TLeaf) ]
b50f886d96f74a9b349a3f625c4a031c6cd7324f26a22bd473e2de5f08be2cba
mpickering/apply-refact
Lambda38.hs
foo a b c = bar (flux ++ quux) c where flux = c
null
https://raw.githubusercontent.com/mpickering/apply-refact/a4343ea0f4f9d8c2e16d6b16b9068f321ba4f272/tests/examples/Lambda38.hs
haskell
foo a b c = bar (flux ++ quux) c where flux = c
d3d8f72c7802cff475a3d8e26f08afaf8746fb845dd8b7a3f4789890dc0d248b
travisbrady/ocaml-vw
simple.ml
(* * A trivial example showing how to create a vw instance * feed it some examples and then generate a prediction *) let printf = Printf.printf let () = let vw = Vw.initialize "--invert_hash the_model.vw" in printf "VW!!\n%!"; let examples = Array.map (fun x -> Vw.read_example vw x) [|"0 | price:.23 sqft:.25 age:.05 2006"; "1 | price:.33 sqft:.35 age:.02 2006"|] in let label = Vw.get_label (examples.(0)) in printf "get_label result: %f!!!\n" label; for i = 0 to 100 do let _ = Vw.learn vw examples.(i mod 2) in () done; let test_example = Vw.read_example vw "| price:.33 sqft:.35 age:.02 2006" in let pred = Vw.predict vw test_example in printf "predict result %f\n" pred; Array.iter (fun ex -> Vw.finish_example vw ex) examples; Vw.finish vw; ()
null
https://raw.githubusercontent.com/travisbrady/ocaml-vw/2c5ac40872a7bd4b921a8554f82f8783f5e2f88d/examples/simple.ml
ocaml
* A trivial example showing how to create a vw instance * feed it some examples and then generate a prediction
let printf = Printf.printf let () = let vw = Vw.initialize "--invert_hash the_model.vw" in printf "VW!!\n%!"; let examples = Array.map (fun x -> Vw.read_example vw x) [|"0 | price:.23 sqft:.25 age:.05 2006"; "1 | price:.33 sqft:.35 age:.02 2006"|] in let label = Vw.get_label (examples.(0)) in printf "get_label result: %f!!!\n" label; for i = 0 to 100 do let _ = Vw.learn vw examples.(i mod 2) in () done; let test_example = Vw.read_example vw "| price:.33 sqft:.35 age:.02 2006" in let pred = Vw.predict vw test_example in printf "predict result %f\n" pred; Array.iter (fun ex -> Vw.finish_example vw ex) examples; Vw.finish vw; ()
dd0a50da98e4be7d22228efd6277c1b96e0218cff76d0ca38fa4768fca7f9518
dongcarl/guix
emacs.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2015 < > Copyright © 2020 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at ;;; your option) any later version. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (guix build-system emacs) #:use-module ((guix build emacs-build-system) #:select (%default-include %default-exclude)) #:use-module (guix store) #:use-module (guix utils) #:use-module (guix packages) #:use-module (guix derivations) #:use-module (guix search-paths) #:use-module (guix build-system) #:use-module (guix build-system gnu) #:use-module (ice-9 match) #:use-module (srfi srfi-26) #:export (%emacs-build-system-modules emacs-build emacs-build-system) #:re-export (%default-include ;for convenience %default-exclude)) ;; Commentary: ;; Standard build procedure for Emacs packages . This is implemented as an ;; extension of 'gnu-build-system'. ;; ;; Code: (define %emacs-build-system-modules ;; Build-side modules imported by default. `((guix build emacs-build-system) (guix build emacs-utils) ,@%gnu-build-system-modules)) (define (default-emacs) "Return the default Emacs package." ;; Lazily resolve the binding to avoid a circular dependency. (let ((emacs-mod (resolve-interface '(gnu packages emacs)))) (module-ref emacs-mod 'emacs-minimal))) (define* (lower name #:key source inputs native-inputs outputs system target (emacs (default-emacs)) #:allow-other-keys #:rest arguments) "Return a bag for NAME." (define private-keywords '(#:target #:emacs #:inputs #:native-inputs)) (and (not target) ;XXX: no cross-compilation (bag (name name) (system system) (host-inputs `(,@(if source `(("source" ,source)) '()) ,@inputs ;; Keep the standard inputs of 'gnu-build-system'. ,@(standard-packages))) (build-inputs `(("emacs" ,emacs) ,@native-inputs)) (outputs outputs) (build emacs-build) (arguments (strip-keyword-arguments private-keywords arguments))))) (define* (emacs-build store name inputs #:key source (tests? #f) (parallel-tests? #t) (test-command ''("make" "check")) (phases '(@ (guix build emacs-build-system) %standard-phases)) (outputs '("out")) (include (quote %default-include)) (exclude (quote %default-exclude)) (search-paths '()) (system (%current-system)) (guile #f) (imported-modules %emacs-build-system-modules) (modules '((guix build emacs-build-system) (guix build utils) (guix build emacs-utils)))) "Build SOURCE using EMACS, and with INPUTS." (define builder `(begin (use-modules ,@modules) (emacs-build #:name ,name #:source ,(match (assoc-ref inputs "source") (((? derivation? source)) (derivation->output-path source)) ((source) source) (source source)) #:system ,system #:test-command ,test-command #:tests? ,tests? #:parallel-tests? ,parallel-tests? #:phases ,phases #:outputs %outputs #:include ,include #:exclude ,exclude #:search-paths ',(map search-path-specification->sexp search-paths) #:inputs %build-inputs))) (define guile-for-build (match guile ((? package?) (package-derivation store guile system #:graft? #f)) (#f ; the default (let* ((distro (resolve-interface '(gnu packages commencement))) (guile (module-ref distro 'guile-final))) (package-derivation store guile system #:graft? #f))))) (build-expression->derivation store name builder #:inputs inputs #:system system #:modules imported-modules #:outputs outputs #:guile-for-build guile-for-build)) (define emacs-build-system (build-system (name 'emacs) (description "The build system for Emacs packages") (lower lower))) ;;; emacs.scm ends here
null
https://raw.githubusercontent.com/dongcarl/guix/82543e9649da2da9a5285ede4ec4f718fd740fcb/guix/build-system/emacs.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. for convenience Commentary: extension of 'gnu-build-system'. Code: Build-side modules imported by default. Lazily resolve the binding to avoid a circular dependency. XXX: no cross-compilation Keep the standard inputs of 'gnu-build-system'. the default emacs.scm ends here
Copyright © 2015 < > Copyright © 2020 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (guix build-system emacs) #:use-module ((guix build emacs-build-system) #:select (%default-include %default-exclude)) #:use-module (guix store) #:use-module (guix utils) #:use-module (guix packages) #:use-module (guix derivations) #:use-module (guix search-paths) #:use-module (guix build-system) #:use-module (guix build-system gnu) #:use-module (ice-9 match) #:use-module (srfi srfi-26) #:export (%emacs-build-system-modules emacs-build emacs-build-system) %default-exclude)) Standard build procedure for Emacs packages . This is implemented as an (define %emacs-build-system-modules `((guix build emacs-build-system) (guix build emacs-utils) ,@%gnu-build-system-modules)) (define (default-emacs) "Return the default Emacs package." (let ((emacs-mod (resolve-interface '(gnu packages emacs)))) (module-ref emacs-mod 'emacs-minimal))) (define* (lower name #:key source inputs native-inputs outputs system target (emacs (default-emacs)) #:allow-other-keys #:rest arguments) "Return a bag for NAME." (define private-keywords '(#:target #:emacs #:inputs #:native-inputs)) (bag (name name) (system system) (host-inputs `(,@(if source `(("source" ,source)) '()) ,@inputs ,@(standard-packages))) (build-inputs `(("emacs" ,emacs) ,@native-inputs)) (outputs outputs) (build emacs-build) (arguments (strip-keyword-arguments private-keywords arguments))))) (define* (emacs-build store name inputs #:key source (tests? #f) (parallel-tests? #t) (test-command ''("make" "check")) (phases '(@ (guix build emacs-build-system) %standard-phases)) (outputs '("out")) (include (quote %default-include)) (exclude (quote %default-exclude)) (search-paths '()) (system (%current-system)) (guile #f) (imported-modules %emacs-build-system-modules) (modules '((guix build emacs-build-system) (guix build utils) (guix build emacs-utils)))) "Build SOURCE using EMACS, and with INPUTS." (define builder `(begin (use-modules ,@modules) (emacs-build #:name ,name #:source ,(match (assoc-ref inputs "source") (((? derivation? source)) (derivation->output-path source)) ((source) source) (source source)) #:system ,system #:test-command ,test-command #:tests? ,tests? #:parallel-tests? ,parallel-tests? #:phases ,phases #:outputs %outputs #:include ,include #:exclude ,exclude #:search-paths ',(map search-path-specification->sexp search-paths) #:inputs %build-inputs))) (define guile-for-build (match guile ((? package?) (package-derivation store guile system #:graft? #f)) (let* ((distro (resolve-interface '(gnu packages commencement))) (guile (module-ref distro 'guile-final))) (package-derivation store guile system #:graft? #f))))) (build-expression->derivation store name builder #:inputs inputs #:system system #:modules imported-modules #:outputs outputs #:guile-for-build guile-for-build)) (define emacs-build-system (build-system (name 'emacs) (description "The build system for Emacs packages") (lower lower)))
0d9c0add1be4370496f567b2dcfc773235b69eea402430bf3ccfdd518fb74833
tomgr/libcspm
Monad.hs
# LANGUAGE CPP # module CSPM.Evaluator.Monad where import Control.Monad.Reader import Prelude hiding (lookup) import CSPM.Syntax.Names import CSPM.Evaluator.Environment import {-# SOURCE #-} CSPM.Evaluator.Values import Util.Annotated import Util.Exception type EvaluationState = Environment type EvaluationMonad = Reader EvaluationState gets :: (EvaluationState -> a) -> EvaluationMonad a gets = asks modify :: (EvaluationState -> EvaluationState) -> EvaluationMonad a -> EvaluationMonad a modify = local runEvaluator :: EvaluationState -> EvaluationMonad a -> a runEvaluator st prog = runReader prog st getState :: EvaluationMonad EvaluationState getState = gets id # INLINE getState # getEnvironment :: EvaluationMonad Environment getEnvironment = gets id # INLINE getEnvironment # lookupVarMaybeThunk :: Name -> EvaluationMonad Value lookupVarMaybeThunk n = do This should never produce an error as the TC would -- catch it env <- getEnvironment return $ lookup env n # INLINE lookupVarMaybeThunk # maybeLookupVarMaybeThunk :: Name -> EvaluationMonad (Maybe Value) maybeLookupVarMaybeThunk n = do env <- getEnvironment return $ maybeLookup env n -- | Implements non-recursive lets. addScopeAndBind :: [(Name, Value)] -> EvaluationMonad a -> EvaluationMonad a #ifndef CSPM_PROFILING addScopeAndBind [] prog = prog #endif addScopeAndBind bs prog = modify (\ st -> newLayerAndBind st bs) prog -- | Implements recursive lets. addScopeAndBindM :: [(Name, EvaluationMonad Value)] -> EvaluationMonad a -> EvaluationMonad a #ifndef CSPM_PROFILING addScopeAndBindM [] prog = prog #endif addScopeAndBindM binds prog = do st <- getState let env' = newLayerAndBind st bs st' = env' bs = [(n, runEvaluator st' v) | (n, v) <- binds] modify (\_ -> st') prog registerFrame :: InstantiatedFrame -> SrcSpan -> EvaluationMonad a -> EvaluationMonad a registerFrame frame loc prog = modify (\st -> addFrame st (StackFrame frame loc)) prog # INLINE registerFrame # getCallStack :: EvaluationMonad StackTrace getCallStack = do env <- getEnvironment return $ getFrames env # INLINE getCallStack # withCurrentCallStack :: EvaluationState -> EvaluationMonad EvaluationState withCurrentCallStack st = do stk <- getCallStack return $ withFrames st stk # INLINE withCurrentCallStack # throwError :: ErrorMessage -> a throwError err = throwSourceError [err] throwError' :: (StackTrace -> ErrorMessage) -> EvaluationMonad a throwError' f = do stk <- getCallStack throwError (f stk)
null
https://raw.githubusercontent.com/tomgr/libcspm/24d1b41954191a16e3b5e388e35f5ba0915d671e/src/CSPM/Evaluator/Monad.hs
haskell
# SOURCE # catch it | Implements non-recursive lets. | Implements recursive lets.
# LANGUAGE CPP # module CSPM.Evaluator.Monad where import Control.Monad.Reader import Prelude hiding (lookup) import CSPM.Syntax.Names import CSPM.Evaluator.Environment import Util.Annotated import Util.Exception type EvaluationState = Environment type EvaluationMonad = Reader EvaluationState gets :: (EvaluationState -> a) -> EvaluationMonad a gets = asks modify :: (EvaluationState -> EvaluationState) -> EvaluationMonad a -> EvaluationMonad a modify = local runEvaluator :: EvaluationState -> EvaluationMonad a -> a runEvaluator st prog = runReader prog st getState :: EvaluationMonad EvaluationState getState = gets id # INLINE getState # getEnvironment :: EvaluationMonad Environment getEnvironment = gets id # INLINE getEnvironment # lookupVarMaybeThunk :: Name -> EvaluationMonad Value lookupVarMaybeThunk n = do This should never produce an error as the TC would env <- getEnvironment return $ lookup env n # INLINE lookupVarMaybeThunk # maybeLookupVarMaybeThunk :: Name -> EvaluationMonad (Maybe Value) maybeLookupVarMaybeThunk n = do env <- getEnvironment return $ maybeLookup env n addScopeAndBind :: [(Name, Value)] -> EvaluationMonad a -> EvaluationMonad a #ifndef CSPM_PROFILING addScopeAndBind [] prog = prog #endif addScopeAndBind bs prog = modify (\ st -> newLayerAndBind st bs) prog addScopeAndBindM :: [(Name, EvaluationMonad Value)] -> EvaluationMonad a -> EvaluationMonad a #ifndef CSPM_PROFILING addScopeAndBindM [] prog = prog #endif addScopeAndBindM binds prog = do st <- getState let env' = newLayerAndBind st bs st' = env' bs = [(n, runEvaluator st' v) | (n, v) <- binds] modify (\_ -> st') prog registerFrame :: InstantiatedFrame -> SrcSpan -> EvaluationMonad a -> EvaluationMonad a registerFrame frame loc prog = modify (\st -> addFrame st (StackFrame frame loc)) prog # INLINE registerFrame # getCallStack :: EvaluationMonad StackTrace getCallStack = do env <- getEnvironment return $ getFrames env # INLINE getCallStack # withCurrentCallStack :: EvaluationState -> EvaluationMonad EvaluationState withCurrentCallStack st = do stk <- getCallStack return $ withFrames st stk # INLINE withCurrentCallStack # throwError :: ErrorMessage -> a throwError err = throwSourceError [err] throwError' :: (StackTrace -> ErrorMessage) -> EvaluationMonad a throwError' f = do stk <- getCallStack throwError (f stk)
3548be80cd7f976c2b6ea3c6200531f3391834d7c9f6ffabeeab6b7e0f37dcb3
ocsigen/eliom
ppx_eliom.mli
* Eliom PPX syntax extension . For documentation , refer to { % < < a_manual chapter="ppx - syntax"|the corresponding manual page.>>% } Eliom PPX syntax extension. For documentation, refer to {% <<a_manual chapter="ppx-syntax"|the corresponding manual page.>>%} *)
null
https://raw.githubusercontent.com/ocsigen/eliom/a78186cc8720db70009f89bd9069d1f21f166ec4/src/ppx/ppx_eliom.mli
ocaml
* Eliom PPX syntax extension . For documentation , refer to { % < < a_manual chapter="ppx - syntax"|the corresponding manual page.>>% } Eliom PPX syntax extension. For documentation, refer to {% <<a_manual chapter="ppx-syntax"|the corresponding manual page.>>%} *)
70d691c7283121ed74f1a8156864802016b174fbac42a09b86cf1fdc8fb0cc54
coccinelle/coccinelle
sexp_ast_c.mli
val string_of_toplevel: Ast_c.toplevel -> string val string_of_expression: Ast_c.expression -> string val string_of_program: Ast_c.program -> string val show_info: bool ref val show_qualifier: bool ref val show_expr_info: bool ref
null
https://raw.githubusercontent.com/coccinelle/coccinelle/57cbff0c5768e22bb2d8c20e8dae74294515c6b3/parsing_c/sexp_ast_c.mli
ocaml
val string_of_toplevel: Ast_c.toplevel -> string val string_of_expression: Ast_c.expression -> string val string_of_program: Ast_c.program -> string val show_info: bool ref val show_qualifier: bool ref val show_expr_info: bool ref
fc4c084e00987d6d6b8d826f47da669d9b437265d9557e84a060a51ab147b3d7
ragkousism/Guix-on-Hurd
gnupg.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2010 , 2011 , 2013 , 2014 , 2016 < > 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 (guix gnupg) #:use-module (ice-9 popen) #:use-module (ice-9 match) #:use-module (ice-9 regex) #:use-module (ice-9 rdelim) #:use-module (ice-9 i18n) #:use-module (srfi srfi-1) #:use-module (guix ui) #:export (%gpg-command %openpgp-key-server gnupg-verify gnupg-verify* gnupg-status-good-signature? gnupg-status-missing-key?)) ;;; Commentary: ;;; ;;; GnuPG interface. ;;; ;;; Code: (define %gpg-command ;; The GnuPG 2.x command-line program name. (make-parameter (or (getenv "GUIX_GPG_COMMAND") "gpg"))) (define %openpgp-key-server ;; The default key server. Note that keys.gnupg.net appears to be ;; unreliable. (make-parameter "pgp.mit.edu")) (define (gnupg-verify sig file) "Verify signature SIG for FILE. Return a status s-exp if GnuPG failed." (define (status-line->sexp line) See file ` doc / DETAILS ' in GnuPG . (define sigid-rx (make-regexp "^\\[GNUPG:\\] SIG_ID ([A-Za-z0-9+/]+) ([[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}) ([[:digit:]]+)")) (define goodsig-rx (make-regexp "^\\[GNUPG:\\] GOODSIG ([[:xdigit:]]+) (.+)$")) (define validsig-rx (make-regexp "^\\[GNUPG:\\] VALIDSIG ([[:xdigit:]]+) ([[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}) ([[:digit:]]+) .*$")) (define expkeysig-rx ; good signature, but expired key (make-regexp "^\\[GNUPG:\\] EXPKEYSIG ([[:xdigit:]]+) (.*)$")) (define errsig-rx (make-regexp "^\\[GNUPG:\\] ERRSIG ([[:xdigit:]]+) ([^ ]+) ([^ ]+) ([^ ]+) ([[:digit:]]+) ([[:digit:]]+)")) (cond ((regexp-exec sigid-rx line) => (lambda (match) `(signature-id ,(match:substring match 1) ; sig id ,(match:substring match 2) ; date ,(string->number ; timestamp (match:substring match 3))))) ((regexp-exec goodsig-rx line) => (lambda (match) `(good-signature ,(match:substring match 1) ; key id ,(match:substring match 2)))) ; user name ((regexp-exec validsig-rx line) => (lambda (match) `(valid-signature ,(match:substring match 1) ; fingerprint ,(match:substring match 2) ; sig creation date ,(string->number ; timestamp (match:substring match 3))))) ((regexp-exec expkeysig-rx line) => (lambda (match) `(expired-key-signature ,(match:substring match 1) ; fingerprint ,(match:substring match 2)))) ; user name ((regexp-exec errsig-rx line) => (lambda (match) `(signature-error ,(match:substring match 1) ; key id or fingerprint ,(match:substring match 2) ; pubkey algo ,(match:substring match 3) ; hash algo ,(match:substring match 4) ; sig class ,(string->number ; timestamp (match:substring match 5)) ,(let ((rc (string->number ; return code (match:substring match 6)))) (case rc ((9) 'missing-key) ((4) 'unknown-algorithm) (else rc)))))) (else `(unparsed-line ,line)))) (define (parse-status input) (let loop ((line (read-line input)) (result '())) (if (eof-object? line) (reverse result) (loop (read-line input) (cons (status-line->sexp line) result))))) (let* ((pipe (open-pipe* OPEN_READ (%gpg-command) "--status-fd=1" "--verify" sig file)) (status (parse-status pipe))) ;; Ignore PIPE's exit status since STATUS above should contain all the ;; info we need. (close-pipe pipe) status)) (define (gnupg-status-good-signature? status) "If STATUS, as returned by `gnupg-verify', denotes a good signature, return a key-id/user pair; return #f otherwise." (any (lambda (sexp) (match sexp (((or 'good-signature 'expired-key-signature) key-id user) (cons key-id user)) (_ #f))) status)) (define (gnupg-status-missing-key? status) "If STATUS denotes a missing-key error, then return the key-id of the missing key." (any (lambda (sexp) (match sexp (('signature-error key-id _ ...) key-id) (_ #f))) status)) (define (gnupg-receive-keys key-id server) (system* (%gpg-command) "--keyserver" server "--recv-keys" key-id)) (define* (gnupg-verify* sig file #:key (key-download 'interactive) (server (%openpgp-key-server))) "Like `gnupg-verify', but try downloading the public key if it's missing. Return #t if the signature was good, #f otherwise. KEY-DOWNLOAD specifies a download policy for missing OpenPGP keys; allowed values: 'always', 'never', and 'interactive' (default)." (let ((status (gnupg-verify sig file))) (or (gnupg-status-good-signature? status) (let ((missing (gnupg-status-missing-key? status))) (define (download-and-try-again) ;; Download the missing key and try again. (begin (gnupg-receive-keys missing server) (gnupg-status-good-signature? (gnupg-verify sig file)))) (define (receive?) (let ((answer (begin (format #t (_ "~a~a~%") "Would you like to download this key " "and add it to your keyring?") (read-line)))) (string-match (locale-yes-regexp) answer))) (and missing (case key-download ((never) #f) ((always) (download-and-try-again)) (else (and (receive?) (download-and-try-again))))))))) ;;; gnupg.scm ends here
null
https://raw.githubusercontent.com/ragkousism/Guix-on-Hurd/e951bb2c0c4961dc6ac2bda8f331b9c4cee0da95/guix/gnupg.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Commentary: GnuPG interface. Code: The GnuPG 2.x command-line program name. The default key server. Note that keys.gnupg.net appears to be unreliable. good signature, but expired key sig id date timestamp key id user name fingerprint sig creation date timestamp fingerprint user name key id or fingerprint pubkey algo hash algo sig class timestamp return code Ignore PIPE's exit status since STATUS above should contain all the info we need. return #f otherwise." allowed values: 'always', 'never', Download the missing key and try again. gnupg.scm ends here
Copyright © 2010 , 2011 , 2013 , 2014 , 2016 < > 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 (guix gnupg) #:use-module (ice-9 popen) #:use-module (ice-9 match) #:use-module (ice-9 regex) #:use-module (ice-9 rdelim) #:use-module (ice-9 i18n) #:use-module (srfi srfi-1) #:use-module (guix ui) #:export (%gpg-command %openpgp-key-server gnupg-verify gnupg-verify* gnupg-status-good-signature? gnupg-status-missing-key?)) (define %gpg-command (make-parameter (or (getenv "GUIX_GPG_COMMAND") "gpg"))) (define %openpgp-key-server (make-parameter "pgp.mit.edu")) (define (gnupg-verify sig file) "Verify signature SIG for FILE. Return a status s-exp if GnuPG failed." (define (status-line->sexp line) See file ` doc / DETAILS ' in GnuPG . (define sigid-rx (make-regexp "^\\[GNUPG:\\] SIG_ID ([A-Za-z0-9+/]+) ([[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}) ([[:digit:]]+)")) (define goodsig-rx (make-regexp "^\\[GNUPG:\\] GOODSIG ([[:xdigit:]]+) (.+)$")) (define validsig-rx (make-regexp "^\\[GNUPG:\\] VALIDSIG ([[:xdigit:]]+) ([[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}) ([[:digit:]]+) .*$")) (make-regexp "^\\[GNUPG:\\] EXPKEYSIG ([[:xdigit:]]+) (.*)$")) (define errsig-rx (make-regexp "^\\[GNUPG:\\] ERRSIG ([[:xdigit:]]+) ([^ ]+) ([^ ]+) ([^ ]+) ([[:digit:]]+) ([[:digit:]]+)")) (cond ((regexp-exec sigid-rx line) => (lambda (match) (match:substring match 3))))) ((regexp-exec goodsig-rx line) => (lambda (match) ((regexp-exec validsig-rx line) => (lambda (match) (match:substring match 3))))) ((regexp-exec expkeysig-rx line) => (lambda (match) ((regexp-exec errsig-rx line) => (lambda (match) (match:substring match 5)) ,(let ((rc (match:substring match 6)))) (case rc ((9) 'missing-key) ((4) 'unknown-algorithm) (else rc)))))) (else `(unparsed-line ,line)))) (define (parse-status input) (let loop ((line (read-line input)) (result '())) (if (eof-object? line) (reverse result) (loop (read-line input) (cons (status-line->sexp line) result))))) (let* ((pipe (open-pipe* OPEN_READ (%gpg-command) "--status-fd=1" "--verify" sig file)) (status (parse-status pipe))) (close-pipe pipe) status)) (define (gnupg-status-good-signature? status) "If STATUS, as returned by `gnupg-verify', denotes a good signature, return (any (lambda (sexp) (match sexp (((or 'good-signature 'expired-key-signature) key-id user) (cons key-id user)) (_ #f))) status)) (define (gnupg-status-missing-key? status) "If STATUS denotes a missing-key error, then return the key-id of the missing key." (any (lambda (sexp) (match sexp (('signature-error key-id _ ...) key-id) (_ #f))) status)) (define (gnupg-receive-keys key-id server) (system* (%gpg-command) "--keyserver" server "--recv-keys" key-id)) (define* (gnupg-verify* sig file #:key (key-download 'interactive) (server (%openpgp-key-server))) "Like `gnupg-verify', but try downloading the public key if it's missing. Return #t if the signature was good, #f otherwise. KEY-DOWNLOAD specifies a and 'interactive' (default)." (let ((status (gnupg-verify sig file))) (or (gnupg-status-good-signature? status) (let ((missing (gnupg-status-missing-key? status))) (define (download-and-try-again) (begin (gnupg-receive-keys missing server) (gnupg-status-good-signature? (gnupg-verify sig file)))) (define (receive?) (let ((answer (begin (format #t (_ "~a~a~%") "Would you like to download this key " "and add it to your keyring?") (read-line)))) (string-match (locale-yes-regexp) answer))) (and missing (case key-download ((never) #f) ((always) (download-and-try-again)) (else (and (receive?) (download-and-try-again)))))))))
386b96624cc0412e24c404971b9ea7a31cafa881eb5363080878414268d52c06
smaccoun/polysemy-servant
Serve.hs
module Server.Serve where import AppBase import Servant.Server import Servant (errHTTPCode) import Server.API.API (apiServer, api) import qualified Network.Wai.Handler.Warp as Warp import Config import qualified Network.Wai as Wai import Polysemy hiding (run) import Effects import Control.Monad.Except (throwError, catchError) webApp :: Config -> Wai.Application webApp config = serve api $ hoistServer api (toHandler config) apiServer toHandler :: Config -> Sem AllAppEffects a -> Handler a toHandler config action = Handler . ExceptT $ (runServerIO config action) runServer :: Config -> IO () runServer config = Warp.run 8080 (webApp config)
null
https://raw.githubusercontent.com/smaccoun/polysemy-servant/93f7977d6c03995d03674e9e5e0c24f02458b182/src/Server/Serve.hs
haskell
module Server.Serve where import AppBase import Servant.Server import Servant (errHTTPCode) import Server.API.API (apiServer, api) import qualified Network.Wai.Handler.Warp as Warp import Config import qualified Network.Wai as Wai import Polysemy hiding (run) import Effects import Control.Monad.Except (throwError, catchError) webApp :: Config -> Wai.Application webApp config = serve api $ hoistServer api (toHandler config) apiServer toHandler :: Config -> Sem AllAppEffects a -> Handler a toHandler config action = Handler . ExceptT $ (runServerIO config action) runServer :: Config -> IO () runServer config = Warp.run 8080 (webApp config)
0c5039134041246515c24678b28348136cd8b834984f65b6d815e2b3bc5c4c3c
raph-amiard/CamllVM
13_gcd_clean.ml
let rec gcd a b = if a = 0 then b else if b = 0 then a else if a > b then gcd b (a mod b) else gcd a (b mod a);; print_int (gcd 12344 24482);; print_newline ();;
null
https://raw.githubusercontent.com/raph-amiard/CamllVM/d36928f0e81a6f4f65ddd3a8653887d187632dc2/test/testfiles/13_gcd_clean.ml
ocaml
let rec gcd a b = if a = 0 then b else if b = 0 then a else if a > b then gcd b (a mod b) else gcd a (b mod a);; print_int (gcd 12344 24482);; print_newline ();;
eeb14b41684b28bb94eb9bce8cb199232ba33f764a2fa719a06ac6f78d616b48
drcode/webfui
inverse_kinematics.clj
(ns webfui-examples.views.inverse-kinematics (:require [webfui-examples.views.common :as common] [noir.content.getting-started]) (:use [noir.core :only [defpage]] [hiccup.core :only [html]])) (defpage "/inverse_kinematics" [] (common/layout "inverse_kinematics"))
null
https://raw.githubusercontent.com/drcode/webfui/e8ba6e9224542755e5780488cb43f0c5510827f9/webfui-examples/src-clj/webfui_examples/views/inverse_kinematics.clj
clojure
(ns webfui-examples.views.inverse-kinematics (:require [webfui-examples.views.common :as common] [noir.content.getting-started]) (:use [noir.core :only [defpage]] [hiccup.core :only [html]])) (defpage "/inverse_kinematics" [] (common/layout "inverse_kinematics"))
862d20dd0a4ca7436d953822fd04a5876945e2e8df427107bfcd55f14ba8e09d
careercup/CtCI-6th-Edition-Clojure
chapter_4_q8_test.clj
(ns ^{:author "Leeor Engel"} chapter-4.chapter-4-q8-test (:require [clojure.test :refer :all] [data-structures.tree :refer :all] [chapter-4.chapter-4-q8 :refer :all] [clojure.zip :as zip])) (deftest first-common-ancestor-test (testing "equal depths" (let [tree (create-tree-zipper [4]) n1 tree n2 tree] (is (= (zip/node n1) (first-common-ancestor n1 n2)))) (let [tree (create-tree-zipper [4 [2] [3]]) left-child (zip-left-child tree) right-child (zip-right-child tree)] (is (= (zip/node tree) (first-common-ancestor left-child right-child)))) (let [tree (create-tree-zipper [4 [2 [1] [nil]] [3 [nil] [7]]]) n1 (-> tree zip-left-child zip-left-child) n2 (-> tree zip-right-child zip-right-child)] (is (= (zip/node tree) (first-common-ancestor n1 n2))))) (testing "un-equal depths" (let [tree (create-tree-zipper [4 [2 [1 [14] [nil]] [8]] [3 [nil] [7]]]) n1 (-> tree zip-left-child zip-left-child zip-left-child) n2 (-> tree zip-left-child zip-right-child)] (is (= (-> tree zip-left-child zip/node) (first-common-ancestor n1 n2)))) (let [tree (create-tree-zipper [4 [2 [1 [14 [24]] [nil]] [8]] [3 [nil] [7]]]) n1 (-> tree zip-left-child zip-left-child zip-left-child zip-left-child) n2 (-> tree zip-left-child zip-right-child)] (is (= (-> tree zip-left-child zip/node) (first-common-ancestor n1 n2))))))
null
https://raw.githubusercontent.com/careercup/CtCI-6th-Edition-Clojure/ef151b94978af82fb3e0b1b0cd084d910870c52a/test/chapter_4/chapter_4_q8_test.clj
clojure
(ns ^{:author "Leeor Engel"} chapter-4.chapter-4-q8-test (:require [clojure.test :refer :all] [data-structures.tree :refer :all] [chapter-4.chapter-4-q8 :refer :all] [clojure.zip :as zip])) (deftest first-common-ancestor-test (testing "equal depths" (let [tree (create-tree-zipper [4]) n1 tree n2 tree] (is (= (zip/node n1) (first-common-ancestor n1 n2)))) (let [tree (create-tree-zipper [4 [2] [3]]) left-child (zip-left-child tree) right-child (zip-right-child tree)] (is (= (zip/node tree) (first-common-ancestor left-child right-child)))) (let [tree (create-tree-zipper [4 [2 [1] [nil]] [3 [nil] [7]]]) n1 (-> tree zip-left-child zip-left-child) n2 (-> tree zip-right-child zip-right-child)] (is (= (zip/node tree) (first-common-ancestor n1 n2))))) (testing "un-equal depths" (let [tree (create-tree-zipper [4 [2 [1 [14] [nil]] [8]] [3 [nil] [7]]]) n1 (-> tree zip-left-child zip-left-child zip-left-child) n2 (-> tree zip-left-child zip-right-child)] (is (= (-> tree zip-left-child zip/node) (first-common-ancestor n1 n2)))) (let [tree (create-tree-zipper [4 [2 [1 [14 [24]] [nil]] [8]] [3 [nil] [7]]]) n1 (-> tree zip-left-child zip-left-child zip-left-child zip-left-child) n2 (-> tree zip-left-child zip-right-child)] (is (= (-> tree zip-left-child zip/node) (first-common-ancestor n1 n2))))))
e3923491a9f2d3cb8f0dd17c70c7d18a971cc152b30682bf960d49de2592eb53
MaskRay/99-problems-ocaml
6.ml
let is_palindrome xs = List.rev xs = xs
null
https://raw.githubusercontent.com/MaskRay/99-problems-ocaml/652604f13ba7a73eee06d359b4db549b49ec9bb3/1-10/6.ml
ocaml
let is_palindrome xs = List.rev xs = xs
9e9576e22685ae5be12f0255e9ee2f4ebecba65d5a7f6608603cd8d996450be7
AndrasKovacs/setoidtt
FlatParseIndent.hs
module Old.FlatParseIndent where import qualified Data.ByteString as B import qualified Data.ByteString.Short.Internal as SB import qualified Data.ByteString.Unsafe as B import qualified Data.Text.Short as T import qualified Data.Text.Short.Unsafe as T import qualified Data.Map.Strict as M import Data.Map (Map) import Data.Bits import Data.Char (ord) import Data.Foldable import Data.Word import GHC.Exts import GHC.Word import Language.Haskell.TH import System.IO.Unsafe -------------------------------------------------------------------------------- data Error e = Default | Custom e deriving Show type Res# e a = (# (# a, Addr#, Int# #) | (# Error e, Addr# #) #) pattern OK# :: a -> Addr# -> Int# -> Res# e a pattern OK# a s j = (# (# a, s, j #) | #) pattern Err# :: Error e -> Addr# -> Res# e a pattern Err# e s = (# | (# e, s #) #) {-# complete OK#, Err# #-} newtype Parser e a = Parser {runParser# :: Addr# -> Int# -> Addr# -> Int# -> Res# e a} instance Functor (Parser e) where fmap f (Parser g) = Parser \e i s j -> case g e i s j of OK# a s j -> let !b = f a in OK# b s j Err# e s -> Err# e s # inline fmap # (<$) a' (Parser g) = Parser \e i s j -> case g e i s j of OK# a s j -> OK# a' s j Err# e s -> Err# e s {-# inline (<$) #-} err :: e -> Parser e a err e = Parser \_ i s j -> Err# (Custom e) s # inline err # empty :: Parser e a empty = Parser \e i s j -> Err# Default s {-# inline empty #-} instance Applicative (Parser e) where pure a = Parser \e i s j -> OK# a s j {-# inline pure #-} Parser ff <*> Parser fa = Parser \e i s j -> case ff e i s j of Err# e s -> Err# e s OK# f s j -> case fa e i s j of Err# e s -> Err# e s OK# a s j -> OK# (f a) s j {-# inline (<*>) #-} Parser fa <* Parser fb = Parser \e i s j -> case fa e i s j of Err# e s -> Err# e s OK# a s j -> case fb e i s j of Err# e s -> Err# e s OK# b s j -> OK# a s j {-# inline (<*) #-} Parser fa *> Parser fb = Parser \e i s j -> case fa e i s j of Err# e s -> Err# e s OK# a s j -> fb e i s j {-# inline (*>) #-} instance Monad (Parser e) where return = pure {-# inline return #-} Parser fa >>= f = Parser \e i s j -> case fa e i s j of Err# e s -> Err# e s OK# a s j -> runParser# (f a) e i s j {-# inline (>>=) #-} Parser fa >> Parser fb = Parser \e i s j -> case fa e i s j of Err# e s -> Err# e s OK# a s j -> fb e i s j {-# inline (>>) #-} ask :: Parser e Int ask = Parser \e i s j -> OK# (I# i) s j {-# inline ask #-} local :: (Int -> Int) -> Parser e a -> Parser e a local f (Parser fa) = Parser \e i s j -> case f (I# i) of I# i -> fa e i s j {-# inline local #-} derefChar8# :: Addr# -> Char# derefChar8# addr = indexCharOffAddr# addr 0# {-# inline derefChar8# #-} eof :: Parser e () eof = Parser \e i s j -> case eqAddr# e s of 1# -> OK# () s j _ -> Err# Default s # inline eof # isDigit :: Char -> Bool isDigit c = '0' <= c && c <= '9' {-# inline isDigit #-} isLatinLetter :: Char -> Bool isLatinLetter c = ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') # inline isLatinLetter # isGreekLetter :: Char -> Bool isGreekLetter c = ('Α' <= c && c <= 'Ω') || ('α' <= c && c <= 'ω') {-# inline isGreekLetter #-} | Choose between two parsers . The second parser is tried if the first one fails , regardless of how much input the first parser consumed . infixr 6 <!> (<!>) :: Parser e a -> Parser e a -> Parser e a (<!>) (Parser f) (Parser g) = Parser \e i s j -> case f e i s j of Err# _ _ -> g e i s j x -> x {-# inline (<!>) #-} | Choose between two parsers . The second parser is only tried if the first one fails without having consumed input . infixr 6 <|> (<|>) :: Parser e a -> Parser e a -> Parser e a (<|>) (Parser f) (Parser g) = Parser \e i s j -> case f e i s j of Err# err s' -> case eqAddr# s s' of 1# -> g e i s j _ -> Err# err s' x -> x {-# inline (<|>) #-} -- | Reset the input position if the given parser fails. try :: Parser e a -> Parser e a try (Parser f) = Parser \e i s j -> case f e i s j of Err# err _ -> Err# err s x -> x {-# inline try #-} | Parse any ` Char ` in the ASCII range . anyCharA :: Parser e Char anyCharA = Parser \e i s j -> case eqAddr# e s of 1# -> Err# Default s _ -> case derefChar8# s of c1 -> case c1 `leChar#` '\x7F'# of 1# -> OK# (C# c1) (plusAddr# s 1#) j _ -> Err# Default s {-# inline anyCharA #-} | Skip any ` Char ` in the ASCII range . anyCharA_ :: Parser e () anyCharA_ = () <$ anyCharA {-# inline anyCharA_ #-} -- | Parse any `Char`. -- Assumes that input is UTF8! anyChar :: Parser e Char anyChar = Parser \e i s j -> case eqAddr# e s of 1# -> Err# Default s _ -> case derefChar8# s of c1 -> case c1 `leChar#` '\x7F'# of 1# -> OK# (C# c1) (plusAddr# s 1#) j _ -> case eqAddr# e (plusAddr# s 1#) of 1# -> Err# Default s _ -> case indexCharOffAddr# s 1# of c2 -> case c1 `leChar#` '\xDF'# of 1# -> let resc = ((ord# c1 -# 0xC0#) `uncheckedIShiftL#` 6#) `orI#` (ord# c2 -# 0x80#) in OK# (C# (chr# resc)) (plusAddr# s 2#) j _ -> case eqAddr# e (plusAddr# s 2#) of 1# -> Err# Default s _ -> case indexCharOffAddr# s 2# of c3 -> case c1 `leChar#` '\xEF'# of 1# -> let resc = ((ord# c1 -# 0xE0#) `uncheckedIShiftL#` 12#) `orI#` ((ord# c2 -# 0x80#) `uncheckedIShiftL#` 6#) `orI#` (ord# c3 -# 0x80#) in OK# (C# (chr# resc)) (plusAddr# s 3#) j _ -> case eqAddr# e (plusAddr# s 3#) of 1# -> Err# Default s _ -> case indexCharOffAddr# s 3# of c4 -> let resc = ((ord# c1 -# 0xF0#) `uncheckedIShiftL#` 18#) `orI#` ((ord# c2 -# 0x80#) `uncheckedIShiftL#` 12#) `orI#` ((ord# c3 -# 0x80#) `uncheckedIShiftL#` 6#) `orI#` (ord# c4 -# 0x80#) in OK# (C# (chr# resc)) (plusAddr# s 4#) j # inline anyChar # -- | Skip any `Char`. anyChar_ :: Parser e () anyChar_ = Parser \e i s j -> case eqAddr# e s of 1# -> Err# Default s _ -> case derefChar8# s of c1 -> case c1 `leChar#` '\x7F'# of 1# -> OK# () (plusAddr# s 1#) j _ -> let s' = case c1 `leChar#` '\xDF'# of 1# -> plusAddr# s 2# _ -> case c1 `leChar#` '\xEF'# of 1# -> plusAddr# s 3# _ -> plusAddr# s 4# in case leAddr# s' e of 1# -> OK# () s' j _ -> Err# Default s # inline anyChar _ # | Parser a ` Char ` for which a predicate holds . satisfy :: (Char -> Bool) -> Parser e Char satisfy f = Parser \e i s j -> case runParser# anyChar e i s j of OK# c s j | f c -> OK# c s j OK# c _ _ -> Err# Default s Err# e s -> Err# e s {-# inline satisfy #-} | Parse an ASCII ` Char ` for which a predicate holds . satisfyA :: (Char -> Bool) -> Parser e Char satisfyA f = Parser \e i s j -> case runParser# anyCharA e i s j of OK# c s j | f c -> OK# c s j OK# c _ _ -> Err# Default s Err# e s -> Err# e s {-# inline satisfyA #-} | Skip a parser zero or more times . This fails if the given parser fails with -- having consumed input. many_ :: Parser e a -> Parser e () many_ (Parser f) = go where go = Parser \e i s j -> case f e i s j of Err# e s' -> case eqAddr# s s' of 1# -> OK# () s j _ -> Err# e s' OK# a s j -> runParser# go e i s j {-# inline many_ #-} manyBr_ :: Parser e a -> Parser e b -> Parser e () manyBr_ pa pb = go where go = br pa (pb >> go) (pure ()) {-# inline manyBr_ #-} manyTok_ :: Parser e a -> Parser e () manyTok_ (Parser f) = go where go = Parser \e i s j -> case f e i s j of Err# _ _ -> OK# () s j OK# a s j -> runParser# go e i s j {-# inline manyTok_ #-} -- | Skip a parser one or more times. This fails if the given parser fails with -- having consumed input. some_ :: Parser e a -> Parser e () some_ pa = pa >> many_ pa {-# inline some_ #-} someBr_ :: Parser e a -> Parser e b -> Parser e () someBr_ pa pb = pa >> pb >> manyBr_ pa pb {-# inline someBr_ #-} someTok_ :: Parser e a -> Parser e () someTok_ pa = pa >> manyTok_ pa {-# inline someTok_ #-} | Skip a parser zero or more times until a closing parser . This fails -- if the closing parser fails with having consumed input. manyTill_ :: Parser e a -> Parser e b -> Parser e () manyTill_ pa end = go where go = (() <$ end) <|> (pa >> go) # inline manyTill _ # chainl :: (b -> a -> b) -> Parser e b -> Parser e a -> Parser e b chainl f start elem = start >>= go where go b = do {!a <- elem; go $! f b a} <|> pure b # inline chainl # chainr :: (a -> b -> b) -> Parser e a -> Parser e b -> Parser e b chainr f elem end = go where go = (f <$> elem <*> go) <|> end # inline chainr # silent :: Parser e a -> Parser e a silent pa = Parser \e i s j -> case runParser# pa e i s j of Err# e s -> Err# Default s x -> x {-# inline silent #-} data Pos = Pos Addr# instance Eq Pos where Pos p == Pos p' = isTrue# (eqAddr# p p') {-# inline (==) #-} data Span = Span !Pos !Pos deriving Eq spanned :: Parser e a -> Parser e (a, Span) spanned (Parser f) = Parser \e i s j -> case f e i s j of Err# e s -> Err# e s OK# a s' j' -> OK# (a, Span (Pos s) (Pos s')) s' j' {-# inline spanned #-} spanToShortText :: Span -> T.ShortText spanToShortText (Span (Pos start) (Pos end)) = let len = minusAddr# end start in T.fromShortByteStringUnsafe (SB.SBS (runRW# \s -> case newByteArray# len s of (# s, marr #) -> case copyAddrToByteArray# start marr 0# len s of s -> case unsafeFreezeByteArray# marr s of (# s, arr #) -> arr)) {-# inline spanToShortText #-} asShortText :: Parser e a -> Parser e (T.ShortText) asShortText p = fmap (\(_ ,s) -> spanToShortText s) (spanned p) {-# inline asShortText #-} getPos :: Parser e Pos getPos = Parser \e i s j -> OK# (Pos s) s j # inline getPos # setPos :: Pos -> Parser e () setPos (Pos s) = Parser \e i _ j -> OK# () s j # inline setPos # data PosInfo = PosInfo { _lineNum :: !Int, _colNum :: !Int, _line :: {-# unpack #-} !(B.ByteString) } deriving Show -- | Retrieve line and column informations for a list of `Pos`-s. Throw an error if any of the positions does not point into the ` ByteString ` . posInfo :: B.ByteString -> [Pos] -> [PosInfo] posInfo = error "TODO" -- | Run a parser in a given span. The span behaves as the new beginning and end -- of the input buffer. The `Int` parameter is the current indentation level -- at the beginning of the spane. When the parser finishes, the original -- external state is restored. inSpan :: Int -> Span -> Parser e a -> Parser e a inSpan (I# j) (Span (Pos start) (Pos end)) (Parser f) = Parser \e' i s' j' -> case f end i start j of OK# a _ _ -> OK# a s' j' Err# err _ -> Err# err s' {-# inline inSpan #-} data Result e a = OK a B.ByteString | Err (Error e) B.ByteString deriving Show runParser :: Parser e a -> B.ByteString -> Result e a runParser (Parser f) b = unsafeDupablePerformIO do B.unsafeUseAsCString b \(Ptr buf) -> do let !(I# len) = B.length b let end = plusAddr# buf len case f end 0# buf 0# of Err# e s -> do let offset = minusAddr# s buf pure (Err e (B.drop (I# offset) b)) OK# a s j -> do let offset = minusAddr# s buf pure (OK a (B.drop (I# offset) b)) testParser :: Parser e a -> String -> Result e a testParser pa s = runParser pa (B.pack (concatMap charToBytes s)) br :: Parser e a -> Parser e b -> Parser e b -> Parser e b br pa pt pf = Parser \e i s j -> case runParser# pa e i s j of OK# _ s j -> runParser# pt e i s j Err# _ _ -> runParser# pf e i s j # inline br # get :: Parser e Int get = Parser \e i s j -> OK# (I# j) s j {-# inline get #-} put :: Int -> Parser e () put (I# j) = Parser \e i s _ -> OK# () s j {-# inline put #-} modify :: (Int -> Int) -> Parser e () modify f = Parser \e i s j -> case f (I# j) of I# j -> OK# () s j {-# inline modify #-} -- char and string -------------------------------------------------------------------------------- charToBytes :: Char -> [Word8] charToBytes c' | c <= 0x7f = [fromIntegral c] | c <= 0x7ff = [0xc0 .|. y, 0x80 .|. z] | c <= 0xffff = [0xe0 .|. x, 0x80 .|. y, 0x80 .|. z] | c <= 0x10ffff = [0xf0 .|. w, 0x80 .|. x, 0x80 .|. y, 0x80 .|. z] | otherwise = error "Not a valid Unicode code point" where c = ord c' z = fromIntegral (c .&. 0x3f) y = fromIntegral (unsafeShiftR c 6 .&. 0x3f) x = fromIntegral (unsafeShiftR c 12 .&. 0x3f) w = fromIntegral (unsafeShiftR c 18 .&. 0x7) strToBytes :: String -> [Word8] strToBytes = concatMap charToBytes # inline strToBytes # packBytes :: [Word8] -> Word packBytes = fst . foldl' go (0, 0) where go (acc, shift) w | shift == 64 = error "packWords: too many bytes" go (acc, shift) w = (unsafeShiftL (fromIntegral w) shift .|. acc, shift+8) splitBytes :: [Word8] -> ([Word8], [Word]) splitBytes ws = case quotRem (length ws) 8 of (0, _) -> (ws, []) (_, r) -> (as, chunk8s bs) where (as, bs) = splitAt r ws chunk8s [] = [] chunk8s ws = let (as, bs) = splitAt 8 ws in packBytes as : chunk8s bs scanAny8# :: Parser e Word8 scanAny8# = Parser \e i s j -> OK# (W8# (indexWord8OffAddr# s 0#)) (plusAddr# s 1#) j # inline scanAny8 # # scan8# :: Word -> Parser e () scan8# (W# c) = Parser \e i s j -> case indexWord8OffAddr# s 0# of c' -> case eqWord# c c' of 1# -> OK# () (plusAddr# s 1#) j _ -> Err# Default s # inline scan8 # # scan16# :: Word -> Parser e () scan16# (W# c) = Parser \e i s j -> case indexWord16OffAddr# s 0# of c' -> case eqWord# c c' of 1# -> OK# () (plusAddr# s 2#) j _ -> Err# Default s # inline scan16 # # scan32# :: Word -> Parser e () scan32# (W# c) = Parser \e i s j -> case indexWord32OffAddr# s 0# of c' -> case eqWord# c c' of 1# -> OK# () (plusAddr# s 4#) j _ -> Err# Default s {-# inline scan32# #-} scan64# :: Word -> Parser e () scan64# (W# c) = Parser \e i s j -> case indexWord64OffAddr# s 0# of c' -> case eqWord# c c' of 1# -> OK# () (plusAddr# s 8#) j _ -> Err# Default s {-# inline scan64# #-} scanPartial64# :: Int -> Word -> Parser e () scanPartial64# (I# len) (W# w) = Parser \e i s j -> case indexWordOffAddr# s 0# of w' -> case uncheckedIShiftL# (8# -# len) 3# of sh -> case uncheckedShiftL# w' sh of w' -> case uncheckedShiftRL# w' sh of w' -> case eqWord# w w' of 1# -> OK# () (plusAddr# s len) j _ -> Err# Default s # inline scanPartial64 # # ensureBytes# :: Int -> Parser e () ensureBytes# (I# len) = Parser \e i s j -> case len <=# minusAddr# e s of 1# -> OK# () s j _ -> Err# Default s # inline ensureBytes # # scanBytes# :: Bool -> [Word8] -> Q Exp scanBytes# isToken bytes = do let !(leading, w8s) = splitBytes bytes !leadingLen = length leading !w8sLen = length w8s !scanw8s = go w8s where go (w8:[] ) = [| scan64# w8 |] go (w8:w8s) = [| scan64# w8 >> $(go w8s) |] go [] = [| pure () |] case w8s of [] -> if elem leadingLen [3, 5, 6, 7] && isToken then [| try $(go leading) |] else [| $(go leading) |] where go (a:b:c:d:[]) = let !w = packBytes [a, b, c, d] in [| scan32# w |] go (a:b:c:d:ws) = let !w = packBytes [a, b, c, d] in [| scan32# w >> $(go ws) |] go (a:b:[]) = let !w = packBytes [a, b] in [| scan16# w |] go (a:b:ws) = let !w = packBytes [a, b] in [| scan16# w >> $(go ws) |] go (a:[]) = [| scan8# a |] go [] = [| pure () |] _ -> case leading of [] | w8sLen /= 1 && isToken -> [| try $scanw8s |] | otherwise -> [| $scanw8s |] [a] | isToken -> [| try (scan8# a >> $scanw8s) |] | otherwise -> [| scan8# a >> $scanw8s |] ws -> let !w = packBytes ws !l = length ws in if isToken then [| try (scanPartial64# l w >> $scanw8s) |] else [| scanPartial64# l w >> $scanw8s |] string :: String -> Q Exp string str = do let !bytes = strToBytes str !len = length bytes [| ensureBytes# len >> $(scanBytes# True bytes) |] char :: Char -> Q Exp char c = string [c] -- Word sets -------------------------------------------------------------------------------- data Trie a = Branch !Bool !a !(Map Word8 (Trie a)) deriving Show nilTrie :: Trie () nilTrie = Branch False () mempty insert :: [Word8] -> Trie () -> Trie () insert [] (Branch _ d ts) = Branch True d ts insert (c:cs) (Branch b d ts) = Branch b d (M.alter (Just . maybe (insert cs nilTrie) (insert cs)) c ts) fromList :: [String] -> Trie () fromList = foldl' (\t s -> insert (charToBytes =<< s) t) nilTrie mindepths :: Trie () -> Trie Int mindepths (Branch b _ ts) = if M.null ts then Branch b 0 mempty else let ts' = M.map mindepths ts in Branch b (minimum (M.map (\(Branch b d _) -> if b then 1 else d + 1) ts')) ts' data Trie' = Branch' !Bool !Int !(Map Word8 Trie') | Path !Bool !Int ![Word8] !Trie' deriving Show pathify :: Trie Int -> Trie' pathify (Branch b d ts) = case M.toList ts of [] -> Branch' b d mempty [(w, t)] -> case pathify t of Path False _ ws t -> Path b d (w:ws) t t -> Path b d [w] t _ -> Branch' b d (M.map pathify ts) genTrie :: Trie' -> Q Exp genTrie = go 0 where go :: Int -> Trie' -> Q Exp go !res (Branch' b d ts) | M.null ts = if res == 0 then (if b then [| eof |] else [| empty |]) else error "impossible" go res (Path True d ws t) = let l = length ws in if res < l then let !res' = d - res in [| eof <!> (ensureBytes# res' >> $(scanBytes# False ws) >> $(go (d-l) t)) |] else [| eof <!> ($(scanBytes# False ws) >> $(go (res - l) t)) |] go res (Path False d ws t) = let l = length ws in if res < l then let !res' = d - res in [| ensureBytes# res' >> $(scanBytes# False ws) >> $(go (d-l) t) |] else [| $(scanBytes# False ws) >> $(go (res - l) t) |] go res (Branch' True d ts) = if res < 1 then [| eof <!> (ensureBytes# d >> $(branch d ts)) |] else [| eof <!> $(branch res ts) |] go res (Branch' False d ts) = if res < 1 then [| ensureBytes# d >> $(branch d ts) |] else branch res ts branch :: Int -> Map Word8 Trie' -> Q Exp branch res ts = do next <- (traverse . traverse) (go (res - 1)) (M.toList ts) pure $ DoE [ BindS (VarP (mkName "c")) (VarE 'scanAny8#), NoBindS (CaseE (VarE (mkName "c")) (map (\(w, t) -> Match (LitP (IntegerL (fromIntegral w))) (NormalB t) []) next ++ [Match WildP (NormalB (VarE 'empty)) []])) ] wordSet :: [String] -> Q Exp wordSet = genTrie . pathify . mindepths . Old.FlatParseIndent.fromList -------------------------------------------------------------------------------- -- -- match :: Q Exp -> Q Exp -- -- match _ = [| () |]
null
https://raw.githubusercontent.com/AndrasKovacs/setoidtt/621aef2c4ae5a6acb418fa1153575b21e2dc48d2/setoidtt/flatparse/Old/FlatParseIndent.hs
haskell
------------------------------------------------------------------------------ # complete OK#, Err# # # inline (<$) # # inline empty # # inline pure # # inline (<*>) # # inline (<*) # # inline (*>) # # inline return # # inline (>>=) # # inline (>>) # # inline ask # # inline local # # inline derefChar8# # # inline isDigit # # inline isGreekLetter # # inline (<!>) # # inline (<|>) # | Reset the input position if the given parser fails. # inline try # # inline anyCharA # # inline anyCharA_ # | Parse any `Char`. Assumes that input is UTF8! | Skip any `Char`. # inline satisfy # # inline satisfyA # having consumed input. # inline many_ # # inline manyBr_ # # inline manyTok_ # | Skip a parser one or more times. This fails if the given parser fails with having consumed input. # inline some_ # # inline someBr_ # # inline someTok_ # if the closing parser fails with having consumed input. # inline silent # # inline (==) # # inline spanned # # inline spanToShortText # # inline asShortText # # unpack # | Retrieve line and column informations for a list of `Pos`-s. Throw an | Run a parser in a given span. The span behaves as the new beginning and end of the input buffer. The `Int` parameter is the current indentation level at the beginning of the spane. When the parser finishes, the original external state is restored. # inline inSpan # # inline get # # inline put # # inline modify # char and string ------------------------------------------------------------------------------ # inline scan32# # # inline scan64# # Word sets ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- match :: Q Exp -> Q Exp -- match _ = [| () |]
module Old.FlatParseIndent where import qualified Data.ByteString as B import qualified Data.ByteString.Short.Internal as SB import qualified Data.ByteString.Unsafe as B import qualified Data.Text.Short as T import qualified Data.Text.Short.Unsafe as T import qualified Data.Map.Strict as M import Data.Map (Map) import Data.Bits import Data.Char (ord) import Data.Foldable import Data.Word import GHC.Exts import GHC.Word import Language.Haskell.TH import System.IO.Unsafe data Error e = Default | Custom e deriving Show type Res# e a = (# (# a, Addr#, Int# #) | (# Error e, Addr# #) #) pattern OK# :: a -> Addr# -> Int# -> Res# e a pattern OK# a s j = (# (# a, s, j #) | #) pattern Err# :: Error e -> Addr# -> Res# e a pattern Err# e s = (# | (# e, s #) #) newtype Parser e a = Parser {runParser# :: Addr# -> Int# -> Addr# -> Int# -> Res# e a} instance Functor (Parser e) where fmap f (Parser g) = Parser \e i s j -> case g e i s j of OK# a s j -> let !b = f a in OK# b s j Err# e s -> Err# e s # inline fmap # (<$) a' (Parser g) = Parser \e i s j -> case g e i s j of OK# a s j -> OK# a' s j Err# e s -> Err# e s err :: e -> Parser e a err e = Parser \_ i s j -> Err# (Custom e) s # inline err # empty :: Parser e a empty = Parser \e i s j -> Err# Default s instance Applicative (Parser e) where pure a = Parser \e i s j -> OK# a s j Parser ff <*> Parser fa = Parser \e i s j -> case ff e i s j of Err# e s -> Err# e s OK# f s j -> case fa e i s j of Err# e s -> Err# e s OK# a s j -> OK# (f a) s j Parser fa <* Parser fb = Parser \e i s j -> case fa e i s j of Err# e s -> Err# e s OK# a s j -> case fb e i s j of Err# e s -> Err# e s OK# b s j -> OK# a s j Parser fa *> Parser fb = Parser \e i s j -> case fa e i s j of Err# e s -> Err# e s OK# a s j -> fb e i s j instance Monad (Parser e) where return = pure Parser fa >>= f = Parser \e i s j -> case fa e i s j of Err# e s -> Err# e s OK# a s j -> runParser# (f a) e i s j Parser fa >> Parser fb = Parser \e i s j -> case fa e i s j of Err# e s -> Err# e s OK# a s j -> fb e i s j ask :: Parser e Int ask = Parser \e i s j -> OK# (I# i) s j local :: (Int -> Int) -> Parser e a -> Parser e a local f (Parser fa) = Parser \e i s j -> case f (I# i) of I# i -> fa e i s j derefChar8# :: Addr# -> Char# derefChar8# addr = indexCharOffAddr# addr 0# eof :: Parser e () eof = Parser \e i s j -> case eqAddr# e s of 1# -> OK# () s j _ -> Err# Default s # inline eof # isDigit :: Char -> Bool isDigit c = '0' <= c && c <= '9' isLatinLetter :: Char -> Bool isLatinLetter c = ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') # inline isLatinLetter # isGreekLetter :: Char -> Bool isGreekLetter c = ('Α' <= c && c <= 'Ω') || ('α' <= c && c <= 'ω') | Choose between two parsers . The second parser is tried if the first one fails , regardless of how much input the first parser consumed . infixr 6 <!> (<!>) :: Parser e a -> Parser e a -> Parser e a (<!>) (Parser f) (Parser g) = Parser \e i s j -> case f e i s j of Err# _ _ -> g e i s j x -> x | Choose between two parsers . The second parser is only tried if the first one fails without having consumed input . infixr 6 <|> (<|>) :: Parser e a -> Parser e a -> Parser e a (<|>) (Parser f) (Parser g) = Parser \e i s j -> case f e i s j of Err# err s' -> case eqAddr# s s' of 1# -> g e i s j _ -> Err# err s' x -> x try :: Parser e a -> Parser e a try (Parser f) = Parser \e i s j -> case f e i s j of Err# err _ -> Err# err s x -> x | Parse any ` Char ` in the ASCII range . anyCharA :: Parser e Char anyCharA = Parser \e i s j -> case eqAddr# e s of 1# -> Err# Default s _ -> case derefChar8# s of c1 -> case c1 `leChar#` '\x7F'# of 1# -> OK# (C# c1) (plusAddr# s 1#) j _ -> Err# Default s | Skip any ` Char ` in the ASCII range . anyCharA_ :: Parser e () anyCharA_ = () <$ anyCharA anyChar :: Parser e Char anyChar = Parser \e i s j -> case eqAddr# e s of 1# -> Err# Default s _ -> case derefChar8# s of c1 -> case c1 `leChar#` '\x7F'# of 1# -> OK# (C# c1) (plusAddr# s 1#) j _ -> case eqAddr# e (plusAddr# s 1#) of 1# -> Err# Default s _ -> case indexCharOffAddr# s 1# of c2 -> case c1 `leChar#` '\xDF'# of 1# -> let resc = ((ord# c1 -# 0xC0#) `uncheckedIShiftL#` 6#) `orI#` (ord# c2 -# 0x80#) in OK# (C# (chr# resc)) (plusAddr# s 2#) j _ -> case eqAddr# e (plusAddr# s 2#) of 1# -> Err# Default s _ -> case indexCharOffAddr# s 2# of c3 -> case c1 `leChar#` '\xEF'# of 1# -> let resc = ((ord# c1 -# 0xE0#) `uncheckedIShiftL#` 12#) `orI#` ((ord# c2 -# 0x80#) `uncheckedIShiftL#` 6#) `orI#` (ord# c3 -# 0x80#) in OK# (C# (chr# resc)) (plusAddr# s 3#) j _ -> case eqAddr# e (plusAddr# s 3#) of 1# -> Err# Default s _ -> case indexCharOffAddr# s 3# of c4 -> let resc = ((ord# c1 -# 0xF0#) `uncheckedIShiftL#` 18#) `orI#` ((ord# c2 -# 0x80#) `uncheckedIShiftL#` 12#) `orI#` ((ord# c3 -# 0x80#) `uncheckedIShiftL#` 6#) `orI#` (ord# c4 -# 0x80#) in OK# (C# (chr# resc)) (plusAddr# s 4#) j # inline anyChar # anyChar_ :: Parser e () anyChar_ = Parser \e i s j -> case eqAddr# e s of 1# -> Err# Default s _ -> case derefChar8# s of c1 -> case c1 `leChar#` '\x7F'# of 1# -> OK# () (plusAddr# s 1#) j _ -> let s' = case c1 `leChar#` '\xDF'# of 1# -> plusAddr# s 2# _ -> case c1 `leChar#` '\xEF'# of 1# -> plusAddr# s 3# _ -> plusAddr# s 4# in case leAddr# s' e of 1# -> OK# () s' j _ -> Err# Default s # inline anyChar _ # | Parser a ` Char ` for which a predicate holds . satisfy :: (Char -> Bool) -> Parser e Char satisfy f = Parser \e i s j -> case runParser# anyChar e i s j of OK# c s j | f c -> OK# c s j OK# c _ _ -> Err# Default s Err# e s -> Err# e s | Parse an ASCII ` Char ` for which a predicate holds . satisfyA :: (Char -> Bool) -> Parser e Char satisfyA f = Parser \e i s j -> case runParser# anyCharA e i s j of OK# c s j | f c -> OK# c s j OK# c _ _ -> Err# Default s Err# e s -> Err# e s | Skip a parser zero or more times . This fails if the given parser fails with many_ :: Parser e a -> Parser e () many_ (Parser f) = go where go = Parser \e i s j -> case f e i s j of Err# e s' -> case eqAddr# s s' of 1# -> OK# () s j _ -> Err# e s' OK# a s j -> runParser# go e i s j manyBr_ :: Parser e a -> Parser e b -> Parser e () manyBr_ pa pb = go where go = br pa (pb >> go) (pure ()) manyTok_ :: Parser e a -> Parser e () manyTok_ (Parser f) = go where go = Parser \e i s j -> case f e i s j of Err# _ _ -> OK# () s j OK# a s j -> runParser# go e i s j some_ :: Parser e a -> Parser e () some_ pa = pa >> many_ pa someBr_ :: Parser e a -> Parser e b -> Parser e () someBr_ pa pb = pa >> pb >> manyBr_ pa pb someTok_ :: Parser e a -> Parser e () someTok_ pa = pa >> manyTok_ pa | Skip a parser zero or more times until a closing parser . This fails manyTill_ :: Parser e a -> Parser e b -> Parser e () manyTill_ pa end = go where go = (() <$ end) <|> (pa >> go) # inline manyTill _ # chainl :: (b -> a -> b) -> Parser e b -> Parser e a -> Parser e b chainl f start elem = start >>= go where go b = do {!a <- elem; go $! f b a} <|> pure b # inline chainl # chainr :: (a -> b -> b) -> Parser e a -> Parser e b -> Parser e b chainr f elem end = go where go = (f <$> elem <*> go) <|> end # inline chainr # silent :: Parser e a -> Parser e a silent pa = Parser \e i s j -> case runParser# pa e i s j of Err# e s -> Err# Default s x -> x data Pos = Pos Addr# instance Eq Pos where Pos p == Pos p' = isTrue# (eqAddr# p p') data Span = Span !Pos !Pos deriving Eq spanned :: Parser e a -> Parser e (a, Span) spanned (Parser f) = Parser \e i s j -> case f e i s j of Err# e s -> Err# e s OK# a s' j' -> OK# (a, Span (Pos s) (Pos s')) s' j' spanToShortText :: Span -> T.ShortText spanToShortText (Span (Pos start) (Pos end)) = let len = minusAddr# end start in T.fromShortByteStringUnsafe (SB.SBS (runRW# \s -> case newByteArray# len s of (# s, marr #) -> case copyAddrToByteArray# start marr 0# len s of s -> case unsafeFreezeByteArray# marr s of (# s, arr #) -> arr)) asShortText :: Parser e a -> Parser e (T.ShortText) asShortText p = fmap (\(_ ,s) -> spanToShortText s) (spanned p) getPos :: Parser e Pos getPos = Parser \e i s j -> OK# (Pos s) s j # inline getPos # setPos :: Pos -> Parser e () setPos (Pos s) = Parser \e i _ j -> OK# () s j # inline setPos # data PosInfo = PosInfo { _lineNum :: !Int, _colNum :: !Int, } deriving Show error if any of the positions does not point into the ` ByteString ` . posInfo :: B.ByteString -> [Pos] -> [PosInfo] posInfo = error "TODO" inSpan :: Int -> Span -> Parser e a -> Parser e a inSpan (I# j) (Span (Pos start) (Pos end)) (Parser f) = Parser \e' i s' j' -> case f end i start j of OK# a _ _ -> OK# a s' j' Err# err _ -> Err# err s' data Result e a = OK a B.ByteString | Err (Error e) B.ByteString deriving Show runParser :: Parser e a -> B.ByteString -> Result e a runParser (Parser f) b = unsafeDupablePerformIO do B.unsafeUseAsCString b \(Ptr buf) -> do let !(I# len) = B.length b let end = plusAddr# buf len case f end 0# buf 0# of Err# e s -> do let offset = minusAddr# s buf pure (Err e (B.drop (I# offset) b)) OK# a s j -> do let offset = minusAddr# s buf pure (OK a (B.drop (I# offset) b)) testParser :: Parser e a -> String -> Result e a testParser pa s = runParser pa (B.pack (concatMap charToBytes s)) br :: Parser e a -> Parser e b -> Parser e b -> Parser e b br pa pt pf = Parser \e i s j -> case runParser# pa e i s j of OK# _ s j -> runParser# pt e i s j Err# _ _ -> runParser# pf e i s j # inline br # get :: Parser e Int get = Parser \e i s j -> OK# (I# j) s j put :: Int -> Parser e () put (I# j) = Parser \e i s _ -> OK# () s j modify :: (Int -> Int) -> Parser e () modify f = Parser \e i s j -> case f (I# j) of I# j -> OK# () s j charToBytes :: Char -> [Word8] charToBytes c' | c <= 0x7f = [fromIntegral c] | c <= 0x7ff = [0xc0 .|. y, 0x80 .|. z] | c <= 0xffff = [0xe0 .|. x, 0x80 .|. y, 0x80 .|. z] | c <= 0x10ffff = [0xf0 .|. w, 0x80 .|. x, 0x80 .|. y, 0x80 .|. z] | otherwise = error "Not a valid Unicode code point" where c = ord c' z = fromIntegral (c .&. 0x3f) y = fromIntegral (unsafeShiftR c 6 .&. 0x3f) x = fromIntegral (unsafeShiftR c 12 .&. 0x3f) w = fromIntegral (unsafeShiftR c 18 .&. 0x7) strToBytes :: String -> [Word8] strToBytes = concatMap charToBytes # inline strToBytes # packBytes :: [Word8] -> Word packBytes = fst . foldl' go (0, 0) where go (acc, shift) w | shift == 64 = error "packWords: too many bytes" go (acc, shift) w = (unsafeShiftL (fromIntegral w) shift .|. acc, shift+8) splitBytes :: [Word8] -> ([Word8], [Word]) splitBytes ws = case quotRem (length ws) 8 of (0, _) -> (ws, []) (_, r) -> (as, chunk8s bs) where (as, bs) = splitAt r ws chunk8s [] = [] chunk8s ws = let (as, bs) = splitAt 8 ws in packBytes as : chunk8s bs scanAny8# :: Parser e Word8 scanAny8# = Parser \e i s j -> OK# (W8# (indexWord8OffAddr# s 0#)) (plusAddr# s 1#) j # inline scanAny8 # # scan8# :: Word -> Parser e () scan8# (W# c) = Parser \e i s j -> case indexWord8OffAddr# s 0# of c' -> case eqWord# c c' of 1# -> OK# () (plusAddr# s 1#) j _ -> Err# Default s # inline scan8 # # scan16# :: Word -> Parser e () scan16# (W# c) = Parser \e i s j -> case indexWord16OffAddr# s 0# of c' -> case eqWord# c c' of 1# -> OK# () (plusAddr# s 2#) j _ -> Err# Default s # inline scan16 # # scan32# :: Word -> Parser e () scan32# (W# c) = Parser \e i s j -> case indexWord32OffAddr# s 0# of c' -> case eqWord# c c' of 1# -> OK# () (plusAddr# s 4#) j _ -> Err# Default s scan64# :: Word -> Parser e () scan64# (W# c) = Parser \e i s j -> case indexWord64OffAddr# s 0# of c' -> case eqWord# c c' of 1# -> OK# () (plusAddr# s 8#) j _ -> Err# Default s scanPartial64# :: Int -> Word -> Parser e () scanPartial64# (I# len) (W# w) = Parser \e i s j -> case indexWordOffAddr# s 0# of w' -> case uncheckedIShiftL# (8# -# len) 3# of sh -> case uncheckedShiftL# w' sh of w' -> case uncheckedShiftRL# w' sh of w' -> case eqWord# w w' of 1# -> OK# () (plusAddr# s len) j _ -> Err# Default s # inline scanPartial64 # # ensureBytes# :: Int -> Parser e () ensureBytes# (I# len) = Parser \e i s j -> case len <=# minusAddr# e s of 1# -> OK# () s j _ -> Err# Default s # inline ensureBytes # # scanBytes# :: Bool -> [Word8] -> Q Exp scanBytes# isToken bytes = do let !(leading, w8s) = splitBytes bytes !leadingLen = length leading !w8sLen = length w8s !scanw8s = go w8s where go (w8:[] ) = [| scan64# w8 |] go (w8:w8s) = [| scan64# w8 >> $(go w8s) |] go [] = [| pure () |] case w8s of [] -> if elem leadingLen [3, 5, 6, 7] && isToken then [| try $(go leading) |] else [| $(go leading) |] where go (a:b:c:d:[]) = let !w = packBytes [a, b, c, d] in [| scan32# w |] go (a:b:c:d:ws) = let !w = packBytes [a, b, c, d] in [| scan32# w >> $(go ws) |] go (a:b:[]) = let !w = packBytes [a, b] in [| scan16# w |] go (a:b:ws) = let !w = packBytes [a, b] in [| scan16# w >> $(go ws) |] go (a:[]) = [| scan8# a |] go [] = [| pure () |] _ -> case leading of [] | w8sLen /= 1 && isToken -> [| try $scanw8s |] | otherwise -> [| $scanw8s |] [a] | isToken -> [| try (scan8# a >> $scanw8s) |] | otherwise -> [| scan8# a >> $scanw8s |] ws -> let !w = packBytes ws !l = length ws in if isToken then [| try (scanPartial64# l w >> $scanw8s) |] else [| scanPartial64# l w >> $scanw8s |] string :: String -> Q Exp string str = do let !bytes = strToBytes str !len = length bytes [| ensureBytes# len >> $(scanBytes# True bytes) |] char :: Char -> Q Exp char c = string [c] data Trie a = Branch !Bool !a !(Map Word8 (Trie a)) deriving Show nilTrie :: Trie () nilTrie = Branch False () mempty insert :: [Word8] -> Trie () -> Trie () insert [] (Branch _ d ts) = Branch True d ts insert (c:cs) (Branch b d ts) = Branch b d (M.alter (Just . maybe (insert cs nilTrie) (insert cs)) c ts) fromList :: [String] -> Trie () fromList = foldl' (\t s -> insert (charToBytes =<< s) t) nilTrie mindepths :: Trie () -> Trie Int mindepths (Branch b _ ts) = if M.null ts then Branch b 0 mempty else let ts' = M.map mindepths ts in Branch b (minimum (M.map (\(Branch b d _) -> if b then 1 else d + 1) ts')) ts' data Trie' = Branch' !Bool !Int !(Map Word8 Trie') | Path !Bool !Int ![Word8] !Trie' deriving Show pathify :: Trie Int -> Trie' pathify (Branch b d ts) = case M.toList ts of [] -> Branch' b d mempty [(w, t)] -> case pathify t of Path False _ ws t -> Path b d (w:ws) t t -> Path b d [w] t _ -> Branch' b d (M.map pathify ts) genTrie :: Trie' -> Q Exp genTrie = go 0 where go :: Int -> Trie' -> Q Exp go !res (Branch' b d ts) | M.null ts = if res == 0 then (if b then [| eof |] else [| empty |]) else error "impossible" go res (Path True d ws t) = let l = length ws in if res < l then let !res' = d - res in [| eof <!> (ensureBytes# res' >> $(scanBytes# False ws) >> $(go (d-l) t)) |] else [| eof <!> ($(scanBytes# False ws) >> $(go (res - l) t)) |] go res (Path False d ws t) = let l = length ws in if res < l then let !res' = d - res in [| ensureBytes# res' >> $(scanBytes# False ws) >> $(go (d-l) t) |] else [| $(scanBytes# False ws) >> $(go (res - l) t) |] go res (Branch' True d ts) = if res < 1 then [| eof <!> (ensureBytes# d >> $(branch d ts)) |] else [| eof <!> $(branch res ts) |] go res (Branch' False d ts) = if res < 1 then [| ensureBytes# d >> $(branch d ts) |] else branch res ts branch :: Int -> Map Word8 Trie' -> Q Exp branch res ts = do next <- (traverse . traverse) (go (res - 1)) (M.toList ts) pure $ DoE [ BindS (VarP (mkName "c")) (VarE 'scanAny8#), NoBindS (CaseE (VarE (mkName "c")) (map (\(w, t) -> Match (LitP (IntegerL (fromIntegral w))) (NormalB t) []) next ++ [Match WildP (NormalB (VarE 'empty)) []])) ] wordSet :: [String] -> Q Exp wordSet = genTrie . pathify . mindepths . Old.FlatParseIndent.fromList
c345361c4c0da5b60d93e136f72c318f636ffe3d02b1ba794b2c3ce2e9a45e95
elastic/runbld
fs.clj
(ns runbld.fs) (defprotocol FileSystem (fs-mountpoint [_] "/dev/md0") (fs-type [_] "xfs") (fs-bytes-total [_]) (fs-bytes-used [_]) (fs-bytes-free [_]) (fs-percent-used [_]) (fs-percent-free [_]) )
null
https://raw.githubusercontent.com/elastic/runbld/7afcb1d95a464dc068f95abf3ad8a7566202ce28/src/clj/runbld/fs.clj
clojure
(ns runbld.fs) (defprotocol FileSystem (fs-mountpoint [_] "/dev/md0") (fs-type [_] "xfs") (fs-bytes-total [_]) (fs-bytes-used [_]) (fs-bytes-free [_]) (fs-percent-used [_]) (fs-percent-free [_]) )
d430b3f4e60c047037247271d4ec66f95a61c4d532d705533203c80d21df3a59
greglook/solanum
tcp.clj
(ns solanum.source.tcp "Metrics source that checks the availability of a local TCP port." (:require [solanum.source.core :as source]) (:import (java.net InetSocketAddress Socket SocketTimeoutException))) # # Measurements (defn- test-port "Test a TCP port by connecting to it. Returns a vector with a state and description." [host port timeout] (let [address (InetSocketAddress. (str host) (long port)) socket (Socket.)] (try (.connect socket address (long timeout)) [:ok (format "TCP port %d is open on %s" port host)] (catch SocketTimeoutException _ [:critical (format "Timed out connecting to TCP port %d on %s" port host)]) (catch Exception ex [:critical (format "Error connecting to TCP port %d on %s\n%s: %s" port host (.getName (class ex)) (ex-message ex))]) (finally (.close socket))))) # # TCP Source (defrecord TCPSource [label host port] source/Source (collect-events [_] (let [[state desc] (test-port host port 1000)] [{:service "tcp socket open" :port (str (or label port)) :metric (if (= :ok state) 1 0) :state state :description desc}]))) (defmethod source/initialize :tcp [config] (when-not (:port config) (throw (IllegalArgumentException. "Cannot initialize TCP source without a port"))) (map->TCPSource {:label (:label config) :host (:host config "localhost") :port (int (:port config))}))
null
https://raw.githubusercontent.com/greglook/solanum/5b0fed6cc897e691bb93aeb5d4bfea892b425d54/src/solanum/source/tcp.clj
clojure
(ns solanum.source.tcp "Metrics source that checks the availability of a local TCP port." (:require [solanum.source.core :as source]) (:import (java.net InetSocketAddress Socket SocketTimeoutException))) # # Measurements (defn- test-port "Test a TCP port by connecting to it. Returns a vector with a state and description." [host port timeout] (let [address (InetSocketAddress. (str host) (long port)) socket (Socket.)] (try (.connect socket address (long timeout)) [:ok (format "TCP port %d is open on %s" port host)] (catch SocketTimeoutException _ [:critical (format "Timed out connecting to TCP port %d on %s" port host)]) (catch Exception ex [:critical (format "Error connecting to TCP port %d on %s\n%s: %s" port host (.getName (class ex)) (ex-message ex))]) (finally (.close socket))))) # # TCP Source (defrecord TCPSource [label host port] source/Source (collect-events [_] (let [[state desc] (test-port host port 1000)] [{:service "tcp socket open" :port (str (or label port)) :metric (if (= :ok state) 1 0) :state state :description desc}]))) (defmethod source/initialize :tcp [config] (when-not (:port config) (throw (IllegalArgumentException. "Cannot initialize TCP source without a port"))) (map->TCPSource {:label (:label config) :host (:host config "localhost") :port (int (:port config))}))
3b27dbb20feec3993bfe25c22a8c317331f0f1baa283471c6fe17e014d807faa
qiuxiafei/zk-web
zk.clj
(ns zk-web.zk (:import [com.netflix.curator.retry RetryNTimes] [com.netflix.curator.framework CuratorFramework CuratorFrameworkFactory]) (:require [clj-time.format :as time-format] [clj-time.coerce :as time-coerce]) (:refer-clojure :exclude [set get]) (:use zk-web.util)) (defn- mk-zk-cli-inner "Create a zk client using addr as connecting string" [ addr ] (let [cli (-> (CuratorFrameworkFactory/builder) (.connectString addr) (.retryPolicy (RetryNTimes. (int 3) (int 1000))) (.build)) _ (.start cli)] cli)) ;; memorize this function to save net connection (def mk-zk-cli (memoize mk-zk-cli-inner)) (defn create "Create a node in zk with a client" ([cli path data] (-> cli (.create) (.creatingParentsIfNeeded) (.forPath path data))) ([cli path] (-> cli (.create) (.creatingParentsIfNeeded) (.forPath path)))) (defn rm "Delete a node in zk with a client" [cli path] (-> cli (.delete) (.forPath path))) (defn ls "List children of a node" [cli path] (-> cli (.getChildren) (.forPath path))) (defn stat "Get stat of a node, return nil if no such node" [cli path] (letfn [(pretty-time [t] (let [date-time (time-coerce/from-long t)] (time-format/unparse (time-format/formatters :date-hour-minute-second) date-time)))] (let [node-data (-> cli (.checkExists) (.forPath path) bean) ctime-pretty (pretty-time (clojure.core/get node-data :ctime 0)) mtime-pretty (pretty-time (clojure.core/get node-data :mtime 0)) modified-node-data (assoc (dissoc node-data :class) :ctime-pretty ctime-pretty :mtime-pretty mtime-pretty)] (sort-by first (seq modified-node-data))))) (defn set "Set data to a node" [cli path data] (-> cli (.setData) (.forPath path data))) (defn get "Get data from a node" [cli path] (-> cli (.getData) (.forPath path))) (defn rmr "Remove recursively" [cli path] (println "rmr " path) (doseq [child (ls cli path)] (rmr cli (child-path path child))) (rm cli path))
null
https://raw.githubusercontent.com/qiuxiafei/zk-web/30399b0a6f540d5d45970cc14b897814912a6f0c/src/zk_web/zk.clj
clojure
memorize this function to save net connection
(ns zk-web.zk (:import [com.netflix.curator.retry RetryNTimes] [com.netflix.curator.framework CuratorFramework CuratorFrameworkFactory]) (:require [clj-time.format :as time-format] [clj-time.coerce :as time-coerce]) (:refer-clojure :exclude [set get]) (:use zk-web.util)) (defn- mk-zk-cli-inner "Create a zk client using addr as connecting string" [ addr ] (let [cli (-> (CuratorFrameworkFactory/builder) (.connectString addr) (.retryPolicy (RetryNTimes. (int 3) (int 1000))) (.build)) _ (.start cli)] cli)) (def mk-zk-cli (memoize mk-zk-cli-inner)) (defn create "Create a node in zk with a client" ([cli path data] (-> cli (.create) (.creatingParentsIfNeeded) (.forPath path data))) ([cli path] (-> cli (.create) (.creatingParentsIfNeeded) (.forPath path)))) (defn rm "Delete a node in zk with a client" [cli path] (-> cli (.delete) (.forPath path))) (defn ls "List children of a node" [cli path] (-> cli (.getChildren) (.forPath path))) (defn stat "Get stat of a node, return nil if no such node" [cli path] (letfn [(pretty-time [t] (let [date-time (time-coerce/from-long t)] (time-format/unparse (time-format/formatters :date-hour-minute-second) date-time)))] (let [node-data (-> cli (.checkExists) (.forPath path) bean) ctime-pretty (pretty-time (clojure.core/get node-data :ctime 0)) mtime-pretty (pretty-time (clojure.core/get node-data :mtime 0)) modified-node-data (assoc (dissoc node-data :class) :ctime-pretty ctime-pretty :mtime-pretty mtime-pretty)] (sort-by first (seq modified-node-data))))) (defn set "Set data to a node" [cli path data] (-> cli (.setData) (.forPath path data))) (defn get "Get data from a node" [cli path] (-> cli (.getData) (.forPath path))) (defn rmr "Remove recursively" [cli path] (println "rmr " path) (doseq [child (ls cli path)] (rmr cli (child-path path child))) (rm cli path))
7b3ae3d753128af090752f6fa5dbb5edfada82c451e8baaa6a789749eb06ace5
dmbarbour/awelon
Main.hs
# LANGUAGE PatternGuards , ViewPatterns , OverloadedStrings # -- | The `ao` command line executable, with many utilities for -- non-interactive programming. module Main ( main ) where import Control.Applicative import Control.Monad import Data.Monoid import Data.Ratio import qualified Data.Map as M import qualified Data.Text as T import qualified Data.List as L import qualified Data.Sequence as S import qualified Data.ByteString.Builder as BB import qualified Data.ByteString.Lazy as LBS import qualified Data.Set as Set import qualified Data.IORef as IORef import qualified System.IO as Sys import System . ( unsafeInterleaveIO ) import qualified System.Exit as Sys import qualified System.Environment as Env import qualified Text.Parsec as P import qualified Data.Decimal as Decimal import ABC.Simplify (simplify) import ABC.Operators import ABC.Resource import ABC.Imperative.Value import ABC.Imperative.Interpreter import ABC.Quote import AO.Dict import AO.Code import AO.AOFile import AO.Parser import AO.Compile import AORT import Util helpMsg :: String helpMsg = "The `ao` executable provides many utilities for non-interactive\n\ \operations involving AO or ABC code. Usage:\n\ \\n\ \ ao help print this message \n\ \ \n\ \ ao test run all `test.` words in test environment \n\ \ \n\ \ ao abc command dump simplified ABC for AO command \n\ \ ao abc.raw command dump raw ABC for AO command \n\ \ ao abc.ann command dump annotated ABC for AO command \n\ \ ao exec command execute AO command \n\ \ ao exec.abc command execute ABC code \n\ \ \n\ \ ao abc.s dump simplified ABC for AO on input stream \n\ \ ao abc.raw.s dump raw ABC for AO on input stream \n\ \ ao abc.ann.s dump annotated ABC for AO on input stream \n\ \ ao exec.s execute AO commands from input stream \n\ \ ao exec.abc.s execute ABC from input stream \n\ \ \n\ \ ao rsc rscTok dump ABC for ABC resource invocation {#rscTok} \n\ \ \n\ \ ao list pattern list words matching pattern (e.g. test.*) \n\ \ ao defs pattern find definitions of words matching pattern \n\ \ ao uses pattern find uses of words matching pattern \n\ \ ao def word print full accepted definition of word \n\ \ \n\ \ (Experimental Modes) \n\ \ \n\ \ ao ss command pure octet stream transform (stdin -- stdout) \n\ \ ao aodict dump '.ao' export file for Wikilon\n\ \\n\ \All 'exec' operations use the same powers and environment as `aoi`. \n\ \Streams process stdin to stdout, one AO or ABC paragraph at a time. \n\ \\n\ \Environment Variables: \n\ \ AO_PATH: where to search for '.ao' files \n\ \ AO_DICT: root dictionary text; default \"ao\" \n\ \ AO_TEMP: directory for temporaries; default \"aotmp\" \n\ \" \ \n\ \ ( JIT inoperative at moment ) \n\ \ ao jit command print haskell code for imperative JIT \n\ \ ao test.jit run all ` test . ` words using JIT \n\ \ \n\ \ (JIT inoperative at moment) \n\ \ ao jit command print haskell code for imperative JIT \n\ \ ao test.jit run all `test.` words using JIT \n\ -} -- todo: typechecking! -- when persistence is working, perhaps add an AO_HOME or similar. main :: IO () main = Env.getArgs >>= runMode type Dict = AODict AOFMeta data CMode = CMode { cm_simplify :: [Op] -> [Op] , cm_annotate :: Dict -> Dict } modeSimp, modeRaw, modeAnn :: CMode modeSimp = CMode simplify id modeRaw = CMode id id modeAnn = CMode id annoDict -- very simple command line processing runMode :: [String] -> IO () runMode ["help"] = Sys.putStrLn helpMsg runMode ["abc",cmd] = mkCmdS cmd >>= dumpABC modeSimp runMode ["abc.raw",cmd] = mkCmdS cmd >>= dumpABC modeRaw runMode ["abc.ann",cmd] = mkCmdS cmd >>= dumpABC modeAnn runMode ["exec",cmd] = mkCmdS cmd >>= execAO runMode ["exec.abc",cmd] = mkCmdS cmd >>= execABC runMode ["abc.s"] = stdCmdS >>= dumpABC modeSimp runMode ["abc.raw.s"] = stdCmdS >>= dumpABC modeRaw runMode ["abc.ann.s"] = stdCmdS >>= dumpABC modeAnn runMode ["exec.s"] = stdCmdS >>= execAO runMode ["exec.abc.s"] = stdCmdS >>= execABC runMode ["ss",cmd] = execSS cmd runMode ["rsc",rsc] = printResource rsc --runMode ["jit",cmd] = printImperativeJIT cmd runMode ["list",ptrn] = listWords ptrn runMode ["uses",ptrn] = listUses ptrn runMode ["defs",ptrn] = listDefs ptrn runMode ["def",word] = printDef word runMode ["test"] = runAOTests (return . interpret . simplify) runMode ["aodict"] = dumpAODict --runMode ["test.jit"] = runAOTests (abc_jit . simplify) runMode _ = putErrLn eMsg >> Sys.exitFailure where eMsg = "arguments not recognized; try `ao help`" -- extract paragraphs from command string mkCmdS :: String -> IO [String] mkCmdS s = Sys.hClose Sys.stdin >> return (paragraphs s) lazily obtain paragraphs from stdin -- (I kind of hate lazy IO, but it's convenient here) stdCmdS :: IO [String] stdCmdS = paragraphs <$> Sys.hGetContents Sys.stdin getAO_DICT :: IO String getAO_DICT = maybe "ao" id <$> tryJust (Env.getEnv "AO_DICT") -- obtain a list of paragraphs. Each paragraph is recognized by two or more sequential ' \n ' characters . paragraphs :: String -> [String] paragraphs = pp0 where pp0 ('\n':ss) = pp0 ss pp0 (c:ss) = pp1 [c] ss pp0 [] = [] pp1 ('\n':p) ('\n':ss) = L.reverse p : pp0 ss pp1 p (c:ss) = pp1 (c:p) ss pp1 p [] = L.reverse p : [] -- getDict will always succeed, but might return an empty -- dictionary... and might complain a lot on stderr getDict :: IO Dict getDict = getAO_DICT >>= flip loadAODict putErrLn putErrLn :: String -> IO () putErrLn = Sys.hPutStrLn Sys.stderr dump ABC code , paragraph at a time , to standard output dumpABC :: CMode -> [String] -> IO () dumpABC mode ss = (cm_annotate mode <$> getDict) >>= \ d -> let nss = L.zip [1..] ss in mapM_ (uncurry (dumpABC' d mode)) nss dumpABC' :: AODict md -> CMode -> Int -> String -> IO () dumpABC' dict mode nPara aoStr = when (nPara > 1) (Sys.putChar '\n') >> compilePara dict nPara aoStr >>= \ ops -> Sys.putStr (show (cm_simplify mode ops)) >> Sys.putChar '\n' >> Sys.hFlush Sys.stdout compilePara :: AODict md -> Int -> String -> IO [Op] compilePara dict nPara aoStr = case compileAOString dict aoStr of Left err -> putErrLn ("paragraph " ++ show nPara) >> putErrLn err >> Sys.exitFailure Right ops -> return ops compileAOString :: AODict md -> String -> Either String [Op] compileAOString dict aoString = case P.parse parseAO "" aoString of Left err -> Left $ show err Right ao -> case compileAOtoABC dict ao of Left mw -> Left $ undefinedWordsMsg mw Right abc -> Right abc undefinedWordsMsg :: [Word] -> String undefinedWordsMsg mw = "undefined words: " ++ mwStr where mwStr = L.unwords $ fmap T.unpack mw annoDict :: Dict -> Dict annoDict = unsafeUpdateAODict (M.mapWithKey annoLoc) where showsLoc w aofm = showString (T.unpack w) . showChar '@' . showString (T.unpack (aofm_import aofm)) . showChar ':' . shows (aofm_line aofm) annoLoc w (c,aofm) = let loc = showsLoc w aofm [] in let entryTok = "&+" ++ loc in let exitTok = "&-" ++ loc in let c' = AO_Tok entryTok : (c ++ [AO_Tok exitTok]) in (c',aofm) execAO :: [String] -> IO () execAO ss = getDict >>= \ d -> let compile (n,s) = simplify <$> compilePara d n s in execOps $ fmap compile $ L.zip [1..] ss execute ABC in its raw form . execABC :: [String] -> IO () execABC = execOps . fmap (return . simplify . read) type CX = AORT_CX type RtVal = V AORT execOps :: [IO [Op]] -> IO () execOps ppOps = newDefaultRuntime >>= \ cx -> runRT cx newDefaultEnvironment >>= \ v0 -> void (execOps' cx v0 ppOps) -- the toplevel will simply interpret operations -- (leave JIT for inner loops!) execOps' :: CX -> RtVal -> [IO [Op]] -> IO RtVal execOps' _ v [] = return v execOps' cx v (readPara:more) = readPara >>= \ ops -> let prog = interpret ops in runRT cx (prog v) >>= \ v' -> execOps' cx v' more pure stream transformer process model ( stdin -- stdout ) execSS :: String -> IO () execSS aoCmd = getDict >>= \ d -> case compileAOString d aoCmd of Left err -> putErrLn err >> Sys.exitFailure Right ops -> Sys.hSetBinaryMode Sys.stdin True >> Sys.hSetBinaryMode Sys.stdout True >> Sys.hSetBuffering Sys.stdout Sys.NoBuffering >> newDefaultRuntime >>= \ cx -> runRT cx $ newDefaultEnvironment >>= \ (P stack env) -> interpret ops (P (P stdIn stack) env) >>= \ (P (P (B bStdOut) _) _) -> writeSS (b_prog bStdOut) stdIn modeled as a simple affine stream stdIn :: RtVal stdIn = B b where b = Block { b_aff = True, b_rel = False, b_code = code, b_prog = prog } code = S.singleton (Tok "stdin") -- visible via {&debug print raw} prog U = liftIO $ Sys.hIsEOF Sys.stdin >>= \ bEOF -> if bEOF then return (R U) else Sys.hGetChar Sys.stdin >>= \ c8 -> let n = (N . fromIntegral . fromEnum) c8 in return (L (P n stdIn)) prog v = fail $ show v ++ " @ {stdin} (unexpected input)" writeSS :: Prog AORT -> AORT () writeSS getC = getC U >>= \ mbC -> -- get a character (maybe) case mbC of (L (P (N n) (B b))) | isOctet n -> let c8 = (toEnum . fromIntegral . numerator) n in liftIO (Sys.hPutChar Sys.stdout c8) >> -- write character to stdout writeSS (b_prog b) -- repeat on next character (R U) -> return () v -> fail $ "illegal output from stdout stream: " ++ show v isOctet :: Rational -> Bool isOctet r = (1 == d) && (0 <= n) && (n < 256) where d = denominator r n = numerator r -- pattern with simple wildcards. -- may escape '*' using '\*' type Pattern = String matchStr :: Pattern -> String -> Bool matchStr ('*':[]) _ = True matchStr pp@('*':pp') ss@(_:ss') = matchStr pp' ss || matchStr pp ss' matchStr ('\\':'*':pp) (c:ss) = (c == '*') && matchStr pp ss matchStr (c:pp) (c':ss) = (c == c') && (matchStr pp ss) matchStr pp ss = null pp && null ss -- List words starting with a given regular expression. listWords :: String -> IO () listWords pattern = (fmap T.unpack . M.keys . readAODict) <$> getDict >>= \ allWords -> let matchingWords = L.filter (matchStr pattern) allWords in mapM_ Sys.putStrLn matchingWords getDictFiles :: IO [AOFile] getDictFiles = getAO_DICT >>= \ root -> loadAOFiles root putErrLn -- find all uses of a given word (modulo entries that fail to compile) listUses :: Pattern -> IO () listUses ptrn = getDictFiles >>= mapM_ (fileUses ptrn) fileUses :: Pattern -> AOFile -> IO () fileUses p file = let defs = L.filter (codeUsesWord p . fst . snd) (aof_defs file) in if null defs then return () else Sys.putStrLn (show (aof_path file)) >> mapM_ (Sys.putStrLn . (" " ++) . defSummary) defs codeUsesWord :: Pattern -> AO_Code -> Bool codeUsesWord = L.any . actionUsesWord actionUsesWord :: Pattern -> AO_Action -> Bool actionUsesWord p (AO_Word w) = (matchStr p (T.unpack w)) actionUsesWord p (AO_Block code) = codeUsesWord p code actionUsesWord _ _ = False defSummary :: AODef Int -> String defSummary (defWord,(code,line)) = showsSummary [] where showsSummary = shows line . showChar ' ' . showChar '@' . showsCode (AO_Word defWord : code) showsCode = shows . fmap cutBigText cutBigText (AO_Text txt) | isBigText txt = AO_Word (T.pack "(TEXT)") cutBigText (AO_Block ops) = AO_Block (fmap cutBigText ops) cutBigText op = op isBigText txt = (L.length txt > 14) || (L.any isMC txt) isMC c = ('"' == c) || ('\n' == c) listDefs :: Pattern -> IO () listDefs ptrn = getDictFiles >>= mapM_ (fileDefines ptrn) fileDefines :: Pattern -> AOFile -> IO () fileDefines p file = let defs = L.filter (matchStr p . T.unpack . fst) (aof_defs file) in if null defs then return () else Sys.putStrLn (show (aof_path file)) >> mapM_ (Sys.putStrLn . (" " ++) . defSummary) defs printDef :: String -> IO () printDef word = getDict >>= \ d -> case M.lookup (T.pack word) (readAODict d) of Nothing -> putErrLn "undefined" >> Sys.exitFailure Just (def,_) -> Sys.putStrLn (show def) runAOTests :: ([Op] -> IO (Prog AORT)) -> IO () runAOTests compile = getDict >>= \ d -> mapM (runTest compile d) (testWords d) >>= \ lSummary -> let nPass = length $ filter (==PASS) lSummary in let nWarn = length $ filter (==WARN) lSummary in let nFail = length $ filter (==FAIL) lSummary in let summary = showString "SUMMARY: " . shows nPass . showString " PASS, " . shows nWarn . showString " WARN, " . shows nFail . showString " FAIL" in Sys.putStrLn (summary []) data TestResult = PASS|WARN|FAIL deriving (Eq) -- obtain words in dictionary starting with "test." testWords :: AODict md -> [Word] testWords = filter hasTestPrefix . M.keys . readAODict where hasTestPrefix = (T.pack "test." `T.isPrefixOf`) -- assumes word is in dictionary runTest :: ([Op] -> IO (Prog AORT)) -> AODict md -> Word -> IO TestResult runTest compile d w = let (Right ops) = compileAOtoABC d [AO_Word w] in compile ops >>= \ prog -> newDefaultRuntime >>= \ rt -> IORef.newIORef [] >>= \ rfW -> let fwarn s = liftIO $ IORef.modifyIORef rfW (s:) in runRT rt (newTestPB d fwarn) >>= \ testPB -> let testEnv = aoStdEnv testPB in let runProg = runRT rt (prog testEnv) in try runProg >>= \ evf -> IORef.readIORef rfW >>= \ warnings -> reportTest w (L.reverse warnings) evf type Warning = String reportTest :: (Show err) => Word -> [Warning] -> Either err (V AORT) -> IO TestResult reportTest w [] (Right _) = Sys.putStrLn ("(pass) " ++ T.unpack w) >> return PASS reportTest w ws (Right _) = Sys.putStrLn ("(Warn) " ++ T.unpack w) >> mapM_ reportWarning ws >> return WARN reportTest w ws (Left err) = Sys.putStrLn ("(FAIL) " ++ T.unpack w) >> mapM_ reportWarning ws >> Sys.putStrLn (indent " " (show err)) >> return FAIL reportWarning :: Warning -> IO () reportWarning = Sys.putStrLn . indent " " test powerblock is linear , and is not serialized at the moment newTestPB :: AODict md -> (Warning -> AORT ()) -> AORT (Block AORT) newTestPB d fwarn = return b where b = Block { b_aff = True, b_rel = True, b_code = code, b_prog = prog } code = S.singleton $ Tok "test powers" prog (P (valToText -> Just cmd) arg) = runCmd cmd arg >>= \ result -> newTestPB d fwarn >>= \ tpb -> return (P (B tpb) result) prog v = fail $ "not structured as a command: " ++ show v runCmd "warn" (valToText -> Just msg) = fwarn msg >> return U runCmd "error" (valToText -> Just msg) = fwarn msg >> fail "error command" runCmd s v = fail $ "unrecognized command: " ++ s ++ " with arg " ++ show v {- -- for now, I just emit code. I might later need to emit a context -- that is held by the runtime and recovered dynamically. printImperativeJIT :: String -> IO () printImperativeJIT aoStr = getDict >>= \ d -> case compileAOString d aoStr >>= abc2hs_auto . simplify of Left err -> putErrLn err >> Sys.exitFailure Right hsCode -> Sys.putStrLn hsCode -} printResource :: String -> IO () printResource s = tryIO load >>= either onFail onPass where load = loadResource loadRscFile ('#':s) onFail e = putErrLn (show e) >> Sys.exitFailure onPass = Sys.putStrLn . show -------------------------------------- -- Running : : [ W ] - > IO ( ) runType [ ] = loadDictionary > > = \ dictA0 - > let dc = compileDictionary dictA0 in mapM _ ( uncurry runTypeW ) ( M.toList dc ) runType ws = loadDictionary > > = \ dictA0 - > let dc = compileDictionary dictA0 in mapM _ ( findAndType dc ) ws findAndType : : DictC - > W - > IO ( ) findAndType dc w = maybe notFound ( ) ( M.lookup w dc ) where notFound = Sys.putStrLn $ T.unpack w + + " : : ( WORD NOT FOUND ! ) " runTypeW : : W - > S.Seq Op - > IO ( ) runTypeW w code = Sys.putStrLn ( T.unpack w + + " : : " + + msg ) where msg = case code of Left etxt - > " ( ERROR!)\n " + + indent " " ( T.unpack etxt ) Right ( tyIn , tyOut ) - > show tyIn + + " → " + + show tyOut -------------------------------------- -- Running Pass0 typecheck -------------------------------------- runType :: [W] -> IO () runType [] = loadDictionary >>= \ dictA0 -> let dc = compileDictionary dictA0 in mapM_ (uncurry runTypeW) (M.toList dc) runType ws = loadDictionary >>= \ dictA0 -> let dc = compileDictionary dictA0 in mapM_ (findAndType dc) ws findAndType :: DictC -> W -> IO () findAndType dc w = maybe notFound (runTypeW w) (M.lookup w dc) where notFound = Sys.putStrLn $ T.unpack w ++ " :: (WORD NOT FOUND!)" runTypeW :: W -> S.Seq Op -> IO () runTypeW w code = Sys.putStrLn (T.unpack w ++ " :: " ++ msg) where msg = case typeOfABC code of Left etxt -> "(ERROR!)\n" ++ indent " " (T.unpack etxt) Right (tyIn, tyOut) -> show tyIn ++ " → " ++ show tyOut -} dumpAODict :: IO () dumpAODict = getDict >>= LBS.hPutStr Sys.stdout . renderAODict aodefToABC :: AO_Code -> [Op] aodefToABC = L.concatMap opToABC where opToABC (AO_Word w) = return (Tok ('%' : T.unpack w)) opToABC (AO_Block ops) = [BL (aodefToABC ops), Tok "%block"] opToABC (AO_Num r) | (1 == denominator r) = integer r | Just d <- toDecimal r = decimal d | otherwise = ratio r opToABC (AO_Text s) = [TL s, Tok "%literal"] opToABC (AO_ABC op) = [aopToABC op] opToABC (AO_Tok t) = [Tok t] integer n = quote n <> [Tok "%integer"] decimal d = integer (Decimal.decimalMantissa d) <> integer (toInteger $ Decimal.decimalPlaces d) <> [Tok "%decimal"] ratio r = integer (numerator r) <> integer (denominator r) <> [Tok "%ratio"] -- | attempt to reasonably render AO code into the AODict format. renderAODict :: Dict -> LBS.ByteString renderAODict d = BB.toLazyByteString $ render Set.empty lw where dm = readAODict d lw = M.keys dm renderText = BB.stringUtf8 . T.unpack renderLine w = case M.lookup w dm of Nothing -> mempty Just def -> BB.char8 '@' <> renderText w <> BB.char8 ' ' <> BB.stringUtf8 (show (aodefToABC (fst def))) <> BB.char8 '\n' render _ [] = mempty render s ws@(w:ws') = if Set.member w s then render s ws' else let lDeps = maybe [] (aoWords . fst) $ M.lookup w dm in let lNewDeps = L.filter (`Set.notMember` s) $ lDeps in let bHasNewDeps = not (L.null lNewDeps) in if bHasNewDeps then render s (lNewDeps ++ ws) else renderLine w <> render (Set.insert w s) ws' toDecimal :: Rational -> Maybe Decimal.Decimal toDecimal r = case Decimal.eitherFromRational r of Right d -> Just d _ -> Nothing
null
https://raw.githubusercontent.com/dmbarbour/awelon/af9124654dd9462cc4887dccf67b3e33302c7351/hsrc_ao/Main.hs
haskell
| The `ao` command line executable, with many utilities for non-interactive programming. stdout) \n\ todo: typechecking! when persistence is working, perhaps add an AO_HOME or similar. very simple command line processing runMode ["jit",cmd] = printImperativeJIT cmd runMode ["test.jit"] = runAOTests (abc_jit . simplify) extract paragraphs from command string (I kind of hate lazy IO, but it's convenient here) obtain a list of paragraphs. Each paragraph is recognized getDict will always succeed, but might return an empty dictionary... and might complain a lot on stderr the toplevel will simply interpret operations (leave JIT for inner loops!) stdout ) visible via {&debug print raw} get a character (maybe) write character to stdout repeat on next character pattern with simple wildcards. may escape '*' using '\*' List words starting with a given regular expression. find all uses of a given word (modulo entries that fail to compile) obtain words in dictionary starting with "test." assumes word is in dictionary -- for now, I just emit code. I might later need to emit a context -- that is held by the runtime and recovered dynamically. printImperativeJIT :: String -> IO () printImperativeJIT aoStr = getDict >>= \ d -> case compileAOString d aoStr >>= abc2hs_auto . simplify of Left err -> putErrLn err >> Sys.exitFailure Right hsCode -> Sys.putStrLn hsCode ------------------------------------ Running : : [ W ] - > IO ( ) ------------------------------------ Running Pass0 typecheck ------------------------------------ | attempt to reasonably render AO code into the AODict format.
# LANGUAGE PatternGuards , ViewPatterns , OverloadedStrings # module Main ( main ) where import Control.Applicative import Control.Monad import Data.Monoid import Data.Ratio import qualified Data.Map as M import qualified Data.Text as T import qualified Data.List as L import qualified Data.Sequence as S import qualified Data.ByteString.Builder as BB import qualified Data.ByteString.Lazy as LBS import qualified Data.Set as Set import qualified Data.IORef as IORef import qualified System.IO as Sys import System . ( unsafeInterleaveIO ) import qualified System.Exit as Sys import qualified System.Environment as Env import qualified Text.Parsec as P import qualified Data.Decimal as Decimal import ABC.Simplify (simplify) import ABC.Operators import ABC.Resource import ABC.Imperative.Value import ABC.Imperative.Interpreter import ABC.Quote import AO.Dict import AO.Code import AO.AOFile import AO.Parser import AO.Compile import AORT import Util helpMsg :: String helpMsg = "The `ao` executable provides many utilities for non-interactive\n\ \operations involving AO or ABC code. Usage:\n\ \\n\ \ ao help print this message \n\ \ \n\ \ ao test run all `test.` words in test environment \n\ \ \n\ \ ao abc command dump simplified ABC for AO command \n\ \ ao abc.raw command dump raw ABC for AO command \n\ \ ao abc.ann command dump annotated ABC for AO command \n\ \ ao exec command execute AO command \n\ \ ao exec.abc command execute ABC code \n\ \ \n\ \ ao abc.s dump simplified ABC for AO on input stream \n\ \ ao abc.raw.s dump raw ABC for AO on input stream \n\ \ ao abc.ann.s dump annotated ABC for AO on input stream \n\ \ ao exec.s execute AO commands from input stream \n\ \ ao exec.abc.s execute ABC from input stream \n\ \ \n\ \ ao rsc rscTok dump ABC for ABC resource invocation {#rscTok} \n\ \ \n\ \ ao list pattern list words matching pattern (e.g. test.*) \n\ \ ao defs pattern find definitions of words matching pattern \n\ \ ao uses pattern find uses of words matching pattern \n\ \ ao def word print full accepted definition of word \n\ \ \n\ \ (Experimental Modes) \n\ \ \n\ \ ao aodict dump '.ao' export file for Wikilon\n\ \\n\ \All 'exec' operations use the same powers and environment as `aoi`. \n\ \Streams process stdin to stdout, one AO or ABC paragraph at a time. \n\ \\n\ \Environment Variables: \n\ \ AO_PATH: where to search for '.ao' files \n\ \ AO_DICT: root dictionary text; default \"ao\" \n\ \ AO_TEMP: directory for temporaries; default \"aotmp\" \n\ \" \ \n\ \ ( JIT inoperative at moment ) \n\ \ ao jit command print haskell code for imperative JIT \n\ \ ao test.jit run all ` test . ` words using JIT \n\ \ \n\ \ (JIT inoperative at moment) \n\ \ ao jit command print haskell code for imperative JIT \n\ \ ao test.jit run all `test.` words using JIT \n\ -} main :: IO () main = Env.getArgs >>= runMode type Dict = AODict AOFMeta data CMode = CMode { cm_simplify :: [Op] -> [Op] , cm_annotate :: Dict -> Dict } modeSimp, modeRaw, modeAnn :: CMode modeSimp = CMode simplify id modeRaw = CMode id id modeAnn = CMode id annoDict runMode :: [String] -> IO () runMode ["help"] = Sys.putStrLn helpMsg runMode ["abc",cmd] = mkCmdS cmd >>= dumpABC modeSimp runMode ["abc.raw",cmd] = mkCmdS cmd >>= dumpABC modeRaw runMode ["abc.ann",cmd] = mkCmdS cmd >>= dumpABC modeAnn runMode ["exec",cmd] = mkCmdS cmd >>= execAO runMode ["exec.abc",cmd] = mkCmdS cmd >>= execABC runMode ["abc.s"] = stdCmdS >>= dumpABC modeSimp runMode ["abc.raw.s"] = stdCmdS >>= dumpABC modeRaw runMode ["abc.ann.s"] = stdCmdS >>= dumpABC modeAnn runMode ["exec.s"] = stdCmdS >>= execAO runMode ["exec.abc.s"] = stdCmdS >>= execABC runMode ["ss",cmd] = execSS cmd runMode ["rsc",rsc] = printResource rsc runMode ["list",ptrn] = listWords ptrn runMode ["uses",ptrn] = listUses ptrn runMode ["defs",ptrn] = listDefs ptrn runMode ["def",word] = printDef word runMode ["test"] = runAOTests (return . interpret . simplify) runMode ["aodict"] = dumpAODict runMode _ = putErrLn eMsg >> Sys.exitFailure where eMsg = "arguments not recognized; try `ao help`" mkCmdS :: String -> IO [String] mkCmdS s = Sys.hClose Sys.stdin >> return (paragraphs s) lazily obtain paragraphs from stdin stdCmdS :: IO [String] stdCmdS = paragraphs <$> Sys.hGetContents Sys.stdin getAO_DICT :: IO String getAO_DICT = maybe "ao" id <$> tryJust (Env.getEnv "AO_DICT") by two or more sequential ' \n ' characters . paragraphs :: String -> [String] paragraphs = pp0 where pp0 ('\n':ss) = pp0 ss pp0 (c:ss) = pp1 [c] ss pp0 [] = [] pp1 ('\n':p) ('\n':ss) = L.reverse p : pp0 ss pp1 p (c:ss) = pp1 (c:p) ss pp1 p [] = L.reverse p : [] getDict :: IO Dict getDict = getAO_DICT >>= flip loadAODict putErrLn putErrLn :: String -> IO () putErrLn = Sys.hPutStrLn Sys.stderr dump ABC code , paragraph at a time , to standard output dumpABC :: CMode -> [String] -> IO () dumpABC mode ss = (cm_annotate mode <$> getDict) >>= \ d -> let nss = L.zip [1..] ss in mapM_ (uncurry (dumpABC' d mode)) nss dumpABC' :: AODict md -> CMode -> Int -> String -> IO () dumpABC' dict mode nPara aoStr = when (nPara > 1) (Sys.putChar '\n') >> compilePara dict nPara aoStr >>= \ ops -> Sys.putStr (show (cm_simplify mode ops)) >> Sys.putChar '\n' >> Sys.hFlush Sys.stdout compilePara :: AODict md -> Int -> String -> IO [Op] compilePara dict nPara aoStr = case compileAOString dict aoStr of Left err -> putErrLn ("paragraph " ++ show nPara) >> putErrLn err >> Sys.exitFailure Right ops -> return ops compileAOString :: AODict md -> String -> Either String [Op] compileAOString dict aoString = case P.parse parseAO "" aoString of Left err -> Left $ show err Right ao -> case compileAOtoABC dict ao of Left mw -> Left $ undefinedWordsMsg mw Right abc -> Right abc undefinedWordsMsg :: [Word] -> String undefinedWordsMsg mw = "undefined words: " ++ mwStr where mwStr = L.unwords $ fmap T.unpack mw annoDict :: Dict -> Dict annoDict = unsafeUpdateAODict (M.mapWithKey annoLoc) where showsLoc w aofm = showString (T.unpack w) . showChar '@' . showString (T.unpack (aofm_import aofm)) . showChar ':' . shows (aofm_line aofm) annoLoc w (c,aofm) = let loc = showsLoc w aofm [] in let entryTok = "&+" ++ loc in let exitTok = "&-" ++ loc in let c' = AO_Tok entryTok : (c ++ [AO_Tok exitTok]) in (c',aofm) execAO :: [String] -> IO () execAO ss = getDict >>= \ d -> let compile (n,s) = simplify <$> compilePara d n s in execOps $ fmap compile $ L.zip [1..] ss execute ABC in its raw form . execABC :: [String] -> IO () execABC = execOps . fmap (return . simplify . read) type CX = AORT_CX type RtVal = V AORT execOps :: [IO [Op]] -> IO () execOps ppOps = newDefaultRuntime >>= \ cx -> runRT cx newDefaultEnvironment >>= \ v0 -> void (execOps' cx v0 ppOps) execOps' :: CX -> RtVal -> [IO [Op]] -> IO RtVal execOps' _ v [] = return v execOps' cx v (readPara:more) = readPara >>= \ ops -> let prog = interpret ops in runRT cx (prog v) >>= \ v' -> execOps' cx v' more execSS :: String -> IO () execSS aoCmd = getDict >>= \ d -> case compileAOString d aoCmd of Left err -> putErrLn err >> Sys.exitFailure Right ops -> Sys.hSetBinaryMode Sys.stdin True >> Sys.hSetBinaryMode Sys.stdout True >> Sys.hSetBuffering Sys.stdout Sys.NoBuffering >> newDefaultRuntime >>= \ cx -> runRT cx $ newDefaultEnvironment >>= \ (P stack env) -> interpret ops (P (P stdIn stack) env) >>= \ (P (P (B bStdOut) _) _) -> writeSS (b_prog bStdOut) stdIn modeled as a simple affine stream stdIn :: RtVal stdIn = B b where b = Block { b_aff = True, b_rel = False, b_code = code, b_prog = prog } prog U = liftIO $ Sys.hIsEOF Sys.stdin >>= \ bEOF -> if bEOF then return (R U) else Sys.hGetChar Sys.stdin >>= \ c8 -> let n = (N . fromIntegral . fromEnum) c8 in return (L (P n stdIn)) prog v = fail $ show v ++ " @ {stdin} (unexpected input)" writeSS :: Prog AORT -> AORT () writeSS getC = case mbC of (L (P (N n) (B b))) | isOctet n -> let c8 = (toEnum . fromIntegral . numerator) n in (R U) -> return () v -> fail $ "illegal output from stdout stream: " ++ show v isOctet :: Rational -> Bool isOctet r = (1 == d) && (0 <= n) && (n < 256) where d = denominator r n = numerator r type Pattern = String matchStr :: Pattern -> String -> Bool matchStr ('*':[]) _ = True matchStr pp@('*':pp') ss@(_:ss') = matchStr pp' ss || matchStr pp ss' matchStr ('\\':'*':pp) (c:ss) = (c == '*') && matchStr pp ss matchStr (c:pp) (c':ss) = (c == c') && (matchStr pp ss) matchStr pp ss = null pp && null ss listWords :: String -> IO () listWords pattern = (fmap T.unpack . M.keys . readAODict) <$> getDict >>= \ allWords -> let matchingWords = L.filter (matchStr pattern) allWords in mapM_ Sys.putStrLn matchingWords getDictFiles :: IO [AOFile] getDictFiles = getAO_DICT >>= \ root -> loadAOFiles root putErrLn listUses :: Pattern -> IO () listUses ptrn = getDictFiles >>= mapM_ (fileUses ptrn) fileUses :: Pattern -> AOFile -> IO () fileUses p file = let defs = L.filter (codeUsesWord p . fst . snd) (aof_defs file) in if null defs then return () else Sys.putStrLn (show (aof_path file)) >> mapM_ (Sys.putStrLn . (" " ++) . defSummary) defs codeUsesWord :: Pattern -> AO_Code -> Bool codeUsesWord = L.any . actionUsesWord actionUsesWord :: Pattern -> AO_Action -> Bool actionUsesWord p (AO_Word w) = (matchStr p (T.unpack w)) actionUsesWord p (AO_Block code) = codeUsesWord p code actionUsesWord _ _ = False defSummary :: AODef Int -> String defSummary (defWord,(code,line)) = showsSummary [] where showsSummary = shows line . showChar ' ' . showChar '@' . showsCode (AO_Word defWord : code) showsCode = shows . fmap cutBigText cutBigText (AO_Text txt) | isBigText txt = AO_Word (T.pack "(TEXT)") cutBigText (AO_Block ops) = AO_Block (fmap cutBigText ops) cutBigText op = op isBigText txt = (L.length txt > 14) || (L.any isMC txt) isMC c = ('"' == c) || ('\n' == c) listDefs :: Pattern -> IO () listDefs ptrn = getDictFiles >>= mapM_ (fileDefines ptrn) fileDefines :: Pattern -> AOFile -> IO () fileDefines p file = let defs = L.filter (matchStr p . T.unpack . fst) (aof_defs file) in if null defs then return () else Sys.putStrLn (show (aof_path file)) >> mapM_ (Sys.putStrLn . (" " ++) . defSummary) defs printDef :: String -> IO () printDef word = getDict >>= \ d -> case M.lookup (T.pack word) (readAODict d) of Nothing -> putErrLn "undefined" >> Sys.exitFailure Just (def,_) -> Sys.putStrLn (show def) runAOTests :: ([Op] -> IO (Prog AORT)) -> IO () runAOTests compile = getDict >>= \ d -> mapM (runTest compile d) (testWords d) >>= \ lSummary -> let nPass = length $ filter (==PASS) lSummary in let nWarn = length $ filter (==WARN) lSummary in let nFail = length $ filter (==FAIL) lSummary in let summary = showString "SUMMARY: " . shows nPass . showString " PASS, " . shows nWarn . showString " WARN, " . shows nFail . showString " FAIL" in Sys.putStrLn (summary []) data TestResult = PASS|WARN|FAIL deriving (Eq) testWords :: AODict md -> [Word] testWords = filter hasTestPrefix . M.keys . readAODict where hasTestPrefix = (T.pack "test." `T.isPrefixOf`) runTest :: ([Op] -> IO (Prog AORT)) -> AODict md -> Word -> IO TestResult runTest compile d w = let (Right ops) = compileAOtoABC d [AO_Word w] in compile ops >>= \ prog -> newDefaultRuntime >>= \ rt -> IORef.newIORef [] >>= \ rfW -> let fwarn s = liftIO $ IORef.modifyIORef rfW (s:) in runRT rt (newTestPB d fwarn) >>= \ testPB -> let testEnv = aoStdEnv testPB in let runProg = runRT rt (prog testEnv) in try runProg >>= \ evf -> IORef.readIORef rfW >>= \ warnings -> reportTest w (L.reverse warnings) evf type Warning = String reportTest :: (Show err) => Word -> [Warning] -> Either err (V AORT) -> IO TestResult reportTest w [] (Right _) = Sys.putStrLn ("(pass) " ++ T.unpack w) >> return PASS reportTest w ws (Right _) = Sys.putStrLn ("(Warn) " ++ T.unpack w) >> mapM_ reportWarning ws >> return WARN reportTest w ws (Left err) = Sys.putStrLn ("(FAIL) " ++ T.unpack w) >> mapM_ reportWarning ws >> Sys.putStrLn (indent " " (show err)) >> return FAIL reportWarning :: Warning -> IO () reportWarning = Sys.putStrLn . indent " " test powerblock is linear , and is not serialized at the moment newTestPB :: AODict md -> (Warning -> AORT ()) -> AORT (Block AORT) newTestPB d fwarn = return b where b = Block { b_aff = True, b_rel = True, b_code = code, b_prog = prog } code = S.singleton $ Tok "test powers" prog (P (valToText -> Just cmd) arg) = runCmd cmd arg >>= \ result -> newTestPB d fwarn >>= \ tpb -> return (P (B tpb) result) prog v = fail $ "not structured as a command: " ++ show v runCmd "warn" (valToText -> Just msg) = fwarn msg >> return U runCmd "error" (valToText -> Just msg) = fwarn msg >> fail "error command" runCmd s v = fail $ "unrecognized command: " ++ s ++ " with arg " ++ show v printResource :: String -> IO () printResource s = tryIO load >>= either onFail onPass where load = loadResource loadRscFile ('#':s) onFail e = putErrLn (show e) >> Sys.exitFailure onPass = Sys.putStrLn . show runType [ ] = loadDictionary > > = \ dictA0 - > let dc = compileDictionary dictA0 in mapM _ ( uncurry runTypeW ) ( M.toList dc ) runType ws = loadDictionary > > = \ dictA0 - > let dc = compileDictionary dictA0 in mapM _ ( findAndType dc ) ws findAndType : : DictC - > W - > IO ( ) findAndType dc w = maybe notFound ( ) ( M.lookup w dc ) where notFound = Sys.putStrLn $ T.unpack w + + " : : ( WORD NOT FOUND ! ) " runTypeW : : W - > S.Seq Op - > IO ( ) runTypeW w code = Sys.putStrLn ( T.unpack w + + " : : " + + msg ) where msg = case code of Left etxt - > " ( ERROR!)\n " + + indent " " ( T.unpack etxt ) Right ( tyIn , tyOut ) - > show tyIn + + " → " + + show tyOut runType :: [W] -> IO () runType [] = loadDictionary >>= \ dictA0 -> let dc = compileDictionary dictA0 in mapM_ (uncurry runTypeW) (M.toList dc) runType ws = loadDictionary >>= \ dictA0 -> let dc = compileDictionary dictA0 in mapM_ (findAndType dc) ws findAndType :: DictC -> W -> IO () findAndType dc w = maybe notFound (runTypeW w) (M.lookup w dc) where notFound = Sys.putStrLn $ T.unpack w ++ " :: (WORD NOT FOUND!)" runTypeW :: W -> S.Seq Op -> IO () runTypeW w code = Sys.putStrLn (T.unpack w ++ " :: " ++ msg) where msg = case typeOfABC code of Left etxt -> "(ERROR!)\n" ++ indent " " (T.unpack etxt) Right (tyIn, tyOut) -> show tyIn ++ " → " ++ show tyOut -} dumpAODict :: IO () dumpAODict = getDict >>= LBS.hPutStr Sys.stdout . renderAODict aodefToABC :: AO_Code -> [Op] aodefToABC = L.concatMap opToABC where opToABC (AO_Word w) = return (Tok ('%' : T.unpack w)) opToABC (AO_Block ops) = [BL (aodefToABC ops), Tok "%block"] opToABC (AO_Num r) | (1 == denominator r) = integer r | Just d <- toDecimal r = decimal d | otherwise = ratio r opToABC (AO_Text s) = [TL s, Tok "%literal"] opToABC (AO_ABC op) = [aopToABC op] opToABC (AO_Tok t) = [Tok t] integer n = quote n <> [Tok "%integer"] decimal d = integer (Decimal.decimalMantissa d) <> integer (toInteger $ Decimal.decimalPlaces d) <> [Tok "%decimal"] ratio r = integer (numerator r) <> integer (denominator r) <> [Tok "%ratio"] renderAODict :: Dict -> LBS.ByteString renderAODict d = BB.toLazyByteString $ render Set.empty lw where dm = readAODict d lw = M.keys dm renderText = BB.stringUtf8 . T.unpack renderLine w = case M.lookup w dm of Nothing -> mempty Just def -> BB.char8 '@' <> renderText w <> BB.char8 ' ' <> BB.stringUtf8 (show (aodefToABC (fst def))) <> BB.char8 '\n' render _ [] = mempty render s ws@(w:ws') = if Set.member w s then render s ws' else let lDeps = maybe [] (aoWords . fst) $ M.lookup w dm in let lNewDeps = L.filter (`Set.notMember` s) $ lDeps in let bHasNewDeps = not (L.null lNewDeps) in if bHasNewDeps then render s (lNewDeps ++ ws) else renderLine w <> render (Set.insert w s) ws' toDecimal :: Rational -> Maybe Decimal.Decimal toDecimal r = case Decimal.eitherFromRational r of Right d -> Just d _ -> Nothing
7300cabf716a52f851250410e531e8385118aaaa18e4d45b82f4b050531647ef
ekmett/algebra
Commutative.hs
# LANGUAGE MultiParamTypeClasses , UndecidableInstances , FlexibleInstances , TypeOperators # module Numeric.Algebra.Commutative ( Commutative , CommutativeAlgebra , CocommutativeCoalgebra , CommutativeBialgebra ) where import Data.Int import Data.IntSet (IntSet) import Data.IntMap (IntMap) import Data.Set (Set) import Data.Map (Map) import Data.Word import Numeric.Additive.Class import Numeric.Algebra.Class import Numeric.Algebra.Unital import Numeric.Natural import Prelude (Bool, Ord, Integer) -- | A commutative multiplicative semigroup class Multiplicative r => Commutative r instance Commutative () instance Commutative Bool instance Commutative Integer instance Commutative Int instance Commutative Int8 instance Commutative Int16 instance Commutative Int32 instance Commutative Int64 instance Commutative Natural instance Commutative Word instance Commutative Word8 instance Commutative Word16 instance Commutative Word32 instance Commutative Word64 instance ( Commutative a , Commutative b ) => Commutative (a,b) instance ( Commutative a , Commutative b , Commutative c ) => Commutative (a,b,c) instance ( Commutative a , Commutative b , Commutative c , Commutative d ) => Commutative (a,b,c,d) instance ( Commutative a , Commutative b , Commutative c , Commutative d , Commutative e ) => Commutative (a,b,c,d,e) instance CommutativeAlgebra r a => Commutative (a -> r) class Algebra r a => CommutativeAlgebra r a instance ( Commutative r , Semiring r ) => CommutativeAlgebra r () instance ( CommutativeAlgebra r a , CommutativeAlgebra r b ) => CommutativeAlgebra r (a,b) instance ( CommutativeAlgebra r a , CommutativeAlgebra r b , CommutativeAlgebra r c ) => CommutativeAlgebra r (a,b,c) instance ( CommutativeAlgebra r a , CommutativeAlgebra r b , CommutativeAlgebra r c , CommutativeAlgebra r d ) => CommutativeAlgebra r (a,b,c,d) instance ( CommutativeAlgebra r a , CommutativeAlgebra r b , CommutativeAlgebra r c , CommutativeAlgebra r d , CommutativeAlgebra r e ) => CommutativeAlgebra r (a,b,c,d,e) instance ( Commutative r , Semiring r , Ord a ) => CommutativeAlgebra r (Set a) instance (Commutative r , Semiring r ) => CommutativeAlgebra r IntSet -- instance (Commutative r -- , Monoidal r -- , Semiring r , a , Abelian b , b -- ) => CommutativeAlgebra r (Map a b) -- instance ( Commutative r -- , Monoidal r -- , Semiring r , Abelian b , b ) = > CommutativeAlgebra r ( IntMap b ) class Coalgebra r c => CocommutativeCoalgebra r c instance CommutativeAlgebra r m => CocommutativeCoalgebra r (m -> r) instance (Commutative r, Semiring r) => CocommutativeCoalgebra r () instance ( CocommutativeCoalgebra r a , CocommutativeCoalgebra r b ) => CocommutativeCoalgebra r (a,b) instance ( CocommutativeCoalgebra r a , CocommutativeCoalgebra r b , CocommutativeCoalgebra r c ) => CocommutativeCoalgebra r (a,b,c) instance ( CocommutativeCoalgebra r a , CocommutativeCoalgebra r b , CocommutativeCoalgebra r c , CocommutativeCoalgebra r d ) => CocommutativeCoalgebra r (a,b,c,d) instance ( CocommutativeCoalgebra r a , CocommutativeCoalgebra r b , CocommutativeCoalgebra r c , CocommutativeCoalgebra r d , CocommutativeCoalgebra r e ) => CocommutativeCoalgebra r (a,b,c,d,e) instance ( Commutative r , Semiring r , Ord a) => CocommutativeCoalgebra r (Set a) instance ( Commutative r , Semiring r ) => CocommutativeCoalgebra r IntSet instance ( Commutative r , Semiring r , Ord a , Abelian b ) => CocommutativeCoalgebra r (Map a b) instance ( Commutative r , Semiring r , Abelian b ) => CocommutativeCoalgebra r (IntMap b) class ( Bialgebra r h , CommutativeAlgebra r h , CocommutativeCoalgebra r h ) => CommutativeBialgebra r h instance ( Bialgebra r h , CommutativeAlgebra r h , CocommutativeCoalgebra r h ) => CommutativeBialgebra r h
null
https://raw.githubusercontent.com/ekmett/algebra/12dd33e848f406dd53d19b69b4f14c93ba6e352b/src/Numeric/Algebra/Commutative.hs
haskell
| A commutative multiplicative semigroup instance (Commutative r , Monoidal r , Semiring r ) => CommutativeAlgebra r (Map a b) instance ( Commutative r , Monoidal r , Semiring r
# LANGUAGE MultiParamTypeClasses , UndecidableInstances , FlexibleInstances , TypeOperators # module Numeric.Algebra.Commutative ( Commutative , CommutativeAlgebra , CocommutativeCoalgebra , CommutativeBialgebra ) where import Data.Int import Data.IntSet (IntSet) import Data.IntMap (IntMap) import Data.Set (Set) import Data.Map (Map) import Data.Word import Numeric.Additive.Class import Numeric.Algebra.Class import Numeric.Algebra.Unital import Numeric.Natural import Prelude (Bool, Ord, Integer) class Multiplicative r => Commutative r instance Commutative () instance Commutative Bool instance Commutative Integer instance Commutative Int instance Commutative Int8 instance Commutative Int16 instance Commutative Int32 instance Commutative Int64 instance Commutative Natural instance Commutative Word instance Commutative Word8 instance Commutative Word16 instance Commutative Word32 instance Commutative Word64 instance ( Commutative a , Commutative b ) => Commutative (a,b) instance ( Commutative a , Commutative b , Commutative c ) => Commutative (a,b,c) instance ( Commutative a , Commutative b , Commutative c , Commutative d ) => Commutative (a,b,c,d) instance ( Commutative a , Commutative b , Commutative c , Commutative d , Commutative e ) => Commutative (a,b,c,d,e) instance CommutativeAlgebra r a => Commutative (a -> r) class Algebra r a => CommutativeAlgebra r a instance ( Commutative r , Semiring r ) => CommutativeAlgebra r () instance ( CommutativeAlgebra r a , CommutativeAlgebra r b ) => CommutativeAlgebra r (a,b) instance ( CommutativeAlgebra r a , CommutativeAlgebra r b , CommutativeAlgebra r c ) => CommutativeAlgebra r (a,b,c) instance ( CommutativeAlgebra r a , CommutativeAlgebra r b , CommutativeAlgebra r c , CommutativeAlgebra r d ) => CommutativeAlgebra r (a,b,c,d) instance ( CommutativeAlgebra r a , CommutativeAlgebra r b , CommutativeAlgebra r c , CommutativeAlgebra r d , CommutativeAlgebra r e ) => CommutativeAlgebra r (a,b,c,d,e) instance ( Commutative r , Semiring r , Ord a ) => CommutativeAlgebra r (Set a) instance (Commutative r , Semiring r ) => CommutativeAlgebra r IntSet , a , Abelian b , b , Abelian b , b ) = > CommutativeAlgebra r ( IntMap b ) class Coalgebra r c => CocommutativeCoalgebra r c instance CommutativeAlgebra r m => CocommutativeCoalgebra r (m -> r) instance (Commutative r, Semiring r) => CocommutativeCoalgebra r () instance ( CocommutativeCoalgebra r a , CocommutativeCoalgebra r b ) => CocommutativeCoalgebra r (a,b) instance ( CocommutativeCoalgebra r a , CocommutativeCoalgebra r b , CocommutativeCoalgebra r c ) => CocommutativeCoalgebra r (a,b,c) instance ( CocommutativeCoalgebra r a , CocommutativeCoalgebra r b , CocommutativeCoalgebra r c , CocommutativeCoalgebra r d ) => CocommutativeCoalgebra r (a,b,c,d) instance ( CocommutativeCoalgebra r a , CocommutativeCoalgebra r b , CocommutativeCoalgebra r c , CocommutativeCoalgebra r d , CocommutativeCoalgebra r e ) => CocommutativeCoalgebra r (a,b,c,d,e) instance ( Commutative r , Semiring r , Ord a) => CocommutativeCoalgebra r (Set a) instance ( Commutative r , Semiring r ) => CocommutativeCoalgebra r IntSet instance ( Commutative r , Semiring r , Ord a , Abelian b ) => CocommutativeCoalgebra r (Map a b) instance ( Commutative r , Semiring r , Abelian b ) => CocommutativeCoalgebra r (IntMap b) class ( Bialgebra r h , CommutativeAlgebra r h , CocommutativeCoalgebra r h ) => CommutativeBialgebra r h instance ( Bialgebra r h , CommutativeAlgebra r h , CocommutativeCoalgebra r h ) => CommutativeBialgebra r h
23372acebfe95667c350725b6967e802d276ac3affef5206865300baa8d2bf5c
ocaml-ppx/ppx
exposed_sexp.ml
type t = Stdppx.Sexp.t = | Atom of string | List of t list
null
https://raw.githubusercontent.com/ocaml-ppx/ppx/40e5a35a4386d969effaf428078c900bd03b78ec/src/exposed_sexp.ml
ocaml
type t = Stdppx.Sexp.t = | Atom of string | List of t list
0c6e43c4e70c550490ebd057af1d03fcb2d6a32e5c4eb1ede69ca78bc43c726f
SamB/coq
printmod.ml
(************************************************************************) 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 *) (************************************************************************) open Pp open Util open Names open Declarations open Nameops open Libnames let get_new_id locals id = let rec get_id l id = let dir = make_dirpath [id] in if not (Nametab.exists_module dir) then id else get_id (id::l) (Nameops.next_ident_away id l) in get_id (List.map snd locals) id let rec print_local_modpath locals = function | MPbound mbid -> pr_id (List.assoc mbid locals) | MPdot(mp,l) -> print_local_modpath locals mp ++ str "." ++ pr_lab l | MPself _ | MPfile _ -> raise Not_found let print_modpath locals mp = try (* must be with let because streams are lazy! *) let qid = Nametab.shortest_qualid_of_module mp in pr_qualid qid with | Not_found -> print_local_modpath locals mp let print_kn locals kn = try let qid = Nametab.shortest_qualid_of_modtype kn in pr_qualid qid with Not_found -> try print_local_modpath locals kn with Not_found -> print_modpath locals kn let rec flatten_app mexpr l = match mexpr with | SEBapply (mexpr,marg,_) -> flatten_app mexpr (marg::l) | mexpr -> mexpr::l let rec print_module name locals with_body mb = let body = match with_body, mb.mod_expr with | false, _ | true, None -> mt() | true, Some mexpr -> spc () ++ str ":= " ++ print_modexpr locals mexpr in let modtype = match mb.mod_type with None -> str "" | Some t -> str": " ++ print_modtype locals t in hv 2 (str "Module " ++ name ++ spc () ++ modtype ++ body) and print_modtype locals mty = match mty with | SEBident kn -> print_kn locals kn | SEBfunctor (mbid,mtb1,mtb2) -> let env ' = Modops.add_module ( MPbid mbid ) ( Modops.body_of_type mtb ) env in (Modops.body_of_type mtb) env in *) let locals' = (mbid, get_new_id locals (id_of_mbid mbid)) ::locals in hov 2 (str "Funsig" ++ spc () ++ str "(" ++ pr_id (id_of_mbid mbid) ++ str " : " ++ print_modtype locals mtb1.typ_expr ++ str ")" ++ spc() ++ print_modtype locals' mtb2) | SEBstruct (msid,sign) -> hv 2 (str "Sig" ++ spc () ++ print_sig locals msid sign ++ brk (1,-2) ++ str "End") | SEBapply (mexpr,marg,_) -> let lapp = flatten_app mexpr [marg] in let fapp = List.hd lapp in let mapp = List.tl lapp in hov 3 (str"(" ++ (print_modtype locals fapp) ++ spc () ++ prlist_with_sep spc (print_modexpr locals) mapp ++ str")") | SEBwith(seb,With_definition_body(idl,cb))-> let s = (String.concat "." (List.map string_of_id idl)) in hov 2 (print_modtype locals seb ++ spc() ++ str "with" ++ spc() ++ str "Definition"++ spc() ++ str s ++ spc() ++ str ":="++ spc()) | SEBwith(seb,With_module_body(idl,mp,_))-> let s =(String.concat "." (List.map string_of_id idl)) in hov 2 (print_modtype locals seb ++ spc() ++ str "with" ++ spc() ++ str "Module"++ spc() ++ str s ++ spc() ++ str ":="++ spc()) and print_sig locals msid sign = let print_spec (l,spec) = (match spec with | SFBconst {const_body=Some _; const_opaque=false} -> str "Definition " | SFBconst {const_body=None} | SFBconst {const_opaque=true} -> str "Parameter " | SFBmind _ -> str "Inductive " | SFBmodule _ -> str "Module " | SFBalias (mp,_) -> str "Module" | SFBmodtype _ -> str "Module Type ") ++ str (string_of_label l) in prlist_with_sep spc print_spec sign and print_struct locals msid struc = let print_body (l,body) = (match body with | SFBconst {const_body=Some _; const_opaque=false} -> str "Definition " | SFBconst {const_body=Some _; const_opaque=true} -> str "Theorem " | SFBconst {const_body=None} -> str "Parameter " | SFBmind _ -> str "Inductive " | SFBmodule _ -> str "Module " | SFBalias (mp,_) -> str "Module" | SFBmodtype _ -> str "Module Type ") ++ str (string_of_label l) in prlist_with_sep spc print_body struc and print_modexpr locals mexpr = match mexpr with | SEBident mp -> print_modpath locals mp | SEBfunctor (mbid,mty,mexpr) -> let env ' = Modops.add_module ( MPbid mbid ) ( Modops.body_of_type mtb ) env in in *) let locals' = (mbid, get_new_id locals (id_of_mbid mbid))::locals in hov 2 (str "Functor" ++ spc() ++ str"[" ++ pr_id(id_of_mbid mbid) ++ str ":" ++ print_modtype locals mty.typ_expr ++ str "]" ++ spc () ++ print_modexpr locals' mexpr) | SEBstruct (msid, struc) -> hv 2 (str "Struct" ++ spc () ++ print_struct locals msid struc ++ brk (1,-2) ++ str "End") | SEBapply (mexpr,marg,_) -> let lapp = flatten_app mexpr [marg] in hov 3 (str"(" ++ prlist_with_sep spc (print_modexpr locals) lapp ++ str")") | SEBwith (_,_)-> anomaly "Not avaible yet" let rec printable_body dir = let dir = dirpath_prefix dir in dir = empty_dirpath || try match Nametab.locate_dir (qualid_of_dirpath dir) with DirOpenModtype _ -> false | DirModule _ | DirOpenModule _ -> printable_body dir | _ -> true with Not_found -> true let print_module with_body mp = let name = print_modpath [] mp in print_module name [] with_body (Global.lookup_module mp) ++ fnl () let print_modtype kn = let mtb = Global.lookup_modtype kn in let name = print_kn [] kn in str "Module Type " ++ name ++ str " = " ++ print_modtype [] mtb.typ_expr ++ fnl ()
null
https://raw.githubusercontent.com/SamB/coq/8f84aba9ae83a4dc43ea6e804227ae8cae8086b1/parsing/printmod.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** must be with let because streams are lazy!
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Pp open Util open Names open Declarations open Nameops open Libnames let get_new_id locals id = let rec get_id l id = let dir = make_dirpath [id] in if not (Nametab.exists_module dir) then id else get_id (id::l) (Nameops.next_ident_away id l) in get_id (List.map snd locals) id let rec print_local_modpath locals = function | MPbound mbid -> pr_id (List.assoc mbid locals) | MPdot(mp,l) -> print_local_modpath locals mp ++ str "." ++ pr_lab l | MPself _ | MPfile _ -> raise Not_found let print_modpath locals mp = let qid = Nametab.shortest_qualid_of_module mp in pr_qualid qid with | Not_found -> print_local_modpath locals mp let print_kn locals kn = try let qid = Nametab.shortest_qualid_of_modtype kn in pr_qualid qid with Not_found -> try print_local_modpath locals kn with Not_found -> print_modpath locals kn let rec flatten_app mexpr l = match mexpr with | SEBapply (mexpr,marg,_) -> flatten_app mexpr (marg::l) | mexpr -> mexpr::l let rec print_module name locals with_body mb = let body = match with_body, mb.mod_expr with | false, _ | true, None -> mt() | true, Some mexpr -> spc () ++ str ":= " ++ print_modexpr locals mexpr in let modtype = match mb.mod_type with None -> str "" | Some t -> str": " ++ print_modtype locals t in hv 2 (str "Module " ++ name ++ spc () ++ modtype ++ body) and print_modtype locals mty = match mty with | SEBident kn -> print_kn locals kn | SEBfunctor (mbid,mtb1,mtb2) -> let env ' = Modops.add_module ( MPbid mbid ) ( Modops.body_of_type mtb ) env in (Modops.body_of_type mtb) env in *) let locals' = (mbid, get_new_id locals (id_of_mbid mbid)) ::locals in hov 2 (str "Funsig" ++ spc () ++ str "(" ++ pr_id (id_of_mbid mbid) ++ str " : " ++ print_modtype locals mtb1.typ_expr ++ str ")" ++ spc() ++ print_modtype locals' mtb2) | SEBstruct (msid,sign) -> hv 2 (str "Sig" ++ spc () ++ print_sig locals msid sign ++ brk (1,-2) ++ str "End") | SEBapply (mexpr,marg,_) -> let lapp = flatten_app mexpr [marg] in let fapp = List.hd lapp in let mapp = List.tl lapp in hov 3 (str"(" ++ (print_modtype locals fapp) ++ spc () ++ prlist_with_sep spc (print_modexpr locals) mapp ++ str")") | SEBwith(seb,With_definition_body(idl,cb))-> let s = (String.concat "." (List.map string_of_id idl)) in hov 2 (print_modtype locals seb ++ spc() ++ str "with" ++ spc() ++ str "Definition"++ spc() ++ str s ++ spc() ++ str ":="++ spc()) | SEBwith(seb,With_module_body(idl,mp,_))-> let s =(String.concat "." (List.map string_of_id idl)) in hov 2 (print_modtype locals seb ++ spc() ++ str "with" ++ spc() ++ str "Module"++ spc() ++ str s ++ spc() ++ str ":="++ spc()) and print_sig locals msid sign = let print_spec (l,spec) = (match spec with | SFBconst {const_body=Some _; const_opaque=false} -> str "Definition " | SFBconst {const_body=None} | SFBconst {const_opaque=true} -> str "Parameter " | SFBmind _ -> str "Inductive " | SFBmodule _ -> str "Module " | SFBalias (mp,_) -> str "Module" | SFBmodtype _ -> str "Module Type ") ++ str (string_of_label l) in prlist_with_sep spc print_spec sign and print_struct locals msid struc = let print_body (l,body) = (match body with | SFBconst {const_body=Some _; const_opaque=false} -> str "Definition " | SFBconst {const_body=Some _; const_opaque=true} -> str "Theorem " | SFBconst {const_body=None} -> str "Parameter " | SFBmind _ -> str "Inductive " | SFBmodule _ -> str "Module " | SFBalias (mp,_) -> str "Module" | SFBmodtype _ -> str "Module Type ") ++ str (string_of_label l) in prlist_with_sep spc print_body struc and print_modexpr locals mexpr = match mexpr with | SEBident mp -> print_modpath locals mp | SEBfunctor (mbid,mty,mexpr) -> let env ' = Modops.add_module ( MPbid mbid ) ( Modops.body_of_type mtb ) env in in *) let locals' = (mbid, get_new_id locals (id_of_mbid mbid))::locals in hov 2 (str "Functor" ++ spc() ++ str"[" ++ pr_id(id_of_mbid mbid) ++ str ":" ++ print_modtype locals mty.typ_expr ++ str "]" ++ spc () ++ print_modexpr locals' mexpr) | SEBstruct (msid, struc) -> hv 2 (str "Struct" ++ spc () ++ print_struct locals msid struc ++ brk (1,-2) ++ str "End") | SEBapply (mexpr,marg,_) -> let lapp = flatten_app mexpr [marg] in hov 3 (str"(" ++ prlist_with_sep spc (print_modexpr locals) lapp ++ str")") | SEBwith (_,_)-> anomaly "Not avaible yet" let rec printable_body dir = let dir = dirpath_prefix dir in dir = empty_dirpath || try match Nametab.locate_dir (qualid_of_dirpath dir) with DirOpenModtype _ -> false | DirModule _ | DirOpenModule _ -> printable_body dir | _ -> true with Not_found -> true let print_module with_body mp = let name = print_modpath [] mp in print_module name [] with_body (Global.lookup_module mp) ++ fnl () let print_modtype kn = let mtb = Global.lookup_modtype kn in let name = print_kn [] kn in str "Module Type " ++ name ++ str " = " ++ print_modtype [] mtb.typ_expr ++ fnl ()
0570a97af9a619010bb4d1b7973350bd4a4b77af9e0002d8c7e16e97db57e79a
zack-bitcoin/amoveo-mining-pool
config.erl
-module(config). -compile(export_all). mode() -> production. %mode() -> test. full_node() -> case mode() of test -> ":3011/";%useful for testing by connecting to `make multi-quick` mode in the amoveo full node. production -> ":8081/" end. external() -> X = full_node(), Y = lists:reverse(X), Z = [hd("/")|[hd("0")|tl(tl(Y))]], lists:reverse(Z). this is the portion of the block reward that goes to the mining pool . It is a fraction { numerator , denominator } . for example { 1 , 9 } would mean that 1/9th of the block reward is kept as a fee , and 8/9ths are paid to miners .. block_reward() -> 40461210.%64139933.%100227592. Initially , this pubkey controls all the shares in the pool . About half of the first ( rt ( ) + 1 ) block rewards will go to this account . This is important so that we do n't over - reward the miners of the first 10 blocks . When you are ready to shut off your node , first do ` accounts : final_reward ( ) . ` this way you do n't under - reward the miners of the last 10 blocks . Use the extra money you got from the first 10 blocks to afford to pay the miners of the last 10 blocks . share_block_ratio() -> case mode() of test -> 2; production -> 11 end. share_block_ratio ( ) - > 11.% for every block , we pay out 2^share_block_ratio many rewards . so if this is 4 , that means we pay 16 shares for every block we find on average . if it is 10 , then we pay 1024 shares for every block we find . rt() -> 9.%rewards are smoothed out over the last rt()+1 blocks. ratio() -> {rt(), rt()+1}. tx_fee() -> 100000.%when you shut off the pool, it pays out to everyone who has more than this much veo. payout_limit() -> 40000000.%when a miner has more than this much veo, it automatically pays out to you. how often we get a new problem from the server to work on . in seconds confirmations() -> 5. %how many confirmations does a block need before we can pay out the reward spend_log_file() -> "spend.log". 10 minutes
null
https://raw.githubusercontent.com/zack-bitcoin/amoveo-mining-pool/fd39d6812e0bc9bdd613aec0e82c3c3907df23c5/apps/amoveo_mining_pool/src/config.erl
erlang
mode() -> test. useful for testing by connecting to `make multi-quick` mode in the amoveo full node. 64139933.%100227592. for every block , we pay out 2^share_block_ratio many rewards . rewards are smoothed out over the last rt()+1 blocks. when you shut off the pool, it pays out to everyone who has more than this much veo. when a miner has more than this much veo, it automatically pays out to you. how many confirmations does a block need before we can pay out the reward
-module(config). -compile(export_all). mode() -> production. full_node() -> case mode() of test -> production -> ":8081/" end. external() -> X = full_node(), Y = lists:reverse(X), Z = [hd("/")|[hd("0")|tl(tl(Y))]], lists:reverse(Z). this is the portion of the block reward that goes to the mining pool . It is a fraction { numerator , denominator } . for example { 1 , 9 } would mean that 1/9th of the block reward is kept as a fee , and 8/9ths are paid to miners .. Initially , this pubkey controls all the shares in the pool . About half of the first ( rt ( ) + 1 ) block rewards will go to this account . This is important so that we do n't over - reward the miners of the first 10 blocks . When you are ready to shut off your node , first do ` accounts : final_reward ( ) . ` this way you do n't under - reward the miners of the last 10 blocks . Use the extra money you got from the first 10 blocks to afford to pay the miners of the last 10 blocks . share_block_ratio() -> case mode() of test -> 2; production -> 11 end. so if this is 4 , that means we pay 16 shares for every block we find on average . if it is 10 , then we pay 1024 shares for every block we find . ratio() -> {rt(), rt()+1}. how often we get a new problem from the server to work on . in seconds spend_log_file() -> "spend.log". 10 minutes
9d3c81b109a564b90446fad56a21913e273275dbe3da66f5c5938b6880f7ceba
robrix/sequoia
Quantification.hs
{-# LANGUAGE ConstraintKinds #-} # LANGUAGE QuantifiedConstraints # # LANGUAGE UndecidableInstances # module Sequoia.Connective.Quantification ( -- * Adjunction leftAdjunct , rightAdjunct -- * Quantified constraints , type (==>) -- * Connectives , module Sequoia.Connective.Exists , module Sequoia.Connective.ForAll ) where import Data.Kind (Constraint) import Sequoia.Connective.Exists import Sequoia.Connective.ForAll import Sequoia.Polarity import Sequoia.Profunctor.Continuation Adjunction leftAdjunct :: (forall x . Exists r p a -> b x •• r) -> (forall x . Polarized p x => a x •• r -> ForAll r p b) leftAdjunct f a = ForAll (f (Exists a)) rightAdjunct :: (forall x . a x •• r -> ForAll r p b) -> (forall x . Polarized p x => Exists r p a -> b x •• r) rightAdjunct f (Exists r) = runForAll (f r) -- Quantified constraints type (cx ==> cf) f = (forall x . cx x => cf (f x)) :: Constraint infix 5 ==>
null
https://raw.githubusercontent.com/robrix/sequoia/2851088bc763e6c8bad99152ab94b2cf7bf7c580/src/Sequoia/Connective/Quantification.hs
haskell
# LANGUAGE ConstraintKinds # * Adjunction * Quantified constraints * Connectives Quantified constraints
# LANGUAGE QuantifiedConstraints # # LANGUAGE UndecidableInstances # module Sequoia.Connective.Quantification leftAdjunct , rightAdjunct , type (==>) , module Sequoia.Connective.Exists , module Sequoia.Connective.ForAll ) where import Data.Kind (Constraint) import Sequoia.Connective.Exists import Sequoia.Connective.ForAll import Sequoia.Polarity import Sequoia.Profunctor.Continuation Adjunction leftAdjunct :: (forall x . Exists r p a -> b x •• r) -> (forall x . Polarized p x => a x •• r -> ForAll r p b) leftAdjunct f a = ForAll (f (Exists a)) rightAdjunct :: (forall x . a x •• r -> ForAll r p b) -> (forall x . Polarized p x => Exists r p a -> b x •• r) rightAdjunct f (Exists r) = runForAll (f r) type (cx ==> cf) f = (forall x . cx x => cf (f x)) :: Constraint infix 5 ==>
d4951beae3a6bf0b4b153f69ab6b9774c6ed84344ed18f7133daa44b97b2d1fc
softwarelanguageslab/maf
R5RS_scp1_counter-4.scm
; Changes: * removed : 1 * added : 0 * swaps : 0 ; * negated predicates: 0 ; * swapped branches: 0 ; * calls to id fun: 0 (letrec ((result ()) (output (lambda (i) (set! result (cons i result)))) (count1 (lambda (x) (if (= 0 x) (display x) (begin (<change> (display x) ()) (count1 (- x 1)))))) (count2 (lambda (x) (if (= 0 x) (display x) (begin (count2 (- x 1)) (display x)))))) (count1 4) (count2 4) (equal? result (__toplevel_cons 4 (__toplevel_cons 3 (__toplevel_cons 2 (__toplevel_cons 1 (__toplevel_cons 0 (__toplevel_cons 0 (__toplevel_cons 1 (__toplevel_cons 2 (__toplevel_cons 3 (__toplevel_cons 4 ()))))))))))))
null
https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_scp1_counter-4.scm
scheme
Changes: * negated predicates: 0 * swapped branches: 0 * calls to id fun: 0
* removed : 1 * added : 0 * swaps : 0 (letrec ((result ()) (output (lambda (i) (set! result (cons i result)))) (count1 (lambda (x) (if (= 0 x) (display x) (begin (<change> (display x) ()) (count1 (- x 1)))))) (count2 (lambda (x) (if (= 0 x) (display x) (begin (count2 (- x 1)) (display x)))))) (count1 4) (count2 4) (equal? result (__toplevel_cons 4 (__toplevel_cons 3 (__toplevel_cons 2 (__toplevel_cons 1 (__toplevel_cons 0 (__toplevel_cons 0 (__toplevel_cons 1 (__toplevel_cons 2 (__toplevel_cons 3 (__toplevel_cons 4 ()))))))))))))
14100ef310ae39661b5747e4cf8de07f76a96d715dbd4195cf83ad54562f2e5a
TrustInSoft/tis-kernel
LogicAssigns.ml
(**************************************************************************) (* *) This file is part of . (* *) is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 (* *) is released under GPLv2 (* *) (**************************************************************************) (**************************************************************************) (* *) This file is part of WP plug - in of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat a l'energie atomique et aux energies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) open Ctypes open Lang open Lang.F open Memory module type Code = sig type loc val equal_obj : c_object -> loc value -> loc value -> F.pred end module type Logic = sig type loc val vars : loc Memory.sloc list -> Vars.t val pp_logic : Format.formatter -> loc Memory.logic -> unit val pp_sloc : Format.formatter -> loc Memory.sloc -> unit val pp_region : Format.formatter -> loc Memory.sloc list -> unit end module Make ( M : Memory.Model ) ( C : Code with type loc = M.loc ) ( L : Logic with type loc = M.loc ) = struct module Dom = M.Heap.Set type region = (c_object * M.loc sloc list) list (* -------------------------------------------------------------------------- *) (* --- Domain --- *) (* -------------------------------------------------------------------------- *) let vars (r:region) = List.fold_left (fun xs (_,s) -> Vars.union xs (L.vars s)) Vars.empty r let dsloc obj = function | Sloc l | Sdescr(_,l,_) -> M.domain obj l | Srange(l,obj,_,_) | Sarray(l,obj,_) -> M.domain obj l let domain (r:region) = List.fold_left (fun d (obj,slocs) -> List.fold_left (fun d sloc -> Dom.union d (dsloc obj sloc)) d slocs ) Dom.empty r (* -------------------------------------------------------------------------- *) (* --- Assignation --- *) (* -------------------------------------------------------------------------- *) let rec assigned_seq hs s = function | [] -> Bag.concat (M.Sigma.assigned s.pre s.post Dom.empty) hs | [obj,sloc] -> let hs_sloc = Bag.list (M.assigned s obj sloc) in let hs_sdom = M.Sigma.assigned s.pre s.post (dsloc obj sloc) in Bag.concat (Bag.concat hs_sloc hs_sdom) hs | (obj,sloc)::tail -> let sigma = M.Sigma.havoc s.post (dsloc obj sloc) in let s_local = { pre = sigma ; post = s.post } in let s_other = { pre = s.pre ; post = sigma } in let hs_sloc = Bag.list (M.assigned s_local obj sloc) in assigned_seq (Bag.concat hs_sloc hs) s_other tail let assigned (s:M.sigma sequence) (r:region) = let hs = assigned_seq Bag.empty s begin List.fold_left (fun w (obj,slocs) -> List.fold_left (fun w sloc -> (obj,sloc) :: w) w slocs ) [] r end in Bag.elements hs end
null
https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/plugins/wp/LogicAssigns.ml
ocaml
************************************************************************ ************************************************************************ ************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ -------------------------------------------------------------------------- --- Domain --- -------------------------------------------------------------------------- -------------------------------------------------------------------------- --- Assignation --- --------------------------------------------------------------------------
This file is part of . is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 is released under GPLv2 This file is part of WP plug - in of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat a l'energie atomique et aux energies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . open Ctypes open Lang open Lang.F open Memory module type Code = sig type loc val equal_obj : c_object -> loc value -> loc value -> F.pred end module type Logic = sig type loc val vars : loc Memory.sloc list -> Vars.t val pp_logic : Format.formatter -> loc Memory.logic -> unit val pp_sloc : Format.formatter -> loc Memory.sloc -> unit val pp_region : Format.formatter -> loc Memory.sloc list -> unit end module Make ( M : Memory.Model ) ( C : Code with type loc = M.loc ) ( L : Logic with type loc = M.loc ) = struct module Dom = M.Heap.Set type region = (c_object * M.loc sloc list) list let vars (r:region) = List.fold_left (fun xs (_,s) -> Vars.union xs (L.vars s)) Vars.empty r let dsloc obj = function | Sloc l | Sdescr(_,l,_) -> M.domain obj l | Srange(l,obj,_,_) | Sarray(l,obj,_) -> M.domain obj l let domain (r:region) = List.fold_left (fun d (obj,slocs) -> List.fold_left (fun d sloc -> Dom.union d (dsloc obj sloc)) d slocs ) Dom.empty r let rec assigned_seq hs s = function | [] -> Bag.concat (M.Sigma.assigned s.pre s.post Dom.empty) hs | [obj,sloc] -> let hs_sloc = Bag.list (M.assigned s obj sloc) in let hs_sdom = M.Sigma.assigned s.pre s.post (dsloc obj sloc) in Bag.concat (Bag.concat hs_sloc hs_sdom) hs | (obj,sloc)::tail -> let sigma = M.Sigma.havoc s.post (dsloc obj sloc) in let s_local = { pre = sigma ; post = s.post } in let s_other = { pre = s.pre ; post = sigma } in let hs_sloc = Bag.list (M.assigned s_local obj sloc) in assigned_seq (Bag.concat hs_sloc hs) s_other tail let assigned (s:M.sigma sequence) (r:region) = let hs = assigned_seq Bag.empty s begin List.fold_left (fun w (obj,slocs) -> List.fold_left (fun w sloc -> (obj,sloc) :: w) w slocs ) [] r end in Bag.elements hs end
56c90b3834a2c0ac259a8fa50af1efa1997ee48fe0a11913cb4525782b591a36
penpot/penpot
helpers.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.srepl.helpers "A main namespace for server repl." #_:clj-kondo/ignore (:require [app.auth :refer [derive-password]] [app.common.data :as d] [app.common.exceptions :as ex] [app.common.files.features :as ffeat] [app.common.logging :as l] [app.common.pages :as cp] [app.common.pages.migrations :as pmg] [app.common.pprint :refer [pprint]] [app.common.spec :as us] [app.common.uuid :as uuid] [app.config :as cfg] [app.db :as db] [app.db.sql :as sql] [app.main :refer [system]] [app.rpc.commands.files :as files] [app.rpc.queries.profile :as prof] [app.util.blob :as blob] [app.util.objects-map :as omap] [app.util.pointer-map :as pmap] [app.util.time :as dt] [clojure.spec.alpha :as s] [clojure.stacktrace :as strace] [clojure.walk :as walk] [cuerdas.core :as str] [expound.alpha :as expound])) (def ^:dynamic *conn*) (defn reset-password! "Reset a password to a specific one for a concrete user or all users if email is `:all` keyword." [system & {:keys [email password] :or {password "123123"} :as params}] (us/verify! (contains? params :email) "`email` parameter is mandatory") (db/with-atomic [conn (:app.db/pool system)] (let [password (derive-password password)] (if (= email :all) (db/exec! conn ["update profile set password=?" password]) (let [email (str/lower email)] (db/exec! conn ["update profile set password=? where email=?" password email])))))) (defn reset-file-data! "Hardcode replace of the data of one file." [system id data] (db/with-atomic [conn (:app.db/pool system)] (db/update! conn :file {:data data} {:id id}))) (defn get-file "Get the migrated data of one file." [system id] (-> (:app.db/pool system) (db/get-by-id :file id) (update :data blob/decode) (update :data pmg/migrate-data))) (defn update-file! "Apply a function to the data of one file. Optionally save the changes or not. The function receives the decoded and migrated file data." [system & {:keys [update-fn id save? migrate? inc-revn?] :or {save? false migrate? true inc-revn? true}}] (db/with-atomic [conn (:app.db/pool system)] (let [file (-> (db/get-by-id conn :file id {::db/for-update? true}) (update :features db/decode-pgarray #{}))] (binding [*conn* conn pmap/*tracked* (atom {}) pmap/*load-fn* (partial files/load-pointer conn id) ffeat/*wrap-with-pointer-map-fn* (if (contains? (:features file) "storage/pointer-map") pmap/wrap identity) ffeat/*wrap-with-objects-map-fn* (if (contains? (:features file) "storage/objectd-map") omap/wrap identity)] (let [file (-> file (update :data blob/decode) (cond-> migrate? (update :data pmg/migrate-data)) (update-fn) (cond-> inc-revn? (update :revn inc)))] (when save? (let [features (db/create-array conn "text" (:features file)) data (blob/encode (:data file))] (db/update! conn :file {:data data :revn (:revn file) :features features} {:id id}) (when (contains? (:features file) "storage/pointer-map") (files/persist-pointers! conn id)))) (dissoc file :data)))))) (def ^:private sql:retrieve-files-chunk "SELECT id, name, created_at, data FROM file WHERE created_at < ? AND deleted_at is NULL ORDER BY created_at desc LIMIT ?") (defn analyze-files "Apply a function to all files in the database, reading them in batches. Do not change data. The `on-file` parameter should be a function that receives the file and the previous state and returns the new state." [system & {:keys [chunk-size max-items start-at on-file on-error on-end] :or {chunk-size 10 max-items Long/MAX_VALUE}}] (letfn [(get-chunk [conn cursor] (let [rows (db/exec! conn [sql:retrieve-files-chunk cursor chunk-size])] [(some->> rows peek :created-at) (seq rows)])) (get-candidates [conn] (->> (d/iteration (partial get-chunk conn) :vf second :kf first :initk (or start-at (dt/now))) (take max-items) (map #(update % :data blob/decode)))) (on-error* [file cause] (println "unexpected exception happened on processing file: " (:id file)) (strace/print-stack-trace cause))] (db/with-atomic [conn (:app.db/pool system)] (loop [state {} files (get-candidates conn)] (if-let [file (first files)] (let [state' (try (on-file file state) (catch Throwable cause (let [on-error (or on-error on-error*)] (on-error file cause))))] (recur (or state' state) (rest files))) (if (fn? on-end) (on-end state) state)))))) (defn update-pages "Apply a function to all pages of one file. The function receives a page and returns an updated page." [data f] (update data :pages-index update-vals f)) (defn update-shapes "Apply a function to all shapes of one page The function receives a shape and returns an updated shape" [page f] (update page :objects update-vals f))
null
https://raw.githubusercontent.com/penpot/penpot/42e97f8be105af41757f8e896b93a99032a2b72a/backend/src/app/srepl/helpers.clj
clojure
Copyright (c) KALEIDOS INC
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.srepl.helpers "A main namespace for server repl." #_:clj-kondo/ignore (:require [app.auth :refer [derive-password]] [app.common.data :as d] [app.common.exceptions :as ex] [app.common.files.features :as ffeat] [app.common.logging :as l] [app.common.pages :as cp] [app.common.pages.migrations :as pmg] [app.common.pprint :refer [pprint]] [app.common.spec :as us] [app.common.uuid :as uuid] [app.config :as cfg] [app.db :as db] [app.db.sql :as sql] [app.main :refer [system]] [app.rpc.commands.files :as files] [app.rpc.queries.profile :as prof] [app.util.blob :as blob] [app.util.objects-map :as omap] [app.util.pointer-map :as pmap] [app.util.time :as dt] [clojure.spec.alpha :as s] [clojure.stacktrace :as strace] [clojure.walk :as walk] [cuerdas.core :as str] [expound.alpha :as expound])) (def ^:dynamic *conn*) (defn reset-password! "Reset a password to a specific one for a concrete user or all users if email is `:all` keyword." [system & {:keys [email password] :or {password "123123"} :as params}] (us/verify! (contains? params :email) "`email` parameter is mandatory") (db/with-atomic [conn (:app.db/pool system)] (let [password (derive-password password)] (if (= email :all) (db/exec! conn ["update profile set password=?" password]) (let [email (str/lower email)] (db/exec! conn ["update profile set password=? where email=?" password email])))))) (defn reset-file-data! "Hardcode replace of the data of one file." [system id data] (db/with-atomic [conn (:app.db/pool system)] (db/update! conn :file {:data data} {:id id}))) (defn get-file "Get the migrated data of one file." [system id] (-> (:app.db/pool system) (db/get-by-id :file id) (update :data blob/decode) (update :data pmg/migrate-data))) (defn update-file! "Apply a function to the data of one file. Optionally save the changes or not. The function receives the decoded and migrated file data." [system & {:keys [update-fn id save? migrate? inc-revn?] :or {save? false migrate? true inc-revn? true}}] (db/with-atomic [conn (:app.db/pool system)] (let [file (-> (db/get-by-id conn :file id {::db/for-update? true}) (update :features db/decode-pgarray #{}))] (binding [*conn* conn pmap/*tracked* (atom {}) pmap/*load-fn* (partial files/load-pointer conn id) ffeat/*wrap-with-pointer-map-fn* (if (contains? (:features file) "storage/pointer-map") pmap/wrap identity) ffeat/*wrap-with-objects-map-fn* (if (contains? (:features file) "storage/objectd-map") omap/wrap identity)] (let [file (-> file (update :data blob/decode) (cond-> migrate? (update :data pmg/migrate-data)) (update-fn) (cond-> inc-revn? (update :revn inc)))] (when save? (let [features (db/create-array conn "text" (:features file)) data (blob/encode (:data file))] (db/update! conn :file {:data data :revn (:revn file) :features features} {:id id}) (when (contains? (:features file) "storage/pointer-map") (files/persist-pointers! conn id)))) (dissoc file :data)))))) (def ^:private sql:retrieve-files-chunk "SELECT id, name, created_at, data FROM file WHERE created_at < ? AND deleted_at is NULL ORDER BY created_at desc LIMIT ?") (defn analyze-files "Apply a function to all files in the database, reading them in batches. Do not change data. The `on-file` parameter should be a function that receives the file and the previous state and returns the new state." [system & {:keys [chunk-size max-items start-at on-file on-error on-end] :or {chunk-size 10 max-items Long/MAX_VALUE}}] (letfn [(get-chunk [conn cursor] (let [rows (db/exec! conn [sql:retrieve-files-chunk cursor chunk-size])] [(some->> rows peek :created-at) (seq rows)])) (get-candidates [conn] (->> (d/iteration (partial get-chunk conn) :vf second :kf first :initk (or start-at (dt/now))) (take max-items) (map #(update % :data blob/decode)))) (on-error* [file cause] (println "unexpected exception happened on processing file: " (:id file)) (strace/print-stack-trace cause))] (db/with-atomic [conn (:app.db/pool system)] (loop [state {} files (get-candidates conn)] (if-let [file (first files)] (let [state' (try (on-file file state) (catch Throwable cause (let [on-error (or on-error on-error*)] (on-error file cause))))] (recur (or state' state) (rest files))) (if (fn? on-end) (on-end state) state)))))) (defn update-pages "Apply a function to all pages of one file. The function receives a page and returns an updated page." [data f] (update data :pages-index update-vals f)) (defn update-shapes "Apply a function to all shapes of one page The function receives a shape and returns an updated shape" [page f] (update page :objects update-vals f))
7c2bf5abee59c29c8bba4cfcb5be3aa7a317aa4caa05973a5bf078de2c288f1f
isovector/dynahaskell
Typecheck.hs
# LANGUAGE TemplateHaskell # module Sem.Typecheck where import Types import Polysemy import GHC import HIE.Bios import Printers data Typecheck m a where Typecheck :: Source -> Typecheck m (Maybe TypecheckedModule) makeSem ''Typecheck runTypechecker :: Members '[Embed Ghc, Embed IO] r => Sem (Typecheck ': r) a -> Sem r a runTypechecker = interpret \case Typecheck src -> do embed $ writeFile "/tmp/dyna.hs" $ mconcat [ "{-# OPTIONS_GHC -fdefer-type-errors #-}\n" , prettySource src ] fmap (fmap fst) $ embed $ loadFile @Ghc ("/tmp/dyna.hs", "/tmp/dyna.hs")
null
https://raw.githubusercontent.com/isovector/dynahaskell/50819888fa118e123f45d98d3d135e611f4b0c35/src/Sem/Typecheck.hs
haskell
# LANGUAGE TemplateHaskell # module Sem.Typecheck where import Types import Polysemy import GHC import HIE.Bios import Printers data Typecheck m a where Typecheck :: Source -> Typecheck m (Maybe TypecheckedModule) makeSem ''Typecheck runTypechecker :: Members '[Embed Ghc, Embed IO] r => Sem (Typecheck ': r) a -> Sem r a runTypechecker = interpret \case Typecheck src -> do embed $ writeFile "/tmp/dyna.hs" $ mconcat [ "{-# OPTIONS_GHC -fdefer-type-errors #-}\n" , prettySource src ] fmap (fmap fst) $ embed $ loadFile @Ghc ("/tmp/dyna.hs", "/tmp/dyna.hs")
a9482ce5eb1bea0d75903220ab8983beb1353f98057a1d132c65f54deed91a64
metaocaml/ber-metaocaml
mod_use.ml
TEST files = " mod.ml " * expect files = "mod.ml" * expect *) #mod_use "mod.ml" [%%expect {| module Mod : sig val answer : int end |}];;
null
https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/testsuite/tests/tool-toplevel/mod_use.ml
ocaml
TEST files = " mod.ml " * expect files = "mod.ml" * expect *) #mod_use "mod.ml" [%%expect {| module Mod : sig val answer : int end |}];;
35876f1ba1fb3439377d7576c8cca9432a9210507b4c8a19d126d1f062fb067d
2600hz/kazoo
webhooks_channel_answer.erl
%%%----------------------------------------------------------------------------- ( C ) 2010 - 2020 , 2600Hz %%% %%% This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %%% %%% @end %%%----------------------------------------------------------------------------- -module(webhooks_channel_answer). -export([init/0 ,bindings_and_responders/0 ]). -include("webhooks.hrl"). -define(ID, kz_term:to_binary(?MODULE)). -define(NAME, <<"Channel Answer">>). -define(DESC, <<"This webhook is triggered when a channel establishes two-way audio, such as a voicemail box or the called party answering">>). -define(METADATA ,kz_json:from_list([{<<"_id">>, ?ID} ,{<<"name">>, ?NAME} ,{<<"description">>, ?DESC} ]) ). -spec init() -> 'ok'. init() -> webhooks_util:init_metadata(?ID, ?METADATA). -spec bindings_and_responders() -> {gen_listener:bindings(), gen_listener:responders()}. bindings_and_responders() -> {bindings(), responders()}. -spec bindings() -> gen_listener:bindings(). bindings() -> [{'call', [{'restrict_to', ['CHANNEL_ANSWER']}]}]. -spec responders() -> gen_listener:responders(). responders() -> [{{'webhooks_channel_util', 'handle_event'} ,[{<<"call_event">>, <<"CHANNEL_ANSWER">>}] } ].
null
https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/applications/webhooks/src/modules/webhooks_channel_answer.erl
erlang
----------------------------------------------------------------------------- @end -----------------------------------------------------------------------------
( C ) 2010 - 2020 , 2600Hz This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. -module(webhooks_channel_answer). -export([init/0 ,bindings_and_responders/0 ]). -include("webhooks.hrl"). -define(ID, kz_term:to_binary(?MODULE)). -define(NAME, <<"Channel Answer">>). -define(DESC, <<"This webhook is triggered when a channel establishes two-way audio, such as a voicemail box or the called party answering">>). -define(METADATA ,kz_json:from_list([{<<"_id">>, ?ID} ,{<<"name">>, ?NAME} ,{<<"description">>, ?DESC} ]) ). -spec init() -> 'ok'. init() -> webhooks_util:init_metadata(?ID, ?METADATA). -spec bindings_and_responders() -> {gen_listener:bindings(), gen_listener:responders()}. bindings_and_responders() -> {bindings(), responders()}. -spec bindings() -> gen_listener:bindings(). bindings() -> [{'call', [{'restrict_to', ['CHANNEL_ANSWER']}]}]. -spec responders() -> gen_listener:responders(). responders() -> [{{'webhooks_channel_util', 'handle_event'} ,[{<<"call_event">>, <<"CHANNEL_ANSWER">>}] } ].
fd579145eb8f33eb9d45768693de48e6e5051c0c845d5aeb3532d0442b40422e
killy971/hpc-coveralls
HpcCoverallsCmdLine.hs
{-# LANGUAGE DeriveDataTypeable #-} module HpcCoverallsCmdLine where import Data.List import Data.Version (Version(..)) import Paths_hpc_coveralls (version) import System.Console.CmdArgs import Trace.Hpc.Coveralls.Types data HpcCoverallsArgs = CmdMain { optExcludeDirs :: [String] , argTestSuites :: [String] , optCabalFile :: Maybe String , optServiceName :: Maybe String , optRepoToken :: Maybe String , optDisplayReport :: Bool , optCurlVerbose :: Bool , optDontSend :: Bool , optCoverageMode :: CoverageMode } deriving (Data, Show, Typeable) hpcCoverallsArgs :: HpcCoverallsArgs hpcCoverallsArgs = CmdMain { optExcludeDirs = [] &= explicit &= typDir &= name "exclude-dir" &= help "Exclude sources files under the matching directory from the coverage report" , optDisplayReport = False &= explicit &= name "display-report" &= help "Display the json code coverage report that will be sent to coveralls.io" , optCurlVerbose = False &= explicit &= name "curl-verbose" &= help "Enable curl verbose mode and prints the json response received from coveralls.io" , optDontSend = False &= explicit &= name "dont-send" &= help "Do not send the report to coveralls.io" , optCoverageMode = AllowPartialLines &= explicit &= typ "MODE" &= name "coverage-mode" &= help "Coverage conversion mode: AllowPartialLines (default), StrictlyFullLines" , optCabalFile = Nothing &= explicit &= typ "FILE" &= name "cabal-file" &= help "Cabal file (ex.: module-name.cabal)" , optServiceName = Nothing &= explicit &= typ "TOKEN" &= name "service-name" &= help "service-name (e.g. travis-pro)" , optRepoToken = Nothing &= explicit &= typ "TOKEN" &= name "repo-token" &= help "Coveralls repo token" , argTestSuites = [] &= typ "TEST-SUITES" &= args } &= summary ("hpc-coveralls v" ++ versionString version ++ ", (C) Guillaume Nargeot 2014-2015") &= program "hpc-coveralls" where versionString = intercalate "." . map show . versionBranch
null
https://raw.githubusercontent.com/killy971/hpc-coveralls/04fe42c4533b3244e9fa1c2772aa5e30baf5eef0/src/HpcCoverallsCmdLine.hs
haskell
# LANGUAGE DeriveDataTypeable #
module HpcCoverallsCmdLine where import Data.List import Data.Version (Version(..)) import Paths_hpc_coveralls (version) import System.Console.CmdArgs import Trace.Hpc.Coveralls.Types data HpcCoverallsArgs = CmdMain { optExcludeDirs :: [String] , argTestSuites :: [String] , optCabalFile :: Maybe String , optServiceName :: Maybe String , optRepoToken :: Maybe String , optDisplayReport :: Bool , optCurlVerbose :: Bool , optDontSend :: Bool , optCoverageMode :: CoverageMode } deriving (Data, Show, Typeable) hpcCoverallsArgs :: HpcCoverallsArgs hpcCoverallsArgs = CmdMain { optExcludeDirs = [] &= explicit &= typDir &= name "exclude-dir" &= help "Exclude sources files under the matching directory from the coverage report" , optDisplayReport = False &= explicit &= name "display-report" &= help "Display the json code coverage report that will be sent to coveralls.io" , optCurlVerbose = False &= explicit &= name "curl-verbose" &= help "Enable curl verbose mode and prints the json response received from coveralls.io" , optDontSend = False &= explicit &= name "dont-send" &= help "Do not send the report to coveralls.io" , optCoverageMode = AllowPartialLines &= explicit &= typ "MODE" &= name "coverage-mode" &= help "Coverage conversion mode: AllowPartialLines (default), StrictlyFullLines" , optCabalFile = Nothing &= explicit &= typ "FILE" &= name "cabal-file" &= help "Cabal file (ex.: module-name.cabal)" , optServiceName = Nothing &= explicit &= typ "TOKEN" &= name "service-name" &= help "service-name (e.g. travis-pro)" , optRepoToken = Nothing &= explicit &= typ "TOKEN" &= name "repo-token" &= help "Coveralls repo token" , argTestSuites = [] &= typ "TEST-SUITES" &= args } &= summary ("hpc-coveralls v" ++ versionString version ++ ", (C) Guillaume Nargeot 2014-2015") &= program "hpc-coveralls" where versionString = intercalate "." . map show . versionBranch
a1735c094d12b2c1a5cb93a4a34d889770fc89035b5acc819c90b089405e3116
gcv/appengine-magic
core_google.clj
(in-ns 'appengine-magic.core) (import '[java.io File FileInputStream BufferedInputStream]) (defn appengine-base-url [& {:keys [https?] :or {https? false}}] (when (= :dev-appserver (appengine-environment-type)) (throw (RuntimeException. "appengine-magic.core/appengine-base-url not supported in dev-appserver.sh"))) (str (if https? "https" "http") "://" (appengine-app-id) ".appspot.com")) (defmacro def-appengine-app [app-var-name handler & [args]] `(def ~app-var-name ~handler))
null
https://raw.githubusercontent.com/gcv/appengine-magic/facc9fe4945b3becd772d6b053844e572dcc1c73/src/appengine_magic/core_google.clj
clojure
(in-ns 'appengine-magic.core) (import '[java.io File FileInputStream BufferedInputStream]) (defn appengine-base-url [& {:keys [https?] :or {https? false}}] (when (= :dev-appserver (appengine-environment-type)) (throw (RuntimeException. "appengine-magic.core/appengine-base-url not supported in dev-appserver.sh"))) (str (if https? "https" "http") "://" (appengine-app-id) ".appspot.com")) (defmacro def-appengine-app [app-var-name handler & [args]] `(def ~app-var-name ~handler))
44ef29f929ab44d8b075099c033c61023ed616275149461abfcbff1b0b2695a2
fccm/glMLite
accanti.ml
Copyright ( c ) , 1994 . ( c ) Copyright 1993 , Silicon Graphics , Inc. * ALL RIGHTS RESERVED * Permission to use , copy , modify , and distribute this software for * any purpose and without fee is hereby granted , provided that the above * copyright notice appear in all copies and that both the copyright notice * and this permission notice appear in supporting documentation , and that * the name of Silicon Graphics , Inc. not be used in advertising * or publicity pertaining to distribution of the software without specific , * written prior permission . * * THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU " AS - IS " * AND WITHOUT WARRANTY OF ANY KIND , EXPRESS , IMPLIED OR OTHERWISE , * INCLUDING WITHOUT LIMITATION , ANY WARRANTY OF MERCHANTABILITY OR * FITNESS FOR A PARTICULAR PURPOSE . IN NO EVENT SHALL SILICON * GRAPHICS , INC . BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT , * SPECIAL , INCIDENTAL , INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY * KIND , OR ANY DAMAGES WHATSOEVER , INCLUDING WITHOUT LIMITATION , * LOSS OF PROFIT , LOSS OF USE , SAVINGS OR REVENUE , OR THE CLAIMS OF * THIRD PARTIES , WHETHER OR NOT SILICON GRAPHICS , INC . HAS * ADVISED OF THE POSSIBILITY OF SUCH LOSS , HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY , ARISING OUT OF OR IN CONNECTION WITH THE * POSSESSION , USE OR PERFORMANCE OF THIS SOFTWARE . * * US Government Users Restricted Rights * Use , duplication , or disclosure by the Government is subject to * restrictions set forth in FAR 52.227.19(c)(2 ) or subparagraph * ( c)(1)(ii ) of the Rights in Technical Data and Computer Software * clause at DFARS 252.227 - 7013 and/or in similar or successor * clauses in the FAR or the DOD or NASA FAR Supplement . * Unpublished-- rights reserved under the copyright laws of the * United States . Contractor / manufacturer is Silicon Graphics , * Inc. , 2011 N. Shoreline Blvd . , Mountain View , CA 94039 - 7311 . * * OpenGL(TM ) is a trademark of Silicon Graphics , Inc. * ALL RIGHTS RESERVED * Permission to use, copy, modify, and distribute this software for * any purpose and without fee is hereby granted, provided that the above * copyright notice appear in all copies and that both the copyright notice * and this permission notice appear in supporting documentation, and that * the name of Silicon Graphics, Inc. not be used in advertising * or publicity pertaining to distribution of the software without specific, * written prior permission. * * THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS" * AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE, * INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR * FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON * GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT, * SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY * KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION, * LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF * THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN * ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE * POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE. * * US Government Users Restricted Rights * Use, duplication, or disclosure by the Government is subject to * restrictions set forth in FAR 52.227.19(c)(2) or subparagraph * (c)(1)(ii) of the Rights in Technical Data and Computer Software * clause at DFARS 252.227-7013 and/or in similar or successor * clauses in the FAR or the DOD or NASA FAR Supplement. * Unpublished-- rights reserved under the copyright laws of the * United States. Contractor/manufacturer is Silicon Graphics, * Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311. * * OpenGL(TM) is a trademark of Silicon Graphics, Inc. *) (* accanti.ml *) open GL open Glu open Glut jitter This is jitter point array for 8 jitters . Values are floating point in the range -.5 < x < .5 , -.5 < y < .5 , and have a gaussian distribution around the origin . This is used to do model jittering for scene anti - aliasing and view volume jittering for depth of field effects . Use in conjunction with the accwindow ( ) routine . This is jitter point array for 8 jitters. Values are floating point in the range -.5 < x < .5, -.5 < y < .5, and have a gaussian distribution around the origin. This is used to do model jittering for scene anti-aliasing and view volume jittering for depth of field effects. Use in conjunction with the accwindow() routine. *) type jitter_point = { x: float; y: float } 8 jitter points let j8 = [| {x = -0.334818; y = 0.435331}; {x = 0.286438; y = -0.393495}; {x = 0.459462; y = 0.141540}; {x = -0.414498; y = -0.192829}; {x = -0.183790; y = 0.082102}; {x = -0.079263; y = -0.317383}; {x = 0.102254; y = 0.299133}; {x = 0.164216; y = -0.054399}; |] ;; Initialize lighting and other values . *) let myinit() = let mat_ambient = (1.0, 1.0, 1.0, 1.0) and mat_specular = (1.0, 1.0, 1.0, 1.0) and light_position = (0.0, 0.0, 10.0, 1.0) and lm_ambient = (0.2, 0.2, 0.2, 1.0) in glMaterial GL_FRONT (Material.GL_AMBIENT mat_ambient); glMaterial GL_FRONT (Material.GL_SPECULAR mat_specular); glMaterial GL_FRONT (Material.GL_SHININESS 50.0); glLight (GL_LIGHT 0) (Light.GL_POSITION light_position); glLightModel (GL_LIGHT_MODEL_AMBIENT lm_ambient); glEnable GL_LIGHTING; glEnable GL_LIGHT0; glDepthFunc GL_LESS; glEnable GL_DEPTH_TEST; glShadeModel GL_FLAT; glClearColor 0.0 0.0 0.0 0.0; glClearAccum 0.0 0.0 0.0 0.0; ;; let displayObjects() = let torus_diffuse = (0.7, 0.7, 0.0, 1.0) and cube_diffuse = (0.0, 0.7, 0.7, 1.0) and sphere_diffuse = (0.7, 0.0, 0.7, 1.0) and octa_diffuse = (0.7, 0.4, 0.4, 1.0) in glPushMatrix (); glRotate 30.0 1.0 0.0 0.0; glPushMatrix (); glTranslate (-0.80) (0.35) (0.0); glRotate 100.0 1.0 0.0 0.0; glMaterial GL_FRONT (Material.GL_DIFFUSE torus_diffuse); glutSolidTorus 0.275 0.85 16 16; glPopMatrix (); glPushMatrix (); glTranslate (-0.75) (-0.50) (0.0); glRotate 45.0 0.0 0.0 1.0; glRotate 45.0 1.0 0.0 0.0; glMaterial GL_FRONT (Material.GL_DIFFUSE cube_diffuse); glutSolidCube 1.5; glPopMatrix (); glPushMatrix (); glTranslate 0.75 0.60 0.0; glRotate 30.0 1.0 0.0 0.0; glMaterial GL_FRONT (Material.GL_DIFFUSE sphere_diffuse); glutSolidSphere 1.0 16 16; glPopMatrix (); glPushMatrix (); glTranslate (0.70) (-0.90) (0.25); glMaterial GL_FRONT (Material.GL_DIFFUSE octa_diffuse); glutSolidOctahedron (); glPopMatrix (); glPopMatrix (); ;; let display() = let _, _, viewport2, viewport3 = glGetInteger4 Get.GL_VIEWPORT in glClear [GL_ACCUM_BUFFER_BIT]; Array.iter (fun j -> glClear [GL_COLOR_BUFFER_BIT; GL_DEPTH_BUFFER_BIT]; glPushMatrix (); Note that 4.5 is the distance in world space between * left and right and bottom and top . * This formula converts fractional pixel movement to * world coordinates . * left and right and bottom and top. * This formula converts fractional pixel movement to * world coordinates. *) glTranslate (j.x *. 4.5 /. float viewport2) (j.y *. 4.5 /. float viewport3) 0.0; displayObjects (); glPopMatrix (); glAccum GL_ACCUM (1.0 /. float(Array.length j8)); ) j8; glAccum GL_RETURN 1.0; glFlush(); ;; let reshape ~width:w ~height:h = glViewport 0 0 w h; glMatrixMode GL_PROJECTION; glLoadIdentity(); let w = float w and h = float h in if w <= h then glOrtho (-2.25) (2.25) (-2.25 *. h /. w) (2.25 *. h /. w) (-10.0) (10.0) else glOrtho (-2.25 *. w /. h) (2.25 *. w /. h) (-2.25) (2.25) (-10.0) (10.0); glMatrixMode GL_MODELVIEW; ;; let keyboard ~key ~x ~y = begin match key with | '\027' -> (* Escape *) exit(0); | _ -> () end; glutPostRedisplay(); ;; Main Loop * Open window with initial window size , title bar , * RGBA display mode , and handle input events . * Open window with initial window size, title bar, * RGBA display mode, and handle input events. *) let () = let _ = glutInit Sys.argv in glutInitDisplayMode [GLUT_SINGLE; GLUT_RGB; GLUT_ACCUM; GLUT_DEPTH]; glutInitWindowSize 250 250; let _ = glutCreateWindow Sys.argv.(0) in myinit(); glutReshapeFunc ~reshape; glutDisplayFunc ~display; glutKeyboardFunc ~keyboard; glutMainLoop(); ;;
null
https://raw.githubusercontent.com/fccm/glMLite/c52cd806909581e49d9b660195576c8a932f6d33/RedBook-Samples/accanti.ml
ocaml
accanti.ml Escape
Copyright ( c ) , 1994 . ( c ) Copyright 1993 , Silicon Graphics , Inc. * ALL RIGHTS RESERVED * Permission to use , copy , modify , and distribute this software for * any purpose and without fee is hereby granted , provided that the above * copyright notice appear in all copies and that both the copyright notice * and this permission notice appear in supporting documentation , and that * the name of Silicon Graphics , Inc. not be used in advertising * or publicity pertaining to distribution of the software without specific , * written prior permission . * * THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU " AS - IS " * AND WITHOUT WARRANTY OF ANY KIND , EXPRESS , IMPLIED OR OTHERWISE , * INCLUDING WITHOUT LIMITATION , ANY WARRANTY OF MERCHANTABILITY OR * FITNESS FOR A PARTICULAR PURPOSE . IN NO EVENT SHALL SILICON * GRAPHICS , INC . BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT , * SPECIAL , INCIDENTAL , INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY * KIND , OR ANY DAMAGES WHATSOEVER , INCLUDING WITHOUT LIMITATION , * LOSS OF PROFIT , LOSS OF USE , SAVINGS OR REVENUE , OR THE CLAIMS OF * THIRD PARTIES , WHETHER OR NOT SILICON GRAPHICS , INC . HAS * ADVISED OF THE POSSIBILITY OF SUCH LOSS , HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY , ARISING OUT OF OR IN CONNECTION WITH THE * POSSESSION , USE OR PERFORMANCE OF THIS SOFTWARE . * * US Government Users Restricted Rights * Use , duplication , or disclosure by the Government is subject to * restrictions set forth in FAR 52.227.19(c)(2 ) or subparagraph * ( c)(1)(ii ) of the Rights in Technical Data and Computer Software * clause at DFARS 252.227 - 7013 and/or in similar or successor * clauses in the FAR or the DOD or NASA FAR Supplement . * Unpublished-- rights reserved under the copyright laws of the * United States . Contractor / manufacturer is Silicon Graphics , * Inc. , 2011 N. Shoreline Blvd . , Mountain View , CA 94039 - 7311 . * * OpenGL(TM ) is a trademark of Silicon Graphics , Inc. * ALL RIGHTS RESERVED * Permission to use, copy, modify, and distribute this software for * any purpose and without fee is hereby granted, provided that the above * copyright notice appear in all copies and that both the copyright notice * and this permission notice appear in supporting documentation, and that * the name of Silicon Graphics, Inc. not be used in advertising * or publicity pertaining to distribution of the software without specific, * written prior permission. * * THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS" * AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE, * INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR * FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON * GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT, * SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY * KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION, * LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF * THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN * ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE * POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE. * * US Government Users Restricted Rights * Use, duplication, or disclosure by the Government is subject to * restrictions set forth in FAR 52.227.19(c)(2) or subparagraph * (c)(1)(ii) of the Rights in Technical Data and Computer Software * clause at DFARS 252.227-7013 and/or in similar or successor * clauses in the FAR or the DOD or NASA FAR Supplement. * Unpublished-- rights reserved under the copyright laws of the * United States. Contractor/manufacturer is Silicon Graphics, * Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311. * * OpenGL(TM) is a trademark of Silicon Graphics, Inc. *) open GL open Glu open Glut jitter This is jitter point array for 8 jitters . Values are floating point in the range -.5 < x < .5 , -.5 < y < .5 , and have a gaussian distribution around the origin . This is used to do model jittering for scene anti - aliasing and view volume jittering for depth of field effects . Use in conjunction with the accwindow ( ) routine . This is jitter point array for 8 jitters. Values are floating point in the range -.5 < x < .5, -.5 < y < .5, and have a gaussian distribution around the origin. This is used to do model jittering for scene anti-aliasing and view volume jittering for depth of field effects. Use in conjunction with the accwindow() routine. *) type jitter_point = { x: float; y: float } 8 jitter points let j8 = [| {x = -0.334818; y = 0.435331}; {x = 0.286438; y = -0.393495}; {x = 0.459462; y = 0.141540}; {x = -0.414498; y = -0.192829}; {x = -0.183790; y = 0.082102}; {x = -0.079263; y = -0.317383}; {x = 0.102254; y = 0.299133}; {x = 0.164216; y = -0.054399}; |] ;; Initialize lighting and other values . *) let myinit() = let mat_ambient = (1.0, 1.0, 1.0, 1.0) and mat_specular = (1.0, 1.0, 1.0, 1.0) and light_position = (0.0, 0.0, 10.0, 1.0) and lm_ambient = (0.2, 0.2, 0.2, 1.0) in glMaterial GL_FRONT (Material.GL_AMBIENT mat_ambient); glMaterial GL_FRONT (Material.GL_SPECULAR mat_specular); glMaterial GL_FRONT (Material.GL_SHININESS 50.0); glLight (GL_LIGHT 0) (Light.GL_POSITION light_position); glLightModel (GL_LIGHT_MODEL_AMBIENT lm_ambient); glEnable GL_LIGHTING; glEnable GL_LIGHT0; glDepthFunc GL_LESS; glEnable GL_DEPTH_TEST; glShadeModel GL_FLAT; glClearColor 0.0 0.0 0.0 0.0; glClearAccum 0.0 0.0 0.0 0.0; ;; let displayObjects() = let torus_diffuse = (0.7, 0.7, 0.0, 1.0) and cube_diffuse = (0.0, 0.7, 0.7, 1.0) and sphere_diffuse = (0.7, 0.0, 0.7, 1.0) and octa_diffuse = (0.7, 0.4, 0.4, 1.0) in glPushMatrix (); glRotate 30.0 1.0 0.0 0.0; glPushMatrix (); glTranslate (-0.80) (0.35) (0.0); glRotate 100.0 1.0 0.0 0.0; glMaterial GL_FRONT (Material.GL_DIFFUSE torus_diffuse); glutSolidTorus 0.275 0.85 16 16; glPopMatrix (); glPushMatrix (); glTranslate (-0.75) (-0.50) (0.0); glRotate 45.0 0.0 0.0 1.0; glRotate 45.0 1.0 0.0 0.0; glMaterial GL_FRONT (Material.GL_DIFFUSE cube_diffuse); glutSolidCube 1.5; glPopMatrix (); glPushMatrix (); glTranslate 0.75 0.60 0.0; glRotate 30.0 1.0 0.0 0.0; glMaterial GL_FRONT (Material.GL_DIFFUSE sphere_diffuse); glutSolidSphere 1.0 16 16; glPopMatrix (); glPushMatrix (); glTranslate (0.70) (-0.90) (0.25); glMaterial GL_FRONT (Material.GL_DIFFUSE octa_diffuse); glutSolidOctahedron (); glPopMatrix (); glPopMatrix (); ;; let display() = let _, _, viewport2, viewport3 = glGetInteger4 Get.GL_VIEWPORT in glClear [GL_ACCUM_BUFFER_BIT]; Array.iter (fun j -> glClear [GL_COLOR_BUFFER_BIT; GL_DEPTH_BUFFER_BIT]; glPushMatrix (); Note that 4.5 is the distance in world space between * left and right and bottom and top . * This formula converts fractional pixel movement to * world coordinates . * left and right and bottom and top. * This formula converts fractional pixel movement to * world coordinates. *) glTranslate (j.x *. 4.5 /. float viewport2) (j.y *. 4.5 /. float viewport3) 0.0; displayObjects (); glPopMatrix (); glAccum GL_ACCUM (1.0 /. float(Array.length j8)); ) j8; glAccum GL_RETURN 1.0; glFlush(); ;; let reshape ~width:w ~height:h = glViewport 0 0 w h; glMatrixMode GL_PROJECTION; glLoadIdentity(); let w = float w and h = float h in if w <= h then glOrtho (-2.25) (2.25) (-2.25 *. h /. w) (2.25 *. h /. w) (-10.0) (10.0) else glOrtho (-2.25 *. w /. h) (2.25 *. w /. h) (-2.25) (2.25) (-10.0) (10.0); glMatrixMode GL_MODELVIEW; ;; let keyboard ~key ~x ~y = begin match key with exit(0); | _ -> () end; glutPostRedisplay(); ;; Main Loop * Open window with initial window size , title bar , * RGBA display mode , and handle input events . * Open window with initial window size, title bar, * RGBA display mode, and handle input events. *) let () = let _ = glutInit Sys.argv in glutInitDisplayMode [GLUT_SINGLE; GLUT_RGB; GLUT_ACCUM; GLUT_DEPTH]; glutInitWindowSize 250 250; let _ = glutCreateWindow Sys.argv.(0) in myinit(); glutReshapeFunc ~reshape; glutDisplayFunc ~display; glutKeyboardFunc ~keyboard; glutMainLoop(); ;;
b1d06f76473c099de0b128f4037dd7da6d9c5c4ef18f4184c8124be84065c1d0
gar1t/modlib
proxy_http.erl
-module(proxy_http). -include("webapp.hrl"). -include("httpd.hrl"). -export([start/1, request/3]). start(Port) -> application:start(inets), modlib:start([{port, Port}, {modules, [?MODULE]}]). request(_, "/favicon.ico", _) -> {not_found, "Not Found"}; request(_Method, _Path, Mod) -> handle_request(Mod). handle_request(Mod) -> Method = httpc_method(Mod), URL = proxy_url(httpc_uri(Mod)), {Headers, ContentType} = httpc_headers(Mod), Body = httpc_body(Mod), handle_response(httpc_request(Method, URL, Headers, ContentType, Body)). httpc_request(Method, URL, Headers, undefined, _) -> httpc_request(Method, {URL, Headers}); httpc_request(Method, URL, Headers, ContentType, Body) -> httpc_request(Method, {URL, Headers, ContentType, Body}). httpc_request(Method, Request) -> error_logger:info_report({proxy_request, {Method, Request}}), httpc:request(Method, Request, [], []). handle_response({ok, {{_, Code, _}, Headers, Body}}) -> {Code, Headers, Body}; handle_response({error, Err}) -> error_logger:error_report({proxy_error, Err}), {500, "Internal Error"}. proxy_url(URI) -> ":8888" ++ URI. httpc_method(#mod{method="POST"}) -> post; httpc_method(#mod{method="GET"}) -> get; httpc_method(#mod{method="DELETE"}) -> delete; httpc_method(#mod{method="PUT"}) -> put; httpc_method(#mod{method="HEAD"}) -> head; httpc_method(_) -> bad_request(). httpc_uri(#mod{request_uri=URI}) -> URI. httpc_headers(#mod{parsed_header=Headers}) -> case lists:keytake("content-type", 1, Headers) of {value, {_, ContentType}, NewHeaders} -> {NewHeaders, ContentType}; false -> {Headers, undefined} end. httpc_body(#mod{entity_body=Body}) -> Body. bad_request() -> throw({badreq, "Bad Request"}).
null
https://raw.githubusercontent.com/gar1t/modlib/e1e0b2aa160a760964a0508283146af81800d098/examples/proxy_http.erl
erlang
-module(proxy_http). -include("webapp.hrl"). -include("httpd.hrl"). -export([start/1, request/3]). start(Port) -> application:start(inets), modlib:start([{port, Port}, {modules, [?MODULE]}]). request(_, "/favicon.ico", _) -> {not_found, "Not Found"}; request(_Method, _Path, Mod) -> handle_request(Mod). handle_request(Mod) -> Method = httpc_method(Mod), URL = proxy_url(httpc_uri(Mod)), {Headers, ContentType} = httpc_headers(Mod), Body = httpc_body(Mod), handle_response(httpc_request(Method, URL, Headers, ContentType, Body)). httpc_request(Method, URL, Headers, undefined, _) -> httpc_request(Method, {URL, Headers}); httpc_request(Method, URL, Headers, ContentType, Body) -> httpc_request(Method, {URL, Headers, ContentType, Body}). httpc_request(Method, Request) -> error_logger:info_report({proxy_request, {Method, Request}}), httpc:request(Method, Request, [], []). handle_response({ok, {{_, Code, _}, Headers, Body}}) -> {Code, Headers, Body}; handle_response({error, Err}) -> error_logger:error_report({proxy_error, Err}), {500, "Internal Error"}. proxy_url(URI) -> ":8888" ++ URI. httpc_method(#mod{method="POST"}) -> post; httpc_method(#mod{method="GET"}) -> get; httpc_method(#mod{method="DELETE"}) -> delete; httpc_method(#mod{method="PUT"}) -> put; httpc_method(#mod{method="HEAD"}) -> head; httpc_method(_) -> bad_request(). httpc_uri(#mod{request_uri=URI}) -> URI. httpc_headers(#mod{parsed_header=Headers}) -> case lists:keytake("content-type", 1, Headers) of {value, {_, ContentType}, NewHeaders} -> {NewHeaders, ContentType}; false -> {Headers, undefined} end. httpc_body(#mod{entity_body=Body}) -> Body. bad_request() -> throw({badreq, "Bad Request"}).
7ed3d74fb57c0dd4998b2a2fa6b2a50acedcb41807b4c45255c7a19feab0ee9e
albertoruiz/easyVision
warp.hs
# LANGUAGE TemplateHaskell , RecordWildCards # import Vision.GUI import Image.Processing import Numeric.LinearAlgebra ((<>)) import Vision(ht,desp,scaling,kgen) import Util.Rotation import Util.Misc(degree) autoParam "CGParam" "cg-" [ ("pan", "Double", realParam (0) (-40) (40)) , ("dx", "Double", realParam (0) (-1) (1)) , ("dy", "Double", realParam (0) (-1) (1)) , ("tilt", "Double", realParam (15) (-30) (30)) , ("roll", "Double", realParam 20 (-40) (40)) , ("focal", "Double", listParam 2.8 [0.5, 0.7, 1, 2, 2.6, 2.8, 5, 5.5, 9,10]) , ("scale", "Double", listParam 0.8 [1.05**k|k<-[-20..20]])] main = run $ arr rgb >>> deskew @@@ winParam >>> observe "warped" id deskew par@CGParam{..} img = warp (Word24 80 0 0) (size img) r img where h = conjugateRotation par [[a,b]] = ht h [[dx,-dy]] r = desp (-a,-b) <> h conjugateRotation CGParam{..} = scaling scale <> kgen focal <> rot1 (tilt*degree) <> rot2 (pan*degree) <> rot3 (roll*degree) <> kgen (1/focal)
null
https://raw.githubusercontent.com/albertoruiz/easyVision/26bb2efaa676c902cecb12047560a09377a969f2/projects/examples/warp.hs
haskell
# LANGUAGE TemplateHaskell , RecordWildCards # import Vision.GUI import Image.Processing import Numeric.LinearAlgebra ((<>)) import Vision(ht,desp,scaling,kgen) import Util.Rotation import Util.Misc(degree) autoParam "CGParam" "cg-" [ ("pan", "Double", realParam (0) (-40) (40)) , ("dx", "Double", realParam (0) (-1) (1)) , ("dy", "Double", realParam (0) (-1) (1)) , ("tilt", "Double", realParam (15) (-30) (30)) , ("roll", "Double", realParam 20 (-40) (40)) , ("focal", "Double", listParam 2.8 [0.5, 0.7, 1, 2, 2.6, 2.8, 5, 5.5, 9,10]) , ("scale", "Double", listParam 0.8 [1.05**k|k<-[-20..20]])] main = run $ arr rgb >>> deskew @@@ winParam >>> observe "warped" id deskew par@CGParam{..} img = warp (Word24 80 0 0) (size img) r img where h = conjugateRotation par [[a,b]] = ht h [[dx,-dy]] r = desp (-a,-b) <> h conjugateRotation CGParam{..} = scaling scale <> kgen focal <> rot1 (tilt*degree) <> rot2 (pan*degree) <> rot3 (roll*degree) <> kgen (1/focal)
25164488ec9fa987042323f9d876c7508112cafc1e39bc2334ce913767127c4e
malcolmreynolds/GSLL
roots-one.lisp
One - dimensional root solver . Time - stamp : < 2009 - 04 - 04 22:27:16EDT roots-one.lisp > $ Id$ (in-package :gsl) /usr / include / gsl / gsl_roots.h ;;;;**************************************************************************** ;;;; Initialization ;;;;**************************************************************************** (defmobject one-dimensional-root-solver-f "gsl_root_fsolver" ((type :pointer)) "one-dimensional root solver with function only" :initialize-suffix "set" :initialize-args ((callback :pointer) (lower :double) (upper :double)) :callbacks (callback fnstruct nil (function :double (:input :double) :slug)) :singular (function)) (defmobject one-dimensional-root-solver-fdf "gsl_root_fdfsolver" ((type :pointer)) "one-dimensional root solver with function and derivative" :initialize-suffix "set" :initialize-args ((callback :pointer) (root-guess :double)) :callbacks (callback fnstruct-fdf nil (function :double (:input :double) :slug) (df :double (:input :double) :slug) (fdf :void (:input :double) :slug (:output :double :cvector 1) (:output :double :cvector 1))) :arglists-function (lambda (set) `((type &optional (function nil ,set) df fdf root-guess) (:type type) (:functions (list function df fdf) :root-guess root-guess)))) (defmfun name ((solver one-dimensional-root-solver-f)) "gsl_root_fsolver_name" (((mpointer solver) :pointer)) :definition :method :c-return :string "The name of the solver.") (defmfun name ((solver one-dimensional-root-solver-fdf)) "gsl_root_fdfsolver_name" (((mpointer solver) :pointer)) :definition :method :c-return :string "The name of the solver.") ;;;;**************************************************************************** ;;;; Iteration ;;;;**************************************************************************** It appears that this is always returning : SUCCESS ( 0 ) . (defmfun iterate ((solver one-dimensional-root-solver-f)) "gsl_root_fsolver_iterate" (((mpointer solver) :pointer)) :definition :method :callback-object solver "Perform a single iteration of the solver. The following errors may be signalled: 'bad-function-supplied, the iteration encountered a singular point where the function or its derivative evaluated to infinity or NaN, or 'gsl-division-by-zero, the derivative of the function vanished at the iteration point, preventing the algorithm from continuing without a division by zero.") (defmfun iterate ((solver one-dimensional-root-solver-fdf)) "gsl_root_fdfsolver_iterate" (((mpointer solver) :pointer)) :definition :method :callback-object solver "Perform a single iteration of the solver. The following errors may be signalled: 'bad-function-supplied, the iteration encountered a singular point where the function or its derivative evaluated to infinity or NaN, or 'gsl-division-by-zero, the derivative of the function vanished at the iteration point, preventing the algorithm from continuing without a division by zero.") (defmfun solution ((solver one-dimensional-root-solver-f)) "gsl_root_fsolver_root" (((mpointer solver) :pointer)) :definition :method :c-return :double "The current estimate of the root for the solver.") (defmfun solution ((solver one-dimensional-root-solver-fdf)) "gsl_root_fdfsolver_root" (((mpointer solver) :pointer)) :definition :method :c-return :double "The current estimate of the root for the solver.") (defmfun fsolver-lower (solver) "gsl_root_fsolver_x_lower" (((mpointer solver) :pointer)) :c-return :double "The lower end of the current bracketing interval for the solver.") (defmfun fsolver-upper (solver) "gsl_root_fsolver_x_upper" (((mpointer solver) :pointer)) :c-return :double "The upper end of the current bracketing interval for the solver.") ;;;;**************************************************************************** ;;;; Search stopping conditions ;;;;**************************************************************************** (defmfun root-test-interval (lower upper absolute-error relative-error) "gsl_root_test_interval" ((lower :double) (upper :double) (absolute-error :double) (relative-error :double)) GSL documentation not clear on this "Test for the convergence of the interval [lower,upper] with absolute error absolute-error and relative error relative-error. This returns T if the following condition is achieved, |a - b| < epsabs + epsrel min(|a|,|b|) when the interval x = [a,b] does not include the origin. If the interval includes the origin then min(|a|,|b|) is replaced by zero (which is the minimum value of |x| over the interval). This ensures that the relative error is accurately estimated for roots close to the origin. This condition on the interval also implies that any estimate of the root r in the interval satisfies the same condition with respect to the true root r^*, |r - r^*| < epsabs + epsrel r^* assuming that the true root r^* is contained within the interval.") (defmfun root-test-delta (x1 x0 absolute-error relative-error) "gsl_root_test_delta" ((x1 :double) (x0 :double) (absolute-error :double) (relative-error :double)) :c-return :success-continue "Test for the convergence of the sequence ... x0, x1 with absolute error absolute-error and relative error relative-error. The test returns T if the following condition is achieved, |x_1 - x_0| < epsabs + epsrel |x_1| and returns NIL otherwise.") (defmfun root-test-residual (f absolute-error) "gsl_root_test_residual" ((f :double) (absolute-error :double)) :c-return :success-continue "Tests the residual value f against the absolute error bound absolute-error. The test returns T if the following condition is achieved, |f| < epsabs and returns NIL otherwise. This criterion is suitable for situations where the precise location of the root, x, is unimportant provided a value can be found where the residual, |f(x)|, is small enough.") ;;;;**************************************************************************** ;;;; Root bracketing algorithms ;;;;**************************************************************************** (defmpar +bisection-fsolver+ "gsl_root_fsolver_bisection" "The bisection algorithm is the simplest method of bracketing the roots of a function. It is the slowest algorithm provided by the library, with linear convergence. On each iteration, the interval is bisected and the value of the function at the midpoint is calculated. The sign of this value is used to determine which half of the interval does not contain a root. That half is discarded to give a new, smaller interval containing the root. This procedure can be continued indefinitely until the interval is sufficiently small. At any time the current estimate of the root is taken as the midpoint of the interval.") (defmpar +false-position-fsolver+ "gsl_root_fsolver_falsepos" "The false position algorithm is a method of finding roots based on linear interpolation. Its convergence is linear, but it is usually faster than bisection. On each iteration a line is drawn between the endpoints (a,f(a)) and (b,f(b)) and the point where this line crosses the x-axis taken as a ``midpoint''. The value of the function at this point is calculated and its sign is used to determine which side of the interval does not contain a root. That side is discarded to give a new, smaller interval containing the root. This procedure can be continued indefinitely until the interval is sufficiently small. The best estimate of the root is taken from the linear interpolation of the interval on the current iteration.") (defmpar +brent-fsolver+ "gsl_root_fsolver_brent" "The Brent-Dekker method (referred to here as Brent's method) combines an interpolation strategy with the bisection algorithm. This produces a fast algorithm which is still robust. On each iteration Brent's method approximates the function using an interpolating curve. On the first iteration this is a linear interpolation of the two endpoints. For subsequent iterations the algorithm uses an inverse quadratic fit to the last three points, for higher accuracy. The intercept of the interpolating curve with the x-axis is taken as a guess for the root. If it lies within the bounds of the current interval then the interpolating point is accepted, and used to generate a smaller interval. If the interpolating point is not accepted then the algorithm falls back to an ordinary bisection step. The best estimate of the root is taken from the most recent interpolation or bisection.") ;;;;**************************************************************************** ;;;; Root finding algorithms using derivatives ;;;;**************************************************************************** (defmpar +newton-fdfsolver+ "gsl_root_fdfsolver_newton" "Newton's Method is the standard root-polishing algorithm. The algorithm begins with an initial guess for the location of the root. On each iteration, a line tangent to the function f is drawn at that position. The point where this line crosses the x-axis becomes the new guess. The iteration is defined by the following sequence, x_{i+1} = x_i - f(x_i) / f'(x_i) Newton's method converges quadratically for single roots, and linearly for multiple roots.") (defmpar +secant-fdfsolver+ "gsl_root_fdfsolver_secant" "The secant method is a simplified version of Newton's method which does not require the computation of the derivative on every step. On its first iteration the algorithm begins with Newton's method, using the derivative to compute a first step, x_1 = x_0 - f(x_0)/f'(x_0) Subsequent iterations avoid the evaluation of the derivative by replacing it with a numerical estimate, the slope of the line through the previous two points, x_{i+1} = x_i - f(x_i) / f'_{est} where f'_{est} = f(x_{i}) - f(x_{i-1}) / x_i - x_{i-1} When the derivative does not change significantly in the vicinity of the root the secant method gives a useful saving. Asymptotically the secant method is faster than Newton's method whenever the cost of evaluating the derivative is more than 0.44 times the cost of evaluating the function itself. As with all methods of computing a numerical derivative the estimate can suffer from cancellation errors if the separation of the points becomes too small. On single roots, the method has a convergence of order (1 + \sqrt 5)/2 (approximately 1.62). It converges linearly for multiple roots.") (defmpar +steffenson-fdfsolver+ "gsl_root_fdfsolver_steffenson" "The Steffenson method provides the fastest convergence of all the routines. It combines the basic Newton algorithm with an Aitken ``delta-squared'' acceleration. If the Newton iterates are x_i then the acceleration procedure generates a new sequence R_i, R_i = x_i - (x_{i+1} - x_i)^2 / (x_{i+2} - 2 x_{i+1} + x_i) which converges faster than the original sequence under reasonable conditions. The new sequence requires three terms before it can produce its first value so the method returns accelerated values on the second and subsequent iterations. On the first iteration it returns the ordinary Newton estimate. The Newton iterate is also returned if the denominator of the acceleration term ever becomes zero. As with all acceleration procedures this method can become unstable if the function is not well-behaved.") ;;;;**************************************************************************** ;;;; Examples ;;;;**************************************************************************** This is the example given in Sec . 32.10 . (let ((a 1.0d0) (b 0.0d0) (c -5.0d0)) (defun quadratic (x) (+ (* (+ (* a x) b) x) c)) (defun quadratic-derivative (x) (+ (* 2 a x) b)) (defun quadratic-and-derivative (x) (values (+ (* (+ (* a x) b) x) c) (+ (* 2 a x) b)))) (defun roots-one-example-no-derivative (&optional (method +brent-fsolver+) (print-steps t)) "Solving a quadratic, the example given in Sec. 32.10 of the GSL manual." (let ((max-iter 50) (solver (make-one-dimensional-root-solver-f method 'quadratic 0.0d0 5.0d0))) (when print-steps (format t "iter ~6t [lower ~24tupper] ~36troot ~44terr ~54terr(est)~&")) (loop for iter from 0 for root = (solution solver) for lower = (fsolver-lower solver) for upper = (fsolver-upper solver) do (iterate solver) while (and (< iter max-iter) (not (root-test-interval lower upper 0.0d0 0.001d0))) do (when print-steps (format t "~d~6t~10,6f~18t~10,6f~28t~12,9f ~44t~10,4g ~10,4g~&" iter lower upper root (- root (sqrt 5.0d0)) (- upper lower))) finally (return root)))) (defun roots-one-example-derivative (&optional (method +newton-fdfsolver+) (print-steps t)) "Solving a quadratic, the example given in Sec. 32.10 of the GSL manual." (let* ((max-iter 100) (initial 5.0d0) (solver (make-one-dimensional-root-solver-fdf method 'quadratic 'quadratic-derivative 'quadratic-and-derivative initial))) (when print-steps (format t "iter ~6t ~8troot ~22terr ~34terr(est)~&")) (loop for iter from 0 for oldroot = initial then root for root = (progn (iterate solver) (solution solver)) while (and (< iter max-iter) (not (root-test-delta root oldroot 0.0d0 1.0d-5))) do (when print-steps (format t "~d~6t~10,8g ~18t~10,6g~34t~10,6g~&" iter root (- root (sqrt 5.0d0)) (- root oldroot))) finally (return root)))) ;; To see step-by-step information as the solution progresses, make the last argument (save-test roots-one (roots-one-example-no-derivative +bisection-fsolver+ nil) (roots-one-example-no-derivative +false-position-fsolver+ nil) (roots-one-example-no-derivative +brent-fsolver+ nil) (roots-one-example-derivative +newton-fdfsolver+ nil) (roots-one-example-derivative +secant-fdfsolver+ nil) (roots-one-example-derivative +steffenson-fdfsolver+ nil))
null
https://raw.githubusercontent.com/malcolmreynolds/GSLL/2f722f12f1d08e1b9550a46e2a22adba8e1e52c4/solve-minimize-fit/roots-one.lisp
lisp
**************************************************************************** Initialization **************************************************************************** **************************************************************************** Iteration **************************************************************************** **************************************************************************** Search stopping conditions **************************************************************************** **************************************************************************** Root bracketing algorithms **************************************************************************** **************************************************************************** Root finding algorithms using derivatives **************************************************************************** **************************************************************************** Examples **************************************************************************** To see step-by-step information as the solution progresses, make
One - dimensional root solver . Time - stamp : < 2009 - 04 - 04 22:27:16EDT roots-one.lisp > $ Id$ (in-package :gsl) /usr / include / gsl / gsl_roots.h (defmobject one-dimensional-root-solver-f "gsl_root_fsolver" ((type :pointer)) "one-dimensional root solver with function only" :initialize-suffix "set" :initialize-args ((callback :pointer) (lower :double) (upper :double)) :callbacks (callback fnstruct nil (function :double (:input :double) :slug)) :singular (function)) (defmobject one-dimensional-root-solver-fdf "gsl_root_fdfsolver" ((type :pointer)) "one-dimensional root solver with function and derivative" :initialize-suffix "set" :initialize-args ((callback :pointer) (root-guess :double)) :callbacks (callback fnstruct-fdf nil (function :double (:input :double) :slug) (df :double (:input :double) :slug) (fdf :void (:input :double) :slug (:output :double :cvector 1) (:output :double :cvector 1))) :arglists-function (lambda (set) `((type &optional (function nil ,set) df fdf root-guess) (:type type) (:functions (list function df fdf) :root-guess root-guess)))) (defmfun name ((solver one-dimensional-root-solver-f)) "gsl_root_fsolver_name" (((mpointer solver) :pointer)) :definition :method :c-return :string "The name of the solver.") (defmfun name ((solver one-dimensional-root-solver-fdf)) "gsl_root_fdfsolver_name" (((mpointer solver) :pointer)) :definition :method :c-return :string "The name of the solver.") It appears that this is always returning : SUCCESS ( 0 ) . (defmfun iterate ((solver one-dimensional-root-solver-f)) "gsl_root_fsolver_iterate" (((mpointer solver) :pointer)) :definition :method :callback-object solver "Perform a single iteration of the solver. The following errors may be signalled: 'bad-function-supplied, the iteration encountered a singular point where the function or its derivative evaluated to infinity or NaN, or 'gsl-division-by-zero, the derivative of the function vanished at the iteration point, preventing the algorithm from continuing without a division by zero.") (defmfun iterate ((solver one-dimensional-root-solver-fdf)) "gsl_root_fdfsolver_iterate" (((mpointer solver) :pointer)) :definition :method :callback-object solver "Perform a single iteration of the solver. The following errors may be signalled: 'bad-function-supplied, the iteration encountered a singular point where the function or its derivative evaluated to infinity or NaN, or 'gsl-division-by-zero, the derivative of the function vanished at the iteration point, preventing the algorithm from continuing without a division by zero.") (defmfun solution ((solver one-dimensional-root-solver-f)) "gsl_root_fsolver_root" (((mpointer solver) :pointer)) :definition :method :c-return :double "The current estimate of the root for the solver.") (defmfun solution ((solver one-dimensional-root-solver-fdf)) "gsl_root_fdfsolver_root" (((mpointer solver) :pointer)) :definition :method :c-return :double "The current estimate of the root for the solver.") (defmfun fsolver-lower (solver) "gsl_root_fsolver_x_lower" (((mpointer solver) :pointer)) :c-return :double "The lower end of the current bracketing interval for the solver.") (defmfun fsolver-upper (solver) "gsl_root_fsolver_x_upper" (((mpointer solver) :pointer)) :c-return :double "The upper end of the current bracketing interval for the solver.") (defmfun root-test-interval (lower upper absolute-error relative-error) "gsl_root_test_interval" ((lower :double) (upper :double) (absolute-error :double) (relative-error :double)) GSL documentation not clear on this "Test for the convergence of the interval [lower,upper] with absolute error absolute-error and relative error relative-error. This returns T if the following condition is achieved, |a - b| < epsabs + epsrel min(|a|,|b|) when the interval x = [a,b] does not include the origin. If the interval includes the origin then min(|a|,|b|) is replaced by zero (which is the minimum value of |x| over the interval). This ensures that the relative error is accurately estimated for roots close to the origin. This condition on the interval also implies that any estimate of the root r in the interval satisfies the same condition with respect to the true root r^*, |r - r^*| < epsabs + epsrel r^* assuming that the true root r^* is contained within the interval.") (defmfun root-test-delta (x1 x0 absolute-error relative-error) "gsl_root_test_delta" ((x1 :double) (x0 :double) (absolute-error :double) (relative-error :double)) :c-return :success-continue "Test for the convergence of the sequence ... x0, x1 with absolute error absolute-error and relative error relative-error. The test returns T if the following condition is achieved, |x_1 - x_0| < epsabs + epsrel |x_1| and returns NIL otherwise.") (defmfun root-test-residual (f absolute-error) "gsl_root_test_residual" ((f :double) (absolute-error :double)) :c-return :success-continue "Tests the residual value f against the absolute error bound absolute-error. The test returns T if the following condition is achieved, |f| < epsabs and returns NIL otherwise. This criterion is suitable for situations where the precise location of the root, x, is unimportant provided a value can be found where the residual, |f(x)|, is small enough.") (defmpar +bisection-fsolver+ "gsl_root_fsolver_bisection" "The bisection algorithm is the simplest method of bracketing the roots of a function. It is the slowest algorithm provided by the library, with linear convergence. On each iteration, the interval is bisected and the value of the function at the midpoint is calculated. The sign of this value is used to determine which half of the interval does not contain a root. That half is discarded to give a new, smaller interval containing the root. This procedure can be continued indefinitely until the interval is sufficiently small. At any time the current estimate of the root is taken as the midpoint of the interval.") (defmpar +false-position-fsolver+ "gsl_root_fsolver_falsepos" "The false position algorithm is a method of finding roots based on linear interpolation. Its convergence is linear, but it is usually faster than bisection. On each iteration a line is drawn between the endpoints (a,f(a)) and (b,f(b)) and the point where this line crosses the x-axis taken as a ``midpoint''. The value of the function at this point is calculated and its sign is used to determine which side of the interval does not contain a root. That side is discarded to give a new, smaller interval containing the root. This procedure can be continued indefinitely until the interval is sufficiently small. The best estimate of the root is taken from the linear interpolation of the interval on the current iteration.") (defmpar +brent-fsolver+ "gsl_root_fsolver_brent" "The Brent-Dekker method (referred to here as Brent's method) combines an interpolation strategy with the bisection algorithm. This produces a fast algorithm which is still robust. On each iteration Brent's method approximates the function using an interpolating curve. On the first iteration this is a linear interpolation of the two endpoints. For subsequent iterations the algorithm uses an inverse quadratic fit to the last three points, for higher accuracy. The intercept of the interpolating curve with the x-axis is taken as a guess for the root. If it lies within the bounds of the current interval then the interpolating point is accepted, and used to generate a smaller interval. If the interpolating point is not accepted then the algorithm falls back to an ordinary bisection step. The best estimate of the root is taken from the most recent interpolation or bisection.") (defmpar +newton-fdfsolver+ "gsl_root_fdfsolver_newton" "Newton's Method is the standard root-polishing algorithm. The algorithm begins with an initial guess for the location of the root. On each iteration, a line tangent to the function f is drawn at that position. The point where this line crosses the x-axis becomes the new guess. The iteration is defined by the following sequence, x_{i+1} = x_i - f(x_i) / f'(x_i) Newton's method converges quadratically for single roots, and linearly for multiple roots.") (defmpar +secant-fdfsolver+ "gsl_root_fdfsolver_secant" "The secant method is a simplified version of Newton's method which does not require the computation of the derivative on every step. On its first iteration the algorithm begins with Newton's method, using the derivative to compute a first step, x_1 = x_0 - f(x_0)/f'(x_0) Subsequent iterations avoid the evaluation of the derivative by replacing it with a numerical estimate, the slope of the line through the previous two points, x_{i+1} = x_i - f(x_i) / f'_{est} where f'_{est} = f(x_{i}) - f(x_{i-1}) / x_i - x_{i-1} When the derivative does not change significantly in the vicinity of the root the secant method gives a useful saving. Asymptotically the secant method is faster than Newton's method whenever the cost of evaluating the derivative is more than 0.44 times the cost of evaluating the function itself. As with all methods of computing a numerical derivative the estimate can suffer from cancellation errors if the separation of the points becomes too small. On single roots, the method has a convergence of order (1 + \sqrt 5)/2 (approximately 1.62). It converges linearly for multiple roots.") (defmpar +steffenson-fdfsolver+ "gsl_root_fdfsolver_steffenson" "The Steffenson method provides the fastest convergence of all the routines. It combines the basic Newton algorithm with an Aitken ``delta-squared'' acceleration. If the Newton iterates are x_i then the acceleration procedure generates a new sequence R_i, R_i = x_i - (x_{i+1} - x_i)^2 / (x_{i+2} - 2 x_{i+1} + x_i) which converges faster than the original sequence under reasonable conditions. The new sequence requires three terms before it can produce its first value so the method returns accelerated values on the second and subsequent iterations. On the first iteration it returns the ordinary Newton estimate. The Newton iterate is also returned if the denominator of the acceleration term ever becomes zero. As with all acceleration procedures this method can become unstable if the function is not well-behaved.") This is the example given in Sec . 32.10 . (let ((a 1.0d0) (b 0.0d0) (c -5.0d0)) (defun quadratic (x) (+ (* (+ (* a x) b) x) c)) (defun quadratic-derivative (x) (+ (* 2 a x) b)) (defun quadratic-and-derivative (x) (values (+ (* (+ (* a x) b) x) c) (+ (* 2 a x) b)))) (defun roots-one-example-no-derivative (&optional (method +brent-fsolver+) (print-steps t)) "Solving a quadratic, the example given in Sec. 32.10 of the GSL manual." (let ((max-iter 50) (solver (make-one-dimensional-root-solver-f method 'quadratic 0.0d0 5.0d0))) (when print-steps (format t "iter ~6t [lower ~24tupper] ~36troot ~44terr ~54terr(est)~&")) (loop for iter from 0 for root = (solution solver) for lower = (fsolver-lower solver) for upper = (fsolver-upper solver) do (iterate solver) while (and (< iter max-iter) (not (root-test-interval lower upper 0.0d0 0.001d0))) do (when print-steps (format t "~d~6t~10,6f~18t~10,6f~28t~12,9f ~44t~10,4g ~10,4g~&" iter lower upper root (- root (sqrt 5.0d0)) (- upper lower))) finally (return root)))) (defun roots-one-example-derivative (&optional (method +newton-fdfsolver+) (print-steps t)) "Solving a quadratic, the example given in Sec. 32.10 of the GSL manual." (let* ((max-iter 100) (initial 5.0d0) (solver (make-one-dimensional-root-solver-fdf method 'quadratic 'quadratic-derivative 'quadratic-and-derivative initial))) (when print-steps (format t "iter ~6t ~8troot ~22terr ~34terr(est)~&")) (loop for iter from 0 for oldroot = initial then root for root = (progn (iterate solver) (solution solver)) while (and (< iter max-iter) (not (root-test-delta root oldroot 0.0d0 1.0d-5))) do (when print-steps (format t "~d~6t~10,8g ~18t~10,6g~34t~10,6g~&" iter root (- root (sqrt 5.0d0)) (- root oldroot))) finally (return root)))) the last argument (save-test roots-one (roots-one-example-no-derivative +bisection-fsolver+ nil) (roots-one-example-no-derivative +false-position-fsolver+ nil) (roots-one-example-no-derivative +brent-fsolver+ nil) (roots-one-example-derivative +newton-fdfsolver+ nil) (roots-one-example-derivative +secant-fdfsolver+ nil) (roots-one-example-derivative +steffenson-fdfsolver+ nil))
9f60a00e6f4b6f2319086b53e91d8d4df44cbe564d89d992dd6347d69e05cada
fission-codes/cli
Main.hs
module Main (main) where import Fission.Prelude import qualified RIO.Partial as Partial import Network.HTTP.Client as HTTP import Network.HTTP.Client.TLS as HTTP import Servant.Client import Fission.Environment import Fission.Internal.App (isDebugEnabled, setRioVerbose) import qualified Fission.Web.Client as Client import qualified Network.IPFS.BinPath.Types as IPFS import qualified Network.IPFS.Timeout.Types as IPFS import Fission.CLI import qualified Fission.CLI.Config.Base.Types as CLI main :: IO () main = do isVerbose <- isDebugEnabled setRioVerbose isVerbose logOptions <- logOptionsHandle stderr isVerbose processCtx <- mkDefaultProcessContext ipfsPath <- withEnv "IPFS_PATH" (IPFS.BinPath "/usr/local/bin/ipfs") IPFS.BinPath ipfsTimeout <- withEnv "IPFS_TIMEOUT" (IPFS.Timeout 3600) (IPFS.Timeout . Partial.read) isTLS <- getFlag "FISSION_TLS" .!~ True path <- withEnv "FISSION_ROOT" "" identity host <- withEnv "FISSION_HOST" "runfission.com" identity port <- withEnv "FISSION_PORT" (if isTLS then 443 else 80) Partial.read tOut <- withEnv "FISSION_TIMEOUT" 1800000000 Partial.read let rawHTTPSettings = if isTLS then tlsManagerSettings else defaultManagerSettings httpManager <- HTTP.newManager <| rawHTTPSettings { managerResponseTimeout = responseTimeoutMicro tOut } let url = BaseUrl (if isTLS then Https else Http) host port path fissionAPI = Client.Runner (Client.request httpManager url) withLogFunc logOptions \logFunc -> cli CLI.BaseConfig {..}
null
https://raw.githubusercontent.com/fission-codes/cli/dc3500babad35a6cb44835fa503d27d672cbcdb3/app/Main.hs
haskell
module Main (main) where import Fission.Prelude import qualified RIO.Partial as Partial import Network.HTTP.Client as HTTP import Network.HTTP.Client.TLS as HTTP import Servant.Client import Fission.Environment import Fission.Internal.App (isDebugEnabled, setRioVerbose) import qualified Fission.Web.Client as Client import qualified Network.IPFS.BinPath.Types as IPFS import qualified Network.IPFS.Timeout.Types as IPFS import Fission.CLI import qualified Fission.CLI.Config.Base.Types as CLI main :: IO () main = do isVerbose <- isDebugEnabled setRioVerbose isVerbose logOptions <- logOptionsHandle stderr isVerbose processCtx <- mkDefaultProcessContext ipfsPath <- withEnv "IPFS_PATH" (IPFS.BinPath "/usr/local/bin/ipfs") IPFS.BinPath ipfsTimeout <- withEnv "IPFS_TIMEOUT" (IPFS.Timeout 3600) (IPFS.Timeout . Partial.read) isTLS <- getFlag "FISSION_TLS" .!~ True path <- withEnv "FISSION_ROOT" "" identity host <- withEnv "FISSION_HOST" "runfission.com" identity port <- withEnv "FISSION_PORT" (if isTLS then 443 else 80) Partial.read tOut <- withEnv "FISSION_TIMEOUT" 1800000000 Partial.read let rawHTTPSettings = if isTLS then tlsManagerSettings else defaultManagerSettings httpManager <- HTTP.newManager <| rawHTTPSettings { managerResponseTimeout = responseTimeoutMicro tOut } let url = BaseUrl (if isTLS then Https else Http) host port path fissionAPI = Client.Runner (Client.request httpManager url) withLogFunc logOptions \logFunc -> cli CLI.BaseConfig {..}
37b7a5116b8b06c5ee93de03694934a04c26ff72671af93e59116481b7b648a5
brendanhay/terrafomo
Types.hs
-- This module was auto-generated. If it is modified, it will not be overwritten. -- | -- Module : Terrafomo.Ignition.Types Copyright : ( c ) 2017 - 2018 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) -- module Terrafomo.Ignition.Types where import Data . Text ( Text ) import Terrafomo -- import Formatting (Format, (%)) import Terrafomo . Ignition . Lens import qualified Terrafomo . Attribute as TF import qualified Terrafomo . HCL as TF import qualified Terrafomo . Name as TF import qualified Terrafomo . Provider as TF import qualified Terrafomo . Schema as TF
null
https://raw.githubusercontent.com/brendanhay/terrafomo/387a0e9341fb9cd5543ef8332dea126f50f1070e/provider/terrafomo-ignition/src/Terrafomo/Ignition/Types.hs
haskell
This module was auto-generated. If it is modified, it will not be overwritten. | Module : Terrafomo.Ignition.Types Stability : auto-generated import Formatting (Format, (%))
Copyright : ( c ) 2017 - 2018 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) module Terrafomo.Ignition.Types where import Data . Text ( Text ) import Terrafomo import Terrafomo . Ignition . Lens import qualified Terrafomo . Attribute as TF import qualified Terrafomo . HCL as TF import qualified Terrafomo . Name as TF import qualified Terrafomo . Provider as TF import qualified Terrafomo . Schema as TF
f80057a49c0ba90e09f4691db593f37f4db43aa23fdf28e058896f6d6db7b292
erlang/rebar3
rebar_resource_v2.erl
-*- erlang - indent - level : 4;indent - tabs - mode : nil -*- %% ex: ts=4 sw=4 et -module(rebar_resource_v2). -export([new/3, find_resource_state/2, format_source/1, lock/2, download/3, needs_update/2, make_vsn/3, format_error/1]). -export_type([resource/0, source/0, type/0, location/0, ref/0, resource_state/0]). -include("rebar.hrl"). -include_lib("providers/include/providers.hrl"). -type resource() :: #resource{}. -type source() :: {type(), location(), ref()} | {type(), location(), ref(), binary()} | {type(), location(), ref(), binary(), binary()}. -type type() :: atom(). -type location() :: string(). -type ref() :: any(). -type resource_state() :: term(). -callback init(type(), rebar_state:t()) -> {ok, resource()}. -callback lock(rebar_app_info:t(), resource_state()) -> source(). -callback download(file:filename_all(), rebar_app_info:t(), rebar_state:t(), resource_state()) -> ok | {error, any()}. -callback needs_update(rebar_app_info:t(), resource_state()) -> boolean(). -callback make_vsn(rebar_app_info:t(), resource_state()) -> {plain, string()} | {error, string()}. -spec new(type(), module(), term()) -> resource(). new(Type, Module, State) -> #resource{type=Type, module=Module, state=State, implementation=?MODULE}. -spec find_resource(type(), [resource()]) -> {ok, resource()} | {error, not_found}. find_resource(Type, Resources) -> case ec_lists:find(fun(#resource{type=T}) -> T =:= Type end, Resources) of error when is_atom(Type) -> case code:which(Type) of non_existing -> {error, not_found}; _ -> {ok, rebar_resource:new(Type, Type, #{})} end; error -> {error, not_found}; {ok, Resource} -> {ok, Resource} end. find_resource_state(Type, Resources) -> case lists:keyfind(Type, #resource.type, Resources) of false -> {error, not_found}; #resource{state=State} -> State end. format_source(AppInfo) -> Name = rebar_app_info:name(AppInfo), case rebar_app_info:source(AppInfo) of {pkg, _Name, Vsn, _OldHash, _Hash, _} -> io_lib:format("~ts v~s", [Name, Vsn]); Source -> io_lib:format("~ts (from ~p)", [Name, Source]) end. lock(AppInfo, State) -> resource_run(lock, rebar_app_info:source(AppInfo), [AppInfo], State). resource_run(Function, Source, Args, State) -> Resources = rebar_state:resources(State), case get_resource_type(Source, Resources) of {ok, #resource{type=_, module=Module, state=ResourceState, implementation=?MODULE}} -> erlang:apply(Module, Function, Args++[ResourceState]); {ok, #resource{type=_, module=Module, state=_, implementation=rebar_resource}} -> erlang:apply(rebar_resource, Function, [Module | Args]) end. download(TmpDir, AppInfo, State) -> resource_run(download, rebar_app_info:source(AppInfo), [TmpDir, AppInfo, State], State). needs_update(AppInfo, State) -> resource_run(needs_update, rebar_app_info:source(AppInfo), [AppInfo], State). this is a special case since it is used for project apps as well , not just make_vsn(AppInfo, Vsn, State) -> VcsType = case Vsn of {T, _} -> T; T -> T end, Resources = rebar_state:resources(State), case is_resource_type(VcsType, Resources) of true -> case find_resource(VcsType, Resources) of {ok, #resource{type=_, module=Module, state=ResourceState, implementation=?MODULE}} -> Module:make_vsn(AppInfo, ResourceState); {ok, #resource{type=_, module=Module, state=_, implementation=rebar_resource}} -> rebar_resource:make_vsn(Module, AppInfo) end; false -> unknown end. format_error({no_resource, Location, Type}) -> io_lib:format("Cannot handle dependency ~ts.~n" " No module found for resource type ~p.", [Location, Type]); format_error({no_resource, Source}) -> io_lib:format("Cannot handle dependency ~ts.~n" " No module found for unknown resource type.", [Source]). is_resource_type(Type, Resources) -> lists:any(fun(#resource{type=T}) -> T =:= Type end, Resources). -spec get_resource_type(term(), [resource()]) -> {ok, resource()}. get_resource_type({Type, Location}, Resources) -> get_resource(Type, Location, Resources); get_resource_type({Type, Location, _}, Resources) -> get_resource(Type, Location, Resources); get_resource_type({Type, _, _, Location}, Resources) -> get_resource(Type, Location, Resources); get_resource_type(Location={Type, _, _, _, _, _}, Resources) -> get_resource(Type, Location, Resources); get_resource_type(Source, _) -> throw(?PRV_ERROR({no_resource, Source})). -spec get_resource(type(), term(), [resource()]) -> {ok, resource()}. get_resource(Type, Location, Resources) -> case find_resource(Type, Resources) of {error, not_found} -> throw(?PRV_ERROR({no_resource, Location, Type})); {ok, Resource} -> {ok, Resource} end.
null
https://raw.githubusercontent.com/erlang/rebar3/048412ed4593e19097f4fa91747593aac6706afb/apps/rebar/src/rebar_resource_v2.erl
erlang
ex: ts=4 sw=4 et
-*- erlang - indent - level : 4;indent - tabs - mode : nil -*- -module(rebar_resource_v2). -export([new/3, find_resource_state/2, format_source/1, lock/2, download/3, needs_update/2, make_vsn/3, format_error/1]). -export_type([resource/0, source/0, type/0, location/0, ref/0, resource_state/0]). -include("rebar.hrl"). -include_lib("providers/include/providers.hrl"). -type resource() :: #resource{}. -type source() :: {type(), location(), ref()} | {type(), location(), ref(), binary()} | {type(), location(), ref(), binary(), binary()}. -type type() :: atom(). -type location() :: string(). -type ref() :: any(). -type resource_state() :: term(). -callback init(type(), rebar_state:t()) -> {ok, resource()}. -callback lock(rebar_app_info:t(), resource_state()) -> source(). -callback download(file:filename_all(), rebar_app_info:t(), rebar_state:t(), resource_state()) -> ok | {error, any()}. -callback needs_update(rebar_app_info:t(), resource_state()) -> boolean(). -callback make_vsn(rebar_app_info:t(), resource_state()) -> {plain, string()} | {error, string()}. -spec new(type(), module(), term()) -> resource(). new(Type, Module, State) -> #resource{type=Type, module=Module, state=State, implementation=?MODULE}. -spec find_resource(type(), [resource()]) -> {ok, resource()} | {error, not_found}. find_resource(Type, Resources) -> case ec_lists:find(fun(#resource{type=T}) -> T =:= Type end, Resources) of error when is_atom(Type) -> case code:which(Type) of non_existing -> {error, not_found}; _ -> {ok, rebar_resource:new(Type, Type, #{})} end; error -> {error, not_found}; {ok, Resource} -> {ok, Resource} end. find_resource_state(Type, Resources) -> case lists:keyfind(Type, #resource.type, Resources) of false -> {error, not_found}; #resource{state=State} -> State end. format_source(AppInfo) -> Name = rebar_app_info:name(AppInfo), case rebar_app_info:source(AppInfo) of {pkg, _Name, Vsn, _OldHash, _Hash, _} -> io_lib:format("~ts v~s", [Name, Vsn]); Source -> io_lib:format("~ts (from ~p)", [Name, Source]) end. lock(AppInfo, State) -> resource_run(lock, rebar_app_info:source(AppInfo), [AppInfo], State). resource_run(Function, Source, Args, State) -> Resources = rebar_state:resources(State), case get_resource_type(Source, Resources) of {ok, #resource{type=_, module=Module, state=ResourceState, implementation=?MODULE}} -> erlang:apply(Module, Function, Args++[ResourceState]); {ok, #resource{type=_, module=Module, state=_, implementation=rebar_resource}} -> erlang:apply(rebar_resource, Function, [Module | Args]) end. download(TmpDir, AppInfo, State) -> resource_run(download, rebar_app_info:source(AppInfo), [TmpDir, AppInfo, State], State). needs_update(AppInfo, State) -> resource_run(needs_update, rebar_app_info:source(AppInfo), [AppInfo], State). this is a special case since it is used for project apps as well , not just make_vsn(AppInfo, Vsn, State) -> VcsType = case Vsn of {T, _} -> T; T -> T end, Resources = rebar_state:resources(State), case is_resource_type(VcsType, Resources) of true -> case find_resource(VcsType, Resources) of {ok, #resource{type=_, module=Module, state=ResourceState, implementation=?MODULE}} -> Module:make_vsn(AppInfo, ResourceState); {ok, #resource{type=_, module=Module, state=_, implementation=rebar_resource}} -> rebar_resource:make_vsn(Module, AppInfo) end; false -> unknown end. format_error({no_resource, Location, Type}) -> io_lib:format("Cannot handle dependency ~ts.~n" " No module found for resource type ~p.", [Location, Type]); format_error({no_resource, Source}) -> io_lib:format("Cannot handle dependency ~ts.~n" " No module found for unknown resource type.", [Source]). is_resource_type(Type, Resources) -> lists:any(fun(#resource{type=T}) -> T =:= Type end, Resources). -spec get_resource_type(term(), [resource()]) -> {ok, resource()}. get_resource_type({Type, Location}, Resources) -> get_resource(Type, Location, Resources); get_resource_type({Type, Location, _}, Resources) -> get_resource(Type, Location, Resources); get_resource_type({Type, _, _, Location}, Resources) -> get_resource(Type, Location, Resources); get_resource_type(Location={Type, _, _, _, _, _}, Resources) -> get_resource(Type, Location, Resources); get_resource_type(Source, _) -> throw(?PRV_ERROR({no_resource, Source})). -spec get_resource(type(), term(), [resource()]) -> {ok, resource()}. get_resource(Type, Location, Resources) -> case find_resource(Type, Resources) of {error, not_found} -> throw(?PRV_ERROR({no_resource, Location, Type})); {ok, Resource} -> {ok, Resource} end.
29ec6a2cadec6b28ada048adb8ec41a8fdfa8b00d4b8b572aa533363aefe6a85
themattchan/advent-of-code
Zipper.hs
module Zipper where newtype Zipper a = Zipper ([a], a, [a]) deriving Show zipLeft :: Int -> Zipper a -> Maybe (Zipper a) zipLeft 0 z = Just z zipLeft n (Zipper ([],_,_)) = Nothing zipLeft n (Zipper (l:ls,e,rs)) = zipLeft (n-1) (Zipper (ls, l, e:rs)) zipRight :: Int -> Zipper a -> Maybe (Zipper a) zipRight 0 z = Just z zipRight n (Zipper (_,_,[])) = Nothing zipRight n (Zipper (ls,e,r:rs)) = zipRight (n-1) (Zipper (e:ls, r, rs)) move :: Int -> Zipper a -> Maybe (Zipper a) move n | n > 0 = zipRight n | otherwise = zipLeft (abs n) viewFoci :: Zipper a -> a viewFoci (Zipper (_,e,_)) = e modifyFoci :: (a -> a) -> Zipper a -> Zipper a modifyFoci f (Zipper (ls, e, rs)) = Zipper (ls, f e, rs) zipperFromList :: [a] -> Zipper a zipperFromList [] = undefined zipperFromList (x:xs) = Zipper ([], x, xs) unzipper :: Zipper a -> [a] unzipper (Zipper (xs,e,ys)) = xs ++ e:ys
null
https://raw.githubusercontent.com/themattchan/advent-of-code/0b08a4fbadf7e713d40044523af3debb7d0cb6b9/Zipper.hs
haskell
module Zipper where newtype Zipper a = Zipper ([a], a, [a]) deriving Show zipLeft :: Int -> Zipper a -> Maybe (Zipper a) zipLeft 0 z = Just z zipLeft n (Zipper ([],_,_)) = Nothing zipLeft n (Zipper (l:ls,e,rs)) = zipLeft (n-1) (Zipper (ls, l, e:rs)) zipRight :: Int -> Zipper a -> Maybe (Zipper a) zipRight 0 z = Just z zipRight n (Zipper (_,_,[])) = Nothing zipRight n (Zipper (ls,e,r:rs)) = zipRight (n-1) (Zipper (e:ls, r, rs)) move :: Int -> Zipper a -> Maybe (Zipper a) move n | n > 0 = zipRight n | otherwise = zipLeft (abs n) viewFoci :: Zipper a -> a viewFoci (Zipper (_,e,_)) = e modifyFoci :: (a -> a) -> Zipper a -> Zipper a modifyFoci f (Zipper (ls, e, rs)) = Zipper (ls, f e, rs) zipperFromList :: [a] -> Zipper a zipperFromList [] = undefined zipperFromList (x:xs) = Zipper ([], x, xs) unzipper :: Zipper a -> [a] unzipper (Zipper (xs,e,ys)) = xs ++ e:ys
d03f6df9c0f94b589ad2b0619f8d0ec4eab34eb7b9afe527a508692e2c7b606a
baskeboler/cljs-karaoke-client
playlists.cljs
(ns cljs-karaoke.events.playlists (:require [re-frame.core :as rf :include-macros true] [cljs-karaoke.playlists :as pl] [cljs-karaoke.protocols :as protocols] ;; [cljs-karaoke.events :as events] ;; [cljs-karaoke.events.songs :as song-events] [day8.re-frame.tracing :refer-macros [fn-traced]])) (rf/reg-event-fx ::playlist-load (fn-traced [{:keys [db]} _] {:db db : dispatch - later [ { : ms 2000 ;; :dispatch [::set-current-playlist-song]})) :dispatch [::build-verified-playlist]})) (rf/reg-event-fx ::set-current-playlist-song (fn-traced [{:keys [db]} _] {:db db :dispatch (if-not (nil? (:playlist db)) [:cljs-karaoke.events.songs/navigate-to-song (protocols/current (:playlist db))] [::playlist-load])})) (rf/reg-event-fx ::jump-to-playlist-position (fn-traced [{:keys [db]} [_ position]] {:db (-> db (update :playlist assoc :current position)) :dispatch [::set-current-playlist-song]})) (rf/reg-event-fx ::add-song (fn-traced [{:keys [db]} [_ song-name]] {:db (if-not (or (nil? (:playlist db)) (protocols/contains-song? (:playlist db) song-name)) (do (println "song not in playlist, adding.") (-> db (update :playlist protocols/add-song song-name))) (do (println "song already in playlist, skipping") db))})) (rf/reg-event-fx ::build-verified-playlist (fn-traced [{:keys [db]} _] (let [pl (pl/build-playlist (keys (get db :custom-song-delay {})))] {:db (-> db (assoc :playlist pl)) :dispatch [::playlist-ready]}))) (rf/reg-event-db ::playlist-ready (fn-traced [db _] db)) (rf/reg-event-fx ::playlist-next (fn-traced [{:keys [db]} _] (let [new-db (-> db (update :playlist protocols/next-song))] {:db new-db :dispatch [:cljs-karaoke.events.songs/navigate-to-song (protocols/current (:playlist new-db))]}))) (rf/reg-event-fx ::move-song-up (fn-traced [{:keys [db]} [_ pos]] {:db (-> db (update :playlist #(protocols/update-song-position % pos -1)))})) (rf/reg-event-fx ::move-song-down (fn-traced [{:keys [db]} [_ pos]] {:db (-> db (update :playlist #(protocols/update-song-position % pos 1)))}))
null
https://raw.githubusercontent.com/baskeboler/cljs-karaoke-client/bb6512435eaa436d35034886be99213625847ee0/src/main/cljs_karaoke/events/playlists.cljs
clojure
[cljs-karaoke.events :as events] [cljs-karaoke.events.songs :as song-events] :dispatch [::set-current-playlist-song]}))
(ns cljs-karaoke.events.playlists (:require [re-frame.core :as rf :include-macros true] [cljs-karaoke.playlists :as pl] [cljs-karaoke.protocols :as protocols] [day8.re-frame.tracing :refer-macros [fn-traced]])) (rf/reg-event-fx ::playlist-load (fn-traced [{:keys [db]} _] {:db db : dispatch - later [ { : ms 2000 :dispatch [::build-verified-playlist]})) (rf/reg-event-fx ::set-current-playlist-song (fn-traced [{:keys [db]} _] {:db db :dispatch (if-not (nil? (:playlist db)) [:cljs-karaoke.events.songs/navigate-to-song (protocols/current (:playlist db))] [::playlist-load])})) (rf/reg-event-fx ::jump-to-playlist-position (fn-traced [{:keys [db]} [_ position]] {:db (-> db (update :playlist assoc :current position)) :dispatch [::set-current-playlist-song]})) (rf/reg-event-fx ::add-song (fn-traced [{:keys [db]} [_ song-name]] {:db (if-not (or (nil? (:playlist db)) (protocols/contains-song? (:playlist db) song-name)) (do (println "song not in playlist, adding.") (-> db (update :playlist protocols/add-song song-name))) (do (println "song already in playlist, skipping") db))})) (rf/reg-event-fx ::build-verified-playlist (fn-traced [{:keys [db]} _] (let [pl (pl/build-playlist (keys (get db :custom-song-delay {})))] {:db (-> db (assoc :playlist pl)) :dispatch [::playlist-ready]}))) (rf/reg-event-db ::playlist-ready (fn-traced [db _] db)) (rf/reg-event-fx ::playlist-next (fn-traced [{:keys [db]} _] (let [new-db (-> db (update :playlist protocols/next-song))] {:db new-db :dispatch [:cljs-karaoke.events.songs/navigate-to-song (protocols/current (:playlist new-db))]}))) (rf/reg-event-fx ::move-song-up (fn-traced [{:keys [db]} [_ pos]] {:db (-> db (update :playlist #(protocols/update-song-position % pos -1)))})) (rf/reg-event-fx ::move-song-down (fn-traced [{:keys [db]} [_ pos]] {:db (-> db (update :playlist #(protocols/update-song-position % pos 1)))}))
21295f27eae581e1509f01aff64c47cc1f4c1fa15f1e865d680319b4d7243b6f
dgtized/shimmers
unwinding.cljs
(ns shimmers.sketches.unwinding (:require [quil.core :as q :include-macros true] [quil.middleware :as m] [shimmers.common.framerate :as framerate] [shimmers.sketch :as sketch :include-macros true] [shimmers.common.quil :as cq] [shimmers.math.equations :as eq] [thi.ng.geom.vector :as gv] [thi.ng.math.core :as tm] [thi.ng.geom.core :as g])) (defn remap-from [pos scale points] (mapv (fn [p] (g/translate (tm/* p scale) pos)) points)) (defn plot [points] (q/begin-shape) (doseq [[x y] points] (q/vertex x y)) (q/end-shape)) (defn setup [] (q/color-mode :hsl 1.0) {:t 0.0}) (defn update-state [state] (update state :t (fn [t] (mod (+ t 0.005) eq/TAU)))) (defn draw [{:keys [t]}] (q/background 1.0) (q/ellipse-mode :radius) (q/no-fill) (q/translate (cq/rel-vec 0.5 0.5)) (q/scale 1 -1) (q/stroke-weight 2) (let [scaled (fn [s] (fn [p] (tm/* p s))) inner (mapv (scaled 7) (eq/clothoid-from 9 (+ 25 (* 15 (Math/cos t))) 50 -1 t (gv/vec2))) angle (g/heading (apply tm/- (reverse (take-last 2 inner)))) left (remap-from (last inner) 7 (eq/clothoid 10 (+ 35 (* 15 (Math/sin (+ t Math/PI)))) 100 -1 angle (gv/vec2))) right (remap-from (last inner) 7 (eq/clothoid 8 (+ 40 (* 15 (Math/sin t))) 100 1 angle (gv/vec2))) big-left (remap-from (last inner) 13 (eq/clothoid (+ 11 (* 6 (Math/sin (+ t Math/PI (/ Math/PI 3))))) 20 60 -1 angle (gv/vec2))) big-right (remap-from (last inner) 13 (eq/clothoid (+ 13 (* 7 (Math/sin (+ t (/ Math/PI 3))))) 25 60 1 angle (gv/vec2)))] (doseq [base (butlast (tm/norm-range 5))] (q/with-rotation [(* base eq/TAU)] (q/stroke 0.0) (plot inner) (q/stroke 0.2) (plot left) (plot right) (q/stroke 0.4) (plot big-left) (plot big-right))))) (sketch/defquil unwinding :created-at "2023-01-01" :tags #{:genuary2023} :size [800 600] :setup setup :update update-state :draw draw :middleware [m/fun-mode framerate/mode])
null
https://raw.githubusercontent.com/dgtized/shimmers/ce42c63db4f7fff4fedcfd695047653513e2747e/src/shimmers/sketches/unwinding.cljs
clojure
(ns shimmers.sketches.unwinding (:require [quil.core :as q :include-macros true] [quil.middleware :as m] [shimmers.common.framerate :as framerate] [shimmers.sketch :as sketch :include-macros true] [shimmers.common.quil :as cq] [shimmers.math.equations :as eq] [thi.ng.geom.vector :as gv] [thi.ng.math.core :as tm] [thi.ng.geom.core :as g])) (defn remap-from [pos scale points] (mapv (fn [p] (g/translate (tm/* p scale) pos)) points)) (defn plot [points] (q/begin-shape) (doseq [[x y] points] (q/vertex x y)) (q/end-shape)) (defn setup [] (q/color-mode :hsl 1.0) {:t 0.0}) (defn update-state [state] (update state :t (fn [t] (mod (+ t 0.005) eq/TAU)))) (defn draw [{:keys [t]}] (q/background 1.0) (q/ellipse-mode :radius) (q/no-fill) (q/translate (cq/rel-vec 0.5 0.5)) (q/scale 1 -1) (q/stroke-weight 2) (let [scaled (fn [s] (fn [p] (tm/* p s))) inner (mapv (scaled 7) (eq/clothoid-from 9 (+ 25 (* 15 (Math/cos t))) 50 -1 t (gv/vec2))) angle (g/heading (apply tm/- (reverse (take-last 2 inner)))) left (remap-from (last inner) 7 (eq/clothoid 10 (+ 35 (* 15 (Math/sin (+ t Math/PI)))) 100 -1 angle (gv/vec2))) right (remap-from (last inner) 7 (eq/clothoid 8 (+ 40 (* 15 (Math/sin t))) 100 1 angle (gv/vec2))) big-left (remap-from (last inner) 13 (eq/clothoid (+ 11 (* 6 (Math/sin (+ t Math/PI (/ Math/PI 3))))) 20 60 -1 angle (gv/vec2))) big-right (remap-from (last inner) 13 (eq/clothoid (+ 13 (* 7 (Math/sin (+ t (/ Math/PI 3))))) 25 60 1 angle (gv/vec2)))] (doseq [base (butlast (tm/norm-range 5))] (q/with-rotation [(* base eq/TAU)] (q/stroke 0.0) (plot inner) (q/stroke 0.2) (plot left) (plot right) (q/stroke 0.4) (plot big-left) (plot big-right))))) (sketch/defquil unwinding :created-at "2023-01-01" :tags #{:genuary2023} :size [800 600] :setup setup :update update-state :draw draw :middleware [m/fun-mode framerate/mode])
fbcef92b0c3caed91fcf046d2a35dd9da4ca50e36adea7ca120dfc15b67bf3bc
cartazio/tlaps
p_parser.mli
* concept.mli --- conceptualizing * * * Copyright ( C ) 2008 - 2010 INRIA and Microsoft Corporation * concept.mli --- conceptualizing * * * Copyright (C) 2008-2010 INRIA and Microsoft Corporation *) type supp = Emit | Suppress val usebody : P_t.usable Tla_parser.lprs val proof : P_t.proof Tla_parser.lprs val suppress : supp Tla_parser.lprs
null
https://raw.githubusercontent.com/cartazio/tlaps/562a34c066b636da7b921ae30fc5eacf83608280/src/proof/p_parser.mli
ocaml
* concept.mli --- conceptualizing * * * Copyright ( C ) 2008 - 2010 INRIA and Microsoft Corporation * concept.mli --- conceptualizing * * * Copyright (C) 2008-2010 INRIA and Microsoft Corporation *) type supp = Emit | Suppress val usebody : P_t.usable Tla_parser.lprs val proof : P_t.proof Tla_parser.lprs val suppress : supp Tla_parser.lprs
0439300c0fd2301748123f512663f8ff6d897f2911fe7ed7b0bbc115689eea54
projectcs13/sensor-cloud
triggers_lib_tests.erl
@author < > %% [www.csproj13.student.it.uu.se] %% @version 1.0 [ Copyright information ] %% %% @doc == triggers_lib_tests == %% This module contains several tests to test the functionallity %% in the module triggers_lib. %% %% @end -module(triggers_lib_tests). -include_lib("eunit/include/eunit.hrl"). -include_lib("amqp_client.hrl"). -export([]). %% @doc %% Function: less_than_test/0 %% Purpose: Used test the less_than function %% Returns: ok | {error, term()} %% %% @end -spec less_than_test() -> ok | {error, term()}. less_than_test() -> Data = [{"1","{\"value\":5}"},{"2","{\"value\":7}"},{"3","{\"value\":9}"},{"4","{\"value\":15}"}], Input = [{5,["Tomas"]},{7,["Erik"]},{9,["Johan"]},{15,["Jimmy"]}], Result = triggers_lib:less_than(Input,Data), ExpectedResult = [{5,"1",7,["Erik"]},{5,"1",9,["Johan"]},{5,"1",15,["Jimmy"]},{7,"2",9,["Johan"]},{7,"2",15,["Jimmy"]},{9,"3",15,["Jimmy"]}], ?assertEqual(Result,ExpectedResult). %% @doc %% Function: greater_than_test/0 %% Purpose: Used test the less_than function %% Returns: ok | {error, term()} %% %% @end -spec greater_than_test() -> ok | {error, term()}. greater_than_test() -> Data = [{"1","{\"value\":5}"},{"2","{\"value\":7}"},{"3","{\"value\":9}"},{"4","{\"value\":15}"}], Input = [{5,["Tomas"]},{7,["Erik"]},{9,["Johan"]},{15,["Jimmy"]}], Result = triggers_lib:greater_than(Input,Data), ExpectedResult = [{7,"2",5,["Tomas"]},{9,"3",5,["Tomas"]},{9,"3",7,["Erik"]},{15,"4",5,["Tomas"]},{15,"4",7,["Erik"]},{15,"4",9,["Johan"]}], ?assertEqual(Result,ExpectedResult). %% @doc %% Function: span_test/0 %% Purpose: Used test the span function %% Returns: ok | {error, term()} %% %% @end -spec span_test() -> ok | {error, term()}. span_test() -> Data = [{"1","{\"value\":5}"},{"2","{\"value\":7}"},{"3","{\"value\":9}"},{"4","{\"value\":15}"}], Input = [{[5,16],["Tomas"]},{[7,16],["Erik"]},{[9,16],["Johan"]},{[15,16],["Jimmy"]}], Result = triggers_lib:span(Input,Data), ExpectedResult = [{5,"1",[7,16],["Erik"]},{5,"1",[9,16],["Johan"]},{5,"1",[15,16],["Jimmy"]},{7,"2",[9,16],["Johan"]},{7,"2",[15,16],["Jimmy"]},{9,"3",[15,16],["Jimmy"]}], ?assertEqual(Result,ExpectedResult).
null
https://raw.githubusercontent.com/projectcs13/sensor-cloud/0302bd74b2e62fddbd832fb4c7a27b9c62852b90/test/triggers_lib_tests.erl
erlang
[www.csproj13.student.it.uu.se] @version 1.0 @doc == triggers_lib_tests == This module contains several tests to test the functionallity in the module triggers_lib. @end @doc Function: less_than_test/0 Purpose: Used test the less_than function Returns: ok | {error, term()} @end @doc Function: greater_than_test/0 Purpose: Used test the less_than function Returns: ok | {error, term()} @end @doc Function: span_test/0 Purpose: Used test the span function Returns: ok | {error, term()} @end
@author < > [ Copyright information ] -module(triggers_lib_tests). -include_lib("eunit/include/eunit.hrl"). -include_lib("amqp_client.hrl"). -export([]). -spec less_than_test() -> ok | {error, term()}. less_than_test() -> Data = [{"1","{\"value\":5}"},{"2","{\"value\":7}"},{"3","{\"value\":9}"},{"4","{\"value\":15}"}], Input = [{5,["Tomas"]},{7,["Erik"]},{9,["Johan"]},{15,["Jimmy"]}], Result = triggers_lib:less_than(Input,Data), ExpectedResult = [{5,"1",7,["Erik"]},{5,"1",9,["Johan"]},{5,"1",15,["Jimmy"]},{7,"2",9,["Johan"]},{7,"2",15,["Jimmy"]},{9,"3",15,["Jimmy"]}], ?assertEqual(Result,ExpectedResult). -spec greater_than_test() -> ok | {error, term()}. greater_than_test() -> Data = [{"1","{\"value\":5}"},{"2","{\"value\":7}"},{"3","{\"value\":9}"},{"4","{\"value\":15}"}], Input = [{5,["Tomas"]},{7,["Erik"]},{9,["Johan"]},{15,["Jimmy"]}], Result = triggers_lib:greater_than(Input,Data), ExpectedResult = [{7,"2",5,["Tomas"]},{9,"3",5,["Tomas"]},{9,"3",7,["Erik"]},{15,"4",5,["Tomas"]},{15,"4",7,["Erik"]},{15,"4",9,["Johan"]}], ?assertEqual(Result,ExpectedResult). -spec span_test() -> ok | {error, term()}. span_test() -> Data = [{"1","{\"value\":5}"},{"2","{\"value\":7}"},{"3","{\"value\":9}"},{"4","{\"value\":15}"}], Input = [{[5,16],["Tomas"]},{[7,16],["Erik"]},{[9,16],["Johan"]},{[15,16],["Jimmy"]}], Result = triggers_lib:span(Input,Data), ExpectedResult = [{5,"1",[7,16],["Erik"]},{5,"1",[9,16],["Johan"]},{5,"1",[15,16],["Jimmy"]},{7,"2",[9,16],["Johan"]},{7,"2",[15,16],["Jimmy"]},{9,"3",[15,16],["Jimmy"]}], ?assertEqual(Result,ExpectedResult).
3345f24e31a01e0143df5a3b323ebbc3f76803e13ca3f187936f6a58b8303f38
tarantool/jepsen.tarantool
register.clj
(ns tarantool.register "Run register tests." (:require [clojure.tools.logging :refer [info warn]] [clojure.string :as str] [jepsen [cli :as cli] [client :as client] [checker :as checker] [core :as jepsen] [control :as c] [independent :as independent] [generator :as gen] [util :refer [timeout meh]]] [next.jdbc :as j] [next.jdbc.sql :as sql] [knossos.model :as model] [jepsen.checker.timeline :as timeline] [tarantool [client :as cl] [db :as db]])) (def table-name "register") (defn r [_ _] {:type :invoke, :f :read, :value nil}) (defn w [_ _] {:type :invoke, :f :write, :value (rand-int 5)}) (defn cas [_ _] {:type :invoke, :f :cas, :value [(rand-int 5) (rand-int 5)]}) (defrecord Client [conn] client/Client (open! [this test node] (let [conn (cl/open node test)] (assert conn) (assoc this :conn conn :node node))) (setup! [this test node] (let [conn (cl/open node test)] (assert conn) (Thread/sleep 10000) ; wait for leader election and joining to a cluster (if (= node (first (db/primaries test))) (cl/with-conn-failure-retry conn (j/execute! conn [(str "CREATE TABLE IF NOT EXISTS " table-name " (id INT NOT NULL PRIMARY KEY, value INT NOT NULL)")]) (let [table (clojure.string/upper-case table-name)] (j/execute! conn [(str "SELECT LUA('return box.space." table ":alter{ is_sync = true } or 1')")])))) (assoc this :conn conn :node node))) (invoke! [this test op] (let [[k value] (:value op)] (case (:f op) :read (let [r (first (sql/query conn [(str "SELECT value FROM " table-name " WHERE id = " k)])) v (:value r)] (assoc op :type :ok, :value (independent/tuple k v))) :write (do (let [con (cl/open (first (db/primaries test)) test) table (clojure.string/upper-case table-name)] (j/execute! con [(str "SELECT _UPSERT(" k ", " value ", '" table "')")]) (assoc op :type :ok :value (independent/tuple k value)))) :cas (do (let [[old new] value con (cl/open (first (db/primaries test)) test) table (clojure.string/upper-case table-name) r (->> (j/execute! con [(str "SELECT _CAS(" k ", " old ", " new ", '" table "')")]) (first) (vals) (first))] (if r (assoc op :type :ok :value (independent/tuple k value)) (assoc op :type :fail))))))) (teardown! [_ test] (when-not (:leave-db-running? test) (cl/with-conn-failure-retry conn (j/execute! conn [(str "DROP TABLE IF EXISTS " table-name)])))) (close! [_ test])) (defn workload [opts] {:client (Client. nil) :generator (independent/concurrent-generator 10 (range) (fn [k] (->> (gen/mix [w cas]) (gen/reserve 5 r) (gen/limit 100)))) :checker (independent/checker (checker/compose {:timeline (timeline/html) :linearizable (checker/linearizable {:model (model/cas-register 0) :algorithm :linear})}))})
null
https://raw.githubusercontent.com/tarantool/jepsen.tarantool/4bc6a97c5755ed57790b85959b59d0614ba93916/src/tarantool/register.clj
clojure
wait for leader election and joining to a cluster
(ns tarantool.register "Run register tests." (:require [clojure.tools.logging :refer [info warn]] [clojure.string :as str] [jepsen [cli :as cli] [client :as client] [checker :as checker] [core :as jepsen] [control :as c] [independent :as independent] [generator :as gen] [util :refer [timeout meh]]] [next.jdbc :as j] [next.jdbc.sql :as sql] [knossos.model :as model] [jepsen.checker.timeline :as timeline] [tarantool [client :as cl] [db :as db]])) (def table-name "register") (defn r [_ _] {:type :invoke, :f :read, :value nil}) (defn w [_ _] {:type :invoke, :f :write, :value (rand-int 5)}) (defn cas [_ _] {:type :invoke, :f :cas, :value [(rand-int 5) (rand-int 5)]}) (defrecord Client [conn] client/Client (open! [this test node] (let [conn (cl/open node test)] (assert conn) (assoc this :conn conn :node node))) (setup! [this test node] (let [conn (cl/open node test)] (assert conn) (if (= node (first (db/primaries test))) (cl/with-conn-failure-retry conn (j/execute! conn [(str "CREATE TABLE IF NOT EXISTS " table-name " (id INT NOT NULL PRIMARY KEY, value INT NOT NULL)")]) (let [table (clojure.string/upper-case table-name)] (j/execute! conn [(str "SELECT LUA('return box.space." table ":alter{ is_sync = true } or 1')")])))) (assoc this :conn conn :node node))) (invoke! [this test op] (let [[k value] (:value op)] (case (:f op) :read (let [r (first (sql/query conn [(str "SELECT value FROM " table-name " WHERE id = " k)])) v (:value r)] (assoc op :type :ok, :value (independent/tuple k v))) :write (do (let [con (cl/open (first (db/primaries test)) test) table (clojure.string/upper-case table-name)] (j/execute! con [(str "SELECT _UPSERT(" k ", " value ", '" table "')")]) (assoc op :type :ok :value (independent/tuple k value)))) :cas (do (let [[old new] value con (cl/open (first (db/primaries test)) test) table (clojure.string/upper-case table-name) r (->> (j/execute! con [(str "SELECT _CAS(" k ", " old ", " new ", '" table "')")]) (first) (vals) (first))] (if r (assoc op :type :ok :value (independent/tuple k value)) (assoc op :type :fail))))))) (teardown! [_ test] (when-not (:leave-db-running? test) (cl/with-conn-failure-retry conn (j/execute! conn [(str "DROP TABLE IF EXISTS " table-name)])))) (close! [_ test])) (defn workload [opts] {:client (Client. nil) :generator (independent/concurrent-generator 10 (range) (fn [k] (->> (gen/mix [w cas]) (gen/reserve 5 r) (gen/limit 100)))) :checker (independent/checker (checker/compose {:timeline (timeline/html) :linearizable (checker/linearizable {:model (model/cas-register 0) :algorithm :linear})}))})
044ddacbe6f5224ce748e408db43a579afdbceae2656a5cd3d8944bf6c514235
chiroptical/thinking-with-types
Lib.hs
module Lib where import Data.Word (Word8) import Test.QuickCheck -- Cardinality -- --- -- Given a data constructor, the amount of inhabitants -- Syntax: |{data constuctor}| = {inhabitants} -- |Void| = 0 data Void |Unit| = 1 data Unit = Void |Bool'| = 2 data Bool' = True' | False' Isomorphic -- --- Any two data constructors with the same cardinality -- are isomorphic, we can define the `to` and `from` functions -- Syntax: $s \cong t$ -- Laws: -- to . from = id -- from . to = id to :: s -> t to = undefined from :: t -> s from = undefined -- Bool and Spin are isomorphic data Spin = Up | Down deriving (Eq, Show) instance Arbitrary Spin where arbitrary = oneof [pure Up, pure Down] toSpin :: Bool -> Spin toSpin True = Up toSpin False = Down fromSpin :: Spin -> Bool fromSpin Up = True fromSpin Down = False toSpin' :: Bool -> Spin toSpin' True = Down toSpin' False = Up fromSpin' :: Spin -> Bool fromSpin' Up = False fromSpin' Down = True -- Sum Types, -- the cardinality is the sum of inhabitants' cardinality -- Example: data Either' a b = Left' a | Right' b data Maybe' a = Nothing' | Just' a Cardinality is |Either'| = |a| + |b| |Either = |Bool| + |Bool| = 2 + 2 = 4 |Maybe ' Bool| = |Nothing| + |Bool| = 1 + 2 = 3 Either ' is not isomorphic with Maybe ' However , Either ' Unit Bool is isomorphic with Maybe ' -- Product Types, -- the cardinality is the product of the inhabitants cardinality -- Example: data MixedFraction a = Fraction { mixedBit :: Word8 , numerator :: a , denominator :: a } |MixedFraction Bool| = |Word8| x |Bool| x |Bool| = 256 x 2 x 2 = 1024 -- Prove `a x 1 = a` by showing an isomorphism between (a, ()) and a |(a , |()| = 1 |(a , ( ) ) = |a| x 1 -- therefore, |a| x 1 == |a| prodUnitTo :: a -> (a, ()) prodUnitTo a = (a, ()) prodUnitFrom :: (a, ()) -> a prodUnitFrom (a, _) = a -- Functions, -- the cardinality is computed as the result cardinality to the input cardinality power -- |a -> b| = \prod_{i=0}^{|a|} |b_i| = |b|^{|a|} Exercise : Determine the cardinality of Either ( Bool , Maybe ) - > Bool -- |Bool| ^ (|Bool| + (|Bool| x (|Nothing| + |Bool|))) 2 ^ ( 2 + ( 2 x ( 1 + 2 ) ) ) 2 ^ 8 = 256 data TicTacToe a = TicTacToe { topLeft :: a , topCenter :: a , topRight :: a , centerLeft :: a , centerCenter :: a , centerRight :: a , bottomLeft :: a , bottomCenter :: a , bottomRight :: a } emptyBoard :: TicTacToe (Maybe a) emptyBoard = TicTacToe Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing |TicTacToe a| = = = |a|^(3 x 3 ) isomorphic to ( |3| , ) - > a data Three = One | Two | Three deriving (Eq, Ord, Enum, Bounded) data TicTacToe' a = TicTacToe' { board :: Three -> Three -> a } emptyBoard' :: TicTacToe' (Maybe a) emptyBoard' = TicTacToe' $ const $ const Nothing -- Algebra | Types -- --------|------------- -- a + b | Either a b -- a x b | (a, b) -- b ^ a | a -> b -- a = b | isomorphism -- 0 | Void -- 1 | Unit Example , a ^ 1 = a In Curry - Howard , represents an isomorphism between ` ( ) - > a ` and ` a ` Exercise , using Curry - Howard prove ( a ^ b ) ^ c is isomorphic -- with a ^ (b x c), that is: provide a function of type ` ( b - > c - > a ) - > ( b , c ) - > a ` and one of ` ( ( b , c ) - > a ) - > b - > c - > a ` -- a ^ (b x c) ~ (b, c) -> a -- (a ^ b) ^ c ~ b -> c -> a -- uncurry fun :: (b -> c -> a) -> (b, c) -> a fun f (y, z) = f y z -- curry fun' :: ((b, c) -> a) -> b -> c -> a fun' f y z = f (y, z) -- fun . fun' $ f == id f, fun' . fun $ f == id f -- a ^ b x a ^ c = a ^ (b + c) -- --- -- a ^ b x a ^ c = (b -> a, c -> a) -- a ^ (b + c) = Either b c -> a exeTwoTo :: (b -> a, c -> a) -> (Either b c -> a) exeTwoTo (f, _) (Left x) = f x exeTwoTo (_, g) (Right y) = g y exeTwoFrom :: (Either b c -> a) -> (b -> a, c -> a) exeTwoFrom f = (f . Left, f . Right) -- (a x b) ^ c == a ^ c x b ^ c -- --- -- (a x b) ^ c = c -> (a, b) -- a ^ c x b ^ c = (c -> a, c -> b) exeThreeTo :: (c -> (a, b)) -> (c -> a, c -> b) exeThreeTo f = (fst . f, snd . f) exeThreeFrom :: Applicative f => (f a, f b) -> f (a, b) exeThreeFrom (fa, fb) = (,) <$> fa <*> fb -- exeThreeFrom :: (c -> a, c -> b) -> (c -> (a, b)) exeThreeFrom ( , fb ) = \c - > ( fa c , fb c ) -- Canonical Representation is ``sum of products'' t = \Sigma_m t_{m , n } -- --- A bit confused here , supposedly clarified in Chapter 13 -- HELP data SumOfProduct a = A a | B a data ProductOfSum a b = ProductOfSum { _one :: Either a a , _two :: Either b b } data SumOfProduct' a b = A' { _one' :: Either a a } | B' { _two' :: Either b b }
null
https://raw.githubusercontent.com/chiroptical/thinking-with-types/781f90f1b08eb94ef3600c5b7da92dfaf9ea4285/Chapter1/exercises/src/Lib.hs
haskell
Cardinality --- Given a data constructor, the amount of inhabitants Syntax: |{data constuctor}| = {inhabitants} --- are isomorphic, we can define the `to` and `from` functions Syntax: $s \cong t$ Laws: to . from = id from . to = id Bool and Spin are isomorphic Sum Types, the cardinality is the sum of inhabitants' cardinality Example: Product Types, the cardinality is the product of the inhabitants cardinality Example: Prove `a x 1 = a` by showing an isomorphism between (a, ()) and a therefore, |a| x 1 == |a| Functions, the cardinality is computed as the result cardinality to the input cardinality power |a -> b| = \prod_{i=0}^{|a|} |b_i| = |b|^{|a|} |Bool| ^ (|Bool| + (|Bool| x (|Nothing| + |Bool|))) Algebra | Types --------|------------- a + b | Either a b a x b | (a, b) b ^ a | a -> b a = b | isomorphism 0 | Void 1 | Unit with a ^ (b x c), that is: provide a function of type a ^ (b x c) ~ (b, c) -> a (a ^ b) ^ c ~ b -> c -> a uncurry curry fun . fun' $ f == id f, fun' . fun $ f == id f a ^ b x a ^ c = a ^ (b + c) --- a ^ b x a ^ c = (b -> a, c -> a) a ^ (b + c) = Either b c -> a (a x b) ^ c == a ^ c x b ^ c --- (a x b) ^ c = c -> (a, b) a ^ c x b ^ c = (c -> a, c -> b) exeThreeFrom :: (c -> a, c -> b) -> (c -> (a, b)) Canonical Representation is ``sum of products'' --- HELP
module Lib where import Data.Word (Word8) import Test.QuickCheck |Void| = 0 data Void |Unit| = 1 data Unit = Void |Bool'| = 2 data Bool' = True' | False' Isomorphic Any two data constructors with the same cardinality to :: s -> t to = undefined from :: t -> s from = undefined data Spin = Up | Down deriving (Eq, Show) instance Arbitrary Spin where arbitrary = oneof [pure Up, pure Down] toSpin :: Bool -> Spin toSpin True = Up toSpin False = Down fromSpin :: Spin -> Bool fromSpin Up = True fromSpin Down = False toSpin' :: Bool -> Spin toSpin' True = Down toSpin' False = Up fromSpin' :: Spin -> Bool fromSpin' Up = False fromSpin' Down = True data Either' a b = Left' a | Right' b data Maybe' a = Nothing' | Just' a Cardinality is |Either'| = |a| + |b| |Either = |Bool| + |Bool| = 2 + 2 = 4 |Maybe ' Bool| = |Nothing| + |Bool| = 1 + 2 = 3 Either ' is not isomorphic with Maybe ' However , Either ' Unit Bool is isomorphic with Maybe ' data MixedFraction a = Fraction { mixedBit :: Word8 , numerator :: a , denominator :: a } |MixedFraction Bool| = |Word8| x |Bool| x |Bool| = 256 x 2 x 2 = 1024 |(a , |()| = 1 |(a , ( ) ) = |a| x 1 prodUnitTo :: a -> (a, ()) prodUnitTo a = (a, ()) prodUnitFrom :: (a, ()) -> a prodUnitFrom (a, _) = a Exercise : Determine the cardinality of Either ( Bool , Maybe ) - > Bool 2 ^ ( 2 + ( 2 x ( 1 + 2 ) ) ) 2 ^ 8 = 256 data TicTacToe a = TicTacToe { topLeft :: a , topCenter :: a , topRight :: a , centerLeft :: a , centerCenter :: a , centerRight :: a , bottomLeft :: a , bottomCenter :: a , bottomRight :: a } emptyBoard :: TicTacToe (Maybe a) emptyBoard = TicTacToe Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing |TicTacToe a| = = = |a|^(3 x 3 ) isomorphic to ( |3| , ) - > a data Three = One | Two | Three deriving (Eq, Ord, Enum, Bounded) data TicTacToe' a = TicTacToe' { board :: Three -> Three -> a } emptyBoard' :: TicTacToe' (Maybe a) emptyBoard' = TicTacToe' $ const $ const Nothing Example , a ^ 1 = a In Curry - Howard , represents an isomorphism between ` ( ) - > a ` and ` a ` Exercise , using Curry - Howard prove ( a ^ b ) ^ c is isomorphic ` ( b - > c - > a ) - > ( b , c ) - > a ` and one of ` ( ( b , c ) - > a ) - > b - > c - > a ` fun :: (b -> c -> a) -> (b, c) -> a fun f (y, z) = f y z fun' :: ((b, c) -> a) -> b -> c -> a fun' f y z = f (y, z) exeTwoTo :: (b -> a, c -> a) -> (Either b c -> a) exeTwoTo (f, _) (Left x) = f x exeTwoTo (_, g) (Right y) = g y exeTwoFrom :: (Either b c -> a) -> (b -> a, c -> a) exeTwoFrom f = (f . Left, f . Right) exeThreeTo :: (c -> (a, b)) -> (c -> a, c -> b) exeThreeTo f = (fst . f, snd . f) exeThreeFrom :: Applicative f => (f a, f b) -> f (a, b) exeThreeFrom (fa, fb) = (,) <$> fa <*> fb exeThreeFrom ( , fb ) = \c - > ( fa c , fb c ) t = \Sigma_m t_{m , n } A bit confused here , supposedly clarified in Chapter 13 data SumOfProduct a = A a | B a data ProductOfSum a b = ProductOfSum { _one :: Either a a , _two :: Either b b } data SumOfProduct' a b = A' { _one' :: Either a a } | B' { _two' :: Either b b }
9db713f94d4f333d9cab54ec2c7f54c91a394894760ed2ed354b8a165b9f45e2
haskell/cabal
PackageEnvironment.hs
# LANGUAGE DeriveGeneric # ----------------------------------------------------------------------------- -- | Module : Distribution . Client . . PackageEnvironment -- Maintainer : -- Portability : portable -- Utilities for working with the package environment file . Patterned after -- Distribution.Client.Config. ----------------------------------------------------------------------------- module Distribution.Client.Sandbox.PackageEnvironment ( PackageEnvironment(..) , PackageEnvironmentType(..) , classifyPackageEnvironment , readPackageEnvironmentFile , showPackageEnvironment , showPackageEnvironmentWithComments , loadUserConfig , userPackageEnvironmentFile ) where import Distribution.Client.Compat.Prelude import Prelude () import Distribution.Client.Config ( SavedConfig(..) , configFieldDescriptions , haddockFlagsFields , installDirsFields, withProgramsFields , withProgramOptionsFields ) import Distribution.Client.ParseUtils ( parseFields, ppFields, ppSection ) import Distribution.Client.Setup ( ConfigExFlags(..) ) import Distribution.Client.Targets ( userConstraintPackageName ) import Distribution.Simple.InstallDirs ( InstallDirs(..), PathTemplate ) import Distribution.Simple.Setup ( Flag(..) , ConfigFlags(..), HaddockFlags(..) ) import Distribution.Simple.Utils ( warn, debug ) import Distribution.Solver.Types.ConstraintSource import Distribution.Deprecated.ParseUtils ( FieldDescr(..), ParseResult(..) , commaListFieldParsec, commaNewLineListFieldParsec , liftField, lineNo, locatedErrorMsg , readFields , showPWarning , syntaxError, warning ) import System.Directory ( doesFileExist ) import System.FilePath ( (</>) ) import System.IO.Error ( isDoesNotExistError ) import Text.PrettyPrint ( ($+$) ) import qualified Data.ByteString as BS import qualified Text.PrettyPrint as Disp import qualified Distribution.Deprecated.ParseUtils as ParseUtils ( Field(..) ) -- -- * Configuration saved in the package environment file -- -- TODO: would be nice to remove duplication between D.C.Sandbox . PackageEnvironment and D.C.Config . data PackageEnvironment = PackageEnvironment { pkgEnvSavedConfig :: SavedConfig } deriving Generic instance Monoid PackageEnvironment where mempty = gmempty mappend = (<>) instance Semigroup PackageEnvironment where (<>) = gmappend -- | Optional package environment file that can be used to customize the default -- settings. Created by the user. userPackageEnvironmentFile :: FilePath userPackageEnvironmentFile = "cabal.config" -- | Type of the current package environment. data PackageEnvironmentType = UserPackageEnvironment -- ^ './cabal.config' | AmbientPackageEnvironment -- ^ '~/.config/cabal/config' -- | Is there a 'cabal.config' in this directory? classifyPackageEnvironment :: FilePath -> IO PackageEnvironmentType classifyPackageEnvironment pkgEnvDir = do isUser <- configExists userPackageEnvironmentFile return (classify isUser) where configExists fname = doesFileExist (pkgEnvDir </> fname) classify :: Bool -> PackageEnvironmentType classify True = UserPackageEnvironment classify False = AmbientPackageEnvironment -- | Load the user package environment if it exists (the optional "cabal.config" -- file). If it does not exist locally, attempt to load an optional global one. userPackageEnvironment :: Verbosity -> FilePath -> Maybe FilePath -> IO PackageEnvironment userPackageEnvironment verbosity pkgEnvDir globalConfigLocation = do let path = pkgEnvDir </> userPackageEnvironmentFile minp <- readPackageEnvironmentFile (ConstraintSourceUserConfig path) mempty path case (minp, globalConfigLocation) of (Just parseRes, _) -> processConfigParse path parseRes (_, Just globalLoc) -> do minp' <- readPackageEnvironmentFile (ConstraintSourceUserConfig globalLoc) mempty globalLoc maybe (warn verbosity ("no constraints file found at " ++ globalLoc) >> return mempty) (processConfigParse globalLoc) minp' _ -> do debug verbosity ("no user package environment file found at " ++ pkgEnvDir) return mempty where processConfigParse path (ParseOk warns parseResult) = do unless (null warns) $ warn verbosity $ unlines (map (showPWarning path) warns) return parseResult processConfigParse path (ParseFailed err) = do let (line, msg) = locatedErrorMsg err warn verbosity $ "Error parsing package environment file " ++ path ++ maybe "" (\n -> ":" ++ show n) line ++ ":\n" ++ msg return mempty | Same as @userPackageEnvironmentFile@ , but returns a SavedConfig . loadUserConfig :: Verbosity -> FilePath -> Maybe FilePath -> IO SavedConfig loadUserConfig verbosity pkgEnvDir globalConfigLocation = fmap pkgEnvSavedConfig $ userPackageEnvironment verbosity pkgEnvDir globalConfigLocation -- | Descriptions of all fields in the package environment file. pkgEnvFieldDescrs :: ConstraintSource -> [FieldDescr PackageEnvironment] pkgEnvFieldDescrs src = [ commaNewLineListFieldParsec "constraints" (pretty . fst) ((\pc -> (pc, src)) `fmap` parsec) (sortConstraints . configExConstraints . savedConfigureExFlags . pkgEnvSavedConfig) (\v pkgEnv -> updateConfigureExFlags pkgEnv (\flags -> flags { configExConstraints = v })) , commaListFieldParsec "preferences" pretty parsec (configPreferences . savedConfigureExFlags . pkgEnvSavedConfig) (\v pkgEnv -> updateConfigureExFlags pkgEnv (\flags -> flags { configPreferences = v })) ] ++ map toPkgEnv configFieldDescriptions' where configFieldDescriptions' :: [FieldDescr SavedConfig] configFieldDescriptions' = filter (\(FieldDescr name _ _) -> name /= "preference" && name /= "constraint") (configFieldDescriptions src) toPkgEnv :: FieldDescr SavedConfig -> FieldDescr PackageEnvironment toPkgEnv fieldDescr = liftField pkgEnvSavedConfig (\savedConfig pkgEnv -> pkgEnv { pkgEnvSavedConfig = savedConfig}) fieldDescr updateConfigureExFlags :: PackageEnvironment -> (ConfigExFlags -> ConfigExFlags) -> PackageEnvironment updateConfigureExFlags pkgEnv f = pkgEnv { pkgEnvSavedConfig = (pkgEnvSavedConfig pkgEnv) { savedConfigureExFlags = f . savedConfigureExFlags . pkgEnvSavedConfig $ pkgEnv } } sortConstraints = sortBy (comparing $ userConstraintPackageName . fst) -- | Read the package environment file. readPackageEnvironmentFile :: ConstraintSource -> PackageEnvironment -> FilePath -> IO (Maybe (ParseResult PackageEnvironment)) readPackageEnvironmentFile src initial file = handleNotExists $ fmap (Just . parsePackageEnvironment src initial) (BS.readFile file) where handleNotExists action = catchIO action $ \ioe -> if isDoesNotExistError ioe then return Nothing else ioError ioe -- | Parse the package environment file. parsePackageEnvironment :: ConstraintSource -> PackageEnvironment -> BS.ByteString -> ParseResult PackageEnvironment parsePackageEnvironment src initial str = do fields <- readFields str let (knownSections, others) = partition isKnownSection fields pkgEnv <- parse others let config = pkgEnvSavedConfig pkgEnv installDirs0 = savedUserInstallDirs config (haddockFlags, installDirs, paths, args) <- foldM parseSections (savedHaddockFlags config, installDirs0, [], []) knownSections return pkgEnv { pkgEnvSavedConfig = config { savedConfigureFlags = (savedConfigureFlags config) { configProgramPaths = paths, configProgramArgs = args }, savedHaddockFlags = haddockFlags, savedUserInstallDirs = installDirs, savedGlobalInstallDirs = installDirs } } where isKnownSection :: ParseUtils.Field -> Bool isKnownSection (ParseUtils.Section _ "haddock" _ _) = True isKnownSection (ParseUtils.Section _ "install-dirs" _ _) = True isKnownSection (ParseUtils.Section _ "program-locations" _ _) = True isKnownSection (ParseUtils.Section _ "program-default-options" _ _) = True isKnownSection _ = False parse :: [ParseUtils.Field] -> ParseResult PackageEnvironment parse = parseFields (pkgEnvFieldDescrs src) initial parseSections :: SectionsAccum -> ParseUtils.Field -> ParseResult SectionsAccum parseSections accum@(h,d,p,a) (ParseUtils.Section _ "haddock" name fs) | name == "" = do h' <- parseFields haddockFlagsFields h fs return (h', d, p, a) | otherwise = do warning "The 'haddock' section should be unnamed" return accum parseSections (h,d,p,a) (ParseUtils.Section line "install-dirs" name fs) | name == "" = do d' <- parseFields installDirsFields d fs return (h, d',p,a) | otherwise = syntaxError line $ "Named 'install-dirs' section: '" ++ name ++ "'. Note that named 'install-dirs' sections are not allowed in the '" ++ userPackageEnvironmentFile ++ "' file." parseSections accum@(h, d,p,a) (ParseUtils.Section _ "program-locations" name fs) | name == "" = do p' <- parseFields withProgramsFields p fs return (h, d, p', a) | otherwise = do warning "The 'program-locations' section should be unnamed" return accum parseSections accum@(h, d, p, a) (ParseUtils.Section _ "program-default-options" name fs) | name == "" = do a' <- parseFields withProgramOptionsFields a fs return (h, d, p, a') | otherwise = do warning "The 'program-default-options' section should be unnamed" return accum parseSections accum f = do warning $ "Unrecognized stanza on line " ++ show (lineNo f) return accum -- | Accumulator type for 'parseSections'. type SectionsAccum = (HaddockFlags, InstallDirs (Flag PathTemplate) , [(String, FilePath)], [(String, [String])]) -- | Pretty-print the package environment. showPackageEnvironment :: PackageEnvironment -> String showPackageEnvironment pkgEnv = showPackageEnvironmentWithComments Nothing pkgEnv -- | Pretty-print the package environment with default values for empty fields commented out ( just like the default Cabal config file ) . showPackageEnvironmentWithComments :: (Maybe PackageEnvironment) -> PackageEnvironment -> String showPackageEnvironmentWithComments mdefPkgEnv pkgEnv = Disp.render $ ppFields (pkgEnvFieldDescrs ConstraintSourceUnknown) mdefPkgEnv pkgEnv $+$ Disp.text "" $+$ ppSection "install-dirs" "" installDirsFields (fmap installDirsSection mdefPkgEnv) (installDirsSection pkgEnv) where installDirsSection = savedUserInstallDirs . pkgEnvSavedConfig
null
https://raw.githubusercontent.com/haskell/cabal/9f7dc559d682331515692dd7b42f9abd3a087898/cabal-install/src/Distribution/Client/Sandbox/PackageEnvironment.hs
haskell
--------------------------------------------------------------------------- | Maintainer : Portability : portable Distribution.Client.Config. --------------------------------------------------------------------------- * Configuration saved in the package environment file TODO: would be nice to remove duplication between | Optional package environment file that can be used to customize the default settings. Created by the user. | Type of the current package environment. ^ './cabal.config' ^ '~/.config/cabal/config' | Is there a 'cabal.config' in this directory? | Load the user package environment if it exists (the optional "cabal.config" file). If it does not exist locally, attempt to load an optional global one. | Descriptions of all fields in the package environment file. | Read the package environment file. | Parse the package environment file. | Accumulator type for 'parseSections'. | Pretty-print the package environment. | Pretty-print the package environment with default values for empty fields
# LANGUAGE DeriveGeneric # Module : Distribution . Client . . PackageEnvironment Utilities for working with the package environment file . Patterned after module Distribution.Client.Sandbox.PackageEnvironment ( PackageEnvironment(..) , PackageEnvironmentType(..) , classifyPackageEnvironment , readPackageEnvironmentFile , showPackageEnvironment , showPackageEnvironmentWithComments , loadUserConfig , userPackageEnvironmentFile ) where import Distribution.Client.Compat.Prelude import Prelude () import Distribution.Client.Config ( SavedConfig(..) , configFieldDescriptions , haddockFlagsFields , installDirsFields, withProgramsFields , withProgramOptionsFields ) import Distribution.Client.ParseUtils ( parseFields, ppFields, ppSection ) import Distribution.Client.Setup ( ConfigExFlags(..) ) import Distribution.Client.Targets ( userConstraintPackageName ) import Distribution.Simple.InstallDirs ( InstallDirs(..), PathTemplate ) import Distribution.Simple.Setup ( Flag(..) , ConfigFlags(..), HaddockFlags(..) ) import Distribution.Simple.Utils ( warn, debug ) import Distribution.Solver.Types.ConstraintSource import Distribution.Deprecated.ParseUtils ( FieldDescr(..), ParseResult(..) , commaListFieldParsec, commaNewLineListFieldParsec , liftField, lineNo, locatedErrorMsg , readFields , showPWarning , syntaxError, warning ) import System.Directory ( doesFileExist ) import System.FilePath ( (</>) ) import System.IO.Error ( isDoesNotExistError ) import Text.PrettyPrint ( ($+$) ) import qualified Data.ByteString as BS import qualified Text.PrettyPrint as Disp import qualified Distribution.Deprecated.ParseUtils as ParseUtils ( Field(..) ) D.C.Sandbox . PackageEnvironment and D.C.Config . data PackageEnvironment = PackageEnvironment { pkgEnvSavedConfig :: SavedConfig } deriving Generic instance Monoid PackageEnvironment where mempty = gmempty mappend = (<>) instance Semigroup PackageEnvironment where (<>) = gmappend userPackageEnvironmentFile :: FilePath userPackageEnvironmentFile = "cabal.config" data PackageEnvironmentType classifyPackageEnvironment :: FilePath -> IO PackageEnvironmentType classifyPackageEnvironment pkgEnvDir = do isUser <- configExists userPackageEnvironmentFile return (classify isUser) where configExists fname = doesFileExist (pkgEnvDir </> fname) classify :: Bool -> PackageEnvironmentType classify True = UserPackageEnvironment classify False = AmbientPackageEnvironment userPackageEnvironment :: Verbosity -> FilePath -> Maybe FilePath -> IO PackageEnvironment userPackageEnvironment verbosity pkgEnvDir globalConfigLocation = do let path = pkgEnvDir </> userPackageEnvironmentFile minp <- readPackageEnvironmentFile (ConstraintSourceUserConfig path) mempty path case (minp, globalConfigLocation) of (Just parseRes, _) -> processConfigParse path parseRes (_, Just globalLoc) -> do minp' <- readPackageEnvironmentFile (ConstraintSourceUserConfig globalLoc) mempty globalLoc maybe (warn verbosity ("no constraints file found at " ++ globalLoc) >> return mempty) (processConfigParse globalLoc) minp' _ -> do debug verbosity ("no user package environment file found at " ++ pkgEnvDir) return mempty where processConfigParse path (ParseOk warns parseResult) = do unless (null warns) $ warn verbosity $ unlines (map (showPWarning path) warns) return parseResult processConfigParse path (ParseFailed err) = do let (line, msg) = locatedErrorMsg err warn verbosity $ "Error parsing package environment file " ++ path ++ maybe "" (\n -> ":" ++ show n) line ++ ":\n" ++ msg return mempty | Same as @userPackageEnvironmentFile@ , but returns a SavedConfig . loadUserConfig :: Verbosity -> FilePath -> Maybe FilePath -> IO SavedConfig loadUserConfig verbosity pkgEnvDir globalConfigLocation = fmap pkgEnvSavedConfig $ userPackageEnvironment verbosity pkgEnvDir globalConfigLocation pkgEnvFieldDescrs :: ConstraintSource -> [FieldDescr PackageEnvironment] pkgEnvFieldDescrs src = [ commaNewLineListFieldParsec "constraints" (pretty . fst) ((\pc -> (pc, src)) `fmap` parsec) (sortConstraints . configExConstraints . savedConfigureExFlags . pkgEnvSavedConfig) (\v pkgEnv -> updateConfigureExFlags pkgEnv (\flags -> flags { configExConstraints = v })) , commaListFieldParsec "preferences" pretty parsec (configPreferences . savedConfigureExFlags . pkgEnvSavedConfig) (\v pkgEnv -> updateConfigureExFlags pkgEnv (\flags -> flags { configPreferences = v })) ] ++ map toPkgEnv configFieldDescriptions' where configFieldDescriptions' :: [FieldDescr SavedConfig] configFieldDescriptions' = filter (\(FieldDescr name _ _) -> name /= "preference" && name /= "constraint") (configFieldDescriptions src) toPkgEnv :: FieldDescr SavedConfig -> FieldDescr PackageEnvironment toPkgEnv fieldDescr = liftField pkgEnvSavedConfig (\savedConfig pkgEnv -> pkgEnv { pkgEnvSavedConfig = savedConfig}) fieldDescr updateConfigureExFlags :: PackageEnvironment -> (ConfigExFlags -> ConfigExFlags) -> PackageEnvironment updateConfigureExFlags pkgEnv f = pkgEnv { pkgEnvSavedConfig = (pkgEnvSavedConfig pkgEnv) { savedConfigureExFlags = f . savedConfigureExFlags . pkgEnvSavedConfig $ pkgEnv } } sortConstraints = sortBy (comparing $ userConstraintPackageName . fst) readPackageEnvironmentFile :: ConstraintSource -> PackageEnvironment -> FilePath -> IO (Maybe (ParseResult PackageEnvironment)) readPackageEnvironmentFile src initial file = handleNotExists $ fmap (Just . parsePackageEnvironment src initial) (BS.readFile file) where handleNotExists action = catchIO action $ \ioe -> if isDoesNotExistError ioe then return Nothing else ioError ioe parsePackageEnvironment :: ConstraintSource -> PackageEnvironment -> BS.ByteString -> ParseResult PackageEnvironment parsePackageEnvironment src initial str = do fields <- readFields str let (knownSections, others) = partition isKnownSection fields pkgEnv <- parse others let config = pkgEnvSavedConfig pkgEnv installDirs0 = savedUserInstallDirs config (haddockFlags, installDirs, paths, args) <- foldM parseSections (savedHaddockFlags config, installDirs0, [], []) knownSections return pkgEnv { pkgEnvSavedConfig = config { savedConfigureFlags = (savedConfigureFlags config) { configProgramPaths = paths, configProgramArgs = args }, savedHaddockFlags = haddockFlags, savedUserInstallDirs = installDirs, savedGlobalInstallDirs = installDirs } } where isKnownSection :: ParseUtils.Field -> Bool isKnownSection (ParseUtils.Section _ "haddock" _ _) = True isKnownSection (ParseUtils.Section _ "install-dirs" _ _) = True isKnownSection (ParseUtils.Section _ "program-locations" _ _) = True isKnownSection (ParseUtils.Section _ "program-default-options" _ _) = True isKnownSection _ = False parse :: [ParseUtils.Field] -> ParseResult PackageEnvironment parse = parseFields (pkgEnvFieldDescrs src) initial parseSections :: SectionsAccum -> ParseUtils.Field -> ParseResult SectionsAccum parseSections accum@(h,d,p,a) (ParseUtils.Section _ "haddock" name fs) | name == "" = do h' <- parseFields haddockFlagsFields h fs return (h', d, p, a) | otherwise = do warning "The 'haddock' section should be unnamed" return accum parseSections (h,d,p,a) (ParseUtils.Section line "install-dirs" name fs) | name == "" = do d' <- parseFields installDirsFields d fs return (h, d',p,a) | otherwise = syntaxError line $ "Named 'install-dirs' section: '" ++ name ++ "'. Note that named 'install-dirs' sections are not allowed in the '" ++ userPackageEnvironmentFile ++ "' file." parseSections accum@(h, d,p,a) (ParseUtils.Section _ "program-locations" name fs) | name == "" = do p' <- parseFields withProgramsFields p fs return (h, d, p', a) | otherwise = do warning "The 'program-locations' section should be unnamed" return accum parseSections accum@(h, d, p, a) (ParseUtils.Section _ "program-default-options" name fs) | name == "" = do a' <- parseFields withProgramOptionsFields a fs return (h, d, p, a') | otherwise = do warning "The 'program-default-options' section should be unnamed" return accum parseSections accum f = do warning $ "Unrecognized stanza on line " ++ show (lineNo f) return accum type SectionsAccum = (HaddockFlags, InstallDirs (Flag PathTemplate) , [(String, FilePath)], [(String, [String])]) showPackageEnvironment :: PackageEnvironment -> String showPackageEnvironment pkgEnv = showPackageEnvironmentWithComments Nothing pkgEnv commented out ( just like the default Cabal config file ) . showPackageEnvironmentWithComments :: (Maybe PackageEnvironment) -> PackageEnvironment -> String showPackageEnvironmentWithComments mdefPkgEnv pkgEnv = Disp.render $ ppFields (pkgEnvFieldDescrs ConstraintSourceUnknown) mdefPkgEnv pkgEnv $+$ Disp.text "" $+$ ppSection "install-dirs" "" installDirsFields (fmap installDirsSection mdefPkgEnv) (installDirsSection pkgEnv) where installDirsSection = savedUserInstallDirs . pkgEnvSavedConfig
ee122b2c3334e8f14080287dd25478b5011b1bc6d4491bdd3a142193eab7bcee
mrossini-ethz/physical-quantities
conversion-test.lisp
(in-package :pq) (define-test conversion-test () (check ;; Different prefix (qtest #q(1 m -> km) :value 1/1000 :error 0 :unit '((|km| 1))) ;; Different prefix, different unit (qtest #q(1 m / s -> km / h) :value 36/10 :error 0 :unit '((|km| 1) (|h| -1))) Different prefix , power > 1 (qtest #q(1 m ^ 3 -> cm ^ 3) :value 1000000 :error 0 :unit '((|cm| 3))) Conversion factor ! = 1 , power > 1 (qtest #q(1 hour ^ 2 -> second ^ 2) :value 12960000 :error 0 :unit '((|s| 2))) ;; Derived units (qtest #q(1 kg m / s ^ 2 -> newton) :value 1 :error 0 :unit '((|N| 1))) (qtest #q(1 newton -> kg m / s ^ 2) :value 1 :error 0 :unit '((|kg| 1) (|m| 1) (|s| -2))) ;; Special cases (qtest #q(1 kelvin -> celsius) :value 1 :error 0 :unit '((|celsius| 1))) (qtest #q(1 rad -> deg) :value (/ 180 pi) :error 0 :unit '((|degree| 1))) ;; Incompatible units (condition= #q(1 m -> s) invalid-unit-conversion-error)))
null
https://raw.githubusercontent.com/mrossini-ethz/physical-quantities/348827f0632eb5bd14b378dab4e47bb6e3102f70/test/conversion-test.lisp
lisp
Different prefix Different prefix, different unit Derived units Special cases Incompatible units
(in-package :pq) (define-test conversion-test () (check (qtest #q(1 m -> km) :value 1/1000 :error 0 :unit '((|km| 1))) (qtest #q(1 m / s -> km / h) :value 36/10 :error 0 :unit '((|km| 1) (|h| -1))) Different prefix , power > 1 (qtest #q(1 m ^ 3 -> cm ^ 3) :value 1000000 :error 0 :unit '((|cm| 3))) Conversion factor ! = 1 , power > 1 (qtest #q(1 hour ^ 2 -> second ^ 2) :value 12960000 :error 0 :unit '((|s| 2))) (qtest #q(1 kg m / s ^ 2 -> newton) :value 1 :error 0 :unit '((|N| 1))) (qtest #q(1 newton -> kg m / s ^ 2) :value 1 :error 0 :unit '((|kg| 1) (|m| 1) (|s| -2))) (qtest #q(1 kelvin -> celsius) :value 1 :error 0 :unit '((|celsius| 1))) (qtest #q(1 rad -> deg) :value (/ 180 pi) :error 0 :unit '((|degree| 1))) (condition= #q(1 m -> s) invalid-unit-conversion-error)))
be425830de0da8863ad986b6ef5ca0c2b8be6446d531ccb2382d8170bc0a928e
acl2/acl2
bv-array-read@useless-runes.lsp
(BV-ARRAY-READ) (BV-ARRAY-READ-OF-TRUE-LIST-FIX (28 4 (:REWRITE BVCHOP-IDENTITY)) (24 4 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (16 9 (:REWRITE DEFAULT-<-2)) (14 9 (:REWRITE DEFAULT-<-1)) (13 13 (:TYPE-PRESCRIPTION CEILING-OF-LG)) (10 4 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (8 8 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (8 8 (:REWRITE BOUND-WHEN-USB)) (8 4 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (8 4 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (8 4 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (7 4 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (6 6 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (6 2 (:REWRITE NTH-WHEN-ZP-CHEAP)) (6 2 (:REWRITE NTH-WHEN-<=-LEN-CHEAP)) (6 2 (:DEFINITION TRUE-LIST-FIX)) (6 1 (:REWRITE UNSIGNED-BYTE-P-OF-CEILING-OF-LG-WHEN-<)) (4 4 (:TYPE-PRESCRIPTION POSP)) (4 4 (:TYPE-PRESCRIPTION NATP)) (4 4 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (4 4 (:REWRITE BVCHOP-SUBST-CONSTANT)) (4 4 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (3 3 (:REWRITE UBP-LONGER-BETTER)) (3 3 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (3 3 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (3 3 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:TYPE-PRESCRIPTION ZP)) (2 2 (:REWRITE NTH-WHEN-NOT-CONSP-CHEAP)) (2 2 (:REWRITE DEFAULT-CDR)) (2 2 (:REWRITE DEFAULT-CAR)) (2 2 (:REWRITE BVCHOP-NUMERIC-BOUND)) (2 2 (:REWRITE BVCHOP-BOUND)) (2 2 (:REWRITE <-OF-BVCHOP-WHEN-<-OF-BVCHOP-BIGGER)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) ) (BV-ARRAY-READ-OPENER (16 10 (:REWRITE DEFAULT-<-2)) (15 3 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (13 10 (:REWRITE DEFAULT-<-1)) (10 10 (:REWRITE BOUND-WHEN-USB)) (10 1 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (8 1 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (7 7 (:TYPE-PRESCRIPTION NATP)) (7 7 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (6 6 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (6 3 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (5 3 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (5 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (4 4 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (4 2 (:REWRITE NTH-WHEN-ZP-CHEAP)) (4 2 (:REWRITE NTH-WHEN-<=-LEN-CHEAP)) (3 3 (:TYPE-PRESCRIPTION POSP)) (3 3 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (3 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (3 3 (:REWRITE BVCHOP-SUBST-CONSTANT)) (3 3 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:TYPE-PRESCRIPTION ZP)) (2 2 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (2 2 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (2 2 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (2 2 (:REWRITE UBP-LONGER-BETTER)) (2 2 (:REWRITE NTH-WHEN-NOT-CONSP-CHEAP)) (2 2 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (1 1 (:REWRITE INTEGER-LENGTH-WHEN-NOT-INTEGERP-CHEAP)) (1 1 (:REWRITE DEFAULT-+-2)) (1 1 (:REWRITE DEFAULT-+-1)) ) (UNSIGNED-BYTE-P-OF-BV-ARRAY-READ-GEN (50 4 (:REWRITE BVCHOP-IDENTITY)) (35 22 (:REWRITE DEFAULT-<-1)) (25 9 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (23 22 (:REWRITE DEFAULT-<-2)) (19 19 (:REWRITE BOUND-WHEN-USB)) (13 13 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (13 2 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (12 12 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (9 9 (:TYPE-PRESCRIPTION CEILING-OF-LG)) (9 9 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (9 9 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (9 9 (:REWRITE UBP-LONGER-BETTER)) (7 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (6 1 (:REWRITE UNSIGNED-BYTE-P-OF-CEILING-OF-LG-WHEN-<)) (4 4 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (4 4 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (4 4 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (4 4 (:REWRITE BVCHOP-SUBST-CONSTANT)) (4 4 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (4 4 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (4 4 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (3 2 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (3 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (3 2 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (3 1 (:REWRITE NTH-WHEN-ZP-CHEAP)) (3 1 (:REWRITE NTH-WHEN-<=-LEN-CHEAP)) (2 2 (:TYPE-PRESCRIPTION POSP)) (2 2 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (2 2 (:TYPE-PRESCRIPTION <=-OF-0-AND-EXPT)) (2 2 (:TYPE-PRESCRIPTION <-OF-0-AND-EXPT)) (2 2 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG1)) (2 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (1 1 (:TYPE-PRESCRIPTION ZP)) (1 1 (:REWRITE NTH-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE BVCHOP-NUMERIC-BOUND)) (1 1 (:REWRITE BVCHOP-BOUND)) (1 1 (:REWRITE <-OF-BVCHOP-WHEN-<-OF-BVCHOP-BIGGER)) ) (EQUAL-OF-BVCHOP-OF-CAR-AND-BV-ARRAY-READ (379 48 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (217 57 (:REWRITE DEFAULT-<-1)) (76 38 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (60 57 (:REWRITE DEFAULT-<-2)) (53 53 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (53 53 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (53 53 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (48 48 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (48 48 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (48 48 (:REWRITE UBP-LONGER-BETTER)) (48 48 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (47 47 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (47 47 (:TYPE-PRESCRIPTION <=-OF-0-AND-EXPT)) (47 47 (:TYPE-PRESCRIPTION <-OF-0-AND-EXPT)) (47 47 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (47 47 (:REWRITE BVCHOP-SUBST-CONSTANT)) (38 38 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (38 38 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (38 38 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (38 38 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (38 38 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (36 36 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (19 19 (:REWRITE BOUND-WHEN-USB)) (16 16 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (16 8 (:REWRITE DEFAULT-+-2)) (8 8 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (8 8 (:REWRITE DEFAULT-+-1)) (8 6 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (7 7 (:REWRITE DEFAULT-CDR)) (3 3 (:REWRITE NTH-WHEN-ZP-CHEAP)) (3 3 (:REWRITE NTH-WHEN-NOT-CONSP-CHEAP)) (3 3 (:REWRITE NTH-WHEN-<=-LEN-CHEAP)) (2 2 (:REWRITE BVCHOPS-SAME-WHEN-BVCHOPS-SAME)) ) (BV-ARRAY-READ-OF-BVCHOP-HELPER (107 18 (:REWRITE BVCHOP-IDENTITY)) (68 17 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (50 29 (:REWRITE DEFAULT-<-2)) (40 29 (:REWRITE DEFAULT-<-1)) (36 18 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (30 3 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (29 29 (:REWRITE BOUND-WHEN-USB)) (29 17 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (28 28 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (27 18 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (26 26 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (26 17 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (24 3 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (23 17 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (21 21 (:TYPE-PRESCRIPTION NATP)) (19 18 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (19 6 (:REWRITE NTH-WHEN-ZP-CHEAP)) (19 6 (:REWRITE NTH-WHEN-<=-LEN-CHEAP)) (18 18 (:TYPE-PRESCRIPTION POSP)) (18 18 (:REWRITE BVCHOP-SUBST-CONSTANT)) (18 18 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (14 14 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (14 14 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (14 14 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (14 14 (:REWRITE UBP-LONGER-BETTER)) (11 11 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (10 10 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (9 9 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (9 9 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (9 9 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (8 2 (:REWRITE DEFAULT-+-2)) (7 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (6 6 (:TYPE-PRESCRIPTION ZP)) (6 6 (:REWRITE NTH-WHEN-NOT-CONSP-CHEAP)) (6 6 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (4 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE BVCHOP-NUMERIC-BOUND)) (3 3 (:REWRITE BVCHOP-BOUND)) (3 3 (:REWRITE <-OF-BVCHOP-WHEN-<-OF-BVCHOP-BIGGER)) (2 2 (:REWRITE DEFAULT-+-1)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (1 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) ) (BV-ARRAY-READ-OF-BVCHOP (22 22 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (15 8 (:REWRITE DEFAULT-+-2)) (10 5 (:REWRITE EXPT-2-OF-+-OF--1-AND-INTEGER-LENGTH-WHEN-POWER-OF-2P-CHEAP)) (8 8 (:REWRITE DEFAULT-+-1)) (7 7 (:REWRITE INTEGER-LENGTH-WHEN-NOT-INTEGERP-CHEAP)) (7 1 (:REWRITE BVCHOP-IDENTITY)) (7 1 (:LINEAR <-OF-EXPT-OF-ONE-LESS-OF-INTEGER-LENGTH-LINEAR)) (5 5 (:TYPE-PRESCRIPTION POWER-OF-2P)) (4 3 (:REWRITE DEFAULT-<-2)) (4 3 (:REWRITE DEFAULT-<-1)) (4 1 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (3 3 (:REWRITE BOUND-WHEN-USB)) (2 2 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (2 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (1 1 (:TYPE-PRESCRIPTION POSP)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (1 1 (:REWRITE UBP-LONGER-BETTER)) (1 1 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (1 1 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (1 1 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (1 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (1 1 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (1 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (1 1 (:REWRITE BVCHOP-SUBST-CONSTANT)) (1 1 (:REWRITE BVCHOP-IDENTITY-CHEAP)) ) (BV-ARRAY-READ-OF-TAKE (28 4 (:REWRITE BVCHOP-IDENTITY)) (24 4 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (16 9 (:REWRITE DEFAULT-<-2)) (14 9 (:REWRITE DEFAULT-<-1)) (12 1 (:REWRITE TAKE-DOES-NOTHING)) (10 4 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (8 8 (:REWRITE BOUND-WHEN-USB)) (8 4 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (8 4 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (8 4 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (7 4 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (6 6 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (6 6 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (6 2 (:REWRITE NTH-WHEN-ZP-CHEAP)) (6 2 (:REWRITE NTH-WHEN-<=-LEN-CHEAP)) (6 1 (:REWRITE UNSIGNED-BYTE-P-OF-CEILING-OF-LG-WHEN-<)) (5 1 (:DEFINITION LEN)) (4 4 (:TYPE-PRESCRIPTION POSP)) (4 4 (:TYPE-PRESCRIPTION NATP)) (4 4 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (4 4 (:REWRITE BVCHOP-SUBST-CONSTANT)) (4 4 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (3 3 (:REWRITE UBP-LONGER-BETTER)) (3 3 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (3 3 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:TYPE-PRESCRIPTION ZP)) (2 2 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (2 2 (:REWRITE NTH-WHEN-NOT-CONSP-CHEAP)) (2 2 (:REWRITE BVCHOP-NUMERIC-BOUND)) (2 2 (:REWRITE BVCHOP-BOUND)) (2 1 (:REWRITE DEFAULT-+-2)) (1 1 (:REWRITE DEFAULT-CDR)) (1 1 (:REWRITE DEFAULT-+-1)) ) (BV-ARRAY-READ-OF-CONS (84 50 (:REWRITE DEFAULT-<-2)) (77 50 (:REWRITE DEFAULT-<-1)) (54 35 (:REWRITE DEFAULT-+-2)) (49 7 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (47 35 (:REWRITE DEFAULT-+-1)) (42 42 (:REWRITE BOUND-WHEN-USB)) (42 7 (:REWRITE <-OF-INTEGER-LENGTH-ARG2)) (35 35 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (23 16 (:REWRITE INTEGER-LENGTH-WHEN-NOT-INTEGERP-CHEAP)) (21 21 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (20 2 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (17 17 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (16 16 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (16 16 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (16 16 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (16 2 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (14 7 (:REWRITE EXPT-2-OF-+-OF--1-AND-INTEGER-LENGTH-WHEN-POWER-OF-2P-CHEAP)) (14 7 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (14 7 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (14 7 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (14 7 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (14 7 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (11 11 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (10 5 (:REWRITE NTH-WHEN-ZP-CHEAP)) (10 5 (:REWRITE NTH-WHEN-<=-LEN-CHEAP)) (10 1 (:LINEAR INTEGER-LENGTH-BOUND)) (7 7 (:TYPE-PRESCRIPTION POWER-OF-2P)) (7 7 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (7 7 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (7 7 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (7 7 (:REWRITE UBP-LONGER-BETTER)) (7 7 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (7 7 (:REWRITE BVCHOP-SUBST-CONSTANT)) (5 5 (:TYPE-PRESCRIPTION ZP)) (5 5 (:REWRITE NTH-WHEN-NOT-CONSP-CHEAP)) (5 5 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (4 4 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (2 2 (:REWRITE NTH-OF-CONS-CONSTANT-VERSION)) (1 1 (:REWRITE NTH-OF-PLUS-OF-CONS-WHEN-CONSTANT)) ) (BV-ARRAY-READ-OF-CONS-BASE (27 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (16 9 (:REWRITE DEFAULT-<-1)) (15 9 (:REWRITE DEFAULT-<-2)) (15 3 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (10 1 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (9 9 (:REWRITE BOUND-WHEN-USB)) (8 1 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (7 7 (:TYPE-PRESCRIPTION NATP)) (7 7 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (6 6 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (6 3 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (5 3 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (5 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (4 4 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (4 4 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (3 3 (:TYPE-PRESCRIPTION POSP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (3 3 (:REWRITE UBP-LONGER-BETTER)) (3 3 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (3 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (3 3 (:REWRITE BVCHOP-SUBST-CONSTANT)) (3 3 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (2 2 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (1 1 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) ) (BV-ARRAY-READ-OF-CONS-BOTH (23 14 (:REWRITE DEFAULT-<-2)) (22 4 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (22 4 (:REWRITE BVCHOP-IDENTITY)) (17 14 (:REWRITE DEFAULT-<-1)) (13 13 (:REWRITE BOUND-WHEN-USB)) (12 12 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (10 1 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (9 9 (:TYPE-PRESCRIPTION NATP)) (8 4 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (8 4 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (8 4 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (8 1 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (7 7 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (7 4 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (7 4 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (6 6 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (6 6 (:REWRITE DEFAULT-+-2)) (6 6 (:REWRITE DEFAULT-+-1)) (4 4 (:TYPE-PRESCRIPTION POSP)) (4 4 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (4 4 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (4 4 (:REWRITE BVCHOP-SUBST-CONSTANT)) (4 4 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (4 4 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (4 4 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (3 3 (:REWRITE UBP-LONGER-BETTER)) (3 3 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (2 2 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (2 2 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (2 2 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) ) (BV-ARRAY-READ-OF-1-ARG2 (30 4 (:REWRITE BVCHOP-IDENTITY)) (15 3 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (11 5 (:REWRITE DEFAULT-<-2)) (11 5 (:REWRITE DEFAULT-<-1)) (11 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (10 1 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (8 1 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (7 7 (:TYPE-PRESCRIPTION NATP)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (6 3 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (6 1 (:DEFINITION NATP)) (5 5 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (5 5 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (5 3 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (5 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (4 4 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (4 4 (:REWRITE BVCHOP-SUBST-CONSTANT)) (4 4 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (4 4 (:REWRITE BOUND-WHEN-USB)) (4 4 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (4 4 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 2 (:REWRITE NTH-WHEN-<=-LEN-CHEAP)) (3 3 (:TYPE-PRESCRIPTION POSP)) (3 3 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (3 3 (:REWRITE UBP-LONGER-BETTER)) (3 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (2 2 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (2 2 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (2 2 (:REWRITE NTH-WHEN-ZP-CHEAP)) (2 2 (:REWRITE NTH-WHEN-NOT-CONSP-CHEAP)) (2 2 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (1 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG1)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) ) (BV-ARRAY-READ-OF-1-ARG2-BETTER (20 3 (:REWRITE BVCHOP-IDENTITY)) (9 3 (:REWRITE DEFAULT-<-2)) (8 2 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (7 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (4 4 (:TYPE-PRESCRIPTION NATP)) (4 2 (:REWRITE NTH-WHEN-<=-LEN-CHEAP)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (4 2 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (3 3 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (3 3 (:REWRITE DEFAULT-<-1)) (3 3 (:REWRITE BVCHOP-SUBST-CONSTANT)) (3 3 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (3 2 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (3 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (2 2 (:TYPE-PRESCRIPTION POSP)) (2 2 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (2 2 (:REWRITE UBP-LONGER-BETTER)) (2 2 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (2 2 (:REWRITE NTH-WHEN-ZP-CHEAP)) (2 2 (:REWRITE NTH-WHEN-NOT-CONSP-CHEAP)) (2 2 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (2 2 (:REWRITE BOUND-WHEN-USB)) (2 2 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (2 2 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (1 1 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (1 1 (:TYPE-PRESCRIPTION <=-OF-0-AND-EXPT)) (1 1 (:TYPE-PRESCRIPTION <-OF-0-AND-EXPT)) (1 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG1)) ) (BV-ARRAY-READ-OF-NIL) (BV-ARRAY-READ-OF-0-ARG2) (BV-ARRAY-READ-SHORTEN-CORE (53 53 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (34 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (22 1 (:REWRITE TAKE-DOES-NOTHING)) (19 9 (:REWRITE DEFAULT-<-2)) (18 18 (:TYPE-PRESCRIPTION CEILING-OF-LG)) (15 9 (:REWRITE DEFAULT-<-1)) (15 3 (:DEFINITION LEN)) (12 3 (:REWRITE UBP-LONGER-BETTER)) (10 1 (:REWRITE <-OF-EXPT-AND-EXPT)) (9 9 (:REWRITE BOUND-WHEN-USB)) (8 2 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (6 3 (:REWRITE DEFAULT-+-2)) (4 4 (:TYPE-PRESCRIPTION NATP)) (4 2 (:REWRITE NTH-WHEN-ZP-CHEAP)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (4 2 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (3 3 (:REWRITE DEFAULT-CDR)) (3 3 (:REWRITE DEFAULT-+-1)) (3 3 (:REWRITE <-OF-CEILING-OF-LG-AND-CONSTANT)) (3 2 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (3 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (2 2 (:TYPE-PRESCRIPTION ZP)) (2 2 (:TYPE-PRESCRIPTION POSP)) (2 2 (:REWRITE NTH-WHEN-NOT-CONSP-CHEAP)) (2 2 (:REWRITE NTH-WHEN-<=-LEN-CHEAP)) (2 2 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (2 2 (:REWRITE BVCHOP-SUBST-CONSTANT)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (1 1 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (1 1 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (1 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (1 1 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (1 1 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (1 1 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) )
null
https://raw.githubusercontent.com/acl2/acl2/f64742cc6d41c35f9d3f94e154cd5fd409105d34/books/kestrel/bv-lists/.sys/bv-array-read%40useless-runes.lsp
lisp
(BV-ARRAY-READ) (BV-ARRAY-READ-OF-TRUE-LIST-FIX (28 4 (:REWRITE BVCHOP-IDENTITY)) (24 4 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (16 9 (:REWRITE DEFAULT-<-2)) (14 9 (:REWRITE DEFAULT-<-1)) (13 13 (:TYPE-PRESCRIPTION CEILING-OF-LG)) (10 4 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (8 8 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (8 8 (:REWRITE BOUND-WHEN-USB)) (8 4 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (8 4 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (8 4 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (7 4 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (6 6 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (6 2 (:REWRITE NTH-WHEN-ZP-CHEAP)) (6 2 (:REWRITE NTH-WHEN-<=-LEN-CHEAP)) (6 2 (:DEFINITION TRUE-LIST-FIX)) (6 1 (:REWRITE UNSIGNED-BYTE-P-OF-CEILING-OF-LG-WHEN-<)) (4 4 (:TYPE-PRESCRIPTION POSP)) (4 4 (:TYPE-PRESCRIPTION NATP)) (4 4 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (4 4 (:REWRITE BVCHOP-SUBST-CONSTANT)) (4 4 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (3 3 (:REWRITE UBP-LONGER-BETTER)) (3 3 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (3 3 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (3 3 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:TYPE-PRESCRIPTION ZP)) (2 2 (:REWRITE NTH-WHEN-NOT-CONSP-CHEAP)) (2 2 (:REWRITE DEFAULT-CDR)) (2 2 (:REWRITE DEFAULT-CAR)) (2 2 (:REWRITE BVCHOP-NUMERIC-BOUND)) (2 2 (:REWRITE BVCHOP-BOUND)) (2 2 (:REWRITE <-OF-BVCHOP-WHEN-<-OF-BVCHOP-BIGGER)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) ) (BV-ARRAY-READ-OPENER (16 10 (:REWRITE DEFAULT-<-2)) (15 3 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (13 10 (:REWRITE DEFAULT-<-1)) (10 10 (:REWRITE BOUND-WHEN-USB)) (10 1 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (8 1 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (7 7 (:TYPE-PRESCRIPTION NATP)) (7 7 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (6 6 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (6 3 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (5 3 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (5 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (4 4 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (4 2 (:REWRITE NTH-WHEN-ZP-CHEAP)) (4 2 (:REWRITE NTH-WHEN-<=-LEN-CHEAP)) (3 3 (:TYPE-PRESCRIPTION POSP)) (3 3 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (3 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (3 3 (:REWRITE BVCHOP-SUBST-CONSTANT)) (3 3 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:TYPE-PRESCRIPTION ZP)) (2 2 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (2 2 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (2 2 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (2 2 (:REWRITE UBP-LONGER-BETTER)) (2 2 (:REWRITE NTH-WHEN-NOT-CONSP-CHEAP)) (2 2 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (1 1 (:REWRITE INTEGER-LENGTH-WHEN-NOT-INTEGERP-CHEAP)) (1 1 (:REWRITE DEFAULT-+-2)) (1 1 (:REWRITE DEFAULT-+-1)) ) (UNSIGNED-BYTE-P-OF-BV-ARRAY-READ-GEN (50 4 (:REWRITE BVCHOP-IDENTITY)) (35 22 (:REWRITE DEFAULT-<-1)) (25 9 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (23 22 (:REWRITE DEFAULT-<-2)) (19 19 (:REWRITE BOUND-WHEN-USB)) (13 13 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (13 2 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (12 12 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (9 9 (:TYPE-PRESCRIPTION CEILING-OF-LG)) (9 9 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (9 9 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (9 9 (:REWRITE UBP-LONGER-BETTER)) (7 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (6 1 (:REWRITE UNSIGNED-BYTE-P-OF-CEILING-OF-LG-WHEN-<)) (4 4 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (4 4 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (4 4 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (4 4 (:REWRITE BVCHOP-SUBST-CONSTANT)) (4 4 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (4 4 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (4 4 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (3 2 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (3 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (3 2 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (3 1 (:REWRITE NTH-WHEN-ZP-CHEAP)) (3 1 (:REWRITE NTH-WHEN-<=-LEN-CHEAP)) (2 2 (:TYPE-PRESCRIPTION POSP)) (2 2 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (2 2 (:TYPE-PRESCRIPTION <=-OF-0-AND-EXPT)) (2 2 (:TYPE-PRESCRIPTION <-OF-0-AND-EXPT)) (2 2 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG1)) (2 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (1 1 (:TYPE-PRESCRIPTION ZP)) (1 1 (:REWRITE NTH-WHEN-NOT-CONSP-CHEAP)) (1 1 (:REWRITE BVCHOP-NUMERIC-BOUND)) (1 1 (:REWRITE BVCHOP-BOUND)) (1 1 (:REWRITE <-OF-BVCHOP-WHEN-<-OF-BVCHOP-BIGGER)) ) (EQUAL-OF-BVCHOP-OF-CAR-AND-BV-ARRAY-READ (379 48 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (217 57 (:REWRITE DEFAULT-<-1)) (76 38 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (60 57 (:REWRITE DEFAULT-<-2)) (53 53 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (53 53 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (53 53 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (48 48 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (48 48 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (48 48 (:REWRITE UBP-LONGER-BETTER)) (48 48 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (47 47 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (47 47 (:TYPE-PRESCRIPTION <=-OF-0-AND-EXPT)) (47 47 (:TYPE-PRESCRIPTION <-OF-0-AND-EXPT)) (47 47 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (47 47 (:REWRITE BVCHOP-SUBST-CONSTANT)) (38 38 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (38 38 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (38 38 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (38 38 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (38 38 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (36 36 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (19 19 (:REWRITE BOUND-WHEN-USB)) (16 16 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (16 8 (:REWRITE DEFAULT-+-2)) (8 8 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (8 8 (:REWRITE DEFAULT-+-1)) (8 6 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (7 7 (:REWRITE DEFAULT-CDR)) (3 3 (:REWRITE NTH-WHEN-ZP-CHEAP)) (3 3 (:REWRITE NTH-WHEN-NOT-CONSP-CHEAP)) (3 3 (:REWRITE NTH-WHEN-<=-LEN-CHEAP)) (2 2 (:REWRITE BVCHOPS-SAME-WHEN-BVCHOPS-SAME)) ) (BV-ARRAY-READ-OF-BVCHOP-HELPER (107 18 (:REWRITE BVCHOP-IDENTITY)) (68 17 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (50 29 (:REWRITE DEFAULT-<-2)) (40 29 (:REWRITE DEFAULT-<-1)) (36 18 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (30 3 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (29 29 (:REWRITE BOUND-WHEN-USB)) (29 17 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (28 28 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (27 18 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (26 26 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (26 17 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (24 3 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (23 17 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (21 21 (:TYPE-PRESCRIPTION NATP)) (19 18 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (19 6 (:REWRITE NTH-WHEN-ZP-CHEAP)) (19 6 (:REWRITE NTH-WHEN-<=-LEN-CHEAP)) (18 18 (:TYPE-PRESCRIPTION POSP)) (18 18 (:REWRITE BVCHOP-SUBST-CONSTANT)) (18 18 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (14 14 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (14 14 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (14 14 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (14 14 (:REWRITE UBP-LONGER-BETTER)) (11 11 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (10 10 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (9 9 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (9 9 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (9 9 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (8 2 (:REWRITE DEFAULT-+-2)) (7 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP-WHEN-ALREADY)) (6 6 (:TYPE-PRESCRIPTION ZP)) (6 6 (:REWRITE NTH-WHEN-NOT-CONSP-CHEAP)) (6 6 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (4 1 (:REWRITE UNSIGNED-BYTE-P-OF-BVCHOP)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE BVCHOP-NUMERIC-BOUND)) (3 3 (:REWRITE BVCHOP-BOUND)) (3 3 (:REWRITE <-OF-BVCHOP-WHEN-<-OF-BVCHOP-BIGGER)) (2 2 (:REWRITE DEFAULT-+-1)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (1 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) ) (BV-ARRAY-READ-OF-BVCHOP (22 22 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (15 8 (:REWRITE DEFAULT-+-2)) (10 5 (:REWRITE EXPT-2-OF-+-OF--1-AND-INTEGER-LENGTH-WHEN-POWER-OF-2P-CHEAP)) (8 8 (:REWRITE DEFAULT-+-1)) (7 7 (:REWRITE INTEGER-LENGTH-WHEN-NOT-INTEGERP-CHEAP)) (7 1 (:REWRITE BVCHOP-IDENTITY)) (7 1 (:LINEAR <-OF-EXPT-OF-ONE-LESS-OF-INTEGER-LENGTH-LINEAR)) (5 5 (:TYPE-PRESCRIPTION POWER-OF-2P)) (4 3 (:REWRITE DEFAULT-<-2)) (4 3 (:REWRITE DEFAULT-<-1)) (4 1 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (3 3 (:REWRITE BOUND-WHEN-USB)) (2 2 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (2 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (2 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (1 1 (:TYPE-PRESCRIPTION POSP)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (1 1 (:REWRITE UBP-LONGER-BETTER)) (1 1 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (1 1 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (1 1 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (1 1 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (1 1 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (1 1 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (1 1 (:REWRITE BVCHOP-SUBST-CONSTANT)) (1 1 (:REWRITE BVCHOP-IDENTITY-CHEAP)) ) (BV-ARRAY-READ-OF-TAKE (28 4 (:REWRITE BVCHOP-IDENTITY)) (24 4 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (16 9 (:REWRITE DEFAULT-<-2)) (14 9 (:REWRITE DEFAULT-<-1)) (12 1 (:REWRITE TAKE-DOES-NOTHING)) (10 4 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (8 8 (:REWRITE BOUND-WHEN-USB)) (8 4 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (8 4 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (8 4 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (7 4 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (6 6 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (6 6 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (6 2 (:REWRITE NTH-WHEN-ZP-CHEAP)) (6 2 (:REWRITE NTH-WHEN-<=-LEN-CHEAP)) (6 1 (:REWRITE UNSIGNED-BYTE-P-OF-CEILING-OF-LG-WHEN-<)) (5 1 (:DEFINITION LEN)) (4 4 (:TYPE-PRESCRIPTION POSP)) (4 4 (:TYPE-PRESCRIPTION NATP)) (4 4 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (4 4 (:REWRITE BVCHOP-SUBST-CONSTANT)) (4 4 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (3 3 (:REWRITE UBP-LONGER-BETTER)) (3 3 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (3 3 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:TYPE-PRESCRIPTION ZP)) (2 2 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (2 2 (:REWRITE NTH-WHEN-NOT-CONSP-CHEAP)) (2 2 (:REWRITE BVCHOP-NUMERIC-BOUND)) (2 2 (:REWRITE BVCHOP-BOUND)) (2 1 (:REWRITE DEFAULT-+-2)) (1 1 (:REWRITE DEFAULT-CDR)) (1 1 (:REWRITE DEFAULT-+-1)) ) (BV-ARRAY-READ-OF-CONS (84 50 (:REWRITE DEFAULT-<-2)) (77 50 (:REWRITE DEFAULT-<-1)) (54 35 (:REWRITE DEFAULT-+-2)) (49 7 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (47 35 (:REWRITE DEFAULT-+-1)) (42 42 (:REWRITE BOUND-WHEN-USB)) (42 7 (:REWRITE <-OF-INTEGER-LENGTH-ARG2)) (35 35 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (23 16 (:REWRITE INTEGER-LENGTH-WHEN-NOT-INTEGERP-CHEAP)) (21 21 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (20 2 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (17 17 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (16 16 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (16 16 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (16 16 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (16 2 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (14 7 (:REWRITE EXPT-2-OF-+-OF--1-AND-INTEGER-LENGTH-WHEN-POWER-OF-2P-CHEAP)) (14 7 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (14 7 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (14 7 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (14 7 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (14 7 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (11 11 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (10 5 (:REWRITE NTH-WHEN-ZP-CHEAP)) (10 5 (:REWRITE NTH-WHEN-<=-LEN-CHEAP)) (10 1 (:LINEAR INTEGER-LENGTH-BOUND)) (7 7 (:TYPE-PRESCRIPTION POWER-OF-2P)) (7 7 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (7 7 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (7 7 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (7 7 (:REWRITE UBP-LONGER-BETTER)) (7 7 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (7 7 (:REWRITE BVCHOP-SUBST-CONSTANT)) (5 5 (:TYPE-PRESCRIPTION ZP)) (5 5 (:REWRITE NTH-WHEN-NOT-CONSP-CHEAP)) (5 5 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (4 4 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (3 3 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (2 2 (:REWRITE NTH-OF-CONS-CONSTANT-VERSION)) (1 1 (:REWRITE NTH-OF-PLUS-OF-CONS-WHEN-CONSTANT)) ) (BV-ARRAY-READ-OF-CONS-BASE (27 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (16 9 (:REWRITE DEFAULT-<-1)) (15 9 (:REWRITE DEFAULT-<-2)) (15 3 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (10 1 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (9 9 (:REWRITE BOUND-WHEN-USB)) (8 1 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (7 7 (:TYPE-PRESCRIPTION NATP)) (7 7 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (6 6 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (6 3 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (5 3 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (5 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (4 4 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (4 4 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (3 3 (:TYPE-PRESCRIPTION POSP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (3 3 (:REWRITE UBP-LONGER-BETTER)) (3 3 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (3 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (3 3 (:REWRITE BVCHOP-SUBST-CONSTANT)) (3 3 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (3 3 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (2 2 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) (1 1 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) ) (BV-ARRAY-READ-OF-CONS-BOTH (23 14 (:REWRITE DEFAULT-<-2)) (22 4 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (22 4 (:REWRITE BVCHOP-IDENTITY)) (17 14 (:REWRITE DEFAULT-<-1)) (13 13 (:REWRITE BOUND-WHEN-USB)) (12 12 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (10 1 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (9 9 (:TYPE-PRESCRIPTION NATP)) (8 4 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (8 4 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (8 4 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (8 1 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (7 7 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (7 4 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (7 4 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (6 6 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (6 6 (:REWRITE DEFAULT-+-2)) (6 6 (:REWRITE DEFAULT-+-1)) (4 4 (:TYPE-PRESCRIPTION POSP)) (4 4 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (4 4 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (4 4 (:REWRITE BVCHOP-SUBST-CONSTANT)) (4 4 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (4 4 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (4 4 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (3 3 (:REWRITE UBP-LONGER-BETTER)) (3 3 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (2 2 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (2 2 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (2 2 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) ) (BV-ARRAY-READ-OF-1-ARG2 (30 4 (:REWRITE BVCHOP-IDENTITY)) (15 3 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (11 5 (:REWRITE DEFAULT-<-2)) (11 5 (:REWRITE DEFAULT-<-1)) (11 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (10 1 (:LINEAR BVCHOP-UPPER-BOUND-LINEAR-STRONG)) (8 1 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR)) (7 7 (:TYPE-PRESCRIPTION NATP)) (6 3 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (6 3 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (6 1 (:DEFINITION NATP)) (5 5 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (5 5 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (5 3 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (5 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (4 4 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (4 4 (:REWRITE BVCHOP-SUBST-CONSTANT)) (4 4 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (4 4 (:REWRITE BOUND-WHEN-USB)) (4 4 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (4 4 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (4 2 (:REWRITE NTH-WHEN-<=-LEN-CHEAP)) (3 3 (:TYPE-PRESCRIPTION POSP)) (3 3 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (3 3 (:REWRITE UBP-LONGER-BETTER)) (3 3 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (2 2 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (2 2 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (2 2 (:REWRITE NTH-WHEN-ZP-CHEAP)) (2 2 (:REWRITE NTH-WHEN-NOT-CONSP-CHEAP)) (2 2 (:LINEAR <=-OF-BVCHOP-SAME-LINEAR-2)) (1 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG1)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P-SIZE-ARG)) (1 1 (:REWRITE NATP-WHEN-UNSIGNED-BYTE-P)) ) (BV-ARRAY-READ-OF-1-ARG2-BETTER (20 3 (:REWRITE BVCHOP-IDENTITY)) (9 3 (:REWRITE DEFAULT-<-2)) (8 2 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (7 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (4 4 (:TYPE-PRESCRIPTION NATP)) (4 2 (:REWRITE NTH-WHEN-<=-LEN-CHEAP)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (4 2 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (3 3 (:TYPE-PRESCRIPTION UNSIGNED-BYTE-P)) (3 3 (:REWRITE DEFAULT-<-1)) (3 3 (:REWRITE BVCHOP-SUBST-CONSTANT)) (3 3 (:REWRITE BVCHOP-IDENTITY-CHEAP)) (3 2 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (3 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (2 2 (:TYPE-PRESCRIPTION POSP)) (2 2 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (2 2 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (2 2 (:REWRITE UBP-LONGER-BETTER)) (2 2 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (2 2 (:REWRITE NTH-WHEN-ZP-CHEAP)) (2 2 (:REWRITE NTH-WHEN-NOT-CONSP-CHEAP)) (2 2 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (2 2 (:REWRITE BOUND-WHEN-USB)) (2 2 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (2 2 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (1 1 (:TYPE-PRESCRIPTION INTEGERP-OF-EXPT-TYPE)) (1 1 (:TYPE-PRESCRIPTION <=-OF-0-AND-EXPT)) (1 1 (:TYPE-PRESCRIPTION <-OF-0-AND-EXPT)) (1 1 (:REWRITE UNSIGNED-BYTE-P-OF-0-ARG1)) ) (BV-ARRAY-READ-OF-NIL) (BV-ARRAY-READ-OF-0-ARG2) (BV-ARRAY-READ-SHORTEN-CORE (53 53 (:TYPE-PRESCRIPTION NATP-OF-EXPT)) (34 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUND)) (22 1 (:REWRITE TAKE-DOES-NOTHING)) (19 9 (:REWRITE DEFAULT-<-2)) (18 18 (:TYPE-PRESCRIPTION CEILING-OF-LG)) (15 9 (:REWRITE DEFAULT-<-1)) (15 3 (:DEFINITION LEN)) (12 3 (:REWRITE UBP-LONGER-BETTER)) (10 1 (:REWRITE <-OF-EXPT-AND-EXPT)) (9 9 (:REWRITE BOUND-WHEN-USB)) (8 2 (:REWRITE BVCHOP-WITH-N-NEGATIVE)) (6 3 (:REWRITE DEFAULT-+-2)) (4 4 (:TYPE-PRESCRIPTION NATP)) (4 2 (:REWRITE NTH-WHEN-ZP-CHEAP)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-POSP)) (4 2 (:REWRITE BVCHOP-WHEN-SIZE-IS-NOT-NATP)) (4 2 (:REWRITE BVCHOP-WHEN-NOT-NATP-ARG1-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-WHEN-<=-CHEAP)) (3 3 (:REWRITE UNSIGNED-BYTE-P-FROM-BOUNDS)) (3 3 (:REWRITE DEFAULT-CDR)) (3 3 (:REWRITE DEFAULT-+-1)) (3 3 (:REWRITE <-OF-CEILING-OF-LG-AND-CONSTANT)) (3 2 (:REWRITE BVCHOP-WITH-N-NOT-AN-INTEGER)) (3 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER)) (2 2 (:TYPE-PRESCRIPTION ZP)) (2 2 (:TYPE-PRESCRIPTION POSP)) (2 2 (:REWRITE NTH-WHEN-NOT-CONSP-CHEAP)) (2 2 (:REWRITE NTH-WHEN-<=-LEN-CHEAP)) (2 2 (:REWRITE INTEGERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (2 2 (:REWRITE BVCHOP-WHEN-I-IS-NOT-AN-INTEGER-CHEAP)) (2 2 (:REWRITE BVCHOP-SUBST-CONSTANT)) (1 1 (:REWRITE UNSIGNED-BYTE-P-WHEN-SIZE-IS-NEGATIVE-LIMITED)) (1 1 (:REWRITE UNSIGNED-BYTE-P-FALSE-WHEN-NOT-LONGER)) (1 1 (:REWRITE SIZE-NON-NEGATIVE-WHEN-UNSIGNED-BYTE-P-FREE)) (1 1 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (1 1 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE)) (1 1 (:REWRITE BVCHOP-IMPOSSIBLE-VALUE)) (1 1 (:REWRITE ACL2-NUMBERP-WHEN-UNSIGNED-BYTE-P)) (1 1 (:REWRITE ACL2-NUMBERP-FROM-UNSIGNED-BYTE-P-SIZE-PARAM)) (1 1 (:REWRITE <-OF-EXPT-2-AND-CONSTANT)) )
9c27967179705d8f8d40d5d8aed6ec17a6fd9a9dfd18537d8b824d925cbc4c5f
rtoy/ansi-cl-tests
labels.lsp
;-*- Mode: Lisp -*- Author : Created : We d Oct 9 19:06:33 2002 ;;;; Contains: Tests of LABELS (in-package :cl-test) (deftest labels.1 (labels ((%f () 1)) (%f)) 1) (deftest labels.2 (labels ((%f (x) x)) (%f 2)) 2) (deftest labels.3 (labels ((%f (&rest args) args)) (%f 'a 'b 'c)) (a b c)) ;;; The optional arguments are not in the block defined by ;;; the local function declaration (deftest labels.4 (block %f (labels ((%f (&optional (x (return-from %f :good))) nil)) (%f) :bad)) :good) ;;; Keyword parameter initializers are not in the blocked defined ;;; by the local function declaration (deftest labels.4a (block %f (labels ((%f (&key (x (return-from %f :good))) nil)) (%f) :bad)) :good) (deftest labels.5 (labels ((%f () (return-from %f 15) 35)) (%f)) 15) ;;; The aux parameters are not in the block defined by ;;; the local function declaration (deftest labels.6 (block %f (labels ((%f (&aux (x (return-from %f 10))) 20)) (%f) :bad)) 10) ;;; The function is visible inside itself (deftest labels.7 (labels ((%f (x n) (cond ((eql n 0) x) (t (%f (+ x n) (1- n)))))) (%f 0 10)) 55) Scope of defined function names includes & AUX parameters (deftest labels.7b (labels ((%f (x &aux (b (%g x))) b) (%g (y) (+ y y))) (%f 10)) 20) Scope of defined function names includes & OPTIONAL parameters (deftest labels.7c (labels ((%f (x &optional (b (%g x))) b) (%g (y) (+ y y))) (%f 10)) 20) ;;; Scope of defined function names includes &KEY parameters (deftest labels.7d (labels ((%f (x &key (b (%g x))) b) (%g (y) (+ y y))) (%f 10)) 20) ;;; Keyword arguments (deftest labels.8 (labels ((%f (&key a (b 0 b-p)) (values a b (not (not b-p))))) (%f)) nil 0 nil) (deftest labels.9 (labels ((%f (&key a (b 0 b-p)) (values a b (not (not b-p))))) (%f :a 1)) 1 0 nil) (deftest labels.10 (labels ((%f (&key a (b 0 b-p)) (values a b (not (not b-p))))) (%f :b 2)) nil 2 t) (deftest labels.11 (labels ((%f (&key a (b 0 b-p)) (values a b (not (not b-p))))) (%f :b 2 :a 3)) 3 2 t) ;;; Unknown keyword parameter should throw a program-error in safe code ;;; (section 3.5.1.4) (deftest labels.12 (signals-error (labels ((%f (&key a (b 0 b-p)) (values a b (not (not b-p))))) (%f :c 4)) program-error) t) ;;; Odd # of keyword args should throw a program-error in safe code ( section 3.5.1.6 ) (deftest labels.13 (signals-error (labels ((%f (&key a (b 0 b-p)) (values a b (not (not b-p))))) (%f :a)) program-error) t) Too few arguments ( section 3.5.1.2 ) (deftest labels.14 (signals-error (labels ((%f (a) a)) (%f)) program-error) t) ;;; Too many arguments (section 3.5.1.3) (deftest labels.15 (signals-error (labels ((%f (a) a)) (%f 1 2)) program-error) t) Invalid keyword argument ( section 3.5.1.5 ) (deftest labels.16 (signals-error (labels ((%f (&key a) a)) (%f '(foo))) program-error) t) Definition of a ( setf ... ) function (deftest labels.17 (labels (((setf %f) (x y) (setf (car y) x))) (let ((z (list 1 2))) (setf (%f z) 'a) z)) (a 2)) ;;; Body is an implicit progn (deftest labels.18 (labels ((%f (x) (incf x) (+ x x))) (%f 10)) 22) Can handle at least 50 lambda parameters (deftest labels.19 (labels ((%f (a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 b1 b2 b3 b4 b5 b6 b7 b8 b9 b10 c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 d1 d2 d3 d4 d5 d6 d7 d8 d9 d10 e1 e2 e3 e4 e5 e6 e7 e8 e9 e10) (+ a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 b1 b2 b3 b4 b5 b6 b7 b8 b9 b10 c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 d1 d2 d3 d4 d5 d6 d7 d8 d9 d10 e1 e2 e3 e4 e5 e6 e7 e8 e9 e10))) (%f 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50)) 1275) ;;; labels works with the maximum number of arguments (if ;;; not too many.) (deftest labels.20 (let* ((n (min (1- lambda-parameters-limit) 1024)) (vars (loop repeat n collect (gensym)))) (eval `(eqlt ,n (labels ((%f ,vars (+ ,@ vars))) (%f ,@(loop for e in vars collect 1)))))) t) ;;; Declarations and documentation strings are ok (deftest labels.21 (labels ((%f (x) (declare (type fixnum x)) "Add one to the fixnum x." (1+ x))) (declare (ftype (function (fixnum) integer) %f)) (%f 10)) 11) ;;; Keywords can be function names (deftest labels.22 (labels ((:foo () 10) (:bar () (1+ (:foo)))) (:bar)) 11) (deftest labels.23 (labels ((:foo () 10) (:bar () (1+ (funcall #':foo)))) (funcall #':bar)) 11) (deftest labels.24 (loop for s in *cl-non-function-macro-special-operator-symbols* for form = `(ignore-errors (labels ((,s (x) (foo (1- x))) (foo (y) (if (<= y 0) 'a (,s (1- y))))) (,s 10))) unless (eq (eval form) 'a) collect s) nil) (deftest labels.25 (loop for s in *cl-non-function-macro-special-operator-symbols* for form = `(ignore-errors (labels ((,s (x) (foo (1- x))) (foo (y) (if (<= y 0) 'a (,s (1- y))))) (declare (ftype (function (integer) symbol) foo ,s)) (,s 10))) unless (eq (eval form) 'a) collect s) nil) (deftest labels.26 (loop for s in *cl-non-function-macro-special-operator-symbols* for form = `(ignore-errors (labels (((setf ,s) (&rest args) (declare (ignore args)) 'a)) (setf (,s) 10))) unless (eq (eval form) 'a) collect s) nil) ;;; Check that LABELS does not have a tagbody (deftest labels.27 (block done (tagbody (labels ((%f () (go 10) 10 (return-from done 'bad))) (%f)) 10 (return-from done 'good))) good) ;;; Check that nil keyword arguments do not enable the default values (deftest labels.28 (labels ((%f (&key (a 'wrong)) a)) (%f :a nil)) nil) (deftest labels.29 (labels ((%f (&key (a 'wrong a-p)) (list a (not a-p)))) (%f :a nil)) (nil nil)) (deftest labels.30 (labels ((%f (&key ((:a b) 'wrong)) b)) (%f :a nil)) nil) (deftest labels.31 (labels ((%f (&key ((:a b) 'wrong present?)) (list b (not present?)))) (%f :a nil)) (nil nil)) (deftest labels.32 (labels ((%f (&key) 'good)) (%f :allow-other-keys nil)) good) (deftest labels.33 (labels ((%f (&key) 'good)) (%f :allow-other-keys t)) good) (deftest labels.34 (labels ((%f (&key) 'good)) (%f :allow-other-keys t :a 1 :b 2)) good) (deftest labels.35 (labels ((%f (&key &allow-other-keys) 'good)) (%f :a 1 :b 2)) good) NIL as a disallowed keyword argument (deftest labels.36 (signals-error (labels ((%f (&key) :bad)) (%f nil nil)) program-error) t) ;;; Identity of function objects ;;; Since (FUNCTION <name>) returns *the* functional value, it ;;; should be the case that different invocations of this form ;;; in the same lexical environment return the same value. (deftest labels.37 (labels ((f () 'foo)) (eqt #'f #'f)) t) (deftest labels.38 (labels ((f () 'foo)) (destructuring-bind (x y) (loop repeat 2 collect #'f) (eqlt x y))) t) (deftest labels.39 (labels ((f () #'f)) (eqlt (f) #'f)) t) (deftest labels.40 (let ((x (labels ((f () #'f)) #'f))) (eqlt x (funcall x))) t) ;;; Test that free declarations do not affect argument forms (deftest labels.41 (let ((x :bad)) (declare (special x)) (let ((x :good)) (labels ((%f (&optional (y x)) (declare (special x)) y)) (%f)))) :good) (deftest labels.42 (let ((x :bad)) (declare (special x)) (let ((x :good)) (labels ((%f (&key (y x)) (declare (special x)) y)) (%f)))) :good) (deftest labels.43 (let ((x :bad)) (declare (special x)) (let ((x :good)) (labels () (declare (special x))) x)) :good) (deftest labels.44 (let ((x :bad)) (declare (special x)) (let ((x :good)) (labels ((%f () (declare (special x))))) x)) :good) (deftest labels.45 (let ((x :bad)) (declare (special x)) (let ((x :good)) (labels ((%f () (declare (special x)))) x))) :good) (deftest labels.46 (let ((x :bad)) (declare (special x)) (let ((x :good)) (labels ((%f (&aux (y x)) (declare (special x)) y)) (%f)))) :good) (deftest labels.47 (let ((x :bad)) (declare (special x)) (let ((x :good)) (labels ((%f () x)) (declare (special x)) (%f)))) :good) Macros are expanded in the appropriate environment (deftest labels.48 (macrolet ((%m (z) z)) (labels () (expand-in-current-env (%m :good)))) :good) (deftest labels.49 (macrolet ((%m (z) z)) (labels ((%f () (expand-in-current-env (%m :good)))) (%f))) :good) ;;; local function bindings shadow global functions, macros ;;; and compiler-macros (defun labels.50 () :bad) (deftest labels.50 (labels ((labels.50 () :good)) (labels.50)) :good) (defmacro labels.51 () :bad) (deftest labels.51 (labels ((labels.51 () :good)) (labels.51)) :good) (define-compiler-macro labels.52 (&whole form) :bad) (deftest labels.52 (labels ((labels.52 () :good)) (labels.52)) :good)
null
https://raw.githubusercontent.com/rtoy/ansi-cl-tests/9708f3977220c46def29f43bb237e97d62033c1d/labels.lsp
lisp
-*- Mode: Lisp -*- Contains: Tests of LABELS The optional arguments are not in the block defined by the local function declaration Keyword parameter initializers are not in the blocked defined by the local function declaration The aux parameters are not in the block defined by the local function declaration The function is visible inside itself Scope of defined function names includes &KEY parameters Keyword arguments Unknown keyword parameter should throw a program-error in safe code (section 3.5.1.4) Odd # of keyword args should throw a program-error in safe code Too many arguments (section 3.5.1.3) Body is an implicit progn labels works with the maximum number of arguments (if not too many.) Declarations and documentation strings are ok Keywords can be function names Check that LABELS does not have a tagbody Check that nil keyword arguments do not enable the default values Identity of function objects Since (FUNCTION <name>) returns *the* functional value, it should be the case that different invocations of this form in the same lexical environment return the same value. Test that free declarations do not affect argument forms local function bindings shadow global functions, macros and compiler-macros
Author : Created : We d Oct 9 19:06:33 2002 (in-package :cl-test) (deftest labels.1 (labels ((%f () 1)) (%f)) 1) (deftest labels.2 (labels ((%f (x) x)) (%f 2)) 2) (deftest labels.3 (labels ((%f (&rest args) args)) (%f 'a 'b 'c)) (a b c)) (deftest labels.4 (block %f (labels ((%f (&optional (x (return-from %f :good))) nil)) (%f) :bad)) :good) (deftest labels.4a (block %f (labels ((%f (&key (x (return-from %f :good))) nil)) (%f) :bad)) :good) (deftest labels.5 (labels ((%f () (return-from %f 15) 35)) (%f)) 15) (deftest labels.6 (block %f (labels ((%f (&aux (x (return-from %f 10))) 20)) (%f) :bad)) 10) (deftest labels.7 (labels ((%f (x n) (cond ((eql n 0) x) (t (%f (+ x n) (1- n)))))) (%f 0 10)) 55) Scope of defined function names includes & AUX parameters (deftest labels.7b (labels ((%f (x &aux (b (%g x))) b) (%g (y) (+ y y))) (%f 10)) 20) Scope of defined function names includes & OPTIONAL parameters (deftest labels.7c (labels ((%f (x &optional (b (%g x))) b) (%g (y) (+ y y))) (%f 10)) 20) (deftest labels.7d (labels ((%f (x &key (b (%g x))) b) (%g (y) (+ y y))) (%f 10)) 20) (deftest labels.8 (labels ((%f (&key a (b 0 b-p)) (values a b (not (not b-p))))) (%f)) nil 0 nil) (deftest labels.9 (labels ((%f (&key a (b 0 b-p)) (values a b (not (not b-p))))) (%f :a 1)) 1 0 nil) (deftest labels.10 (labels ((%f (&key a (b 0 b-p)) (values a b (not (not b-p))))) (%f :b 2)) nil 2 t) (deftest labels.11 (labels ((%f (&key a (b 0 b-p)) (values a b (not (not b-p))))) (%f :b 2 :a 3)) 3 2 t) (deftest labels.12 (signals-error (labels ((%f (&key a (b 0 b-p)) (values a b (not (not b-p))))) (%f :c 4)) program-error) t) ( section 3.5.1.6 ) (deftest labels.13 (signals-error (labels ((%f (&key a (b 0 b-p)) (values a b (not (not b-p))))) (%f :a)) program-error) t) Too few arguments ( section 3.5.1.2 ) (deftest labels.14 (signals-error (labels ((%f (a) a)) (%f)) program-error) t) (deftest labels.15 (signals-error (labels ((%f (a) a)) (%f 1 2)) program-error) t) Invalid keyword argument ( section 3.5.1.5 ) (deftest labels.16 (signals-error (labels ((%f (&key a) a)) (%f '(foo))) program-error) t) Definition of a ( setf ... ) function (deftest labels.17 (labels (((setf %f) (x y) (setf (car y) x))) (let ((z (list 1 2))) (setf (%f z) 'a) z)) (a 2)) (deftest labels.18 (labels ((%f (x) (incf x) (+ x x))) (%f 10)) 22) Can handle at least 50 lambda parameters (deftest labels.19 (labels ((%f (a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 b1 b2 b3 b4 b5 b6 b7 b8 b9 b10 c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 d1 d2 d3 d4 d5 d6 d7 d8 d9 d10 e1 e2 e3 e4 e5 e6 e7 e8 e9 e10) (+ a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 b1 b2 b3 b4 b5 b6 b7 b8 b9 b10 c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 d1 d2 d3 d4 d5 d6 d7 d8 d9 d10 e1 e2 e3 e4 e5 e6 e7 e8 e9 e10))) (%f 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50)) 1275) (deftest labels.20 (let* ((n (min (1- lambda-parameters-limit) 1024)) (vars (loop repeat n collect (gensym)))) (eval `(eqlt ,n (labels ((%f ,vars (+ ,@ vars))) (%f ,@(loop for e in vars collect 1)))))) t) (deftest labels.21 (labels ((%f (x) (declare (type fixnum x)) "Add one to the fixnum x." (1+ x))) (declare (ftype (function (fixnum) integer) %f)) (%f 10)) 11) (deftest labels.22 (labels ((:foo () 10) (:bar () (1+ (:foo)))) (:bar)) 11) (deftest labels.23 (labels ((:foo () 10) (:bar () (1+ (funcall #':foo)))) (funcall #':bar)) 11) (deftest labels.24 (loop for s in *cl-non-function-macro-special-operator-symbols* for form = `(ignore-errors (labels ((,s (x) (foo (1- x))) (foo (y) (if (<= y 0) 'a (,s (1- y))))) (,s 10))) unless (eq (eval form) 'a) collect s) nil) (deftest labels.25 (loop for s in *cl-non-function-macro-special-operator-symbols* for form = `(ignore-errors (labels ((,s (x) (foo (1- x))) (foo (y) (if (<= y 0) 'a (,s (1- y))))) (declare (ftype (function (integer) symbol) foo ,s)) (,s 10))) unless (eq (eval form) 'a) collect s) nil) (deftest labels.26 (loop for s in *cl-non-function-macro-special-operator-symbols* for form = `(ignore-errors (labels (((setf ,s) (&rest args) (declare (ignore args)) 'a)) (setf (,s) 10))) unless (eq (eval form) 'a) collect s) nil) (deftest labels.27 (block done (tagbody (labels ((%f () (go 10) 10 (return-from done 'bad))) (%f)) 10 (return-from done 'good))) good) (deftest labels.28 (labels ((%f (&key (a 'wrong)) a)) (%f :a nil)) nil) (deftest labels.29 (labels ((%f (&key (a 'wrong a-p)) (list a (not a-p)))) (%f :a nil)) (nil nil)) (deftest labels.30 (labels ((%f (&key ((:a b) 'wrong)) b)) (%f :a nil)) nil) (deftest labels.31 (labels ((%f (&key ((:a b) 'wrong present?)) (list b (not present?)))) (%f :a nil)) (nil nil)) (deftest labels.32 (labels ((%f (&key) 'good)) (%f :allow-other-keys nil)) good) (deftest labels.33 (labels ((%f (&key) 'good)) (%f :allow-other-keys t)) good) (deftest labels.34 (labels ((%f (&key) 'good)) (%f :allow-other-keys t :a 1 :b 2)) good) (deftest labels.35 (labels ((%f (&key &allow-other-keys) 'good)) (%f :a 1 :b 2)) good) NIL as a disallowed keyword argument (deftest labels.36 (signals-error (labels ((%f (&key) :bad)) (%f nil nil)) program-error) t) (deftest labels.37 (labels ((f () 'foo)) (eqt #'f #'f)) t) (deftest labels.38 (labels ((f () 'foo)) (destructuring-bind (x y) (loop repeat 2 collect #'f) (eqlt x y))) t) (deftest labels.39 (labels ((f () #'f)) (eqlt (f) #'f)) t) (deftest labels.40 (let ((x (labels ((f () #'f)) #'f))) (eqlt x (funcall x))) t) (deftest labels.41 (let ((x :bad)) (declare (special x)) (let ((x :good)) (labels ((%f (&optional (y x)) (declare (special x)) y)) (%f)))) :good) (deftest labels.42 (let ((x :bad)) (declare (special x)) (let ((x :good)) (labels ((%f (&key (y x)) (declare (special x)) y)) (%f)))) :good) (deftest labels.43 (let ((x :bad)) (declare (special x)) (let ((x :good)) (labels () (declare (special x))) x)) :good) (deftest labels.44 (let ((x :bad)) (declare (special x)) (let ((x :good)) (labels ((%f () (declare (special x))))) x)) :good) (deftest labels.45 (let ((x :bad)) (declare (special x)) (let ((x :good)) (labels ((%f () (declare (special x)))) x))) :good) (deftest labels.46 (let ((x :bad)) (declare (special x)) (let ((x :good)) (labels ((%f (&aux (y x)) (declare (special x)) y)) (%f)))) :good) (deftest labels.47 (let ((x :bad)) (declare (special x)) (let ((x :good)) (labels ((%f () x)) (declare (special x)) (%f)))) :good) Macros are expanded in the appropriate environment (deftest labels.48 (macrolet ((%m (z) z)) (labels () (expand-in-current-env (%m :good)))) :good) (deftest labels.49 (macrolet ((%m (z) z)) (labels ((%f () (expand-in-current-env (%m :good)))) (%f))) :good) (defun labels.50 () :bad) (deftest labels.50 (labels ((labels.50 () :good)) (labels.50)) :good) (defmacro labels.51 () :bad) (deftest labels.51 (labels ((labels.51 () :good)) (labels.51)) :good) (define-compiler-macro labels.52 (&whole form) :bad) (deftest labels.52 (labels ((labels.52 () :good)) (labels.52)) :good)
027685a789375311bae443b96c8a6c46676bc0246bc49b5a9dd501627d42d9dc
fdopen/ppx_cstubs
ppx_cstubs_custom.mli
This file is part of ppx_cstubs ( ) * Copyright ( c ) 2018 - 2019 fdopen * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * Copyright (c) 2018-2019 fdopen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) val init : unit -> unit
null
https://raw.githubusercontent.com/fdopen/ppx_cstubs/5d5ce9b7cf45d87bb71c046a76d30c17ec6075e5/src/custom/ppx_cstubs_custom.mli
ocaml
This file is part of ppx_cstubs ( ) * Copyright ( c ) 2018 - 2019 fdopen * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * Copyright (c) 2018-2019 fdopen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) val init : unit -> unit
1f4d307767eff1c1d05b1d9d3b027e915504d54e5cca7d1c3a5b9989403ba242
opencog/pln
simple-implication-scope.scm
(ImplicationScope (stv 1 1) (TypedVariable (Variable "$X") (Type "ConceptNode")) (Evaluation (Predicate "P") (Variable "$X")) (Evaluation (Predicate "Q") (Variable "$X")))
null
https://raw.githubusercontent.com/opencog/pln/52dc099e21393892cf5529fef687a69682436b2d/tests/pln/rules/simple-implication-scope.scm
scheme
(ImplicationScope (stv 1 1) (TypedVariable (Variable "$X") (Type "ConceptNode")) (Evaluation (Predicate "P") (Variable "$X")) (Evaluation (Predicate "Q") (Variable "$X")))
05b37cba705567e275cc51753cd3771a80b36e286ebf393eb2ed119f3fc60b00
Ericson2314/lighthouse
Internals.hs
# OPTIONS_GHC -cpp -fffi # ----------------------------------------------------------------------------- -- | -- Module : System.Process.Internals Copyright : ( c ) The University of Glasgow 2004 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : -- Stability : experimental -- Portability : portable -- Operations for creating and interacting with sub - processes . -- ----------------------------------------------------------------------------- -- #hide module System.Process.Internals ( #ifndef __HUGS__ ProcessHandle(..), ProcessHandle__(..), PHANDLE, closePHANDLE, mkProcessHandle, withProcessHandle, withProcessHandle_, #endif #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__) pPrPr_disableITimers, c_execvpe, # ifdef __GLASGOW_HASKELL__ runProcessPosix, # endif ignoreSignal, defaultSignal, #else # ifdef __GLASGOW_HASKELL__ runProcessWin32, translate, # endif #endif #ifndef __HUGS__ commandToProcess, #endif withFilePathException, withCEnvironment ) where import Prelude -- necessary to get dependencies right #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__) import System.Posix.Types ( CPid ) import System.Posix.Process.Internals ( pPrPr_disableITimers, c_execvpe ) import System.IO ( Handle ) #else import Data.Word ( Word32 ) import Data.IORef #endif import System.Exit ( ExitCode ) import Data.Maybe ( fromMaybe ) # ifdef __GLASGOW_HASKELL__ import GHC.IOBase ( haFD, FD, Exception(..), IOException(..) ) import GHC.Handle ( stdin, stdout, stderr, withHandle_ ) # elif __HUGS__ import Hugs.Exception ( Exception(..), IOException(..) ) # endif import Control.Concurrent import Control.Exception ( handle, throwIO ) import Foreign.C import Foreign #if defined(mingw32_HOST_OS) import Control.Monad ( when ) import System.Directory ( doesFileExist ) import Control.Exception ( catchJust, ioErrors ) import System.IO.Error ( isDoesNotExistError, doesNotExistErrorType, mkIOError ) import System.Environment ( getEnv ) import System.FilePath #endif #ifdef __HUGS__ # CFILES cbits / execvpe.c # #endif #include "HsProcessConfig.h" #ifndef __HUGS__ -- ---------------------------------------------------------------------------- -- ProcessHandle type {- | A handle to a process, which can be used to wait for termination of the process using 'waitForProcess'. None of the process-creation functions in this library wait for termination: they all return a 'ProcessHandle' which may be used to wait for the process later. -} data ProcessHandle__ = OpenHandle PHANDLE | ClosedHandle ExitCode newtype ProcessHandle = ProcessHandle (MVar ProcessHandle__) withProcessHandle :: ProcessHandle -> (ProcessHandle__ -> IO (ProcessHandle__, a)) -> IO a withProcessHandle (ProcessHandle m) io = modifyMVar m io withProcessHandle_ :: ProcessHandle -> (ProcessHandle__ -> IO ProcessHandle__) -> IO () withProcessHandle_ (ProcessHandle m) io = modifyMVar_ m io #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__) type PHANDLE = CPid mkProcessHandle :: PHANDLE -> IO ProcessHandle mkProcessHandle p = do m <- newMVar (OpenHandle p) return (ProcessHandle m) closePHANDLE :: PHANDLE -> IO () closePHANDLE _ = return () #else type PHANDLE = Word32 On Windows , we have to close this HANDLE when it is no longer required , -- hence we add a finalizer to it, using an IORef as the box on which to -- attach the finalizer. mkProcessHandle :: PHANDLE -> IO ProcessHandle mkProcessHandle h = do m <- newMVar (OpenHandle h) addMVarFinalizer m (processHandleFinaliser m) return (ProcessHandle m) processHandleFinaliser m = modifyMVar_ m $ \p_ -> do case p_ of OpenHandle ph -> closePHANDLE ph _ -> return () return (error "closed process handle") closePHANDLE :: PHANDLE -> IO () closePHANDLE ph = c_CloseHandle ph foreign import stdcall unsafe "CloseHandle" c_CloseHandle :: PHANDLE -> IO () #endif #endif /* !__HUGS__ */ -- ---------------------------------------------------------------------------- #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__) #ifdef __GLASGOW_HASKELL__ -- ----------------------------------------------------------------------------- -- POSIX runProcess with signal handling in the child runProcessPosix :: String -> FilePath -- ^ Filename of the executable -> [String] -- ^ Arguments to pass to the executable -> Maybe FilePath -- ^ Optional path to the working directory -> Maybe [(String,String)] -- ^ Optional environment (otherwise inherit) -> Maybe Handle -- ^ Handle to use for @stdin@ -> Maybe Handle -- ^ Handle to use for @stdout@ ^ Handle to use for @stderr@ -> Maybe CLong -- handler for SIGINT handler for SIGQUIT -> IO ProcessHandle runProcessPosix fun cmd args mb_cwd mb_env mb_stdin mb_stdout mb_stderr mb_sigint mb_sigquit = withFilePathException cmd $ do fd_stdin <- withHandle_ fun (fromMaybe stdin mb_stdin) $ return . haFD fd_stdout <- withHandle_ fun (fromMaybe stdout mb_stdout) $ return . haFD fd_stderr <- withHandle_ fun (fromMaybe stderr mb_stderr) $ return . haFD -- some of these might refer to the same Handle, so don't do nested withHandle _ 's ( that will deadlock ) . maybeWith withCEnvironment mb_env $ \pEnv -> do maybeWith withCString mb_cwd $ \pWorkDir -> do withMany withCString (cmd:args) $ \cstrs -> do let (set_int, inthand) = case mb_sigint of Nothing -> (0, 0) Just hand -> (1, hand) (set_quit, quithand) = case mb_sigquit of Nothing -> (0, 0) Just hand -> (1, hand) withArray0 nullPtr cstrs $ \pargs -> do ph <- throwErrnoIfMinus1 fun $ c_runProcess pargs pWorkDir pEnv fd_stdin fd_stdout fd_stderr set_int inthand set_quit quithand mkProcessHandle ph foreign import ccall unsafe "runProcess" c_runProcess :: Ptr CString -- args -> CString -- working directory (or NULL) -> Ptr CString -- env (or NULL) stdin -> FD -- stdout -> FD -- stderr -> CInt -- non-zero: set child's SIGINT handler -> CLong -- SIGINT handler non - zero : set child 's SIGQUIT handler SIGQUIT handler -> IO PHANDLE #endif /* __GLASGOW_HASKELL__ */ ignoreSignal = CONST_SIG_IGN :: CLong defaultSignal = CONST_SIG_DFL :: CLong #else #ifdef __GLASGOW_HASKELL__ runProcessWin32 fun cmd args mb_cwd mb_env mb_stdin mb_stdout mb_stderr extra_cmdline = withFilePathException cmd $ do fd_stdin <- withHandle_ fun (fromMaybe stdin mb_stdin) $ return . haFD fd_stdout <- withHandle_ fun (fromMaybe stdout mb_stdout) $ return . haFD fd_stderr <- withHandle_ fun (fromMaybe stderr mb_stderr) $ return . haFD -- some of these might refer to the same Handle, so don't do nested withHandle _ 's ( that will deadlock ) . maybeWith withCEnvironment mb_env $ \pEnv -> do maybeWith withCString mb_cwd $ \pWorkDir -> do let cmdline = translate cmd ++ concat (map ((' ':) . translate) args) ++ (if null extra_cmdline then "" else ' ':extra_cmdline) withCString cmdline $ \pcmdline -> do proc_handle <- throwErrnoIfMinus1 fun (c_runProcess pcmdline pWorkDir pEnv fd_stdin fd_stdout fd_stderr) mkProcessHandle proc_handle foreign import ccall unsafe "runProcess" c_runProcess :: CString -> CString -> Ptr () -> FD -> FD -> FD -> IO PHANDLE -- ------------------------------------------------------------------------ Passing commands to the OS on Windows On Windows this is tricky . We use CreateProcess , passing a single command - line string ( lpCommandLine ) as its argument . ( CreateProcess is well documented on . ) - It parses the beginning of the string to find the command . If the file name has embedded spaces , it must be quoted , using double quotes thus " foo\this that\cmd " arg1 arg2 - The invoked command can in turn access the entire lpCommandLine string , and the C runtime does indeed do so , parsing it to generate the traditional argument vector argv[0 ] , argv[1 ] , etc . It does this using a complex and arcane set of rules which are described here : -us/vccelng/htm/progs_12.asp ( if this URL stops working , you might be able to find it by searching for " Parsing C Command - Line Arguments " on MSDN . Also , the code in the Microsoft C runtime that does this translation is shipped with VC++ ) . Our goal in runProcess is to take a command filename and list of arguments , and construct a string which inverts the translatsions described above , such that the program at the other end sees exactly the same arguments in its argv [ ] that we passed to . This inverse translation is implemented by ' translate ' below . Here are some pages that give informations on Windows - related limitations and deviations from Unix conventions : ;en-us;830473 Command lines and environment variables effectively limited to 8191 characters on Win XP , 2047 on NT/2000 ( probably even less on Win 9x ): Command - line substitution under Windows XP . IIRC these facilities ( or at least a large subset of them ) are available on Win NT and 2000 . Some might be available on Win 9x . How CMD.EXE processes command lines . Note : CreateProcess does have a separate argument ( lpApplicationName ) with which you can specify the command , but we have to slap the command into lpCommandLine anyway , so that argv[0 ] is what a C program expects ( namely the application name ) . So it seems simpler to just use lpCommandLine alone , which CreateProcess supports . On Windows this is tricky. We use CreateProcess, passing a single command-line string (lpCommandLine) as its argument. (CreateProcess is well documented on .) - It parses the beginning of the string to find the command. If the file name has embedded spaces, it must be quoted, using double quotes thus "foo\this that\cmd" arg1 arg2 - The invoked command can in turn access the entire lpCommandLine string, and the C runtime does indeed do so, parsing it to generate the traditional argument vector argv[0], argv[1], etc. It does this using a complex and arcane set of rules which are described here: -us/vccelng/htm/progs_12.asp (if this URL stops working, you might be able to find it by searching for "Parsing C Command-Line Arguments" on MSDN. Also, the code in the Microsoft C runtime that does this translation is shipped with VC++). Our goal in runProcess is to take a command filename and list of arguments, and construct a string which inverts the translatsions described above, such that the program at the other end sees exactly the same arguments in its argv[] that we passed to rawSystem. This inverse translation is implemented by 'translate' below. Here are some pages that give informations on Windows-related limitations and deviations from Unix conventions: ;en-us;830473 Command lines and environment variables effectively limited to 8191 characters on Win XP, 2047 on NT/2000 (probably even less on Win 9x): Command-line substitution under Windows XP. IIRC these facilities (or at least a large subset of them) are available on Win NT and 2000. Some might be available on Win 9x. How CMD.EXE processes command lines. Note: CreateProcess does have a separate argument (lpApplicationName) with which you can specify the command, but we have to slap the command into lpCommandLine anyway, so that argv[0] is what a C program expects (namely the application name). So it seems simpler to just use lpCommandLine alone, which CreateProcess supports. -} Translate command - line arguments for passing to CreateProcess ( ) . translate :: String -> String translate str = '"' : snd (foldr escape (True,"\"") str) where escape '"' (b, str) = (True, '\\' : '"' : str) escape '\\' (True, str) = (True, '\\' : '\\' : str) escape '\\' (False, str) = (False, '\\' : str) escape c (b, str) = (False, c : str) -- See long comment above for what this function is trying to do. -- The passed back along the string is True iff the -- rest of the string is a sequence of backslashes followed by -- a double quote. #endif /* __GLASGOW_HASKELL__ */ #endif #ifndef __HUGS__ -- ---------------------------------------------------------------------------- -- commandToProcess | Turns a shell command into a raw command . Usually this involves wrapping it in an invocation of the shell . There 's a difference in the signature of commandToProcess between the Windows and Unix versions . On Unix , exec takes a list of strings , and we want to pass our command to /bin / sh as a single argument . On Windows , CreateProcess takes a single string for the command , which is later decomposed by cmd.exe . In this case , we just want to prepend @\"c:\WINDOWS\CMD.EXE \/c\"@ to our command line . The command - line translation that we normally do for arguments on Windows is n't required ( or desirable ) here . wrapping it in an invocation of the shell. There's a difference in the signature of commandToProcess between the Windows and Unix versions. On Unix, exec takes a list of strings, and we want to pass our command to /bin/sh as a single argument. On Windows, CreateProcess takes a single string for the command, which is later decomposed by cmd.exe. In this case, we just want to prepend @\"c:\WINDOWS\CMD.EXE \/c\"@ to our command line. The command-line translation that we normally do for arguments on Windows isn't required (or desirable) here. -} #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__) commandToProcess :: String -> IO (FilePath,[String]) commandToProcess string = return ("/bin/sh", ["-c", string]) #else commandToProcess :: String -> IO (FilePath,String) commandToProcess string = do cmd <- findCommandInterpreter return (cmd, "/c "++string) -- We don't want to put the cmd into a single -- argument, because cmd.exe will not try to split it up. Instead, -- we just tack the command on the end of the cmd.exe command line, -- which partly works. There seem to be some quoting issues, but I do n't have the energy to find+fix them right now ( ToDo ) . --SDM -- (later) Now I don't know what the above comment means. sigh. -- Find CMD.EXE (or COMMAND.COM on Win98). We use the same algorithm as system ( ) in the VC++ CRT ( Vc7 / crt / src / system.c in a VC++ installation ) . findCommandInterpreter :: IO FilePath findCommandInterpreter = do try COMSPEC first catchJust ioErrors (getEnv "COMSPEC") $ \e -> do when (not (isDoesNotExistError e)) $ ioError e try to find CMD.EXE or XXX We used to look at _ ( using cbits ) and pick which shell to use with let filename | osver . & . 0x8000 /= 0 = " command.com " | otherwise = " cmd.exe " We ought to use instead , but for now we just look for either filename XXX We used to look at _osver (using cbits) and pick which shell to use with let filename | osver .&. 0x8000 /= 0 = "command.com" | otherwise = "cmd.exe" We ought to use GetVersionEx instead, but for now we just look for either filename -} path <- getEnv "PATH" let use our own version of System . , because -- that assumes the .exe suffix. search :: [FilePath] -> IO (Maybe FilePath) search [] = return Nothing search (d:ds) = do let path1 = d </> "cmd.exe" path2 = d </> "command.com" b1 <- doesFileExist path1 b2 <- doesFileExist path2 if b1 then return (Just path1) else if b2 then return (Just path2) else search ds -- mb_path <- search (splitSearchPath path) case mb_path of Nothing -> ioError (mkIOError doesNotExistErrorType "findCommandInterpreter" Nothing Nothing) Just cmd -> return cmd #endif #endif /* __HUGS__ */ -- ---------------------------------------------------------------------------- Utils withFilePathException :: FilePath -> IO a -> IO a withFilePathException fpath act = handle mapEx act where mapEx (IOException (IOError h iot fun str _)) = ioError (IOError h iot fun str (Just fpath)) mapEx e = throwIO e #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__) withCEnvironment :: [(String,String)] -> (Ptr CString -> IO a) -> IO a withCEnvironment env act = let env' = map (\(name, val) -> name ++ ('=':val)) env in withMany withCString env' (\pEnv -> withArray0 nullPtr pEnv act) #else withCEnvironment :: [(String,String)] -> (Ptr () -> IO a) -> IO a withCEnvironment env act = let env' = foldr (\(name, val) env -> name ++ ('=':val)++'\0':env) "\0" env in withCString env' (act . castPtr) #endif
null
https://raw.githubusercontent.com/Ericson2314/lighthouse/210078b846ebd6c43b89b5f0f735362a01a9af02/ghc-6.8.2/libraries/process/System/Process/Internals.hs
haskell
--------------------------------------------------------------------------- | Module : System.Process.Internals License : BSD-style (see the file libraries/base/LICENSE) Maintainer : Stability : experimental Portability : portable --------------------------------------------------------------------------- #hide necessary to get dependencies right ---------------------------------------------------------------------------- ProcessHandle type | A handle to a process, which can be used to wait for termination of the process using 'waitForProcess'. None of the process-creation functions in this library wait for termination: they all return a 'ProcessHandle' which may be used to wait for the process later. hence we add a finalizer to it, using an IORef as the box on which to attach the finalizer. ---------------------------------------------------------------------------- ----------------------------------------------------------------------------- POSIX runProcess with signal handling in the child ^ Filename of the executable ^ Arguments to pass to the executable ^ Optional path to the working directory ^ Optional environment (otherwise inherit) ^ Handle to use for @stdin@ ^ Handle to use for @stdout@ handler for SIGINT some of these might refer to the same Handle, so don't do args working directory (or NULL) env (or NULL) stdout stderr non-zero: set child's SIGINT handler SIGINT handler some of these might refer to the same Handle, so don't do ------------------------------------------------------------------------ See long comment above for what this function is trying to do. rest of the string is a sequence of backslashes followed by a double quote. ---------------------------------------------------------------------------- commandToProcess We don't want to put the cmd into a single argument, because cmd.exe will not try to split it up. Instead, we just tack the command on the end of the cmd.exe command line, which partly works. There seem to be some quoting issues, but SDM (later) Now I don't know what the above comment means. sigh. Find CMD.EXE (or COMMAND.COM on Win98). We use the same algorithm as that assumes the .exe suffix. ----------------------------------------------------------------------------
# OPTIONS_GHC -cpp -fffi # Copyright : ( c ) The University of Glasgow 2004 Operations for creating and interacting with sub - processes . module System.Process.Internals ( #ifndef __HUGS__ ProcessHandle(..), ProcessHandle__(..), PHANDLE, closePHANDLE, mkProcessHandle, withProcessHandle, withProcessHandle_, #endif #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__) pPrPr_disableITimers, c_execvpe, # ifdef __GLASGOW_HASKELL__ runProcessPosix, # endif ignoreSignal, defaultSignal, #else # ifdef __GLASGOW_HASKELL__ runProcessWin32, translate, # endif #endif #ifndef __HUGS__ commandToProcess, #endif withFilePathException, withCEnvironment ) where #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__) import System.Posix.Types ( CPid ) import System.Posix.Process.Internals ( pPrPr_disableITimers, c_execvpe ) import System.IO ( Handle ) #else import Data.Word ( Word32 ) import Data.IORef #endif import System.Exit ( ExitCode ) import Data.Maybe ( fromMaybe ) # ifdef __GLASGOW_HASKELL__ import GHC.IOBase ( haFD, FD, Exception(..), IOException(..) ) import GHC.Handle ( stdin, stdout, stderr, withHandle_ ) # elif __HUGS__ import Hugs.Exception ( Exception(..), IOException(..) ) # endif import Control.Concurrent import Control.Exception ( handle, throwIO ) import Foreign.C import Foreign #if defined(mingw32_HOST_OS) import Control.Monad ( when ) import System.Directory ( doesFileExist ) import Control.Exception ( catchJust, ioErrors ) import System.IO.Error ( isDoesNotExistError, doesNotExistErrorType, mkIOError ) import System.Environment ( getEnv ) import System.FilePath #endif #ifdef __HUGS__ # CFILES cbits / execvpe.c # #endif #include "HsProcessConfig.h" #ifndef __HUGS__ data ProcessHandle__ = OpenHandle PHANDLE | ClosedHandle ExitCode newtype ProcessHandle = ProcessHandle (MVar ProcessHandle__) withProcessHandle :: ProcessHandle -> (ProcessHandle__ -> IO (ProcessHandle__, a)) -> IO a withProcessHandle (ProcessHandle m) io = modifyMVar m io withProcessHandle_ :: ProcessHandle -> (ProcessHandle__ -> IO ProcessHandle__) -> IO () withProcessHandle_ (ProcessHandle m) io = modifyMVar_ m io #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__) type PHANDLE = CPid mkProcessHandle :: PHANDLE -> IO ProcessHandle mkProcessHandle p = do m <- newMVar (OpenHandle p) return (ProcessHandle m) closePHANDLE :: PHANDLE -> IO () closePHANDLE _ = return () #else type PHANDLE = Word32 On Windows , we have to close this HANDLE when it is no longer required , mkProcessHandle :: PHANDLE -> IO ProcessHandle mkProcessHandle h = do m <- newMVar (OpenHandle h) addMVarFinalizer m (processHandleFinaliser m) return (ProcessHandle m) processHandleFinaliser m = modifyMVar_ m $ \p_ -> do case p_ of OpenHandle ph -> closePHANDLE ph _ -> return () return (error "closed process handle") closePHANDLE :: PHANDLE -> IO () closePHANDLE ph = c_CloseHandle ph foreign import stdcall unsafe "CloseHandle" c_CloseHandle :: PHANDLE -> IO () #endif #endif /* !__HUGS__ */ #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__) #ifdef __GLASGOW_HASKELL__ runProcessPosix :: String ^ Handle to use for @stderr@ handler for SIGQUIT -> IO ProcessHandle runProcessPosix fun cmd args mb_cwd mb_env mb_stdin mb_stdout mb_stderr mb_sigint mb_sigquit = withFilePathException cmd $ do fd_stdin <- withHandle_ fun (fromMaybe stdin mb_stdin) $ return . haFD fd_stdout <- withHandle_ fun (fromMaybe stdout mb_stdout) $ return . haFD fd_stderr <- withHandle_ fun (fromMaybe stderr mb_stderr) $ return . haFD nested withHandle _ 's ( that will deadlock ) . maybeWith withCEnvironment mb_env $ \pEnv -> do maybeWith withCString mb_cwd $ \pWorkDir -> do withMany withCString (cmd:args) $ \cstrs -> do let (set_int, inthand) = case mb_sigint of Nothing -> (0, 0) Just hand -> (1, hand) (set_quit, quithand) = case mb_sigquit of Nothing -> (0, 0) Just hand -> (1, hand) withArray0 nullPtr cstrs $ \pargs -> do ph <- throwErrnoIfMinus1 fun $ c_runProcess pargs pWorkDir pEnv fd_stdin fd_stdout fd_stderr set_int inthand set_quit quithand mkProcessHandle ph foreign import ccall unsafe "runProcess" c_runProcess stdin non - zero : set child 's SIGQUIT handler SIGQUIT handler -> IO PHANDLE #endif /* __GLASGOW_HASKELL__ */ ignoreSignal = CONST_SIG_IGN :: CLong defaultSignal = CONST_SIG_DFL :: CLong #else #ifdef __GLASGOW_HASKELL__ runProcessWin32 fun cmd args mb_cwd mb_env mb_stdin mb_stdout mb_stderr extra_cmdline = withFilePathException cmd $ do fd_stdin <- withHandle_ fun (fromMaybe stdin mb_stdin) $ return . haFD fd_stdout <- withHandle_ fun (fromMaybe stdout mb_stdout) $ return . haFD fd_stderr <- withHandle_ fun (fromMaybe stderr mb_stderr) $ return . haFD nested withHandle _ 's ( that will deadlock ) . maybeWith withCEnvironment mb_env $ \pEnv -> do maybeWith withCString mb_cwd $ \pWorkDir -> do let cmdline = translate cmd ++ concat (map ((' ':) . translate) args) ++ (if null extra_cmdline then "" else ' ':extra_cmdline) withCString cmdline $ \pcmdline -> do proc_handle <- throwErrnoIfMinus1 fun (c_runProcess pcmdline pWorkDir pEnv fd_stdin fd_stdout fd_stderr) mkProcessHandle proc_handle foreign import ccall unsafe "runProcess" c_runProcess :: CString -> CString -> Ptr () -> FD -> FD -> FD -> IO PHANDLE Passing commands to the OS on Windows On Windows this is tricky . We use CreateProcess , passing a single command - line string ( lpCommandLine ) as its argument . ( CreateProcess is well documented on . ) - It parses the beginning of the string to find the command . If the file name has embedded spaces , it must be quoted , using double quotes thus " foo\this that\cmd " arg1 arg2 - The invoked command can in turn access the entire lpCommandLine string , and the C runtime does indeed do so , parsing it to generate the traditional argument vector argv[0 ] , argv[1 ] , etc . It does this using a complex and arcane set of rules which are described here : -us/vccelng/htm/progs_12.asp ( if this URL stops working , you might be able to find it by searching for " Parsing C Command - Line Arguments " on MSDN . Also , the code in the Microsoft C runtime that does this translation is shipped with VC++ ) . Our goal in runProcess is to take a command filename and list of arguments , and construct a string which inverts the translatsions described above , such that the program at the other end sees exactly the same arguments in its argv [ ] that we passed to . This inverse translation is implemented by ' translate ' below . Here are some pages that give informations on Windows - related limitations and deviations from Unix conventions : ;en-us;830473 Command lines and environment variables effectively limited to 8191 characters on Win XP , 2047 on NT/2000 ( probably even less on Win 9x ): Command - line substitution under Windows XP . IIRC these facilities ( or at least a large subset of them ) are available on Win NT and 2000 . Some might be available on Win 9x . How CMD.EXE processes command lines . Note : CreateProcess does have a separate argument ( lpApplicationName ) with which you can specify the command , but we have to slap the command into lpCommandLine anyway , so that argv[0 ] is what a C program expects ( namely the application name ) . So it seems simpler to just use lpCommandLine alone , which CreateProcess supports . On Windows this is tricky. We use CreateProcess, passing a single command-line string (lpCommandLine) as its argument. (CreateProcess is well documented on .) - It parses the beginning of the string to find the command. If the file name has embedded spaces, it must be quoted, using double quotes thus "foo\this that\cmd" arg1 arg2 - The invoked command can in turn access the entire lpCommandLine string, and the C runtime does indeed do so, parsing it to generate the traditional argument vector argv[0], argv[1], etc. It does this using a complex and arcane set of rules which are described here: -us/vccelng/htm/progs_12.asp (if this URL stops working, you might be able to find it by searching for "Parsing C Command-Line Arguments" on MSDN. Also, the code in the Microsoft C runtime that does this translation is shipped with VC++). Our goal in runProcess is to take a command filename and list of arguments, and construct a string which inverts the translatsions described above, such that the program at the other end sees exactly the same arguments in its argv[] that we passed to rawSystem. This inverse translation is implemented by 'translate' below. Here are some pages that give informations on Windows-related limitations and deviations from Unix conventions: ;en-us;830473 Command lines and environment variables effectively limited to 8191 characters on Win XP, 2047 on NT/2000 (probably even less on Win 9x): Command-line substitution under Windows XP. IIRC these facilities (or at least a large subset of them) are available on Win NT and 2000. Some might be available on Win 9x. How CMD.EXE processes command lines. Note: CreateProcess does have a separate argument (lpApplicationName) with which you can specify the command, but we have to slap the command into lpCommandLine anyway, so that argv[0] is what a C program expects (namely the application name). So it seems simpler to just use lpCommandLine alone, which CreateProcess supports. -} Translate command - line arguments for passing to CreateProcess ( ) . translate :: String -> String translate str = '"' : snd (foldr escape (True,"\"") str) where escape '"' (b, str) = (True, '\\' : '"' : str) escape '\\' (True, str) = (True, '\\' : '\\' : str) escape '\\' (False, str) = (False, '\\' : str) escape c (b, str) = (False, c : str) The passed back along the string is True iff the #endif /* __GLASGOW_HASKELL__ */ #endif #ifndef __HUGS__ | Turns a shell command into a raw command . Usually this involves wrapping it in an invocation of the shell . There 's a difference in the signature of commandToProcess between the Windows and Unix versions . On Unix , exec takes a list of strings , and we want to pass our command to /bin / sh as a single argument . On Windows , CreateProcess takes a single string for the command , which is later decomposed by cmd.exe . In this case , we just want to prepend @\"c:\WINDOWS\CMD.EXE \/c\"@ to our command line . The command - line translation that we normally do for arguments on Windows is n't required ( or desirable ) here . wrapping it in an invocation of the shell. There's a difference in the signature of commandToProcess between the Windows and Unix versions. On Unix, exec takes a list of strings, and we want to pass our command to /bin/sh as a single argument. On Windows, CreateProcess takes a single string for the command, which is later decomposed by cmd.exe. In this case, we just want to prepend @\"c:\WINDOWS\CMD.EXE \/c\"@ to our command line. The command-line translation that we normally do for arguments on Windows isn't required (or desirable) here. -} #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__) commandToProcess :: String -> IO (FilePath,[String]) commandToProcess string = return ("/bin/sh", ["-c", string]) #else commandToProcess :: String -> IO (FilePath,String) commandToProcess string = do cmd <- findCommandInterpreter return (cmd, "/c "++string) system ( ) in the VC++ CRT ( Vc7 / crt / src / system.c in a VC++ installation ) . findCommandInterpreter :: IO FilePath findCommandInterpreter = do try COMSPEC first catchJust ioErrors (getEnv "COMSPEC") $ \e -> do when (not (isDoesNotExistError e)) $ ioError e try to find CMD.EXE or XXX We used to look at _ ( using cbits ) and pick which shell to use with let filename | osver . & . 0x8000 /= 0 = " command.com " | otherwise = " cmd.exe " We ought to use instead , but for now we just look for either filename XXX We used to look at _osver (using cbits) and pick which shell to use with let filename | osver .&. 0x8000 /= 0 = "command.com" | otherwise = "cmd.exe" We ought to use GetVersionEx instead, but for now we just look for either filename -} path <- getEnv "PATH" let use our own version of System . , because search :: [FilePath] -> IO (Maybe FilePath) search [] = return Nothing search (d:ds) = do let path1 = d </> "cmd.exe" path2 = d </> "command.com" b1 <- doesFileExist path1 b2 <- doesFileExist path2 if b1 then return (Just path1) else if b2 then return (Just path2) else search ds mb_path <- search (splitSearchPath path) case mb_path of Nothing -> ioError (mkIOError doesNotExistErrorType "findCommandInterpreter" Nothing Nothing) Just cmd -> return cmd #endif #endif /* __HUGS__ */ Utils withFilePathException :: FilePath -> IO a -> IO a withFilePathException fpath act = handle mapEx act where mapEx (IOException (IOError h iot fun str _)) = ioError (IOError h iot fun str (Just fpath)) mapEx e = throwIO e #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__) withCEnvironment :: [(String,String)] -> (Ptr CString -> IO a) -> IO a withCEnvironment env act = let env' = map (\(name, val) -> name ++ ('=':val)) env in withMany withCString env' (\pEnv -> withArray0 nullPtr pEnv act) #else withCEnvironment :: [(String,String)] -> (Ptr () -> IO a) -> IO a withCEnvironment env act = let env' = foldr (\(name, val) env -> name ++ ('=':val)++'\0':env) "\0" env in withCString env' (act . castPtr) #endif
96c9141a16e5a73cf84a48b7975cd82d18e151f119e98715dd08e02586a7426c
jumarko/clojure-experiments
tennis_test.clj
(ns clojure-experiments.dojo-katas.tennis-test (:require [clojure-experiments.dojo-katas.tennis :as tennis] [clojure.test :refer [deftest is testing]])) (defn new-game [] (tennis/make-game "P1" "P2")) ;;; TODO: fixture later check -to-pass-a-value-from-a-fixture-to-a-test-with-clojure-test ( defn prepare - game - fixture [ ] ;; ) ;; (use-fixtures :each prepare-game-fixture) ;; TODO: This feels it should be easier (maybe `iterate` or `reduce`?) but it doesn't matter much after all (defn- score-n-times [game player-name n] (loop [new-game game cnt n] (if (zero? cnt) new-game (recur (tennis/win-ball new-game player-name) (dec cnt))))) (defn- check-score [[player1-name player1-points] [player2-name player2-points] expected-score] (testing (format "When player 1 scores %s times and player 2 scores %s times then we expect score: %s" player1-points player2-points expected-score) (let [game-result (-> (new-game) (score-n-times player1-name player1-points) (score-n-times player2-name player2-points))] (is (= expected-score (tennis/score game-result)))))) (deftest simple-game-first-player (check-score ["P1" 0] ["P2" 0] "0-0") (check-score ["P1" 1] ["P2" 0] "15-0") (check-score ["P1" 2] ["P2" 0] "30-0") (check-score ["P1" 3] ["P2" 0] "40-0")) (deftest simple-game-second-player (check-score ["P1" 0] ["P2" 1] "0-15") (check-score ["P1" 0] ["P2" 3] "0-40")) (deftest simple-game-both-players (check-score ["P1" 1] ["P2" 1] "15-15") (check-score ["P1" 1] ["P2" 2] "15-30") (check-score ["P1" 2] ["P2" 3] "30-40")) ;;; TODO Tests categories ;; player wins (deftest simple-game-first-player-wins (check-score ["P1" 4] ["P2" 0] "P1 WON!") (check-score ["P1" 4] ["P2" 3] "P1 WON!") this should still be the winninig for the first player ! (check-score ["P1" 4] ["P2" 4] "P1 WON!")) (deftest simple-game-second-player-wins (check-score ["P1" 0] ["P2" 4] "P2 WON!") this should still be the winninig for the first player ! (check-score ["P2" 4] ["P1" 4] "P2 WON!")) (deftest deuce (testing "Simple deuce" (check-score ["P1" 3] ["P2" 3] "DEUCE")) (testing "Deuce when players have more than 40 points" (let [game-result (-> (new-game) (score-n-times "P1" 3) (score-n-times "P2" 3) (score-n-times "P1" 1) (score-n-times "P2" 1))] (is (= "DEUCE" (tennis/score game-result)))))) ;; advantage (deftest advantage (testing "player1 has advantage after first deuce" (let [game-result (-> (new-game) (score-n-times "P1" 3) (score-n-times "P2" 3) (score-n-times "P1" 1))] (is (= "P1 ADVANTAGE" (tennis/score game-result))))) (testing "player2 has advantage after the first deuce" (check-score ["P1" 3] ["P2" 4] "P2 ADVANTAGE")) (testing "player2 has advantage after three deuces" (let [game-result (-> (new-game) (score-n-times "P1" 3) (score-n-times "P2" 4) (score-n-times "P1" 1) (score-n-times "P2" 1) (score-n-times "P1" 1) (score-n-times "P2" 1))] (is (= "P2 ADVANTAGE" (tennis/score game-result))))))
null
https://raw.githubusercontent.com/jumarko/clojure-experiments/f0f9c091959e7f54c3fb13d0585a793ebb09e4f9/test/clojure_experiments/dojo_katas/tennis_test.clj
clojure
TODO: fixture later ) (use-fixtures :each prepare-game-fixture) TODO: This feels it should be easier (maybe `iterate` or `reduce`?) but it doesn't matter much after all TODO Tests categories player wins advantage
(ns clojure-experiments.dojo-katas.tennis-test (:require [clojure-experiments.dojo-katas.tennis :as tennis] [clojure.test :refer [deftest is testing]])) (defn new-game [] (tennis/make-game "P1" "P2")) check -to-pass-a-value-from-a-fixture-to-a-test-with-clojure-test ( defn prepare - game - fixture [ ] (defn- score-n-times [game player-name n] (loop [new-game game cnt n] (if (zero? cnt) new-game (recur (tennis/win-ball new-game player-name) (dec cnt))))) (defn- check-score [[player1-name player1-points] [player2-name player2-points] expected-score] (testing (format "When player 1 scores %s times and player 2 scores %s times then we expect score: %s" player1-points player2-points expected-score) (let [game-result (-> (new-game) (score-n-times player1-name player1-points) (score-n-times player2-name player2-points))] (is (= expected-score (tennis/score game-result)))))) (deftest simple-game-first-player (check-score ["P1" 0] ["P2" 0] "0-0") (check-score ["P1" 1] ["P2" 0] "15-0") (check-score ["P1" 2] ["P2" 0] "30-0") (check-score ["P1" 3] ["P2" 0] "40-0")) (deftest simple-game-second-player (check-score ["P1" 0] ["P2" 1] "0-15") (check-score ["P1" 0] ["P2" 3] "0-40")) (deftest simple-game-both-players (check-score ["P1" 1] ["P2" 1] "15-15") (check-score ["P1" 1] ["P2" 2] "15-30") (check-score ["P1" 2] ["P2" 3] "30-40")) (deftest simple-game-first-player-wins (check-score ["P1" 4] ["P2" 0] "P1 WON!") (check-score ["P1" 4] ["P2" 3] "P1 WON!") this should still be the winninig for the first player ! (check-score ["P1" 4] ["P2" 4] "P1 WON!")) (deftest simple-game-second-player-wins (check-score ["P1" 0] ["P2" 4] "P2 WON!") this should still be the winninig for the first player ! (check-score ["P2" 4] ["P1" 4] "P2 WON!")) (deftest deuce (testing "Simple deuce" (check-score ["P1" 3] ["P2" 3] "DEUCE")) (testing "Deuce when players have more than 40 points" (let [game-result (-> (new-game) (score-n-times "P1" 3) (score-n-times "P2" 3) (score-n-times "P1" 1) (score-n-times "P2" 1))] (is (= "DEUCE" (tennis/score game-result)))))) (deftest advantage (testing "player1 has advantage after first deuce" (let [game-result (-> (new-game) (score-n-times "P1" 3) (score-n-times "P2" 3) (score-n-times "P1" 1))] (is (= "P1 ADVANTAGE" (tennis/score game-result))))) (testing "player2 has advantage after the first deuce" (check-score ["P1" 3] ["P2" 4] "P2 ADVANTAGE")) (testing "player2 has advantage after three deuces" (let [game-result (-> (new-game) (score-n-times "P1" 3) (score-n-times "P2" 4) (score-n-times "P1" 1) (score-n-times "P2" 1) (score-n-times "P1" 1) (score-n-times "P2" 1))] (is (= "P2 ADVANTAGE" (tennis/score game-result))))))
fa183e4ffd3f92d20ae8cece37cd3d03afee1ecf39eb76e154c499e1dbf1fb16
winterland1989/mysql-haskell
TLS.hs
| Module : Database . MySQL.Connection Description : TLS support for mysql - haskell via @tls@ package . Copyright : ( c ) Winterland , 2016 License : BSD Maintainer : Stability : experimental Portability : PORTABLE This module provides secure MySQL connection using ' tls ' package , please make sure your certificate is v3 extension enabled . Module : Database.MySQL.Connection Description : TLS support for mysql-haskell via @tls@ package. Copyright : (c) Winterland, 2016 License : BSD Maintainer : Stability : experimental Portability : PORTABLE This module provides secure MySQL connection using 'tls' package, please make sure your certificate is v3 extension enabled. -} module Database.MySQL.TLS ( connect , connectDetail , module Data.TLSSetting ) where import Control.Exception (bracketOnError, throwIO) import qualified Data.Binary as Binary import qualified Data.Binary.Put as Binary import qualified Data.Connection as Conn import Data.IORef (newIORef) import Data.TLSSetting import Database.MySQL.Connection hiding (connect, connectDetail) import Database.MySQL.Protocol.Auth import Database.MySQL.Protocol.Packet import qualified Network.TLS as TLS import qualified System.IO.Streams.TCP as TCP import qualified Data.Connection as TCP import qualified System.IO.Streams.TLS as TLS -------------------------------------------------------------------------------- -- | Provide a 'TLS.ClientParams' and a subject name to establish a TLS connection. -- connect :: ConnectInfo -> (TLS.ClientParams, String) -> IO MySQLConn connect c cp = fmap snd (connectDetail c cp) connectDetail :: ConnectInfo -> (TLS.ClientParams, String) -> IO (Greeting, MySQLConn) connectDetail (ConnectInfo host port db user pass charset) (cparams, subName) = bracketOnError (connectWithBufferSize host port bUFSIZE) (TCP.close) $ \ c -> do let is = TCP.source c is' <- decodeInputStream is p <- readPacket is' greet <- decodeFromPacket p if supportTLS (greetingCaps greet) then do let cparams' = cparams { TLS.clientUseServerNameIndication = False , TLS.clientServerIdentification = (subName, "") } let (sock, sockAddr) = Conn.connExtraInfo c write c (encodeToPacket 1 $ sslRequest charset) bracketOnError (TLS.contextNew sock cparams') ( \ ctx -> TLS.bye ctx >> TCP.close c ) $ \ ctx -> do TLS.handshake ctx tc <- TLS.tLsToConnection (ctx, sockAddr) let tlsIs = TCP.source tc tlsIs' <- decodeInputStream tlsIs let auth = mkAuth db user pass charset greet write tc (encodeToPacket 2 auth) q <- readPacket tlsIs' if isOK q then do consumed <- newIORef True let conn = MySQLConn tlsIs' (write tc) (TCP.close tc) consumed return (greet, conn) else TCP.close c >> decodeFromPacket q >>= throwIO . ERRException else error "Database.MySQL.TLS: server doesn't support TLS connection" where connectWithBufferSize h p bs = TCP.connectSocket h p >>= TCP.socketToConnection bs write c a = TCP.send c $ Binary.runPut . Binary.put $ a
null
https://raw.githubusercontent.com/winterland1989/mysql-haskell/d93caffe0991e1090a3854acff355ff0ea6075c7/Database/MySQL/TLS.hs
haskell
------------------------------------------------------------------------------ | Provide a 'TLS.ClientParams' and a subject name to establish a TLS connection.
| Module : Database . MySQL.Connection Description : TLS support for mysql - haskell via @tls@ package . Copyright : ( c ) Winterland , 2016 License : BSD Maintainer : Stability : experimental Portability : PORTABLE This module provides secure MySQL connection using ' tls ' package , please make sure your certificate is v3 extension enabled . Module : Database.MySQL.Connection Description : TLS support for mysql-haskell via @tls@ package. Copyright : (c) Winterland, 2016 License : BSD Maintainer : Stability : experimental Portability : PORTABLE This module provides secure MySQL connection using 'tls' package, please make sure your certificate is v3 extension enabled. -} module Database.MySQL.TLS ( connect , connectDetail , module Data.TLSSetting ) where import Control.Exception (bracketOnError, throwIO) import qualified Data.Binary as Binary import qualified Data.Binary.Put as Binary import qualified Data.Connection as Conn import Data.IORef (newIORef) import Data.TLSSetting import Database.MySQL.Connection hiding (connect, connectDetail) import Database.MySQL.Protocol.Auth import Database.MySQL.Protocol.Packet import qualified Network.TLS as TLS import qualified System.IO.Streams.TCP as TCP import qualified Data.Connection as TCP import qualified System.IO.Streams.TLS as TLS connect :: ConnectInfo -> (TLS.ClientParams, String) -> IO MySQLConn connect c cp = fmap snd (connectDetail c cp) connectDetail :: ConnectInfo -> (TLS.ClientParams, String) -> IO (Greeting, MySQLConn) connectDetail (ConnectInfo host port db user pass charset) (cparams, subName) = bracketOnError (connectWithBufferSize host port bUFSIZE) (TCP.close) $ \ c -> do let is = TCP.source c is' <- decodeInputStream is p <- readPacket is' greet <- decodeFromPacket p if supportTLS (greetingCaps greet) then do let cparams' = cparams { TLS.clientUseServerNameIndication = False , TLS.clientServerIdentification = (subName, "") } let (sock, sockAddr) = Conn.connExtraInfo c write c (encodeToPacket 1 $ sslRequest charset) bracketOnError (TLS.contextNew sock cparams') ( \ ctx -> TLS.bye ctx >> TCP.close c ) $ \ ctx -> do TLS.handshake ctx tc <- TLS.tLsToConnection (ctx, sockAddr) let tlsIs = TCP.source tc tlsIs' <- decodeInputStream tlsIs let auth = mkAuth db user pass charset greet write tc (encodeToPacket 2 auth) q <- readPacket tlsIs' if isOK q then do consumed <- newIORef True let conn = MySQLConn tlsIs' (write tc) (TCP.close tc) consumed return (greet, conn) else TCP.close c >> decodeFromPacket q >>= throwIO . ERRException else error "Database.MySQL.TLS: server doesn't support TLS connection" where connectWithBufferSize h p bs = TCP.connectSocket h p >>= TCP.socketToConnection bs write c a = TCP.send c $ Binary.runPut . Binary.put $ a
4f980abebbfc5f52d1c01735ebc12c3d7b80cd7eb320acb63b054da1ae12ee8d
ZHaskell/stdio
ExtraSpec.hs
# LANGUAGE TypeApplications # # LANGUAGE ScopedTypeVariables # module Std.Data.Vector.ExtraSpec where import qualified Data.List as List import Data.Word import qualified Std.Data.Vector as V import qualified Std.Data.Vector.Base as V import qualified Std.Data.Vector.Extra as V import Test.QuickCheck import Test.QuickCheck.Function import Test.QuickCheck.Property import Test.Hspec import Test.Hspec.QuickCheck spec :: Spec spec = describe "vector-extras" $ do describe "vector cons == List.(:)" $ do prop "vector cons == List.(:)" $ \ xs x -> (V.cons x . V.pack @V.Vector @Integer $ xs) === (V.pack . (:) x $ xs) prop "vector cons == List.(:)" $ \ xs x -> (V.cons x . V.pack @V.PrimVector @Int $ xs) === (V.pack . (:) x $ xs) prop "vector cons == List.(:)" $ \ xs x -> (V.cons x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . (:) x $ xs) describe "vector snoc == List.++" $ do prop "vector snoc == List.++" $ \ xs x -> ((`V.snoc` x) . V.pack @V.Vector @Integer $ xs) === (V.pack . (++ [x]) $ xs) prop "vector snoc == List.++" $ \ xs x -> ((`V.snoc` x) . V.pack @V.PrimVector @Int $ xs) === (V.pack . (++ [x]) $ xs) prop "vector snoc == List.++" $ \ xs x -> ((`V.snoc` x) . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . (++ [x]) $ xs) describe "vector headMaybe == Just. List.head" $ do prop "vector headMaybe === Just . list.head" $ \ (NonEmpty xs) -> (V.headMaybe . V.pack @V.Vector @Integer $ xs) === (Just . List.head $ xs) prop "vector headMaybe === Just . List.head" $ \ (NonEmpty xs) -> (V.headMaybe . V.pack @V.PrimVector @Int $ xs) === (Just . List.head $ xs) prop "vector headMaybe === Just . List.head" $ \ (NonEmpty xs) -> (V.headMaybe . V.pack @V.PrimVector @Word8 $ xs) === (Just . List.head $ xs) describe "vector initMayEmpty == List.init" $ do prop "vector initMayEmpty === List.init" $ \ (NonEmpty xs) -> (V.initMayEmpty . V.pack @V.Vector @Integer $ xs) === (V.pack . List.init $ xs) prop "vector initMayEmpty === List.init" $ \ (NonEmpty xs) -> (V.initMayEmpty . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.init $ xs) prop "vector initMayEmpty === List.init" $ \ (NonEmpty xs) -> (V.initMayEmpty . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.init $ xs) describe "vector lastMaybe == Just. List.last" $ do prop "vector lastMaybe === Just . list.last" $ \ (NonEmpty xs) -> (V.lastMaybe . V.pack @V.Vector @Integer $ xs) === (Just . List.last $ xs) prop "vector lastMaybe === Just . List.last" $ \ (NonEmpty xs) -> (V.lastMaybe . V.pack @V.PrimVector @Int $ xs) === (Just . List.last $ xs) prop "vector lastMaybe === Just . List.last" $ \ (NonEmpty xs) -> (V.lastMaybe . V.pack @V.PrimVector @Word8 $ xs) === (Just . List.last $ xs) describe "vector tailMayEmpty == List.tail" $ do prop "vector tailMayEmpty === List.tail" $ \ (NonEmpty xs) -> (V.tailMayEmpty . V.pack @V.Vector @Integer $ xs) === (V.pack . List.tail $ xs) prop "vector tailMayEmpty === List.tail" $ \ (NonEmpty xs) -> (V.tailMayEmpty . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.tail $ xs) prop "vector tailMayEmpty === List.tail" $ \ (NonEmpty xs) -> (V.tailMayEmpty . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.tail $ xs) describe "vector take == List.take" $ do prop "vector take == List.take" $ \ xs x -> (V.take x . V.pack @V.Vector @Integer $ xs) === (V.pack . List.take x $ xs) prop "vector take == List.take" $ \ xs x -> (V.take x . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.take x $ xs) prop "vector take == List.take" $ \ xs x -> (V.take x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.take x $ xs) describe "vector takeR x == List.reverse . List.take x . List.reverse" $ do prop "vector takeR x == List.reverse . List.take x . List.reverse" $ \ xs x -> (V.takeR x . V.pack @V.Vector @Integer $ xs) === (V.pack . List.reverse . List.take x . List.reverse $ xs) prop "vector takeR x == List.reverse . List.take x . List.reverse" $ \ xs x -> (V.takeR x . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.reverse . List.take x . List.reverse $ xs) prop "vector takeR x == List.reverse . List.take x . List.reverse" $ \ xs x -> (V.takeR x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.reverse . List.take x . List.reverse $ xs) describe "vector drop == List.drop" $ do prop "vector drop == List.drop" $ \ xs x -> (V.drop x . V.pack @V.Vector @Integer $ xs) === (V.pack . List.drop x $ xs) prop "vector drop == List.drop" $ \ xs x -> (V.drop x . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.drop x $ xs) prop "vector drop == List.drop" $ \ xs x -> (V.drop x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.drop x $ xs) describe "vector dropR x == List.reverse . List.drop x . List.reverse" $ do prop "vector dropR x == List.reverse . List.drop x . List.reverse" $ \ xs x -> (V.dropR x . V.pack @V.Vector @Integer $ xs) === (V.pack . List.reverse . List.drop x . List.reverse $ xs) prop "vector dropR x == List.reverse . List.drop x . List.reverse" $ \ xs x -> (V.dropR x . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.reverse . List.drop x . List.reverse $ xs) prop "vector dropR x == List.reverse . List.drop x . List.reverse" $ \ xs x -> (V.dropR x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.reverse . List.drop x . List.reverse $ xs) describe "vector slice x y == drop x . take (x+y)" $ do prop "vector slice x y === drop x . take (x+y)" $ \ x y xs -> (V.slice x y . V.pack @V.Vector @Integer $ xs) === (V.pack . drop x . take (x+y) $ xs) prop "vector slice x y xs === drop x . take (x+y) x" $ \ x y xs -> (V.slice x y . V.pack @V.PrimVector @Int $ xs) === (V.pack . drop x . take (x+y) $ xs) prop "vector slice x y xs === drop x . take (x+y) x" $ \ x y xs -> (V.slice x y . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . drop x . take (x+y) $ xs) describe "vector splitAt == List.splitAt" $ do prop "vector splitAt == List.splitAt" $ \ xs x -> (V.splitAt x . V.pack @V.Vector @Integer $ xs) === (let (a,b) = List.splitAt x $ xs in (V.pack a, V.pack b)) prop "vector splitAt == List.splitAt" $ \ xs x -> (V.splitAt x . V.pack @V.PrimVector @Int $ xs) === (let (a,b) = List.splitAt x $ xs in (V.pack a, V.pack b)) prop "vector splitAt == List.splitAt" $ \ xs x -> (V.splitAt x . V.pack @V.PrimVector @Word8 $ xs) === (let (a,b) = List.splitAt x $ xs in (V.pack a, V.pack b)) describe "vector takeWhile == List.takeWhile" $ do prop "vector takeWhile == List.takeWhile" $ \ xs (Fun _ x) -> (V.takeWhile x . V.pack @V.Vector @Integer $ xs) === (V.pack . List.takeWhile x $ xs) prop "vector takeWhile == List.takeWhile" $ \ xs (Fun _ x) -> (V.takeWhile x . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.takeWhile x $ xs) prop "vector takeWhile == List.takeWhile" $ \ xs (Fun _ x) -> (V.takeWhile x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.takeWhile x $ xs) describe "vector takeWhileR == reverse . List.takeWhile . reverse" $ do prop "vector takeWhileR == reverse . List.takeWhile . reverse" $ \ xs (Fun _ x) -> (V.takeWhileR x . V.pack @V.Vector @Integer $ xs) === (V.pack . List.reverse . List.takeWhile x $ List.reverse xs) prop "vector takeWhileR == reverse . List.takeWhile . reverse" $ \ xs (Fun _ x) -> (V.takeWhileR x . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.reverse . List.takeWhile x $ List.reverse xs) prop "vector takeWhileR == reverse . List.takeWhile . reverse" $ \ xs (Fun _ x) -> (V.takeWhileR x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.reverse . List.takeWhile x $ List.reverse xs) describe "vector dropWhile == List.dropWhile" $ do prop "vector dropWhile == List.dropWhile" $ \ xs (Fun _ x) -> (V.dropWhile x . V.pack @V.Vector @Integer $ xs) === (V.pack . List.dropWhile x $ xs) prop "vector dropWhile == List.dropWhile" $ \ xs (Fun _ x) -> (V.dropWhile x . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.dropWhile x $ xs) prop "vector dropWhile == List.dropWhile" $ \ xs (Fun _ x) -> (V.dropWhile x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.dropWhile x $ xs) describe "vector dropWhileR == reverse . List.dropWhile . reverse" $ do prop "vector dropWhileR == reverse . List.dropWhile . reverse" $ \ xs (Fun _ x) -> (V.dropWhileR x . V.pack @V.Vector @Integer $ xs) === (V.pack . List.reverse . List.dropWhile x $ List.reverse xs) prop "vector dropWhileR == reverse . List.dropWhile . reverse" $ \ xs (Fun _ x) -> (V.dropWhileR x . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.reverse . List.dropWhile x $ List.reverse xs) prop "vector dropWhileR == reverse . List.dropWhile . reverse" $ \ xs (Fun _ x) -> (V.dropWhileR x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.reverse . List.dropWhile x $ List.reverse xs) describe "vector break == List.break" $ do prop "vector break == List.break" $ \ xs (Fun _ x) -> (V.break x . V.pack @V.Vector @Integer $ xs) === (let (a,b) = List.break x $ xs in (V.pack a, V.pack b)) prop "vector break == List.break" $ \ xs (Fun _ x) -> (V.break x . V.pack @V.PrimVector @Int $ xs) === (let (a,b) = List.break x $ xs in (V.pack a, V.pack b)) prop "vector break == List.break" $ \ xs (Fun _ x) -> (V.break x . V.pack @V.PrimVector @Word8 $ xs) === (let (a,b) = List.break x $ xs in (V.pack a, V.pack b)) describe "vector breakOn rules" $ do prop "vector breakOn rules" $ \ xs ys -> (let (a, b) = V.breakOn (V.pack xs) . V.pack @V.Vector @Integer $ ys in (a `V.append` b, V.pack xs `V.isPrefixOf` b || V.null b) === (V.pack ys, True)) prop "vector breakOn rules" $ \ xs ys -> (let (a, b) = V.breakOn (V.pack xs) . V.pack @V.PrimVector @Int $ ys in (a `V.append` b, V.pack xs `V.isPrefixOf` b || V.null b) === (V.pack ys, True)) prop "vector breakOn rules" $ \ xs ys -> (let (a, b) = V.breakOn (V.pack xs) . V.pack @V.PrimVector @Word8 $ ys in (a `V.append` b, V.pack xs `V.isPrefixOf` b || V.null b) === (V.pack ys, True)) describe "vector span == List.span" $ do prop "vector span == List.span" $ \ xs (Fun _ x) -> (V.span x . V.pack @V.Vector @Integer $ xs) === (let (a,b) = List.span x $ xs in (V.pack a, V.pack b)) prop "vector span == List.span" $ \ xs (Fun _ x) -> (V.span x . V.pack @V.PrimVector @Int $ xs) === (let (a,b) = List.span x $ xs in (V.pack a, V.pack b)) prop "vector span == List.span" $ \ xs (Fun _ x) -> (V.span x . V.pack @V.PrimVector @Word8 $ xs) === (let (a,b) = List.span x $ xs in (V.pack a, V.pack b)) describe "vector breakR == List.break in reverse driection" $ do prop "vector breakR == List.break in reverse driection" $ \ xs (Fun _ x) -> (V.breakR x . V.pack @V.Vector @Integer $ xs) === (let (b,a) = List.break x . List.reverse $ xs in (V.reverse $ V.pack a, V.reverse $ V.pack b)) prop "vector breakR == List.break in reverse driection" $ \ xs (Fun _ x) -> (V.breakR x . V.pack @V.PrimVector @Int $ xs) === (let (b,a) = List.break x . List.reverse $ xs in (V.reverse $ V.pack a, V.reverse $ V.pack b)) prop "vector breakR == List.break in reverse driection" $ \ xs (Fun _ x) -> (V.breakR x . V.pack @V.PrimVector @Word8 $ xs) === (let (b,a) = List.break x . List.reverse $ xs in (V.reverse $ V.pack a, V.reverse $ V.pack b)) describe "vector spanR == List.span in reverse driection" $ do prop "vector spanR == List.span in reverse driection" $ \ xs (Fun _ x) -> (V.spanR x . V.pack @V.Vector @Integer $ xs) === (let (b,a) = List.span x . List.reverse $ xs in (V.reverse $ V.pack a, V.reverse $ V.pack b)) prop "vector spanR == List.span in reverse driection" $ \ xs (Fun _ x) -> (V.spanR x . V.pack @V.PrimVector @Int $ xs) === (let (b,a) = List.span x . List.reverse $ xs in (V.reverse $ V.pack a, V.reverse $ V.pack b)) prop "vector spanR == List.span in reverse driection" $ \ xs (Fun _ x) -> (V.spanR x . V.pack @V.PrimVector @Word8 $ xs) === (let (b,a) = List.span x . List.reverse $ xs in (V.reverse $ V.pack a, V.reverse $ V.pack b)) describe "vector group == List.group" $ do prop "vector group == List.group" $ \ xs -> (V.group . V.pack @V.Vector @Integer $ xs) === (V.pack <$> List.group xs) prop "vector group == List.group" $ \ xs -> (V.group . V.pack @V.PrimVector @Int $ xs) === (V.pack <$> List.group xs) prop "vector group == List.group" $ \ xs -> (V.group . V.pack @V.PrimVector @Word8 $ xs) === (V.pack <$> List.group xs) describe "vector groupBy == List.groupBy" $ do prop "vector groupBy == List.groupBy" $ \ xs x -> (V.groupBy (applyFun2 x) . V.pack @V.Vector @Integer $ xs) === (V.pack <$> List.groupBy (applyFun2 x) xs) prop "vector groupBy == List.groupBy" $ \ xs x -> (V.groupBy (applyFun2 x) . V.pack @V.PrimVector @Int $ xs) === (V.pack <$> List.groupBy (applyFun2 x) xs) prop "vector groupBy == List.groupBy" $ \ xs x -> (V.groupBy (applyFun2 x) . V.pack @V.PrimVector @Word8 $ xs) === (V.pack <$> List.groupBy (applyFun2 x) xs) describe "vector stripPrefix a (a+b) = b " $ do prop "vector stripPrefix == List.stripPrefix" $ \ xs ys -> (V.stripPrefix (V.pack xs) . V.pack @V.Vector @Integer $ xs++ys) === (Just $ V.pack ys) prop "vector stripPrefix == List.stripPrefix" $ \ xs ys -> (V.stripPrefix (V.pack xs) . V.pack @V.PrimVector @Int $ xs++ys) === (Just $ V.pack ys) prop "vector stripPrefix == List.stripPrefix" $ \ xs ys -> (V.stripPrefix (V.pack xs) . V.pack @V.PrimVector @Word8 $ xs++ys) === (Just $ V.pack ys) describe "vector stripSuffix b (a+b) = a " $ do prop "vector stripSuffix == List.stripSuffix" $ \ xs ys -> (V.stripSuffix (V.pack xs) . V.pack @V.Vector @Integer $ ys++xs) === (Just $ V.pack ys) prop "vector stripSuffix == List.stripSuffix" $ \ xs ys -> (V.stripSuffix (V.pack xs) . V.pack @V.PrimVector @Int $ ys++xs) === (Just $ V.pack ys) prop "vector stripSuffix == List.stripSuffix" $ \ xs ys -> (V.stripSuffix (V.pack xs) . V.pack @V.PrimVector @Word8 $ ys++xs) === (Just $ V.pack ys) describe "vector isInfixOf b (a+b+c) = True " $ do prop "vector isInfixOf == List.isInfixOf" $ \ xs ys zs -> (V.isInfixOf (V.pack xs) . V.pack @V.Vector @Integer $ ys++xs++zs) === True prop "vector isInfixOf == List.isInfixOf" $ \ xs ys zs -> (V.isInfixOf (V.pack xs) . V.pack @V.PrimVector @Int $ ys++xs++zs) === True prop "vector isInfixOf == List.isInfixOf" $ \ xs ys zs -> (V.isInfixOf (V.pack xs) . V.pack @V.PrimVector @Word8 $ ys++xs++zs) === True describe "let (c,a,b) = vector commonPrefix x y in (a,b) = (stripPrefix c x,stripPrefix c y) " $ do prop "vector commonPrefix rules" $ \ xs ys -> let (c,a,b) = V.commonPrefix (V.pack xs) . V.pack @V.Vector @Integer $ ys Just xs' = V.stripPrefix c $ V.pack xs Just ys' = V.stripPrefix c $ V.pack ys in (a,b) === (xs', ys') prop "vector commonPrefix rules" $ \ xs ys -> let (c,a,b) = V.commonPrefix (V.pack xs) . V.pack @V.PrimVector @Int $ ys Just xs' = V.stripPrefix c $ V.pack xs Just ys' = V.stripPrefix c $ V.pack ys in (a,b) === (xs', ys') prop "vector commonPrefix rules" $ \ xs ys -> let (c,a,b) = V.commonPrefix (V.pack xs) . V.pack @V.PrimVector @Word8 $ ys Just xs' = V.stripPrefix c $ V.pack xs Just ys' = V.stripPrefix c $ V.pack ys in (a,b) === (xs', ys') describe "vector intercalate [x] . split x == id" $ do prop "vector intercalate [x] . split x == id" $ \ xs x -> (V.intercalate (V.singleton x) . V.split x . V.pack @V.Vector @Integer $ xs) === V.pack xs prop "vector intercalate [x] . split x == id" $ \ xs x -> (V.intercalate (V.singleton x) . V.split x . V.pack @V.PrimVector @Int $ xs) === V.pack xs prop "vector intercalate [x] . split x == id" $ \ xs x -> (V.intercalate (V.singleton x) . V.split x . V.pack @V.PrimVector @Word8 $ xs) === V.pack xs describe "vector intercalate x . splitOn x == id" $ do prop "vector intercalate x . splitOn x == id" $ \ xs x -> (V.intercalate (V.pack x) . V.splitOn (V.pack x) . V.pack @V.Vector @Integer $ xs) === V.pack xs prop "vector intercalate x . splitOn x == id" $ \ xs x -> (V.intercalate (V.pack x) . V.splitOn (V.pack x) . V.pack @V.PrimVector @Int $ xs) === V.pack xs prop "vector intercalate x . splitOn x == id" $ \ xs x -> (V.intercalate (V.pack x) . V.splitOn (V.pack x) . V.pack @V.PrimVector @Word8 $ xs) === V.pack xs describe "vector reverse . pack == packR" . modifyMaxSuccess (*10) . modifyMaxSize (*10) $ do prop "reverse . pack === packR XX" $ \ xs -> (V.reverse $ V.pack @V.Vector @Integer xs) === (V.packR xs) prop "reverse . pack === packR XX" $ \ xs -> (V.reverse $ V.pack @V.PrimVector @Int xs) === (V.packR xs) prop "reverse . pack === packR XX" $ \ xs -> (V.reverse $ V.pack @V.PrimVector @Word8 xs) === (V.packR xs) describe "vector words == List.words" $ do prop "vector words === List.words" $ \ xs -> (V.words . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.map V.c2w <$> (List.words . List.map V.w2c $ xs)) describe "vector lines == List.lines" $ do prop "vector lines === List.lines" $ \ xs -> (V.lines . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.map V.c2w <$> (List.lines . List.map V.w2c $ xs)) describe "vector unwords == List.unwords" $ do prop "vector unwords === List.unwords" $ \ xs -> (V.unwords $ V.pack @V.PrimVector @Word8 <$> xs) === (V.pack (List.map V.c2w . List.unwords $ List.map V.w2c <$> xs)) describe "vector unlines == List.unlines" $ do prop "vector unlines === List.unlines" $ \ xs -> (V.unlines $ V.pack @V.PrimVector @Word8 <$> xs) === (V.pack (List.map V.c2w . List.unlines $ List.map V.w2c <$> xs)) describe "vector padLeft n x xs = if l >= n then xs else replicate (n-l) x ++ xs" $ do prop "vector padLeft n x xs = if l >= n then xs else replicate (n-l) x ++ xs" $ \ xs n x -> (V.padLeft n x . V.pack @V.Vector @Integer $ xs) === (let l = List.length xs in if l >= n then V.pack xs else V.pack $ (List.replicate (n-l) x ++ xs)) prop "vector padLeft n x xs = if l >= n then xs else replicate (n-l) x ++ xs" $ \ xs n x -> (V.padLeft n x . V.pack @V.PrimVector @Int $ xs) === (let l = List.length xs in if l >= n then V.pack xs else V.pack $ (List.replicate (n-l) x ++ xs)) prop "vector padLeft n x xs = if l >= n then xs else replicate (n-l) x ++ xs" $ \ xs n x -> (V.padLeft n x . V.pack @V.PrimVector @Word8 $ xs) === (let l = List.length xs in if l >= n then V.pack xs else V.pack $ (List.replicate (n-l) x ++ xs)) describe "vector padRight n x xs = if l >= n then xs else xs ++ List.replicate (n-l) x" $ do prop "vector padRight n x xs = if l >= n then xs else xs ++ List.replicate (n-l) x" $ \ xs n x -> (V.padRight n x . V.pack @V.Vector @Integer $ xs) === (let l = List.length xs in if l >= n then V.pack xs else V.pack $ xs ++ (List.replicate (n-l) x)) prop "vector padRight n x xs = if l >= n then xs else xs ++ List.replicate (n-l) x" $ \ xs n x -> (V.padRight n x . V.pack @V.PrimVector @Int $ xs) === (let l = List.length xs in if l >= n then V.pack xs else V.pack $ xs ++ (List.replicate (n-l) x)) prop "vector padRight n x xs = if l >= n then xs else xs ++ List.replicate (n-l) x" $ \ xs n x -> (V.padRight n x . V.pack @V.PrimVector @Word8 $ xs) === (let l = List.length xs in if l >= n then V.pack xs else V.pack $ xs ++ (List.replicate (n-l) x)) describe "vector reverse == List.reverse" $ do prop "vector reverse === List.reverse" $ \ xs -> (V.reverse . V.pack @V.Vector @Integer $ xs) === (V.pack . List.reverse $ xs) prop "vector reverse === List.reverse" $ \ xs -> (V.reverse . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.reverse $ xs) prop "vector reverse === List.reverse" $ \ xs -> (V.reverse . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.reverse $ xs) describe "vector intersperse == List.intersperse" $ do prop "vector intersperse === List.intersperse" $ \ xs x -> (V.intersperse x . V.pack @V.Vector @Integer $ xs) === (V.pack . List.intersperse x $ xs) prop "vector intersperse x === List.intersperse x" $ \ xs x -> (V.intersperse x . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.intersperse x $ xs) prop "vector intersperse x === List.intersperse x" $ \ xs x -> (V.intersperse x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.intersperse x $ xs) describe "vector intercalate == List.intercalate" $ do prop "vector intercalate === List.intercalate" $ \ xs ys -> (V.intercalate (V.pack ys) . List.map (V.pack @V.Vector @Integer) $ xs) === (V.pack . List.intercalate ys $ xs) prop "vector intercalate ys === List.intercalate x" $ \ xs ys -> (V.intercalate (V.pack ys) . List.map (V.pack @V.PrimVector @Int) $ xs) === (V.pack . List.intercalate ys $ xs) prop "vector intercalate ys === List.intercalate x" $ \ xs ys -> (V.intercalate (V.pack ys) . List.map (V.pack @V.PrimVector @Word8) $ xs) === (V.pack . List.intercalate ys $ xs) describe "vector intercalateElem x == List.intercalate [x]" $ do prop "vector intercalateElem x === List.intercalate [x]" $ \ xs x -> (V.intercalateElem x . List.map (V.pack @V.Vector @Integer) $ xs) === (V.pack . List.intercalate [x] $ xs) prop "vector intercalateElem ys === List.intercalate x" $ \ xs x -> (V.intercalateElem x . List.map (V.pack @V.PrimVector @Int) $ xs) === (V.pack . List.intercalate [x] $ xs) prop "vector intercalateElem ys === List.intercalate x" $ \ xs x -> (V.intercalateElem x . List.map (V.pack @V.PrimVector @Word8) $ xs) === (V.pack . List.intercalate [x] $ xs) describe "vector transpose == List.transpose" $ do prop "vector transpose == List.transpose" $ \ xs -> (V.transpose $ V.pack @V.Vector @Integer <$> xs) === (V.pack <$> List.transpose xs) prop "vector transpose == List.transpose" $ \ xs -> (V.transpose $ V.pack @V.PrimVector @Int <$> xs) === (V.pack <$> List.transpose xs) prop "vector transpose == List.transpose" $ \ xs -> (V.transpose $ V.pack @V.PrimVector @Word8 <$> xs) === (V.pack <$> List.transpose xs) describe "vector zipWith' == List.zipWith" $ do prop "vector zipWith' == List.zipWith" $ \ xs ys x -> let pack' = V.pack @V.Vector @Integer in (V.zipWith' (applyFun2 x) (pack' xs) (pack' ys)) === (pack' $ List.zipWith (applyFun2 x) xs ys) prop "vector zipWith == List.zipWith" $ \ xs ys x -> let pack' = V.pack @V.PrimVector @Int in (V.zipWith' (applyFun2 x) (pack' xs) (pack' ys)) === (pack' $ List.zipWith (applyFun2 x) xs ys) prop "vector zipWith' == List.zipWith" $ \ xs ys x -> let pack' = V.pack @V.PrimVector @Word8 in (V.zipWith' (applyFun2 x) (pack' xs) (pack' ys)) === (pack' $ List.zipWith (applyFun2 x) xs ys) describe "vector unzipWith' f == List.unzip . List.map f" $ do prop "vector zipWith' == List.unzip . List.map f" $ \ zs (Fun _ x) -> let pack' = V.pack @V.Vector @Integer in (V.unzipWith' x (pack' zs)) === (let (a,b) = List.unzip (List.map x zs) in (pack' a, pack' b)) prop "vector zipWith == List.unzip . List.map f" $ \ zs (Fun _ x) -> let pack' = V.pack @V.PrimVector @Int in (V.unzipWith' x (pack' zs)) === (let (a,b) = List.unzip (List.map x zs) in (pack' a, pack' b)) prop "vector zipWith' == List.unzip . List.map f" $ \ zs (Fun _ x) -> let pack' = V.pack @V.PrimVector @Word8 in (V.unzipWith' x (pack' zs)) === (let (a,b) = List.unzip (List.map x zs) in (pack' a, pack' b)) describe "vector scanl' == List.scanl" $ do prop "vector scanl' === List.scanl" $ \ xs f x -> (V.scanl' @V.Vector @V.Vector (applyFun2 f :: Integer -> Integer -> Integer) x . V.pack @V.Vector @Integer $ xs) === (V.pack . List.scanl (applyFun2 f) x $ xs) prop "vector scanl' x === List.scanl x" $ \ xs f x -> (V.scanl' @V.PrimVector @V.PrimVector (applyFun2 f :: Int -> Int -> Int) x . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.scanl (applyFun2 f) x $ xs) prop "vector scanl' x === List.scanl x" $ \ xs f x -> (V.scanl' @V.PrimVector @V.Vector (applyFun2 f :: Int -> Word8 -> Int) x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.scanl (applyFun2 f) x $ xs) describe "vector scanl1' == List.scanl1" $ do prop "vector scanl1' === List.scanl1" $ \ xs f -> (V.scanl1' (applyFun2 f :: Integer -> Integer -> Integer) . V.pack @V.Vector @Integer $ xs) === (V.pack . List.scanl1 (applyFun2 f) $ xs) prop "vector scanl1' x === List.scanl1 x" $ \ xs f -> (V.scanl1' (applyFun2 f :: Int -> Int -> Int) . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.scanl1 (applyFun2 f) $ xs) prop "vector scanl1' x === List.scanl1 x" $ \ xs f -> (V.scanl1' (applyFun2 f :: Word8 -> Word8 -> Word8) . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.scanl1 (applyFun2 f) $ xs) describe "vector scanr' == List.scanr" $ do prop "vector scanr' === List.scanr" $ \ xs f x -> (V.scanr' @V.Vector @V.Vector (applyFun2 f :: Integer -> Integer -> Integer) x . V.pack @V.Vector @Integer $ xs) === (V.pack . List.scanr (applyFun2 f) x $ xs) prop "vector scanr' x === List.scanr x" $ \ xs f x -> (V.scanr' @V.PrimVector @V.PrimVector (applyFun2 f :: Int -> Int -> Int) x . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.scanr (applyFun2 f) x $ xs) prop "vector scanr' x === List.scanr x" $ \ xs f x -> (V.scanr' @V.PrimVector @V.Vector (applyFun2 f :: Word8 -> Int -> Int) x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.scanr (applyFun2 f) x $ xs) describe "vector scanr1' == List.scanr1" $ do prop "vector scanr1' === List.scanr1" $ \ xs f -> (V.scanr1' (applyFun2 f :: Integer -> Integer -> Integer) . V.pack @V.Vector @Integer $ xs) === (V.pack . List.scanr1 (applyFun2 f) $ xs) prop "vector scanr1' x === List.scanr1 x" $ \ xs f -> (V.scanr1' (applyFun2 f :: Int -> Int -> Int) . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.scanr1 (applyFun2 f) $ xs) prop "vector scanr1' x === List.scanr1 x" $ \ xs f -> (V.scanr1' (applyFun2 f :: Word8 -> Word8 -> Word8) . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.scanr1 (applyFun2 f) $ xs)
null
https://raw.githubusercontent.com/ZHaskell/stdio/7887b9413dc9feb957ddcbea96184f904cf37c12/std-data/test/Std/Data/Vector/ExtraSpec.hs
haskell
# LANGUAGE TypeApplications # # LANGUAGE ScopedTypeVariables # module Std.Data.Vector.ExtraSpec where import qualified Data.List as List import Data.Word import qualified Std.Data.Vector as V import qualified Std.Data.Vector.Base as V import qualified Std.Data.Vector.Extra as V import Test.QuickCheck import Test.QuickCheck.Function import Test.QuickCheck.Property import Test.Hspec import Test.Hspec.QuickCheck spec :: Spec spec = describe "vector-extras" $ do describe "vector cons == List.(:)" $ do prop "vector cons == List.(:)" $ \ xs x -> (V.cons x . V.pack @V.Vector @Integer $ xs) === (V.pack . (:) x $ xs) prop "vector cons == List.(:)" $ \ xs x -> (V.cons x . V.pack @V.PrimVector @Int $ xs) === (V.pack . (:) x $ xs) prop "vector cons == List.(:)" $ \ xs x -> (V.cons x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . (:) x $ xs) describe "vector snoc == List.++" $ do prop "vector snoc == List.++" $ \ xs x -> ((`V.snoc` x) . V.pack @V.Vector @Integer $ xs) === (V.pack . (++ [x]) $ xs) prop "vector snoc == List.++" $ \ xs x -> ((`V.snoc` x) . V.pack @V.PrimVector @Int $ xs) === (V.pack . (++ [x]) $ xs) prop "vector snoc == List.++" $ \ xs x -> ((`V.snoc` x) . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . (++ [x]) $ xs) describe "vector headMaybe == Just. List.head" $ do prop "vector headMaybe === Just . list.head" $ \ (NonEmpty xs) -> (V.headMaybe . V.pack @V.Vector @Integer $ xs) === (Just . List.head $ xs) prop "vector headMaybe === Just . List.head" $ \ (NonEmpty xs) -> (V.headMaybe . V.pack @V.PrimVector @Int $ xs) === (Just . List.head $ xs) prop "vector headMaybe === Just . List.head" $ \ (NonEmpty xs) -> (V.headMaybe . V.pack @V.PrimVector @Word8 $ xs) === (Just . List.head $ xs) describe "vector initMayEmpty == List.init" $ do prop "vector initMayEmpty === List.init" $ \ (NonEmpty xs) -> (V.initMayEmpty . V.pack @V.Vector @Integer $ xs) === (V.pack . List.init $ xs) prop "vector initMayEmpty === List.init" $ \ (NonEmpty xs) -> (V.initMayEmpty . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.init $ xs) prop "vector initMayEmpty === List.init" $ \ (NonEmpty xs) -> (V.initMayEmpty . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.init $ xs) describe "vector lastMaybe == Just. List.last" $ do prop "vector lastMaybe === Just . list.last" $ \ (NonEmpty xs) -> (V.lastMaybe . V.pack @V.Vector @Integer $ xs) === (Just . List.last $ xs) prop "vector lastMaybe === Just . List.last" $ \ (NonEmpty xs) -> (V.lastMaybe . V.pack @V.PrimVector @Int $ xs) === (Just . List.last $ xs) prop "vector lastMaybe === Just . List.last" $ \ (NonEmpty xs) -> (V.lastMaybe . V.pack @V.PrimVector @Word8 $ xs) === (Just . List.last $ xs) describe "vector tailMayEmpty == List.tail" $ do prop "vector tailMayEmpty === List.tail" $ \ (NonEmpty xs) -> (V.tailMayEmpty . V.pack @V.Vector @Integer $ xs) === (V.pack . List.tail $ xs) prop "vector tailMayEmpty === List.tail" $ \ (NonEmpty xs) -> (V.tailMayEmpty . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.tail $ xs) prop "vector tailMayEmpty === List.tail" $ \ (NonEmpty xs) -> (V.tailMayEmpty . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.tail $ xs) describe "vector take == List.take" $ do prop "vector take == List.take" $ \ xs x -> (V.take x . V.pack @V.Vector @Integer $ xs) === (V.pack . List.take x $ xs) prop "vector take == List.take" $ \ xs x -> (V.take x . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.take x $ xs) prop "vector take == List.take" $ \ xs x -> (V.take x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.take x $ xs) describe "vector takeR x == List.reverse . List.take x . List.reverse" $ do prop "vector takeR x == List.reverse . List.take x . List.reverse" $ \ xs x -> (V.takeR x . V.pack @V.Vector @Integer $ xs) === (V.pack . List.reverse . List.take x . List.reverse $ xs) prop "vector takeR x == List.reverse . List.take x . List.reverse" $ \ xs x -> (V.takeR x . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.reverse . List.take x . List.reverse $ xs) prop "vector takeR x == List.reverse . List.take x . List.reverse" $ \ xs x -> (V.takeR x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.reverse . List.take x . List.reverse $ xs) describe "vector drop == List.drop" $ do prop "vector drop == List.drop" $ \ xs x -> (V.drop x . V.pack @V.Vector @Integer $ xs) === (V.pack . List.drop x $ xs) prop "vector drop == List.drop" $ \ xs x -> (V.drop x . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.drop x $ xs) prop "vector drop == List.drop" $ \ xs x -> (V.drop x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.drop x $ xs) describe "vector dropR x == List.reverse . List.drop x . List.reverse" $ do prop "vector dropR x == List.reverse . List.drop x . List.reverse" $ \ xs x -> (V.dropR x . V.pack @V.Vector @Integer $ xs) === (V.pack . List.reverse . List.drop x . List.reverse $ xs) prop "vector dropR x == List.reverse . List.drop x . List.reverse" $ \ xs x -> (V.dropR x . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.reverse . List.drop x . List.reverse $ xs) prop "vector dropR x == List.reverse . List.drop x . List.reverse" $ \ xs x -> (V.dropR x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.reverse . List.drop x . List.reverse $ xs) describe "vector slice x y == drop x . take (x+y)" $ do prop "vector slice x y === drop x . take (x+y)" $ \ x y xs -> (V.slice x y . V.pack @V.Vector @Integer $ xs) === (V.pack . drop x . take (x+y) $ xs) prop "vector slice x y xs === drop x . take (x+y) x" $ \ x y xs -> (V.slice x y . V.pack @V.PrimVector @Int $ xs) === (V.pack . drop x . take (x+y) $ xs) prop "vector slice x y xs === drop x . take (x+y) x" $ \ x y xs -> (V.slice x y . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . drop x . take (x+y) $ xs) describe "vector splitAt == List.splitAt" $ do prop "vector splitAt == List.splitAt" $ \ xs x -> (V.splitAt x . V.pack @V.Vector @Integer $ xs) === (let (a,b) = List.splitAt x $ xs in (V.pack a, V.pack b)) prop "vector splitAt == List.splitAt" $ \ xs x -> (V.splitAt x . V.pack @V.PrimVector @Int $ xs) === (let (a,b) = List.splitAt x $ xs in (V.pack a, V.pack b)) prop "vector splitAt == List.splitAt" $ \ xs x -> (V.splitAt x . V.pack @V.PrimVector @Word8 $ xs) === (let (a,b) = List.splitAt x $ xs in (V.pack a, V.pack b)) describe "vector takeWhile == List.takeWhile" $ do prop "vector takeWhile == List.takeWhile" $ \ xs (Fun _ x) -> (V.takeWhile x . V.pack @V.Vector @Integer $ xs) === (V.pack . List.takeWhile x $ xs) prop "vector takeWhile == List.takeWhile" $ \ xs (Fun _ x) -> (V.takeWhile x . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.takeWhile x $ xs) prop "vector takeWhile == List.takeWhile" $ \ xs (Fun _ x) -> (V.takeWhile x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.takeWhile x $ xs) describe "vector takeWhileR == reverse . List.takeWhile . reverse" $ do prop "vector takeWhileR == reverse . List.takeWhile . reverse" $ \ xs (Fun _ x) -> (V.takeWhileR x . V.pack @V.Vector @Integer $ xs) === (V.pack . List.reverse . List.takeWhile x $ List.reverse xs) prop "vector takeWhileR == reverse . List.takeWhile . reverse" $ \ xs (Fun _ x) -> (V.takeWhileR x . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.reverse . List.takeWhile x $ List.reverse xs) prop "vector takeWhileR == reverse . List.takeWhile . reverse" $ \ xs (Fun _ x) -> (V.takeWhileR x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.reverse . List.takeWhile x $ List.reverse xs) describe "vector dropWhile == List.dropWhile" $ do prop "vector dropWhile == List.dropWhile" $ \ xs (Fun _ x) -> (V.dropWhile x . V.pack @V.Vector @Integer $ xs) === (V.pack . List.dropWhile x $ xs) prop "vector dropWhile == List.dropWhile" $ \ xs (Fun _ x) -> (V.dropWhile x . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.dropWhile x $ xs) prop "vector dropWhile == List.dropWhile" $ \ xs (Fun _ x) -> (V.dropWhile x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.dropWhile x $ xs) describe "vector dropWhileR == reverse . List.dropWhile . reverse" $ do prop "vector dropWhileR == reverse . List.dropWhile . reverse" $ \ xs (Fun _ x) -> (V.dropWhileR x . V.pack @V.Vector @Integer $ xs) === (V.pack . List.reverse . List.dropWhile x $ List.reverse xs) prop "vector dropWhileR == reverse . List.dropWhile . reverse" $ \ xs (Fun _ x) -> (V.dropWhileR x . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.reverse . List.dropWhile x $ List.reverse xs) prop "vector dropWhileR == reverse . List.dropWhile . reverse" $ \ xs (Fun _ x) -> (V.dropWhileR x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.reverse . List.dropWhile x $ List.reverse xs) describe "vector break == List.break" $ do prop "vector break == List.break" $ \ xs (Fun _ x) -> (V.break x . V.pack @V.Vector @Integer $ xs) === (let (a,b) = List.break x $ xs in (V.pack a, V.pack b)) prop "vector break == List.break" $ \ xs (Fun _ x) -> (V.break x . V.pack @V.PrimVector @Int $ xs) === (let (a,b) = List.break x $ xs in (V.pack a, V.pack b)) prop "vector break == List.break" $ \ xs (Fun _ x) -> (V.break x . V.pack @V.PrimVector @Word8 $ xs) === (let (a,b) = List.break x $ xs in (V.pack a, V.pack b)) describe "vector breakOn rules" $ do prop "vector breakOn rules" $ \ xs ys -> (let (a, b) = V.breakOn (V.pack xs) . V.pack @V.Vector @Integer $ ys in (a `V.append` b, V.pack xs `V.isPrefixOf` b || V.null b) === (V.pack ys, True)) prop "vector breakOn rules" $ \ xs ys -> (let (a, b) = V.breakOn (V.pack xs) . V.pack @V.PrimVector @Int $ ys in (a `V.append` b, V.pack xs `V.isPrefixOf` b || V.null b) === (V.pack ys, True)) prop "vector breakOn rules" $ \ xs ys -> (let (a, b) = V.breakOn (V.pack xs) . V.pack @V.PrimVector @Word8 $ ys in (a `V.append` b, V.pack xs `V.isPrefixOf` b || V.null b) === (V.pack ys, True)) describe "vector span == List.span" $ do prop "vector span == List.span" $ \ xs (Fun _ x) -> (V.span x . V.pack @V.Vector @Integer $ xs) === (let (a,b) = List.span x $ xs in (V.pack a, V.pack b)) prop "vector span == List.span" $ \ xs (Fun _ x) -> (V.span x . V.pack @V.PrimVector @Int $ xs) === (let (a,b) = List.span x $ xs in (V.pack a, V.pack b)) prop "vector span == List.span" $ \ xs (Fun _ x) -> (V.span x . V.pack @V.PrimVector @Word8 $ xs) === (let (a,b) = List.span x $ xs in (V.pack a, V.pack b)) describe "vector breakR == List.break in reverse driection" $ do prop "vector breakR == List.break in reverse driection" $ \ xs (Fun _ x) -> (V.breakR x . V.pack @V.Vector @Integer $ xs) === (let (b,a) = List.break x . List.reverse $ xs in (V.reverse $ V.pack a, V.reverse $ V.pack b)) prop "vector breakR == List.break in reverse driection" $ \ xs (Fun _ x) -> (V.breakR x . V.pack @V.PrimVector @Int $ xs) === (let (b,a) = List.break x . List.reverse $ xs in (V.reverse $ V.pack a, V.reverse $ V.pack b)) prop "vector breakR == List.break in reverse driection" $ \ xs (Fun _ x) -> (V.breakR x . V.pack @V.PrimVector @Word8 $ xs) === (let (b,a) = List.break x . List.reverse $ xs in (V.reverse $ V.pack a, V.reverse $ V.pack b)) describe "vector spanR == List.span in reverse driection" $ do prop "vector spanR == List.span in reverse driection" $ \ xs (Fun _ x) -> (V.spanR x . V.pack @V.Vector @Integer $ xs) === (let (b,a) = List.span x . List.reverse $ xs in (V.reverse $ V.pack a, V.reverse $ V.pack b)) prop "vector spanR == List.span in reverse driection" $ \ xs (Fun _ x) -> (V.spanR x . V.pack @V.PrimVector @Int $ xs) === (let (b,a) = List.span x . List.reverse $ xs in (V.reverse $ V.pack a, V.reverse $ V.pack b)) prop "vector spanR == List.span in reverse driection" $ \ xs (Fun _ x) -> (V.spanR x . V.pack @V.PrimVector @Word8 $ xs) === (let (b,a) = List.span x . List.reverse $ xs in (V.reverse $ V.pack a, V.reverse $ V.pack b)) describe "vector group == List.group" $ do prop "vector group == List.group" $ \ xs -> (V.group . V.pack @V.Vector @Integer $ xs) === (V.pack <$> List.group xs) prop "vector group == List.group" $ \ xs -> (V.group . V.pack @V.PrimVector @Int $ xs) === (V.pack <$> List.group xs) prop "vector group == List.group" $ \ xs -> (V.group . V.pack @V.PrimVector @Word8 $ xs) === (V.pack <$> List.group xs) describe "vector groupBy == List.groupBy" $ do prop "vector groupBy == List.groupBy" $ \ xs x -> (V.groupBy (applyFun2 x) . V.pack @V.Vector @Integer $ xs) === (V.pack <$> List.groupBy (applyFun2 x) xs) prop "vector groupBy == List.groupBy" $ \ xs x -> (V.groupBy (applyFun2 x) . V.pack @V.PrimVector @Int $ xs) === (V.pack <$> List.groupBy (applyFun2 x) xs) prop "vector groupBy == List.groupBy" $ \ xs x -> (V.groupBy (applyFun2 x) . V.pack @V.PrimVector @Word8 $ xs) === (V.pack <$> List.groupBy (applyFun2 x) xs) describe "vector stripPrefix a (a+b) = b " $ do prop "vector stripPrefix == List.stripPrefix" $ \ xs ys -> (V.stripPrefix (V.pack xs) . V.pack @V.Vector @Integer $ xs++ys) === (Just $ V.pack ys) prop "vector stripPrefix == List.stripPrefix" $ \ xs ys -> (V.stripPrefix (V.pack xs) . V.pack @V.PrimVector @Int $ xs++ys) === (Just $ V.pack ys) prop "vector stripPrefix == List.stripPrefix" $ \ xs ys -> (V.stripPrefix (V.pack xs) . V.pack @V.PrimVector @Word8 $ xs++ys) === (Just $ V.pack ys) describe "vector stripSuffix b (a+b) = a " $ do prop "vector stripSuffix == List.stripSuffix" $ \ xs ys -> (V.stripSuffix (V.pack xs) . V.pack @V.Vector @Integer $ ys++xs) === (Just $ V.pack ys) prop "vector stripSuffix == List.stripSuffix" $ \ xs ys -> (V.stripSuffix (V.pack xs) . V.pack @V.PrimVector @Int $ ys++xs) === (Just $ V.pack ys) prop "vector stripSuffix == List.stripSuffix" $ \ xs ys -> (V.stripSuffix (V.pack xs) . V.pack @V.PrimVector @Word8 $ ys++xs) === (Just $ V.pack ys) describe "vector isInfixOf b (a+b+c) = True " $ do prop "vector isInfixOf == List.isInfixOf" $ \ xs ys zs -> (V.isInfixOf (V.pack xs) . V.pack @V.Vector @Integer $ ys++xs++zs) === True prop "vector isInfixOf == List.isInfixOf" $ \ xs ys zs -> (V.isInfixOf (V.pack xs) . V.pack @V.PrimVector @Int $ ys++xs++zs) === True prop "vector isInfixOf == List.isInfixOf" $ \ xs ys zs -> (V.isInfixOf (V.pack xs) . V.pack @V.PrimVector @Word8 $ ys++xs++zs) === True describe "let (c,a,b) = vector commonPrefix x y in (a,b) = (stripPrefix c x,stripPrefix c y) " $ do prop "vector commonPrefix rules" $ \ xs ys -> let (c,a,b) = V.commonPrefix (V.pack xs) . V.pack @V.Vector @Integer $ ys Just xs' = V.stripPrefix c $ V.pack xs Just ys' = V.stripPrefix c $ V.pack ys in (a,b) === (xs', ys') prop "vector commonPrefix rules" $ \ xs ys -> let (c,a,b) = V.commonPrefix (V.pack xs) . V.pack @V.PrimVector @Int $ ys Just xs' = V.stripPrefix c $ V.pack xs Just ys' = V.stripPrefix c $ V.pack ys in (a,b) === (xs', ys') prop "vector commonPrefix rules" $ \ xs ys -> let (c,a,b) = V.commonPrefix (V.pack xs) . V.pack @V.PrimVector @Word8 $ ys Just xs' = V.stripPrefix c $ V.pack xs Just ys' = V.stripPrefix c $ V.pack ys in (a,b) === (xs', ys') describe "vector intercalate [x] . split x == id" $ do prop "vector intercalate [x] . split x == id" $ \ xs x -> (V.intercalate (V.singleton x) . V.split x . V.pack @V.Vector @Integer $ xs) === V.pack xs prop "vector intercalate [x] . split x == id" $ \ xs x -> (V.intercalate (V.singleton x) . V.split x . V.pack @V.PrimVector @Int $ xs) === V.pack xs prop "vector intercalate [x] . split x == id" $ \ xs x -> (V.intercalate (V.singleton x) . V.split x . V.pack @V.PrimVector @Word8 $ xs) === V.pack xs describe "vector intercalate x . splitOn x == id" $ do prop "vector intercalate x . splitOn x == id" $ \ xs x -> (V.intercalate (V.pack x) . V.splitOn (V.pack x) . V.pack @V.Vector @Integer $ xs) === V.pack xs prop "vector intercalate x . splitOn x == id" $ \ xs x -> (V.intercalate (V.pack x) . V.splitOn (V.pack x) . V.pack @V.PrimVector @Int $ xs) === V.pack xs prop "vector intercalate x . splitOn x == id" $ \ xs x -> (V.intercalate (V.pack x) . V.splitOn (V.pack x) . V.pack @V.PrimVector @Word8 $ xs) === V.pack xs describe "vector reverse . pack == packR" . modifyMaxSuccess (*10) . modifyMaxSize (*10) $ do prop "reverse . pack === packR XX" $ \ xs -> (V.reverse $ V.pack @V.Vector @Integer xs) === (V.packR xs) prop "reverse . pack === packR XX" $ \ xs -> (V.reverse $ V.pack @V.PrimVector @Int xs) === (V.packR xs) prop "reverse . pack === packR XX" $ \ xs -> (V.reverse $ V.pack @V.PrimVector @Word8 xs) === (V.packR xs) describe "vector words == List.words" $ do prop "vector words === List.words" $ \ xs -> (V.words . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.map V.c2w <$> (List.words . List.map V.w2c $ xs)) describe "vector lines == List.lines" $ do prop "vector lines === List.lines" $ \ xs -> (V.lines . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.map V.c2w <$> (List.lines . List.map V.w2c $ xs)) describe "vector unwords == List.unwords" $ do prop "vector unwords === List.unwords" $ \ xs -> (V.unwords $ V.pack @V.PrimVector @Word8 <$> xs) === (V.pack (List.map V.c2w . List.unwords $ List.map V.w2c <$> xs)) describe "vector unlines == List.unlines" $ do prop "vector unlines === List.unlines" $ \ xs -> (V.unlines $ V.pack @V.PrimVector @Word8 <$> xs) === (V.pack (List.map V.c2w . List.unlines $ List.map V.w2c <$> xs)) describe "vector padLeft n x xs = if l >= n then xs else replicate (n-l) x ++ xs" $ do prop "vector padLeft n x xs = if l >= n then xs else replicate (n-l) x ++ xs" $ \ xs n x -> (V.padLeft n x . V.pack @V.Vector @Integer $ xs) === (let l = List.length xs in if l >= n then V.pack xs else V.pack $ (List.replicate (n-l) x ++ xs)) prop "vector padLeft n x xs = if l >= n then xs else replicate (n-l) x ++ xs" $ \ xs n x -> (V.padLeft n x . V.pack @V.PrimVector @Int $ xs) === (let l = List.length xs in if l >= n then V.pack xs else V.pack $ (List.replicate (n-l) x ++ xs)) prop "vector padLeft n x xs = if l >= n then xs else replicate (n-l) x ++ xs" $ \ xs n x -> (V.padLeft n x . V.pack @V.PrimVector @Word8 $ xs) === (let l = List.length xs in if l >= n then V.pack xs else V.pack $ (List.replicate (n-l) x ++ xs)) describe "vector padRight n x xs = if l >= n then xs else xs ++ List.replicate (n-l) x" $ do prop "vector padRight n x xs = if l >= n then xs else xs ++ List.replicate (n-l) x" $ \ xs n x -> (V.padRight n x . V.pack @V.Vector @Integer $ xs) === (let l = List.length xs in if l >= n then V.pack xs else V.pack $ xs ++ (List.replicate (n-l) x)) prop "vector padRight n x xs = if l >= n then xs else xs ++ List.replicate (n-l) x" $ \ xs n x -> (V.padRight n x . V.pack @V.PrimVector @Int $ xs) === (let l = List.length xs in if l >= n then V.pack xs else V.pack $ xs ++ (List.replicate (n-l) x)) prop "vector padRight n x xs = if l >= n then xs else xs ++ List.replicate (n-l) x" $ \ xs n x -> (V.padRight n x . V.pack @V.PrimVector @Word8 $ xs) === (let l = List.length xs in if l >= n then V.pack xs else V.pack $ xs ++ (List.replicate (n-l) x)) describe "vector reverse == List.reverse" $ do prop "vector reverse === List.reverse" $ \ xs -> (V.reverse . V.pack @V.Vector @Integer $ xs) === (V.pack . List.reverse $ xs) prop "vector reverse === List.reverse" $ \ xs -> (V.reverse . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.reverse $ xs) prop "vector reverse === List.reverse" $ \ xs -> (V.reverse . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.reverse $ xs) describe "vector intersperse == List.intersperse" $ do prop "vector intersperse === List.intersperse" $ \ xs x -> (V.intersperse x . V.pack @V.Vector @Integer $ xs) === (V.pack . List.intersperse x $ xs) prop "vector intersperse x === List.intersperse x" $ \ xs x -> (V.intersperse x . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.intersperse x $ xs) prop "vector intersperse x === List.intersperse x" $ \ xs x -> (V.intersperse x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.intersperse x $ xs) describe "vector intercalate == List.intercalate" $ do prop "vector intercalate === List.intercalate" $ \ xs ys -> (V.intercalate (V.pack ys) . List.map (V.pack @V.Vector @Integer) $ xs) === (V.pack . List.intercalate ys $ xs) prop "vector intercalate ys === List.intercalate x" $ \ xs ys -> (V.intercalate (V.pack ys) . List.map (V.pack @V.PrimVector @Int) $ xs) === (V.pack . List.intercalate ys $ xs) prop "vector intercalate ys === List.intercalate x" $ \ xs ys -> (V.intercalate (V.pack ys) . List.map (V.pack @V.PrimVector @Word8) $ xs) === (V.pack . List.intercalate ys $ xs) describe "vector intercalateElem x == List.intercalate [x]" $ do prop "vector intercalateElem x === List.intercalate [x]" $ \ xs x -> (V.intercalateElem x . List.map (V.pack @V.Vector @Integer) $ xs) === (V.pack . List.intercalate [x] $ xs) prop "vector intercalateElem ys === List.intercalate x" $ \ xs x -> (V.intercalateElem x . List.map (V.pack @V.PrimVector @Int) $ xs) === (V.pack . List.intercalate [x] $ xs) prop "vector intercalateElem ys === List.intercalate x" $ \ xs x -> (V.intercalateElem x . List.map (V.pack @V.PrimVector @Word8) $ xs) === (V.pack . List.intercalate [x] $ xs) describe "vector transpose == List.transpose" $ do prop "vector transpose == List.transpose" $ \ xs -> (V.transpose $ V.pack @V.Vector @Integer <$> xs) === (V.pack <$> List.transpose xs) prop "vector transpose == List.transpose" $ \ xs -> (V.transpose $ V.pack @V.PrimVector @Int <$> xs) === (V.pack <$> List.transpose xs) prop "vector transpose == List.transpose" $ \ xs -> (V.transpose $ V.pack @V.PrimVector @Word8 <$> xs) === (V.pack <$> List.transpose xs) describe "vector zipWith' == List.zipWith" $ do prop "vector zipWith' == List.zipWith" $ \ xs ys x -> let pack' = V.pack @V.Vector @Integer in (V.zipWith' (applyFun2 x) (pack' xs) (pack' ys)) === (pack' $ List.zipWith (applyFun2 x) xs ys) prop "vector zipWith == List.zipWith" $ \ xs ys x -> let pack' = V.pack @V.PrimVector @Int in (V.zipWith' (applyFun2 x) (pack' xs) (pack' ys)) === (pack' $ List.zipWith (applyFun2 x) xs ys) prop "vector zipWith' == List.zipWith" $ \ xs ys x -> let pack' = V.pack @V.PrimVector @Word8 in (V.zipWith' (applyFun2 x) (pack' xs) (pack' ys)) === (pack' $ List.zipWith (applyFun2 x) xs ys) describe "vector unzipWith' f == List.unzip . List.map f" $ do prop "vector zipWith' == List.unzip . List.map f" $ \ zs (Fun _ x) -> let pack' = V.pack @V.Vector @Integer in (V.unzipWith' x (pack' zs)) === (let (a,b) = List.unzip (List.map x zs) in (pack' a, pack' b)) prop "vector zipWith == List.unzip . List.map f" $ \ zs (Fun _ x) -> let pack' = V.pack @V.PrimVector @Int in (V.unzipWith' x (pack' zs)) === (let (a,b) = List.unzip (List.map x zs) in (pack' a, pack' b)) prop "vector zipWith' == List.unzip . List.map f" $ \ zs (Fun _ x) -> let pack' = V.pack @V.PrimVector @Word8 in (V.unzipWith' x (pack' zs)) === (let (a,b) = List.unzip (List.map x zs) in (pack' a, pack' b)) describe "vector scanl' == List.scanl" $ do prop "vector scanl' === List.scanl" $ \ xs f x -> (V.scanl' @V.Vector @V.Vector (applyFun2 f :: Integer -> Integer -> Integer) x . V.pack @V.Vector @Integer $ xs) === (V.pack . List.scanl (applyFun2 f) x $ xs) prop "vector scanl' x === List.scanl x" $ \ xs f x -> (V.scanl' @V.PrimVector @V.PrimVector (applyFun2 f :: Int -> Int -> Int) x . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.scanl (applyFun2 f) x $ xs) prop "vector scanl' x === List.scanl x" $ \ xs f x -> (V.scanl' @V.PrimVector @V.Vector (applyFun2 f :: Int -> Word8 -> Int) x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.scanl (applyFun2 f) x $ xs) describe "vector scanl1' == List.scanl1" $ do prop "vector scanl1' === List.scanl1" $ \ xs f -> (V.scanl1' (applyFun2 f :: Integer -> Integer -> Integer) . V.pack @V.Vector @Integer $ xs) === (V.pack . List.scanl1 (applyFun2 f) $ xs) prop "vector scanl1' x === List.scanl1 x" $ \ xs f -> (V.scanl1' (applyFun2 f :: Int -> Int -> Int) . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.scanl1 (applyFun2 f) $ xs) prop "vector scanl1' x === List.scanl1 x" $ \ xs f -> (V.scanl1' (applyFun2 f :: Word8 -> Word8 -> Word8) . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.scanl1 (applyFun2 f) $ xs) describe "vector scanr' == List.scanr" $ do prop "vector scanr' === List.scanr" $ \ xs f x -> (V.scanr' @V.Vector @V.Vector (applyFun2 f :: Integer -> Integer -> Integer) x . V.pack @V.Vector @Integer $ xs) === (V.pack . List.scanr (applyFun2 f) x $ xs) prop "vector scanr' x === List.scanr x" $ \ xs f x -> (V.scanr' @V.PrimVector @V.PrimVector (applyFun2 f :: Int -> Int -> Int) x . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.scanr (applyFun2 f) x $ xs) prop "vector scanr' x === List.scanr x" $ \ xs f x -> (V.scanr' @V.PrimVector @V.Vector (applyFun2 f :: Word8 -> Int -> Int) x . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.scanr (applyFun2 f) x $ xs) describe "vector scanr1' == List.scanr1" $ do prop "vector scanr1' === List.scanr1" $ \ xs f -> (V.scanr1' (applyFun2 f :: Integer -> Integer -> Integer) . V.pack @V.Vector @Integer $ xs) === (V.pack . List.scanr1 (applyFun2 f) $ xs) prop "vector scanr1' x === List.scanr1 x" $ \ xs f -> (V.scanr1' (applyFun2 f :: Int -> Int -> Int) . V.pack @V.PrimVector @Int $ xs) === (V.pack . List.scanr1 (applyFun2 f) $ xs) prop "vector scanr1' x === List.scanr1 x" $ \ xs f -> (V.scanr1' (applyFun2 f :: Word8 -> Word8 -> Word8) . V.pack @V.PrimVector @Word8 $ xs) === (V.pack . List.scanr1 (applyFun2 f) $ xs)
0df599ac7dd0d52b3c8bafa1a1ceb2391fb20ef5c1f14c58c3da81892f083e15
haskell-waargonaut/waargonaut
Bench.hs
module Main where import qualified Waargbench main :: IO () main = Waargbench.main
null
https://raw.githubusercontent.com/haskell-waargonaut/waargonaut/ba1dbbc170c2279749ea29bc8aaf375bdb659ad2/waargbench/bench/Bench.hs
haskell
module Main where import qualified Waargbench main :: IO () main = Waargbench.main
70a765de3191399fc8a233ef4fec2498ce15d8a4c67aa4d00743d7b1c9262e06
MyDataFlow/ttalk-server
ets_statem.erl
Copyright 2010 - 2011 < > , < > and < > %%% This file is part of PropEr . %%% %%% PropEr 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. %%% %%% PropEr 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 PropEr. If not, see </>. 2010 - 2011 , and %%% @version {@version} @author %%% @doc Simple statem test for ets tables -module(ets_statem). -behaviour(proper_statem). -export([initial_state/0, initial_state/1, initial_state/2, command/1, precondition/2, postcondition/3, next_state/3]). -export([sample_commands/0]). -include_lib("proper/include/proper.hrl"). -type object() :: tuple(). -type table_type() :: 'set' | 'ordered_set' | 'bag' | 'duplicate_bag'. -record(state, {tids = [] :: [ets:tid()], stored = [] :: [object()], %% list of objects stored in %% ets table type = set :: table_type()}). %% type of ets table -define(INT_KEYS, lists:seq(0, 2)). -define(FLOAT_KEYS, [float(Key) || Key <- ?INT_KEYS]). %%% Generators key() -> frequency([{2, elements(?INT_KEYS)}, {1, elements(?FLOAT_KEYS)}]). value() -> frequency([{5, int()}, {1, elements([a, b, c, d])}]). object() -> {key(), value()}. object(S) -> elements(S#state.stored). key(S) -> ?LET(Object, object(S), element(1, Object)). tid(S) -> elements(S#state.tids). %%% Abstract state machine for ets table initial_state() -> #state{type = set}. initial_state(Type) -> #state{type = Type}. initial_state(Type, parallel) -> #state{tids = [tab], type = Type}. command(#state{tids = [], type = Type}) -> {call,ets,new,[tab, [Type]]}; command(S) -> oneof([{call,ets,insert,[tid(S), object()]}, {call,ets,delete,[tid(S), key()]}] ++ [{call,ets,lookup_element,[tid(S), key(S), range(1, 2)]} || S#state.stored =/= []] ++ [{call,ets,update_counter,[tid(S), key(S), int()]} || S#state.stored =/= [], S#state.type =:= set orelse S#state.type =:= ordered_set]). precondition(S, {call,_,lookup_element,[_, Key, _]}) -> proplists:is_defined(Key, S#state.stored); precondition(S, {call,_,update_counter,[_, Key, _Incr]}) -> proplists:is_defined(Key, S#state.stored) andalso case S#state.type of set -> Obj = proplists:lookup(Key, S#state.stored), is_integer(element(2, Obj)); ordered_set -> Obj = lists:keyfind(Key, 1, S#state.stored), is_integer(element(2, Obj)); _ -> false end; precondition(_S, {call,_,_,_}) -> true. next_state(S, V, {call,_,new,[_Tab, _Opts]}) -> S#state{tids = [V|S#state.tids]}; next_state(S, _V, {call,_,update_counter,[_Tab, Key, Incr]}) -> case S#state.type of set -> Object = proplists:lookup(Key, S#state.stored), Value = element(2, Object), NewObj = setelement(2, Object, Value + Incr), S#state{stored=keyreplace(Key, 1, S#state.stored, NewObj)}; ordered_set -> Object = lists:keyfind(Key, 1, S#state.stored), Value = element(2, Object), NewObj = setelement(2, Object, Value + Incr), S#state{stored=lists:keyreplace(Key, 1, S#state.stored, NewObj)} end; next_state(S, _V, {call,_,insert,[_Tab, Object]}) -> case S#state.type of set -> Key = element(1, Object), case proplists:is_defined(Key, S#state.stored) of false -> S#state{stored = S#state.stored ++ [Object]}; true -> %% correct model S#state{stored=keyreplace(Key, 1, S#state.stored, Object)} error model , run { numtests , 3000 } to discover the bug S#state{stored = lists : keyreplace(Key , 1 , S#state.stored , %% Object)} end; ordered_set -> Key = element(1, Object), case lists:keymember(Key, 1, S#state.stored) of false -> S#state{stored = S#state.stored ++ [Object]}; true -> S#state{stored=lists:keyreplace(Key, 1, S#state.stored, Object)} end; bag -> case lists:member(Object, S#state.stored) of false -> S#state{stored = S#state.stored ++ [Object]}; true -> S end; duplicate_bag -> S#state{stored = S#state.stored ++ [Object]} end; next_state(S, _V, {call,_,delete,[_Tab, Key]}) -> case S#state.type of ordered_set -> S#state{stored=lists:keydelete(Key, 1, S#state.stored)}; _ -> S#state{stored=proplists:delete(Key, S#state.stored)} end; next_state(S, _V, {call,_,_,_}) -> S. postcondition(_S, {call,_,new,[_Tab, _Opts]}, _Res) -> true; postcondition(S, {call,_,update_counter,[_Tab, Key, Incr]}, Res) -> Object = case S#state.type of set -> proplists:lookup(Key, S#state.stored); ordered_set -> lists:keyfind(Key, 1, S#state.stored) end, Value = element(2, Object), Res =:= Value + Incr; postcondition(_S, {call,_,delete,[_Tab, _Key]}, Res) -> Res =:= true; postcondition(_S, {call,_,insert,[_Tab, _Object]}, Res) -> Res =:= true; postcondition(S, {call,_,lookup_element,[_Tab, Key, Pos]}, Res) -> case S#state.type of ordered_set -> Res =:= element(Pos, lists:keyfind(Key, 1, S#state.stored)); set -> Res =:= element(Pos, proplists:lookup(Key, S#state.stored)); _ -> Res =:= [element(Pos, Tuple) || Tuple <- proplists:lookup_all(Key, S#state.stored)] end. %%% Sample properties prop_ets() -> ?FORALL(Type, noshrink(table_type()), ?FORALL(Cmds, commands(?MODULE, initial_state(Type)), begin {H,S,Res} = run_commands(?MODULE, Cmds), [ets:delete(Tab) || Tab <- S#state.tids], ?WHENFAIL( io:format("History: ~p\nState: ~p\nRes: ~p\n", [H,S,Res]), collect(Type, Res =:= ok)) end)). prop_parallel_ets() -> ?FORALL(Type, noshrink(table_type()), ?FORALL(Cmds, commands(?MODULE, initial_state(Type, parallel)), begin ets:new(tab, [named_table, public, Type]), {Seq,P,Res} = run_commands(?MODULE, Cmds), ets:delete(tab), ?WHENFAIL( io:format("Sequential: ~p\nParallel: ~p\nRes: ~p\n", [Seq,P,Res]), collect(Type, Res =:= ok)) end)). %%% Demo commands sample_commands() -> proper_gen:sample( ?LET(Type, oneof([set, ordered_set, bag, duplicate_bag]), commands(?MODULE, initial_state(Type)))). %%% Utility Functions keyreplace(Key, Pos, List, NewTuple) -> keyreplace(Key, Pos, List, NewTuple, []). keyreplace(_Key, _Pos, [], _NewTuple, Acc) -> lists:reverse(Acc); keyreplace(Key, Pos, [Tuple|Rest], NewTuple, Acc) -> case element(Pos, Tuple) =:= Key of true -> lists:reverse(Acc) ++ [NewTuple|Rest]; false -> keyreplace(Key, Pos, Rest, NewTuple, [Tuple|Acc]) end.
null
https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/deps/proper/examples/ets_statem.erl
erlang
PropEr is free software: you can redistribute it and/or modify (at your option) any later version. PropEr 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 PropEr. If not, see </>. @version {@version} @doc Simple statem test for ets tables list of objects stored in ets table type of ets table Generators Abstract state machine for ets table correct model Object)} Sample properties Demo commands Utility Functions
Copyright 2010 - 2011 < > , < > and < > This file is part of PropEr . it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License 2010 - 2011 , and @author -module(ets_statem). -behaviour(proper_statem). -export([initial_state/0, initial_state/1, initial_state/2, command/1, precondition/2, postcondition/3, next_state/3]). -export([sample_commands/0]). -include_lib("proper/include/proper.hrl"). -type object() :: tuple(). -type table_type() :: 'set' | 'ordered_set' | 'bag' | 'duplicate_bag'. -record(state, {tids = [] :: [ets:tid()], -define(INT_KEYS, lists:seq(0, 2)). -define(FLOAT_KEYS, [float(Key) || Key <- ?INT_KEYS]). key() -> frequency([{2, elements(?INT_KEYS)}, {1, elements(?FLOAT_KEYS)}]). value() -> frequency([{5, int()}, {1, elements([a, b, c, d])}]). object() -> {key(), value()}. object(S) -> elements(S#state.stored). key(S) -> ?LET(Object, object(S), element(1, Object)). tid(S) -> elements(S#state.tids). initial_state() -> #state{type = set}. initial_state(Type) -> #state{type = Type}. initial_state(Type, parallel) -> #state{tids = [tab], type = Type}. command(#state{tids = [], type = Type}) -> {call,ets,new,[tab, [Type]]}; command(S) -> oneof([{call,ets,insert,[tid(S), object()]}, {call,ets,delete,[tid(S), key()]}] ++ [{call,ets,lookup_element,[tid(S), key(S), range(1, 2)]} || S#state.stored =/= []] ++ [{call,ets,update_counter,[tid(S), key(S), int()]} || S#state.stored =/= [], S#state.type =:= set orelse S#state.type =:= ordered_set]). precondition(S, {call,_,lookup_element,[_, Key, _]}) -> proplists:is_defined(Key, S#state.stored); precondition(S, {call,_,update_counter,[_, Key, _Incr]}) -> proplists:is_defined(Key, S#state.stored) andalso case S#state.type of set -> Obj = proplists:lookup(Key, S#state.stored), is_integer(element(2, Obj)); ordered_set -> Obj = lists:keyfind(Key, 1, S#state.stored), is_integer(element(2, Obj)); _ -> false end; precondition(_S, {call,_,_,_}) -> true. next_state(S, V, {call,_,new,[_Tab, _Opts]}) -> S#state{tids = [V|S#state.tids]}; next_state(S, _V, {call,_,update_counter,[_Tab, Key, Incr]}) -> case S#state.type of set -> Object = proplists:lookup(Key, S#state.stored), Value = element(2, Object), NewObj = setelement(2, Object, Value + Incr), S#state{stored=keyreplace(Key, 1, S#state.stored, NewObj)}; ordered_set -> Object = lists:keyfind(Key, 1, S#state.stored), Value = element(2, Object), NewObj = setelement(2, Object, Value + Incr), S#state{stored=lists:keyreplace(Key, 1, S#state.stored, NewObj)} end; next_state(S, _V, {call,_,insert,[_Tab, Object]}) -> case S#state.type of set -> Key = element(1, Object), case proplists:is_defined(Key, S#state.stored) of false -> S#state{stored = S#state.stored ++ [Object]}; true -> S#state{stored=keyreplace(Key, 1, S#state.stored, Object)} error model , run { numtests , 3000 } to discover the bug S#state{stored = lists : keyreplace(Key , 1 , S#state.stored , end; ordered_set -> Key = element(1, Object), case lists:keymember(Key, 1, S#state.stored) of false -> S#state{stored = S#state.stored ++ [Object]}; true -> S#state{stored=lists:keyreplace(Key, 1, S#state.stored, Object)} end; bag -> case lists:member(Object, S#state.stored) of false -> S#state{stored = S#state.stored ++ [Object]}; true -> S end; duplicate_bag -> S#state{stored = S#state.stored ++ [Object]} end; next_state(S, _V, {call,_,delete,[_Tab, Key]}) -> case S#state.type of ordered_set -> S#state{stored=lists:keydelete(Key, 1, S#state.stored)}; _ -> S#state{stored=proplists:delete(Key, S#state.stored)} end; next_state(S, _V, {call,_,_,_}) -> S. postcondition(_S, {call,_,new,[_Tab, _Opts]}, _Res) -> true; postcondition(S, {call,_,update_counter,[_Tab, Key, Incr]}, Res) -> Object = case S#state.type of set -> proplists:lookup(Key, S#state.stored); ordered_set -> lists:keyfind(Key, 1, S#state.stored) end, Value = element(2, Object), Res =:= Value + Incr; postcondition(_S, {call,_,delete,[_Tab, _Key]}, Res) -> Res =:= true; postcondition(_S, {call,_,insert,[_Tab, _Object]}, Res) -> Res =:= true; postcondition(S, {call,_,lookup_element,[_Tab, Key, Pos]}, Res) -> case S#state.type of ordered_set -> Res =:= element(Pos, lists:keyfind(Key, 1, S#state.stored)); set -> Res =:= element(Pos, proplists:lookup(Key, S#state.stored)); _ -> Res =:= [element(Pos, Tuple) || Tuple <- proplists:lookup_all(Key, S#state.stored)] end. prop_ets() -> ?FORALL(Type, noshrink(table_type()), ?FORALL(Cmds, commands(?MODULE, initial_state(Type)), begin {H,S,Res} = run_commands(?MODULE, Cmds), [ets:delete(Tab) || Tab <- S#state.tids], ?WHENFAIL( io:format("History: ~p\nState: ~p\nRes: ~p\n", [H,S,Res]), collect(Type, Res =:= ok)) end)). prop_parallel_ets() -> ?FORALL(Type, noshrink(table_type()), ?FORALL(Cmds, commands(?MODULE, initial_state(Type, parallel)), begin ets:new(tab, [named_table, public, Type]), {Seq,P,Res} = run_commands(?MODULE, Cmds), ets:delete(tab), ?WHENFAIL( io:format("Sequential: ~p\nParallel: ~p\nRes: ~p\n", [Seq,P,Res]), collect(Type, Res =:= ok)) end)). sample_commands() -> proper_gen:sample( ?LET(Type, oneof([set, ordered_set, bag, duplicate_bag]), commands(?MODULE, initial_state(Type)))). keyreplace(Key, Pos, List, NewTuple) -> keyreplace(Key, Pos, List, NewTuple, []). keyreplace(_Key, _Pos, [], _NewTuple, Acc) -> lists:reverse(Acc); keyreplace(Key, Pos, [Tuple|Rest], NewTuple, Acc) -> case element(Pos, Tuple) =:= Key of true -> lists:reverse(Acc) ++ [NewTuple|Rest]; false -> keyreplace(Key, Pos, Rest, NewTuple, [Tuple|Acc]) end.
657663bf7f71eedbc5679d33b157191154b17da35ec5095167763467331d54f8
Dasudian/DSDIN
wormhole_close_solo_tx.erl
-module(wormhole_close_solo_tx). -include("channel_txs.hrl"). -behavior(aetx). %% Behavior API -export([new/1, type/0, fee/1, ttl/1, nonce/1, origin/1, check/5, process/5, accounts/1, signers/2, serialization_template/1, serialize/1, deserialize/2, for_client/1 ]). %%%=================================================================== %%% Types %%%=================================================================== -define(CHANNEL_CLOSE_SOLO_TX_VSN, 1). -define(CHANNEL_CLOSE_SOLO_TX_TYPE, channel_close_solo_tx). -define(CHANNEL_CLOSE_SOLO_TX_FEE, 4). -opaque tx() :: #channel_close_solo_tx{}. -export_type([tx/0]). %%%=================================================================== %%% Behaviour API %%%=================================================================== -spec new(map()) -> {ok, aetx:tx()}. new(#{channel_id := ChannelId, from := FromPubKey, payload := Payload, ttl := TTL, fee := Fee, nonce := Nonce}) -> Tx = #channel_close_solo_tx{ channel_id = ChannelId, from = FromPubKey, payload = Payload, ttl = TTL, fee = Fee, nonce = Nonce}, {ok, aetx:new(?MODULE, Tx)}. type() -> ?CHANNEL_CLOSE_SOLO_TX_TYPE. -spec fee(tx()) -> non_neg_integer(). fee(#channel_close_solo_tx{fee = Fee}) -> Fee. -spec ttl(tx()) -> aec_blocks:height(). ttl(#channel_close_solo_tx{ttl = TTL}) -> TTL. -spec nonce(tx()) -> non_neg_integer(). nonce(#channel_close_solo_tx{nonce = Nonce}) -> Nonce. -spec origin(tx()) -> aec_keys:pubkey(). origin(#channel_close_solo_tx{from = FromPubKey}) -> FromPubKey. -spec check(tx(), aetx:tx_context(), aec_trees:trees(), aec_blocks:height(), non_neg_integer()) -> {ok, aec_trees:trees()} | {error, term()}. check(#channel_close_solo_tx{channel_id = ChannelId, from = FromPubKey, payload = Payload, fee = Fee, nonce = Nonce}, _Context, Trees, _Height, _ConsensusVersion) -> Checks = [fun() -> aetx_utils:check_account(FromPubKey, Trees, Nonce, Fee) end, fun() -> check_payload(ChannelId, FromPubKey, Payload, Trees) end], case aeu_validation:run(Checks) of ok -> {ok, Trees}; {error, _Reason} = Error -> Error end. -spec process(tx(), aetx:tx_context(), aec_trees:trees(), aec_blocks:height(), non_neg_integer()) -> {ok, aec_trees:trees()}. process(#channel_close_solo_tx{channel_id = ChannelId, from = FromPubKey, payload = Payload, fee = Fee, nonce = Nonce}, _Context, Trees, Height, _ConsensusVersion) -> AccountsTree0 = aec_trees:accounts(Trees), ChannelsTree0 = aec_trees:channels(Trees), FromAccount0 = aec_accounts_trees:get(FromPubKey, AccountsTree0), {ok, FromAccount1} = aec_accounts:spend(FromAccount0, Fee, Nonce), AccountsTree1 = aec_accounts_trees:enter(FromAccount1, AccountsTree0), {ok, _SignedTx, StateTx} = deserialize_from_binary(Payload), Channel0 = wormhole_state_tree:get(ChannelId, ChannelsTree0), Channel1 = wormhole_channels:close_solo(Channel0, StateTx, Height), ChannelsTree1 = wormhole_state_tree:enter(Channel1, ChannelsTree0), Trees1 = aec_trees:set_accounts(Trees, AccountsTree1), Trees2 = aec_trees:set_channels(Trees1, ChannelsTree1), {ok, Trees2}. -spec accounts(tx()) -> list(aec_keys:pubkey()). accounts(#channel_close_solo_tx{payload = Payload}) -> case deserialize_from_binary(Payload) of {ok, SignedState, _StateTx} -> {ok, Accounts} = aetx:signers(aetx_sign:tx(SignedState), aec_trees:new()), Accounts; {error, _Reason} -> [] end. -spec signers(tx(), aec_trees:trees()) -> {ok, list(aec_keys:pubkey())}. signers(#channel_close_solo_tx{from = FromPubKey}, _) -> {ok, [FromPubKey]}. -spec serialize(tx()) -> {vsn(), list()}. serialize(#channel_close_solo_tx{channel_id = ChannelId, from = FromPubKey, payload = Payload, ttl = TTL, fee = Fee, nonce = Nonce}) -> {version(), [ {channel_id, ChannelId} , {from , FromPubKey} , {payload , Payload} , {ttl , TTL} , {fee , Fee} , {nonce , Nonce} ]}. -spec deserialize(vsn(), list()) -> tx(). deserialize(?CHANNEL_CLOSE_SOLO_TX_VSN, [ {channel_id, ChannelId} , {from , FromPubKey} , {payload , Payload} , {ttl , TTL} , {fee , Fee} , {nonce , Nonce}]) -> #channel_close_solo_tx{channel_id = ChannelId, from = FromPubKey, payload = Payload, ttl = TTL, fee = Fee, nonce = Nonce}. -spec for_client(tx()) -> map(). for_client(#channel_close_solo_tx{channel_id = ChannelId, from = FromPubKey, payload = Payload, ttl = TTL, fee = Fee, nonce = Nonce}) -> #{<<"data_schema">>=> <<"ChannelCloseSoloTxJSON">>, % swagger schema name <<"vsn">> => version(), <<"channel_id">> => aec_base58c:encode(channel, ChannelId), <<"from">> => aec_base58c:encode(account_pubkey, FromPubKey), <<"payload">> => Payload, <<"ttl">> => TTL, <<"fee">> => Fee, <<"nonce">> => Nonce}. serialization_template(?CHANNEL_CLOSE_SOLO_TX_VSN) -> [ {channel_id, binary} , {from , binary} , {payload , binary} , {ttl , int} , {fee , int} , {nonce , int} ]. %%%=================================================================== Internal functions %%%=================================================================== -spec check_payload(wormhole_channels:id(), aec_keys:pubkey(), binary(), aec_trees:trees()) -> ok | {error, term()}. check_payload(ChannelId, FromPubKey, Payload, Trees) -> case deserialize_from_binary(Payload) of {ok, SignedState, StateTx} -> Checks = [fun() -> is_peer(FromPubKey, SignedState, Trees) end, fun() -> aetx_sign:verify(SignedState, Trees) end, fun() -> check_channel(ChannelId, StateTx, Trees) end], aeu_validation:run(Checks); {error, _Reason} = Error -> Error end. deserialize_from_binary(Payload) -> try SignedTx = aetx_sign:deserialize_from_binary(Payload), Tx = aetx_sign:tx(SignedTx), case aetx:specialize_type(Tx) of {channel_offchain_tx, StateTx} -> {ok, SignedTx, StateTx}; {_Type, _TxBody} -> {error, bad_offchain_state_type} end catch _:_ -> {error, payload_deserialization_failed} end. is_peer(FromPubKey, SignedState, Trees) -> Tx = aetx_sign:tx(SignedState), case aetx:signers(Tx, Trees) of {ok, Signers} -> case lists:member(FromPubKey, Signers) of true -> ok; false -> {error, account_not_peer} end; {error, _Reason}=Err -> Err end. check_channel(ChannelId, StateTx, Trees) -> case ChannelId =:= wormhole_offchain_tx:channel_id(StateTx) of true -> wormhole_utils:check_active_channel_exists( ChannelId, StateTx, Trees); false -> {error, bad_state_channel_id} end. -spec version() -> non_neg_integer(). version() -> ?CHANNEL_CLOSE_SOLO_TX_VSN.
null
https://raw.githubusercontent.com/Dasudian/DSDIN/b27a437d8deecae68613604fffcbb9804a6f1729/apps/wormhole/src/wormhole_close_solo_tx.erl
erlang
Behavior API =================================================================== Types =================================================================== =================================================================== Behaviour API =================================================================== swagger schema name =================================================================== ===================================================================
-module(wormhole_close_solo_tx). -include("channel_txs.hrl"). -behavior(aetx). -export([new/1, type/0, fee/1, ttl/1, nonce/1, origin/1, check/5, process/5, accounts/1, signers/2, serialization_template/1, serialize/1, deserialize/2, for_client/1 ]). -define(CHANNEL_CLOSE_SOLO_TX_VSN, 1). -define(CHANNEL_CLOSE_SOLO_TX_TYPE, channel_close_solo_tx). -define(CHANNEL_CLOSE_SOLO_TX_FEE, 4). -opaque tx() :: #channel_close_solo_tx{}. -export_type([tx/0]). -spec new(map()) -> {ok, aetx:tx()}. new(#{channel_id := ChannelId, from := FromPubKey, payload := Payload, ttl := TTL, fee := Fee, nonce := Nonce}) -> Tx = #channel_close_solo_tx{ channel_id = ChannelId, from = FromPubKey, payload = Payload, ttl = TTL, fee = Fee, nonce = Nonce}, {ok, aetx:new(?MODULE, Tx)}. type() -> ?CHANNEL_CLOSE_SOLO_TX_TYPE. -spec fee(tx()) -> non_neg_integer(). fee(#channel_close_solo_tx{fee = Fee}) -> Fee. -spec ttl(tx()) -> aec_blocks:height(). ttl(#channel_close_solo_tx{ttl = TTL}) -> TTL. -spec nonce(tx()) -> non_neg_integer(). nonce(#channel_close_solo_tx{nonce = Nonce}) -> Nonce. -spec origin(tx()) -> aec_keys:pubkey(). origin(#channel_close_solo_tx{from = FromPubKey}) -> FromPubKey. -spec check(tx(), aetx:tx_context(), aec_trees:trees(), aec_blocks:height(), non_neg_integer()) -> {ok, aec_trees:trees()} | {error, term()}. check(#channel_close_solo_tx{channel_id = ChannelId, from = FromPubKey, payload = Payload, fee = Fee, nonce = Nonce}, _Context, Trees, _Height, _ConsensusVersion) -> Checks = [fun() -> aetx_utils:check_account(FromPubKey, Trees, Nonce, Fee) end, fun() -> check_payload(ChannelId, FromPubKey, Payload, Trees) end], case aeu_validation:run(Checks) of ok -> {ok, Trees}; {error, _Reason} = Error -> Error end. -spec process(tx(), aetx:tx_context(), aec_trees:trees(), aec_blocks:height(), non_neg_integer()) -> {ok, aec_trees:trees()}. process(#channel_close_solo_tx{channel_id = ChannelId, from = FromPubKey, payload = Payload, fee = Fee, nonce = Nonce}, _Context, Trees, Height, _ConsensusVersion) -> AccountsTree0 = aec_trees:accounts(Trees), ChannelsTree0 = aec_trees:channels(Trees), FromAccount0 = aec_accounts_trees:get(FromPubKey, AccountsTree0), {ok, FromAccount1} = aec_accounts:spend(FromAccount0, Fee, Nonce), AccountsTree1 = aec_accounts_trees:enter(FromAccount1, AccountsTree0), {ok, _SignedTx, StateTx} = deserialize_from_binary(Payload), Channel0 = wormhole_state_tree:get(ChannelId, ChannelsTree0), Channel1 = wormhole_channels:close_solo(Channel0, StateTx, Height), ChannelsTree1 = wormhole_state_tree:enter(Channel1, ChannelsTree0), Trees1 = aec_trees:set_accounts(Trees, AccountsTree1), Trees2 = aec_trees:set_channels(Trees1, ChannelsTree1), {ok, Trees2}. -spec accounts(tx()) -> list(aec_keys:pubkey()). accounts(#channel_close_solo_tx{payload = Payload}) -> case deserialize_from_binary(Payload) of {ok, SignedState, _StateTx} -> {ok, Accounts} = aetx:signers(aetx_sign:tx(SignedState), aec_trees:new()), Accounts; {error, _Reason} -> [] end. -spec signers(tx(), aec_trees:trees()) -> {ok, list(aec_keys:pubkey())}. signers(#channel_close_solo_tx{from = FromPubKey}, _) -> {ok, [FromPubKey]}. -spec serialize(tx()) -> {vsn(), list()}. serialize(#channel_close_solo_tx{channel_id = ChannelId, from = FromPubKey, payload = Payload, ttl = TTL, fee = Fee, nonce = Nonce}) -> {version(), [ {channel_id, ChannelId} , {from , FromPubKey} , {payload , Payload} , {ttl , TTL} , {fee , Fee} , {nonce , Nonce} ]}. -spec deserialize(vsn(), list()) -> tx(). deserialize(?CHANNEL_CLOSE_SOLO_TX_VSN, [ {channel_id, ChannelId} , {from , FromPubKey} , {payload , Payload} , {ttl , TTL} , {fee , Fee} , {nonce , Nonce}]) -> #channel_close_solo_tx{channel_id = ChannelId, from = FromPubKey, payload = Payload, ttl = TTL, fee = Fee, nonce = Nonce}. -spec for_client(tx()) -> map(). for_client(#channel_close_solo_tx{channel_id = ChannelId, from = FromPubKey, payload = Payload, ttl = TTL, fee = Fee, nonce = Nonce}) -> <<"vsn">> => version(), <<"channel_id">> => aec_base58c:encode(channel, ChannelId), <<"from">> => aec_base58c:encode(account_pubkey, FromPubKey), <<"payload">> => Payload, <<"ttl">> => TTL, <<"fee">> => Fee, <<"nonce">> => Nonce}. serialization_template(?CHANNEL_CLOSE_SOLO_TX_VSN) -> [ {channel_id, binary} , {from , binary} , {payload , binary} , {ttl , int} , {fee , int} , {nonce , int} ]. Internal functions -spec check_payload(wormhole_channels:id(), aec_keys:pubkey(), binary(), aec_trees:trees()) -> ok | {error, term()}. check_payload(ChannelId, FromPubKey, Payload, Trees) -> case deserialize_from_binary(Payload) of {ok, SignedState, StateTx} -> Checks = [fun() -> is_peer(FromPubKey, SignedState, Trees) end, fun() -> aetx_sign:verify(SignedState, Trees) end, fun() -> check_channel(ChannelId, StateTx, Trees) end], aeu_validation:run(Checks); {error, _Reason} = Error -> Error end. deserialize_from_binary(Payload) -> try SignedTx = aetx_sign:deserialize_from_binary(Payload), Tx = aetx_sign:tx(SignedTx), case aetx:specialize_type(Tx) of {channel_offchain_tx, StateTx} -> {ok, SignedTx, StateTx}; {_Type, _TxBody} -> {error, bad_offchain_state_type} end catch _:_ -> {error, payload_deserialization_failed} end. is_peer(FromPubKey, SignedState, Trees) -> Tx = aetx_sign:tx(SignedState), case aetx:signers(Tx, Trees) of {ok, Signers} -> case lists:member(FromPubKey, Signers) of true -> ok; false -> {error, account_not_peer} end; {error, _Reason}=Err -> Err end. check_channel(ChannelId, StateTx, Trees) -> case ChannelId =:= wormhole_offchain_tx:channel_id(StateTx) of true -> wormhole_utils:check_active_channel_exists( ChannelId, StateTx, Trees); false -> {error, bad_state_channel_id} end. -spec version() -> non_neg_integer(). version() -> ?CHANNEL_CLOSE_SOLO_TX_VSN.
d89a11ce9f966e1cce8eb490e75bd9ba94aa41257ec64e358e27a14984b7e395
jiangpengnju/htdp2e
ex188.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex188) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) ; Design a program that sorts lists of game players by score: (define-struct gp [name score]) A GamePlayer is a structure : ; (make-gp String Number) interpretation : ( make - gp p s ) represents player who scored a maximum of s points A Logp ( List of Game Players ) is one of : ; - '() - ( cons ) interpretation : an instance of Logp represents a list of game players (define gp1 (make-gp "A" 30)) (define gp2 (make-gp "B" 20)) (define gp3 (make-gp "C" 10)) (define l1 '()) (define l2 (list gp1 gp2)) (define l3 (list gp2 gp1)) (define l4 (list gp2 gp3 gp1)) (define l5 (list gp1 gp2 gp3)) Logp - > Logp ; sorts list of game players by score, descendingly. (check-expect (sort-by-score> l1) '()) (check-expect (sort-by-score> l3) l2) (check-expect (sort-by-score> l4) l5) (define (sort-by-score> alogp) (cond [(empty? alogp) '()] [else (insert (first alogp) (sort-by-score> (rest alogp)))])) > Logp ; insert gp into the score descendingly ordered list of game players l (check-expect (insert gp1 '()) (list gp1)) (check-expect (insert gp1 (list gp2 gp3)) (list gp1 gp2 gp3)) (check-expect (insert gp2 (list gp1 gp3)) (list gp1 gp2 gp3)) (define (insert gp l) (cond [(empty? l) (list gp)] [else (if (>= (gp-score gp) (gp-score (first l))) (cons gp l) (cons (first l) (insert gp (rest l))))]))
null
https://raw.githubusercontent.com/jiangpengnju/htdp2e/d41555519fbb378330f75c88141f72b00a9ab1d3/arbitrarily-large-data/composing-functions/ex188.rkt
racket
about the language level of this file in a form that our tools can easily process. Design a program that sorts lists of game players by score: (make-gp String Number) - '() sorts list of game players by score, descendingly. insert gp into the score descendingly ordered list of game players l
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex188) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (define-struct gp [name score]) A GamePlayer is a structure : interpretation : ( make - gp p s ) represents player who scored a maximum of s points A Logp ( List of Game Players ) is one of : - ( cons ) interpretation : an instance of Logp represents a list of game players (define gp1 (make-gp "A" 30)) (define gp2 (make-gp "B" 20)) (define gp3 (make-gp "C" 10)) (define l1 '()) (define l2 (list gp1 gp2)) (define l3 (list gp2 gp1)) (define l4 (list gp2 gp3 gp1)) (define l5 (list gp1 gp2 gp3)) Logp - > Logp (check-expect (sort-by-score> l1) '()) (check-expect (sort-by-score> l3) l2) (check-expect (sort-by-score> l4) l5) (define (sort-by-score> alogp) (cond [(empty? alogp) '()] [else (insert (first alogp) (sort-by-score> (rest alogp)))])) > Logp (check-expect (insert gp1 '()) (list gp1)) (check-expect (insert gp1 (list gp2 gp3)) (list gp1 gp2 gp3)) (check-expect (insert gp2 (list gp1 gp3)) (list gp1 gp2 gp3)) (define (insert gp l) (cond [(empty? l) (list gp)] [else (if (>= (gp-score gp) (gp-score (first l))) (cons gp l) (cons (first l) (insert gp (rest l))))]))
880ff15fe503ade9ed36f59ce2977dcab3c7ee35169eca580e8ce80ca904e151
ktakashi/sagittarius-scheme
queue.scm
-*- mode : scheme ; coding : utf-8 -*- ;;; ;;; queue.scm - Queue utilities ;;; Copyright ( c ) 2010 - 2014 < > ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; API names are taken from Gauche and slib (library (util queue) (export <queue> <mtqueue> make-queue make-mtqueue queue? mtqueue? queue-length mtqueue-max-length mtqueue-room queue-empty? copy-queue queue-push! queue-push-unique! enqueue! enqueue-unique! queue-pop! dequeue! dequeue-all! queue-front queue-rear queue->list list->queue find-in-queue remove-from-queue! any-in-queue every-in-queue filter-in-queue MT queue enqueue/wait! queue-push/wait! dequeue/wait! queue-pop/wait!) (import (rnrs) (clos user) (clos core) (util deque) (sagittarius object) (sagittarius control)) (define-class <queue> (<sequence>) ((deque :init-keyword :deque))) (define (queue? o) (is-a? o <queue>)) ;; only for marking (define-class <mtqueue> (<queue>) ()) (define (mtqueue? o) (is-a? o <mtqueue>)) (define (make-queue) (make <queue> :deque (make-deque))) (define (make-mtqueue :key (max-length -1)) (make <mtqueue> :deque (make-mtdeque :max-length max-length))) (define (queue-length q) (deque-length (~ q 'deque))) (define (mtqueue-max-length q) (mtdeque-max-length (~ q 'deque))) (define (mtqueue-room q) (mtdeque-room (~ q 'deque))) (define (queue-empty? q) (deque-empty? (~ q 'deque))) (define (queue->list q) (deque->list (~ q 'deque))) (define (list->queue lst :optional (class <queue>) :rest initargs) (rlet1 q (make class) (set! (~ q 'deque) (apply list->deque lst ;; a bit tricky... (if (subtype? class <mtqueue>) <mtdeque> <deque>) initargs)))) (define-generic copy-queue) (define-method copy-queue ((q <queue>)) (list->queue (deque->list (~ q 'deque)) (class-of q))) (define-method copy-queue ((q <mtqueue>)) (list->queue (deque->list (~ q 'deque)) (class-of q) :max-length (mtqueue-max-length q))) (define queue-front (case-lambda ((q) (deque-front (~ q 'deque))) ((q default) (deque-front (~ q 'deque) default)))) (define queue-rear (case-lambda ((q) (deque-rear (~ q 'deque))) ((q default) (deque-rear (~ q 'deque) default)))) (define (find-in-queue pred q) (find-in-deque pred (~ q 'deque))) (define (any-in-queue pred q) (any-in-deque pred (~ q 'deque))) (define (every-in-queue pred q) (every-in-deque pred (~ q 'deque))) (define (enqueue! q obj . more) (apply deque-push! (~ q 'deque) obj more) q) (define (enqueue-unique! q cmp obj . more) (apply deque-push-unique! (~ q 'deque) cmp obj more) q) (define (enqueue/wait! q obj . opts) (apply deque-push/wait! (~ q 'deque) obj opts)) (define (queue-push! q obj . more) (apply deque-unshift! (~ q 'deque) obj more) q) (define (queue-push-unique! q cmp obj . more) (apply deque-unshift-unique! (~ q 'deque) cmp obj more) q) (define (queue-push/wait! q obj . opts) (apply deque-unshift/wait! (~ q 'deque) obj opts)) (define (dequeue! q . opts) (apply deque-shift! (~ q 'deque) opts)) (define (dequeue-all! q) (deque-shift-all! (~ q 'deque))) (define (dequeue/wait! q . opts) (apply deque-shift/wait! (~ q 'deque) opts)) (define queue-pop! dequeue!) (define queue-pop/wait! dequeue/wait!) (define (remove-from-queue! pred q) (remove-from-deque! pred (~ q 'deque))) (define (filter-in-queue pred q) (filter-in-deque pred (~ q 'deque))) )
null
https://raw.githubusercontent.com/ktakashi/sagittarius-scheme/0c8a04f60adefd7ed6ba089704fb4c4581e26e28/sitelib/util/queue.scm
scheme
coding : utf-8 -*- queue.scm - Queue utilities Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. only for marking a bit tricky...
Copyright ( c ) 2010 - 2014 < > " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING API names are taken from Gauche and slib (library (util queue) (export <queue> <mtqueue> make-queue make-mtqueue queue? mtqueue? queue-length mtqueue-max-length mtqueue-room queue-empty? copy-queue queue-push! queue-push-unique! enqueue! enqueue-unique! queue-pop! dequeue! dequeue-all! queue-front queue-rear queue->list list->queue find-in-queue remove-from-queue! any-in-queue every-in-queue filter-in-queue MT queue enqueue/wait! queue-push/wait! dequeue/wait! queue-pop/wait!) (import (rnrs) (clos user) (clos core) (util deque) (sagittarius object) (sagittarius control)) (define-class <queue> (<sequence>) ((deque :init-keyword :deque))) (define (queue? o) (is-a? o <queue>)) (define-class <mtqueue> (<queue>) ()) (define (mtqueue? o) (is-a? o <mtqueue>)) (define (make-queue) (make <queue> :deque (make-deque))) (define (make-mtqueue :key (max-length -1)) (make <mtqueue> :deque (make-mtdeque :max-length max-length))) (define (queue-length q) (deque-length (~ q 'deque))) (define (mtqueue-max-length q) (mtdeque-max-length (~ q 'deque))) (define (mtqueue-room q) (mtdeque-room (~ q 'deque))) (define (queue-empty? q) (deque-empty? (~ q 'deque))) (define (queue->list q) (deque->list (~ q 'deque))) (define (list->queue lst :optional (class <queue>) :rest initargs) (rlet1 q (make class) (set! (~ q 'deque) (apply list->deque lst (if (subtype? class <mtqueue>) <mtdeque> <deque>) initargs)))) (define-generic copy-queue) (define-method copy-queue ((q <queue>)) (list->queue (deque->list (~ q 'deque)) (class-of q))) (define-method copy-queue ((q <mtqueue>)) (list->queue (deque->list (~ q 'deque)) (class-of q) :max-length (mtqueue-max-length q))) (define queue-front (case-lambda ((q) (deque-front (~ q 'deque))) ((q default) (deque-front (~ q 'deque) default)))) (define queue-rear (case-lambda ((q) (deque-rear (~ q 'deque))) ((q default) (deque-rear (~ q 'deque) default)))) (define (find-in-queue pred q) (find-in-deque pred (~ q 'deque))) (define (any-in-queue pred q) (any-in-deque pred (~ q 'deque))) (define (every-in-queue pred q) (every-in-deque pred (~ q 'deque))) (define (enqueue! q obj . more) (apply deque-push! (~ q 'deque) obj more) q) (define (enqueue-unique! q cmp obj . more) (apply deque-push-unique! (~ q 'deque) cmp obj more) q) (define (enqueue/wait! q obj . opts) (apply deque-push/wait! (~ q 'deque) obj opts)) (define (queue-push! q obj . more) (apply deque-unshift! (~ q 'deque) obj more) q) (define (queue-push-unique! q cmp obj . more) (apply deque-unshift-unique! (~ q 'deque) cmp obj more) q) (define (queue-push/wait! q obj . opts) (apply deque-unshift/wait! (~ q 'deque) obj opts)) (define (dequeue! q . opts) (apply deque-shift! (~ q 'deque) opts)) (define (dequeue-all! q) (deque-shift-all! (~ q 'deque))) (define (dequeue/wait! q . opts) (apply deque-shift/wait! (~ q 'deque) opts)) (define queue-pop! dequeue!) (define queue-pop/wait! dequeue/wait!) (define (remove-from-queue! pred q) (remove-from-deque! pred (~ q 'deque))) (define (filter-in-queue pred q) (filter-in-deque pred (~ q 'deque))) )
ef236e2e7c62912af52d21937c516fd4ea12142198b97749c48990a64609cd22
gdamore/tree-sitter-d
with.scm
================================================================================ With statement ================================================================================ unittest { with (x) x++; } -------------------------------------------------------------------------------- (source_file (unittest_declaration (unittest) (block_statement (with_statement (with) (expression (identifier)) (scope_statement (expression_statement (expression_list (postfix_expression (identifier))))))))) ================================================================================ With statment declaration ================================================================================ unittest { with (x) int y = 0; } -------------------------------------------------------------------------------- (source_file (unittest_declaration (unittest) (block_statement (with_statement (with) (expression (identifier)) (scope_statement (variable_declaration (type (int)) (declarator (identifier) (int_literal))))))))
null
https://raw.githubusercontent.com/gdamore/tree-sitter-d/601c4a1e8310fb2f3c43fa8a923d0d27497f3c04/test/corpus/with.scm
scheme
} }
================================================================================ With statement ================================================================================ -------------------------------------------------------------------------------- (source_file (unittest_declaration (unittest) (block_statement (with_statement (with) (expression (identifier)) (scope_statement (expression_statement (expression_list (postfix_expression (identifier))))))))) ================================================================================ With statment declaration ================================================================================ -------------------------------------------------------------------------------- (source_file (unittest_declaration (unittest) (block_statement (with_statement (with) (expression (identifier)) (scope_statement (variable_declaration (type (int)) (declarator (identifier) (int_literal))))))))
a7ceacfb003f1b60d2164d5c978f7cbe2e0b006c7060793fefc40151a67929d6
kupl/LearnML
patch.ml
exception Error of string type lambda = V of string | P of (string * lambda) | C of (lambda * lambda) let rec __s3 (__s4 : lambda) : string list = match __s4 with | V __s5 -> [ __s5 ] | P (__s6, __s7) -> List.filter (fun (__s8 : string) -> not (__s6 = __s8)) (__s3 __s7) | C (__s9, __s10) -> __s3 __s9 @ __s3 __s10 let rec check (met : lambda) : bool = let rec check2 (a : string) (me : lambda) : bool = match me with | V x -> if x = a then true else false | P (q, V b) -> if a = b then true else false | P (x, C (t, p)) -> ( match (t, p) with | V e, V f -> check2 x t || check2 x p | _ -> check2 x t && check2 x p ) | P (x, P (e, f)) -> check2 x (P (e, f)) && check2 e f | C (x, y) -> ( match (x, y) with | V e, V f -> check2 a x || check2 a y | _ -> check2 a x && check2 a x ) in List.length (__s3 met) = 0
null
https://raw.githubusercontent.com/kupl/LearnML/c98ef2b95ef67e657b8158a2c504330e9cfb7700/result/cafe2/lambda/sub6/patch.ml
ocaml
exception Error of string type lambda = V of string | P of (string * lambda) | C of (lambda * lambda) let rec __s3 (__s4 : lambda) : string list = match __s4 with | V __s5 -> [ __s5 ] | P (__s6, __s7) -> List.filter (fun (__s8 : string) -> not (__s6 = __s8)) (__s3 __s7) | C (__s9, __s10) -> __s3 __s9 @ __s3 __s10 let rec check (met : lambda) : bool = let rec check2 (a : string) (me : lambda) : bool = match me with | V x -> if x = a then true else false | P (q, V b) -> if a = b then true else false | P (x, C (t, p)) -> ( match (t, p) with | V e, V f -> check2 x t || check2 x p | _ -> check2 x t && check2 x p ) | P (x, P (e, f)) -> check2 x (P (e, f)) && check2 e f | C (x, y) -> ( match (x, y) with | V e, V f -> check2 a x || check2 a y | _ -> check2 a x && check2 a x ) in List.length (__s3 met) = 0
1c11151535a5069cc82a3c3ad0b5914a313c26dc808d5c4b08d09118e0e86c99
kelamg/HtDP2e-workthrough
ex416.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex416) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (define base #i10.0) ;; Number -> N ;; find the integer such that b underflows (check-expect (= (expt base (add1 (underflow-n base))) #i0.0) #false) (check-expect (= (expt base (underflow-n base)) #i0.0) #true) (define (underflow-n b) (flow-n b sub1 #i0.0)) ;; Number -> N ;; find the integer such that b overflows (check-expect (= (expt base (sub1 (overflow-n base))) +inf.0) #false) (check-expect (= (expt base (overflow-n base)) +inf.0) #true) (define (overflow-n b) (flow-n b add1 +inf.0)) ;; Number [N -> N] Number -> N (define (flow-n b fn appr) (local (; N -> N (define (find-flow n) (if (= (expt b n) appr) n (find-flow (fn n))))) (find-flow 0)))
null
https://raw.githubusercontent.com/kelamg/HtDP2e-workthrough/ec05818d8b667a3c119bea8d1d22e31e72e0a958/HtDP/Intertwined-Data/ex416.rkt
racket
about the language level of this file in a form that our tools can easily process. Number -> N find the integer such that b underflows Number -> N find the integer such that b overflows Number [N -> N] Number -> N N -> N
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex416) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (define base #i10.0) (check-expect (= (expt base (add1 (underflow-n base))) #i0.0) #false) (check-expect (= (expt base (underflow-n base)) #i0.0) #true) (define (underflow-n b) (flow-n b sub1 #i0.0)) (check-expect (= (expt base (sub1 (overflow-n base))) +inf.0) #false) (check-expect (= (expt base (overflow-n base)) +inf.0) #true) (define (overflow-n b) (flow-n b add1 +inf.0)) (define (flow-n b fn appr) (local (define (find-flow n) (if (= (expt b n) appr) n (find-flow (fn n))))) (find-flow 0)))
264f7b2e87f382e623923fa04ebc2347a1bda79452dc962047e1cd3a61039f42
ldmberman/HoneyBadgerBFT
RBCTest.hs
# LANGUAGE ScopedTypeVariables # module RBCTest where import Control.Monad.Catch (MonadMask, try) import Control.Monad.State (runState) import Data.ByteString.Char8 (pack) import RBC (In (..), Out (..), RBCError (..), RBCState (..), markReadySent, receive, setup, storeEcho, storeMessage, storeReady) import Test.Tasty (testGroup) import Test.Tasty.HUnit (assertEqual, assertFailure, testCase) unitTests = testGroup "RBC unit tests" [ testCase "Reports unknown validator" $ testReportsUnknownValidator ,testCase "Rejects its own message" $ testRejectsItsOwnMessage ,testCase "Broadcasts the input message" $ testBroadcastsInput ,testCase "Echoes Val's" $ testEchoesVals ,testCase "Collects echoes" $ testCollectsEchoes ,testCase "Fails to parse improperly built proofs" testFailsToParseImproperlyBuiltProofs ,testCase "Ignores invalid proofs" $ testIgnoresInvalidProofs ,testCase "Collects messages from distinct validators" $ testCollectsMessagesFromDistinctValidators ,testCase "Stores echoes" $ testStoresEchoes ,testCase "Does not re-broadcast Ready" $ testDoesNotReBroadcastReady ,testCase "Broadcasts Ready after receiving matching Ready" $ testBroadcastsReadyAfterReceivingMatchingReady ,testCase "Does not broadcast mismatching Ready" $ testDoesNotBroadcastMismatchingReady ,testCase "Outputs the message after the sufficient number of inputs" $ testOutputsAfterSufficientInput ] dummyProof = ((pack "proof", pack "root", pack "leaf"), 1) validRoot = pack "71d7596632e783faf2d375e8ad952db1c73a94eae342df189b15b747a0915816" A proof for the part " A mes " of the message " A message " in the ( 2 , 2 ) scheme . validProof = ((pack "\NUL\NUL\NUL\NUL\NUL\NUL\NUL\STX\NUL\NUL\NUL\NUL\NUL\NUL\NUL@6eeb07289f281c2ff6fd02578c4398ca7fbaf610e27f18f248991280a12af55d\NUL\NUL\NUL\NUL\NUL\NUL\NUL@b9c383ba4dd754a6cf9443a9b85cbd801c93b402378ee46f304ea3a740de3f75\NUL\NUL\NUL\NUL\NUL\NUL\NUL\NUL@7176d01dbadd052dac9865602ca2279ac3f11cc83341b1a0c1fbd00fc54dfd96\NUL\NUL\NUL\NUL\NUL\NUL\NUL@5b304a7122376d5aac29130957632c814242250fb6e99042b89b9e8243bf1e26\NUL", validRoot, pack "A mes"), 9) Same message , second data part . secondValidProof = ((pack "\NUL\NUL\NUL\NUL\NUL\NUL\NUL\STX\NUL\NUL\NUL\NUL\NUL\NUL\NUL@b9c383ba4dd754a6cf9443a9b85cbd801c93b402378ee46f304ea3a740de3f75\NUL\NUL\NUL\NUL\NUL\NUL\NUL@6eeb07289f281c2ff6fd02578c4398ca7fbaf610e27f18f248991280a12af55d\SOH\NUL\NUL\NUL\NUL\NUL\NUL\NUL@7176d01dbadd052dac9865602ca2279ac3f11cc83341b1a0c1fbd00fc54dfd96\NUL\NUL\NUL\NUL\NUL\NUL\NUL@5b304a7122376d5aac29130957632c814242250fb6e99042b89b9e8243bf1e26\NUL", validRoot, pack "sage\NUL"), 9) Same message , first parity part . thirdValidProof = ((pack "\NUL\NUL\NUL\NUL\NUL\NUL\NUL\STX\NUL\NUL\NUL\NUL\NUL\NUL\NUL@f22b572c5f0fceb4baa513d03d9875aba0d257bb937b625b215409990457028c\NUL\NUL\NUL\NUL\NUL\NUL\NUL@aeb6f7984270bc4ddd4e51c9759740c24c6d0a64f5c1c5055117f1b105658db4\NUL\NUL\NUL\NUL\NUL\NUL\NUL\NUL@5b304a7122376d5aac29130957632c814242250fb6e99042b89b9e8243bf1e26\NUL\NUL\NUL\NUL\NUL\NUL\NUL@7176d01dbadd052dac9865602ca2279ac3f11cc83341b1a0c1fbd00fc54dfd96\SOH", validRoot, pack "%\162ye\149"), 9) Same message , second parity part . fourthValidProof = ((pack "\NUL\NUL\NUL\NUL\NUL\NUL\NUL\STX\NUL\NUL\NUL\NUL\NUL\NUL\NUL@aeb6f7984270bc4ddd4e51c9759740c24c6d0a64f5c1c5055117f1b105658db4\NUL\NUL\NUL\NUL\NUL\NUL\NUL@f22b572c5f0fceb4baa513d03d9875aba0d257bb937b625b215409990457028c\SOH\NUL\NUL\NUL\NUL\NUL\NUL\NUL@5b304a7122376d5aac29130957632c814242250fb6e99042b89b9e8243bf1e26\NUL\NUL\NUL\NUL\NUL\NUL\NUL@7176d01dbadd052dac9865602ca2279ac3f11cc83341b1a0c1fbd00fc54dfd96\SOH", validRoot, pack "\ETB\227se\230"), 9) validProofs = [validProof, secondValidProof, thirdValidProof, fourthValidProof] invalidProof = let ((p, root, _), size) = validProof in ((p, root, pack "sage\NUL"), size) testReportsUnknownValidator = do let (out, _) = runState (receive (Input $ pack "A message") 5) (setup 4 0) shouldbeError <- try out case shouldbeError of Right o -> assertFailure $ "Did not report unknown validator, but returned: " ++ show o Left (UnknownValidator _) -> return () Left e -> assertFailure $ "Did not report unknown validator, but raised: " ++ show e testRejectsItsOwnMessage = do let (out, _) = runState (receive (Input $ pack "A message") 0) (setup 1 0) shouldbeError <- try out case shouldbeError of Right o -> assertFailure $ "Did not reject its own message, but returned: " ++ show o Left (OwnMessageError _) -> return () Left e -> assertFailure $ "Did not reject its own message, but raised: " ++ show e testBroadcastsInput = do mapM_ testBroadcastsInput' [(2, 0), (2, 1), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2)] testBroadcastsInput' (n, self) = do let (out, _) = runState (receive (Input $ pack "A message") (head [v | v <- [0..n-1], v /= self])) (setup n self) broadcast <- out case broadcast of Broadcast messages -> assertBroadcastsInput messages n self o -> assertFailure $ "Did not broadcast the expected message: " ++ show o assertBroadcastsInput messages n self = do assertEqual "Did not broadcast to all validators" [v | v <- [0..n-1], v /= self] (map (\(_, v) -> v) messages) mapM_ assertMessage messages where assertMessage (Val (_, size), _) = assertEqual "Did not broadcast the correct message size: " 9 size assertMessage msg = assertFailure $ "Broadcasted not `Val`: " ++ show msg testEchoesVals = do let (out, _) = runState (receive (Val dummyProof) 1) (setup 4 0) Broadcast messages <- out assertEqual "Did not broadcast correct messages to all validators" (map (\v -> (Echo dummyProof, v)) [1, 2, 3]) messages testCollectsEchoes = do let (out, _) = runState (receive (Echo secondValidProof) 1) (setup 4 0) result <- out case result of StoreEcho (proof, validator) -> assertEqual "The echo changed during processing" secondValidProof proof o -> assertFailure $ "Did not output the correct echo processing result: " ++ show o testCollectsMessagesFromDistinctValidators = do let initialState = (setup 4 0) { getEcho = [(1, secondValidProof)] } let (out, _) = runState (receive (Echo secondValidProof) 1) initialState result <- out case result of None -> return () o -> assertFailure $ "Did not ignore the repeated message but returned: " ++ show o testFailsToParseImproperlyBuiltProofs = do let (out, _) = runState (receive (Echo dummyProof) 1) (setup 4 0) maybeResult <- try out case maybeResult of Left (e :: RBCError) -> return () Right o -> assertFailure $ "Did not complain about the improperly coded proof but returned: " ++ show o testIgnoresInvalidProofs = do let (out, _) = runState (receive (Echo invalidProof) 1) (setup 4 0) result <- out case result of None -> return () o -> assertFailure $ "Did not ignore invalid proof but returned: " ++ show o testStoresEchoes = do let (out, stateAfterOneEcho) = runState (storeEcho secondValidProof 1) (setup 4 0) result <- out case result of None -> return () o -> assertFailure $ "Did not just store the echo but returned: " ++ show o let (out, stateAfterTwoEchoes) = runState (storeEcho thirdValidProof 2) stateAfterOneEcho result <- out case result of None -> return () o -> assertFailure $ "Did not just store the echo but returned: " ++ show o let (out, stateAfterThreeEchoes) = runState (storeEcho fourthValidProof 3) stateAfterTwoEchoes result <- out case result of StoreMessage (message, Broadcast messages) -> assertEqual "Did not broadcast the correct messages" [(Ready validRoot, v) | v <- [1, 2, 3]] messages >> assertEqual "Did not record the correct message" (pack "A message") message o -> assertFailure $ "Did not interpolate shards but returned: " ++ show o assertEqual "Did not store all echoes correctly" (zip [1, 2, 3] [secondValidProof, thirdValidProof, fourthValidProof]) (getEcho stateAfterThreeEchoes) buildStateWithTwoEchoes = do let (out, s) = runState (storeEcho secondValidProof 1) (setup 4 0) _ <- out let (out, state) = runState (storeEcho thirdValidProof 2) s _ <- out return state testDoesNotReBroadcastReady = do state <- buildStateWithTwoEchoes let (_, stateAfterReadySent) = runState markReadySent state let (maybeOut, _) = runState (storeEcho fourthValidProof 3) stateAfterReadySent out <- maybeOut case out of None -> return () _ -> assertFailure $ "Did not ignore yet another Ready but returned: " ++ show out testBroadcastsReadyAfterReceivingMatchingReady = do let (out, stateAfterOneReady) = runState (storeReady (pack "A root") 1) (setup 4 0) result <- out case result of None -> return () o -> assertFailure $ "Did not just store Ready but returned: " ++ show o let (out, stateAfterTwoReadies) = runState (storeReady (pack "A root") 2) stateAfterOneReady result <- out case result of Broadcast messages -> assertEqual "Did not broadcast the correct messages" (map (\v -> (Ready (pack "A root"), v)) [1, 2, 3]) messages o -> assertFailure $ "Did not broadcast messages but returned: " ++ show o let (_, afterReadySent) = runState markReadySent stateAfterTwoReadies let (out, _) = runState (storeReady (pack "A root") 3) afterReadySent result <- out case result of None -> return () o -> assertFailure $ "Did not ignore yet another Ready but returned: " ++ show o testDoesNotBroadcastMismatchingReady = do let root = pack "A root" let mismatchingRoot = pack "A mismatching root" let state = (setup 4 0) { getReady = [ (1, root) ,(2, root) ,(1, mismatchingRoot) ] } let (out, _) = runState (storeReady mismatchingRoot 2) state result <- out case result of None -> return () o -> assertFailure $ "Did not ignore mismatching Ready but returned: " ++ show o testOutputsAfterSufficientInput = do The output is expected after at least 2f + 1 Ready and at least N - 2f Echo . enough of Ready but not enough of Echo let state = (setup 4 0) { getEcho = [] ,getReady = [ (1, validRoot) ,(2, validRoot) ,(3, validRoot) ] ,getReadySent = True } let (out, _) = runState (storeEcho secondValidProof 1) state result <- out case result of None -> return () o -> assertFailure $ "Returned unexpected output: " ++ show o let (out, _) = runState (storeReady validRoot 1) state result <- out case result of None -> return () o -> assertFailure $ "Returned unexpected output: " ++ show o enough of Echo but not enough of Ready let state = (setup 4 0) { getEcho = [ (1, secondValidProof) ] ,getReady = [ (1, validRoot) ] ,getReadySent = True } let (out, _) = runState (storeEcho thirdValidProof 2) state result <- out case result of None -> return () o -> assertFailure $ "Returned unexpected output: " ++ show o let (out, _) = runState (storeReady validRoot 2) state result <- out case result of None -> return () o -> assertFailure $ "Returned unexpected output: " ++ show o enough of Echo and Ready let state = (setup 4 0) { getEcho = [ (1, secondValidProof) ,(2, thirdValidProof) ] ,getReady = [ (1, validRoot) ,(2, validRoot) ,(3, validRoot) ] ,getReadySent = True } let (_, withMessage) = runState (storeMessage $ pack "A message") state let (out, _) = runState (storeEcho fourthValidProof 3) withMessage result <- out case result of Output msg -> assertEqual "Did not output the correct message" (pack "A message") msg o -> assertFailure $ "Did not output the message after storing echo but returned: " ++ show o let (out, _) = runState (storeReady validRoot 2) withMessage result <- out case result of Output msg -> assertEqual "Did not output the correct message" (pack "A message") msg o -> assertFailure $ "Did not output the message after storing Ready but returned: " ++ show o
null
https://raw.githubusercontent.com/ldmberman/HoneyBadgerBFT/73e6ee870cfe513a4e826abbc249848634869967/test/RBCTest.hs
haskell
# LANGUAGE ScopedTypeVariables # module RBCTest where import Control.Monad.Catch (MonadMask, try) import Control.Monad.State (runState) import Data.ByteString.Char8 (pack) import RBC (In (..), Out (..), RBCError (..), RBCState (..), markReadySent, receive, setup, storeEcho, storeMessage, storeReady) import Test.Tasty (testGroup) import Test.Tasty.HUnit (assertEqual, assertFailure, testCase) unitTests = testGroup "RBC unit tests" [ testCase "Reports unknown validator" $ testReportsUnknownValidator ,testCase "Rejects its own message" $ testRejectsItsOwnMessage ,testCase "Broadcasts the input message" $ testBroadcastsInput ,testCase "Echoes Val's" $ testEchoesVals ,testCase "Collects echoes" $ testCollectsEchoes ,testCase "Fails to parse improperly built proofs" testFailsToParseImproperlyBuiltProofs ,testCase "Ignores invalid proofs" $ testIgnoresInvalidProofs ,testCase "Collects messages from distinct validators" $ testCollectsMessagesFromDistinctValidators ,testCase "Stores echoes" $ testStoresEchoes ,testCase "Does not re-broadcast Ready" $ testDoesNotReBroadcastReady ,testCase "Broadcasts Ready after receiving matching Ready" $ testBroadcastsReadyAfterReceivingMatchingReady ,testCase "Does not broadcast mismatching Ready" $ testDoesNotBroadcastMismatchingReady ,testCase "Outputs the message after the sufficient number of inputs" $ testOutputsAfterSufficientInput ] dummyProof = ((pack "proof", pack "root", pack "leaf"), 1) validRoot = pack "71d7596632e783faf2d375e8ad952db1c73a94eae342df189b15b747a0915816" A proof for the part " A mes " of the message " A message " in the ( 2 , 2 ) scheme . validProof = ((pack "\NUL\NUL\NUL\NUL\NUL\NUL\NUL\STX\NUL\NUL\NUL\NUL\NUL\NUL\NUL@6eeb07289f281c2ff6fd02578c4398ca7fbaf610e27f18f248991280a12af55d\NUL\NUL\NUL\NUL\NUL\NUL\NUL@b9c383ba4dd754a6cf9443a9b85cbd801c93b402378ee46f304ea3a740de3f75\NUL\NUL\NUL\NUL\NUL\NUL\NUL\NUL@7176d01dbadd052dac9865602ca2279ac3f11cc83341b1a0c1fbd00fc54dfd96\NUL\NUL\NUL\NUL\NUL\NUL\NUL@5b304a7122376d5aac29130957632c814242250fb6e99042b89b9e8243bf1e26\NUL", validRoot, pack "A mes"), 9) Same message , second data part . secondValidProof = ((pack "\NUL\NUL\NUL\NUL\NUL\NUL\NUL\STX\NUL\NUL\NUL\NUL\NUL\NUL\NUL@b9c383ba4dd754a6cf9443a9b85cbd801c93b402378ee46f304ea3a740de3f75\NUL\NUL\NUL\NUL\NUL\NUL\NUL@6eeb07289f281c2ff6fd02578c4398ca7fbaf610e27f18f248991280a12af55d\SOH\NUL\NUL\NUL\NUL\NUL\NUL\NUL@7176d01dbadd052dac9865602ca2279ac3f11cc83341b1a0c1fbd00fc54dfd96\NUL\NUL\NUL\NUL\NUL\NUL\NUL@5b304a7122376d5aac29130957632c814242250fb6e99042b89b9e8243bf1e26\NUL", validRoot, pack "sage\NUL"), 9) Same message , first parity part . thirdValidProof = ((pack "\NUL\NUL\NUL\NUL\NUL\NUL\NUL\STX\NUL\NUL\NUL\NUL\NUL\NUL\NUL@f22b572c5f0fceb4baa513d03d9875aba0d257bb937b625b215409990457028c\NUL\NUL\NUL\NUL\NUL\NUL\NUL@aeb6f7984270bc4ddd4e51c9759740c24c6d0a64f5c1c5055117f1b105658db4\NUL\NUL\NUL\NUL\NUL\NUL\NUL\NUL@5b304a7122376d5aac29130957632c814242250fb6e99042b89b9e8243bf1e26\NUL\NUL\NUL\NUL\NUL\NUL\NUL@7176d01dbadd052dac9865602ca2279ac3f11cc83341b1a0c1fbd00fc54dfd96\SOH", validRoot, pack "%\162ye\149"), 9) Same message , second parity part . fourthValidProof = ((pack "\NUL\NUL\NUL\NUL\NUL\NUL\NUL\STX\NUL\NUL\NUL\NUL\NUL\NUL\NUL@aeb6f7984270bc4ddd4e51c9759740c24c6d0a64f5c1c5055117f1b105658db4\NUL\NUL\NUL\NUL\NUL\NUL\NUL@f22b572c5f0fceb4baa513d03d9875aba0d257bb937b625b215409990457028c\SOH\NUL\NUL\NUL\NUL\NUL\NUL\NUL@5b304a7122376d5aac29130957632c814242250fb6e99042b89b9e8243bf1e26\NUL\NUL\NUL\NUL\NUL\NUL\NUL@7176d01dbadd052dac9865602ca2279ac3f11cc83341b1a0c1fbd00fc54dfd96\SOH", validRoot, pack "\ETB\227se\230"), 9) validProofs = [validProof, secondValidProof, thirdValidProof, fourthValidProof] invalidProof = let ((p, root, _), size) = validProof in ((p, root, pack "sage\NUL"), size) testReportsUnknownValidator = do let (out, _) = runState (receive (Input $ pack "A message") 5) (setup 4 0) shouldbeError <- try out case shouldbeError of Right o -> assertFailure $ "Did not report unknown validator, but returned: " ++ show o Left (UnknownValidator _) -> return () Left e -> assertFailure $ "Did not report unknown validator, but raised: " ++ show e testRejectsItsOwnMessage = do let (out, _) = runState (receive (Input $ pack "A message") 0) (setup 1 0) shouldbeError <- try out case shouldbeError of Right o -> assertFailure $ "Did not reject its own message, but returned: " ++ show o Left (OwnMessageError _) -> return () Left e -> assertFailure $ "Did not reject its own message, but raised: " ++ show e testBroadcastsInput = do mapM_ testBroadcastsInput' [(2, 0), (2, 1), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2)] testBroadcastsInput' (n, self) = do let (out, _) = runState (receive (Input $ pack "A message") (head [v | v <- [0..n-1], v /= self])) (setup n self) broadcast <- out case broadcast of Broadcast messages -> assertBroadcastsInput messages n self o -> assertFailure $ "Did not broadcast the expected message: " ++ show o assertBroadcastsInput messages n self = do assertEqual "Did not broadcast to all validators" [v | v <- [0..n-1], v /= self] (map (\(_, v) -> v) messages) mapM_ assertMessage messages where assertMessage (Val (_, size), _) = assertEqual "Did not broadcast the correct message size: " 9 size assertMessage msg = assertFailure $ "Broadcasted not `Val`: " ++ show msg testEchoesVals = do let (out, _) = runState (receive (Val dummyProof) 1) (setup 4 0) Broadcast messages <- out assertEqual "Did not broadcast correct messages to all validators" (map (\v -> (Echo dummyProof, v)) [1, 2, 3]) messages testCollectsEchoes = do let (out, _) = runState (receive (Echo secondValidProof) 1) (setup 4 0) result <- out case result of StoreEcho (proof, validator) -> assertEqual "The echo changed during processing" secondValidProof proof o -> assertFailure $ "Did not output the correct echo processing result: " ++ show o testCollectsMessagesFromDistinctValidators = do let initialState = (setup 4 0) { getEcho = [(1, secondValidProof)] } let (out, _) = runState (receive (Echo secondValidProof) 1) initialState result <- out case result of None -> return () o -> assertFailure $ "Did not ignore the repeated message but returned: " ++ show o testFailsToParseImproperlyBuiltProofs = do let (out, _) = runState (receive (Echo dummyProof) 1) (setup 4 0) maybeResult <- try out case maybeResult of Left (e :: RBCError) -> return () Right o -> assertFailure $ "Did not complain about the improperly coded proof but returned: " ++ show o testIgnoresInvalidProofs = do let (out, _) = runState (receive (Echo invalidProof) 1) (setup 4 0) result <- out case result of None -> return () o -> assertFailure $ "Did not ignore invalid proof but returned: " ++ show o testStoresEchoes = do let (out, stateAfterOneEcho) = runState (storeEcho secondValidProof 1) (setup 4 0) result <- out case result of None -> return () o -> assertFailure $ "Did not just store the echo but returned: " ++ show o let (out, stateAfterTwoEchoes) = runState (storeEcho thirdValidProof 2) stateAfterOneEcho result <- out case result of None -> return () o -> assertFailure $ "Did not just store the echo but returned: " ++ show o let (out, stateAfterThreeEchoes) = runState (storeEcho fourthValidProof 3) stateAfterTwoEchoes result <- out case result of StoreMessage (message, Broadcast messages) -> assertEqual "Did not broadcast the correct messages" [(Ready validRoot, v) | v <- [1, 2, 3]] messages >> assertEqual "Did not record the correct message" (pack "A message") message o -> assertFailure $ "Did not interpolate shards but returned: " ++ show o assertEqual "Did not store all echoes correctly" (zip [1, 2, 3] [secondValidProof, thirdValidProof, fourthValidProof]) (getEcho stateAfterThreeEchoes) buildStateWithTwoEchoes = do let (out, s) = runState (storeEcho secondValidProof 1) (setup 4 0) _ <- out let (out, state) = runState (storeEcho thirdValidProof 2) s _ <- out return state testDoesNotReBroadcastReady = do state <- buildStateWithTwoEchoes let (_, stateAfterReadySent) = runState markReadySent state let (maybeOut, _) = runState (storeEcho fourthValidProof 3) stateAfterReadySent out <- maybeOut case out of None -> return () _ -> assertFailure $ "Did not ignore yet another Ready but returned: " ++ show out testBroadcastsReadyAfterReceivingMatchingReady = do let (out, stateAfterOneReady) = runState (storeReady (pack "A root") 1) (setup 4 0) result <- out case result of None -> return () o -> assertFailure $ "Did not just store Ready but returned: " ++ show o let (out, stateAfterTwoReadies) = runState (storeReady (pack "A root") 2) stateAfterOneReady result <- out case result of Broadcast messages -> assertEqual "Did not broadcast the correct messages" (map (\v -> (Ready (pack "A root"), v)) [1, 2, 3]) messages o -> assertFailure $ "Did not broadcast messages but returned: " ++ show o let (_, afterReadySent) = runState markReadySent stateAfterTwoReadies let (out, _) = runState (storeReady (pack "A root") 3) afterReadySent result <- out case result of None -> return () o -> assertFailure $ "Did not ignore yet another Ready but returned: " ++ show o testDoesNotBroadcastMismatchingReady = do let root = pack "A root" let mismatchingRoot = pack "A mismatching root" let state = (setup 4 0) { getReady = [ (1, root) ,(2, root) ,(1, mismatchingRoot) ] } let (out, _) = runState (storeReady mismatchingRoot 2) state result <- out case result of None -> return () o -> assertFailure $ "Did not ignore mismatching Ready but returned: " ++ show o testOutputsAfterSufficientInput = do The output is expected after at least 2f + 1 Ready and at least N - 2f Echo . enough of Ready but not enough of Echo let state = (setup 4 0) { getEcho = [] ,getReady = [ (1, validRoot) ,(2, validRoot) ,(3, validRoot) ] ,getReadySent = True } let (out, _) = runState (storeEcho secondValidProof 1) state result <- out case result of None -> return () o -> assertFailure $ "Returned unexpected output: " ++ show o let (out, _) = runState (storeReady validRoot 1) state result <- out case result of None -> return () o -> assertFailure $ "Returned unexpected output: " ++ show o enough of Echo but not enough of Ready let state = (setup 4 0) { getEcho = [ (1, secondValidProof) ] ,getReady = [ (1, validRoot) ] ,getReadySent = True } let (out, _) = runState (storeEcho thirdValidProof 2) state result <- out case result of None -> return () o -> assertFailure $ "Returned unexpected output: " ++ show o let (out, _) = runState (storeReady validRoot 2) state result <- out case result of None -> return () o -> assertFailure $ "Returned unexpected output: " ++ show o enough of Echo and Ready let state = (setup 4 0) { getEcho = [ (1, secondValidProof) ,(2, thirdValidProof) ] ,getReady = [ (1, validRoot) ,(2, validRoot) ,(3, validRoot) ] ,getReadySent = True } let (_, withMessage) = runState (storeMessage $ pack "A message") state let (out, _) = runState (storeEcho fourthValidProof 3) withMessage result <- out case result of Output msg -> assertEqual "Did not output the correct message" (pack "A message") msg o -> assertFailure $ "Did not output the message after storing echo but returned: " ++ show o let (out, _) = runState (storeReady validRoot 2) withMessage result <- out case result of Output msg -> assertEqual "Did not output the correct message" (pack "A message") msg o -> assertFailure $ "Did not output the message after storing Ready but returned: " ++ show o
1db79a9fa1c8642c9466d129a0077199b1e2ed4663e3659545ba8a9e287f8742
dialohq/grpc-proxy-sidecar
discover.ml
Lightweight thread library for * Program discover * Copyright ( C ) 2010 * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation , with linking exceptions ; * either version 2.1 of the License , or ( at your option ) any later * version . See COPYING file for details . * * This program is distributed in the hope that it will be useful , but * WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA * 02111 - 1307 , USA . * * Program discover * Copyright (C) 2010 Jérémie Dimino * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, with linking exceptions; * either version 2.1 of the License, or (at your option) any later * version. See COPYING file for details. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. *) Discover available features let cut_tail l = List.rev (List.tl (List.rev l)) let string_split sep source = let copy_part index offset = String.sub source index (offset - index) in let l = String.length source in let rec loop prev current acc = if current >= l then List.rev acc else match (source.[current] = sep, current = prev, current = l - 1) with | (true, true, _) -> loop (current + 1) (current + 1) acc | (true, _, _) -> loop (current + 1) (current + 1) ((copy_part prev current)::acc) | (false, _, true) -> loop (current + 1) (current + 1) ((copy_part prev (current + 1))::acc) | _ -> loop prev (current + 1) acc in loop 0 0 [] let uniq lst = let unique_set = Hashtbl.create (List.length lst) in List.iter (fun x -> Hashtbl.replace unique_set x ()) lst; Hashtbl.fold (fun x () xs -> x :: xs) unique_set [] let get_paths env_name = try let paths = Sys.getenv env_name in let dirs = string_split ':' paths in List.map (fun dir -> let components = string_split '/' dir in "/" ^ (String.concat "/" (cut_tail components)) ) dirs with Not_found -> [] let env_paths = List.append (get_paths "LIBRARY_PATH") (get_paths "C_INCLUDE_PATH") (* Keep that in sync with the list in myocamlbuild.ml *) let search_paths = uniq (List.append [ "/usr"; "/usr/local"; "/opt"; "/opt/local"; "/opt/homebrew"; "/sw"; "/mingw";] env_paths) open Printf (* +-----------------------------------------------------------------+ | Test codes | +-----------------------------------------------------------------+ *) let caml_code = " external test : unit -> unit = \"lwt_test\" let () = test () " let libev_code = " #include <caml/mlvalues.h> #include <ev.h> CAMLprim value lwt_test() { ev_default_loop(0); return Val_unit; } " (* +-----------------------------------------------------------------+ | Compilation | +-----------------------------------------------------------------+ *) let ocamlc = ref "ocamlc" let ext_obj = ref ".o" let exec_name = ref "a.out" let log_file = ref "" let caml_file = ref "" (* Search for a header file in standard directories. *) let search_header header = let rec loop = function | [] -> None | dir :: dirs -> if Sys.file_exists (dir ^ "/include/" ^ header) then Some dir else loop dirs in loop search_paths let c_args = let flags path = Printf.sprintf "-ccopt -I%s/include -ccopt -L%s/lib" path path in match search_header "ev.h" with | None -> "" | Some path -> flags path let compile c_args args stub_file = let cmd = sprintf "%s -custom %s %s %s %s > %s 2>&1" !ocamlc c_args (Filename.quote stub_file) args (Filename.quote !caml_file) (Filename.quote !log_file) in Sys.command cmd = 0 let safe_remove file_name = try Sys.remove file_name with exn -> () let test_code args stub_code = let stub_file, oc = Filename.open_temp_file "lwt_stub" ".c" in let cleanup () = safe_remove stub_file; safe_remove (Filename.chop_extension (Filename.basename stub_file) ^ !ext_obj) in try output_string oc stub_code; flush oc; close_out oc; let result = compile "" args stub_file || compile c_args args stub_file in cleanup (); result with exn -> (try close_out oc with _ -> ()); cleanup (); raise exn let config = open_out "lwt_config.h" let config_ml = open_out "lwt_config.ml" let test_feature ?(do_check = true) name macro ?(args="") code = if do_check then begin printf "testing for %s:%!" name; if test_code args code then begin fprintf config "#define %s\n" macro; fprintf config_ml "#let %s = true\n" macro; printf " %s available\n%!" (String.make (34 - String.length name) '.'); true end else begin fprintf config "//#define %s\n" macro; fprintf config_ml "#let %s = false\n" macro; printf " %s unavailable\n%!" (String.make (34 - String.length name) '.'); false end end else begin printf "not checking for %s\n%!" name; fprintf config "//#define %s\n" macro; fprintf config_ml "#let %s = false\n" macro; true end (* +-----------------------------------------------------------------+ | Entry point | +-----------------------------------------------------------------+ *) let () = let args = [ "-ocamlc", Arg.Set_string ocamlc, "<path> ocamlc"; "-ext-obj", Arg.Set_string ext_obj, "<ext> C object files extension"; "-exec-name", Arg.Set_string exec_name, "<name> name of the executable produced by ocamlc"; ] in Arg.parse args ignore "check for external C libraries and available features\noptions are:"; (* Put the caml code into a temporary file. *) let file, oc = Filename.open_temp_file "lwt_caml" ".ml" in caml_file := file; output_string oc caml_code; close_out oc; log_file := Filename.temp_file "lwt_output" ".log"; (* Cleanup things on exit. *) at_exit (fun () -> (try close_out config with _ -> ()); (try close_out config_ml with _ -> ()); safe_remove !log_file; safe_remove !exec_name; safe_remove !caml_file; safe_remove (Filename.chop_extension !caml_file ^ ".cmi"); safe_remove (Filename.chop_extension !caml_file ^ ".cmo")); let missing = [] in let missing = if test_feature "libev" "HAVE_LIBEV" ~args:"-cclib -lev" libev_code then missing else "libev" :: missing in if missing <> [] then begin printf " The following recquired C libraries are missing: %s. Please install them and retry. If they are installed in a non-standard location, set the environment variables C_INCLUDE_PATH and LIBRARY_PATH accordingly and retry. For example, if they are installed in /opt/local, you can type: export C_INCLUDE_PATH=/opt/local/include export LIBRARY_PATH=/opt/local/lib To compile without libev support, use ./configure --disable-libev ... " (String.concat ", " missing); exit 1 end; ignore ( test_feature " eventfd " " HAVE_EVENTFD " eventfd_code ) ; ignore ( test_feature " fd passing " " HAVE_FD_PASSING " fd_passing_code ) ; ignore ( test_feature " sched_getcpu " " HAVE_GETCPU " getcpu_code ) ; ignore ( test_feature " affinity getting / setting " " HAVE_AFFINITY " affinity_code ) ; ignore ( test_feature " credentials getting " " HAVE_GET_CREDENTIALS " get_credentials_code ) ; ignore ( test_feature " fdatasync " " HAVE_FDATASYNC " fdatasync_code ) ignore (test_feature "eventfd" "HAVE_EVENTFD" eventfd_code); ignore (test_feature "fd passing" "HAVE_FD_PASSING" fd_passing_code); ignore (test_feature "sched_getcpu" "HAVE_GETCPU" getcpu_code); ignore (test_feature "affinity getting/setting" "HAVE_AFFINITY" affinity_code); ignore (test_feature "credentials getting" "HAVE_GET_CREDENTIALS" get_credentials_code); ignore (test_feature "fdatasync" "HAVE_FDATASYNC" fdatasync_code) *)
null
https://raw.githubusercontent.com/dialohq/grpc-proxy-sidecar/f63ed9f8ce1f6177c125db918f56176ea44d79f5/grpc_proxy_sidecar.esy.lock/opam/conf-libev.4-12/files/discover.ml
ocaml
Keep that in sync with the list in myocamlbuild.ml +-----------------------------------------------------------------+ | Test codes | +-----------------------------------------------------------------+ +-----------------------------------------------------------------+ | Compilation | +-----------------------------------------------------------------+ Search for a header file in standard directories. +-----------------------------------------------------------------+ | Entry point | +-----------------------------------------------------------------+ Put the caml code into a temporary file. Cleanup things on exit.
Lightweight thread library for * Program discover * Copyright ( C ) 2010 * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation , with linking exceptions ; * either version 2.1 of the License , or ( at your option ) any later * version . See COPYING file for details . * * This program is distributed in the hope that it will be useful , but * WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA * 02111 - 1307 , USA . * * Program discover * Copyright (C) 2010 Jérémie Dimino * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, with linking exceptions; * either version 2.1 of the License, or (at your option) any later * version. See COPYING file for details. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. *) Discover available features let cut_tail l = List.rev (List.tl (List.rev l)) let string_split sep source = let copy_part index offset = String.sub source index (offset - index) in let l = String.length source in let rec loop prev current acc = if current >= l then List.rev acc else match (source.[current] = sep, current = prev, current = l - 1) with | (true, true, _) -> loop (current + 1) (current + 1) acc | (true, _, _) -> loop (current + 1) (current + 1) ((copy_part prev current)::acc) | (false, _, true) -> loop (current + 1) (current + 1) ((copy_part prev (current + 1))::acc) | _ -> loop prev (current + 1) acc in loop 0 0 [] let uniq lst = let unique_set = Hashtbl.create (List.length lst) in List.iter (fun x -> Hashtbl.replace unique_set x ()) lst; Hashtbl.fold (fun x () xs -> x :: xs) unique_set [] let get_paths env_name = try let paths = Sys.getenv env_name in let dirs = string_split ':' paths in List.map (fun dir -> let components = string_split '/' dir in "/" ^ (String.concat "/" (cut_tail components)) ) dirs with Not_found -> [] let env_paths = List.append (get_paths "LIBRARY_PATH") (get_paths "C_INCLUDE_PATH") let search_paths = uniq (List.append [ "/usr"; "/usr/local"; "/opt"; "/opt/local"; "/opt/homebrew"; "/sw"; "/mingw";] env_paths) open Printf let caml_code = " external test : unit -> unit = \"lwt_test\" let () = test () " let libev_code = " #include <caml/mlvalues.h> #include <ev.h> CAMLprim value lwt_test() { ev_default_loop(0); return Val_unit; } " let ocamlc = ref "ocamlc" let ext_obj = ref ".o" let exec_name = ref "a.out" let log_file = ref "" let caml_file = ref "" let search_header header = let rec loop = function | [] -> None | dir :: dirs -> if Sys.file_exists (dir ^ "/include/" ^ header) then Some dir else loop dirs in loop search_paths let c_args = let flags path = Printf.sprintf "-ccopt -I%s/include -ccopt -L%s/lib" path path in match search_header "ev.h" with | None -> "" | Some path -> flags path let compile c_args args stub_file = let cmd = sprintf "%s -custom %s %s %s %s > %s 2>&1" !ocamlc c_args (Filename.quote stub_file) args (Filename.quote !caml_file) (Filename.quote !log_file) in Sys.command cmd = 0 let safe_remove file_name = try Sys.remove file_name with exn -> () let test_code args stub_code = let stub_file, oc = Filename.open_temp_file "lwt_stub" ".c" in let cleanup () = safe_remove stub_file; safe_remove (Filename.chop_extension (Filename.basename stub_file) ^ !ext_obj) in try output_string oc stub_code; flush oc; close_out oc; let result = compile "" args stub_file || compile c_args args stub_file in cleanup (); result with exn -> (try close_out oc with _ -> ()); cleanup (); raise exn let config = open_out "lwt_config.h" let config_ml = open_out "lwt_config.ml" let test_feature ?(do_check = true) name macro ?(args="") code = if do_check then begin printf "testing for %s:%!" name; if test_code args code then begin fprintf config "#define %s\n" macro; fprintf config_ml "#let %s = true\n" macro; printf " %s available\n%!" (String.make (34 - String.length name) '.'); true end else begin fprintf config "//#define %s\n" macro; fprintf config_ml "#let %s = false\n" macro; printf " %s unavailable\n%!" (String.make (34 - String.length name) '.'); false end end else begin printf "not checking for %s\n%!" name; fprintf config "//#define %s\n" macro; fprintf config_ml "#let %s = false\n" macro; true end let () = let args = [ "-ocamlc", Arg.Set_string ocamlc, "<path> ocamlc"; "-ext-obj", Arg.Set_string ext_obj, "<ext> C object files extension"; "-exec-name", Arg.Set_string exec_name, "<name> name of the executable produced by ocamlc"; ] in Arg.parse args ignore "check for external C libraries and available features\noptions are:"; let file, oc = Filename.open_temp_file "lwt_caml" ".ml" in caml_file := file; output_string oc caml_code; close_out oc; log_file := Filename.temp_file "lwt_output" ".log"; at_exit (fun () -> (try close_out config with _ -> ()); (try close_out config_ml with _ -> ()); safe_remove !log_file; safe_remove !exec_name; safe_remove !caml_file; safe_remove (Filename.chop_extension !caml_file ^ ".cmi"); safe_remove (Filename.chop_extension !caml_file ^ ".cmo")); let missing = [] in let missing = if test_feature "libev" "HAVE_LIBEV" ~args:"-cclib -lev" libev_code then missing else "libev" :: missing in if missing <> [] then begin printf " The following recquired C libraries are missing: %s. Please install them and retry. If they are installed in a non-standard location, set the environment variables C_INCLUDE_PATH and LIBRARY_PATH accordingly and retry. For example, if they are installed in /opt/local, you can type: export C_INCLUDE_PATH=/opt/local/include export LIBRARY_PATH=/opt/local/lib To compile without libev support, use ./configure --disable-libev ... " (String.concat ", " missing); exit 1 end; ignore ( test_feature " eventfd " " HAVE_EVENTFD " eventfd_code ) ; ignore ( test_feature " fd passing " " HAVE_FD_PASSING " fd_passing_code ) ; ignore ( test_feature " sched_getcpu " " HAVE_GETCPU " getcpu_code ) ; ignore ( test_feature " affinity getting / setting " " HAVE_AFFINITY " affinity_code ) ; ignore ( test_feature " credentials getting " " HAVE_GET_CREDENTIALS " get_credentials_code ) ; ignore ( test_feature " fdatasync " " HAVE_FDATASYNC " fdatasync_code ) ignore (test_feature "eventfd" "HAVE_EVENTFD" eventfd_code); ignore (test_feature "fd passing" "HAVE_FD_PASSING" fd_passing_code); ignore (test_feature "sched_getcpu" "HAVE_GETCPU" getcpu_code); ignore (test_feature "affinity getting/setting" "HAVE_AFFINITY" affinity_code); ignore (test_feature "credentials getting" "HAVE_GET_CREDENTIALS" get_credentials_code); ignore (test_feature "fdatasync" "HAVE_FDATASYNC" fdatasync_code) *)
a8007d3a1fa21dd6e61767b12fbe0c98015b793e18dc519811d774bbad953d20
drym-org/qi
expander.rkt
#lang racket/base (provide expand-flow) (define (expand-flow stx) stx)
null
https://raw.githubusercontent.com/drym-org/qi/a8bd930eda09e07b8f44fd2e7100b7be96d446ea/qi-lib/flow/expander.rkt
racket
#lang racket/base (provide expand-flow) (define (expand-flow stx) stx)
23db986a7ff309710be6c5f504d4882e08b3fe11e9f7ebec75afc6663e3dd31e
vikram/lisplibraries
xml-parser.lisp
-*- package : NOX ; Syntax : Common - lisp ; Base : 10 -*- ;;; xml-parser.lisp ;;; ;;; ;;; -------------------------------------------------------------------------------------- ;;; ;;; The contents of this file are subject to the NOKOS License Version 1.0a (the ;;; "License"); you may not use this file except in compliance with the License. ;;; Software distributed under the License is distributed on an " AS IS " basis , WITHOUT ;;; WARRANTY OF ANY KIND, either express or implied. See the License for the specific ;;; language governing rights and limitations under the License. ;;; The Original Software is WILBUR2 : Nokia Semantic Web Toolkit for CLOS ;;; Copyright ( c ) 2001 - 2005 Nokia and others . All Rights Reserved . Portions Copyright ( c ) 1989 - 1992 . All Rights Reserved . ;;; Contributor(s ): ( mailto: ) ( mailto: ) ;;; ;;; -------------------------------------------------------------------------------------- ;;; ;;; Version : $ I d : xml - parser.lisp , v 1.11 2004/11/28 23:14:53 ora Exp $ ;;; ;;; Purpose: This file contains an implementation of an XML parser. This parser was motivated by RDF , and consequently does not implement all the features of XML 1.0 . In fact , it needs a lot of work . Tough ... ;;; (in-package "NOX") ;;; -------------------------------------------------------------------------------------- ;;; ;;; NAME READTABLE ;;; (eval-when (:compile-toplevel :load-toplevel) (defconstant -name-start-characters- (let ((s (concatenate 'string (loop for i from (char-code #\a) to (char-code #\z) collect (code-char i))))) (concatenate 'string s (string-upcase s) "_:"))) (defconstant -name-characters- (let ((v (make-array 256))) (dotimes (i 256) (setf (svref v i) nil)) (dolist (c (concatenate 'list -name-start-characters- (list #\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 #\. #\-))) (setf (svref v (char-code c)) t)) v))) (defvar *nr-buffer* (make-base-string 256 :adjustable t :fill-pointer 0)) (defun name-reader (stream char) (setf (fill-pointer *nr-buffer*) 0) (vector-push char *nr-buffer*) (with-loop&read-char (c stream) (cond ((svref -name-characters- (char-code c)) (vector-push-extend c *nr-buffer*)) (t (unread-char c stream) (return (concatenate 'string *nr-buffer*)))))) (defun single-character-reader (stream char) (declare (ignore stream)) char) (defun not-allowed-reader (stream char) (declare (ignore stream)) (error 'syntax-error :thing char)) (define-readtable *name-reader* nil (dotimes (i 256) (let ((c (code-char i))) (unless (whitespace-char-p c) (set-macro-character c #'not-allowed-reader)))) (set-macro-character #\/ #'single-character-reader) (set-macro-character #\! #'name-reader) (set-macro-character #\? #'name-reader) (map nil #'(lambda (c) (set-macro-character c #'name-reader)) -name-start-characters-)) ;;; -------------------------------------------------------------------------------------- ;;; ;;; XML READTABLE ;;; (defun read-declaration (stream name) (declare (special *dtd-reader*)) ; forward ref (cond ((string= name "!DOCTYPE") (let ((name (read-using *name-reader* stream t)) (next (skip-whitespace stream))) (cond ((not (eql next #\[)) (make-instance 'dtd-start :string name :externalp t :stuff (read-delimited-list #\> stream t))) (t (setf (parser-in-dtd-p *current-parser*) t (parser-readtable *current-parser*) *dtd-reader*) (skip-whitespace stream t) ; skip [ (make-instance 'dtd-start :string name))))) ((string= name "!") (let ((char (read-char stream t nil t))) CDATA , INCLUDE , IGNORE (let ((name (read-until-char stream #\[))) (cond ((string= name "CDATA") (read-until-%%> stream #\])) ((find name '("INCLUDE" "IGNORE") :test #'string=) (error 'feature-not-supported :thing name)) (t (error 'syntax-error :thing "![")))))))) ((string= name "!--") (make-instance 'comment :string (read-until-%%> stream #\-))) (t (error 'unknown-declaration :thing name)))) (defun open-anglebracket-reader (stream char) (declare (ignore char)) (let ((name (read-using *name-reader* stream t))) (cond ((eql name #\/) (make-instance 'close-tag :string (first (read-delimited-list #\> stream t)))) ((char= (char name 0) #\!) (read-declaration stream name)) ((char= (char name 0) #\?) (let* ((stuff (read-delimited-list #\> stream t))) (if (eql (first (last stuff)) #\?) ignore attrs (error 'pi-termination-problem :thing name)))) (t (let* ((stuff (read-delimited-list #\> stream t)) (parent (first (parser-path *current-parser*))) (tag (make-instance 'open-tag :string name :base (if parent (tag-base parent) (parser-base *current-parser*)))) (attr nil)) (loop (cond ((null stuff) (return tag)) ((eql (setf attr (pop stuff)) #\/) (setf (tag-empty-p tag) t) (return tag)) ((eql (pop stuff) #\=) (setf (tag-attribute tag attr) (pop stuff))) (t (error 'syntax-error :thing "missing ="))))))))) (defun quoted-string-reader (stream char) (read-until-char-expanding-entities stream char nil)) (defun read-xml-token (stream &aux (char (peek-char t stream nil nil))) (when char (if (or (char= char #\<) (and (char= char #\]) (parser-in-dtd-p *current-parser*))) (read-using (parser-readtable *current-parser*) stream) (read-until-char-expanding-entities stream #\< t)))) (define-readtable *xml-reader* nil (dotimes (i 256) (let ((c (code-char i))) (unless (whitespace-char-p c) (set-macro-character c #'not-allowed-reader)))) (set-macro-character #\< #'open-anglebracket-reader) (set-macro-character #\> (get-macro-character #\))) (set-macro-character #\= #'single-character-reader) (set-macro-character #\/ #'single-character-reader) (set-macro-character #\? #'single-character-reader) (set-macro-character #\' #'quoted-string-reader) (set-macro-character #\" #'quoted-string-reader) (map nil #'(lambda (c) (set-macro-character c #'name-reader)) -name-start-characters-)) ;;; -------------------------------------------------------------------------------------- ;;; ;;; (defun dtd-open-anglebracket-reader (stream char) (declare (ignore char)) (let ((name (read-using *name-reader* stream t)) (stuff (read-delimited-list #\> stream t))) (cond ((string= name "!ENTITY") (make-instance 'entity-declaration :name (pop stuff) :string (pop stuff))) ((string= name "!ELEMENT") (make-instance 'element-declaration :name (pop stuff) :contentspec (pop stuff))) ((string= name "!ATTLIST") (make-instance 'attlist-declaration :name (pop stuff))) ((string= name "!NOTATION") (error 'feature-not-supported :thing name)) (t (error 'unknown-declaration :thing name))))) (defun dtd-parenthesis-reader (stream char) (declare (ignore char)) (read-delimited-list #\) stream t)) (defun close-bracket-reader (stream char) (declare (ignore char)) (cond ((not (parser-in-dtd-p *current-parser*)) (error 'syntax-error :thing "]")) ((not (char= (skip-whitespace stream t) #\>)) (error 'dtd-termination-problem)) (t (setf (parser-readtable *current-parser*) *xml-reader*) (make-instance 'dtd-end)))) (define-readtable *dtd-reader* *xml-reader* (set-macro-character #\< #'dtd-open-anglebracket-reader) (set-macro-character #\# (get-macro-character #\A)) (set-macro-character #\] #'close-bracket-reader) (set-macro-character #\( #'dtd-parenthesis-reader) (set-macro-character #\) (get-macro-character #\)))) ;;; -------------------------------------------------------------------------------------- ;;; ;;; CLASS XML-PARSER ;;; (defclass xml-parser (sax-producer) ((expand-namespaces-p :initarg :expand-namespaces-p :initform t :reader parser-expand-namespaces-p) (entities :initform (make-hash-table :test #'equal) :reader parser-entities) (in-dtd-p :initform nil :accessor parser-in-dtd-p) (canonical-uris :initform (make-hash-table :test #'equal) :reader parser-canonical-uris) (readtable :initform nil :accessor parser-readtable) (path :initform nil :accessor parser-path) (base :initform nil :accessor parser-base))) (eval-when (:compile-toplevel :load-toplevel) (defconstant -standard-entities- '(("gt" . ">") ("lt" . "<") ("amp" . "&") ("quot" . "\"") ("apos" . "'")))) (defmethod initialize-instance :after ((self xml-parser) &rest args) (declare (ignore args)) (dolist (pair -standard-entities-) (destructuring-bind (n . e) pair (setf (get-entity self n) e))) (setf (get-canonical-uri self -alternate-rdf-uri-) -rdf-uri- (get-canonical-uri self -alternate-rdfs-uri-) -rdfs-uri- (get-canonical-uri self (subseq -rdfs-uri- 0 (1- (length -rdfs-uri-)))) -rdfs-uri-)) (defun get-entity (parser name) (gethash name (parser-entities parser))) (defun (setf get-entity) (definition parser name) (setf (gethash name (parser-entities parser)) definition)) (defun get-canonical-uri (parser uri) (gethash uri (parser-canonical-uris parser) uri)) (defun (setf get-canonical-uri) (new-uri parser uri) (setf (gethash uri (parser-canonical-uris parser)) new-uri)) (defmethod parse ((self xml-parser) stream locator) (declare (special *xml-parse-buffers*)) (let ((*current-parser* self) (consumer (sax-producer-consumer self))) (with-resource-from-pool (*ruc-buffer* *xml-parse-buffers*) (with-resource-from-pool (*ruc-ee-buffer* *xml-parse-buffers*) (setf (parser-readtable self) *xml-reader* (parser-base self) locator) (handler-bind ((end-of-file #'(lambda (c) (declare (ignore c)) (error 'syntax-error :thing "eof")))) (start-document consumer locator) (parse-start self stream nil nil) (end-document consumer (sax-consumer-mode consumer))))))) (defun parse-start (parser stream end namespaces &aux continuep) (loop (multiple-value-setq (continuep namespaces) (parse-token parser stream (read-xml-token stream) end namespaces)) (unless continuep (return-from parse-start nil)))) (defmethod parse-token ((self xml-parser) stream (token string) ; char-content end namespaces) (declare (ignore stream)) (char-content (sax-producer-consumer self) (collapse-whitespace token) (sax-consumer-mode (sax-producer-consumer self))) (values end namespaces)) (defmethod parse-token ((self xml-parser) stream (token open-tag) end namespaces) (flet ((expand (name) (or (expand-name-with-namespace name namespaces) (progn (cerror "Do not expand" 'missing-namespace-definition :thing name) name)))) (declare (dynamic-extent #'expand)) (let ((consumer (sax-producer-consumer self))) (when (parser-expand-namespaces-p self) (setf namespaces (add-namespaces self token namespaces)) (shiftf (tag-original-name token) (token-string token) (expand (token-string token))) (dolist (k&v (tag-attributes token)) (setf (car k&v) (expand (car k&v))))) (do-string-dict (key value (tag-attributes token)) (when (string= key "xml:base") (setf (tag-attributes token) (string-dict-del (tag-attributes token) key)) (setf (tag-base token) value))) (setf (tag-namespaces token) namespaces) (push token (parser-path self)) (start-element consumer token (sax-consumer-mode consumer)) (cond ((tag-empty-p token) (end-element consumer token (sax-consumer-mode consumer)) (pop (parser-path self))) (t (parse-start self stream token namespaces))) (values end namespaces)))) (defun add-namespaces (parser tag namespaces) (do-string-dict (key value (tag-attributes tag)) (multiple-value-bind (n p) (name&prefix key) (cond ((string= p "xmlns") (let ((uri (get-canonical-uri parser value))) (setf (tag-attributes tag) (string-dict-del (tag-attributes tag) key)) (setf namespaces (string-dict-add namespaces n uri)) (maybe-use-namespace (sax-producer-consumer parser) n uri))) ((and (null p) (string= n "xmlns")) (setf (tag-attributes tag) (string-dict-del (tag-attributes tag) key)) (setf namespaces (string-dict-add namespaces nil (get-canonical-uri parser value))))))) namespaces) (defun ends-in-hash-p (string) (declare (type string string)) (let ((c (char string (1- (length string))))) (or (char= c #\#) (char= c #\/)))) (defun expand-name-with-namespace (string namespaces) (multiple-value-bind (n p) (name&prefix string) (or (and (null p) (hack-rdf-attribute-name n namespaces)) (let ((uri (string-dict-get namespaces p))) (cond (uri (values (concatenate 'string uri (and (not (ends-in-hash-p uri)) "#") n) n p)) ((or (null p) (string-equal p "xml")) (values string nil nil)) (t (values nil n p))))))) (defun hack-rdf-attribute-name (name namespaces) (and (car (rassoc -rdf-uri- namespaces :test #'string=)) (cdr (assoc name -rdf-attr-map- :test #'string=)))) (defmethod parse-token ((self xml-parser) stream (token close-tag) end namespaces) (declare (ignore stream)) (cond ((null end) (error 'unexpected-end-tag :thing (token-string end))) ((string= (tag-original-name end) (token-string token)) (setf (tag-counterpart token) end (tag-counterpart end) token) (end-element (sax-producer-consumer self) end (sax-consumer-mode (sax-producer-consumer self))) (pop (parser-path self)) (values nil namespaces)) (t (error 'unexpected-end-tag :expectation (tag-original-name end) :thing (token-string token))))) (defmethod parse-token ((self xml-parser) stream (token proc-instruction) end namespaces) (declare (ignore stream end)) (let ((consumer (sax-producer-consumer self))) (proc-instruction consumer token (sax-consumer-mode consumer)) (values t namespaces))) (defmethod parse-token ((self xml-parser) stream (token entity-declaration) end namespaces) (declare (ignore stream end)) (setf (get-entity self (entity-name token)) (token-string token)) (values t namespaces)) (defmethod parse-token ((self xml-parser) stream (token comment) end namespaces) (declare (ignore stream end)) (values t namespaces)) (defmethod parse-token ((self xml-parser) stream (token dtd-start) end namespaces) (declare (ignore stream end)) (when (dtd-external-p token) (xml-warning "External DTD ignored:~{ ~S~}" (dtd-stuff token))) (values t namespaces)) (defmethod parse-token ((self xml-parser) stream (token dtd-end) end namespaces) (declare (ignore stream end)) (values t namespaces)) (defmethod parse-token ((self xml-parser) stream (token dtd-declaration) end namespaces) (declare (ignore stream end)) (xml-warning "~S ignored" (class-name (class-of token))) (values t namespaces)) (defmethod parse-token ((self xml-parser) stream token end namespaces) (declare (ignore stream end)) (if token (error 'syntax-error :thing token) null token signifies eof (defun parse-from-stream (stream locator parser-class &rest options) (declare (dynamic-extent options)) (let ((parser (apply #'make-instance parser-class options))) (handler-case (values (parse parser stream locator) parser) (xml-error (e) (let ((*readtable* (copy-readtable nil))) (cerror "Keep going" e)))))) ;;; -------------------------------------------------------------------------------------- ;;; ;;; CLASS XML-FORMATTER ;;; (defclass xml-formatter (sax-consumer) ((stream :initarg :stream :initform nil :reader formatter-stream) (level :initform 0 :accessor formatter-level) (indent-delta :initarg :indent-delta :initform 2 :reader formatter-indent-delta))) (defmethod replay ((formatter xml-formatter) events) (dolist (event events) (let ((mode (sax-consumer-mode formatter))) (etypecase event (open-tag (start-element formatter event mode)) (close-tag (end-element formatter (tag-counterpart event) mode)) (string (char-content formatter event mode)))))) (defun reverse-expand-name (name namespaces &aux (nn (length name))) (do-string-dict (prefix uri namespaces) (let ((un (length uri))) (when (and (>= nn un) (string= name uri :end1 un)) (return-from reverse-expand-name (values (if (= nn un) (format nil "~@[~A~]:" prefix) (format nil "~@[~A:~]~A" prefix (let ((n (subseq name un))) (if (char= (char n 0) #\#) (subseq n 1) n)))) t))))) (values name nil)) (defmethod start-element ((self xml-formatter) (tag open-tag) mode) (declare (ignore mode)) (let ((stream (formatter-stream self))) (format stream "~&~V@T<~A" (formatter-level self) (reverse-expand-name (token-string tag) (tag-namespaces tag))) (do-string-dict (attribute value (tag-attributes tag)) (format stream " ~A=\"~A\"" (reverse-expand-name attribute (tag-namespaces tag)) value)) (princ (if (tag-empty-p tag) "/>" #\>) stream) (incf (formatter-level self) (formatter-indent-delta self)))) (defmethod end-element ((self xml-formatter) tag mode) (declare (ignore mode)) (decf (formatter-level self) (formatter-indent-delta self)) (unless (tag-empty-p tag) (format (formatter-stream self) "~&~V@T</~A>" (formatter-level self) (reverse-expand-name (token-string tag) (tag-namespaces tag))))) (defmethod char-content ((self xml-formatter) char-content mode) (declare (ignore mode)) (princ (string-trim '(#\Space #\Tab #\Newline) char-content) (formatter-stream self))) (defmethod start-document ((self xml-formatter) locator) (declare (ignore locator)) (format (formatter-stream self) "~&<?xml version=\"1.0\"?>")) ;;; -------------------------------------------------------------------------------------- ;;; ;;; CLASS TREE-PARSER ;;; (defclass tree-parser (sax-consumer) ((states :initform nil :accessor parser-states) (package :initarg :package :initform (find-package :keyword) :reader parser-package))) (defun string->keyword (string &optional (package :keyword)) (if package (intern (string-upcase string) package) string)) (defmethod initialize-instance :after ((self tree-parser) &rest args &key producer &allow-other-keys) (declare (ignore args)) (if producer (setf (sax-consumer-producer self) producer (sax-producer-consumer producer) self) (setf (sax-consumer-producer self) (make-instance 'xml-parser :consumer self)))) (defmethod parser-interpret-content ((parser tree-parser) (content string)) content) (defmethod start-element ((parser tree-parser) (tag open-tag) mode) (declare (ignore mode)) (push (list (list (string->keyword (token-string tag) (parser-package parser)))) (parser-states parser))) (defmethod end-element ((parser tree-parser) (tag open-tag) mode) (declare (ignore mode)) (push (reverse (first (pop (parser-states parser)))) (car (first (parser-states parser))))) (defmethod char-content ((parser tree-parser) (content string) mode) (declare (ignore mode)) (push (parser-interpret-content parser content) (car (first (parser-states parser))))) (defmethod parse ((parser tree-parser) stream locator) (setf (parser-states parser) (list (list nil))) (parse (find-first-producer parser) stream locator) (caar (pop (parser-states parser))))
null
https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/wilbur/nox/xml-parser.lisp
lisp
Syntax : Common - lisp ; Base : 10 -*- -------------------------------------------------------------------------------------- The contents of this file are subject to the NOKOS License Version 1.0a (the "License"); you may not use this file except in compliance with the License. WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. -------------------------------------------------------------------------------------- Purpose: This file contains an implementation of an XML parser. This -------------------------------------------------------------------------------------- NAME READTABLE -------------------------------------------------------------------------------------- XML READTABLE forward ref skip [ -------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------- CLASS XML-PARSER char-content -------------------------------------------------------------------------------------- CLASS XML-FORMATTER -------------------------------------------------------------------------------------- CLASS TREE-PARSER
xml-parser.lisp Software distributed under the License is distributed on an " AS IS " basis , WITHOUT The Original Software is WILBUR2 : Nokia Semantic Web Toolkit for CLOS Copyright ( c ) 2001 - 2005 Nokia and others . All Rights Reserved . Portions Copyright ( c ) 1989 - 1992 . All Rights Reserved . Contributor(s ): ( mailto: ) ( mailto: ) Version : $ I d : xml - parser.lisp , v 1.11 2004/11/28 23:14:53 ora Exp $ parser was motivated by RDF , and consequently does not implement all the features of XML 1.0 . In fact , it needs a lot of work . Tough ... (in-package "NOX") (eval-when (:compile-toplevel :load-toplevel) (defconstant -name-start-characters- (let ((s (concatenate 'string (loop for i from (char-code #\a) to (char-code #\z) collect (code-char i))))) (concatenate 'string s (string-upcase s) "_:"))) (defconstant -name-characters- (let ((v (make-array 256))) (dotimes (i 256) (setf (svref v i) nil)) (dolist (c (concatenate 'list -name-start-characters- (list #\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 #\. #\-))) (setf (svref v (char-code c)) t)) v))) (defvar *nr-buffer* (make-base-string 256 :adjustable t :fill-pointer 0)) (defun name-reader (stream char) (setf (fill-pointer *nr-buffer*) 0) (vector-push char *nr-buffer*) (with-loop&read-char (c stream) (cond ((svref -name-characters- (char-code c)) (vector-push-extend c *nr-buffer*)) (t (unread-char c stream) (return (concatenate 'string *nr-buffer*)))))) (defun single-character-reader (stream char) (declare (ignore stream)) char) (defun not-allowed-reader (stream char) (declare (ignore stream)) (error 'syntax-error :thing char)) (define-readtable *name-reader* nil (dotimes (i 256) (let ((c (code-char i))) (unless (whitespace-char-p c) (set-macro-character c #'not-allowed-reader)))) (set-macro-character #\/ #'single-character-reader) (set-macro-character #\! #'name-reader) (set-macro-character #\? #'name-reader) (map nil #'(lambda (c) (set-macro-character c #'name-reader)) -name-start-characters-)) (defun read-declaration (stream name) (cond ((string= name "!DOCTYPE") (let ((name (read-using *name-reader* stream t)) (next (skip-whitespace stream))) (cond ((not (eql next #\[)) (make-instance 'dtd-start :string name :externalp t :stuff (read-delimited-list #\> stream t))) (t (setf (parser-in-dtd-p *current-parser*) t (parser-readtable *current-parser*) *dtd-reader*) (make-instance 'dtd-start :string name))))) ((string= name "!") (let ((char (read-char stream t nil t))) CDATA , INCLUDE , IGNORE (let ((name (read-until-char stream #\[))) (cond ((string= name "CDATA") (read-until-%%> stream #\])) ((find name '("INCLUDE" "IGNORE") :test #'string=) (error 'feature-not-supported :thing name)) (t (error 'syntax-error :thing "![")))))))) ((string= name "!--") (make-instance 'comment :string (read-until-%%> stream #\-))) (t (error 'unknown-declaration :thing name)))) (defun open-anglebracket-reader (stream char) (declare (ignore char)) (let ((name (read-using *name-reader* stream t))) (cond ((eql name #\/) (make-instance 'close-tag :string (first (read-delimited-list #\> stream t)))) ((char= (char name 0) #\!) (read-declaration stream name)) ((char= (char name 0) #\?) (let* ((stuff (read-delimited-list #\> stream t))) (if (eql (first (last stuff)) #\?) ignore attrs (error 'pi-termination-problem :thing name)))) (t (let* ((stuff (read-delimited-list #\> stream t)) (parent (first (parser-path *current-parser*))) (tag (make-instance 'open-tag :string name :base (if parent (tag-base parent) (parser-base *current-parser*)))) (attr nil)) (loop (cond ((null stuff) (return tag)) ((eql (setf attr (pop stuff)) #\/) (setf (tag-empty-p tag) t) (return tag)) ((eql (pop stuff) #\=) (setf (tag-attribute tag attr) (pop stuff))) (t (error 'syntax-error :thing "missing ="))))))))) (defun quoted-string-reader (stream char) (read-until-char-expanding-entities stream char nil)) (defun read-xml-token (stream &aux (char (peek-char t stream nil nil))) (when char (if (or (char= char #\<) (and (char= char #\]) (parser-in-dtd-p *current-parser*))) (read-using (parser-readtable *current-parser*) stream) (read-until-char-expanding-entities stream #\< t)))) (define-readtable *xml-reader* nil (dotimes (i 256) (let ((c (code-char i))) (unless (whitespace-char-p c) (set-macro-character c #'not-allowed-reader)))) (set-macro-character #\< #'open-anglebracket-reader) (set-macro-character #\> (get-macro-character #\))) (set-macro-character #\= #'single-character-reader) (set-macro-character #\/ #'single-character-reader) (set-macro-character #\? #'single-character-reader) (set-macro-character #\' #'quoted-string-reader) (set-macro-character #\" #'quoted-string-reader) (map nil #'(lambda (c) (set-macro-character c #'name-reader)) -name-start-characters-)) (defun dtd-open-anglebracket-reader (stream char) (declare (ignore char)) (let ((name (read-using *name-reader* stream t)) (stuff (read-delimited-list #\> stream t))) (cond ((string= name "!ENTITY") (make-instance 'entity-declaration :name (pop stuff) :string (pop stuff))) ((string= name "!ELEMENT") (make-instance 'element-declaration :name (pop stuff) :contentspec (pop stuff))) ((string= name "!ATTLIST") (make-instance 'attlist-declaration :name (pop stuff))) ((string= name "!NOTATION") (error 'feature-not-supported :thing name)) (t (error 'unknown-declaration :thing name))))) (defun dtd-parenthesis-reader (stream char) (declare (ignore char)) (read-delimited-list #\) stream t)) (defun close-bracket-reader (stream char) (declare (ignore char)) (cond ((not (parser-in-dtd-p *current-parser*)) (error 'syntax-error :thing "]")) ((not (char= (skip-whitespace stream t) #\>)) (error 'dtd-termination-problem)) (t (setf (parser-readtable *current-parser*) *xml-reader*) (make-instance 'dtd-end)))) (define-readtable *dtd-reader* *xml-reader* (set-macro-character #\< #'dtd-open-anglebracket-reader) (set-macro-character #\# (get-macro-character #\A)) (set-macro-character #\] #'close-bracket-reader) (set-macro-character #\( #'dtd-parenthesis-reader) (set-macro-character #\) (get-macro-character #\)))) (defclass xml-parser (sax-producer) ((expand-namespaces-p :initarg :expand-namespaces-p :initform t :reader parser-expand-namespaces-p) (entities :initform (make-hash-table :test #'equal) :reader parser-entities) (in-dtd-p :initform nil :accessor parser-in-dtd-p) (canonical-uris :initform (make-hash-table :test #'equal) :reader parser-canonical-uris) (readtable :initform nil :accessor parser-readtable) (path :initform nil :accessor parser-path) (base :initform nil :accessor parser-base))) (eval-when (:compile-toplevel :load-toplevel) (defconstant -standard-entities- '(("gt" . ">") ("lt" . "<") ("amp" . "&") ("quot" . "\"") ("apos" . "'")))) (defmethod initialize-instance :after ((self xml-parser) &rest args) (declare (ignore args)) (dolist (pair -standard-entities-) (destructuring-bind (n . e) pair (setf (get-entity self n) e))) (setf (get-canonical-uri self -alternate-rdf-uri-) -rdf-uri- (get-canonical-uri self -alternate-rdfs-uri-) -rdfs-uri- (get-canonical-uri self (subseq -rdfs-uri- 0 (1- (length -rdfs-uri-)))) -rdfs-uri-)) (defun get-entity (parser name) (gethash name (parser-entities parser))) (defun (setf get-entity) (definition parser name) (setf (gethash name (parser-entities parser)) definition)) (defun get-canonical-uri (parser uri) (gethash uri (parser-canonical-uris parser) uri)) (defun (setf get-canonical-uri) (new-uri parser uri) (setf (gethash uri (parser-canonical-uris parser)) new-uri)) (defmethod parse ((self xml-parser) stream locator) (declare (special *xml-parse-buffers*)) (let ((*current-parser* self) (consumer (sax-producer-consumer self))) (with-resource-from-pool (*ruc-buffer* *xml-parse-buffers*) (with-resource-from-pool (*ruc-ee-buffer* *xml-parse-buffers*) (setf (parser-readtable self) *xml-reader* (parser-base self) locator) (handler-bind ((end-of-file #'(lambda (c) (declare (ignore c)) (error 'syntax-error :thing "eof")))) (start-document consumer locator) (parse-start self stream nil nil) (end-document consumer (sax-consumer-mode consumer))))))) (defun parse-start (parser stream end namespaces &aux continuep) (loop (multiple-value-setq (continuep namespaces) (parse-token parser stream (read-xml-token stream) end namespaces)) (unless continuep (return-from parse-start nil)))) (defmethod parse-token ((self xml-parser) end namespaces) (declare (ignore stream)) (char-content (sax-producer-consumer self) (collapse-whitespace token) (sax-consumer-mode (sax-producer-consumer self))) (values end namespaces)) (defmethod parse-token ((self xml-parser) stream (token open-tag) end namespaces) (flet ((expand (name) (or (expand-name-with-namespace name namespaces) (progn (cerror "Do not expand" 'missing-namespace-definition :thing name) name)))) (declare (dynamic-extent #'expand)) (let ((consumer (sax-producer-consumer self))) (when (parser-expand-namespaces-p self) (setf namespaces (add-namespaces self token namespaces)) (shiftf (tag-original-name token) (token-string token) (expand (token-string token))) (dolist (k&v (tag-attributes token)) (setf (car k&v) (expand (car k&v))))) (do-string-dict (key value (tag-attributes token)) (when (string= key "xml:base") (setf (tag-attributes token) (string-dict-del (tag-attributes token) key)) (setf (tag-base token) value))) (setf (tag-namespaces token) namespaces) (push token (parser-path self)) (start-element consumer token (sax-consumer-mode consumer)) (cond ((tag-empty-p token) (end-element consumer token (sax-consumer-mode consumer)) (pop (parser-path self))) (t (parse-start self stream token namespaces))) (values end namespaces)))) (defun add-namespaces (parser tag namespaces) (do-string-dict (key value (tag-attributes tag)) (multiple-value-bind (n p) (name&prefix key) (cond ((string= p "xmlns") (let ((uri (get-canonical-uri parser value))) (setf (tag-attributes tag) (string-dict-del (tag-attributes tag) key)) (setf namespaces (string-dict-add namespaces n uri)) (maybe-use-namespace (sax-producer-consumer parser) n uri))) ((and (null p) (string= n "xmlns")) (setf (tag-attributes tag) (string-dict-del (tag-attributes tag) key)) (setf namespaces (string-dict-add namespaces nil (get-canonical-uri parser value))))))) namespaces) (defun ends-in-hash-p (string) (declare (type string string)) (let ((c (char string (1- (length string))))) (or (char= c #\#) (char= c #\/)))) (defun expand-name-with-namespace (string namespaces) (multiple-value-bind (n p) (name&prefix string) (or (and (null p) (hack-rdf-attribute-name n namespaces)) (let ((uri (string-dict-get namespaces p))) (cond (uri (values (concatenate 'string uri (and (not (ends-in-hash-p uri)) "#") n) n p)) ((or (null p) (string-equal p "xml")) (values string nil nil)) (t (values nil n p))))))) (defun hack-rdf-attribute-name (name namespaces) (and (car (rassoc -rdf-uri- namespaces :test #'string=)) (cdr (assoc name -rdf-attr-map- :test #'string=)))) (defmethod parse-token ((self xml-parser) stream (token close-tag) end namespaces) (declare (ignore stream)) (cond ((null end) (error 'unexpected-end-tag :thing (token-string end))) ((string= (tag-original-name end) (token-string token)) (setf (tag-counterpart token) end (tag-counterpart end) token) (end-element (sax-producer-consumer self) end (sax-consumer-mode (sax-producer-consumer self))) (pop (parser-path self)) (values nil namespaces)) (t (error 'unexpected-end-tag :expectation (tag-original-name end) :thing (token-string token))))) (defmethod parse-token ((self xml-parser) stream (token proc-instruction) end namespaces) (declare (ignore stream end)) (let ((consumer (sax-producer-consumer self))) (proc-instruction consumer token (sax-consumer-mode consumer)) (values t namespaces))) (defmethod parse-token ((self xml-parser) stream (token entity-declaration) end namespaces) (declare (ignore stream end)) (setf (get-entity self (entity-name token)) (token-string token)) (values t namespaces)) (defmethod parse-token ((self xml-parser) stream (token comment) end namespaces) (declare (ignore stream end)) (values t namespaces)) (defmethod parse-token ((self xml-parser) stream (token dtd-start) end namespaces) (declare (ignore stream end)) (when (dtd-external-p token) (xml-warning "External DTD ignored:~{ ~S~}" (dtd-stuff token))) (values t namespaces)) (defmethod parse-token ((self xml-parser) stream (token dtd-end) end namespaces) (declare (ignore stream end)) (values t namespaces)) (defmethod parse-token ((self xml-parser) stream (token dtd-declaration) end namespaces) (declare (ignore stream end)) (xml-warning "~S ignored" (class-name (class-of token))) (values t namespaces)) (defmethod parse-token ((self xml-parser) stream token end namespaces) (declare (ignore stream end)) (if token (error 'syntax-error :thing token) null token signifies eof (defun parse-from-stream (stream locator parser-class &rest options) (declare (dynamic-extent options)) (let ((parser (apply #'make-instance parser-class options))) (handler-case (values (parse parser stream locator) parser) (xml-error (e) (let ((*readtable* (copy-readtable nil))) (cerror "Keep going" e)))))) (defclass xml-formatter (sax-consumer) ((stream :initarg :stream :initform nil :reader formatter-stream) (level :initform 0 :accessor formatter-level) (indent-delta :initarg :indent-delta :initform 2 :reader formatter-indent-delta))) (defmethod replay ((formatter xml-formatter) events) (dolist (event events) (let ((mode (sax-consumer-mode formatter))) (etypecase event (open-tag (start-element formatter event mode)) (close-tag (end-element formatter (tag-counterpart event) mode)) (string (char-content formatter event mode)))))) (defun reverse-expand-name (name namespaces &aux (nn (length name))) (do-string-dict (prefix uri namespaces) (let ((un (length uri))) (when (and (>= nn un) (string= name uri :end1 un)) (return-from reverse-expand-name (values (if (= nn un) (format nil "~@[~A~]:" prefix) (format nil "~@[~A:~]~A" prefix (let ((n (subseq name un))) (if (char= (char n 0) #\#) (subseq n 1) n)))) t))))) (values name nil)) (defmethod start-element ((self xml-formatter) (tag open-tag) mode) (declare (ignore mode)) (let ((stream (formatter-stream self))) (format stream "~&~V@T<~A" (formatter-level self) (reverse-expand-name (token-string tag) (tag-namespaces tag))) (do-string-dict (attribute value (tag-attributes tag)) (format stream " ~A=\"~A\"" (reverse-expand-name attribute (tag-namespaces tag)) value)) (princ (if (tag-empty-p tag) "/>" #\>) stream) (incf (formatter-level self) (formatter-indent-delta self)))) (defmethod end-element ((self xml-formatter) tag mode) (declare (ignore mode)) (decf (formatter-level self) (formatter-indent-delta self)) (unless (tag-empty-p tag) (format (formatter-stream self) "~&~V@T</~A>" (formatter-level self) (reverse-expand-name (token-string tag) (tag-namespaces tag))))) (defmethod char-content ((self xml-formatter) char-content mode) (declare (ignore mode)) (princ (string-trim '(#\Space #\Tab #\Newline) char-content) (formatter-stream self))) (defmethod start-document ((self xml-formatter) locator) (declare (ignore locator)) (format (formatter-stream self) "~&<?xml version=\"1.0\"?>")) (defclass tree-parser (sax-consumer) ((states :initform nil :accessor parser-states) (package :initarg :package :initform (find-package :keyword) :reader parser-package))) (defun string->keyword (string &optional (package :keyword)) (if package (intern (string-upcase string) package) string)) (defmethod initialize-instance :after ((self tree-parser) &rest args &key producer &allow-other-keys) (declare (ignore args)) (if producer (setf (sax-consumer-producer self) producer (sax-producer-consumer producer) self) (setf (sax-consumer-producer self) (make-instance 'xml-parser :consumer self)))) (defmethod parser-interpret-content ((parser tree-parser) (content string)) content) (defmethod start-element ((parser tree-parser) (tag open-tag) mode) (declare (ignore mode)) (push (list (list (string->keyword (token-string tag) (parser-package parser)))) (parser-states parser))) (defmethod end-element ((parser tree-parser) (tag open-tag) mode) (declare (ignore mode)) (push (reverse (first (pop (parser-states parser)))) (car (first (parser-states parser))))) (defmethod char-content ((parser tree-parser) (content string) mode) (declare (ignore mode)) (push (parser-interpret-content parser content) (car (first (parser-states parser))))) (defmethod parse ((parser tree-parser) stream locator) (setf (parser-states parser) (list (list nil))) (parse (find-first-producer parser) stream locator) (caar (pop (parser-states parser))))
e2239b123fdbc49e485c7ee110d7b0102e3acd5908a1b73211707c4758ba38c2
mikera/core.matrix
implementations.cljc
(ns clojure.core.matrix.implementations "Namespace for management of core.matrix implementations. Users should avoid using these functions directly as they are intended for library and tool writers." (:require [clojure.core.matrix.protocols :as mp] [clojure.core.matrix.macros #?(:clj :refer :cljs :refer-macros) [TODO error]])) ;; ===================================================== ;; Implementation utilities ;; ;; Tools to support the registration / manangement of clojure.core.matrix implementations (def KNOWN-IMPLEMENTATIONS "A map of known core.matrix implementation namespaces. core.matrix will attempt to load these namespaces when an array of the specified keyword type is requested." (array-map :vectorz 'mikera.vectorz.matrix-api :vectorz-opencl 'mikera.vectorz.opencl-api :neanderthal 'uncomplicate.neanderthal.impl.matrix-api :clojure 'clojure.core.matrix.impl.clojure :ndarray 'clojure.core.matrix.impl.ndarray-object :ndarray-double 'clojure.core.matrix.impl.ndarray-double :ndarray-float 'clojure.core.matrix.impl.ndarray :ndarray-long 'clojure.core.matrix.impl.ndarray :persistent-vector 'clojure.core.matrix.impl.persistent-vector :persistent-map 'clojure.core.matrix.impl.sparse-map :sequence 'clojure.core.matrix.impl.sequence :double-array 'clojure.core.matrix.impl.double-array :scalar-wrapper 'clojure.core.matrix.impl.wrappers :slice-wrapper 'clojure.core.matrix.impl.wrappers :nd-wrapper 'clojure.core.matrix.impl.wrappers :dataset 'clojure.core.matrix.impl.dataset :jblas :TODO :clatrix 'clatrix.core :parallel-colt :TODO :ejml :TODO :nd4j 'nd4clj.kiw :ujmp :TODO :weka 'clj-ml.matrix-api :commons-math 'apache-commons-matrix.core :mtj 'cav.mtj.core.matrix :aljabr 'thinktopic.aljabr.core)) (def DEFAULT-IMPLEMENTATION "The default implementation used in core.matrix. Currently set to `:persistent-vector` for maximum compatibility with regular Clojure code." :persistent-vector) (def ^:dynamic *matrix-implementation* "A dynamic var specifying the current core.matrix implementation in use. May be re-bound to temporarily use a different core.matrix implementation." DEFAULT-IMPLEMENTATION) (def ^:dynamic *numeric-implementation* "A dynamic var specifying the current core.matrix numeric implementation in use. May be re-bound to temporarily use a different core.matrix implementation." :ndarray-double) (defonce ^{:doc "A dynamic var supporting debugging option for core.matrix implementers. Currently supported values: :print-registrations - print when core.matrix implementations are registered :reload-namespaces - require :reload implementation namespaces when setting the current implementation" :dynamic true} *debug-options* {:print-registrations false :reload-namespaces false}) (defonce ^{:doc "An atom holding a map of canonical objects for each loaded core.matrix implementation. Canonical objects may be used to invoke protocol methods on an instance of the correct type to get implementation-specific behaviour. Canonical objects are required to support all mandatory core.matrix protocols."} canonical-objects (atom {})) (defn get-implementation-key "Returns the implementation keyword for a given object" ([m] (cond (keyword? m) m (mp/is-scalar? m) nil :else (mp/implementation-key m)))) (defn register-implementation "Registers a matrix implementation for use. Should be called by all implementations when they are loaded, once for each implementation keyword registered. Safe to call multiple times." ([canonical-object] (register-implementation (mp/implementation-key canonical-object) canonical-object)) ([key canonical-object] (when-not (keyword? key) (error "Implementation key must be a Clojure keyword but got: " #?(:clj (class key) :cljs (type key)))) (when (:print-registrations *debug-options*) (println (str "Registering core.matrix implementation [" key "] with canonical object [" #?(:clj (class canonical-object) :cljs (type canonical-object)) "]"))) (swap! canonical-objects assoc key canonical-object))) (defn- try-load-implementation "Attempts to load an implementation for the given keyword. Returns nil if not possible, a non-nil matrix value of the correct implementation otherwise." ([k] #?(:clj (or (@canonical-objects k) (if-let [ns-sym (KNOWN-IMPLEMENTATIONS k)] (try (do (when (:print-registrations *debug-options*) (println (str "Loading core.matrix implementation [" k "] in ns: " ns-sym))) (if (:reload-namespaces *debug-options*) (require :reload ns-sym) (require ns-sym)) (@canonical-objects k)) (catch Throwable t (println "Error loading core.matrix implementation: " ns-sym) (println t))))) :cljs (println "INFO: No dynamic loading of implementations in Clojurescript.\nYou must require an implementation explicitly in a namespace, for example thinktopic.aljabr.core")))) (defn load-implementation "Attempts to load the implementation for a given keyword or matrix object. Returns nil if not possible, a non-nil matrix value of the correct implementation otherwise." ([korm] (if (keyword? korm) (try-load-implementation korm) (try-load-implementation (mp/implementation-key korm))))) (defn get-canonical-object "Gets the canonical object for a specific implementation. The canonical object is used to call implementation-specific protocol functions where required (e.g. creation of new arrays of the correct type for the implementation). Returns nil if the implementation cannot be found." ([] (get-canonical-object *matrix-implementation*)) ([m] (let [k (get-implementation-key m) obj (@canonical-objects k)] (if k (or obj (if (try-load-implementation k) (@canonical-objects k)) (when-not (keyword? m) m) nil) nil)))) (defn get-canonical-object-or-throw "Like get-canonical-object, except it throws an exception if the implementation cannot be found" ([mk] (or (get-canonical-object mk) (error "Cannot find implementation for " mk)))) (defn construct "Attempts to construct an array according to the type of array m. If not possible, returns another array type." ([m data] (or (mp/construct-matrix m data) ;; TODO: use current implementation? (mp/coerce-param m data) (mp/coerce-param [] data)))) (defn set-current-implementation "Sets the currently active core.matrix implementation. Parameter may be - A known keyword for the implementation e.g. :vectorz - An existing instance from the implementation Throws an exception if the implementation cannot be loaded. This is used primarily for functions that construct new matrices, i.e. it determines the implementation used for expressions like: (matrix [[1 2] [3 4]])" ([m] (when (keyword? m) (or (try-load-implementation m) (error "Unable to load matrix implementation: " m))) #?(:clj (alter-var-root (var *matrix-implementation*) (fn [_] (get-implementation-key m))) :cljs (set! *matrix-implementation* (get-implementation-key m)))))
null
https://raw.githubusercontent.com/mikera/core.matrix/0a35f6e3d6d2335cb56f6f3e5744bfa1dd0390aa/src/main/clojure/clojure/core/matrix/implementations.cljc
clojure
===================================================== Implementation utilities Tools to support the registration / manangement of clojure.core.matrix implementations TODO: use current implementation?
(ns clojure.core.matrix.implementations "Namespace for management of core.matrix implementations. Users should avoid using these functions directly as they are intended for library and tool writers." (:require [clojure.core.matrix.protocols :as mp] [clojure.core.matrix.macros #?(:clj :refer :cljs :refer-macros) [TODO error]])) (def KNOWN-IMPLEMENTATIONS "A map of known core.matrix implementation namespaces. core.matrix will attempt to load these namespaces when an array of the specified keyword type is requested." (array-map :vectorz 'mikera.vectorz.matrix-api :vectorz-opencl 'mikera.vectorz.opencl-api :neanderthal 'uncomplicate.neanderthal.impl.matrix-api :clojure 'clojure.core.matrix.impl.clojure :ndarray 'clojure.core.matrix.impl.ndarray-object :ndarray-double 'clojure.core.matrix.impl.ndarray-double :ndarray-float 'clojure.core.matrix.impl.ndarray :ndarray-long 'clojure.core.matrix.impl.ndarray :persistent-vector 'clojure.core.matrix.impl.persistent-vector :persistent-map 'clojure.core.matrix.impl.sparse-map :sequence 'clojure.core.matrix.impl.sequence :double-array 'clojure.core.matrix.impl.double-array :scalar-wrapper 'clojure.core.matrix.impl.wrappers :slice-wrapper 'clojure.core.matrix.impl.wrappers :nd-wrapper 'clojure.core.matrix.impl.wrappers :dataset 'clojure.core.matrix.impl.dataset :jblas :TODO :clatrix 'clatrix.core :parallel-colt :TODO :ejml :TODO :nd4j 'nd4clj.kiw :ujmp :TODO :weka 'clj-ml.matrix-api :commons-math 'apache-commons-matrix.core :mtj 'cav.mtj.core.matrix :aljabr 'thinktopic.aljabr.core)) (def DEFAULT-IMPLEMENTATION "The default implementation used in core.matrix. Currently set to `:persistent-vector` for maximum compatibility with regular Clojure code." :persistent-vector) (def ^:dynamic *matrix-implementation* "A dynamic var specifying the current core.matrix implementation in use. May be re-bound to temporarily use a different core.matrix implementation." DEFAULT-IMPLEMENTATION) (def ^:dynamic *numeric-implementation* "A dynamic var specifying the current core.matrix numeric implementation in use. May be re-bound to temporarily use a different core.matrix implementation." :ndarray-double) (defonce ^{:doc "A dynamic var supporting debugging option for core.matrix implementers. Currently supported values: :print-registrations - print when core.matrix implementations are registered :reload-namespaces - require :reload implementation namespaces when setting the current implementation" :dynamic true} *debug-options* {:print-registrations false :reload-namespaces false}) (defonce ^{:doc "An atom holding a map of canonical objects for each loaded core.matrix implementation. Canonical objects may be used to invoke protocol methods on an instance of the correct type to get implementation-specific behaviour. Canonical objects are required to support all mandatory core.matrix protocols."} canonical-objects (atom {})) (defn get-implementation-key "Returns the implementation keyword for a given object" ([m] (cond (keyword? m) m (mp/is-scalar? m) nil :else (mp/implementation-key m)))) (defn register-implementation "Registers a matrix implementation for use. Should be called by all implementations when they are loaded, once for each implementation keyword registered. Safe to call multiple times." ([canonical-object] (register-implementation (mp/implementation-key canonical-object) canonical-object)) ([key canonical-object] (when-not (keyword? key) (error "Implementation key must be a Clojure keyword but got: " #?(:clj (class key) :cljs (type key)))) (when (:print-registrations *debug-options*) (println (str "Registering core.matrix implementation [" key "] with canonical object [" #?(:clj (class canonical-object) :cljs (type canonical-object)) "]"))) (swap! canonical-objects assoc key canonical-object))) (defn- try-load-implementation "Attempts to load an implementation for the given keyword. Returns nil if not possible, a non-nil matrix value of the correct implementation otherwise." ([k] #?(:clj (or (@canonical-objects k) (if-let [ns-sym (KNOWN-IMPLEMENTATIONS k)] (try (do (when (:print-registrations *debug-options*) (println (str "Loading core.matrix implementation [" k "] in ns: " ns-sym))) (if (:reload-namespaces *debug-options*) (require :reload ns-sym) (require ns-sym)) (@canonical-objects k)) (catch Throwable t (println "Error loading core.matrix implementation: " ns-sym) (println t))))) :cljs (println "INFO: No dynamic loading of implementations in Clojurescript.\nYou must require an implementation explicitly in a namespace, for example thinktopic.aljabr.core")))) (defn load-implementation "Attempts to load the implementation for a given keyword or matrix object. Returns nil if not possible, a non-nil matrix value of the correct implementation otherwise." ([korm] (if (keyword? korm) (try-load-implementation korm) (try-load-implementation (mp/implementation-key korm))))) (defn get-canonical-object "Gets the canonical object for a specific implementation. The canonical object is used to call implementation-specific protocol functions where required (e.g. creation of new arrays of the correct type for the implementation). Returns nil if the implementation cannot be found." ([] (get-canonical-object *matrix-implementation*)) ([m] (let [k (get-implementation-key m) obj (@canonical-objects k)] (if k (or obj (if (try-load-implementation k) (@canonical-objects k)) (when-not (keyword? m) m) nil) nil)))) (defn get-canonical-object-or-throw "Like get-canonical-object, except it throws an exception if the implementation cannot be found" ([mk] (or (get-canonical-object mk) (error "Cannot find implementation for " mk)))) (defn construct "Attempts to construct an array according to the type of array m. If not possible, returns another array type." ([m data] (or (mp/construct-matrix m data) (mp/coerce-param m data) (mp/coerce-param [] data)))) (defn set-current-implementation "Sets the currently active core.matrix implementation. Parameter may be - A known keyword for the implementation e.g. :vectorz - An existing instance from the implementation Throws an exception if the implementation cannot be loaded. This is used primarily for functions that construct new matrices, i.e. it determines the implementation used for expressions like: (matrix [[1 2] [3 4]])" ([m] (when (keyword? m) (or (try-load-implementation m) (error "Unable to load matrix implementation: " m))) #?(:clj (alter-var-root (var *matrix-implementation*) (fn [_] (get-implementation-key m))) :cljs (set! *matrix-implementation* (get-implementation-key m)))))
55216803a81927214c69241320c81be32bcd80919cd4923190cb9d66317dde34
input-output-hk/plutus
Common.hs
-- editorconfig-checker-disable-file # LANGUAGE FlexibleContexts # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ViewPatterns #-} {- | Miscellaneous shared code for benchmarking-related things. -} module PlutusBenchmark.Common ( module Export , Term , getConfig , toAnonDeBruijnTerm , toNamedDeBruijnTerm , compiledCodeToTerm , haskellValueToTerm , benchTermCek , runTermCek , cekResultMatchesHaskellValue ) where import Paths_plutus_benchmark as Export import PlutusTx qualified as Tx import PlutusCore qualified as PLC import PlutusCore.Default import PlutusCore.Evaluation.Machine.ExBudgetingDefaults qualified as PLC import UntypedPlutusCore qualified as UPLC import UntypedPlutusCore.Evaluation.Machine.Cek as Cek import Criterion.Main import Criterion.Types (Config (..)) import System.FilePath | The Criterion configuration returned by ` getConfig ` will cause an HTML report to be generated . If run via stack / cabal this will be written to the ` plutus - benchmark ` directory by default . The -o option can be used to change this , but an absolute path will probably be required ( eg , " -o=$PWD / report.html " ) . to be generated. If run via stack/cabal this will be written to the `plutus-benchmark` directory by default. The -o option can be used to change this, but an absolute path will probably be required (eg, "-o=$PWD/report.html") . -} getConfig :: Double -> IO Config getConfig limit = do templateDir <- getDataFileName ("common" </> "templates") let templateFile = templateDir </> "with-iterations" <.> "tpl" -- Include number of iterations in HTML report pure $ defaultConfig { template = templateFile, reportFile = Just "report.html", timeLimit = limit } type Term = UPLC.Term PLC.NamedDeBruijn DefaultUni DefaultFun () | Given a - named term , give every variable the name " v " . If we later call unDeBruijn , that will rename the variables to things like " v123 " , where 123 is the relevant de Bruijn index . call unDeBruijn, that will rename the variables to things like "v123", where 123 is the relevant de Bruijn index.-} toNamedDeBruijnTerm :: UPLC.Term UPLC.DeBruijn DefaultUni DefaultFun () -> UPLC.Term UPLC.NamedDeBruijn DefaultUni DefaultFun () toNamedDeBruijnTerm = UPLC.termMapNames UPLC.fakeNameDeBruijn | Remove the textual names from a term toAnonDeBruijnTerm :: Term -> UPLC.Term UPLC.DeBruijn DefaultUni DefaultFun () toAnonDeBruijnTerm = UPLC.termMapNames (\(UPLC.NamedDeBruijn _ ix) -> UPLC.DeBruijn ix) {- | Just extract the body of a program wrapped in a 'CompiledCodeIn'. We use this a lot. -} compiledCodeToTerm :: Tx.CompiledCodeIn DefaultUni DefaultFun a -> Term compiledCodeToTerm (Tx.getPlcNoAnn -> UPLC.Program _ _ body) = body | Lift a value to a PLC term . The constraints get a bit out of control if we try to do this over an arbitrary universe . if we try to do this over an arbitrary universe.-} haskellValueToTerm :: Tx.Lift DefaultUni a => a -> Term haskellValueToTerm = compiledCodeToTerm . Tx.liftCode | Convert a de - Bruijn - named UPLC term to a Benchmark benchTermCek :: Term -> Benchmarkable benchTermCek term = nf (runTermCek) $! term -- Or whnf? {- | Just run a term (used for tests etc.) -} runTermCek :: Term -> EvaluationResult Term runTermCek = unsafeExtractEvaluationResult . (\ (fstT,_,_) -> fstT) . runCekDeBruijn PLC.defaultCekParameters Cek.restrictingEnormous Cek.noEmitter type Result = EvaluationResult Term | Evaluate a PLC term and check that the result matches a given value ( perhaps obtained by running the code that the term was compiled from ) . We evaluate the lifted value as well , because lifting may produce reducible terms . The function is polymorphic in the comparison operator so that we can use it with both HUnit Assertions and QuickCheck Properties . (perhaps obtained by running the Haskell code that the term was compiled from). We evaluate the lifted Haskell value as well, because lifting may produce reducible terms. The function is polymorphic in the comparison operator so that we can use it with both HUnit Assertions and QuickCheck Properties. -} cekResultMatchesHaskellValue :: Tx.Lift DefaultUni a => Term -> (Result -> Result -> b) -> a -> b cekResultMatchesHaskellValue term matches value = (runTermCek term) `matches` (runTermCek $ haskellValueToTerm value)
null
https://raw.githubusercontent.com/input-output-hk/plutus/e470420424cc8c8fb9eb140702b39c6dfeb6a443/plutus-benchmark/common/PlutusBenchmark/Common.hs
haskell
editorconfig-checker-disable-file # LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes # # LANGUAGE ViewPatterns # | Miscellaneous shared code for benchmarking-related things. Include number of iterations in HTML report | Just extract the body of a program wrapped in a 'CompiledCodeIn'. We use this a lot. Or whnf? | Just run a term (used for tests etc.)
# LANGUAGE FlexibleContexts # module PlutusBenchmark.Common ( module Export , Term , getConfig , toAnonDeBruijnTerm , toNamedDeBruijnTerm , compiledCodeToTerm , haskellValueToTerm , benchTermCek , runTermCek , cekResultMatchesHaskellValue ) where import Paths_plutus_benchmark as Export import PlutusTx qualified as Tx import PlutusCore qualified as PLC import PlutusCore.Default import PlutusCore.Evaluation.Machine.ExBudgetingDefaults qualified as PLC import UntypedPlutusCore qualified as UPLC import UntypedPlutusCore.Evaluation.Machine.Cek as Cek import Criterion.Main import Criterion.Types (Config (..)) import System.FilePath | The Criterion configuration returned by ` getConfig ` will cause an HTML report to be generated . If run via stack / cabal this will be written to the ` plutus - benchmark ` directory by default . The -o option can be used to change this , but an absolute path will probably be required ( eg , " -o=$PWD / report.html " ) . to be generated. If run via stack/cabal this will be written to the `plutus-benchmark` directory by default. The -o option can be used to change this, but an absolute path will probably be required (eg, "-o=$PWD/report.html") . -} getConfig :: Double -> IO Config getConfig limit = do templateDir <- getDataFileName ("common" </> "templates") pure $ defaultConfig { template = templateFile, reportFile = Just "report.html", timeLimit = limit } type Term = UPLC.Term PLC.NamedDeBruijn DefaultUni DefaultFun () | Given a - named term , give every variable the name " v " . If we later call unDeBruijn , that will rename the variables to things like " v123 " , where 123 is the relevant de Bruijn index . call unDeBruijn, that will rename the variables to things like "v123", where 123 is the relevant de Bruijn index.-} toNamedDeBruijnTerm :: UPLC.Term UPLC.DeBruijn DefaultUni DefaultFun () -> UPLC.Term UPLC.NamedDeBruijn DefaultUni DefaultFun () toNamedDeBruijnTerm = UPLC.termMapNames UPLC.fakeNameDeBruijn | Remove the textual names from a term toAnonDeBruijnTerm :: Term -> UPLC.Term UPLC.DeBruijn DefaultUni DefaultFun () toAnonDeBruijnTerm = UPLC.termMapNames (\(UPLC.NamedDeBruijn _ ix) -> UPLC.DeBruijn ix) compiledCodeToTerm :: Tx.CompiledCodeIn DefaultUni DefaultFun a -> Term compiledCodeToTerm (Tx.getPlcNoAnn -> UPLC.Program _ _ body) = body | Lift a value to a PLC term . The constraints get a bit out of control if we try to do this over an arbitrary universe . if we try to do this over an arbitrary universe.-} haskellValueToTerm :: Tx.Lift DefaultUni a => a -> Term haskellValueToTerm = compiledCodeToTerm . Tx.liftCode | Convert a de - Bruijn - named UPLC term to a Benchmark benchTermCek :: Term -> Benchmarkable benchTermCek term = runTermCek :: Term -> EvaluationResult Term runTermCek = unsafeExtractEvaluationResult . (\ (fstT,_,_) -> fstT) . runCekDeBruijn PLC.defaultCekParameters Cek.restrictingEnormous Cek.noEmitter type Result = EvaluationResult Term | Evaluate a PLC term and check that the result matches a given value ( perhaps obtained by running the code that the term was compiled from ) . We evaluate the lifted value as well , because lifting may produce reducible terms . The function is polymorphic in the comparison operator so that we can use it with both HUnit Assertions and QuickCheck Properties . (perhaps obtained by running the Haskell code that the term was compiled from). We evaluate the lifted Haskell value as well, because lifting may produce reducible terms. The function is polymorphic in the comparison operator so that we can use it with both HUnit Assertions and QuickCheck Properties. -} cekResultMatchesHaskellValue :: Tx.Lift DefaultUni a => Term -> (Result -> Result -> b) -> a -> b cekResultMatchesHaskellValue term matches value = (runTermCek term) `matches` (runTermCek $ haskellValueToTerm value)
24aafb0a0f9711a05983b85d3723087bd097ad118a3607e811def57aec57404a
racket/typed-racket
callcc.rkt
#lang typed/racket (: tag (Prompt-Tagof Integer (Integer -> Integer))) (define tag (make-continuation-prompt-tag)) (define cc : (Option (-> Integer Nothing)) #f) (call-with-continuation-prompt (λ () (+ 1 (call-with-current-continuation (λ ([k : (Integer -> Nothing)]) (set! cc k) (k 1)) tag))) tag (λ ([x : Integer]) (+ 1 x))) (let ([k cc]) (when k (call-with-continuation-prompt (λ () (k 0)) tag (λ ([x : Integer]) (+ 1 x)))))
null
https://raw.githubusercontent.com/racket/typed-racket/0236151e3b95d6d39276353cb5005197843e16e4/typed-racket-test/succeed/callcc.rkt
racket
#lang typed/racket (: tag (Prompt-Tagof Integer (Integer -> Integer))) (define tag (make-continuation-prompt-tag)) (define cc : (Option (-> Integer Nothing)) #f) (call-with-continuation-prompt (λ () (+ 1 (call-with-current-continuation (λ ([k : (Integer -> Nothing)]) (set! cc k) (k 1)) tag))) tag (λ ([x : Integer]) (+ 1 x))) (let ([k cc]) (when k (call-with-continuation-prompt (λ () (k 0)) tag (λ ([x : Integer]) (+ 1 x)))))
26f51a97a0f74630e75a147938bbbed478376a934ef43841be15973e1374ebdf
distrap/lambdadrive
ADCTest.hs
module Main where import Ivory.Tower.Config import Ivory.OS.FreeRTOS.Tower.STM32 import LDrive.Platforms import LDrive.Tests.ADC (app) main :: IO () main = compileTowerSTM32FreeRTOS testplatform_stm32 p $ app (stm32config_clock . testplatform_stm32) testplatform_adc1 testplatform_pwm testplatform_uart testplatform_leds where p topts = getConfig topts testPlatformParser
null
https://raw.githubusercontent.com/distrap/lambdadrive/2bbf6b173fbc1c6d1f809ee4f95ec0bf737d7064/test/ADCTest.hs
haskell
module Main where import Ivory.Tower.Config import Ivory.OS.FreeRTOS.Tower.STM32 import LDrive.Platforms import LDrive.Tests.ADC (app) main :: IO () main = compileTowerSTM32FreeRTOS testplatform_stm32 p $ app (stm32config_clock . testplatform_stm32) testplatform_adc1 testplatform_pwm testplatform_uart testplatform_leds where p topts = getConfig topts testPlatformParser
713cb622a18d03d98fe30445c01e74d4a08803b6a44efc711e0caeb35131f0a4
theHamsta/petalisp-cuda
package.lisp
(defpackage petalisp-cuda.custom-op (:use :cl :petalisp :petalisp.ir :petalisp.core) (:import-from :petalisp.ir :dendrite-cons :ensure-cluster :cluster-dendrites :dendrite-depth :dendrite :copy-dendrite :grow-dendrite :dendrite-shape :make-cluster :make-dendrite :dendrite-transformation :buffer-readers :kernel-sources :dendrite-kernel :dendrite-stem :make-load-instruction :ir-converter-pqueue :ir-converter-cluster-table :ir-converter-scalar-table :stem-kernel :make-store-instruction :finalize-kernel :kernel :*ir-converter*) (:export :lazy-custom-op :lazy-custom-op-execute :custom-op-kernel :custom-op-kernel-execute :custom-op-kernel-p)) (in-package petalisp-cuda.custom-op)
null
https://raw.githubusercontent.com/theHamsta/petalisp-cuda/12b9ee426e14edf492d862d5bd2dbec18ec427c6/src/custom-op/package.lisp
lisp
(defpackage petalisp-cuda.custom-op (:use :cl :petalisp :petalisp.ir :petalisp.core) (:import-from :petalisp.ir :dendrite-cons :ensure-cluster :cluster-dendrites :dendrite-depth :dendrite :copy-dendrite :grow-dendrite :dendrite-shape :make-cluster :make-dendrite :dendrite-transformation :buffer-readers :kernel-sources :dendrite-kernel :dendrite-stem :make-load-instruction :ir-converter-pqueue :ir-converter-cluster-table :ir-converter-scalar-table :stem-kernel :make-store-instruction :finalize-kernel :kernel :*ir-converter*) (:export :lazy-custom-op :lazy-custom-op-execute :custom-op-kernel :custom-op-kernel-execute :custom-op-kernel-p)) (in-package petalisp-cuda.custom-op)
1e83a4eb30c8dfc5768e3b1207bae54677d0afaac068a3b774e9d75c96b0dcf4
bgusach/exercises-htdp2e
ex-267.rkt
#lang htdp/isl (require test-engine/racket-tests) # # # Constants (define $->€ 1.22) # # # Functions ; [List-of Number] -> [List-of Number] ; Converts a list of dollars into a list of euros (check-within (convert-to-euro '(0 1 5)) (list 0 $->€ (* 5 $->€)) 0.01 ) (define (convert-to-euro lo$) (map dollar->euro lo$) ) ; Number -> Number ; Converts an amount of dollars to an amount of euros NOTE: I think the ; exercise wanted that this is a local defined within convert-to-euro but ; it makes more sense if it is at top-level (check-expect (dollar->euro 1) $->€) (define (dollar->euro amount) (* amount $->€) ) ; [List-of Number] -> [List-of Number] Converts a list of into a list of Celsius NOTE : here again , ; fahrenheit->celsius seems useful outside of the context of this ; function, so I place it at top-level (check-within (convertFC '(-50 0 50)) '(-45.56 -17.78 10.00) 0.1 ) (define (convertFC lof) (map fahrenheit->celsius lof) ) ; Number -> Number Converts a temperature into a Celsius temp . (define (fahrenheit->celsius fahr) (* (- fahr 32) 5/9) ) ; [List-of Posn] -> [[List-of Number]] ; Converts a list of Posn into a list of pairs of numbers ; NOTE: here the helper seems pretty specific, so it stays within ; translate lop (check-expect (translate (list (make-posn 1 2) (make-posn 10 12))) '((1 2) (10 12)) ) (define (translate lop) (local (; Posn -> [List-of Number] Returns a 2 - item list with the x and y coordinates of the posn (define (posn->pair pos) (list (posn-x pos) (posn-y pos)) )) ; -- IN -- (map posn->pair lop) )) (test)
null
https://raw.githubusercontent.com/bgusach/exercises-htdp2e/c4fd33f28fb0427862a2777a1fde8bf6432a7690/3-abstraction/ex-267.rkt
racket
[List-of Number] -> [List-of Number] Converts a list of dollars into a list of euros Number -> Number Converts an amount of dollars to an amount of euros NOTE: I think the exercise wanted that this is a local defined within convert-to-euro but it makes more sense if it is at top-level [List-of Number] -> [List-of Number] fahrenheit->celsius seems useful outside of the context of this function, so I place it at top-level Number -> Number [List-of Posn] -> [[List-of Number]] Converts a list of Posn into a list of pairs of numbers NOTE: here the helper seems pretty specific, so it stays within translate lop Posn -> [List-of Number] -- IN --
#lang htdp/isl (require test-engine/racket-tests) # # # Constants (define $->€ 1.22) # # # Functions (check-within (convert-to-euro '(0 1 5)) (list 0 $->€ (* 5 $->€)) 0.01 ) (define (convert-to-euro lo$) (map dollar->euro lo$) ) (check-expect (dollar->euro 1) $->€) (define (dollar->euro amount) (* amount $->€) ) Converts a list of into a list of Celsius NOTE : here again , (check-within (convertFC '(-50 0 50)) '(-45.56 -17.78 10.00) 0.1 ) (define (convertFC lof) (map fahrenheit->celsius lof) ) Converts a temperature into a Celsius temp . (define (fahrenheit->celsius fahr) (* (- fahr 32) 5/9) ) (check-expect (translate (list (make-posn 1 2) (make-posn 10 12))) '((1 2) (10 12)) ) (define (translate lop) (local Returns a 2 - item list with the x and y coordinates of the posn (define (posn->pair pos) (list (posn-x pos) (posn-y pos)) )) (map posn->pair lop) )) (test)
df8b959e9e8d2247719039ceb73ef0f2cc48ff4ded9548eb8520e401338be665
8c6794b6/haskell-sc-scratch
Pinger.hs
------------------------------------------------------------------------------ example from rd . -- module Pinger where import Sound.SC3 import Sound.OpenSoundControl import Control.Monad (when) import System.Environment (getArgs) import Control.Concurrent (forkIO, threadDelay) | Pause current thread for the indicated duration , given in seconds . sleep :: Double -> IO () sleep n = when (n > 1e-4) (threadDelay (floor (n * 1e6))) | Pause current thread until the given utcr time . sleepUntil :: Double -> IO () sleepUntil t = sleep . (t -) =<< utcr at :: Double -> (Double -> IO Double) -> IO t at t f = do n <- f t sleepUntil (n+t) at (n+t) f ping :: UGen ping = out 0 (pan2 (sinOsc ar f 0 * e) p 1) where e = envGen kr 1 a 0 1 RemoveSynth s s = envPerc 1e-3 200e-3 a = control kr "amp" 0.1 f = control kr "freq" 440 p = control kr "pan" 0 latency :: Double latency = 0.01 bundle :: Double -> [OSC] -> OSC bundle t m = Bundle (UTCr $ t + latency) m tu = 1.1389823209 pinger :: Double -> Double -> Double -> IO a pinger freq a c = do now <- utcr let (q,_) = properFraction (now/tu) d0 = tu * (fromIntegral q + 1) at d0 (g freq a c) g :: Double -> Double -> Double -> (Double -> IO Double) g freq a c t = withSC3 $ \fd -> do send fd $ bundle t [s_new "ping" (-1) AddToTail 1 [("pan", c), ("freq", freq), ("amp", a)]] putStrLn "Sending ping" return tu main :: IO () main = withSC3 $ \fd -> do channel <- fmap (read . head) getArgs async fd $ d_recv $ synthdef "ping" $ ping putStrLn "Resetting scsynth" reset fd putStrLn "Starting schedule thread" forkIO (pinger 440 0.1 channel) putStrLn "delaying main thread" pauseThread 30 putStrLn "End of delay, existing"
null
https://raw.githubusercontent.com/8c6794b6/haskell-sc-scratch/22de2199359fa56f256b544609cd6513b5e40f43/Scratch/RD/Pinger.hs
haskell
----------------------------------------------------------------------------
example from rd . module Pinger where import Sound.SC3 import Sound.OpenSoundControl import Control.Monad (when) import System.Environment (getArgs) import Control.Concurrent (forkIO, threadDelay) | Pause current thread for the indicated duration , given in seconds . sleep :: Double -> IO () sleep n = when (n > 1e-4) (threadDelay (floor (n * 1e6))) | Pause current thread until the given utcr time . sleepUntil :: Double -> IO () sleepUntil t = sleep . (t -) =<< utcr at :: Double -> (Double -> IO Double) -> IO t at t f = do n <- f t sleepUntil (n+t) at (n+t) f ping :: UGen ping = out 0 (pan2 (sinOsc ar f 0 * e) p 1) where e = envGen kr 1 a 0 1 RemoveSynth s s = envPerc 1e-3 200e-3 a = control kr "amp" 0.1 f = control kr "freq" 440 p = control kr "pan" 0 latency :: Double latency = 0.01 bundle :: Double -> [OSC] -> OSC bundle t m = Bundle (UTCr $ t + latency) m tu = 1.1389823209 pinger :: Double -> Double -> Double -> IO a pinger freq a c = do now <- utcr let (q,_) = properFraction (now/tu) d0 = tu * (fromIntegral q + 1) at d0 (g freq a c) g :: Double -> Double -> Double -> (Double -> IO Double) g freq a c t = withSC3 $ \fd -> do send fd $ bundle t [s_new "ping" (-1) AddToTail 1 [("pan", c), ("freq", freq), ("amp", a)]] putStrLn "Sending ping" return tu main :: IO () main = withSC3 $ \fd -> do channel <- fmap (read . head) getArgs async fd $ d_recv $ synthdef "ping" $ ping putStrLn "Resetting scsynth" reset fd putStrLn "Starting schedule thread" forkIO (pinger 440 0.1 channel) putStrLn "delaying main thread" pauseThread 30 putStrLn "End of delay, existing"