code
stringlengths
114
1.05M
path
stringlengths
3
312
quality_prob
float64
0.5
0.99
learning_prob
float64
0.2
1
filename
stringlengths
3
168
kind
stringclasses
1 value
defmodule Rill.Consumer do defmodule Defaults do def poll_interval_milliseconds, do: 100 def batch_size, do: 1000 def position_update_interval, do: 100 end defstruct position: 1, timer_ref: nil, messages: [], identifier: nil, handlers: [], stream_name: nil, poll_interval_milliseconds: Defaults.poll_interval_milliseconds(), batch_size: Defaults.batch_size(), condition: nil, session: nil use Rill.Kernel alias Rill.MessageStore.StreamName alias Rill.MessageStore.MessageData.Read alias Rill.Messaging.Handler alias Rill.Logger.Text, as: LogText @scribble tag: :consumer @type t :: %__MODULE__{ position: pos_integer(), timer_ref: nil | term(), messages: list(%Read{}), identifier: String.t(), handlers: list(module()), stream_name: StreamName.t(), poll_interval_milliseconds: pos_integer(), batch_size: pos_integer(), condition: nil | term(), session: nil | Rill.Session.t() } @spec dispatch(state :: t(), pid :: pid()) :: t() def dispatch(%__MODULE__{messages: []} = state, pid) do Log.trace tags: [:dispatch] do "Consumer cleared batch, fetching new messages (PID: #{inspect(pid)})" end GenServer.cast(pid, :fetch) Log.info tags: [:dispatch] do "Consumer fetched new batch (PID: #{inspect(pid)})" end state end def dispatch( %__MODULE__{messages: [_ | _] = messages_data, session: session} = state, pid ) do handlers = state.handlers [message_data | new_messages_data] = messages_data Log.trace tags: [:dispatch] do stream_info = LogText.message_data(message_data) "Consumer dispatching (PID: #{inspect(pid)}, #{stream_info})" end Log.trace tags: [:data, :dispatch] do inspect(message_data, pretty: true) end Enum.each(handlers, fn handler -> Handler.handle(session, handler, message_data) end) GenServer.cast(pid, :dispatch) Log.info tags: [:dispatch] do stream_info = LogText.message_data(message_data) "Consumer dispatching (PID: #{inspect(pid)}, #{stream_info})" end state |> Map.put(:position, message_data.global_position + 1) |> Map.put(:messages, new_messages_data) end @spec listen(state :: t(), pid :: pid()) :: t() def listen(%__MODULE__{} = state, pid) do Log.trace tags: [:dispatch] do "Consumer start listening (PID: #{inspect(pid)})" end interval = state.poll_interval_milliseconds {:ok, ref} = :timer.send_interval(interval, pid, :reminder) GenServer.cast(pid, :fetch) Log.info tags: [:dispatch] do "Consumer listening (PID: #{inspect(pid)})" end Map.put(state, :timer_ref, ref) end @spec unlisten(state :: t()) :: t() def unlisten(%__MODULE__{} = state) do ref = state.timer_ref :timer.cancel(ref) Map.put(state, :timer_ref, nil) end @spec fetch(state :: t(), pid :: pid()) :: {:noreply, t()} def fetch(%__MODULE__{messages: [_ | _]} = state, _pid), do: state def fetch(%__MODULE__{messages: []} = state, pid) do Log.trace tags: [:fetch] do "Consumer fetching messages (PID: #{inspect(pid)})" end session = state.session opts = [ position: state.position, batch_size: state.batch_size, condition: state.condition ] fetched = case session.database.get(session, state.stream_name, opts) do [] -> state new_messages -> GenServer.cast(pid, :dispatch) Map.put(state, :messages, new_messages) end Log.info tags: [:fetch] do "Consumer fetched messages (PID: #{inspect(pid)})" end fetched end defdelegate start_link(initial_state, opts \\ []), to: Rill.Consumer.Server @doc """ - `:handlers` - `:identifier` - `:stream_name` - `:poll_interval_milliseconds` - `:batch_size` - `:session` - `:condition` """ def child_spec(opts, genserver_opts \\ []) do handlers = Keyword.fetch!(opts, :handlers) identifier = Keyword.fetch!(opts, :identifier) stream_name = Keyword.fetch!(opts, :stream_name) session = Keyword.fetch!(opts, :session) poll_interval_milliseconds = Keyword.get( opts, :poll_interval_milliseconds, Defaults.poll_interval_milliseconds() ) batch_size = Keyword.get(opts, :batch_size, Defaults.batch_size()) condition = Keyword.get(opts, :condition) initial_state = %__MODULE__{ handlers: handlers, identifier: identifier, stream_name: stream_name, session: session, poll_interval_milliseconds: poll_interval_milliseconds, batch_size: batch_size, condition: condition } %{ id: __MODULE__.Server, start: {__MODULE__.Server, :start_link, [initial_state, genserver_opts]} } end end
lib/rill/consumer.ex
0.832441
0.402216
consumer.ex
starcoder
defmodule Discord.SortedSet do @moduledoc """ SortedSet provides a fast, efficient, rust-backed data structure that stores terms in Elixir sort order and ensures the uniqueness of members. See the [README](/sorted_set_nif/doc/readme.html) for more details about """ alias Discord.SortedSet.{NifBridge, Types} @type t :: Types.sorted_set() @default_bucket_size 500 @default_capacity @default_bucket_size @doc """ Construct a new SortedSet with a given capacity and bucket size See the [README](/sorted_set_nif/doc/readme.html) for more information about how SortedSet works. ## Capacity The caller can pre-allocate capacity for the data structure, this can be helpful when the initial set's size can be reasonably estimated. The pre-allocation will be for the buckets but not the contents of the buckets, so setting a high capacity and not using it is still memory efficient. ## Bucket Size Internally the SortedSet is a collection of sorted Buckets, this allows the SortedSet to out perform a simpler array of items. The default bucket size was chosen based off of benchmarking to select a size that performs well for most uses. ## Returned Resource Unlike a native Elixir data structure, the data in the SortedSet is held in the NIF's memory space, there are some important caveats to be aware of when using the SortedSet. First, `new/2` returns a `t:reference/0` instead of a `t:struct/0`. This `t:reference/0` can be used to access the SortedSet in subsequent calls. Second, because the data is stored in the NIF's memory space, the data structure acts more like a mutable data structure than a standard immutable data structure. It's best to treat the `t:reference/0` like one would treat an ETS `tid`. """ @spec new(capacity :: pos_integer(), bucket_size :: pos_integer()) :: t() | Types.common_errors() def new(capacity \\ @default_capacity, bucket_size \\ @default_bucket_size) do {:ok, set} = NifBridge.new(capacity, bucket_size) set end @doc """ Construct a new SortedSet from an enumerable. The enumerable does not have to be proper to use this constructor, if the enumerable is proper then the `from_proper_enumerable/2` function should be used as it is slightly faster. See `from_proper_enumerable/2` for a definition of `proper`. """ @spec from_enumerable(terms :: [Types.supported_term()], bucket_size :: pos_integer()) :: t() | Types.common_errors() def from_enumerable(terms, bucket_size \\ @default_bucket_size) do terms |> Enum.sort() |> Enum.dedup() |> from_proper_enumerable(bucket_size) end @doc """ Construct a new SortedSet from a proper enumerable An enumerable is considered proper if it satisfies the following: - Enumerable is sorted - Enumerable contains no duplicates - Enumerable is made up entirely of supported terms This method of construction is much faster than iterative construction. See `from_enumerable/2` for enumerables that are not proper. """ @spec from_proper_enumerable(terms :: [Types.supported_term()], bucket_size :: pos_integer()) :: t() | Types.common_errors() def from_proper_enumerable(terms, buckets_size \\ @default_bucket_size) def from_proper_enumerable([], bucket_size), do: new(@default_capacity, bucket_size) def from_proper_enumerable(terms, bucket_size) do {:ok, set} = NifBridge.empty(Enum.count(terms), bucket_size) terms |> Enum.chunk_every(bucket_size - 1) |> Enum.reduce_while(set, fn chunk, set -> case NifBridge.append_bucket(set, chunk) do {:ok, :ok} -> {:cont, set} {:error, _} = error -> {:halt, error} end end) end @doc """ Adds an item to the set. To retrieve the index of where the item was added, see `index_add/2` There is no performance penalty for requesting the index while adding an item. ## Performance Unlike a hash based set that has O(1) inserts, the SortedSet is O(log(N/B)) + O(log(B)) where `N` is the number of items in the SortedSet and `B` is the Bucket Size. """ @spec add(set :: t(), item :: Types.supported_term()) :: t() | Types.common_errors() def add(set, item) do case NifBridge.add(set, item) do {:ok, _} -> set other -> other end end @doc """ Adds an item to the set, returning the index. If the index is not needed the `add/2` function can be used instead, there is no performance difference between these two functions. ## Performance Unlike a hash based set that has O(1) inserts, the SortedSet is O(log(N/B)) + O(log(B)) where `N` is the number of items in the SortedSet and `B` is the Bucket Size. """ @spec index_add(set :: t(), item :: any()) :: {index :: non_neg_integer() | nil, t()} | Types.common_errors() def index_add(set, item) do case NifBridge.add(set, item) do {:ok, {:added, index}} -> {index, set} {:ok, {:duplicate, _}} -> {nil, set} other -> other end end @doc """ Removes an item from the set. If the item is not present in the set, the set is simply returned. To retrieve the index of where the item was removed from, see `index_remove/2`. There is no performance penalty for requesting the index while removing an item. ## Performance Unlike a hash based set that has O(1) removes, the SortedSet is O(log(N/B)) + O(log(B)) where `N` is the number of items in the SortedSet and `B` is the Bucket Size. """ @spec remove(set :: t(), item :: any()) :: t() | Types.common_errors() def remove(set, item) do case NifBridge.remove(set, item) do {:ok, {:removed, _}} -> set {:error, :not_found} -> set other -> other end end @doc """ Removes an item from the set, returning the index of the item before removal. If the item is not present in the set, the index `nil` is returned along with the set. If the index is not needed the `remove/2` function can be used instead, there is no performance difference between these two functions. ## Performance Unlike a hash based set that has O(1) removes, the SortedSet is O(log(N/B)) + O(log(B)) where `N` is the number of items in the SortedSet and `B` is the Bucket Size. """ @spec index_remove(set :: t(), item :: any()) :: {index :: non_neg_integer(), t()} | Types.common_errors() def index_remove(set, item) do case NifBridge.remove(set, item) do {:ok, {:removed, index}} -> {index, set} {:error, :not_found} -> {nil, set} other -> other end end @doc """ Get the size of a SortedSet This function follows the standard Elixir naming convention, `size/1` take O(1) time as the size is tracked with every addition and removal. """ @spec size(set :: t()) :: non_neg_integer() | Types.common_errors() def size(set) do case NifBridge.size(set) do {:ok, size} -> size other -> other end end @doc """ Converts a SortedSet into a List This operation requires copying the entire SortedSet out of NIF space and back into Elixir space it can be very expensive. """ @spec to_list(set :: t()) :: [Types.supported_term()] | Types.common_errors() def to_list(set) do case NifBridge.to_list(set) do {:ok, result} when is_list(result) -> result other -> other end end @doc """ Retrieve an item at the given index. If the index is out of bounds then the optional default value is returned instead, this defaults to `nil` if not provided. """ @spec at(set :: t(), index :: non_neg_integer(), default :: any()) :: (item_or_default :: Types.supported_term() | any()) | Types.common_errors() def at(set, index, default \\ nil) do case NifBridge.at(set, index) do {:ok, item} -> item {:error, :index_out_of_bounds} -> default {:error, _} = other -> other end end @doc """ Retrieves a slice of the SortedSet starting at the specified index and including up to the specified amount. `slice/3` will return an empty list if the start index is out of bounds. If the `amount` exceeds the number of items from the start index to the end of the set then all terms up to the end of the set will be returned. This means that the length of the list returned by slice will fall into the range of [0, `amount`] """ @spec slice(set :: t(), start :: non_neg_integer(), amount :: non_neg_integer()) :: [Types.supported_term()] | Types.common_errors() def slice(set, start, amount) do case NifBridge.slice(set, start, amount) do {:ok, items} when is_list(items) -> items other -> other end end @doc """ Finds the index of the specified term. Since SortedSet does enforce uniqueness of terms there is no need to worry about which index gets returned, the term either exists in the set or does not exist in the set. If the term exists the index of the term is returned, if not then `nil` is returned. """ @spec find_index(set :: t(), item :: Types.supported_term()) :: non_neg_integer() | nil | Types.common_errors() def find_index(set, item) do case NifBridge.find_index(set, item) do {:ok, index} -> index {:error, :not_found} -> nil other -> other end end @doc """ Returns a string representation of the underlying Rust data structure. This function is mostly provided as a convenience, since the actual data structure is stored in the NIF memory space it can be difficult to introspect the data structure as it changes. This function allows the caller to get the view of the data structure as Rust sees it. """ @spec debug(set :: t()) :: String.t() def debug(set) do NifBridge.debug(set) end @doc """ Helper function to access the `default_capacity` module attribute """ @spec default_capacity() :: pos_integer() def default_capacity, do: @default_capacity @doc """ Helper function to access the `default_bucket_size` module attribute """ @spec default_bucket_size() :: pos_integer() def default_bucket_size, do: @default_bucket_size @doc """ Returns information about this NIF's memory allocations, as reported by jemalloc. """ defdelegate jemalloc_allocation_info, to: NifBridge end
lib/sorted_set.ex
0.875055
0.63477
sorted_set.ex
starcoder
defmodule ExPlasma.Encoding do @moduledoc """ Provides the common encoding functionality we use across all the transactions and clients. """ @doc """ Converts binary and integer values into its hex string equivalent. ## Examples # Convert a raw binary to hex iex> raw = <<29, 246, 47, 41, 27, 46, 150, 159, 176, 132, 157, 153, 217, 206, 65, 226, 241, 55, 0, 110>> iex> ExPlasma.Encoding.to_hex(raw) "0x1df62f291b2e969fb0849d99d9ce41e2f137006e" # Convert an integer to hex iex> ExPlasma.Encoding.to_hex(1) "0x1" """ @spec to_hex(binary | non_neg_integer) :: String.t() def to_hex(non_hex) def to_hex(raw) when is_binary(raw), do: "0x" <> Base.encode16(raw, case: :lower) def to_hex(int) when is_integer(int), do: "0x" <> Integer.to_string(int, 16) @doc """ Converts a hex string into the integer value. ## Examples # Convert a hex string into an integer iex> ExPlasma.Encoding.to_int("0xb") 11 # Convert a binary into an integer iex> ExPlasma.Encoding.to_int(<<11>>) 11 """ @spec to_int(String.t()) :: non_neg_integer def to_int("0x" <> encoded) do {return, ""} = Integer.parse(encoded, 16) return end def to_int(encoded) when is_binary(encoded), do: :binary.decode_unsigned(encoded, :big) @doc """ Converts a hex string into a binary. ## Examples iex> ExPlasma.Encoding.to_binary("0x1dF62f291b2E969fB0849d99D9Ce41e2F137006e") {:ok, <<29, 246, 47, 41, 27, 46, 150, 159, 176, 132, 157, 153, 217, 206, 65, 226, 241, 55, 0, 110>>} """ @spec to_binary(String.t()) :: {:ok, binary} | {:error, :decoding_error} def to_binary("0x" <> unprefixed_hex) do case unprefixed_hex |> String.upcase() |> Base.decode16() do {:ok, binary} -> {:ok, binary} :error -> {:error, :decoding_error} end end @doc """ Throwing version of to_binary/1 ## Examples iex> ExPlasma.Encoding.to_binary!("0x1dF62f291b2E969fB0849d99D9Ce41e2F137006e") <<29, 246, 47, 41, 27, 46, 150, 159, 176, 132, 157, 153, 217, 206, 65, 226, 241, 55, 0, 110>> """ @spec to_binary!(String.t()) :: binary | no_return() def to_binary!("0x" <> _unprefixed_hex = prefixed_hex) do {:ok, binary} = to_binary(prefixed_hex) binary end end
lib/ex_plasma/encoding.ex
0.892557
0.541106
encoding.ex
starcoder
defmodule Exq.Worker.Server do @moduledoc """ Worker process is responsible for the parsing and execution of a Job. It then broadcasts results to Stats / Manager. Currently uses the `terminate` callback to track job success/failure. ## Initialization: * `job_serialized` - Full JSON payload of the Job. * `manager` - Manager process pid. * `queue` - The queue the job came from. * `stats` - Stats process pid. * `namespace` - Redis namespace * `host` - Host name Expects :work message after initialization to kickoff work. """ use GenServer alias Exq.Middleware.Server, as: Middleware alias Exq.Middleware.Pipeline alias Exq.Worker.Metadata defmodule State do defstruct job_serialized: nil, manager: nil, queue: nil, namespace: nil, stats: nil, host: nil, redis: nil, middleware: nil, pipeline: nil, metadata: nil, middleware_state: nil end def start_link( job_serialized, manager, queue, stats, namespace, host, redis, middleware, metadata ) do GenServer.start_link( __MODULE__, {job_serialized, manager, queue, stats, namespace, host, redis, middleware, metadata}, [] ) end @doc """ Kickoff work associated with worker. """ def work(pid) do GenServer.cast(pid, :work) end ## =========================================================== ## GenServer callbacks ## =========================================================== def init({job_serialized, manager, queue, stats, namespace, host, redis, middleware, metadata}) do { :ok, %State{ job_serialized: job_serialized, manager: manager, queue: queue, stats: stats, namespace: namespace, host: host, redis: redis, middleware: middleware, metadata: metadata } } end @doc """ Kickoff work associated with worker. This step handles: * Parsing of JSON object * Preparation of target module Calls :dispatch to then call target module. """ def handle_cast(:work, state) do state = %{state | middleware_state: Middleware.all(state.middleware)} state = %{state | pipeline: before_work(state)} case state |> Map.fetch!(:pipeline) |> Map.get(:terminated, false) do # case done to run the after hooks true -> nil _ -> GenServer.cast(self(), :dispatch) end {:noreply, state} end # Dispatch work to the target module (call :perform method of target). def handle_cast(:dispatch, state) do dispatch_work( state.pipeline.assigns.worker_module, state.pipeline.assigns.job, state.metadata ) {:noreply, state} end # Worker done with normal termination message. def handle_cast({:done, result}, state) do state = if !has_pipeline_after_work_ran?(state.pipeline) do %{state | pipeline: pipeline_after_processed_work(state, result)} else state end {:stop, :normal, state} end def handle_info({:DOWN, _, _, _, :normal}, state) do state = if !has_pipeline_after_work_ran?(state.pipeline) do error = "Worker shutdown" %{state | pipeline: pipeline_after_failed_work(state, error, error)} else state end {:stop, :normal, state} end def handle_info({:DOWN, _, :process, _, error}, state) do error_message = error |> Inspect.Algebra.to_doc(%Inspect.Opts{}) |> Inspect.Algebra.format(%Inspect.Opts{}.width) |> to_string state = if !has_pipeline_after_work_ran?(state.pipeline) do %{state | pipeline: pipeline_after_failed_work(state, error_message, error)} else state end {:stop, :normal, state} end def handle_info(_info, state) do {:noreply, state} end ## =========================================================== ## Internal Functions ## =========================================================== def dispatch_work(worker_module, job, metadata) do # trap exit so that link can still track dispatch without crashing Process.flag(:trap_exit, true) worker = self() {:ok, pid} = Task.start_link(fn -> :ok = Metadata.associate(metadata, self(), job) result = apply(worker_module, :perform, job.args) GenServer.cast(worker, {:done, result}) end) Process.monitor(pid) end defp before_work(state) do %Pipeline{event: :before_work, worker_pid: self()} |> Pipeline.assign_worker_state(state) |> Pipeline.chain(state.middleware_state) end defp pipeline_after_processed_work(state, result) do %Pipeline{event: :after_processed_work, worker_pid: self(), assigns: state.pipeline.assigns} |> Pipeline.assign(:result, result) |> Pipeline.chain(state.middleware_state) end defp pipeline_after_failed_work(state, error_message, error) do %Pipeline{event: :after_failed_work, worker_pid: self(), assigns: state.pipeline.assigns} |> Pipeline.assign(:error_message, error_message) |> Pipeline.assign(:error, error) |> Pipeline.chain(state.middleware_state) end defp has_pipeline_after_work_ran?(pipeline) do Map.has_key?(pipeline, :result) || Map.has_key?(pipeline, :error) end end
lib/exq/worker/server.ex
0.754373
0.434341
server.ex
starcoder
defmodule ShEx.TripleExpressionReference do @moduledoc false def matches(triple_expression_ref, triples, graph, schema, association, state) do triple_expression_ref |> triple_expression_with_id(state) |> ShEx.TripleExpression.matches(triples, graph, schema, association, state) end def min_cardinality(_) do raise "ShEx.TripleExpressions.min_cardinality/1 not supported on references" end def max_cardinality(_) do raise "ShEx.TripleExpressions.max_cardinality/1 not supported on references" end def predicates(triple_expression_ref, state) do triple_expression_ref |> triple_expression_with_id(state) |> ShEx.TripleExpression.predicates(state) end def triple_constraints(triple_expression_ref, state) do triple_expression_ref |> triple_expression_with_id(state) |> ShEx.TripleExpression.triple_constraints(state) end def required_arcs(triple_expression_ref, state) do triple_expression_ref |> triple_expression_with_id(state) |> ShEx.TripleExpression.required_arcs(state) end def triple_expression_with_id(triple_expression_ref, state) do get_in(state, [:labeled_triple_expressions, triple_expression_ref]) || raise "unknown TripleExprLabel: #{inspect(triple_expression_ref)}" end end defimpl ShEx.TripleExpression, for: RDF.IRI do def matches(triple_expression_ref, triples, graph, schema, association, state), do: ShEx.TripleExpressionReference.matches( triple_expression_ref, triples, graph, schema, association, state ) def min_cardinality(triple_expression_ref), do: ShEx.TripleExpressionReference.min_cardinality(triple_expression_ref) def max_cardinality(triple_expression_ref), do: ShEx.TripleExpressionReference.max_cardinality(triple_expression_ref) def predicates(triple_expression_ref, state), do: ShEx.TripleExpressionReference.predicates(triple_expression_ref, state) def triple_constraints(triple_expression_ref, state), do: ShEx.TripleExpressionReference.triple_constraints(triple_expression_ref, state) def required_arcs(triple_expression_ref, state), do: ShEx.TripleExpressionReference.required_arcs(triple_expression_ref, state) end defimpl ShEx.TripleExpression, for: RDF.BlankNode do def matches(triple_expression_ref, triples, graph, schema, association, state), do: ShEx.TripleExpressionReference.matches( triple_expression_ref, triples, graph, schema, association, state ) def min_cardinality(triple_expression_ref), do: ShEx.TripleExpressionReference.min_cardinality(triple_expression_ref) def max_cardinality(triple_expression_ref), do: ShEx.TripleExpressionReference.max_cardinality(triple_expression_ref) def predicates(triple_expression_ref, state), do: ShEx.TripleExpressionReference.predicates(triple_expression_ref, state) def triple_constraints(triple_expression_ref, state), do: ShEx.TripleExpressionReference.triple_constraints(triple_expression_ref, state) def required_arcs(triple_expression_ref, state), do: ShEx.TripleExpressionReference.required_arcs(triple_expression_ref, state) end
lib/shex/shape_expressions/triple_expression_reference.ex
0.735642
0.544196
triple_expression_reference.ex
starcoder
defmodule AMQPX.Receiver.Standard do @doc """ Called on every incoming message. The payload type will depend on the content type of the incoming message and the codec registered for that content type. If there is no matching codec for that content type, the payload will be passed as is. """ @callback handle(payload :: any(), meta :: Map.t()) :: any() @doc """ Takes the result or `c:handle/2` or its crash reason and formats it in a way that a codec can handle. Only used if the incoming message indicates that a reply is necessary. `payload` will be passed through the codec indicated by `mime_type`. A payload with no matching codec for the declared MIME type will be sent as is. A bare payload string will be sent as is with the content type `application/octet-stream`. """ @callback format_response(response :: any(), meta :: Map.t()) :: {mime_type :: :json | :text | String.t(), payload :: any()} | (payload :: any()) @doc """ Tells the receiver whether to requeue messages when `c:handle/2` crashes. Be careful with choosing to always requeue. If the crash is not caused by some transient condition such as a lost database connection, but a permanent one such as a bug in the message handler or a payload that cannot be parsed, this will cause the message to be redelivered indefinitely at the highest rate supported by your hardware, putting high load on the broker, the network, and the host running your application. Consider using `:retry` to break the loop. Defaults to `false` if not implemented. """ @callback requeue?() :: true | false | :once @callback handling_node(payload :: any(), meta :: Map.t()) :: atom() @doc """ Returns a term uniquely identifying this message. Used for tracking retry limits. The function must be deterministic for the tracker to work as intended. """ @callback identity(payload :: any(), meta :: Map.t()) :: term() @doc """ Called when a message has been retried too many times and has been rejected. """ @callback retry_exhausted(payload :: any(), meta :: Map.t()) :: any() @optional_callbacks requeue?: 0, handling_node: 2, identity: 2, retry_exhausted: 2 @moduledoc """ A message handler implementing some sane defaults. This server should not be started directly; use the `AMQPX.Receiver` supervisor instead. Each receiver sets up its own channel and makes sure it is disposed of when the receiver dies. If you're implementing your own receiver, remember to clean up channels to avoid leaking resources and potentially leaving messages stuck in unacked state. Each receiver sets up a single queue and binds it with multiple routing keys, assigning to each key a handler module implementing the `AMQPX.Receiver.Standard` behaviour; read the callback documentation for details. If the arriving message sets the `reply_to` and `correlation_id` attributes, the result of the message handler (or its crash reason) will be sent as a reply message. This is designed to work transparently in conjunction with `AMQPX.RPC`. # Message handler lifetime Each message spawns a `Task` placed under a `Task.Supervisor` with graceful shutdown to help ensure that under normal shutdown all message handlers are allowed to finish their work and send the acks to the broker. `AMQPX` provides a default supervisor process; however, to help ensure that message handlers have access to the resources they need, such as database connections, it is recommended that you start your own `Task.Supervisor`, set ample shutdown time, and place it in your supervision tree after the required resource but before the `AMQPX.Receiver` that will be spawning the handlers. # Codecs `AMQPX` tries to separate message encoding and the business logic of message handlers with codecs. A codec is a module implementing the `AMQPX.Codec` behaviour. The only codec provided out of the box is `AMQPX.Codec.Text`. `:text` is shorthand for "text/plain" and is handled by `AMQPX.Codec.Text` by default. `:json` is recognised as shorthand for `application/json`, but no codec is included in `AMQPX`; however, both `Poison` and `Jason` can be used as codec modules directly if you bundle them in your application. """ use GenServer require Logger defstruct [ :name, :conn, :ch, :shared_ch, :ctag, :default_handler, :direct_handlers, :wildcard_handlers, :task_sup, :codecs, :mime_type, {:log_traffic, false}, :measurer, :retry, :deduplicate ] @type exchange_option :: {:declare, boolean()} | {:durable, boolean()} | {:passive, boolean()} | {:auto_delete, boolean()} | {:internal, boolean()} | {:no_wait, boolean()} | {:arguments, list()} @type exchange_declare_option :: {:name, String.t()} | {:type, atom()} | {:options, list(exchange_option())} @type log_option :: {:enabled, boolean()} | {:remove_headers, list()} @type option :: {:connection, connection_id :: atom()} | {:name, atom()} | {:prefetch, integer()} | {:exchange, {type :: atom(), name :: String.t(), opts :: [exchange_option]} | {type :: atom(), name :: String.t()} | (name :: String.t())} | {:declare_exchanges, list(exchange_declare_option())} | {:queue, nil | (name :: String.t()) | (opts :: Keyword.t()) | {name :: String.t(), opts :: Keyword.t()}} | {:keys, list(String.t()) | %{(routing_key :: String.t() | {String.t(), String.t()}) => handler :: module()}} | {:handler, atom()} | {:codecs, %{(mime_type :: String.t()) => :handler | (codec :: module())}} | {:supervisor, atom()} | {:name, atom()} | {:log_traffic, boolean() | [log_option()]} | {:measurer, module()} | {:retry, [AMQPX.Receiver.Standard.Retry.option()]} | {:deduplicate, [AMQPX.Receiver.Standard.Deduplicate.option()]} @doc false def child_spec(args) do %{ id: Keyword.get(args, :id, __MODULE__), start: {__MODULE__, :start_link, [args]}, shutdown: Keyword.get(args, :shutdown, :infinity) } end @doc """ Starts the process. ## Options * `:prefetch` – set the prefetch count; defaults to 1 * `:exchange` – the exchange to bind to. The exchange is expected to exist; set `:declare` to `true` to create it. Defaults to a durable topic exchange. * `:declare_exchanges` – a list of exchanges to declare during initialization * `:queue` – the queue to consume from. Defaults to an anonymous auto-deleting queue. * `:keys` – a set of routing keys to bind with and their corresponding handler modules, or just a list of keys. The handler modules must implement the `AMQPX.Receiver.Standard` behaviour. If a list is given, the `:handler` option must be set. Topic exchange wildcards '*' and '#' are supported. * `:handler` – the handler to use when no key-specific handler is set * `:codecs` – override the default set of codecs; see the Codecs section for details * `:supervisor` – the named `Task.Supervisor` to use for individual message handlers * `:name` – the name to register the process with """ @spec start_link([option]) :: {:ok, pid()} def start_link(args) do case Keyword.get(args, :name) do name when is_atom(name) and name != nil -> GenServer.start_link(__MODULE__, args, name: name) _ -> GenServer.start_link(__MODULE__, args) end end def handle_handover(name, request), do: GenServer.call(name, {:handle_handover, request}, :infinity) @impl GenServer def init(args) do alias __MODULE__.Retry alias __MODULE__.Deduplicate Process.flag(:trap_exit, true) name = case :erlang.process_info(self(), :registered_name) do {:registered_name, name} -> name _ -> nil end {:ok, conn} = AMQPX.ConnectionPool.get(Keyword.fetch!(args, :connection)) {:ok, ch} = AMQP.Channel.open(conn) {:ok, shared_ch} = AMQPX.SharedChannel.start(ch) :ok = AMQP.Basic.qos(ch, prefetch_count: Keyword.get(args, :prefetch, 1)) exchange_config = Keyword.get(args, :exchange) ex_name = if exchange_config do {ex_type, ex_name, ex_opts} = case exchange_config do spec = {_type, _name, _opts} -> spec {type, name} -> {type, name, [durable: true]} name -> {:topic, name, [durable: true]} end case Keyword.pop(ex_opts, :declare) do {true, ex_opts} -> :ok = AMQP.Exchange.declare(ch, ex_name, ex_type, ex_opts) _ -> nil end ex_name end Keyword.get(args, :declare_exchanges, []) |> declare_exchanges(ch) {q_name, q_opts} = case Keyword.get(args, :queue) do nil -> {"", [auto_delete: true]} name when is_binary(name) -> {name, []} opts when is_list(opts) -> {"", opts} {name, opts} -> {name, opts} end {:ok, %{queue: queue}} = AMQP.Queue.declare(ch, q_name, q_opts) bind = fn {exchange, rk} -> :ok = AMQP.Queue.bind(ch, queue, exchange, routing_key: rk) rk -> unless ex_name do raise "routing key #{rk} expects a default exchange but none was provided" end :ok = AMQP.Queue.bind(ch, queue, ex_name, routing_key: rk) end Keyword.fetch!(args, :keys) |> Enum.map(fn {key, _handler} -> key key -> key end) |> Enum.each(bind) retry = args |> Keyword.get(:retry) |> Retry.init() deduplicate = args |> Keyword.get(:deduplicate) |> Deduplicate.init() {:ok, ctag} = AMQP.Basic.consume(ch, queue) {direct_handlers, wildcard_handlers} = args |> Keyword.get(:keys) |> build_handler_specs() state = %__MODULE__{ name: name, conn: conn, ch: ch, shared_ch: shared_ch, ctag: ctag, default_handler: Keyword.get(args, :handler), direct_handlers: direct_handlers, wildcard_handlers: wildcard_handlers, codecs: Keyword.get(args, :codecs, %{}) |> AMQPX.Codec.codecs(), mime_type: Keyword.get(args, :mime_type), task_sup: Keyword.get(args, :supervisor, AMQPX.Application.task_supervisor()), log_traffic: Keyword.get(args, :log_traffic) |> normalize_log_options(), measurer: Keyword.get(args, :measurer, nil), retry: retry, deduplicate: deduplicate } {:ok, state} end defp normalize_log_options(nil), do: [enabled: false, remove_headers: []] defp normalize_log_options(false), do: [enabled: false, remove_headers: []] defp normalize_log_options(true), do: [enabled: true, remove_headers: []] defp normalize_log_options(list) when is_list(list), do: list defp build_handler_specs(handlers) do grouped_handlers = handlers |> Map.keys() |> Enum.group_by(&wildcard?/1) direct_handler_keys = grouped_handlers |> Map.get(false, []) direct_handlers = handlers |> Map.take(direct_handler_keys) |> build_handler_spec() wildcard_handler_keys = grouped_handlers |> Map.get(true, []) wildcard_handlers = handlers |> Map.take(wildcard_handler_keys) |> build_handler_spec() {direct_handlers, wildcard_handlers} end defp declare_exchanges(specs, ch) do specs |> Enum.each(&declare_exchange(&1, ch)) end defp declare_exchange(spec, ch) do name = Keyword.fetch!(spec, :name) type = Keyword.get(spec, :type, :topic) opts = Keyword.get(spec, :options, durable: true) :ok = AMQP.Exchange.declare(ch, name, type, opts) end defp wildcard?({_exchange, rk}), do: wildcard?(rk) defp wildcard?(rk), do: AMQPX.RoutingKeyMatcher.wildcard?(rk) @impl GenServer def handle_call( {:handle_handover, {handler, payload, meta}}, from, state = %__MODULE__{shared_ch: shared_ch, task_sup: sup} ) do receiver = self() share_ref = make_ref() child = fn -> Process.flag(:trap_exit, true) AMQPX.SharedChannel.share(shared_ch) send(receiver, {:share_acquired, share_ref}) payload |> handler.handle(meta) |> rpc_reply(handler, meta, state) GenServer.reply(from, :ok) end Task.Supervisor.start_child(sup, child) receive do {:share_acquired, ^share_ref} -> :ok # TODO: what to do if it crashes before it can send? end {:noreply, state} end @impl GenServer def handle_info({:basic_consume_ok, %{consumer_tag: ctag}}, state = %__MODULE__{ctag: ctag}) do {:noreply, state} end def handle_info({:basic_cancel, %{consumer_tag: ctag}}, state = %__MODULE__{ctag: ctag}) do {:stop, :unexpected_cancel, state} end def handle_info({:basic_cancel_ok, %{consumer_tag: ctag}}, state = %__MODULE__{ctag: ctag}) do {:noreply, state} end def handle_info({:basic_deliver, payload, meta}, state) do handle_message(payload, meta, state) {:noreply, state} end def handle_info({:channel_died, ch, _}, state = %__MODULE__{ch: ch}) do {:stop, :channel_died, %__MODULE__{state | ch: nil}} end def handle_info(msg, state) do Logger.warn("unexpected message #{inspect(msg)}") {:noreply, state} end @impl GenServer def terminate(_, %__MODULE__{ch: ch, ctag: ctag}) do if ch != nil && :erlang.is_process_alive(ch.pid) do try do AMQP.Basic.cancel(ch, ctag) receive do {:basic_cancel_ok, %{consumer_tag: ^ctag}} -> nil after 1000 -> # react to timeout? nil end catch # the gen call can crash if the channel proc died in the meantime :exit, _ -> nil end end nil end defp get_handler(rk, %__MODULE__{ direct_handlers: direct, wildcard_handlers: wildcard, default_handler: default }) do case direct do %{^rk => handler} -> handler _ -> case wildcard |> Enum.find(fn {k, _} -> handler_match?(rk, k) end) do {_, handler} -> handler _ -> nil end end || default end defp handler_match?(rk, {_exchange, pattern}), do: handler_match?(rk, pattern) defp handler_match?(rk, pattern), do: AMQPX.RoutingKeyMatcher.matches?(rk, pattern) defp handle_message( payload, meta = %{routing_key: rk}, state = %__MODULE__{ log_traffic: log, retry: retry, deduplicate: dedup } ) do alias __MODULE__.Retry alias __MODULE__.Deduplicate if log?(log), do: Logger.info(["RECV ", payload, " | ", inspect(meta |> filter_headers(log))]) handler = get_handler(rk, state) if handler do cond do Deduplicate.already_seen?(payload, meta, handler, dedup) -> ack(state, meta) Retry.exhausted?(payload, meta, handler, retry) -> reject(state, meta) if :erlang.function_exported(handler, :retry_exhausted, 2), do: handler.retry_exhausted(payload, meta) Retry.clear(payload, meta, handler, retry) true -> handle_message(handler, payload, meta, state) end else if log, do: Logger.info(["IGNR | ", inspect(meta)]) reject(state, meta) end end defp handle_message( handler, payload, meta, state = %__MODULE__{ shared_ch: shared_ch, task_sup: sup, measurer: measurer, retry: retry, deduplicate: dedup } ) do alias __MODULE__.Retry alias __MODULE__.Deduplicate receiver = self() share_ref = make_ref() child = fn -> # make the task supervisor wait for us Process.flag(:trap_exit, true) AMQPX.SharedChannel.share(shared_ch) send(receiver, {:share_acquired, share_ref}) handler_fn = handler_fn(handler, payload, meta, state) child_fn = if measurer do fn -> measurer.measure_packet_handler(handler_fn, meta) end else handler_fn end {_, ref} = spawn_monitor(child_fn) receive do {:DOWN, ^ref, _, _, :normal} -> ack(state, meta) Deduplicate.remember(payload, meta, handler, dedup) Retry.clear(payload, meta, handler, retry) {:DOWN, ^ref, _, _, reason} -> requeue = case reason do {:badrpc, _} -> true _ -> requeue?(handler, meta) end if requeue, do: Retry.delay(retry) reject(state, meta, requeue: requeue) if not requeue, do: rpc_reply(reason, handler, meta, state) end end Task.Supervisor.start_child(sup, child) receive do {:share_acquired, ^share_ref} -> :ok # TODO: what to do if it crashes before it can send? end end defp handler_fn( handler, payload, meta, state = %__MODULE__{ name: name, codecs: codecs } ) do fn -> case payload |> AMQPX.Codec.decode(meta, codecs, handler) do {:ok, payload} -> # We only support handover if the process is named, and we assume it to have the same name on all nodes. # Otherwise we don't know who to talk to on the remote node. node = if name != nil && :erlang.function_exported(handler, :handling_node, 2) do handler.handling_node(payload, meta) else Node.self() end if node == Node.self() do payload |> handler.handle(meta) |> rpc_reply(handler, meta, state) else case :rpc.call(node, __MODULE__, :handle_handover, [ name, {handler, payload, meta} ]) do error = {:badrpc, _} -> exit(error) _ -> :ok end end error -> rpc_reply(error, handler, meta, state) end end end defp rpc_reply(data, handler, meta, state) defp rpc_reply( data, handler, meta = %{reply_to: reply_to, correlation_id: correlation_id}, %__MODULE__{ch: ch, codecs: codecs, mime_type: default_mime_type, log_traffic: log} ) when is_binary(reply_to) or is_pid(reply_to) do {mime, payload} = case handler.format_response(data, meta) do {{:mime_type, mime}, payload} -> {mime, payload} payload -> {default_mime_type || "application/octet-stream", payload} end {:ok, payload} = AMQPX.Codec.encode(payload, mime, codecs, handler) if log?(log), do: Logger.info(["SEND ", payload, " | ", inspect(meta |> filter_headers(log))]) send_response(ch, reply_to, payload, AMQPX.Codec.expand_mime_shortcut(mime), correlation_id) end defp rpc_reply(_, _, _, _), do: nil defp send_response(ch, queue, payload, content_type, correlation_id) when is_binary(queue), do: AMQP.Basic.publish(ch, "", queue, payload, content_type: content_type, correlation_id: correlation_id ) defp send_response(_, pid, payload, _, _) when is_pid(pid), do: send(pid, payload) defp ack(%__MODULE__{ch: ch}, %{delivery_tag: dtag}), do: AMQP.Basic.ack(ch, dtag) defp ack(ch, %{delivery_tag: dtag}), do: AMQP.Basic.ack(ch, dtag) defp ack(_, _), do: nil defp reject(ch_or_state, meta), do: reject(ch_or_state, meta, requeue: false) defp reject(%__MODULE__{ch: ch}, %{delivery_tag: dtag}, opts), do: AMQP.Basic.reject(ch, dtag, opts) defp reject(ch, %{delivery_tag: dtag}, opts), do: AMQP.Basic.reject(ch, dtag, opts) defp reject(_, _, _), do: nil defp requeue?(mod, %{redelivered: redelivered}) do if :erlang.function_exported(mod, :requeue?, 0) do case mod.requeue?() do true -> true false -> false :once -> not redelivered end else false end end defp log?(options), do: Keyword.get(options, :enabled, false) defp filter_headers(meta, options) do filtered = Keyword.get(options, :remove_headers, []) headers = case meta[:headers] do headers when is_list(headers) -> headers |> Enum.reject(fn {key, _type, _value} -> key in filtered end) headers -> headers end Map.put(meta, :headers, headers) end defp build_handler_spec(keys) do keys |> Enum.into(%{}, fn {{_exchange, key}, handler} -> {key, handler} spec = {_key, _handler} -> spec key -> {key, nil} end) end end
lib/amqpx/receiver/standard.ex
0.873889
0.408277
standard.ex
starcoder
defmodule Bamboo.GmailAdapter do @moduledoc """ Sends email using the Gmail API with OAuth2 authentication There are a few preconditions that must be met before this adapter can be used to send email: 1. Admin access to a GSuite account 2. Implement [server-side authorization](https://developers.google.com/gmail/api/auth/web-server) 3. Grant the service account domain-wide authority 4. Authorize API client with required scopes Some application settings must be configured. See the [example section](#module-example-config) below. --- ## Configuration | Setting | Description | Required? | | ---------- | ---------- | ---------- | | `adapter` | Bamboo adapter in use (`Bamboo.GmailAdapter`). | Yes | | `sub` | Email address the service account is impersonating (address the email is sent from). If impersonation is not needed, then `nil` (it is likely needed). | Yes | |`sandbox` | Development mode that does not send email. Details of the API call are instead output to the elixir console. | No | | `json` | Google auth crendentials must be provided in JSON format to the `:goth` app. These are generated in the [Google Developers Console](https://console.developers.google.com/). | Yes | #### Note: *Secrets such as the service account sub, and the auth credentials should not be commited to version control.* Instead, pass in via environment variables using a tuple: {:system, "SUB_ADDRESS"} Or read in from a file: "creds.json" |> File.read! --- ## Example Config config :app_name, GmailAdapterTestWeb.Mailer, adapter: Bamboo.GmailAdapter, sub: {:system, "SUB_ADDRESS"}, sandbox: false # Google auth credentials must be provided to the `goth` app config :goth, json: {:system, "GCP_CREDENTIALS"} """ import Bamboo.GmailAdapter.RFC2822, only: [render: 1] alias Bamboo.GmailAdapter.Errors.{ConfigError, TokenError, HTTPError} @gmail_auth_scope "https://www.googleapis.com/auth/gmail.send" @gmail_send_url "https://www.googleapis.com/gmail/v1/users/me/messages/send" @behaviour Bamboo.Adapter def deliver(email, config) do handle_dispatch(email, config) end def handle_config(config) do validate_config_fields(config) end def supports_attachments?, do: true defp handle_dispatch(email, config = %{sandbox: true}) do log_to_sandbox(config, label: "config") log_to_sandbox(email, label: "email") build_message(email) |> render() |> log_to_sandbox(label: "MIME message") |> Base.url_encode64() |> log_to_sandbox(label: "base64url encoded message") get_sub(config) |> get_access_token() |> log_to_sandbox(label: "access token") end defp handle_dispatch(email, config) do message = build_message(email) get_sub(config) |> get_access_token() |> build_request(message) end defp build_message(email) do Mail.build_multipart() |> put_to(email) |> put_cc(email) |> put_bcc(email) |> put_from(email) |> put_subject(email) |> put_text_body(email) |> put_html_body(email) |> put_attachments(email) end defp put_to(message, %{to: recipients}) do recipients = Enum.map(recipients, fn {_, email} -> email end) Mail.put_to(message, recipients) end defp put_cc(message, %{cc: recipients}) do recipients = Enum.map(recipients, fn {_, email} -> email end) Mail.put_cc(message, recipients) end defp put_bcc(message, %{bcc: recipients}) do recipients = Enum.map(recipients, fn {_, email} -> email end) Mail.put_bcc(message, recipients) end defp put_from(message, %{from: {_, sender}}) do Mail.put_from(message, sender) end defp put_subject(message, %{subject: subject}) do Mail.put_subject(message, subject) end defp put_html_body(message, %{html_body: nil}), do: message defp put_html_body(message, %{html_body: html_body}) do Mail.put_html(message, html_body) end defp put_text_body(message, %{text_body: nil}), do: message defp put_text_body(message, %{text_body: text_body}) do Mail.put_text(message, text_body) end defp put_attachments(message, %{attachments: attachments}) do put_attachments_helper(message, attachments) end defp put_attachments_helper(message, [head | tail]) do put_attachments_helper(message, head) |> put_attachments_helper(tail) end defp put_attachments_helper(message, %Bamboo.Attachment{filename: filename, data: data}) do attachment = Mail.Message.build_attachment({filename, data}) |> Mail.Message.put_header(:content_type, "application/octet-stream") |> Mail.Message.put_header(:content_length, byte_size(data)) Mail.Message.put_part(message, attachment) end defp put_attachments_helper(message, _no_attachments) do message end defp build_request(token, message) do header = build_request_header(token) render(message) |> Base.url_encode64() |> build_request_body() |> send_request(header, @gmail_send_url) end defp send_request(body, header, url) do case HTTPoison.post(url, body, header) do {:ok, response} -> {:ok, response} {:error, error} -> handle_error(:http, error) end end # Right now `sub` is the only required field. # TODO: Generalize this function defp validate_config_fields(config = %{sub: _}), do: config defp validate_config_fields(_no_match) do handle_error(:conf, "sub") end defp get_sub(%{sub: sub}) do case sub do {:system, s} -> validate_env_var(s) _ -> sub end end defp validate_env_var(env_var) do case var = System.get_env(env_var) do nil -> handle_error(:env, "Environment variable '#{env_var}' not found") _ -> var end end defp get_access_token(sub) do case Goth.Token.for_scope(@gmail_auth_scope, sub) do {:ok, token} -> Map.get(token, :token) {:error, error} -> handle_error(:auth, error) end end defp handle_error(scope, error) do case scope do :auth -> {:error, TokenError.build_error(message: error)} :http -> {:error, HTTPError.build_error(message: error)} :conf -> {:error, ConfigError.build_error(field: error)} :env -> {:error, ArgumentError.build_error(message: error)} end end defp build_request_header(token) do [Authorization: "Bearer #{token}", "Content-Type": "application/json"] end defp build_request_body(message) do "{\"raw\": \"#{message}\"}" end defp log_to_sandbox(entity, label: label) do IO.puts("[sandbox] <#{label}> #{inspect(entity)}\n") entity end end
lib/bamboo/adapters/gmail_adapter.ex
0.734405
0.526343
gmail_adapter.ex
starcoder
defmodule Oban.Notifier do @moduledoc """ The `Notifier` coordinates listening for and publishing notifications for events in predefined channels. Every Oban supervision tree contains a notifier process, registered as `Oban.Notifier`, which itself maintains a single connection with an app's database. All incoming notifications are relayed through that connection to other processes. ## Channels The notifier recognizes three predefined channels, each with a distinct responsibility: * `gossip` — arbitrary communication between nodes or jobs are sent on the `gossip` channel * `insert` — as jobs are inserted into the database an event is published on the `insert` channel. Processes such as queue producers use this as a signal to dispatch new jobs. * `signal` — instructions to take action, such as scale a queue or kill a running job, are sent through the `signal` channel. The `insert` and `signal` channels are primarily for internal use. Use the `gossip` channel to send notifications between jobs or processes in your application. ## Caveats The notifications system is built on PostgreSQL's `LISTEN/NOTIFY` functionality. Notifications are only delivered **after a transaction completes** and are de-duplicated before publishing. Most applications run Ecto in sandbox mode while testing. Sandbox mode wraps each test in a separate transaction which is rolled back after the test completes. That means the transaction is never committed, which prevents delivering any notifications. To test using notifications you must run Ecto without sandbox mode enabled. ## Examples Broadcasting after a job is completed: defmodule MyApp.Worker do use Oban.Worker @impl Oban.Worker def perform(job) do :ok = MyApp.do_work(job.args) Oban.Notifier.notify(Oban.config(), :gossip, %{complete: job.id}) :ok end end Listening for job complete events from another process: def insert_and_listen(args) do {:ok, job} = args |> MyApp.Worker.new() |> Oban.insert() receive do {:notification, :gossip, %{"complete" => ^job.id}} -> IO.puts("Other job complete!") after 30_000 -> IO.puts("Other job didn't finish in 30 seconds!") end end """ use GenServer import Oban.Breaker, only: [open_circuit: 1, trip_circuit: 3] alias Oban.{Config, Query, Repo} alias Postgrex.Notifications @type option :: {:name, module()} | {:conf, Config.t()} @type channel :: :gossip | :insert | :signal @mappings %{ gossip: "oban_gossip", insert: "oban_insert", signal: "oban_signal" } @channels Map.keys(@mappings) defmodule State do @moduledoc false @enforce_keys [:conf] defstruct [ :conf, :conn, :name, circuit: :enabled, reset_timer: nil, listeners: %{} ] end defguardp is_channel(channel) when channel in @channels @doc false @spec start_link([option]) :: GenServer.on_start() def start_link(opts) do name = Keyword.get(opts, :name, __MODULE__) GenServer.start_link(__MODULE__, Map.new(opts), name: name) end @doc """ Register the current process to receive relayed messages for the provided channels. All messages are received as `JSON` and decoded _before_ they are relayed to registered processes. Each registered process receives a three element notification tuple in the following format: {:notification, channel :: channel(), decoded :: map()} ## Example Register to listen for all `:gossip` channel messages: Oban.Notifier.listen([:gossip]) Listen for messages on all channels: Oban.Notifier.listen([:gossip, :insert, :signal]) """ @spec listen(GenServer.server(), channels :: list(channel())) :: :ok def listen(server \\ Oban, channels) def listen(pid, channels) when is_pid(pid) and is_list(channels) do :ok = validate_channels!(channels) GenServer.call(pid, {:listen, channels}) end def listen(oban_name, channels) when is_atom(oban_name) and is_list(channels) do oban_name |> Oban.Registry.whereis(__MODULE__) |> listen(channels) end @doc """ Broadcast a notification to listeners on all nodes. Notifications are scoped to the configured `prefix`. For example, if there are instances running with the `public` and `private` prefixes, a notification published in the `public` prefix won't be picked up by processes listening with the `private` prefix. ## Example Broadcast a gossip message: Oban.Notifier.notify(Oban.config(), :gossip, %{message: "hi!"}) """ @spec notify(Config.t(), channel :: channel(), payload :: map()) :: :ok def notify(%Config{} = conf, channel, %{} = payload) when is_channel(channel) do Query.notify(conf, @mappings[channel], payload) end @impl GenServer def init(opts) do Process.flag(:trap_exit, true) {:ok, struct!(State, opts), {:continue, :start}} end @impl GenServer def handle_continue(:start, state) do {:noreply, connect_and_listen(state)} end @impl GenServer def handle_info({:DOWN, _ref, :process, pid, _reason}, %State{listeners: listeners} = state) do {:noreply, %{state | listeners: Map.delete(listeners, pid)}} end def handle_info({:notification, _, _, prefixed_channel, payload}, state) do full_channel = prefixed_channel |> String.split(".") |> List.last() channel = reverse_channel(full_channel) decoded = if any_listeners?(state.listeners, full_channel), do: Jason.decode!(payload) if in_scope?(decoded, state.conf) do for {pid, channels} <- state.listeners, full_channel in channels do send(pid, {:notification, channel, decoded}) end end {:noreply, state} end def handle_info({:EXIT, _pid, error}, %State{} = state) do state = trip_circuit(error, [], state) {:noreply, %{state | conn: nil}} end def handle_info(:reset_circuit, %State{circuit: :disabled} = state) do state = state |> open_circuit() |> connect_and_listen() {:noreply, state} end def handle_info(_message, state) do {:noreply, state} end @impl GenServer def handle_call({:listen, channels}, {pid, _}, %State{listeners: listeners} = state) do if Map.has_key?(listeners, pid) do {:reply, :ok, state} else Process.monitor(pid) full_channels = @mappings |> Map.take(channels) |> Map.values() {:reply, :ok, %{state | listeners: Map.put(listeners, pid, full_channels)}} end end # Helpers for {atom, name} <- @mappings do defp reverse_channel(unquote(name)), do: unquote(atom) end defp validate_channels!([]), do: :ok defp validate_channels!([head | tail]) when is_channel(head), do: validate_channels!(tail) defp validate_channels!([head | _]), do: raise(ArgumentError, "unexpected channel: #{head}") defp any_listeners?(listeners, full_channel) do Enum.any?(listeners, fn {_pid, channels} -> full_channel in channels end) end defp in_scope?(%{"ident" => "any"}, _conf), do: true defp in_scope?(%{"ident" => ident}, conf), do: Config.match_ident?(conf, ident) defp in_scope?(_decoded, _conf), do: true defp connect_and_listen(%State{conf: conf, conn: nil} = state) do case Notifications.start_link(Repo.config(conf)) do {:ok, conn} -> for {_, full} <- @mappings, do: Notifications.listen(conn, "#{conf.prefix}.#{full}") %{state | conn: conn} {:error, error} -> trip_circuit(error, [], state) end end defp connect_and_listen(state), do: state end
lib/oban/notifier.ex
0.908964
0.537223
notifier.ex
starcoder
defmodule ExploringMars.MissionRunner do @moduledoc """ File I/O handling module. Reads parameters from an `io_device` (which should be either a file or `:stdio` and runs each mission using the `ExploringMars.Mission` module. This module should change if the specification of how mission parameters are laid out changes. """ alias ExploringMars.Mission alias ExploringMars.Mission.{Coordinate, Position, Instruction} @doc """ Takes an input file, an output file, and tries to read the input file as a mission specification, containing bounds and several missions. Outputs for each mission either an error (if the mission was malformed) or a mission result. For more information on mission results, check the documentation for the `ExploringMars.Mission` module. """ @spec get_bounds_and_run(File.io_device(), File.io_device()) :: :ok def get_bounds_and_run(input, output) do case read_bounds(input) do {:ok, bounds} -> run_missions_in_bounds(bounds, input, output) File.close(input) File.close(output) {_, msg} -> IO.write(output, "Invalid bounds: " <> msg <> "\n") end end # run 0 to N missions, given bounds. # does most of the input and error handling. Should probably be split # into smaller functions. @spec run_missions_in_bounds( Coordinate.t(), File.io_device(), File.io_device() ) :: :ok defp run_missions_in_bounds(bounds, input, output) do case read_position(input) do :eof -> :ok {:no_parse, err} -> IO.write(output, err <> "\n") skip_line_and_keep_going(bounds, input, output) {:ok, position} -> case read_instructions(input) do :eof -> IO.write(output, "Unexpected end of file") {:ok, instructions} -> result = Mission.run(bounds, position, instructions) IO.write(output, Mission.result_to_string(result)) run_missions_in_bounds(bounds, input, output) err -> IO.write(output, "Unexpected error: " <> inspect(err)) end {:invalid_position, pos} -> IO.write(output, "Invalid position: " <> strip_and_join(pos) <> "\n") skip_line_and_keep_going(bounds, input, output) err -> IO.write(output, "Unexpected error: " <> inspect(err) <> "\n") skip_line_and_keep_going(bounds, input, output) end end @spec skip_line_and_keep_going( Coordinate.t(), File.io_device(), File.io_device() ) :: :ok defp skip_line_and_keep_going(bounds, input, output) do if IO.read(input, :line) != :eof do run_missions_in_bounds(bounds, input, output) else IO.write(output, "Unexpected end of file") :ok end end @spec strip_and_join(list(String.t())) :: String.t() defp strip_and_join(strings) do Enum.map(strings, &String.trim/1) |> Enum.join(" ") end @typep bounds_error :: {:invalid_bounds, String.t()} | {:no_parse, String.t()} | IO.nodata() # read bounds from input file @spec read_bounds(File.io_device()) :: {:ok, Coordinate.t()} | bounds_error defp read_bounds(device) do with line when line != :eof <- IO.read(device, :line), [x, y] <- String.split(line, " ") do Coordinate.positive_from_strings(x, String.trim(y, "\n")) else l when is_list(l) -> {:invalid_bounds, strip_and_join(l)} err -> err end end @typep position_error :: {:invalid_position, list(String.t())} | {:no_parse, String.t()} | IO.nodata() # read position from input file @spec read_position(File.io_device()) :: {:ok, Position.t()} | position_error defp read_position(device) do with line when line != :eof <- IO.read(device, :line), [sx, sy, dir] <- String.split(line, " ") do Position.from_strings(sx, sy, String.trim(dir, "\n")) else l when is_list(l) -> {:invalid_position, l} err -> err end end # read instructions from input file as list @spec read_instructions(File.io_device()) :: {:ok, list(Instruction.t())} | IO.nodata() defp read_instructions(device) do case IO.read(device, :line) do line when is_binary(line) -> instructions = String.trim(line, "\n") |> String.graphemes() |> Enum.filter(fn c -> c != " " end) |> Enum.map(&Instruction.from_string/1) {:ok, instructions} err -> err end end end
lib/exploring_mars/mission_runner.ex
0.772745
0.632148
mission_runner.ex
starcoder
defmodule Nebulex.Adapters.Local.Generation do @moduledoc """ Generational garbage collection process. The generational garbage collector manage the heap as several sub-heaps, known as generations, based on age of the objects. An object is allocated in the youngest generation, sometimes called the nursery, and is promoted to an older generation if its lifetime exceeds the threshold of its current generation (defined by option `:gc_interval`). Everytime the GC runs (triggered by `:gc_interval` timeout), a new cache generation is created and the oldest one is deleted. The only way to create new generations is through this module (this server is the metadata owner) calling `new/2` function. When a Cache is created, a generational garbage collector is attached to it automatically, therefore, this server MUST NOT be started directly. ## Options These options are configured through the `Nebulex.Adapters.Local` adapter: * `:gc_interval` - If it is set, an integer > 0 is expected defining the interval time in milliseconds to garbage collection to run, delete the oldest generation and create a new one. If this option is not set, garbage collection is never executed, so new generations must be created explicitly, e.g.: `MyCache.new_generation(opts)`. * `:max_size` - If it is set, an integer > 0 is expected defining the max number of cached entries (cache limit). If it is not set (`nil`), the check to release memory is not performed (the default). * `:allocated_memory` - If it is set, an integer > 0 is expected defining the max size in bytes allocated for a cache generation. When this option is set and the configured value is reached, a new cache generation is created so the oldest is deleted and force releasing memory space. If it is not set (`nil`), the cleanup check to release memory is not performed (the default). * `:gc_cleanup_min_timeout` - An integer > 0 defining the min timeout in milliseconds for triggering the next cleanup and memory check. This will be the timeout to use when either the max size or max allocated memory is reached. Defaults to `10_000` (10 seconds). * `:gc_cleanup_max_timeout` - An integer > 0 defining the max timeout in milliseconds for triggering the next cleanup and memory check. This is the timeout used when the cache starts and there are few entries or the consumed memory is near to `0`. Defaults to `600_000` (10 minutes). """ # State defstruct [ :cache, :telemetry_prefix, :meta_tab, :backend, :backend_opts, :stats_counter, :gc_interval, :gc_heartbeat_ref, :max_size, :allocated_memory, :gc_cleanup_min_timeout, :gc_cleanup_max_timeout, :gc_cleanup_ref ] use GenServer import Nebulex.Helpers alias Nebulex.Adapter alias Nebulex.Adapter.Stats alias Nebulex.Adapters.Local alias Nebulex.Adapters.Local.{Backend, Metadata} @type t :: %__MODULE__{} @type server_ref :: pid | atom | :ets.tid() @type opts :: Nebulex.Cache.opts() ## API @doc """ Starts the garbage collector for the build-in local cache adapter. """ @spec start_link(opts) :: GenServer.on_start() def start_link(opts) do GenServer.start_link(__MODULE__, opts) end @doc """ Creates a new cache generation. Once the max number of generations is reached, when a new generation is created, the oldest one is deleted. ## Options * `:reset_timer` - Indicates if the poll frequency time-out should be reset or not (default: true). ## Example Nebulex.Adapters.Local.Generation.new(MyCache) Nebulex.Adapters.Local.Generation.new(MyCache, reset_timer: false) """ @spec new(server_ref, opts) :: [atom] def new(server_ref, opts \\ []) do reset_timer? = get_option(opts, :reset_timer, "boolean", &is_boolean/1, true) do_call(server_ref, {:new_generation, reset_timer?}) end @doc """ Removes or flushes all entries from the cache (including all its generations). ## Example Nebulex.Adapters.Local.Generation.delete_all(MyCache) """ @spec delete_all(server_ref) :: integer def delete_all(server_ref) do do_call(server_ref, :delete_all) end @doc """ Reallocates the block of memory that was previously allocated for the given `server_ref` with the new `size`. In other words, reallocates the max memory size for a cache generation. ## Example Nebulex.Adapters.Local.Generation.realloc(MyCache, 1_000_000) """ @spec realloc(server_ref, pos_integer) :: :ok def realloc(server_ref, size) do do_call(server_ref, {:realloc, size}) end @doc """ Returns the memory info in a tuple form `{used_mem, total_mem}`. ## Example Nebulex.Adapters.Local.Generation.memory_info(MyCache) """ @spec memory_info(server_ref) :: {used_mem :: non_neg_integer, total_mem :: non_neg_integer} def memory_info(server_ref) do do_call(server_ref, :memory_info) end @doc """ Resets the timer for pushing new cache generations. ## Example Nebulex.Adapters.Local.Generation.reset_timer(MyCache) """ def reset_timer(server_ref) do server_ref |> server() |> GenServer.cast(:reset_timer) end @doc """ Returns the list of the generations in the form `[newer, older]`. ## Example Nebulex.Adapters.Local.Generation.list(MyCache) """ @spec list(server_ref) :: [:ets.tid()] def list(server_ref) do server_ref |> get_meta_tab() |> Metadata.get(:generations, []) end @doc """ Returns the newer generation. ## Example Nebulex.Adapters.Local.Generation.newer(MyCache) """ @spec newer(server_ref) :: :ets.tid() def newer(server_ref) do server_ref |> get_meta_tab() |> Metadata.get(:generations, []) |> hd() end @doc """ Returns the PID of the GC server for the given `server_ref`. ## Example Nebulex.Adapters.Local.Generation.server(MyCache) """ @spec server(server_ref) :: pid def server(server_ref) do server_ref |> get_meta_tab() |> Metadata.fetch!(:gc_pid) end @doc """ A convenience function for retrieving the state. """ @spec get_state(server_ref) :: t def get_state(server_ref) do server_ref |> server() |> GenServer.call(:get_state) end defp do_call(tab, message) do tab |> server() |> GenServer.call(message) end defp get_meta_tab(server_ref) when is_atom(server_ref) or is_pid(server_ref) do Adapter.with_meta(server_ref, fn _, %{meta_tab: meta_tab} -> meta_tab end) end defp get_meta_tab(server_ref), do: server_ref ## GenServer Callbacks @impl true def init(opts) do # Initial state state = struct(__MODULE__, parse_opts(opts)) # Init cleanup timer cleanup_ref = if state.max_size || state.allocated_memory, do: start_timer(state.gc_cleanup_max_timeout, nil, :cleanup) # Timer ref {:ok, ref} = if state.gc_interval, do: {new_gen(state), start_timer(state.gc_interval)}, else: {new_gen(state), nil} {:ok, %{state | gc_cleanup_ref: cleanup_ref, gc_heartbeat_ref: ref}} end defp parse_opts(opts) do # Get adapter metadata adapter_meta = Keyword.fetch!(opts, :adapter_meta) # Add the GC PID to the meta table meta_tab = Map.fetch!(adapter_meta, :meta_tab) :ok = Metadata.put(meta_tab, :gc_pid, self()) # Common validators pos_integer = &(is_integer(&1) and &1 > 0) pos_integer_or_nil = &((is_integer(&1) and &1 > 0) or is_nil(&1)) Map.merge(adapter_meta, %{ backend_opts: Keyword.get(opts, :backend_opts, []), gc_interval: get_option(opts, :gc_interval, "an integer > 0", pos_integer_or_nil), max_size: get_option(opts, :max_size, "an integer > 0", pos_integer_or_nil), allocated_memory: get_option(opts, :allocated_memory, "an integer > 0", pos_integer_or_nil), gc_cleanup_min_timeout: get_option(opts, :gc_cleanup_min_timeout, "an integer > 0", pos_integer, 10_000), gc_cleanup_max_timeout: get_option(opts, :gc_cleanup_max_timeout, "an integer > 0", pos_integer, 600_000) }) end @impl true def handle_call(:delete_all, _from, %__MODULE__{} = state) do size = state |> Map.from_struct() |> Local.execute(:count_all, nil, []) :ok = new_gen(state) :ok = state.meta_tab |> list() |> Enum.each(&state.backend.delete_all_objects(&1)) {:reply, size, %{state | gc_heartbeat_ref: maybe_reset_timer(true, state)}} end def handle_call({:new_generation, reset_timer?}, _from, state) do :ok = new_gen(state) {:reply, :ok, %{state | gc_heartbeat_ref: maybe_reset_timer(reset_timer?, state)}} end def handle_call( :memory_info, _from, %__MODULE__{backend: backend, meta_tab: meta_tab, allocated_memory: allocated} = state ) do {:reply, {memory_info(backend, meta_tab), allocated}, state} end def handle_call({:realloc, mem_size}, _from, state) do {:reply, :ok, %{state | allocated_memory: mem_size}} end def handle_call(:get_state, _from, state) do {:reply, state, state} end @impl true def handle_cast(:reset_timer, state) do {:noreply, %{state | gc_heartbeat_ref: maybe_reset_timer(true, state)}} end @impl true def handle_info(:heartbeat, %__MODULE__{gc_interval: time, gc_heartbeat_ref: ref} = state) do :ok = new_gen(state) {:noreply, %{state | gc_heartbeat_ref: start_timer(time, ref)}} end def handle_info(:cleanup, state) do state = state |> check_size() |> check_memory() {:noreply, state} end def handle_info(_message, state) do {:noreply, state} end defp check_size( %__MODULE__{ meta_tab: meta_tab, max_size: max_size, backend: backend } = state ) when not is_nil(max_size) do meta_tab |> newer() |> backend.info(:size) |> maybe_cleanup(max_size, state) end defp check_size(state), do: state defp check_memory( %__MODULE__{ meta_tab: meta_tab, backend: backend, allocated_memory: allocated } = state ) when not is_nil(allocated) do backend |> memory_info(meta_tab) |> maybe_cleanup(allocated, state) end defp check_memory(state), do: state defp maybe_cleanup( size, max_size, %__MODULE__{ gc_cleanup_max_timeout: max_timeout, gc_cleanup_ref: cleanup_ref, gc_interval: gc_interval, gc_heartbeat_ref: heartbeat_ref } = state ) when size >= max_size do :ok = new_gen(state) %{ state | gc_cleanup_ref: start_timer(max_timeout, cleanup_ref, :cleanup), gc_heartbeat_ref: start_timer(gc_interval, heartbeat_ref) } end defp maybe_cleanup( size, max_size, %__MODULE__{ gc_cleanup_min_timeout: min_timeout, gc_cleanup_max_timeout: max_timeout, gc_cleanup_ref: cleanup_ref } = state ) do cleanup_ref = size |> linear_inverse_backoff(max_size, min_timeout, max_timeout) |> start_timer(cleanup_ref, :cleanup) %{state | gc_cleanup_ref: cleanup_ref} end ## Private Functions defp new_gen(%__MODULE__{ meta_tab: meta_tab, backend: backend, backend_opts: backend_opts, stats_counter: stats_counter }) do # Create new generation gen_tab = Backend.new(backend, meta_tab, backend_opts) # Update generation list case list(meta_tab) do [newer, older] -> # Since the older generation is deleted, update evictions count :ok = Stats.incr(stats_counter, :evictions, backend.info(older, :size)) # Process the older generation: # - Delete previously stored deprecated generation # - Flush the older generation # - Deprecate it (mark it for deletion) :ok = process_older_gen(meta_tab, backend, older) # Update generations Metadata.put(meta_tab, :generations, [gen_tab, newer]) [newer] -> # Update generations Metadata.put(meta_tab, :generations, [gen_tab, newer]) [] -> # update generations Metadata.put(meta_tab, :generations, [gen_tab]) end end # The older generation cannot be removed immediately because there may be # ongoing operations using it, then it may cause race-condition errors. # Hence, the idea is to keep it alive till a new generation is pushed, but # flushing its data before so that we release memory space. By the time a new # generation is pushed, then it is safe to delete it completely. defp process_older_gen(meta_tab, backend, older) do if deprecated = Metadata.get(meta_tab, :deprecated) do # Delete deprecated generation if it does exist _ = Backend.delete(backend, meta_tab, deprecated) end # Flush older generation to release space so it can be marked for deletion true = backend.delete_all_objects(older) # Keep alive older generation reference into the metadata Metadata.put(meta_tab, :deprecated, older) end defp start_timer(time, ref \\ nil, event \\ :heartbeat) do _ = if ref, do: Process.cancel_timer(ref) Process.send_after(self(), event, time) end defp maybe_reset_timer(_, %__MODULE__{gc_interval: nil} = state) do state.gc_heartbeat_ref end defp maybe_reset_timer(false, state) do state.gc_heartbeat_ref end defp maybe_reset_timer(true, %__MODULE__{} = state) do start_timer(state.gc_interval, state.gc_heartbeat_ref) end defp memory_info(backend, meta_tab) do meta_tab |> newer() |> backend.info(:memory) |> Kernel.*(:erlang.system_info(:wordsize)) end defp linear_inverse_backoff(size, max_size, min_timeout, max_timeout) do round((min_timeout - max_timeout) / max_size * size + max_timeout) end end
lib/nebulex/adapters/local/generation.ex
0.913669
0.652131
generation.ex
starcoder
defprotocol FunWithFlags.Group do @moduledoc """ Implement this protocol to provide groups. Group gates are similar to actor gates, but they apply to a category of entities rather than specific ones. They can be toggled on or off for the _name of the group_ (as an atom) instead of a specific term. Group gates take precendence over boolean gates but are overridden by actor gates. The semantics to determine which entities belong to which groups are application specific. Entities could have an explicit list of groups they belong to, or the groups could be abstract and inferred from some other attribute. For example, an `:employee` group could comprise all `%User{}` structs with an email address matching the company domain, or an `:admin` group could be made of all users with `%User{admin: true}`. In order to be affected by a group gate, an entity should implement the `FunWithFlags.Group` protocol. The protocol automatically falls back to a default `Any` implementation, which states that any entity belongs to no group at all. This makes it possible to safely use "normal" actors when querying group gates, and to implement the protocol only for structs and types for which it matters. The protocol can be implemented for custom structs or literally any other type. defmodule MyApp.User do defstruct [:email, admin: false, groups: []] end defimpl FunWithFlags.Group, for: MyApp.User do def in?(%{email: email}, :employee), do: Regex.match?(~r/@mycompany.com$/, email) def in?(%{admin: is_admin}, :admin), do: !!is_admin def in?(%{groups: list}, group_name), do: group_name in list end elisabeth = %User{email: "<EMAIL>", admin: true, groups: [:engineering, :product]} FunWithFlags.Group.in?(elisabeth, :employee) true FunWithFlags.Group.in?(elisabeth, :admin) true FunWithFlags.Group.in?(elisabeth, :engineering) true FunWithFlags.Group.in?(elisabeth, :marketing) false defimpl FunWithFlags.Group, for: Map do def in?(%{group: group_name}, group_name), do: true def in?(_, _), do: false end FunWithFlags.Group.in?(%{group: :dumb_tests}, :dumb_tests) true With the protocol implemented, actors can be used with the library functions: FunWithFlags.disable(:database_access) FunWithFlags.enable(:database_access, for_group: :engineering) """ @fallback_to_any true @doc """ Should return a boolean. The default implementation will always return `false` for any argument. ## Example iex> user = %{name: "bolo", group: :staff} iex> FunWithFlags.Group.in?(data, :staff) true iex> FunWithFlags.Group.in?(data, :superusers) false """ @spec in?(term, atom) :: boolean def in?(item, group) end defimpl FunWithFlags.Group, for: Any do def in?(_, _), do: false end
lib/fun_with_flags/protocols/group.ex
0.899301
0.552841
group.ex
starcoder
defmodule Graphvix.DotHelpers do @moduledoc """ This module contains a set of helper methods for converting Elixir graph data into its DOT representation. """ @doc """ Convert top-level node and edge properties for a graph or subgraph into correct DOT notation. ## Example iex> graph = Graph.new(edge: [color: "green", style: "dotted"], node: [color: "blue"]) iex> DotHelpers.global_properties_to_dot(graph) ~S( node [color="blue"] edge [color="green",style="dotted"]) """ def global_properties_to_dot(graph) do [:node, :edge] |> Enum.map(&_global_properties_to_dot(graph, &1)) |> compact() |> case do [] -> nil global_props -> Enum.join(global_props, "\n") end end @doc """ Converts a list of attributes into a properly formatted list of DOT attributes. ## Examples iex> DotHelpers.attributes_to_dot(color: "blue", shape: "circle") ~S([color="blue",shape="circle"]) """ def attributes_to_dot([]), do: nil def attributes_to_dot(attributes) do [ "[", attributes |> Enum.map(fn {key, value} -> attribute_to_dot(key, value) end) |> Enum.join(","), "]" ] |> Enum.join("") end @doc """ Convert a single atribute to DOT format for inclusion in a list of attributes. ## Examples iex> DotHelpers.attribute_to_dot(:color, "blue") ~S(color="blue") There is one special case this function handles, which is the label for a record using HTML to build a table. In this case the generated HTML label must be surrounded by a set of angle brackets `< ... >` instead of double quotes. iex> DotHelpers.attribute_to_dot(:label, "<table></table>") "label=<<table></table>>" """ def attribute_to_dot(:label, value = "<table" <> _) do ~s(label=<#{value}>) end def attribute_to_dot(key, value) do value = Regex.replace(~r/"/, value, "\\\"") ~s(#{key}="#{value}") end @doc """ Indent a single line or block of text. An optional second argument can be provided to tell the function how deep to indent (defaults to one level). ## Examples iex> DotHelpers.indent("hello") " hello" iex> DotHelpers.indent("hello", 3) " hello" iex> DotHelpers.indent("line one\\n line two\\nline three") " line one\\n line two\\n line three" """ def indent(string, depth \\ 1) def indent(string, depth) when is_bitstring(string) do string |> String.split("\n") |> indent(depth) |> Enum.join("\n") end def indent(list, depth) when is_list(list) do Enum.map(list, fn s -> String.duplicate(" ", depth) <> s end) end @doc """ Maps a collection of vertices or nodes to their correct DOT format. The first argument is a reference to an ETS table or the list of results from an ETS table. The second argument is the function used to format each element in the collection. """ def elements_to_dot(table, formatting_func) when is_reference(table) or is_integer(table) do table |> :ets.tab2list |> elements_to_dot(formatting_func) end def elements_to_dot(list, formatting_func) when is_list(list) do list |> sort_elements_by_id() |> Enum.map(&formatting_func.(&1)) |> compact() |> return_joined_list_or_nil() end @doc """ Returns nil if an empty list is passed in. Returns the elements of the list joined by the optional second parameter (defaults to `\n` otherwise. ## Examples iex> DotHelpers.return_joined_list_or_nil([]) nil iex> DotHelpers.return_joined_list_or_nil([], "-") nil iex> DotHelpers.return_joined_list_or_nil(["a", "b", "c"]) "a\\nb\\nc" iex> DotHelpers.return_joined_list_or_nil(["a", "b", "c"], "-") "a-b-c" """ def return_joined_list_or_nil(list, joiner \\ "\n") def return_joined_list_or_nil([], _joiner), do: nil def return_joined_list_or_nil(list, joiner) do Enum.join(list, joiner) end @doc """ Takes a list of elements returned from the vertex or edge table and sorts them by their ID. This ensures that vertices and edges are written into the `.dot` file in the same order they were added to the ETS tables. This is important as the order of vertices and edges in a `.dot` file can ultimately affect the final layout of the graph. """ def sort_elements_by_id(elements) do Enum.sort_by(elements, fn element -> [[_ | id] | _] = Tuple.to_list(element) id end) end @doc """ Removes all `nil` elements from an list. ## Examples iex> DotHelpers.compact([]) [] iex> DotHelpers.compact(["a", nil, "b", nil, 1]) ["a", "b", 1] """ def compact(enum), do: Enum.reject(enum, &is_nil/1) ## Private defp _global_properties_to_dot(%{global_properties: global_props}, key) do with props <- Keyword.get(global_props, key) do case length(props) do 0 -> nil _ -> indent("#{key} #{attributes_to_dot(props)}") end end end end
lib/graphvix/dot_helpers.ex
0.874654
0.512022
dot_helpers.ex
starcoder
defmodule Wanon.Integration.StateServer do @moduledoc """ Tracks the current state for response sequences. For a given path, there is a sequence of responses. After the sequence is finished the genserver will keep answering with the last one. The replies map contains the endpoint as a key and a list of answers: "/baseINTEGRATION/getUpdates" => [ {:json, File.read!("integration/fixture.1.json")}, {:json_block, "{\"result\":[]}", 5} ], * :json answers with the given json string * :json_block answers with the given json and blocks for x seconds. """ use GenServer defmodule State do @moduledoc """ Internal State for a run. It keeps a list of remaining replies. """ defstruct replies: [], notify: nil end def start_link(replies) do GenServer.start_link(__MODULE__, replies) end def init(replies) do { :ok, %State{ replies: replies |> Enum.map(fn {k, v} -> {k, %{remaining: v, finished: false}} end) |> Enum.into(%{}) } } end def handle_cast(from, state) do {:noreply, %{state | notify: from}} end def handle_call(path, _from, state) do case Map.fetch(state.replies, path) do {:ok, value} -> next_state(state, value, path) :error -> {:reply, :notfound, state} end end defp next_state(state, %{remaining: [value]}, path) do state = put_in(state.replies[path].finished, true) notify( state.notify, Enum.reduce_while(state.replies, true, fn {_, %{finished: true}}, _ -> {:cont, true} {_, %{finished: false}}, _ -> {:halt, false} end) ) {:reply, value, state} end defp next_state(state, %{remaining: [value | tail]}, path) do new_state = put_in(state.replies[path].remaining, tail) {:reply, value, new_state} end defp notify(_, false), do: nil defp notify(pid, true), do: send(pid, :finished) def request(pid, request_path) do GenServer.call(pid, request_path) end @doc """ Tells the state server to notify the current process when it is finished """ def subscribe(pid) do GenServer.cast(pid, self()) end end defmodule Wanon.Integration.TestServer do import Plug.Conn alias Wanon.Integration.StateServer def init(state_server), do: state_server def call(conn, state_server) do {:ok, body, _} = Plug.Conn.read_body(conn) IO.puts(body) state_server |> StateServer.request(conn.request_path) |> reply(conn) end defp reply(:notfound, conn) do conn |> send_resp(404, "") end defp reply({:json_block, body, duration}, conn) do Process.sleep(duration * 1000) reply({:json, body}, conn) end defp reply({:json, body}, conn) do conn |> put_resp_header("Content-Type", "application/json") |> send_resp(200, body) end end defmodule Wanon.Integration.TelegramAPI do alias Wanon.Integration.StateServer alias Wanon.Integration.TestServer @doc """ Configures the state server and launch the telegram API server """ def start(replies) do {:ok, state} = StateServer.start_link(replies) StateServer.subscribe(state) {:ok, _} = Plug.Cowboy.http(TestServer, state, port: 4242) end def stop(), do: Plug.Cowboy.shutdown(TestServer.HTTP) end
integration/support/telegram_api.ex
0.65202
0.520009
telegram_api.ex
starcoder
if Code.ensure_loaded?(Plug) do defmodule Triplex.Plug do @moduledoc """ This module have some basic functions for our triplex plugs. The plugs we have for now are: - `Triplex.ParamPlug` - loads the tenant from a body or query param - `Triplex.SessionPlug` - loads the tenant from a session param - `Triplex.SubdomainPlug` - loads the tenant from the url subdomain - `Triplex.EnsurePlug` - ensures the current tenant is loaded and halts if not """ import Plug.Conn @raw_tenant_assign :raw_current_tenant @doc """ Puts the given `tenant` as an assign on the given `conn`, but only if the tenant is not reserved. The `config` map/struct must have: - `tenant_handler`: function to handle the tenant param. Its return will be used as the tenant. - `assign`: the name of the assign where we must save the tenant. """ def put_tenant(conn, tenant, config) do if conn.assigns[config.assign] do conn else conn = assign(conn, @raw_tenant_assign, tenant) tenant = tenant_handler(tenant, config.tenant_handler) if Triplex.reserved_tenant?(tenant) do conn else assign(conn, config.assign, tenant) end end end @doc """ Ensure the tenant is loaded, and if not, halts the `conn`. The `config` map/struct must have: - `assign`: the name of the assign where we must save the tenant. """ def ensure_tenant(conn, config) do if loaded_tenant = conn.assigns[config.assign] do callback(conn, loaded_tenant, config.callback) else conn |> callback(conn.assigns[@raw_tenant_assign], config.failure_callback) |> halt() end end defp tenant_handler(tenant, nil), do: tenant defp tenant_handler(tenant, handler) when is_function(handler), do: handler.(tenant) defp callback(conn, _, nil), do: conn defp callback(conn, tenant, callback) when is_function(callback), do: callback.(conn, tenant) end end
lib/triplex/plugs/plug.ex
0.712632
0.417895
plug.ex
starcoder
defmodule ESpec.DocExample do @moduledoc """ Defines the 'extract' method with parse module content and return `%ESpec.DocExample{}` structs. The struct is used by 'ESpec.DocTest' module to build the specs. """ @doc """ DocExample struct: lhs - console input, rhs - console output, fun_arity - {fun, arity} tuple, line - line where function is definde, type - define the doc spec type (:test, :error or :inspect). Read 'ESpec.DocTest' doc for more info. """ defstruct lhs: nil, rhs: nil, fun_arity: nil, line: nil, type: :test defmodule(Error, do: defexception([:message])) @doc "Extract module docs and returns a list of %ESpec.DocExample{} structs" def extract(module) do all_docs = Code.get_docs(module, :all) unless all_docs do raise Error, message: "could not retrieve the documentation for module #{inspect(module)}. " <> "The module was not compiled with documentation or its beam file cannot be accessed" end moduledocs = extract_from_moduledoc(all_docs[:moduledoc]) docs = for doc <- all_docs[:docs], doc <- extract_from_doc(doc), do: doc (moduledocs ++ docs) |> Enum.map(&to_struct/1) |> List.flatten() end def to_struct(%{exprs: list, fun_arity: fun_arity, line: line}) do Enum.map(list, &item_to_struct(&1, fun_arity, line)) end defp item_to_struct({lhs, {:test, rhs}}, fun_arity, line) do %__MODULE__{ lhs: String.trim(lhs), rhs: String.trim(rhs), fun_arity: fun_arity, line: line, type: :test } end defp item_to_struct({lhs, {:error, error_module, error_message}}, fun_arity, line) do %__MODULE__{ lhs: String.trim(lhs), rhs: {error_module, error_message}, fun_arity: fun_arity, line: line, type: :error } end defp item_to_struct({lhs, {:inspect, string}}, fun_arity, line) do %__MODULE__{ lhs: String.trim(lhs), rhs: string, fun_arity: fun_arity, line: line, type: :inspect } end defp extract_from_moduledoc({_, doc}) when doc in [false, nil], do: [] defp extract_from_moduledoc({line, doc}) do for test <- extract_tests(line, doc) do %{test | fun_arity: {:moduledoc, 0}} end end defp extract_from_doc({_, _, _, _, doc}) when doc in [false, nil], do: [] defp extract_from_doc({fa, line, _, _, doc}) do for test <- extract_tests(line, doc) do %{test | fun_arity: fa} end end defp extract_tests(line, doc) do lines = String.split(doc, ~r/\n/, trim: false) |> adjust_indent extract_tests(lines, line, "", "", [], true) end defp adjust_indent(lines) do adjust_indent(lines, [], 0, :text) end defp adjust_indent([], adjusted_lines, _indent, _) do Enum.reverse(adjusted_lines) end @iex_prompt ["iex>", "iex("] @dot_prompt ["...>", "...("] defp adjust_indent([line | rest], adjusted_lines, indent, :text) do case String.starts_with?(String.trim_leading(line), @iex_prompt) do true -> adjust_indent([line | rest], adjusted_lines, get_indent(line, indent), :prompt) false -> adjust_indent(rest, adjusted_lines, indent, :text) end end defp adjust_indent([line | rest], adjusted_lines, indent, check) when check in [:prompt, :after_prompt] do stripped_line = strip_indent(line, indent) case String.trim_leading(line) do "" -> raise Error, message: "expected non-blank line to follow iex> prompt" ^stripped_line -> :ok _ -> raise Error, message: "indentation level mismatch: #{inspect(line)}, should have been #{indent} spaces" end if String.starts_with?(stripped_line, @iex_prompt ++ @dot_prompt) do adjust_indent(rest, [stripped_line | adjusted_lines], indent, :after_prompt) else next = if check == :prompt, do: :after_prompt, else: :code adjust_indent(rest, [stripped_line | adjusted_lines], indent, next) end end defp adjust_indent([line | rest], adjusted_lines, indent, :code) do stripped_line = strip_indent(line, indent) cond do stripped_line == "" -> adjust_indent(rest, [stripped_line | adjusted_lines], 0, :text) String.starts_with?(String.trim_leading(line), @iex_prompt) -> adjust_indent([line | rest], adjusted_lines, indent, :prompt) true -> adjust_indent(rest, [stripped_line | adjusted_lines], indent, :code) end end defp get_indent(line, current_indent) do case Regex.run(~r/iex/, line, return: :index) do [{pos, _len}] -> pos nil -> current_indent end end defp strip_indent(line, indent) do length = byte_size(line) - indent if length > 0 do :binary.part(line, indent, length) else "" end end defp extract_tests([], _line, "", "", [], _) do [] end defp extract_tests([], _line, "", "", acc, _) do Enum.reverse(reverse_last_test(acc)) end # End of input and we've still got a test pending. defp extract_tests([], _, expr_acc, expected_acc, [test = %{exprs: exprs} | t], _) do test = %{test | exprs: [{expr_acc, {:test, expected_acc}} | exprs]} Enum.reverse(reverse_last_test([test | t])) end # We've encountered the next test on an adjacent line. Put them into one group. defp extract_tests( [<<"iex>", _::binary>> | _] = list, line, expr_acc, expected_acc, [test = %{exprs: exprs} | t], newtest ) when expr_acc != "" and expected_acc != "" do test = %{test | exprs: [{expr_acc, {:test, expected_acc}} | exprs]} extract_tests(list, line, "", "", [test | t], newtest) end # Store expr_acc and start a new test case. defp extract_tests([<<"iex>", string::binary>> | lines], line, "", expected_acc, acc, true) do acc = reverse_last_test(acc) test = %{line: line, fun_arity: nil, exprs: []} extract_tests(lines, line, string, expected_acc, [test | acc], false) end # Store expr_acc. defp extract_tests([<<"iex>", string::binary>> | lines], line, "", expected_acc, acc, false) do extract_tests(lines, line, string, expected_acc, acc, false) end # Still gathering expr_acc. Synonym for the next clause. defp extract_tests( [<<"iex>", string::binary>> | lines], line, expr_acc, expected_acc, acc, newtest ) do extract_tests(lines, line, expr_acc <> "\n" <> string, expected_acc, acc, newtest) end # Still gathering expr_acc. Synonym for the previous clause. defp extract_tests( [<<"...>", string::binary>> | lines], line, expr_acc, expected_acc, acc, newtest ) when expr_acc != "" do extract_tests(lines, line, expr_acc <> "\n" <> string, expected_acc, acc, newtest) end # Expression numbers are simply skipped. defp extract_tests( [<<"iex(", _::8, string::binary>> | lines], line, expr_acc, expected_acc, acc, newtest ) do extract_tests( ["iex" <> skip_iex_number(string) | lines], line, expr_acc, expected_acc, acc, newtest ) end # Expression numbers are simply skipped redux. defp extract_tests( [<<"...(", _::8, string::binary>> | lines], line, expr_acc, expected_acc, acc, newtest ) do extract_tests( ["..." <> skip_iex_number(string) | lines], line, expr_acc, expected_acc, acc, newtest ) end # Skip empty or documentation line. defp extract_tests([_ | lines], line, "", "", acc, _) do extract_tests(lines, line, "", "", acc, true) end # Encountered an empty line, store pending test defp extract_tests(["" | lines], line, expr_acc, expected_acc, [test = %{exprs: exprs} | t], _) do test = %{test | exprs: [{expr_acc, {:test, expected_acc}} | exprs]} extract_tests(lines, line, "", "", [test | t], true) end # Exception test. defp extract_tests( [<<"** (", string::binary>> | lines], line, expr_acc, "", [test = %{exprs: exprs} | t], newtest ) do test = %{test | exprs: [{expr_acc, extract_error(string, "")} | exprs]} extract_tests(lines, line, "", "", [test | t], newtest) end # Finally, parse expected_acc. defp extract_tests( [expected | lines], line, expr_acc, expected_acc, [test = %{exprs: exprs} | t] = acc, newtest ) do if expected =~ ~r/^#[A-Z][\w\.]*<.*>$/ do expected = expected_acc <> "\n" <> inspect(expected) test = %{test | exprs: [{expr_acc, {:inspect, expected}} | exprs]} extract_tests(lines, line, "", "", [test | t], newtest) else extract_tests(lines, line, expr_acc, expected_acc <> "\n" <> expected, acc, newtest) end end defp extract_error(<<")", t::binary>>, acc) do {:error, Module.concat([acc]), String.trim(t)} end defp extract_error(<<h, t::binary>>, acc) do extract_error(t, <<acc::binary, h>>) end defp skip_iex_number(<<")", ">", string::binary>>) do ">" <> string end defp skip_iex_number(<<_::8, string::binary>>) do skip_iex_number(string) end defp reverse_last_test([]), do: [] defp reverse_last_test([test = %{exprs: exprs} | t]) do test = %{test | exprs: Enum.reverse(exprs)} [test | t] end end
lib/espec/doc_example.ex
0.720663
0.569553
doc_example.ex
starcoder
defmodule Thrift do @moduledoc ~S""" [Thrift](https://thrift.apache.org/) implementation for Elixir including a Thrift IDL parser, a code generator, and an RPC system ## Thrift IDL Parsing `Thrift.Parser` parses [Thrift IDL](https://thrift.apache.org/docs/idl) into an abstract syntax tree used for code generation. You can also work with `Thrift.AST` directly to support additional use cases, such as building linters or analysis tools. ## Code Generation `Mix.Tasks.Compile.Thrift` is a Mix compiler task that automates Thrift code generation. To use it, add `:thrift` to your project's `:compilers` list. For example: compilers: [:thrift | Mix.compilers] It's important to add `:thrift` *before* the `:elixir` compiler entry. The Thrift compiler generates Elixir source files, which are in turn compiled by the `:elixir` compiler. Configure the compiler using a keyword list under the top-level `:thrift` key. The only required compiler option is `:files`, which defines the list of Thrift files to compile. See `Mix.Tasks.Compile.Thrift` for the full set of available options. By default, the generated Elixir source files will be written to the `lib` directory, but you can change that using the `output_path` option. In this example, we gather all of the `.thrift` files under the `thrift` directory and write our output files to the `lib/generated` directory: defmodule MyProject.Mixfile do # ... def project do [ # ... compilers: [:thrift | Mix.compilers], thrift: [ files: Path.wildcard("thrift/**/*.thrift"), output_path: "lib/generated" ] ] end end You can also use the `Mix.Tasks.Thrift.Generate` Mix task to generate code on-demand. By default, it uses the same project configuration as the compiler task above, but options can also be specified using command line arguments. ### Thrift Definitions Given some Thrift type definitions: ```thrift namespace elixir Thrift.Test exception UserNotFound { 1: string message } struct User { 1: i64 id, 2: string username, } service UserService { bool ping(), User getUser(1: i64 id) throws (1: UserNotFound e), bool delete(1: i64 id), } ``` ... the generated code will be placed in the following modules under `lib/thrift/`: Definition | Module ------------------------- | ----------------------------------------------- `User` struct | `Thrift.Test.User` *└ binary protocol* | `Thrift.Test.User.BinaryProtocol` `UserNotFound` exception | `Thrift.Test.UserNotFound` *└ binary protocol* | `Thrift.Test.UserNotFound.BinaryProtocol` `UserService` service | `Thrift.Test.UserService.Handler` *└ binary framed client* | `Thrift.Test.UserService.Binary.Framed.Client` *└ binary framed server* | `Thrift.Test.UserService.Binary.Framed.Server` ### Namespaces The generated modules' namespace is determined by the `:namespace` compiler option, which defaults to `Thrift.Generated`. Individual `.thrift` files can specify their own namespace using the `namespace` keyword, taking precedence over the compiler's value. ```thrift namespace elixir Thrift.Test ``` Unfortunately, the Apache Thrift compiler will produce a warning on this line because it doesn't recognize `elixir` as a supported language. While that warning is benign, it can be annoying. For that reason, you can also specify your Elixir namespace as a "magic" namespace comment: ```thrift #@namespace elixir Thrift.Test ``` This alternate syntax is [borrowed from Scrooge][scrooge-namespaces], which uses the same trick for defining Scala namespaces. [scrooge-namespaces]: https://twitter.github.io/scrooge/Namespaces.html ## Clients Service clients are built on `Thrift.Binary.Framed.Client`. This module uses the `Connection` behaviour to implement network state handling. In practice, you won't be interacting with this low-level module directly, however. A client interface module is generated for each service. This is much more convenient to use from application code because it provides distinct Elixir functions for each Thrift service function. It also handles argument packing, return value unpacking, and other high-level conversions. In this example, this generated module is `Thrift.Test.UserService.Binary.Framed.Client`. Each generated client function comes in two flavors: a standard version (e.g. `Client.get_user/3`) that returns `{:ok, response}` or `{:error, reason}`, and a *bang!* variant (e.g. `Client.get_user!/3`) that raises an exception on errors. iex> alias Thrift.Test.UserService.Binary.Framed.Client iex> {:ok, client} = Client.start_link("localhost", 2345, []) iex> {:ok, user} = Client.get_user(client, 123) {:ok, %Thrift.Test.User{id: 123, username: "user"}} Note that the generated function names use [Elixir's naming conventions] [naming], so `getUser` becomes `get_user`. [naming]: http://elixir-lang.org/docs/stable/elixir/naming-conventions.html ## Servers Thrift servers are a little more involved because you need to create a module to handle the work. Fortunately, a `Behaviour` is generated for each server (complete with typespecs). Use the `@behaviour` module attribute, and the compiler will tell you about any functions you might have missed. defmodule UserServiceHandler do @behaviour Thrift.Test.UserService.Handler def ping, do: true def get_user(user_id) do case Backend.find_user_by_id(user_id) do {:ok, user} -> user {:error, _} -> raise Thrift.Test.UserNotFound.exception message: "could not find user with id #{user_id}" end end def delete(user_id) do Backend.delete_user(user_id) == :ok end end To start the server: {:ok, pid} = Thrift.Test.UserService.Binary.Framed.Server.start_link(UserServiceHandler, 2345, []) ... and all RPC calls will be delegated to `UserServiceHandler`. The server defines a Supervisor, which can be added to your application's supervision tree. When adding the server to your applications supervision tree, use the `supervisor` function rather than the `worker` function. """ @typedoc "Thrift data types" @type data_type :: :bool | :byte | :i8 | :i16 | :i32 | :i64 | :double | :string | :binary | {:map, data_type, data_type} | {:set, data_type} | {:list, data_type} @type i8 :: -128..127 @type i16 :: -32_768..32_767 @type i32 :: -2_147_483_648..2_147_483_647 @type i64 :: -9_223_372_036_854_775_808..9_223_372_036_854_775_807 @type double :: float() @typedoc "Thrift message types" @type message_type :: :call | :reply | :exception | :oneway @doc """ Returns a list of atoms, each of which is a name of a Thrift primitive type. """ @spec primitive_names() :: [Thrift.Parser.Types.Primitive.t()] def primitive_names do [:bool, :i8, :i16, :i32, :i64, :binary, :double, :byte, :string] end defmodule NaN do @moduledoc """ A struct that represents [IEEE-754 NaN](https://en.wikipedia.org/wiki/NaN) values. """ @type t :: %NaN{ sign: 0 | 1, # 2^52 - 1 fraction: 1..4_503_599_627_370_495 } defstruct sign: nil, fraction: nil end end
lib/thrift.ex
0.912789
0.686048
thrift.ex
starcoder
defmodule Grizzly.ZWave.CommandClasses.SceneActuatorConf do @moduledoc """ "SceneActuatorConf" Command Class The Scene Actuator Configuration Command Class is used to configure scenes settings for a node supporting an actuator Command Class, e.g. a multilevel switch, binary switch etc. """ @behaviour Grizzly.ZWave.CommandClass alias Grizzly.ZWave.DecodeError @type dimming_duration :: :instantly | [seconds: 1..127] | [minutes: 1..127] | :factory_settings @type level :: :on | :off | 1..99 @impl true def byte(), do: 0x2C @impl true def name(), do: :scene_actuator_conf @spec dimming_duration_to_byte(dimming_duration) :: byte def dimming_duration_to_byte(:instantly), do: 0 def dimming_duration_to_byte(:factory_settings), do: 255 def dimming_duration_to_byte(seconds: seconds) when seconds in 1..127, do: seconds # 0x80..0xFE 1 minute (0x80) to 127 minutes (0xFE) in 1 minute resolution. def dimming_duration_to_byte(minutes: minutes) when minutes in 1..127, do: 0x7F + minutes @spec dimming_duration_from_byte(byte) :: {:ok, dimming_duration} | {:error, Grizzly.ZWave.DecodeError.t()} def dimming_duration_from_byte(0), do: {:ok, :instantly} def dimming_duration_from_byte(255), do: {:ok, :factory_settings} def dimming_duration_from_byte(byte) when byte in 1..127, do: {:ok, [seconds: byte]} def dimming_duration_from_byte(byte) when byte in 0x80..0xFE, do: {:ok, [minutes: byte - 0x7F]} def dimming_duration_from_byte(byte), do: {:error, %DecodeError{param: :dimming_duration, value: byte}} @spec level_to_byte(level) :: byte def level_to_byte(:on), do: 0xFF def level_to_byte(:off), do: 0x00 def level_to_byte(byte) when byte in 1..99, do: byte @spec level_from_byte(byte) :: {:ok, level} | {:error, Grizzly.ZWave.DecodeError.t()} def level_from_byte(0), do: {:ok, :off} def level_from_byte(0xFF), do: {:ok, :on} def level_from_byte(byte) when byte in 1..99, do: {:ok, byte} def level_from_byte(byte), do: {:error, %DecodeError{param: :level, value: byte}} end
lib/grizzly/zwave/command_classes/scene_actuator_conf.ex
0.867836
0.466116
scene_actuator_conf.ex
starcoder
defmodule Chronex do ##== Preamble =========================================================== @moduledoc """ # Chronex A small library to seamlessly add code instrumentation to your Elixir projects. The documentation for this project is available at [HexDocs](https://hexdocs.pm/chronex/api-reference.html). ## Quick Start `Chronex` implements a dead simple API consisting of only three functions, `bind/3`, `unbind/3` and `bound?/3`. All three functions take 3 arguments as input. A module name, a function name and an arity. These three arguments are used to identify the target function. `bind/3` is used to attach a stopwatch to the given function. `unbind/3` is used to detach a stopwatch from the given function. Last but not least, `bound?/3` is used to check if the given function has a stopwatch attach to it. > Chronex needs write access to the beam files where the target functions > are implemented. Thus, you will need to run as root should you want to > experiment adding code instrumentation to core functions. ```elixir str = "Hello, world!" String2.length(str) # => 13 # Attach a stopwatch to String2.length/1 :ok = Chronex.bind(String2, :length, 1) true = Chronex.bound?(String2, :length, 1) String2.length(str) # STDOUT: 15:53:09.917 [debug] chronex | hook=:before mfa="Elixir.String2.length/1" args=["Hello, world!"] uuid="39c120fa-3264-11e8-afec-600308a32e10" # STDOUT: chronex | hook=:after_return mfa="Elixir.String2.length/1" return=13 duration=0.003 uuid="39c120fa-3264-11e8-afec-600308a32e10" # => 13 # Detach the stopwatch from String2.length/1 :ok = Chronex.unbind(String2, :length, 1) false = Chronex.bound?(String2, :length, 1) String2.length(str) # => 13 ``` ## Backends `Chronex` implements four hooks: - `before` - Executed before the target function is called. - `after_return` - Executed right after the target function returns. - `after_throw` - Executed right after the target function throws a value (i.e. `catch` clause in a `try` block). - `after_raise` - Executed right after the target function raises an error (i.e. `rescue` clause in a `try` block). `Chronex` ships with a `Logger` backend that can be used to log interesting information surrounding the invocation of the instrumented functions. New backends can easily be implemented by simply writting a module that implements the four hooks listed above. To configure the list of backends, just do as follows: ``` config :chronex, backends: [ Chronex.Backends.Logger ] ``` Note that you can have more than one backend enabled at the same time. To configure the log level of the Logger backend, just add the following line to your config file: ```elixir config :chronex, Chronex.Backends.Logger, log_level: :debug ``` """ @prefix "#chronex" ##== API ================================================================ @doc """ Attach a stopwatch to the given function. The stopwatch is started on every function call targetting the given function. It measures how long it takes for the given function to run. All measurements are handled by the Logger application. """ @spec bind(atom(), atom(), non_neg_integer()) :: :ok | {:error, :bound} def bind(m, f0, a) do case bound?(m, f0, a) do true -> {:error, :bound} false -> f1 = fname(f0) args = args(a) fun = {:function, 0, f0, a, [{:clause, 0, args, [], [{:match, 0, {:var, 0, :c@0}, {:call, 0, {:remote, 0, {:atom, 0, Keyword}, {:atom, 0, :put}}, [{nil, 0}, {:atom, 0, :m}, {:atom, 0, m}]}}, {:match, 0, {:var, 0, :c@1}, {:call, 0, {:remote, 0, {:atom, 0, Keyword}, {:atom, 0, :put}}, [{:var, 0, :c@0}, {:atom, 0, :f}, {:atom, 0, f0}]}}, {:match, 0, {:var, 0, :c@2}, {:call, 0, {:remote, 0, {:atom, 0, Keyword}, {:atom, 0, :put}}, [{:var, 0, :c@1}, {:atom, 0, :a}, {:integer, 0, a}]}}, {:match, 0, {:var, 0, :c@3}, {:call, 0, {:remote, 0, {:atom, 0, Keyword}, {:atom, 0, :put}}, [{:var, 0, :c@2}, {:atom, 0, :uuid}, {:call, 0, {:remote, 0, {:atom, 0, UUID}, {:atom, 0, :uuid1}}, []}]}}, {:call, 0, {:remote, 0, {:atom, 0, Chronex.Backends}, {:atom, 0, :before}}, [list_to_cons(args), {:var, 0, :c@3}]}, {:match, 0, {:var, 0, :t0}, {:call, 0, {:remote, 0, {:atom, 0, System}, {:atom, 0, :monotonic_time}}, []}}, {:try, 0, [{:match, 0, {:var, 0, :v}, {:call, 0, {:atom, 0, f1}, args}}, {:match, 0, {:var, 0, :t1}, {:call, 0, {:remote, 0, {:atom, 0, System}, {:atom, 0, :monotonic_time}}, []}}, {:match, 0, {:var, 0, :t}, {:call, 0, {:remote, 0, {:atom, 0, Chronex.Utils}, {:atom, 0, :diff}}, [{:var, 0, :t0}, {:var, 0, :t1}]}}, {:match, 0, {:var, 0, :c@4}, {:call, 0, {:remote, 0, {:atom, 0, Keyword}, {:atom, 0, :put}}, [{:var, 0, :c@3}, {:atom, 0, :duration}, {:var, 0, :t}]}}, {:call, 0, {:remote, 0, {:atom, 0, Chronex.Backends}, {:atom, 0, :after_return}}, [{:var, 0, :v}, {:var, 0, :c@4}]}, {:var, 0, :v}], [], [{:clause, 0, # rescue [{:tuple, 0, [{:atom, 0, :error}, {:var, 0, :_@2}, {:var, 0, :_}]}], [], [{:match, 0, {:var, 0, :e@1}, {:call, 0, {:remote, 0, {:atom, 0, Exception}, {:atom, 0, :normalize}}, [{:atom, 0, :error}, {:var, 0, :_@2}]}}, {:match, 0, {:var, 0, :t1@c}, {:call, 0, {:remote, 0, {:atom, 0, System}, {:atom, 0, :monotonic_time}}, []}}, {:match, 0, {:var, 0, :t@c}, {:call, 0, {:remote, 0, {:atom, 0, Chronex.Utils}, {:atom, 0, :diff}}, [{:var, 0, :t0}, {:var, 0, :t1@c}]}}, {:match, 0, {:var, 0, :c@4c}, {:call, 0, {:remote, 0, {:atom, 0, Keyword}, {:atom, 0, :put}}, [{:var, 0, :c@3}, {:atom, 0, :duration}, {:var, 0, :t@c}]}}, {:call, 0, {:remote, 0, {:atom, 0, Chronex.Backends}, {:atom, 0, :after_raise}}, [{:var, 0, :e@1}, {:var, 0, :c@4c}]}, {:call, 0, {:remote, 0, {:atom, 0, :erlang}, {:atom, 0, :error}}, [{:call, 0, {:remote, 0, {:atom, 0, Kernel.Utils}, {:atom, 0, :raise}}, [{:var, 0, :e@1}]}]}]}, {:clause, 0, # catch [{:tuple, 0, [{:atom, 0, :throw}, {:var, 0, :e@2}, {:var, 0, :_}]}], [], [{:match, 0, {:var, 0, :t1@c}, {:call, 0, {:remote, 0, {:atom, 0, System}, {:atom, 0, :monotonic_time}}, []}}, {:match, 0, {:var, 0, :t@c}, {:call, 0, {:remote, 0, {:atom, 0, Chronex.Utils}, {:atom, 0, :diff}}, [{:var, 0, :t0}, {:var, 0, :t1@c}]}}, {:match, 0, {:var, 0, :c@4c}, {:call, 0, {:remote, 0, {:atom, 0, Keyword}, {:atom, 0, :put}}, [{:var, 0, :c@3}, {:atom, 0, :duration}, {:var, 0, :t@c}]}}, {:call, 0, {:remote, 0, {:atom, 0, Chronex.Backends}, {:atom, 0, :after_throw}}, [{:var, 0, :e@2}, {:var, 0, :c@4c}]}, {:call, 0, {:remote, 0, {:atom, 0, :erlang}, {:atom, 0, :throw}}, [{:var, 0, :e@2}]}]}], []} ]}]} forms = :forms.read(m) forms = :meta.rename_function(f0, a, f1, false, forms) forms = :meta.add_function(fun, false, forms) :meta.apply_changes(forms, [:force, :permanent]) :ok end end @doc """ Check if the given function has a stopwatch attached to it. """ @spec bound?(atom(), atom(), non_neg_integer()) :: boolean() def bound?(m, f0, a) do f1 = fname(f0) :meta.has_function(f1, a, m) end @doc """ Detach a stopwatch from the given function. """ @spec unbind(atom(), atom(), non_neg_integer()) :: :ok | {:error, :unbound} def unbind(m, f0, a) do case bound?(m, f0, a) do false -> {:error, :unbound} true -> f1 = fname(f0) forms = :forms.read(m) forms = :meta.rm_function(f0, a, false, forms) forms = :meta.rename_function(f1, a, f0, false, forms) :meta.apply_changes(forms, [:force, :permanent]) :ok end end ##== Local functions ==================================================== defp fname(fname) do Enum.join([@prefix, Atom.to_string(fname)], "_") |> String.to_atom end defp args(0), do: [] defp args(arity) do 1..arity |> Enum.map( fn(nth) -> var = String.to_atom("$#{nth}") {:var, 0, var} end) end defp list_to_cons([]) do {:nil, 0} end defp list_to_cons([h| tail]) do {:cons, 0, h, list_to_cons(tail)} end end
lib/chronex.ex
0.727201
0.845496
chronex.ex
starcoder
defmodule EWallet.Web.StartAfterPaginator do @moduledoc """ The StartAfterPaginator allows querying of records by specified `start_after` and `start_by`. They take in a query, break the query down, then selectively query only records that are after the given `start_after`'s scope. If the `start_after` is nil, then return records from the beginning. For example: ``` StartAfterPaginator.paginate_attrs( Account, %{"start_after" => "acc_3", "start_by" => "id", "per_page" => 10}, [:id] ) ``` Let's say we have 10 accounts with ids: `["acc_1", "acc_2", "acc_3", ... , "acc_10"]` The code above return a pagination with accounts: `["acc_4", "acc_5", "acc_6", ... ,"acc_10"]` Note that an account with id "acc_3" is not included because the query range is exclusive. However, query accounts from the beginning is possible by specifying `start_after` to nil: ``` StartAfterPaginator.paginate_attrs( Account, %{"start_after" => nil, "start_by" => "id", "per_page" => 10}, [:id] ) ``` Return accounts: `["acc_1", "acc_2", "acc_3", ... ,"acc_10"]` """ import Ecto.Query require Logger alias EWalletDB.Repo alias EWallet.Web.Paginator @doc """ Paginate a query by attempting to extract `start_after`, `start_by` and `per_page` from the given map of attributes and returns a paginator. """ @spec paginate_attrs(Ecto.Query.t() | Ecto.Queryable.t(), map(), [], Ecto.Repo.t(), map()) :: %Paginator{} | {:error, :invalid_parameter, String.t()} def paginate_attrs( queryable, attrs, allowed_fields \\ [], repo \\ Repo, default_mapped_fields \\ %{} ) # Prevent non-string, non-atom `start_by` def paginate_attrs(_, %{"start_by" => start_by}, _, _, _) when not is_binary(start_by) and not is_atom(start_by) do {:error, :invalid_parameter, "`start_by` must be a string"} end def paginate_attrs( queryable, attrs, allowed_fields, repo, default_mapped_fields ) do default_field = Atom.to_string(hd(allowed_fields)) with {:ok, sort_by} <- attr_to_field(attrs, "sort_by", default_field, default_mapped_fields), {:ok, start_by} <- attr_to_field(attrs, "start_by", default_field, default_mapped_fields), {:allowed, true, _} <- {:allowed, start_by in allowed_fields, start_by} do attrs = attrs |> Map.put("sort_by", sort_by) |> Map.put("start_by", start_by) paginate(queryable, attrs, repo) else {:error, :not_existing_atom, field_type, field_name} -> available_fields = fields_to_string(allowed_fields) msg = "#{field_type}: `#{field_name}` is not allowed. The available fields are: [#{ available_fields }]" {:error, :invalid_parameter, msg} {:allowed, false, start_by} -> available_fields = fields_to_string(allowed_fields) start_by = Atom.to_string(start_by) msg = "start_by: `#{start_by}` is not allowed. The available fields are: [#{available_fields}]" {:error, :invalid_parameter, msg} end end def attr_to_field(attrs, key, default, mapping) do field_name = attrs[key] || default mapped_name = mapping[field_name] || field_name try do {:ok, String.to_existing_atom(mapped_name)} rescue ArgumentError -> {:error, :not_existing_atom, key, field_name} end end defp fields_to_string(fields) do fields |> Enum.map(&Atom.to_string/1) |> Enum.join(", ") end @doc """ Paginate a query using the given `start_after` and `start_by`. Returns a paginator with all records after the specify `start_after` record. """ def paginate(queryable, attrs, repo \\ Repo) # Query and returns `Paginator` def paginate( queryable, %{ "start_by" => start_by, "start_after" => {:ok, start_after}, "per_page" => per_page } = attrs, repo ) do attrs = Map.put(attrs, "start_after", start_after) {records, more_page} = queryable |> get_queryable_start_after(attrs) |> get_queryable_order_by(attrs) |> fetch(per_page, repo) pagination = %{ per_page: per_page, start_by: Atom.to_string(start_by), start_after: start_after, # It's the last page if there are no more records is_last_page: !more_page, count: length(records) } %Paginator{data: records, pagination: pagination} end def paginate(queryable, %{"start_after" => nil} = attrs, repo), do: paginate(queryable, %{attrs | "start_after" => {:ok, nil}}, repo) # Checking if the `start_after` value exist in the db. def paginate( queryable, %{ "start_by" => start_by, "start_after" => start_after, "per_page" => _ } = attrs, repo ) do # Verify if the given `start_after` exist to prevent unexpected result. condition = build_start_after_condition(%{"start_by" => start_by, "start_after" => start_after}) pure_queryable = exclude(queryable, :where) record = try do repo.get_by(pure_queryable, condition) rescue Ecto.Query.CastError -> build_error(:start_after_cast_error, start_after, start_by) error -> build_error(:unknown_db_error, error) end case record do {:error, _, _} -> record # Returns error if the record with `start_after` value is not found. nil -> {:error, :unauthorized} # Record with `start_after` value is found, query the result. _ -> paginate(queryable, %{attrs | "start_after" => {:ok, start_after}}, repo) end end defp build_error(:start_after_cast_error, start_after, start_by) do msg = "" |> Kernel.<>("Invalid `start_after` or `start_by` provided. ") |> Kernel.<>("Given `#{start_after}` cannot be casted to given `#{start_by}`.") {:error, :invalid_parameter, msg} end defp build_error(:unknown_db_error, error) do # This event should not happen. # We will need to handle more if we encounter this error. Logger.error("An unknown error occurred during pagination. Error: #{inspect(error)}") {:error, :unknown_error, "An unknown error occured on the database."} end defp fetch(queryable, per_page, repo) do limit = per_page + 1 records = queryable |> limit(^limit) |> repo.all() case Enum.count(records) do n when n > per_page -> {List.delete_at(records, -1), true} _ -> {records, false} end end def build_start_after_condition(%{"start_by" => start_by, "start_after" => start_after}) do Map.put(%{}, start_by, start_after) end # Query records from the beginning if `start_after` is null or empty, # Otherwise querying after specified `start_after` by `start_by` field. defp get_queryable_start_after( queryable, %{ "start_after" => _, "start_by" => _ } = attrs ) do offset = get_offset(queryable, attrs) queryable |> offset(^offset) end defp get_offset(_, %{"start_after" => nil}), do: 0 defp get_offset( queryable, %{ "start_after" => start_after, "start_by" => start_by, "sort_by" => sort_by, "sort_dir" => sort_dir } ) do offset_queryable = queryable |> exclude(:preload) |> exclude(:distinct) |> exclude(:select) |> get_offset_queryable(%{ "start_by" => start_by, "sort_by" => sort_by, "sort_dir" => sort_dir }) queryable = from(q in subquery(offset_queryable)) result = queryable |> select([q], q.offset) |> where([q], q.start_by == ^start_after) |> Repo.all() parse_get_offset(result) end defp get_offset(queryable, %{"start_after" => start_after, "start_by" => start_by} = attrs) do sort_dir = Map.get(attrs, "sort_dir", "asc") sort_by = Map.get(attrs, "sort_by", start_by) get_offset( queryable, %{ "start_after" => start_after, "start_by" => start_by, "sort_by" => sort_by, "sort_dir" => sort_dir } ) end defp parse_get_offset([]), do: 0 defp parse_get_offset([offset]), do: offset defp get_offset_queryable(queryable, %{ "start_by" => start_by, "sort_by" => sort_by, "sort_dir" => "desc" }) do queryable |> select([a], %{ start_by: field(a, ^start_by), offset: fragment("ROW_NUMBER() OVER (ORDER BY ? DESC)", field(a, ^sort_by)) }) end defp get_offset_queryable(queryable, %{"start_by" => start_by, "sort_by" => sort_by}) do queryable |> select([a], %{ start_by: field(a, ^start_by), offset: fragment("ROW_NUMBER() OVER (ORDER BY ? ASC)", field(a, ^sort_by)) }) end defp get_queryable_order_by(queryable, %{"sort_dir" => "desc", "sort_by" => sort_by}) do order_by(queryable, desc: ^sort_by) end defp get_queryable_order_by(queryable, %{"sort_by" => sort_by}) do order_by(queryable, asc: ^sort_by) end end
apps/ewallet/lib/ewallet/web/paginators/start_after_paginator.ex
0.851444
0.736543
start_after_paginator.ex
starcoder
defmodule Flop.Phoenix do @moduledoc """ View helper functions for Phoenix and Flop. ## Pagination `Flop.meta/3` returns a `Flop.Meta` struct, which holds information such as the total item count, the total page count, the current page etc. This is all you need to render pagination links. `Flop.run/3`, `Flop.validate_and_run/3` and `Flop.validate_and_run!/3` all return the query results alongside the meta information. If you set up your context as described in the [Flop documentation](https://hexdocs.pm/flop), you will have a `list` function similar to the following: @spec list_pets(Flop.t() | map) :: {:ok, {[Pet.t()], Flop.Meta.t}} | {:error, Changeset.t()} def list_pets(flop \\\\ %{}) do Flop.validate_and_run(Pet, flop, for: Pet) end ### Controller You can call this function from your controller to get both the data and the meta data and pass both to your template. defmodule MyAppWeb.PetController do use MyAppWeb, :controller alias Flop alias MyApp.Pets alias MyApp.Pets.Pet action_fallback MyAppWeb.FallbackController def index(conn, params) do with {:ok, {pets, meta}} <- Pets.list_pets(params) do render(conn, "index.html", meta: meta, pets: pets) end end end ### View To make the `Flop.Phoenix` functions available in all templates, locate the `view_helpers/0` macro in `my_app_web.ex` and add another import statement: defp view_helpers do quote do # ... import Flop.Phoenix # ... end end ### Template In your index template, you can now add pagination links like this: <h1>Listing Pets</h1> <table> # ... </table> <%= pagination(@meta, &Routes.pet_path/3, [@conn, :index]) %> The second argument of `Flop.Phoenix.pagination/4` is the route helper function, and the third argument is a list of arguments for that route helper. If you want to add path parameters, you can do that like this: <%= pagination(@meta, &Routes.owner_pet_path/4, [@conn, :index, @owner]) %> ## Customization `Flop.Phoenix` sets some default classes and aria attributes. <nav aria-label="pagination" class="pagination is-centered" role="navigation"> <span class="pagination-previous" disabled="disabled">Previous</span> <a class="pagination-next" href="/pets?page=2&amp;page_size=10">Next</a> <ul class="pagination-list"> <li><span class="pagination-ellipsis">&hellip;</span></li> <li> <a aria-current="page" aria-label="Goto page 1" class="pagination-link is-current" href="/pets?page=1&amp;page_size=10">1</a> </li> <li> <a aria-label="Goto page 2" class="pagination-link" href="/pets?page=2&amp;page_size=10">2</a> </li> <li> <a aria-label="Goto page 3" class="pagination-link" href="/pets?page=3&amp;page_size=2">3</a> </li> <li><span class="pagination-ellipsis">&hellip;</span></li> </ul> </nav> You can customize the css classes and add additional HTML attributes. It is recommended to set up the customization once in a view helper module, so that your templates aren't cluttered with options. Create a new file called `views/flop_helpers.ex`: defmodule MyAppWeb.FlopHelpers do use Phoenix.HTML def pagination(meta, path_helper, path_helper_args) do Flop.Phoenix.pagination( meta, path_helper, path_helper_args, pagination_opts() ) end def pagination_opts do [ # ... ] end end Change the import in `my_app_web.ex`: defp view_helpers do quote do # ... import MyAppWeb.FlopHelpers # ... end end ### Page link options By default, page links for all pages are show. You can limit the number of page links or disable them altogether by passing the `:page_links` option. - `:all`: Show all page links (default). - `:hide`: Don't show any page links. Only the previous/next links will be shown. - `{:ellipsis, x}`: Limits the number of page links. The first and last page are always displayed. The `x` refers to the number of additional page links to show. ### Attributes and CSS classes You can overwrite the default attributes of the `<nav>` tag and the pagination links by passing these options: - `:wrapper_attrs`: attributes for the `<nav>` tag - `:previous_link_attrs`: attributes for the previous link (`<a>` if active, `<span>` if disabled) - `:next_link_attrs`: attributes for the next link (`<a>` if active, `<span>` if disabled) - `:pagination_list_attrs`: attributes for the page link list (`<ul>`) - `:pagination_link_attrs`: attributes for the page links (`<a>`) - `:current_link_attrs`: attributes for the page link to the current page (`<a>`) - note that the `pagination_link_attrs` are not applied to the current page link - `:ellipsis_attrs`: attributes for the ellipsis element (`<span>`) - `:ellipsis_content`: content for the ellipsis element (`<span>`) ### Pagination link aria label For the page links, there is the `:pagination_link_aria_label` option to set the aria label. Since the page number is usually part of the aria label, you need to pass a function that takes the page number as an integer and returns the label as a string. The default is `&"Goto page \#{&1}"`. ### Previous/next links By default, the previous and next links contain the texts `Previous` and `Next`. To change this, you can pass the `:previous_link_content` and `:next_link_content` options. ### Hiding default parameters Default values for page size and ordering are omitted from the query parameters. If you pass the `:for` option, the Flop.Phoenix function will pick up the default values from the schema module deriving `Flop.Schema`. ### Customization example def pagination(meta, path_helper, path_helper_args, opts) do default_opts = [ ellipsis_attrs: [class: "ellipsis"], ellipsis_content: "‥", next_link_attrs: [class: "next"], next_link_content: next_icon(), page_links: {:ellipsis, 7}, pagination_link_aria_label: &"\#{&1}ページ目へ", pagination_link_attrs: [class: "page-link"], pagination_list_attrs: [class: "page-links"], previous_link_attrs: [class: "prev"], previous_link_content: previous_icon(), wrapper_attrs: [class: "paginator"] ] opts = Keyword.merge(default_opts, opts) Flop.Phoenix.pagination(meta, path_helper, path_helper_args, opts) end defp next_icon do tag :i, class: "fas fa-chevron-right" end defp previous_icon do tag :i, class: "fas fa-chevron-left" end ## Sortable table To add a sortable table for pets on the same page, define a function in `MyAppWeb.PetView` that returns the table headers: def table_headers do ["ID", {"Name", :name}, {"Age", :age}, ""] end This defines four header columns: One for the ID, which is not sortable, and columns for the name and the age, which are both sortable, and a fourth column without a header value. The last column will hold the links to the detail pages. The name and age column headers will be linked, so that they the order on the `:name` and `:age` field, respectively. Next, we define a function that returns the column values for a single pet: def table_row(%Pet{id: id, name: name, age: age}, opts) do conn = Keyword.fetch!(opts, :conn) [id, name, age, link("show", to: Routes.pet_path(conn, :show, id))] end The controller already assigns the pets and the meta struct to the conn. All that's left to do is to add the table to the index template: <%= table(%{ items: @pets, meta: @meta, path_helper: &Routes.pet_path/3, path_helper_args: [@conn, :index], headers: table_headers(), row_func: &table_row/2, opts: [conn: @conn] }) %> ## LiveView The functions in this module can be used in both `.eex` and `.leex` templates. Links are generated with `Phoenix.LiveView.Helpers.live_patch/2`. This will lead to `<a>` tags with `data-phx-link` and `data-phx-link-state` attributes, which will be ignored in `.eex` templates. When used in LiveView templates, you will need to handle the new params in the `handle_params/3` callback of your LiveView module. """ use Phoenix.HTML import Phoenix.LiveView.Helpers alias Flop.Meta alias Flop.Phoenix.Pagination alias Flop.Phoenix.Table @default_table_opts [ container: false, container_attrs: [class: "table-container"], no_results_content: content_tag(:p, do: "No results."), symbol_asc: "▴", symbol_attrs: [class: "order-direction"], symbol_desc: "▾", table_attrs: [], tbody_td_attrs: [], tbody_tr_attrs: [], th_wrapper_attrs: [], thead_th_attrs: [], thead_tr_attrs: [] ] @doc """ Generates a pagination element. - `meta`: The meta information of the query as returned by the `Flop` query functions. - `path_helper`: The path helper function that builds a path to the current page, e.g. `&Routes.pet_path/3`. - `path_helper_args`: The arguments to be passed to the route helper function, e.g. `[@conn, :index]`. The page number and page size will be added as query parameters. - `opts`: Options to customize the pagination. See section Customization. See the module documentation for examples. """ @doc section: :generators @spec pagination(Meta.t(), function, [any], keyword) :: Phoenix.LiveView.Rendered.t() def pagination(meta, path_helper, path_helper_args, opts \\ []) def pagination(%Meta{total_pages: p}, _, _, _) when p <= 1, do: raw(nil) def pagination(%Meta{} = meta, path_helper, path_helper_args, opts) do assigns = %{ __changed__: nil, meta: meta, opts: Pagination.init_opts(opts), page_link_helper: Pagination.build_page_link_helper( meta, path_helper, path_helper_args, opts ) } ~L""" <%= if @meta.total_pages > 1 do %> <%= content_tag :nav, Pagination.build_attrs(@opts) do %> <%= Pagination.previous_link(@meta, @page_link_helper, @opts) %> <%= Pagination.next_link(@meta, @page_link_helper, @opts) %> <%= Pagination.page_links(@meta, @page_link_helper, @opts) %> <% end %> <% end %> """ end @doc """ Generates a table with sortable columns. The argument is a map with the following keys: - `headers`: A list of header columns. Can be a list of strings (or markup), or a list of `{value, field_name}` tuples. - `items`: The list of items to be displayed in rows. This is the result list returned by the query. - `meta`: The `Flop.Meta` struct returned by the query function. - `path_helper`: The Phoenix path or url helper that leads to the current page. - `path_helper_args`: The argument list for the path helper. For example, if you would call `Routes.pet_path(@conn, :index)` to generate the path for the current page, this would be `[@conn, :index]`. - `opts`: Keyword list with additional options (see below). This list will also be passed as the second argument to the row function. - `row_func`: A function that takes one item of the `items` list and the `opts` and returns the column values for that item's row. ## Available options - `:for` - The schema module deriving `Flop.Schema`. If set, header links are only added for fields that are defined as sortable. Default: `#{inspect(@default_table_opts[:for])}`. - `:table_attrs` - The attributes for the `<table>` element. Default: `#{inspect(@default_table_opts[:table_attrs])}`. - `:th_wrapper_attrs` - The attributes for the `<span>` element that wraps the header link and the order direction symbol. Default: `#{inspect(@default_table_opts[:th_wrapper_attrs])}`. - `:symbol_attrs` - The attributes for the `<span>` element that wraps the order direction indicator in the header columns. Default: `#{inspect(@default_table_opts[:symbol_attrs])}`. - `:symbol_asc` - The symbol that is used to indicate that the column is sorted in ascending order. Default: `#{inspect(@default_table_opts[:symbol_asc])}`. - `:symbol_desc` - The symbol that is used to indicate that the column is sorted in ascending order. Default: `#{inspect(@default_table_opts[:symbol_desc])}`. - `:container` - Wraps the table in a `<div>` if `true`. Default: `#{inspect(@default_table_opts[:container])}`. - `:container_attrs` - The attributes for the table container. Default: `#{inspect(@default_table_opts[:container_attrs])}`. - `:no_results_content` - Any content that should be rendered if there are no results. Default: `<p>No results.</p>`. - `:thead_tr_attrs`: Attributes to added to each `<tr>` tag within the `<thead>`. Default: `#{inspect(@default_table_opts[:thead_tr_attrs])}`. - `:thead_th_attrs`: Attributes to added to each `<th>` tag within the `<thead>`. Default: `#{inspect(@default_table_opts[:thead_th_attrs])}`. - `:tbody_tr_attrs`: Attributes to added to each `<tr>` tag within the `<tbody>`. Default: `#{inspect(@default_table_opts[:tbody_tr_attrs])}`. - `:tbody_td_attrs`: Attributes to added to each `<td>` tag within the `<tbody>`. Default: `#{inspect(@default_table_opts[:tbody_td_attrs])}`. See the module documentation for examples. """ @doc since: "0.6.0" @doc section: :generators @spec table(map) :: Phoenix.LiveView.Rendered.t() def table(assigns) do assigns = Map.update( assigns, :opts, @default_table_opts, &Keyword.merge(@default_table_opts, &1) ) ~L""" <%= if @items == [] do %> <%= @opts[:no_results_content] %> <% else %> <%= if @opts[:container] do %> <%= content_tag :div, @opts[:container_attrs] do %> <%= Table.render(assigns) %> <% end %> <% else %> <%= Table.render(assigns) %> <% end %> <% end %> """ end @doc """ Converts a Flop struct into a keyword list that can be used as a query with Phoenix route helper functions. Default limits and default order parameters set via the application environment are omitted. You can pass the `:for` option to pick up the default options from a schema module deriving `Flop.Schema`. You can also pass `default_limit` and `default_order` as options directly. The function uses `Flop.get_option/2` internally to retrieve the default options. ## Examples iex> to_query(%Flop{}) [] iex> f = %Flop{order_by: [:name, :age], order_directions: [:desc, :asc]} iex> to_query(f) [order_directions: [:desc, :asc], order_by: [:name, :age]] iex> f |> to_query |> Plug.Conn.Query.encode() "order_directions[]=desc&order_directions[]=asc&order_by[]=name&order_by[]=age" iex> f = %Flop{page: 5, page_size: 20} iex> to_query(f) [page_size: 20, page: 5] iex> f = %Flop{first: 20, after: "g3QAAAABZAAEbmFtZW0AAAAFQXBwbGU="} iex> to_query(f) [first: 20, after: "g3QAAAABZAAEbmFtZW0AAAAFQXBwbGU="] iex> f = %Flop{ ...> filters: [ ...> %Flop.Filter{field: :name, op: :=~, value: "Mag"}, ...> %Flop.Filter{field: :age, op: :>, value: 25} ...> ] ...> } iex> to_query(f) [ filters: %{ 0 => %{field: :name, op: :=~, value: "Mag"}, 1 => %{field: :age, op: :>, value: 25} } ] iex> f |> to_query() |> Plug.Conn.Query.encode() "filters[0][field]=name&filters[0][op]=%3D~&filters[0][value]=Mag&filters[1][field]=age&filters[1][op]=%3E&filters[1][value]=25" iex> f = %Flop{page: 5, page_size: 20} iex> to_query(f, default_limit: 20) [page: 5] """ @doc since: "0.6.0" @doc section: :miscellaneous @spec to_query(Flop.t()) :: keyword def to_query(%Flop{filters: filters} = flop, opts \\ []) do filter_map = filters |> Stream.with_index() |> Enum.into(%{}, fn {filter, index} -> {index, Map.from_struct(filter)} end) keys = [ :after, :before, :first, :last, :offset, :page ] default_limit = Flop.get_option(:default_limit, opts) default_order = Flop.get_option(:default_order, opts) keys |> Enum.reduce([], &maybe_add_param(&2, &1, Map.get(flop, &1))) |> maybe_add_param(:page_size, flop.page_size, default_limit) |> maybe_add_param(:limit, flop.limit, default_limit) |> maybe_add_order_params(flop, default_order) |> maybe_add_param(:filters, filter_map) end defp maybe_add_param(params, key, value, default \\ nil) defp maybe_add_param(params, _, nil, _), do: params defp maybe_add_param(params, _, [], _), do: params defp maybe_add_param(params, _, map, _) when map == %{}, do: params defp maybe_add_param(params, :page, 1, _), do: params defp maybe_add_param(params, :offset, 0, _), do: params defp maybe_add_param(params, _, val, val), do: params defp maybe_add_param(params, key, val, _), do: Keyword.put(params, key, val) defp maybe_add_order_params( params, %Flop{order_by: order_by, order_directions: order_directions}, %{order_by: order_by, order_directions: order_directions} ), do: params defp maybe_add_order_params( params, %Flop{order_by: order_by, order_directions: order_directions}, _ ) do params |> maybe_add_param(:order_by, order_by) |> maybe_add_param(:order_directions, order_directions) end @doc """ Takes a Phoenix path helper function and a list of path helper arguments and builds a path that includes query parameters for the given `Flop` struct. Default values for `limit`, `page_size`, `order_by` and `order_directions` are omit from the query parameters. To pick up the default parameters from a schema module deriving `Flop.Schema`, you need to pass the `:for` option. ## Examples iex> pet_path = fn _conn, :index, query -> ...> "/pets?" <> Plug.Conn.Query.encode(query) ...> end iex> flop = %Flop{page: 2, page_size: 10} iex> build_path(pet_path, [%Plug.Conn{}, :index], flop) "/pets?page_size=10&page=2" We're defining fake path helpers for the scope of the doctests. In a real Phoenix application, you would pass something like `&Routes.pet_path/3` as the first argument. You can also pass a `Flop.Meta` struct or a keyword list as the third argument. iex> pet_path = fn _conn, :index, query -> ...> "/pets?" <> Plug.Conn.Query.encode(query) ...> end iex> flop = %Flop{page: 2, page_size: 10} iex> meta = %Flop.Meta{flop: flop} iex> build_path(pet_path, [%Plug.Conn{}, :index], meta) "/pets?page_size=10&page=2" iex> query_params = to_query(flop) iex> build_path(pet_path, [%Plug.Conn{}, :index], query_params) "/pets?page_size=10&page=2" If the path helper takes additional path parameters, just add them to the second argument. iex> user_pet_path = fn _conn, :index, id, query -> ...> "/users/\#{id}/pets?" <> Plug.Conn.Query.encode(query) ...> end iex> flop = %Flop{page: 2, page_size: 10} iex> build_path(user_pet_path, [%Plug.Conn{}, :index, 123], flop) "/users/123/pets?page_size=10&page=2" If the last path helper argument is a query parameter list, the Flop parameters are merged into it. iex> pet_url = fn _conn, :index, query -> ...> "https://pets.flop/pets?" <> Plug.Conn.Query.encode(query) ...> end iex> flop = %Flop{order_by: :name, order_directions: [:desc]} iex> build_path(pet_url, [%Plug.Conn{}, :index, [user_id: 123]], flop) "https://pets.flop/pets?user_id=123&order_directions[]=desc&order_by=name" iex> build_path( ...> pet_url, ...> [%Plug.Conn{}, :index, [category: "small", user_id: 123]], ...> flop ...> ) "https://pets.flop/pets?category=small&user_id=123&order_directions[]=desc&order_by=name" """ @doc since: "0.6.0" @doc section: :miscellaneous @spec build_path(function, [any], Meta.t() | Flop.t() | keyword, keyword) :: String.t() def build_path(path_helper, args, meta_or_flop_or_params, opts \\ []) def build_path(path_helper, args, %Meta{flop: flop}, opts), do: build_path(path_helper, args, flop, opts) def build_path(path_helper, args, %Flop{} = flop, opts) do build_path(path_helper, args, Flop.Phoenix.to_query(flop, opts)) end def build_path(path_helper, args, flop_params, _opts) when is_function(path_helper) and is_list(args) and is_list(flop_params) do final_args = case Enum.reverse(args) do [last_arg | rest] when is_list(last_arg) -> query_arg = Keyword.merge(last_arg, flop_params) Enum.reverse([query_arg | rest]) _ -> args ++ [flop_params] end apply(path_helper, final_args) end end
lib/flop_phoenix.ex
0.840226
0.506347
flop_phoenix.ex
starcoder
defmodule ExPoloniex.Trading do @moduledoc """ Module for Poloniex Trading API methods https://poloniex.com/support/api/ """ alias ExPoloniex.{DepositsAndWithdrawals, Api} @doc """ Returns all of your available balances """ def return_balances do case Api.trading("returnBalances") do {:ok, balances} -> {:ok, balances} {:error, _} = error -> error end end @doc """ Returns all of your balances, including available balance, balance on orders, and the estimated BTC value of your balance. By default, this call is limited to your exchange account; set the "account" POST parameter to "all" to include your margin and lending accounts """ def return_complete_balances do case Api.trading("returnCompleteBalances") do {:ok, complete_balances} -> {:ok, complete_balances} {:error, _} = error -> error end end @doc false def return_complete_balances(:all) do case Api.trading("returnCompleteBalances", account: :all) do {:ok, complete_balances} -> {:ok, complete_balances} {:error, _} = error -> error end end @doc """ Returns all of your deposit addresses """ def return_deposit_addresses do case Api.trading("returnDepositAddresses") do {:ok, deposit_addresses} -> {:ok, deposit_addresses} {:error, _} = error -> error end end @doc """ Generates a new deposit address for the currency specified by the "currency" POST parameter """ def generate_new_address(currency) do case Api.trading("generateNewAddress", currency: currency) do {:ok, %{"response" => new_address, "success" => 1}} -> {:ok, new_address} {:ok, %{"response" => response, "success" => 0}} -> {:error, response} {:error, _} = error -> error end end @doc """ Returns your deposit and withdrawal history within a range, specified by the "start" and "end" POST parameters, both of which should be given as UNIX timestamps """ def return_deposits_withdrawals(%DateTime{} = start, %DateTime{} = to) do start_unix = DateTime.to_unix(start) end_unix = DateTime.to_unix(to) case Api.trading("returnDepositsWithdrawals", start: start_unix, end: end_unix) do {:ok, %{"deposits" => deposits, "withdrawals" => withdrawals}} -> {:ok, %DepositsAndWithdrawals{deposits: deposits, withdrawals: withdrawals}} {:error, _} = error -> error end end def return_market_rules do case Api.trading("returnMarketRules") do {:ok, rules} -> {:ok, rules} {:error, _} = error -> error end end @doc """ Returns your open orders for a given market, specified by the "currencyPair" POST parameter, e.g. "BTC_XCP". Set "currencyPair" to "all" to return open orders for all markets """ defdelegate return_open_orders(currency_pair), to: ExPoloniex.ReturnOpenOrders, as: :return_open_orders @doc """ Returns the past 200 trades for a given market, or up to 50,000 trades between a range specified in UNIX timestamps by the "start" and "end" GET parameters. """ defdelegate return_trade_history(currency_pair, start, to), to: ExPoloniex.ReturnTradeHistory, as: :return_trade_history @doc """ Returns all trades involving a given order, specified by the "orderNumber" POST parameter. If no trades for the order have occurred or you specify an order that does not belong to you, you will receive an error """ defdelegate return_order_trades(order_number), to: ExPoloniex.ReturnOrderTrades, as: :return_order_trades @doc """ Places a limit buy order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". If successful, the method will return the order number. You may optionally set "fillOrKill", "immediateOrCancel", "postOnly" to 1. A fill-or-kill order will either fill in its entirety or be completely aborted. An immediate-or-cancel order can be partially or completely filled, but any portion of the order that cannot be filled immediately will be canceled rather than left on the order book. A post-only order will only be placed if no portion of it fills immediately; this guarantees you will never pay the taker fee on any part of the order that fills. """ defdelegate buy( currency_pair, rate, amount, order_type \\ nil ), to: ExPoloniex.Buy, as: :buy @doc """ Places a sell order in a given market. Parameters and output are the same as for the buy method. """ defdelegate sell( currency_pair, rate, amount, order_type \\ nil ), to: ExPoloniex.Sell, as: :sell @doc """ Cancels an order you have placed in a given market. Required POST parameter is "orderNumber" """ defdelegate cancel_order(order_number), to: ExPoloniex.CancelOrder, as: :cancel_order def move_order do {:error, :not_implemented} end def withdraw do {:error, :not_implemented} end @doc """ If you are enrolled in the maker-taker fee schedule, returns your current trading fees and trailing 30-day volume in BTC. This information is updated once every 24 hours """ defdelegate return_fee_info(), to: ExPoloniex.ReturnFeeInfo, as: :return_fee_info def return_available_account_balances do {:error, :not_implemented} end def return_tradable_balances do {:error, :not_implemented} end def transfer_balance do {:error, :not_implemented} end def return_margin_account_summary do {:error, :not_implemented} end def margin_buy do {:error, :not_implemented} end def margin_sell do {:error, :not_implemented} end def get_margin_position do {:error, :not_implemented} end def close_margin_position do {:error, :not_implemented} end def create_loan_offer do {:error, :not_implemented} end def cancel_loan_offer do {:error, :not_implemented} end def return_open_loan_offers do {:error, :not_implemented} end def return_active_loans do {:error, :not_implemented} end def return_lending_history do {:error, :not_implemented} end def toggle_auto_renew do {:error, :not_implemented} end end
lib/ex_poloniex/trading.ex
0.81582
0.425426
trading.ex
starcoder
defmodule Accent.Scopes.Revision do import Ecto.Query, only: [from: 2] @doc """ ## Examples iex> Accent.Scopes.Revision.from_project(Accent.Revision, "test") #Ecto.Query<from r0 in Accent.Revision, join: l1 in assoc(r0, :language), where: r0.project_id == ^\"test\", order_by: [desc: r0.master, asc: l1.name]> """ @spec from_project(Ecto.Queryable.t(), String.t()) :: Ecto.Queryable.t() def from_project(query, project_id) do from( revision in query, where: [project_id: ^project_id], inner_join: language in assoc(revision, :language), order_by: [desc: revision.master, asc: language.name] ) end @doc """ ## Examples iex> Accent.Scopes.Revision.from_language(Accent.Revision, "test") #Ecto.Query<from r0 in Accent.Revision, where: r0.language_id == ^\"test\"> """ @spec from_language(Ecto.Queryable.t(), String.t()) :: Ecto.Queryable.t() def from_language(query, language_id) do from(r in query, where: [language_id: ^language_id]) end @doc """ ## Examples iex> Accent.Scopes.Revision.from_language_slug(Accent.Revision, "en-US") #Ecto.Query<from r0 in Accent.Revision, join: l1 in assoc(r0, :language), where: l1.slug == ^\"en-US\"> """ @spec from_language_slug(Ecto.Queryable.t(), String.t()) :: Ecto.Queryable.t() def from_language_slug(query, language_slug) do from(r in query, join: l in assoc(r, :language), where: l.slug == ^language_slug) end @doc """ ## Examples iex> Accent.Scopes.Revision.master(Accent.Revision) #Ecto.Query<from r0 in Accent.Revision, where: r0.master == true> """ @spec master(Ecto.Queryable.t()) :: Ecto.Queryable.t() def master(query) do from(r in query, where: [master: true]) end @doc """ ## Examples iex> Accent.Scopes.Revision.slaves(Accent.Revision) #Ecto.Query<from r0 in Accent.Revision, where: r0.master == false> """ @spec slaves(Ecto.Queryable.t()) :: Ecto.Queryable.t() def slaves(query) do from(r in query, where: [master: false]) end end
lib/accent/scopes/revision.ex
0.567098
0.469277
revision.ex
starcoder
defmodule Strukt.Typespec do @moduledoc false defstruct [:caller, :info, :fields, :embeds] @type t :: %__MODULE__{ # The module where the struct is being defined caller: module, # Metadata about all fields in the struct info: %{optional(atom) => map}, # A list of all non-embed field names fields: [atom], # A list of all embed field names embeds: [atom] } @empty_meta %{type: nil, value_type: nil, required: false, default: nil} @doc """ Given a description of a struct definition, this function produces AST which represents a typespec definition for that struct. For example, given a struct definition like so: defstruct Foo do field :uuid, Ecto.UUID, primary_key: true field :name, :string field :age, :integer end This function would produce a typespec definition equivalent to: @type t :: %Foo{ uuid: Ecto.UUID.t, name: String.t, age: integer } ## Struct Description The description contains a few fields, whose values are sourced based on the following: * `info` - A map of every field for which we have validation metadata * `fields` - This is a list of all field names which are defined via `field/3` * `embeds` - This is a list of all field names which are defined via `embeds_one/3` or `embeds_many/3` """ def generate(%__MODULE__{caller: caller, info: info, fields: fields, embeds: embeds}) do # Build up the AST for each field's type spec fields = fields |> Stream.map(fn name -> {name, Map.get(info, name, @empty_meta)} end) |> Enum.map(fn {name, meta} -> required? = Map.get(meta, :required) == true default_value = Map.get(meta, :default) type_name = type_to_type_name(meta.type) type_spec = if required? or not is_nil(default_value) do type_name else {:|, [], [type_name, nil]} end {name, type_spec} end) # Do the same for embeds_one/embeds_many embeds = embeds |> Enum.map(fn name -> {name, Map.fetch!(info, name)} end) |> Enum.map(fn {name, %{type: :embeds_one, value_type: type}} -> {name, compose_call(type, :t, [])} {name, %{type: :embeds_many, value_type: type}} -> {name, List.wrap(compose_call(type, :t, []))} end) # Join all fields together struct_fields = fields ++ embeds quote(context: caller, do: @type(t :: %__MODULE__{unquote_splicing(struct_fields)})) end defp primitive(atom, args \\ []) when is_atom(atom) and is_list(args), do: {atom, [], args} defp map(elements) when is_list(elements), do: {:%{}, [], elements} defp map(elements) when is_map(elements), do: {:%{}, [], Map.to_list(elements)} defp compose_call(module, function, args) when is_atom(module) and is_list(args), do: {{:., [], [{:__aliases__, [alias: false], [module]}, function]}, [], args} defp compose_call({:__aliases__, _, _} = module, function, args) when is_list(args), do: {{:., [], [module, function]}, [], args} defp type_to_type_name(:id), do: primitive(:non_neg_integer) defp type_to_type_name(:binary_id), do: primitive(:binary) defp type_to_type_name(:integer), do: primitive(:integer) defp type_to_type_name(:float), do: primitive(:float) defp type_to_type_name(:decimal), do: compose_call(Decimal, :t, []) defp type_to_type_name(:boolean), do: primitive(:boolean) defp type_to_type_name(:string), do: compose_call(String, :t, []) defp type_to_type_name(:binary), do: primitive(:binary) defp type_to_type_name(:uuid), do: compose_call(Ecto.UUID, :t, []) defp type_to_type_name({:array, type}), do: [type_to_type_name(type)] defp type_to_type_name(:map), do: primitive(:map) defp type_to_type_name({:map, type}) do element_type = type_to_type_name(type) map([{element_type, element_type}]) end defp type_to_type_name(t) when t in [:utc_datetime_usec, :utc_datetime], do: compose_call(DateTime, :t, []) defp type_to_type_name(t) when t in [:naive_datetime_usec, :naive_datetime], do: compose_call(NaiveDateTime, :t, []) defp type_to_type_name(t) when t in [:time_usec, :time], do: compose_call(Time, :t, []) defp type_to_type_name(:date), do: compose_call(Date, :t, []) defp type_to_type_name({:__aliases__, _, parts} = ast) do case Module.concat(parts) do Ecto.Enum -> primitive(:atom) Ecto.UUID -> primitive(:string) mod -> with {:module, _} <- Code.ensure_compiled(mod) do try do if Kernel.Typespec.defines_type?(mod, {:t, 0}) do compose_call(ast, :t, []) else # No t/0 type defined, so fallback to any/0 primitive(:any) end rescue ArgumentError -> # We shouldn't hit this branch, but if Elixir can't find module metadata # during defines_type?, it raises ArgumentError, so we handle this like the # other pessimistic cases primitive(:any) end else _ -> # Module is unable to be loaded, either due to compiler deadlock, or because # the module name we have is an alias, or perhaps just plain wrong, so we can't # assume anything about its type primitive(:any) end end end defp type_to_type_name(_), do: primitive(:any) end
lib/typespec.ex
0.746416
0.512083
typespec.ex
starcoder
defmodule Hui do @moduledoc """ Hui 辉 ("shine" in Chinese) is an [Elixir](https://elixir-lang.org) client and library for [Solr enterprise search platform](http://lucene.apache.org/solr/). ### Usage - Searching Solr: `q/1`, `q/6`, `search/2`, `search/7` - Updating: `update/3`, `delete/3`, `delete_by_query/3`, `commit/2` - Other: `suggest/2`, `suggest/5` - Admin: `metrics/2`, `ping/1` - [README](https://hexdocs.pm/hui/readme.html#usage) """ import Hui.Guards import Hui.Http alias Hui.Encoder alias Hui.Error alias Hui.Http alias Hui.Query alias Hui.Utils @http_client Application.get_env(:hui, :http_client, Hui.Http) @type endpoint :: binary | atom | {binary, list} | {binary, list, list} @type querying_struct :: Query.Standard.t() | Query.Common.t() | Query.DisMax.t() @type faceting_struct :: Query.Facet.t() | Query.FacetRange.t() | Query.FacetInterval.t() @type highlighting_struct :: Query.Highlight.t() | Query.HighlighterUnified.t() | Query.HighlighterOriginal.t() | Query.HighlighterFastVector.t() @type misc_struct :: Query.MoreLikeThis.t() | Query.Suggest.t() | Query.SpellCheck.t() | Query.Metrics.t() @type solr_struct :: querying_struct | faceting_struct | highlighting_struct | misc_struct @type query :: keyword | map | solr_struct | [solr_struct] @type update_query :: binary | map | list(map) | Query.Update.t() @type http_response :: Http.response() @doc """ Issue a keyword list or structured query to the default Solr endpoint. The query can either be a keyword list or a list of Hui structs - see `t:Hui.solr_struct/0`. This function is a shortcut for `search/2` with `:default` as the configured endpoint key. ### Example ``` Hui.q(q: "loch", rows: 5, facet: true, "facet.field": ["year", "subject"]) # supply a list of Hui structs for more complex query, e.g. faceting alias Hui.Query Hui.q([%Query.Standard{q: "author:I*"}, %Query.Facet{field: ["cat", "author"], mincount: 1}]) # DisMax x = %Query.Dismax{q: "run", qf: "description^2.3 title", mm: "2<-25% 9<-3"} y = %Query.Common{rows: 10, start: 10, fq: ["edited:true"]} z = %Query.Facet{field: ["cat", "author"], mincount: 1} Hui.q([x, y, z]) ``` """ @spec q(query) :: http_response def q(query) when is_list(query), do: get(:default, query) @doc """ Convenience function for issuing various typical queries to the default Solr endpoint. ### Example ``` Hui.q("scott") Hui.q("loch", 10, 20) # .. with paging parameters Hui.q("\\\"apache documentation\\\"~5", 1, 0, "stream_content_type_str:text/html", ["subject"]) # .. plus filter(s) and facet fields ``` """ @spec q( binary, nil | integer, nil | integer, nil | binary | list(binary), nil | binary | list(binary), nil | binary ) :: http_response def q(keywords, rows \\ nil, start \\ nil, filters \\ nil, facet_fields \\ nil, sort \\ nil) def q(keywords, _, _, _, _, _) when is_nil_empty(keywords), do: {:error, %Error{reason: :einval}} def q(keywords, rows, start, filters, facet_fields, sort) do search(:default, keywords, rows, start, filters, facet_fields, sort) end @doc """ Issue a keyword list or structured query to a specified Solr endpoint. ### Example - parameters ``` url = "http://localhost:8983/solr/collection" # a keyword list of arbitrary parameters Hui.search(url, q: "edinburgh", rows: 10) # supply a list of Hui structs for more complex query e.g. DisMax alias Hui.Query x = %Query.DisMax{q: "run", qf: "description^2.3 title", mm: "2<-25% 9<-3"} y = %Query.Common{rows: 10, start: 10, fq: ["edited:true"]} z = %Query.Facet{field: ["cat", "author_str"], mincount: 1} Hui.search(url, [x, y, z]) # SolrCloud query x = %Query.DisMax{q: "john"} y = %Query.Common{collection: "library,commons", rows: 10, distrib: true, "shards.tolerant": true, "shards.info": true} Hui.search(url, [x,y]) # With results highlighting (snippets) x = %Query.Standard{q: "features:photo"} y = %Query.Highlight{fl: "features", usePhraseHighlighter: true, fragsize: 250, snippets: 3} Hui.search(url, [x, y]) ``` ### Example - faceting ``` alias Hui.Query range1 = %Query.FacetRange{range: "price", start: 0, end: 100, gap: 10, per_field: true} range2 = %Query.FacetRange{range: "popularity", start: 0, end: 5, gap: 1, per_field: true} x = %Query.DisMax{q: "ivan"} y = %Query.Facet{field: ["cat", "author_str"], mincount: 1, range: [range1, range2]} Hui.search(:default, [x, y]) ``` The above `Hui.search(:default, [x, y])` example issues a request that resulted in the following Solr response header showing the corresponding generated and encoded parameters. ```json "responseHeader" => %{ "QTime" => 106, "params" => %{ "f.popularity.facet.range.end" => "5", "f.popularity.facet.range.gap" => "1", "f.popularity.facet.range.start" => "0", "f.price.facet.range.end" => "100", "f.price.facet.range.gap" => "10", "f.price.facet.range.start" => "0", "facet" => "true", "facet.field" => ["cat", "author_str"], "facet.mincount" => "1", "facet.range" => ["price", "popularity"], "q" => "ivan" }, "status" => 0, "zkConnected" => true } ``` """ @spec search(endpoint, query) :: http_response def search(endpoint, query) when is_list(query) or is_map(query), do: get(endpoint, query) @doc """ Convenience function for issuing various typical queries to a specified Solr endpoint. See `q/6`. """ @spec search( endpoint, binary, nil | integer, nil | integer, nil | binary | list(binary), nil | binary | list(binary), nil | binary ) :: http_response def search(endpoint, keywords, rows \\ nil, start \\ nil, filters \\ nil, facet_fields \\ nil, sort \\ nil) def search(endpoint, keywords, _, _, _, _, _) when is_nil_empty(keywords) or is_nil_empty(endpoint), do: {:error, %Error{reason: :einval}} def search(endpoint, keywords, nil, nil, nil, nil, nil) do get(endpoint, %Query.Standard{q: keywords}) end def search(endpoint, keywords, rows, start, filters, facet_fields, sort) do get( endpoint, [ %Query.Standard{q: keywords}, %Query.Common{rows: rows, start: start, fq: filters, sort: sort}, %Query.Facet{field: facet_fields} ] ) end @doc """ Issue a structured suggest query to a specified Solr endpoint. ### Example ``` # :library is a configured endpoint suggest_query = %Hui.Query.Suggest{q: "ha", count: 10, dictionary: "name_infix"} Hui.suggest(:library, suggest_query) ``` """ @spec suggest(endpoint, Query.Suggest.t()) :: http_response def suggest(endpoint, %Query.Suggest{} = query), do: get(endpoint, query) @doc """ Convenience function for issuing a suggester query to a specified Solr endpoint. ### Example ``` # :autocomplete is a configured endpoint Hui.suggest(:autocomplete, "t") Hui.suggest(:autocomplete, "bo", 5, ["name_infix", "ln_prefix", "fn_prefix"], "1939") ``` """ @spec suggest(endpoint, binary, nil | integer, nil | binary | list(binary), nil | binary) :: http_response def suggest(endpoint, q, count \\ nil, dictionaries \\ nil, context \\ nil) def suggest(endpoint, q, _, _, _) when is_nil_empty(q) or is_nil_empty(endpoint) do {:error, %Error{reason: :einval}} end def suggest(endpoint, q, count, dictionaries, context) do get(endpoint, %Query.Suggest{q: q, count: count, dictionary: dictionaries, cfq: context}) end @doc """ Updates or adds Solr documents to an index or collection. This function accepts documents as map (single or a list) and commits the docs to the index immediately by default - set `commit` to `false` for manual or auto commits later. It can also operate in update struct and binary modes, the former uses the `t:Hui.Query.Update.t/0` struct while the latter acepts text containing any valid Solr update data or commands. An index/update handler endpoint should be specified through a URL string or {url, headers, options} tuple for headers and HTTP client options specification. A "content-type" request header is required so that Solr knows the incoming data format (JSON, XML etc.) and can process data accordingly. ### Example - map, list and binary data ``` # Index handler for JSON-formatted update headers = [{"content-type", "application/json"}] endpoint = {"http://localhost:8983/solr/collection/update", headers} # Solr docs in maps doc1 = %{ "actors" => ["<NAME>", "<NAME>", "<NAME>", "<NAME>"], "desc" => "A married daughter who longs for her mother's love is visited by the latter, a successful concert pianist.", "directed_by" => ["<NAME>"], "genre" => ["Drama", "Music"], "id" => "tt0077711", "initial_release_date" => "1978-10-08", "name" => "<NAME>" } doc2 = %{ "actors" => ["<NAME>", "<NAME>", "<NAME>"], "desc" => "A nurse is put in charge of a mute actress and finds that their personas are melding together.", "directed_by" => ["<NAME>"], "genre" => ["Drama", "Thriller"], "id" => "tt0060827", "initial_release_date" => "1967-09-21", "name" => "Persona" } Hui.update(endpoint, doc1) # add a single doc Hui.update(endpoint, [doc1, doc2]) # add a list of docs # Don't commit the docs e.g. mass ingestion when index handler is setup for autocommit. Hui.update(endpoint, [doc1, doc2], false) # Send to a configured endpoint Hui.update(:updater, [doc1, doc2]) # Binary mode, add and commit a doc Hui.update(endpoint, "{\\\"add\\\":{\\\"doc\\\":{\\\"name\\\":\\\"Blade Runner\\\",\\\"id\\\":\\\"tt0083658\\\",..}},\\\"commit\\\":{}}") # Binary mode, delete a doc via XML headers = [{"content-type", "application/xml"}] endpoint = {"http://localhost:8983/solr/collection/update", headers} Hui.update(endpoint, "<delete><id>9780141981727</id></delete>") ``` ### Example - `t:Hui.Query.Update.t/0` and other update options ``` # endpoint, doc1, doc2 from the above example ... # Hui.Query.Update struct command for updating and committing the docs to Solr within 5 seconds alias Hui.Query x = %Query.Update{doc: [doc1, doc2], commitWithin: 5000, overwrite: true} {status, resp} = Hui.update(endpoint, x) # Delete the docs by IDs, with a URL key from configuration {status, resp} = Hui.update(:library_update, %Query.Update{delete_id: ["tt1316540", "tt1650453"]}) # Commit and optimise index, keep max index segments at 10 {status, resp} = Hui.update(endpoint, %Query.Update{commit: true, waitSearcher: true, optimize: true, maxSegments: 10}) # Commit index, expunge deleted docs {status, resp} = Hui.update(endpoint, %Query.Update{commit: true, expungeDeletes: true}) ``` """ @spec update(endpoint, update_query, boolean) :: http_response def update(endpoint, docs, commit \\ true) def update(endpoint, docs, _commit) when is_binary(docs), do: post(endpoint, docs) def update(endpoint, %Query.Update{} = docs, _commit), do: post(endpoint, docs) def update(endpoint, docs, commit) when is_map(docs) or is_list(docs) do post(endpoint, %Query.Update{doc: docs, commit: commit}) end @doc """ Deletes Solr documents. This function accepts a single or list of IDs and immediately delete the corresponding documents from the Solr index (commit by default). An index/update handler endpoint should be specified through a URL string or {url, headers, options} tuple. A JSON "content-type" request header is required so that Solr knows the incoming data format and can process data accordingly. ### Example ``` # Index handler for JSON-formatted update headers = [{"content-type", "application/json"}] endpoint = {"http://localhost:8983/solr/collection/update", headers} Hui.delete(endpoint, "tt2358891") # delete a single doc Hui.delete(endpoint, ["tt2358891", "tt1602620"]) # delete a list of docs Hui.delete(endpoint, ["tt2358891", "tt1602620"], false) # delete without immediate commit ``` """ @spec delete(endpoint, binary | list(binary), boolean) :: http_response def delete(endpoint, ids, commit \\ true) when is_binary(ids) or is_list(ids) do post(endpoint, %Query.Update{delete_id: ids, commit: commit}) end @doc """ Deletes Solr documents by filter queries. This function accepts a single or list of filter queries and immediately delete the corresponding documents from the Solr index (commit by default). An index/update handler endpoint should be specified through a URL string or {url, headers, options} tuple. A JSON "content-type" request header is required so that Solr knows the incoming data format and can process data accordingly. ### Example ``` # Index handler for JSON-formatted update headers = [{"content-type", "application/json"}] endpoint = {"http://localhost:8983/solr/collection", headers} Hui.delete_by_query(endpoint, "name:Persona") # delete with a single filter Hui.delete_by_query(endpoint, ["genre:Drama", "name:Persona"]) # delete with a list of filters ``` """ @spec delete_by_query(endpoint, binary | list(binary), boolean) :: http_response def delete_by_query(endpoint, q, commit \\ true) when is_binary(q) or is_list(q) do post(endpoint, %Query.Update{delete_query: q, commit: commit}) end @doc """ Commit any added or deleted Solr documents to the index. This provides a (separate) mechanism to commit previously added or deleted documents to Solr index for different updating and index maintenance scenarios. By default, the commit waits for a new Solr searcher to be regenerated, so that the commit result is made available for search. An index/update handler endpoint should be specified through a URL string or {url, headers, options} tuple. A JSON "content-type" request header is required so that Solr knows the incoming data format and can process data accordingly. ### Example ``` # Index handler for JSON-formatted update headers = [{"content-type", "application/json"}] endpoint = {"http://localhost:8983/solr/collection", headers} Hui.commit(endpoint) # commits, make new docs available for search Hui.commit(endpoint, false) # commits op only, new docs to be made available later ``` Use `t:Hui.Query.Update.t/0` struct for other types of commit and index optimisation, e.g. expunge deleted docs to physically remove docs from the index, which could be a system-intensive operation. """ @spec commit(endpoint, boolean) :: http_response def commit(endpoint, wait_searcher \\ true) do post(endpoint, %Query.Update{commit: true, waitSearcher: wait_searcher}) end @doc """ Retrieves metrics data from the Solr admin API. ### Example ``` endpoint = {"http://localhost:8983/solr/admin/metrics", [{"content-type", "application/json"}]} Hui.metrics(endpoint, group: "core", type: "timer", property: ["mean_ms", "max_ms", "p99_ms"]) ``` """ @spec metrics(endpoint, keyword) :: http_response defdelegate metrics(endpoint, options), to: Hui.Admin @doc """ Ping the default configured endpoint. Successful ping returns a `{:pong, qtime}` tuple, whereas failure gets a `:pang` response. """ @spec ping() :: {:pong, integer} | :pang defdelegate ping(), to: Hui.Admin @doc """ Ping a given endpoint. ### Example ``` # ping a configured atomic endpoint Hui.ping(:gettingstarted) # directly ping a binary URL Hui.ping("http://localhost:8983/solr/gettingstarted/admin/ping") ``` Successful ping returns a `{:pong, qtime}` tuple, whereas failure gets a `:pang` response. """ @spec ping(binary() | atom()) :: {:pong, integer} | :pang defdelegate ping(endpoint), to: Hui.Admin @doc """ Ping a given endpoint with options. Raw HTTP response is returned when options such as `wt`, `distrib` is provided: ``` Hui.ping(:gettingstarted, wt: "xml", distrib: false) # -> returns {:ok, %Hui.HTTP{body: "raw HTTP response", status: 200, ..}} ``` """ @spec ping(binary() | atom(), keyword) :: http_response defdelegate ping(endpoint, options), to: Hui.Admin @doc """ Issues a get request of Solr query to a specific endpoint. The query can be a keyword list or a list of Hui query structs (`t:query/0`). ## Example - parameters ``` endpoint = "http://..." # query via a list of keywords, which are unbound and sent to Solr directly Hui.get(endpoint, q: "glen cova", facet: "true", "facet.field": ["type", "year"]) # query via Hui structs alias Hui.Query Hui.get(endpoint, %Query.DisMax{q: "glen cova"}) Hui.get(endpoint, [%Query.DisMax{q: "glen"}, %Query.Facet{field: ["type", "year"]}]) ``` The use of structs is more idiomatic and succinct. It is bound to qualified Solr fields. ## URLs, Headers, Options HTTP headers and client options for a specific endpoint may also be included in the a `{url, headers, options}` tuple where: - `url` is a typical Solr endpoint that includes a request handler - `headers`: a tuple list of [HTTP headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) - `options`: a keyword list of [Erlang httpc options](https://erlang.org/doc/man/httpc.html#request-4) or [HTTPoison options](https://hexdocs.pm/httpoison/HTTPoison.Request.html) if configured, e.g. `timeout`, `recv_timeout`, `max_redirect` If `HTTPoison` is used, advanced HTTP options such as the use of connection pools may also be specified via `options`. """ @spec get(endpoint, query) :: http_response def get(endpoint, query) do with {:ok, {url, headers, options}} <- Utils.parse_endpoint(endpoint) do %Http{ url: [url, "?", Encoder.encode(query)], headers: headers, options: options } |> dispatch(@http_client) else {:error, reason} -> {:error, reason} end end @doc """ Issues a POST request to a specific Solr endpoint, e.g. for data indexing and deletion. """ @spec post(endpoint, update_query) :: http_response def post(endpoint, docs) do with {:ok, {url, headers, options}} <- Utils.parse_endpoint(endpoint) do %Http{ url: url, headers: headers, method: :post, options: options, body: if(is_binary(docs), do: docs, else: Encoder.encode(docs)) } |> dispatch(@http_client) else {:error, reason} -> {:error, reason} end end end
lib/hui.ex
0.881008
0.745468
hui.ex
starcoder
defmodule MarcoPolo.REST do @moduledoc """ This module provides an interface to the functionalities exposed by OrientDB's REST API. Not all the functionalities that OrientDB exposes are available through the binary protocol that `MarcoPolo` uses: some of them are only available through the HTTP REST API. These functionalities are exposed by this module. The functions in this module are "stateless", so they can be just run without any connection setup (e.g., like what needs to be done with `MarcoPolo.start_link/1` for the binary protocol). ## Options The following is a list of options that functions in this module accept; they're used to handle the connection (e.g., where to connect to, what's the user and the password, and so on). * `:host` - (binary) the host where the OrientDB server is running. Defaults to `"localhost"`. * `:port` - (integer) the port where the OrientDB server is exposing the HTTP REST API. Defaults to `2480`. * `:user` - (binary) the user to use. Mandatory. * `:password` - (binary) the password to use. Mandatory. * `:scheme` - (binary) the scheme to use to connect to the server. Defaults to `"http"`. """ require Logger @default_headers [{"Accept-Encoding", "gzip,deflate"}] @doc """ Imports the database dumped at `db_path` into `destination_database`. This function takes the path to a JSON dump of a database (`db_path`), and imports that dump to the `destination_database`. `opts` is a list of options used for connecting to the REST API of the OrientDB server. You can read more about these options in the documentation for this module. Returns just `:ok` if the import is successful, `{:error, reason}` if anything goes wrong (e.g., the connection to the OrientDB server is unsuccessful or the database cannot be imported). ## Examples opts = [user: "root", password: "<PASSWORD>"] MarcoPolo.REST.import("DestDb", "/path/to/db.json", opts) #=> :ok """ @spec import(binary, Path.t, Keyword.t) :: :ok | {:error, term} def import(destination_database, db_path, opts) when is_binary(destination_database) and is_binary(db_path) and is_list(opts) do url = URI.to_string(%URI{ scheme: Keyword.get(opts, :scheme, "http"), host: Keyword.get(opts, :host, "localhost"), port: Keyword.get(opts, :port, 2480), path: "/import/#{destination_database}", }) headers = [{"Content-Type", "application/json"} | @default_headers] body = File.read!(db_path) options = [ basic_auth: {Keyword.fetch!(opts, :user), Keyword.fetch!(opts, :password)}, ] case :hackney.request(:post, url, headers, body, options) do {:ok, 200, _headers, body_ref} -> :hackney.skip_body(body_ref) :ok {:ok, status, _headers, body_ref} -> {:ok, body} = :hackney.body(body_ref) {:error, "error while importing (status #{status}): #{body}"} {:error, _} = error -> error end end end
lib/marco_polo/rest.ex
0.835349
0.602062
rest.ex
starcoder
defmodule Cards do @moduledoc """ This module provides methods to handle `Cards` operations like shuffle and creates. """ @doc """ This method creates a full deck ## Examples iex> Cards.create_deck ["Ace Spades", "Two Spades", "Three Spades", "Five Spades", "Ace Clubs", "Two Clubs", "Three Clubs", "Five Clubs", "Ace Heart", "Two Heart", "Three Heart", "Five Heart", "Ace Diamonds", "Two Diamonds", "Three Diamonds", "Five Diamonds"] """ def create_deck do values = ["Ace", "Two", "Three", "Five"] suits = ["Spades", "Clubs", "Heart", "Diamonds"] for suit <- suits, value <- values do newValue = value <> " " <> suit end end @doc """ This method shuffles the cards of a `deck` and returns a `deck` ## Examples iex(2)> deck = Cards.create_deck ["Ace Spades", "Two Spades", "Three Spades", "Five Spades", "Ace Clubs", "Two Clubs", "Three Clubs", "Five Clubs", "Ace Heart", "Two Heart", "Three Heart", "Five Heart", "Ace Diamonds", "Two Diamonds", "Three Diamonds", "Five Diamonds"] iex> shuffled_deck = Cards.shuffle(deck) iex> shuffled_deck == deck false iex> Enum.member?(shuffled_deck, "Ace Spades") true """ def shuffle(deck) do Enum.shuffle(deck) end @doc """ This method checks if the card is in deck or not and returns a boolean(atom -> :true or :false) It has two arguments: `deck` and the `element` we want to check ## Examples iex> deck = ["a", "b", "c"] iex> Cards.contains(deck, "a") true iex> Cards.contains(deck, "d") false """ def contains(deck, element) do result = Enum.find(deck, fn x -> x == element end) if result do true else false end end @doc """ This method saves the deck in the file name that we give in arguments It has two arguments: `deck` and `filename` which is the name of the file that we want to save our data ## Examples iex> Cards.save(["simple", "deck"], "newFile") :ok """ def save(deck, filename) do binary = :erlang.term_to_binary(deck) File.write(filename, binary) end @doc """ This method loads a deck from the file that we give in the arguments It has one argument `filename` which is the name of the file that we want to read the deck. ## Examples iex> Cards.load("newFile") ["simple", "deck"] iex> Cards.load("newFileFFF") "File does not exist." """ def load(filename) do case File.read(filename) do { :ok, binary } -> :erlang.binary_to_term(binary) { :error, _reason } -> "File does not exist." end end @doc """ This method first creates a deck and after that shuffles it and return it. We use pipes to execute these two functionalities together ## Examples iex> hand = Cards.create_hand iex> deck = Cards.create_deck iex> hand == deck false """ def create_hand do create_deck |> shuffle end end
cards/lib/cards.ex
0.833053
0.580174
cards.ex
starcoder
defmodule Dynamo.Static do @moduledoc false use GenServer.Behaviour @doc """ Looks up a static asset in the given Dynamo. If the static asset exists, it returns the asset path appended with a query string containing the last modification time of the asset. """ def lookup(dynamo, path) do path = normalize_path(path) { ets, server } = dynamo.static_cache case :ets.lookup(ets, path) do [{ ^path, result }] -> result _ -> :gen_server.call(server, { :lookup, path }) end end defp normalize_path("/" <> bin), do: bin defp normalize_path(bin), do: bin ## Backend @doc false def start_link(dynamo) do { _ets, server } = dynamo.static_cache :gen_server.start({ :local, server }, __MODULE__, dynamo, []) end @doc false def stop(dynamo) do { _ets, server } = dynamo.static_cache :gen_server.call(server, :stop) end defmodule Config do defstruct [:ets, :route, :root, :cache] end @doc false def init(dynamo) do config = dynamo.config[:dynamo] root = Path.expand(config[:static_root], dynamo.root) route = config[:static_route] cache = config[:cache_static] { ets, _server } = dynamo.static_cache :ets.new(ets, [:set, :protected, :named_table, { :read_concurrency, true }]) { :ok, %Config{ets: ets, route: route, root: root, cache: cache} } end @doc false def handle_call({ :lookup, path }, _from, %Config{} = config) do result = static_path(path, config) if config.cache, do: :ets.insert(config.ets, { path, result }) { :reply, result, config } end def handle_call(:stop, _from, config) do { :stop, :normal, :ok, config } end def handle_call(msg, from, config) do super(msg, from, config) end ## Server helpers defp static_path(path, %Config{} = config) do case File.stat(Path.join(config.root, path)) do { :ok, %File.Stat{mtime: mtime, type: type} } when type != :directory and is_tuple(mtime) -> seconds = :calendar.datetime_to_gregorian_seconds(mtime) Path.join(config.route, [path, ??, integer_to_list(seconds)]) _ -> Path.join(config.route, path) end end end
lib/dynamo/static.ex
0.620966
0.440048
static.ex
starcoder
defmodule Esolix.Langs.Piet do @moduledoc """ Documentation for the Piet Module """ # Data Structure used alias Esolix.DataStructures.Stack import ExUnit.CaptureIO @typedoc """ List containing lines of pixels. """ @type pixels :: list(pixel_line()) @typedoc """ List of pixels, represented as RGB values. """ @type pixel_line :: list(pixel_rgb) @typedoc """ Tuple, representing a Pixel by its RGB values: {Red, Green, Blue} """ @type pixel_rgb :: {non_neg_integer(), non_neg_integer(), non_neg_integer()} # # Custom Module Errors # defmodule CustomModuleError do # @moduledoc false # defexception [:message] # def exception() do # msg = "Something went wrong I think" # %CustomModuleError{message: msg} # end # end defmodule Codel do @moduledoc false defstruct [:color, :hue] end defmodule PietExecutor do @moduledoc false defstruct [:codels, :stack, :dp, :cc, :codel_coord, :codel_current, :locked_in_attempts] end @colors %{ white: {255, 255, 255}, black: {0, 0, 0}, light_red: {255, 192, 192}, red: {255, 0, 0}, dark_red: {192, 0, 0}, light_yellow: {255, 255, 192}, yellow: {255, 255, 0}, dark_yellow: {192, 192, 0}, light_green: {192, 255, 192}, green: {0, 255, 0}, dark_green: {0, 192, 0}, light_cyan: {192, 255, 255}, cyan: {0, 255, 255}, dark_cyan: {0, 192, 192}, light_blue: {192, 192, 255}, blue: {0, 0, 255}, dark_blue: {0, 0, 192}, light_magenta: {255, 192, 255}, magenta: {255, 0, 255}, dark_magenta: {192, 0, 192} } @hue_cycle [:light, :normal, :dark] @color_cycle [:red, :yellow, :green, :cyan, :blue, :magenta] @spec eval(pixels(), keyword()) :: String.t() @doc """ Run Piet Code (represented as pixels, represented as RGB values) and returns the IO output as a string. ## Examples iex> Piet.eval("some hello world code") "Hello World!" """ def eval(pixels, _params \\ []) do capture_io(fn -> execute(pixels) end) end @spec eval_file(String.t(), keyword()) :: String.t() @doc """ Runs Piet Code from a .png file and returns the IO output as a string ## Examples iex> Piet.eval_file("path/to/some/hello_world.file") "Hello World!" """ def eval_file(file, params \\ []) do validate_file(file) |> extract_pixels() |> eval(params) end @spec execute(pixels(), keyword()) :: :ok @doc """ Run Piet Code (represented as pixels, represented as RGB values). ## Examples iex> Piet.execute("some hello world code") "Hello World!" :ok """ def execute(pixels, _params \\ []) do codels = pixels_to_codels(pixels) piet_exec = %PietExecutor{ codels: codels, stack: Stack.init(), codel_coord: {0, 0}, codel_current: Enum.at(codels, 0) |> Enum.at(0), dp: :right, cc: :left, locked_in_attempts: 0 } execute_step(piet_exec) :ok end @spec execute_file(String.t(), keyword()) :: :ok @doc """ Run Piet Code from a .png file. ## Examples iex> Piet.eval_file("path/to/some/hello_world.png") "Hello World!" :ok """ def execute_file(file, params \\ []) do validate_file(file) |> extract_pixels() |> execute(params) :ok end defp execute_step( %PietExecutor{ stack: stack, codels: codels, codel_coord: codel_coord, codel_current: codel_current, dp: dp, cc: cc, locked_in_attempts: locked_in_attempts } = piet_exec ) do next_coords = next_coordinates(codels, codel_coord, dp, cc) next_codel = codel_at(codels, next_coords) # debug(piet_exec, next_coords, next_codel, block_size(codels, codel_coord)) cond do # Case 1: Max number of locked in attempts reached, terminate program locked_in_attempts == 8 -> piet_exec # Case 2: Next Codel is black or edge: toggle cc or dp and try again next_codel in [nil, %Codel{color: :black, hue: :none}] -> execute_step(%{ piet_exec | cc: maybe_toggle_cc(cc, locked_in_attempts), dp: maybe_toggle_dp(dp, locked_in_attempts), locked_in_attempts: locked_in_attempts + 1 }) # Case 3: Next Codel is white: next_codel == %Codel{color: :white, hue: :none} -> execute_step(%{ piet_exec | codel_coord: next_coords, codel_current: next_codel, locked_in_attempts: 0 }) # Case 4: Next Codel is another valid color, parse command true -> color_difference = color_difference(codel_current, next_codel) hue_difference = hue_difference(codel_current, next_codel) piet_exec = execute_command(piet_exec, {color_difference, hue_difference}) execute_step(%{ piet_exec | codel_coord: next_coords, codel_current: next_codel, locked_in_attempts: 0 }) end end defp execute_command( %PietExecutor{ stack: stack, codels: codels, codel_coord: codel_coord, dp: dp, cc: cc } = piet_exec, {color_difference, hue_difference} ) do # debug({color_difference, hue_difference}) case {color_difference, hue_difference} do # Push {0, 1} -> stack = Stack.push(stack, block_size(codels, codel_coord)) %{piet_exec | stack: stack} # Pop {0, 2} -> {_, stack} = Stack.pop(stack) %{piet_exec | stack: stack} # Add {1, 0} -> %{piet_exec | stack: Stack.add(stack)} # Sub {1, 1} -> %{piet_exec | stack: Stack.sub(stack, order: :reverse)} # Mul {1, 2} -> %{piet_exec | stack: Stack.mul(stack)} # Div {2, 0} -> %{piet_exec | stack: Stack.div(stack, order: :reverse)} # Mod {2, 1} -> %{piet_exec | stack: Stack.apply(stack, &Integer.mod/2, order: :reverse)} # Not {2, 2} -> %{piet_exec | stack: Stack.logical_not(stack, order: :reverse)} # Greater than {3, 0} -> %{piet_exec | stack: Stack.greater_than(stack)} # Rotate Direction Pointer {3, 1} -> {rotations, stack} = Stack.pop(stack) dp = rotate_dp(dp, rotations) %{piet_exec | stack: stack, dp: dp} # Toggle Codel Chooser {3, 2} -> {toggles, stack} = Stack.pop(stack) cc = toggle_cc(cc, toggles) %{piet_exec | stack: stack, cc: cc} # Duplicate {4, 0} -> %{piet_exec | stack: Stack.duplicate(stack)} # Roll {4, 1} -> {rolls, stack} = Stack.pop(stack) {depth, stack} = Stack.pop(stack) {elements_to_roll, stack} = Stack.popn(stack, depth) stack = Stack.push(stack, roll(elements_to_roll, rolls) |> Enum.reverse()) %{piet_exec | stack: stack} # Input Number {4, 2} -> input = IO.gets("") |> String.trim() |> String.to_integer() %{piet_exec | stack: Stack.push(stack, input)} # Input Char {5, 0} -> input = IO.gets("") |> String.to_charlist() |> Enum.at(0) %{piet_exec | stack: Stack.push(stack, [input])} # Output Number {5, 1} -> {output, stack} = Stack.pop(stack) IO.write(output) %{piet_exec | stack: stack} # Output Char {5, 2} -> {output, stack} = Stack.pop(stack) IO.write([output]) %{piet_exec | stack: stack} {nil, nil} -> piet_exec other -> raise "Error, invalid command: #{other}" end end defp maybe_toggle_cc(cc, locked_in_attempts) do if rem(locked_in_attempts, 2) == 0 do toggle_cc(cc) else cc end end defp toggle_cc(cc, toggles \\ 1) do case {cc, rem(toggles, 2)} do {:left, 1} -> :right {:right, 1} -> :left _ -> cc end end defp maybe_toggle_dp(dp, locked_in_attempts) do if rem(locked_in_attempts, 2) == 1 do rotate_dp(dp, 1) else dp end end defp rotate_dp(dp, rotations) do direction = if rotations > 0, do: :clockwise, else: :counterclockwise rotations = abs(rotations) dp_cycle = case direction do :clockwise -> [:left, :up, :right, :down] :counterclockwise -> [:left, :down, :right, :up] end current = Enum.find_index(dp_cycle, &(&1 == dp)) next = Integer.mod(current + rotations, 4) Enum.at(dp_cycle, next) end defp roll(elements, 0), do: elements defp roll(elements, rolls) when rolls < 0 do elements = Enum.reverse(elements) rolls = -rolls Enum.reduce(1..rolls, elements, fn _elem, acc -> [head | tail] = acc tail ++ [head] end) |> Enum.reverse() end defp roll(elements, rolls) do Enum.reduce(1..rolls, elements, fn _elem, acc -> [head | tail] = acc tail ++ [head] end) end defp codel_at(codels, {x, y}) do if -1 in [x, y] do nil else line = Enum.at(codels, y) if line, do: Enum.at(line, x), else: nil end end defp next_coordinates(codels, {x, y}, dp, cc) do color_block(codels, {x, y}) |> furthest_dp(dp) |> furthest_cc(dp, cc) |> Enum.at(0) |> neighbor_coordinate(dp) end defp furthest_dp(coords, dp) do max_function = case dp do :left -> fn {x, _y} -> -x end :up -> fn {_x, y} -> -y end :right -> fn {x, _y} -> x end :down -> fn {_x, y} -> y end _ -> raise "Invalid direction pointer value" end {max_x, max_y} = Enum.max_by(coords, max_function) filter_function = cond do dp in [:left, :right] -> fn {x, _y} -> x == max_x end dp in [:up, :down] -> fn {_x, y} -> y == max_y end end Enum.filter(coords, filter_function) end defp furthest_cc(coords, dp, cc) do # Since the Codel Chooser direction is relative to the absolute Direction Pointer direction, we must translate it into an absoulte direction # This is achieved by rotating the Direction Pointer once into the direction of the Codel Chooser cc_absolute = case cc do :left -> rotate_dp(dp, -1) :right -> rotate_dp(dp, 1) end # Now we can just run furthest_dp again, using the already filtered coordinates and the absolute Codel Chooser direction instead of the Direction Pointer furthest_dp(coords, cc_absolute) end defp neighbor_coordinate({x, y}, dp) do case dp do :left -> left({x, y}) :right -> right({x, y}) :up -> up({x, y}) :down -> down({x, y}) end end defp validate_file(file) do case {File.exists?(file), Path.extname(file) |> String.downcase()} do {false, _} -> raise "File #{file} does not exist" {true, ".png"} -> file _ -> raise "File #{file} is not a png" end end defp extract_pixels(file) do case Imagineer.load(file) do {:ok, image_data} -> Map.get(image_data, :pixels) _ -> raise "Error while extracting PNG image data" end end defp pixels_to_codels(pixels) do pixels |> Enum.map(fn line -> line |> Enum.map(fn pixel -> pixel_to_codel(pixel) end) end) end defp pixel_to_codel(pixel) do @colors |> Enum.find(fn {_color_name, color_value} -> color_value == pixel end) |> case do nil -> # Treat other colors as white %Codel{color: :white, hue: :none} {hue_and_color, _color_value} -> %Codel{color: get_color(hue_and_color), hue: get_hue(hue_and_color)} end end defp get_hue(hue_and_color) do Atom.to_string(hue_and_color) |> String.split("_") |> Enum.at(0) |> case do "white" -> :none "black" -> :none "light" -> :light "dark" -> :dark _ -> :normal end end defp get_color(hue_and_color) do Atom.to_string(hue_and_color) |> String.split("_") |> List.last() |> String.to_atom() end defp hue_difference(%Codel{hue: hue_1}, %Codel{hue: hue_2}), do: hue_difference(hue_1, hue_2) defp hue_difference(hue_1, hue_2) do if :none in [hue_1, hue_2] do nil else Integer.mod( hue_index(hue_2) - hue_index(hue_1), length(@hue_cycle) ) end end defp color_difference(%Codel{color: color_1}, %Codel{color: color_2}), do: color_difference(color_1, color_2) defp color_difference(color_1, color_2) do if Enum.any?([color_1, color_2], &(&1 in [:black, :white])) do nil else Integer.mod( color_index(color_2) - color_index(color_1), length(@color_cycle) ) end end def color_block(codels, {_x, _y} = coords) do get_all_identical_neighbors(codels, %{unchecked: [coords], checked: []}) end defp block_size(codels, {_x, _y} = coords) do get_all_identical_neighbors(codels, %{unchecked: [coords], checked: []}) |> length() end defp get_all_identical_neighbors( codels, %{unchecked: unchecked_coords, checked: checked_coords} ) do unchecked_coords_neighbors = unchecked_coords |> Enum.map(fn coords -> get_identical_neighbors(codels, coords) end) |> List.flatten() |> Enum.uniq() checked_coords_updated = Enum.uniq(checked_coords ++ unchecked_coords) if Enum.sort(checked_coords_updated) == Enum.sort(checked_coords) do # No new neighbors found, end search checked_coords else # Check neighbors of the newfound unchecked neighbors get_all_identical_neighbors(codels, %{ unchecked: unchecked_coords_neighbors, checked: checked_coords_updated }) end end defp get_identical_neighbors(codels, {_x, _y} = coords) do curr_codel = codel_at(codels, coords) up = if codel_at(codels, up(coords)) == curr_codel, do: up(coords) left = if codel_at(codels, left(coords)) == curr_codel, do: left(coords) right = if codel_at(codels, right(coords)) == curr_codel, do: right(coords) down = if codel_at(codels, down(coords)) == curr_codel, do: down(coords) Enum.filter([up, left, right, down], & &1) end defp color_index(:red), do: 0 defp color_index(:yellow), do: 1 defp color_index(:green), do: 2 defp color_index(:cyan), do: 3 defp color_index(:blue), do: 4 defp color_index(:magenta), do: 5 defp color_index(_other), do: :none defp hue_index(:light), do: 0 defp hue_index(:normal), do: 1 defp hue_index(:dark), do: 2 defp hue_index(_other), do: :none defp up({x, y}), do: {x, y - 1} defp right({x, y}), do: {x + 1, y} defp down({x, y}), do: {x, y + 1} defp left({x, y}), do: {x - 1, y} defp debug({c_dif, h_dif}) do output = case {c_dif, h_dif} do {0, 1} -> "push" {0, 2} -> "pop" {1, 0} -> "add" {1, 1} -> "sub" {1, 2} -> "mul" {2, 0} -> "div" {2, 1} -> "mod" {2, 2} -> "not" {3, 0} -> "greater" {3, 1} -> "pointer" {3, 2} -> "switch" {4, 0} -> "duplicate" {4, 1} -> "roll" {4, 2} -> "in number" {5, 0} -> "in char" {5, 1} -> "out number" {5, 2} -> "out char" {nil, nil} -> "white into other" _ -> "other" end if output != "" do IO.puts("\n\n COMMAND: #{String.upcase(output)}") end end defp debug( %PietExecutor{ stack: stack, # codels: codels, codel_coord: {x, y}, codel_current: codel_current, dp: dp, cc: cc, locked_in_attempts: locked_in_attempts }, next_coords, next_codel, block_size ) do IO.gets("\n\nNext Step?") IO.inspect(binding()) end end
lib/langs/piet.ex
0.841435
0.485661
piet.ex
starcoder
defmodule Intcode do def state_to_int_list(state) do state |> String.split(",") |> Enum.map(fn s -> String.to_integer(String.trim(s)) end) end def state_to_int_map(state) do state |> String.split(",") |> Enum.with_index() |> Enum.map(fn {v, idx} -> {idx, String.to_integer(String.trim(v))} end) |> Map.new() end def map_to_list(m) do m |> Map.to_list() |> Enum.sort(fn {k1, _}, {k2, _} -> k1 <= k2 end) |> Enum.map(fn {_, v} -> v end) end @opcode_input_to 3 @opcode_output_value 4 @opcode_jump_if_true 5 @param_position_mode 0 @param_immediate_mode 1 @param_relative_mode 2 def get_value_in_position_mode(ns, index) do ns[ns[index]] || 0 end def compute(opcodes, position, input \\ [], outputs \\ [], relative_base \\ 0, parent \\ nil) do # oc = Map.get(opcodes, position) oc = opcodes[position] # IO.inspect({"oc", position}) # IO.inspect( # {"oc", oc, position, "input", input, "output", outputs, "relative_base", relative_base} # ) if oc == 99 do if parent do send(parent, {:finish, outputs}) end {opcodes, outputs} else param_opcode = Integer.to_string(oc) {opcode, param_modes} = if String.length(param_opcode) == 1 do {"0" <> param_opcode, [?0, ?0, ?0]} else {String.slice(param_opcode, -2, 2), String.slice(param_opcode, 0, String.length(param_opcode) - 2) |> String.pad_leading(3, "0") |> String.to_charlist()} end modes = Enum.map(param_modes, fn x -> x - ?0 end) [marg1, marg2, marg3] = modes |> Enum.reverse() # IO.inspect({"Margs", [marg1, marg2, marg3]}) # map params mode with params, calculate arg1 = Map.get(opcodes, position + 1) arg1 = cond do marg1 == @param_position_mode -> Map.get(opcodes, arg1) || 0 marg1 == @param_relative_mode -> # IO.inspect({"relative_base", relative_base}) Map.get(opcodes, arg1 + relative_base) || 0 true -> arg1 end arg2 = Map.get(opcodes, position + 2) arg2 = cond do marg2 == @param_position_mode -> Map.get(opcodes, arg2) || 0 marg2 == @param_relative_mode -> Map.get(opcodes, arg2 + relative_base) || 0 true -> arg2 end # IO.inspect( # {"oc", oc, position, "raw", # {opcodes[position + 1], opcodes[position + 2], opcodes[position + 3]}, "arg1", arg1, # "arg2", arg2, "relative_base", relative_base} # ) cond do opcode == "01" -> f = &(&1 + &2) address = if marg3 == @param_relative_mode do opcodes[position + 3] + relative_base else opcodes[position + 3] end opcodes = Map.put(opcodes, address, f.(arg1, arg2)) compute(opcodes, position + 4, input, outputs, relative_base, parent) opcode == "02" -> f = &(&1 * &2) address = if marg3 == @param_relative_mode do opcodes[position + 3] + relative_base else opcodes[position + 3] end opcodes = Map.put(opcodes, address, f.(arg1, arg2)) compute(opcodes, position + 4, input, outputs, relative_base, parent) opcode == "03" -> input = if input == [] do receive do {:color, color} -> # IO.inspect({"child received color", color}) [color] e -> IO.inspect({"ERROR", e}) raise "Child receive bad msg" end else input end [h | t] = input address = if marg1 == @param_relative_mode do opcodes[position + 1] + relative_base else opcodes[position + 1] end # IO.inspect({"Code 03 put input value", h, "to", address}) opcodes = Map.put(opcodes, address, h) compute(opcodes, position + 2, t, outputs, relative_base, parent) opcode == "04" -> # note: reversed as we prepend list out = [arg1 | outputs] out = if parent && length(out) == 2 do [direction, color_to_paint] = out send(parent, {:day11, color_to_paint, direction}) [] else out end compute(opcodes, position + 2, input, out, relative_base, parent) opcode == "05" -> if arg1 != 0 do compute(opcodes, arg2, input, outputs, relative_base, parent) else compute(opcodes, position + 3, input, outputs, relative_base, parent) end opcode == "06" -> # IO.inspect({"Jump if false", arg1, arg2}) if arg1 == 0 do compute(opcodes, arg2, input, outputs, relative_base, parent) else compute(opcodes, position + 3, input, outputs, relative_base, parent) end opcode == "07" -> address = if marg3 == @param_relative_mode do opcodes[position + 3] + relative_base else opcodes[position + 3] end if arg1 < arg2 do opcodes = Map.put(opcodes, address, 1) compute(opcodes, position + 4, input, outputs, relative_base, parent) else opcodes = Map.put(opcodes, address, 0) compute(opcodes, position + 4, input, outputs, relative_base, parent) end opcode == "08" -> address = if marg3 == @param_relative_mode do opcodes[position + 3] + relative_base else opcodes[position + 3] end if arg1 == arg2 do opcodes = Map.put(opcodes, address, 1) compute(opcodes, position + 4, input, outputs, relative_base, parent) else opcodes = Map.put(opcodes, address, 0) compute(opcodes, position + 4, input, outputs, relative_base, parent) end opcode == "09" -> # IO.inspect({"relative add", relative_base, arg1}) compute(opcodes, position + 2, input, outputs, relative_base + arg1, parent) true -> IO.inspect({"BUG", param_opcode, arg1, arg2, opcode, position}) raise "99" end end end def run(state, input \\ [0]) do opcodes = state_to_int_map(state) {opcodes, _} = compute(opcodes, 0, input) opcodes end def check_output(state, input) do # opcodes = state_to_int_list(state) opcodes = state_to_int_map(state) {_, outputs} = compute(opcodes, 0, input) outputs = Enum.reverse(outputs) List.last(outputs) end def check_raw_output(state, input, parent \\ nil) do # opcodes = state_to_int_list(state) opcodes = state_to_int_map(state) {_, outputs} = compute(opcodes, 0, input, [], 0, parent) outputs = Enum.reverse(outputs) outputs end end
lib/intcode.ex
0.638159
0.473353
intcode.ex
starcoder
defmodule Kiq.Reporter do @moduledoc """ Job handling is performed by reporters, which are customized `GenStage` consumers. This module specifies the reporter behaviour and provies an easy way to define new reporters via `use Kiq.Reporter`. The `using` macro defines all necessary `GenStage` functions and defines no-op handlers for all events. ## Example Custom Reporter Custom reporters may be defined within your application. One common use-case for custom reporters would be reporting exceptions to a tracking service. Here we will define a reporter for [Honeybadger](https://honeybadger.io): defmodule MyApp.Reporters.Honeybadger do @moduledoc false use Kiq.Reporter @impl Kiq.Reporter def handle_failure(job, error, stacktrace, state) do metadata = Map.take(job, [:jid, :class, :args, :queue, :retry_count]) :ok = Honeybadger.notify(error, metadata, stacktrace) state end end Next you'll need to specify the reporter inside your application's `Kiq` module, using `extra_reporters`: defmodule MyApp.Kiq do @moduledoc false alias MyApp.Reporters.Honeybadger use Kiq, queues: [default: 50], extra_reporters: [Honeybadger] end This guarantees that your reporter will be supervised by the reporter supervisor, and that it will be re-attached to the reporter producer upon restart if the reporter crashes. ## Notes About State Handler functions are always invoked with the current state. The return value of each handler function will be used as the updated state after all events are processed. """ alias Kiq.{Config, Job} @type options :: [config: Config.t(), name: identifier()] @type state :: any() @doc """ Emitted when a worker starts processing a job. """ @callback handle_started(job :: Job.t(), state :: state()) :: state() @doc """ Emitted when a worker has completed a job and no failures ocurred. """ @callback handle_success(job :: Job.t(), meta :: Keyword.t(), state :: state()) :: state() @doc """ Emitted when job processing has been intentionally aborted. """ @callback handle_aborted(job :: Job.t(), meta :: Keyword.t(), state :: state()) :: state() @doc """ Emitted when an exception ocurred while processing a job. """ @callback handle_failure( job :: Job.t(), error :: Exception.t(), stack :: list(), state :: state() ) :: state() @doc """ Emitted when the worker has completed the job, regardless of whether it succeded or failed. """ @callback handle_stopped(job :: Job.t(), state :: state()) :: state() @doc false defmacro __using__(_opts) do quote do use GenStage alias Kiq.Reporter @behaviour Reporter @doc false @spec start_link(opts :: Reporter.options()) :: GenServer.on_start() def start_link(opts) do {name, opts} = Keyword.pop(opts, :name) GenStage.start_link(__MODULE__, opts, name: name) end @impl GenStage def init(opts) do opts = Keyword.delete(opts, :config) {:consumer, :ok, opts} end @impl GenStage def handle_events(events, _from, state) do new_state = Enum.reduce(events, state, fn event, state -> case event do {:started, job} -> handle_started(job, state) {:success, job, meta} -> handle_success(job, meta, state) {:aborted, job, meta} -> handle_aborted(job, meta, state) {:failure, job, error, stack} -> handle_failure(job, error, stack, state) {:stopped, job} -> handle_stopped(job, state) end end) {:noreply, [], new_state} end @impl Reporter def handle_started(_job, state), do: state @impl Reporter def handle_success(_job, _meta, state), do: state @impl Reporter def handle_aborted(_job, _meta, state), do: state @impl Reporter def handle_failure(_job, _error, _stack, state), do: state @impl Reporter def handle_stopped(_job, state), do: state defoverridable start_link: 1, init: 1, handle_events: 3, handle_aborted: 3, handle_failure: 4, handle_started: 2, handle_stopped: 2, handle_success: 3 end end end
lib/kiq/reporter.ex
0.902382
0.469581
reporter.ex
starcoder
defmodule Cryptopunk.Crypto.Dogecoin do @moduledoc """ Dogecoin address generation logic. It's similar to bitcoin legacy addresses. """ alias Cryptopunk.Crypto.Bitcoin alias Cryptopunk.Key @version_bytes %{ mainnet: 30, testnet: 113 } @doc """ Generate a dogecoin address. It accepts three parameters: - public or private key. if a private key is provided, it will be converted to public key. - network (`:mainnet` or `:testnet`) - optional keyword params. Currently, the only allowed parameter is `:uncompressed` key. Passing `[uncompressed: true]` will generate the address from the uncompressed public key which is not advised. but it may be required for compatibility reasons Examples: iex> private_key = %Cryptopunk.Key{key: <<16, 42, 130, 92, 247, 244, 62, 96, 24, 129, 187, 141, 124, 42, 176, 116, 234, 171, 184, 107, 3, 229, 255, 72, 30, 116, 79, 243, 36, 142, 184, 24>>, type: :private} iex> Cryptopunk.Crypto.Dogecoin.address(private_key, :mainnet) "DNoni2tA31AaaRgdSKnzBXyvTTFyabwPKi" iex> public_key = %Cryptopunk.Key{key: <<4, 57, 163, 96, 19, 48, 21, 151, 218, 239, 65, 251, 229, 147, 160, 44, 197, 19, 208, 181, 85, 39, 236, 45, 241, 5, 14, 46, 143, 244, 156, 133, 194, 60, 190, 125, 237, 14, 124, 230, 165, 148, 137, 107, 143, 98, 136, 143, 219, 197, 200, 130, 19, 5, 226, 234, 66, 191, 1, 227, 115, 0, 17, 98, 129>>, type: :public} iex> Cryptopunk.Crypto.Dogecoin.address(public_key, :testnet) "nYxUariD3FNhvYrgVHGQk6y68aBtLHP87b" iex> private_key = %Cryptopunk.Key{key: <<16, 42, 130, 92, 247, 244, 62, 96, 24, 129, 187, 141, 124, 42, 176, 116, 234, 171, 184, 107, 3, 229, 255, 72, 30, 116, 79, 243, 36, 142, 184, 24>>, type: :private} iex> Cryptopunk.Crypto.Dogecoin.address(private_key, :mainnet, uncompressed: true) "DEyc1dTk53Uzvb9fomq89vXSFZxc2ZcRbs" """ @spec address(Key.t(), atom(), Keyword.t()) :: String.t() def address(private_or_public_key, net, opts \\ []) do version_byte = Map.fetch!(@version_bytes, net) Bitcoin.legacy_address(private_or_public_key, version_byte, opts) end end
lib/cryptopunk/crypto/dogecoin.ex
0.846006
0.42913
dogecoin.ex
starcoder
defmodule BahnEx do @moduledoc """ An Elixir wrapper for the [Deutsche Bahn (DB) Fahrplan API](https://developer.deutschebahn.com/store/apis/info?name=Fahrplan&version=v1&provider=DBOpenData) """ @doc """ Get information about locations matching the given name or name fragment `name_or_fragment` Returns a list of `%BahnEx.Location{}` ## Examples iex>BahnEx.location("Dresden") [%BahnEx.Location{id: 8010085, lat: 51.040562, lon: 13.732039, name: "Dresden Hbf"}, %BahnEx.Location{id: 8010089, lat: 51.065903, lon: 13.740704, name: "Dresden-Neustadt"}] """ defdelegate location(name_or_fragment), to: BahnEx.Location, as: :get_location @doc """ Get arrival board at a given location at a given daten and time. id_or_location: either a `integer` id or a `%BahnEx.Location{}` iso_8601_date_time: a `Calendar.dateTime` or a `string` in ISO8601 date and time format Returns: a list of `%BahnEx.Train{}` for the given station and time. ## Examples iex(1)> BahnEx.arrival_board(8010085, "2017-08-23T19:00:00Z") [%BahnEx.Train{boardId: 8010085, dateTime: #DateTime<2017-08-23 19:35:00Z>, detailsId: "304116%2F104694%2F528716%2F162986%2F80%3fstation_evaId%3D8010085", name: "ICE 1653", origin: "Frankfurt(M) Flughafen Fernbf", stopId: 8010085, stopName: "Dresden Hbf", track: "3", type: "ICE"}, %BahnEx.Train{boardId: 8010085, dateTime: #DateTime<2017-08-23 20:36:00Z>, detailsId: "521202%2F179326%2F919084%2F285808%2F80%3fstation_evaId%3D8010085", name: "IC 2047", origin: "Dortmund Hbf", stopId: 8010085, stopName: "Dresden Hbf", track: "1", type: "IC"}] """ defdelegate arrival_board(id_or_location, iso_8601_date_time), to: BahnEx.ArrivalBoard, as: :get_arrivals @doc """ Get departure board at a given location at a given daten and time. id_or_location: either a `integer` id or a `%BahnEx.Location{}` iso_8601_date_time: a `Calendar.dateTime` or a `string` in ISO8601 date and time format Returns: a list of `%BahnEx.Train{}` for the given station and time. ## Examples iex(1)> BahnEx.arrival_board(8010085, "2017-08-23T19:00:00Z") [%BahnEx.Train{boardId: 8010085, dateTime: #DateTime<2017-08-23 19:35:00Z>, detailsId: "304116%2F104694%2F528716%2F162986%2F80%3fstation_evaId%3D8010085", name: "ICE 1653", origin: "Frankfurt(M) Flughafen Fernbf", stopId: 8010085, stopName: "<NAME>", track: "3", type: "ICE"}, %BahnEx.Train{boardId: 8010085, dateTime: #DateTime<2017-08-23 20:36:00Z>, detailsId: "521202%2F179326%2F919084%2F285808%2F80%3fstation_evaId%3D8010085", name: "IC 2047", origin: "Dortmund Hbf", stopId: 8010085, stopName: "<NAME>", track: "1", type: "IC"}] """ defdelegate departure_board(id_or_location, iso_8601_date_time), to: BahnEx.DepartureBoard, as: :get_departures @doc """ Retrieve details of a journey. The id of journey should come from an arrival board or a departure board. id: Either a `%BahnEx.Train{}` struct or an string id Returns a list of `%BahnEx.TrainLoc{}`s. ## Examples iex(1)> BahnEx.journey_details("475620%252F175342%252F176320%252F70380%252F80%253fstation_evaId%253D8010085") https://api.deutschebahn.com/fahrplan-plus/v1/journeyDetails/475620%252F175342%252F176320%252F70380%252F80%253fstation_evaId%253D8010085 [%BahnEx.TrainLoc{arrTime: nil, depTime: ~T[07:03:00], lat: "52.525589", lon: "13.369549", operator: "DPN", stopId: 8098160, stopName: "<NAME> (tief)", train: "EC 171", type: "EC"}, %BahnEx.TrainLoc{arrTime: ~T[07:08:00], depTime: ~T[07:10:00], lat: "52.475043", lon: "13.365315", operator: "DPN", stopId: 8011113, stopName: "<NAME>", train: "EC 171", type: "EC"}] """ defdelegate journey_details(id_or_train_struct), to: BahnEx.JourneyDetails, as: :get_journey_details end
lib/bahn_ex.ex
0.866048
0.544983
bahn_ex.ex
starcoder
defmodule MateriaCommerce.Deliveries do @moduledoc """ The Deliveries context. """ import Ecto.Query, warn: false @repo Application.get_env(:materia, :repo) alias MateriaCommerce.Deliveries.Delivery @doc """ iex(1)> Application.put_env(:materia_utils, :calender_locale, "Asia/Tokyo") iex(2)> results = MateriaCommerce.Deliveries.list_deliveries iex(3)> view = MateriaCommerceWeb.DeliveryView.render("index.json", %{deliveries: results}) |> Enum.map(fn x -> x = Map.delete(x, :id); x = Map.delete(x, :inserted_at); x = Map.delete(x, :updated_at); end) iex(4)> view = view |> List.first iex(5)> view |> Map.delete(:inserted) |> Map.delete(:updated) |> Map.delete(:snd_user) |> Map.delete(:clt_user) |> Map.delete(:rcv_user) %{ clt_notation_org_name: "××会社", clt_phone_number: "444-4444-4444", snd_condition2: "条件2", snd_note2: "備考2", clt_fax_number: "555-5555-5555", rcv_notation_org_name: "△△会社", snd_note1: "備考1", rcv_phone_number: "222-2222-2222", rcv_address3: "△△ビル", clt_address2_p: "ばつばつ", clt_notation_name_p: "ばつばつ", rcv_note1: "備考1", snd_address1_p: "ふくおかけんふくおかしまるまるく", rcv_condition1: "条件1", clt_address1_p: "ふくおかけんふくおかしばつばつく", snd_time: "23:59:59", lock_version: 0, clt_address1: "福岡県福岡市××区", clt_address2: "××x-x-x", clt_notation_name: "××", snd_notation_name_p: "まるまる", snd_notation_org_name: "〇〇会社", rcv_address3_p: "さんかくさんかくびる", clt_zip_code: "810-XXXX", rcv_notation_org_name_p: "さんかくさんかくかいしゃ", snd_address3_p: "まるまるびる", snd_notation_org_name_p: "まるまるかいしゃ", snd_address2_p: "まるまる", rcv_address2: "△△x-x-x", rcv_note2: "備考2", snd_address2: "〇〇x-x-x", rcv_note3: "備考3", rcv_notation_name: "△△", clt_notation_org_name_p: "ばつばつかいしゃ", rcv_condition3: "条件3", rcv_notation_name_p: "さんかくさんかく", rcv_address1: "福岡県福岡市△△区", snd_condition1: "条件1", snd_notation_name: "〇〇", rcv_time: "00:00:01", rcv_zip_code: "810-YYYY", clt_address3_p: "ばつばつびる", snd_date: "2019/01/01", snd_condition3: "条件3", snd_phone_number: "000-0000-0000", snd_fax_number: "111-1111-1111", snd_address1: "福岡県福岡市○○区", rcv_address1_p: "ふくおかけんふくおかしさんかくさんかくく", clt_address3: "××ビル", snd_address3: "○○ビル", rcv_address2_p: "さんかくさんかく", rcv_condition2: "条件2", rcv_date: "2019/01/02", rcv_fax_number: "333-3333-3333", snd_note3: "備考3", snd_zip_code: "810-ZZZZ", status: 0 } iex(6)> view[:inserted] %{ addresses: [], back_ground_img_url: nil, descriptions: nil, email: "<EMAIL>", external_user_id: nil, icon_img_url: nil, id: 1, lock_version: 2, name: "hogehoge", organization: nil, phone_number: nil, role: "admin", status: 1 } iex(7)> view[:updated] %{ addresses: [], back_ground_img_url: nil, descriptions: nil, email: "<EMAIL>", external_user_id: nil, icon_img_url: nil, id: 1, lock_version: 2, name: "hogehoge", organization: nil, phone_number: nil, role: "admin", status: 1 } iex(8)> view[:snd_user] %{ addresses: [ %{ address1: "福岡市中央区", address2: "大名 x-x-xx", id: 2, latitude: nil, location: "福岡県", lock_version: 0, longitude: nil, organization: nil, subject: "billing", user: [], zip_code: "810-ZZZZ" }, %{ address1: "福岡市中央区", address2: "港 x-x-xx", id: 1, latitude: nil, location: "福岡県", lock_version: 0, longitude: nil, organization: nil, subject: "living", user: [], zip_code: "810-ZZZZ" } ], back_ground_img_url: nil, descriptions: nil, email: "<EMAIL>", external_user_id: nil, icon_img_url: nil, id: 1, lock_version: 2, name: "hogehoge", organization: nil, phone_number: nil, role: "admin", status: 1 } iex(9)> view[:clt_user] %{ addresses: [ %{ address1: "福岡市中央区", address2: "大名 x-x-xx", id: 2, latitude: nil, location: "福岡県", lock_version: 0, longitude: nil, organization: nil, subject: "billing", user: [], zip_code: "810-ZZZZ" }, %{ address1: "福岡市中央区", address2: "港 x-x-xx", id: 1, latitude: nil, location: "福岡県", lock_version: 0, longitude: nil, organization: nil, subject: "living", user: [], zip_code: "810-ZZZZ" } ], back_ground_img_url: nil, descriptions: nil, email: "<EMAIL>", external_user_id: nil, icon_img_url: nil, id: 1, lock_version: 2, name: "hogehoge", organization: nil, phone_number: nil, role: "admin", status: 1 } iex(10)> view[:rcv_user] %{ addresses: [ %{ address1: "福岡市中央区", address2: "大名 x-x-xx", id: 2, latitude: nil, location: "福岡県", lock_version: 0, longitude: nil, organization: nil, subject: "billing", user: [], zip_code: "810-ZZZZ" }, %{ address1: "福岡市中央区", address2: "港 x-x-xx", id: 1, latitude: nil, location: "福岡県", lock_version: 0, longitude: nil, organization: nil, subject: "living", user: [], zip_code: "810-ZZZZ" } ], back_ground_img_url: nil, descriptions: nil, email: "<EMAIL>", external_user_id: nil, icon_img_url: nil, id: 1, lock_version: 2, name: "hogehoge", organization: nil, phone_number: nil, role: "admin", status: 1 } """ def list_deliveries do Delivery |> @repo.all() |> @repo.preload( snd_user: [:addresses], rcv_user: [:addresses], clt_user: [:addresses], inserted: [], updated: [] ) end @doc """ iex(1)> Application.put_env(:materia_utils, :calender_locale, "Asia/Tokyo") iex(2)> results = MateriaCommerce.Deliveries.get_delivery!(1) |> List.wrap() iex(3)> view = MateriaCommerceWeb.DeliveryView.render("index.json", %{deliveries: results}) |> Enum.map(fn x -> x = Map.delete(x, :id); x = Map.delete(x, :inserted_at); x = Map.delete(x, :updated_at); end) iex(4)> view = view |> List.first iex(5)> view |> Map.delete(:inserted) |> Map.delete(:updated) |> Map.delete(:snd_user) |> Map.delete(:clt_user) |> Map.delete(:rcv_user) %{ clt_notation_org_name: "××会社", clt_phone_number: "444-4444-4444", snd_condition2: "条件2", snd_note2: "備考2", clt_fax_number: "555-5555-5555", rcv_notation_org_name: "△△会社", snd_note1: "備考1", rcv_phone_number: "222-2222-2222", rcv_address3: "△△ビル", clt_address2_p: "ばつばつ", clt_notation_name_p: "ばつばつ", rcv_note1: "備考1", snd_address1_p: "ふくおかけんふくおかしまるまるく", rcv_condition1: "条件1", clt_address1_p: "ふくおかけんふくおかしばつばつく", snd_time: "23:59:59", lock_version: 0, clt_address1: "福岡県福岡市××区", clt_address2: "××x-x-x", clt_notation_name: "××", snd_notation_name_p: "まるまる", snd_notation_org_name: "〇〇会社", rcv_address3_p: "さんかくさんかくびる", clt_zip_code: "810-XXXX", rcv_notation_org_name_p: "さんかくさんかくかいしゃ", snd_address3_p: "まるまるびる", snd_notation_org_name_p: "まるまるかいしゃ", snd_address2_p: "まるまる", rcv_address2: "△△x-x-x", rcv_note2: "備考2", snd_address2: "〇〇x-x-x", rcv_note3: "備考3", rcv_notation_name: "△△", clt_notation_org_name_p: "ばつばつかいしゃ", rcv_condition3: "条件3", rcv_notation_name_p: "さんかくさんかく", rcv_address1: "福岡県福岡市△△区", snd_condition1: "条件1", snd_notation_name: "〇〇", rcv_time: "00:00:01", rcv_zip_code: "810-YYYY", clt_address3_p: "ばつばつびる", snd_date: "2019/01/01", snd_condition3: "条件3", snd_phone_number: "000-0000-0000", snd_fax_number: "111-1111-1111", snd_address1: "福岡県福岡市○○区", rcv_address1_p: "ふくおかけんふくおかしさんかくさんかくく", clt_address3: "××ビル", snd_address3: "○○ビル", rcv_address2_p: "さんかくさんかく", rcv_condition2: "条件2", rcv_date: "2019/01/02", rcv_fax_number: "333-3333-3333", snd_note3: "備考3", snd_zip_code: "810-ZZZZ", status: 0 } iex(6)> view[:inserted] %{ addresses: [], back_ground_img_url: nil, descriptions: nil, email: "<EMAIL>", external_user_id: nil, icon_img_url: nil, id: 1, lock_version: 2, name: "hogehoge", organization: nil, phone_number: nil, role: "admin", status: 1 } iex(7)> view[:updated] %{ addresses: [], back_ground_img_url: nil, descriptions: nil, email: "<EMAIL>", external_user_id: nil, icon_img_url: nil, id: 1, lock_version: 2, name: "hogehoge", organization: nil, phone_number: nil, role: "admin", status: 1 } iex(8)> view[:snd_user] %{ addresses: [ %{ address1: "福岡市中央区", address2: "大名 x-x-xx", id: 2, latitude: nil, location: "福岡県", lock_version: 0, longitude: nil, organization: nil, subject: "billing", user: [], zip_code: "810-ZZZZ" }, %{ address1: "福岡市中央区", address2: "港 x-x-xx", id: 1, latitude: nil, location: "福岡県", lock_version: 0, longitude: nil, organization: nil, subject: "living", user: [], zip_code: "810-ZZZZ" } ], back_ground_img_url: nil, descriptions: nil, email: "<EMAIL>", external_user_id: nil, icon_img_url: nil, id: 1, lock_version: 2, name: "hogehoge", organization: nil, phone_number: nil, role: "admin", status: 1 } iex(9)> view[:clt_user] %{ addresses: [ %{ address1: "福岡市中央区", address2: "大名 x-x-xx", id: 2, latitude: nil, location: "福岡県", lock_version: 0, longitude: nil, organization: nil, subject: "billing", user: [], zip_code: "810-ZZZZ" }, %{ address1: "福岡市中央区", address2: "港 x-x-xx", id: 1, latitude: nil, location: "福岡県", lock_version: 0, longitude: nil, organization: nil, subject: "living", user: [], zip_code: "810-ZZZZ" } ], back_ground_img_url: nil, descriptions: nil, email: "<EMAIL>", external_user_id: nil, icon_img_url: nil, id: 1, lock_version: 2, name: "hogehoge", organization: nil, phone_number: nil, role: "admin", status: 1 } iex(10)> view[:rcv_user] %{ addresses: [ %{ address1: "福岡市中央区", address2: "大名 x-x-xx", id: 2, latitude: nil, location: "福岡県", lock_version: 0, longitude: nil, organization: nil, subject: "billing", user: [], zip_code: "810-ZZZZ" }, %{ address1: "福岡市中央区", address2: "港 x-x-xx", id: 1, latitude: nil, location: "福岡県", lock_version: 0, longitude: nil, organization: nil, subject: "living", user: [], zip_code: "810-ZZZZ" } ], back_ground_img_url: nil, descriptions: nil, email: "<EMAIL>", external_user_id: nil, icon_img_url: nil, id: 1, lock_version: 2, name: "hogehoge", organization: nil, phone_number: nil, role: "admin", status: 1 } """ def get_delivery!(id) do Delivery |> @repo.get!(id) |> @repo.preload( snd_user: [:addresses], rcv_user: [:addresses], clt_user: [:addresses], inserted: [], updated: [] ) end @doc """ iex(1)> Application.put_env(:materia_utils, :calender_locale, "Asia/Tokyo") iex(2)> attrs = %{"snd_zip_code" => "000-0000","snd_address1" => "snd_address1","rcv_zip_code" => "111-1111","rcv_address1" => "rcv_address1","clt_zip_code" => "222-2222","clt_address1" => "clt_address1","snd_user_id" => 1,"rcv_user_id" => 1,"clt_user_id" => 1} iex(3)> {:ok, result} = MateriaCommerce.Deliveries.create_delivery(%{}, attrs, 1) iex(4)> results = List.wrap(result) iex(5)> view = MateriaCommerceWeb.DeliveryView.render("index.json", %{deliveries: results}) |> Enum.map(fn x -> x = Map.delete(x, :id); x = Map.delete(x, :inserted_at); x = Map.delete(x, :updated_at); end) iex(6)> view = view |> List.first iex(7)> view |> Map.delete(:inserted) |> Map.delete(:updated) |> Map.delete(:snd_user) |> Map.delete(:clt_user) |> Map.delete(:rcv_user) %{ clt_notation_org_name: nil, clt_phone_number: nil, snd_condition2: nil, snd_note2: nil, clt_fax_number: nil, rcv_notation_org_name: nil, snd_note1: nil, rcv_phone_number: nil, rcv_address3: nil, clt_address2_p: nil, clt_notation_name_p: nil, rcv_note1: nil, snd_address1_p: nil, rcv_condition1: nil, clt_address1_p: nil, snd_time: nil, lock_version: 0, clt_address1: "clt_address1", clt_address2: nil, clt_notation_name: nil, snd_notation_name_p: nil, snd_notation_org_name: nil, rcv_address3_p: nil, clt_zip_code: "222-2222", rcv_notation_org_name_p: nil, snd_address3_p: nil, snd_notation_org_name_p: nil, snd_address2_p: nil, rcv_address2: nil, rcv_note2: nil, snd_address2: nil, rcv_note3: nil, rcv_notation_name: nil, clt_notation_org_name_p: nil, rcv_condition3: nil, rcv_notation_name_p: nil, rcv_address1: "rcv_address1", snd_condition1: nil, snd_notation_name: nil, rcv_time: nil, rcv_zip_code: "111-1111", clt_address3_p: nil, snd_date: nil, snd_condition3: nil, snd_phone_number: nil, snd_fax_number: nil, snd_address1: "snd_address1", rcv_address1_p: nil, clt_address3: nil, snd_address3: nil, rcv_address2_p: nil, rcv_condition2: nil, rcv_date: nil, rcv_fax_number: nil, snd_note3: nil, snd_zip_code: "000-0000", status: 1 } """ def create_delivery(_results, attrs, user_id) do attrs = attrs |> Map.put("inserted_id", user_id) |> Map.put("updated_id", user_id) %Delivery{} |> Delivery.changeset(attrs) |> @repo.insert() end @doc """ iex(1)> Application.put_env(:materia_utils, :calender_locale, "Asia/Tokyo") iex(2)> delivery = MateriaCommerce.Deliveries.get_delivery!(1) iex(3)> {:ok, result} = MateriaCommerce.Deliveries.update_delivery(%{}, delivery, %{"snd_zip_code" => "000-0000"}, 1) iex(4)> results = List.wrap(result) iex(5)> view = MateriaCommerceWeb.DeliveryView.render("index.json", %{deliveries: results}) |> Enum.map(fn x -> x = Map.delete(x, :id); x = Map.delete(x, :inserted_at); x = Map.delete(x, :updated_at); end) iex(6)> view = view |> List.first iex(7)> view |> Map.delete(:inserted) |> Map.delete(:updated) |> Map.delete(:snd_user) |> Map.delete(:clt_user) |> Map.delete(:rcv_user) %{ clt_notation_org_name: "××会社", clt_phone_number: "444-4444-4444", snd_condition2: "条件2", snd_note2: "備考2", clt_fax_number: "555-5555-5555", rcv_notation_org_name: "△△会社", snd_note1: "備考1", rcv_phone_number: "222-2222-2222", rcv_address3: "△△ビル", clt_address2_p: "ばつばつ", clt_notation_name_p: "ばつばつ", rcv_note1: "備考1", snd_address1_p: "ふくおかけんふくおかしまるまるく", rcv_condition1: "条件1", clt_address1_p: "ふくおかけんふくおかしばつばつく", snd_time: "23:59:59", lock_version: 1, clt_address1: "福岡県福岡市××区", clt_address2: "××x-x-x", clt_notation_name: "××", snd_notation_name_p: "まるまる", snd_notation_org_name: "〇〇会社", rcv_address3_p: "さんかくさんかくびる", clt_zip_code: "810-XXXX", rcv_notation_org_name_p: "さんかくさんかくかいしゃ", snd_address3_p: "まるまるびる", snd_notation_org_name_p: "まるまるかいしゃ", snd_address2_p: "まるまる", rcv_address2: "△△x-x-x", rcv_note2: "備考2", snd_address2: "〇〇x-x-x", rcv_note3: "備考3", rcv_notation_name: "△△", clt_notation_org_name_p: "ばつばつかいしゃ", rcv_condition3: "条件3", rcv_notation_name_p: "さんかくさんかく", rcv_address1: "福岡県福岡市△△区", snd_condition1: "条件1", snd_notation_name: "〇〇", rcv_time: "00:00:01", rcv_zip_code: "810-YYYY", clt_address3_p: "ばつばつびる", snd_date: "2019/01/01", snd_condition3: "条件3", snd_phone_number: "000-0000-0000", snd_fax_number: "111-1111-1111", snd_address1: "福岡県福岡市○○区", rcv_address1_p: "ふくおかけんふくおかしさんかくさんかくく", clt_address3: "××ビル", snd_address3: "○○ビル", rcv_address2_p: "さんかくさんかく", rcv_condition2: "条件2", rcv_date: "2019/01/02", rcv_fax_number: "333-3333-3333", snd_note3: "備考3", snd_zip_code: "000-0000", status: 0 } """ def update_delivery(_results, %Delivery{} = delivery, attrs, user_id) do attrs = attrs |> Map.put("updated_id", user_id) delivery |> Delivery.update_changeset(attrs) |> @repo.update() end @doc """ iex(1)> Application.put_env(:materia_utils, :calender_locale, "Asia/Tokyo") iex(2)> delivery = MateriaCommerce.Deliveries.get_delivery!(1) iex(3)> {:ok, result} = MateriaCommerce.Deliveries.delete_delivery(%{}, delivery, 1) iex(4)> results = List.wrap(result) iex(5)> view = MateriaCommerceWeb.DeliveryView.render("index.json", %{deliveries: results}) |> Enum.map(fn x -> x = Map.delete(x, :id); x = Map.delete(x, :inserted_at); x = Map.delete(x, :updated_at); end) iex(6)> view = view |> List.first iex(7)> view |> Map.delete(:inserted) |> Map.delete(:updated) |> Map.delete(:snd_user) |> Map.delete(:clt_user) |> Map.delete(:rcv_user) %{ clt_notation_org_name: "××会社", clt_phone_number: "444-4444-4444", snd_condition2: "条件2", snd_note2: "備考2", clt_fax_number: "555-5555-5555", rcv_notation_org_name: "△△会社", snd_note1: "備考1", rcv_phone_number: "222-2222-2222", rcv_address3: "△△ビル", clt_address2_p: "ばつばつ", clt_notation_name_p: "ばつばつ", rcv_note1: "備考1", snd_address1_p: "ふくおかけんふくおかしまるまるく", rcv_condition1: "条件1", clt_address1_p: "ふくおかけんふくおかしばつばつく", snd_time: "23:59:59", lock_version: 1, clt_address1: "福岡県福岡市××区", clt_address2: "××x-x-x", clt_notation_name: "××", snd_notation_name_p: "まるまる", snd_notation_org_name: "〇〇会社", rcv_address3_p: "さんかくさんかくびる", clt_zip_code: "810-XXXX", rcv_notation_org_name_p: "さんかくさんかくかいしゃ", snd_address3_p: "まるまるびる", snd_notation_org_name_p: "まるまるかいしゃ", snd_address2_p: "まるまる", rcv_address2: "△△x-x-x", rcv_note2: "備考2", snd_address2: "〇〇x-x-x", rcv_note3: "備考3", rcv_notation_name: "△△", clt_notation_org_name_p: "ばつばつかいしゃ", rcv_condition3: "条件3", rcv_notation_name_p: "さんかくさんかく", rcv_address1: "福岡県福岡市△△区", snd_condition1: "条件1", snd_notation_name: "〇〇", rcv_time: "00:00:01", rcv_zip_code: "810-YYYY", clt_address3_p: "ばつばつびる", snd_date: "2019/01/01", snd_condition3: "条件3", snd_phone_number: "000-0000-0000", snd_fax_number: "111-1111-1111", snd_address1: "福岡県福岡市○○区", rcv_address1_p: "ふくおかけんふくおかしさんかくさんかくく", clt_address3: "××ビル", snd_address3: "○○ビル", rcv_address2_p: "さんかくさんかく", rcv_condition2: "条件2", rcv_date: "2019/01/02", rcv_fax_number: "333-3333-3333", snd_note3: "備考3", snd_zip_code: "810-ZZZZ", status: 9 } """ def delete_delivery(_results, %Delivery{} = delivery, user_id) do attrs = %{} |> Map.put("updated_id", user_id) |> Map.put("status", Delivery.status().cancel) delivery |> Delivery.update_changeset(attrs) |> @repo.update() end end
lib/materia_commerce/deliveries/deliveries.ex
0.545528
0.448004
deliveries.ex
starcoder
defmodule Sanbase.Clickhouse.Metric.HistogramMetric do import Sanbase.DateTimeUtils, only: [str_to_sec: 1] import Sanbase.Clickhouse.Metric.HistogramSqlQuery alias Sanbase.ClickhouseRepo @spent_coins_cost_histograms ["price_histogram", "spent_coins_cost", "all_spent_coins_cost"] def histogram_data("age_distribution" = metric, %{slug: slug}, from, to, interval, limit) do {query, args} = histogram_data_query(metric, slug, from, to, interval, limit) ClickhouseRepo.query_transform(query, args, fn [unix, value] -> range_from = unix |> DateTime.from_unix!() range_to = [range_from |> Timex.shift(seconds: str_to_sec(interval)), to] |> Enum.min_by(&DateTime.to_unix/1) %{ range: [range_from, range_to], value: value } end) end def histogram_data(metric, %{slug: slug}, from, to, interval, limit) when metric in @spent_coins_cost_histograms do {query, args} = histogram_data_query(metric, slug, from, to, interval, limit) ClickhouseRepo.query_transform(query, args, fn [price, amount] -> %{ price: Sanbase.Math.to_float(price), value: Sanbase.Math.to_float(amount) } end) |> maybe_transform_into_buckets(slug, from, to, limit) end def first_datetime(metric, %{slug: _} = selector) when metric in @spent_coins_cost_histograms do with {:ok, dt1} <- Sanbase.Metric.first_datetime("price_usd", selector), {:ok, dt2} <- Sanbase.Metric.first_datetime("age_distribution", selector) do {:ok, Enum.max_by([dt1, dt2], &DateTime.to_unix/1)} end end def last_datetime_computed_at(metric, %{slug: _} = selector) when metric in ["price_histogram", "spent_coins_cost", "all_spent_coins_cost"] do with {:ok, dt1} <- Sanbase.Metric.last_datetime_computed_at("price_usd", selector), {:ok, dt2} <- Sanbase.Metric.last_datetime_computed_at("age_distribution", selector) do {:ok, Enum.min_by([dt1, dt2], &DateTime.to_unix/1)} end end # Aggregate the separate prices into `limit` number of evenly spaced buckets defp maybe_transform_into_buckets({:ok, []}, _slug, _from, _to, _limit), do: {:ok, []} defp maybe_transform_into_buckets({:ok, data}, slug, from, to, limit) do {min, max} = Enum.map(data, & &1.price) |> Sanbase.Math.min_max() # Avoid precision issues when using `round` for prices. min = Float.floor(min, 2) max = Float.ceil(max, 2) # `limit - 1` because one of the buckets will be split into 2 bucket_size = Enum.max([Float.round((max - min) / (limit - 1), 2), 0.01]) # Generate the range for given low and high price low_high_range = fn low, high -> [Float.round(low, 2), Float.round(high, 2)] end # Generate ranges tuples in the format needed by Stream.unfold/2 price_ranges = fn value -> [lower, upper] = low_high_range.(value, value + bucket_size) {[lower, upper], upper} end # Generate limit number of ranges to properly empty ranges as 0 ranges_map = Stream.unfold(min, price_ranges) |> Enum.take(limit) |> Enum.into(%{}, fn range -> {range, 0.0} end) # Map every price to the proper range price_to_range = fn price -> bucket = floor((price - min) / bucket_size) lower = min + bucket * bucket_size upper = min + (1 + bucket) * bucket_size low_high_range.(lower, upper) end # Get the average price for the queried. time range. It will break the [X,Y] # price interval containing that price into [X, price_break] and [price_break, Y] {:ok, %{^slug => price_break}} = Sanbase.Metric.aggregated_timeseries_data("price_usd", %{slug: slug}, from, to, :avg) price_break = price_break |> Sanbase.Math.round_float() price_break_range = price_to_range.(price_break) # Put every amount moved at a given price in the proper bucket bucketed_data = Enum.reduce(data, ranges_map, fn %{price: price, value: value}, acc -> key = price_to_range.(price) Map.update(acc, key, 0.0, fn curr_amount -> Float.round(curr_amount + value, 2) end) end) |> break_bucket(data, price_break_range, price_break) |> Enum.map(fn {range, amount} -> %{range: range, value: amount} end) |> Enum.sort_by(fn %{range: [range_start | _]} -> range_start end) {:ok, bucketed_data} end defp maybe_transform_into_buckets({:error, error}, _slug, _from, _to, _limit), do: {:error, error} defp break_bucket(bucketed_data, original_data, [low, high], divider) do {lower_half_amount, upper_half_amount} = original_data |> Enum.reduce({0.0, 0.0}, fn %{price: price, value: value}, {acc_lower, acc_upper} -> cond do price >= low and price < divider -> {acc_lower + value, acc_upper} price >= divider and price < high -> {acc_lower, acc_upper + value} true -> {acc_lower, acc_upper} end end) bucketed_data |> Map.delete([low, high]) |> Map.put([low, divider], Float.round(lower_half_amount, 2)) |> Map.put([divider, high], Float.round(upper_half_amount, 2)) end end
lib/sanbase/clickhouse/metric/histogram_metric.ex
0.838316
0.609669
histogram_metric.ex
starcoder
defmodule Fex.MatchModel do defmodule Model do defstruct lambda: 1.0, mu: 1.0, stoppage1: 0, stoppage2: 0, status: {:first_half, 0, {0,0}} end @home_advantage 1.37 @type minute :: non_neg_integer @type score :: {non_neg_integer, non_neg_integer} @type status :: {:first_half, minute, score} | {:halftime, score} | {:second_half, minute, score} | {:finished, score} @opaque t :: %Model{lambda: float, mu: float, stoppage1: 0..3, stoppage2: 0..6, status: status} @spec new(lambda :: float, mu :: float) :: t def new(lambda, mu) do %Model{lambda: lambda * @home_advantage, mu: mu, stoppage1: stoppage(1), stoppage2: stoppage(2)} end def status(m), do: m.status @spec tick(t) :: t def tick(%Model{status: {:finished,_}}=m), do: m def tick(%Model{status: {:halftime, score}}=m) do %{m | status: {:second_half, 45, score} } end def tick(%Model{status: {:first_half, t, score}, stoppage1: s1}=m) when t>=45+s1 do %{m | status: {:halftime, score}} end def tick(%Model{status: {:second_half, t, score}, stoppage2: s2}=m) when t>=90+s2 do %{m | status: {:finished, score}} end def tick(%Model{status: {half, t, {gh, ga}=score}}=m) do %{m | status: {half, t+1, {gh + goal(lambda(m.lambda, score, t)), ga + goal(mu(m.mu, score, t))}}} end def lambda(lambda, score, t) do lambda * lambda_xy(score) + xi_1(t) end def mu(mu, score, t) do mu * mu_xy(score) + xi_2(t) end def lambda_xy({n,n}), do: 1.00 def lambda_xy({1,0}), do: 0.86 def lambda_xy({0,1}), do: 1.10 def lambda_xy({gh, ga}) when gh>ga and gh>1, do: 1.01 def lambda_xy(_), do: 1.13 def mu_xy({n,n}), do: 1.00 def mu_xy({1,0}), do: 1.33 def mu_xy({0,1}), do: 1.07 def mu_xy({gh, ga}) when gh>ga and gh>1, do: 1.53 def mu_xy(_), do: 1.16 def xi_1(t), do: 0.67/90 * t/90 def xi_2(t), do: 0.47/90 * t/90 def goal(lambda) do case rand() < lambda do true -> 1 false -> 0 end end defp rand() do :random.uniform end @spec sim_match(t) :: score def sim_match(%Model{status: {:finished, score}}) do score end def sim_match(m) do sim_match(tick(m)) end @spec stoppage(integer) :: 0..6 defp stoppage(1) do :crypto.rand_uniform(0,3) end defp stoppage(2) do :crypto.rand_uniform(1,3) + :crypto.rand_uniform(0,5) end def test(1) do new(2.27*0.28/90, 2.55*0.36/90) end end
lib/match_model.ex
0.766556
0.476762
match_model.ex
starcoder
defmodule AWS.CodeBuild do @moduledoc """ AWS CodeBuild AWS CodeBuild is a fully managed build service in the cloud. AWS CodeBuild compiles your source code, runs unit tests, and produces artifacts that are ready to deploy. AWS CodeBuild eliminates the need to provision, manage, and scale your own build servers. It provides prepackaged build environments for the most popular programming languages and build tools, such as Apache Maven, Gradle, and more. You can also fully customize build environments in AWS CodeBuild to use your own build tools. AWS CodeBuild scales automatically to meet peak build requests, and you pay only for the build time you consume. For more information about AWS CodeBuild, see the *AWS CodeBuild User Guide*. AWS CodeBuild supports these operations: <ul> <li> `BatchDeleteBuilds`: Deletes one or more builds. </li> <li> `BatchGetProjects`: Gets information about one or more build projects. A *build project* defines how AWS CodeBuild will run a build. This includes information such as where to get the source code to build, the build environment to use, the build commands to run, and where to store the build output. A *build environment* represents a combination of operating system, programming language runtime, and tools that AWS CodeBuild will use to run a build. Also, you can add tags to build projects to help manage your resources and costs. </li> <li> `CreateProject`: Creates a build project. </li> <li> `CreateWebhook`: For an existing AWS CodeBuild build project that has its source code stored in a GitHub repository, enables AWS CodeBuild to begin automatically rebuilding the source code every time a code change is pushed to the repository. </li> <li> `UpdateWebhook`: Changes the settings of an existing webhook. </li> <li> `DeleteProject`: Deletes a build project. </li> <li> `DeleteWebhook`: For an existing AWS CodeBuild build project that has its source code stored in a GitHub repository, stops AWS CodeBuild from automatically rebuilding the source code every time a code change is pushed to the repository. </li> <li> `ListProjects`: Gets a list of build project names, with each build project name representing a single build project. </li> <li> `UpdateProject`: Changes the settings of an existing build project. </li> <li> `BatchGetBuilds`: Gets information about one or more builds. </li> <li> `ListBuilds`: Gets a list of build IDs, with each build ID representing a single build. </li> <li> `ListBuildsForProject`: Gets a list of build IDs for the specified build project, with each build ID representing a single build. </li> <li> `StartBuild`: Starts running a build. </li> <li> `StopBuild`: Attempts to stop running a build. </li> <li> `ListCuratedEnvironmentImages`: Gets information about Docker images that are managed by AWS CodeBuild. </li> </ul> """ @doc """ Deletes one or more builds. """ def batch_delete_builds(client, input, options \\ []) do request(client, "BatchDeleteBuilds", input, options) end @doc """ Gets information about builds. """ def batch_get_builds(client, input, options \\ []) do request(client, "BatchGetBuilds", input, options) end @doc """ Gets information about build projects. """ def batch_get_projects(client, input, options \\ []) do request(client, "BatchGetProjects", input, options) end @doc """ Creates a build project. """ def create_project(client, input, options \\ []) do request(client, "CreateProject", input, options) end @doc """ For an existing AWS CodeBuild build project that has its source code stored in a GitHub repository, enables AWS CodeBuild to begin automatically rebuilding the source code every time a code change is pushed to the repository. <important> If you enable webhooks for an AWS CodeBuild project, and the project is used as a build step in AWS CodePipeline, then two identical builds will be created for each commit. One build is triggered through webhooks, and one through AWS CodePipeline. Because billing is on a per-build basis, you will be billed for both builds. Therefore, if you are using AWS CodePipeline, we recommend that you disable webhooks in CodeBuild. In the AWS CodeBuild console, clear the Webhook box. For more information, see step 9 in [Change a Build Project's Settings](http://docs.aws.amazon.com/codebuild/latest/userguide/change-project.html#change-project-console). </important> """ def create_webhook(client, input, options \\ []) do request(client, "CreateWebhook", input, options) end @doc """ Deletes a build project. """ def delete_project(client, input, options \\ []) do request(client, "DeleteProject", input, options) end @doc """ For an existing AWS CodeBuild build project that has its source code stored in a GitHub repository, stops AWS CodeBuild from automatically rebuilding the source code every time a code change is pushed to the repository. """ def delete_webhook(client, input, options \\ []) do request(client, "DeleteWebhook", input, options) end @doc """ Resets the cache for a project. """ def invalidate_project_cache(client, input, options \\ []) do request(client, "InvalidateProjectCache", input, options) end @doc """ Gets a list of build IDs, with each build ID representing a single build. """ def list_builds(client, input, options \\ []) do request(client, "ListBuilds", input, options) end @doc """ Gets a list of build IDs for the specified build project, with each build ID representing a single build. """ def list_builds_for_project(client, input, options \\ []) do request(client, "ListBuildsForProject", input, options) end @doc """ Gets information about Docker images that are managed by AWS CodeBuild. """ def list_curated_environment_images(client, input, options \\ []) do request(client, "ListCuratedEnvironmentImages", input, options) end @doc """ Gets a list of build project names, with each build project name representing a single build project. """ def list_projects(client, input, options \\ []) do request(client, "ListProjects", input, options) end @doc """ Starts running a build. """ def start_build(client, input, options \\ []) do request(client, "StartBuild", input, options) end @doc """ Attempts to stop running a build. """ def stop_build(client, input, options \\ []) do request(client, "StopBuild", input, options) end @doc """ Changes the settings of a build project. """ def update_project(client, input, options \\ []) do request(client, "UpdateProject", input, options) end @doc """ Updates the webhook associated with an AWS CodeBuild build project. """ def update_webhook(client, input, options \\ []) do request(client, "UpdateWebhook", input, options) end @spec request(map(), binary(), map(), list()) :: {:ok, Poison.Parser.t | nil, Poison.Response.t} | {:error, Poison.Parser.t} | {:error, HTTPoison.Error.t} defp request(client, action, input, options) do client = %{client | service: "codebuild"} host = get_host("codebuild", client) url = get_url(host, client) headers = [{"Host", host}, {"Content-Type", "application/x-amz-json-1.1"}, {"X-Amz-Target", "CodeBuild_20161006.#{action}"}] payload = Poison.Encoder.encode(input, []) headers = AWS.Request.sign_v4(client, "POST", url, headers, payload) case HTTPoison.post(url, payload, headers, options) do {:ok, response=%HTTPoison.Response{status_code: 200, body: ""}} -> {:ok, nil, response} {:ok, response=%HTTPoison.Response{status_code: 200, body: body}} -> {:ok, Poison.Parser.parse!(body), response} {:ok, _response=%HTTPoison.Response{body: body}} -> error = Poison.Parser.parse!(body) exception = error["__type"] message = error["message"] {:error, {exception, message}} {:error, %HTTPoison.Error{reason: reason}} -> {:error, %HTTPoison.Error{reason: reason}} end end defp get_host(endpoint_prefix, client) do if client.region == "local" do "localhost" else "#{endpoint_prefix}.#{client.region}.#{client.endpoint}" end end defp get_url(host, %{:proto => proto, :port => port}) do "#{proto}://#{host}:#{port}/" end end
lib/aws/code_build.ex
0.810329
0.654853
code_build.ex
starcoder
defmodule Fiet do @moduledoc """ Fiet is a feed parser which aims to provide extensibility, speed, and standard compliance. Currently Fiet supports [RSS 2.0](cyber.harvard.edu/rss/rss.html) and [Atom](https://tools.ietf.org/html/rfc4287). ## Feed format detecting There are two main functions in this module: `parse/1` and `parse!/1`, which provide detecting parsing. That means that it will detect the format of the XML document input then parse and map it into `Fiet.Feed`, which is the unified format of all the feed formats supported by Fiet. Please note that detecting logic works by checking the root tag of the XML document, it does not mean to validate the XML document. ## Detecting overhead If you know exactly the feed format of the XML document you are going to parse, you are recommended to use `Fiet.Atom` or `Fiet.RSS2` to avoid overhead. That will give you the full data parsed from the feed document. """ alias Fiet.{ Atom, RSS2 } @doc """ Parse RSS document into a feed. ## Example rss = File.read!("/path/to/rss") {:ok, %Fiet.Feed{} = feed} = Fiet.parse(rss) """ @spec parse(data :: binary) :: {:ok, feed :: Fiet.Feed.t()} | {:error, reason :: any} def parse(data) when is_binary(data) do case detect_format(data) do :atom -> parse_atom(data) :rss2 -> parse_rss2(data) :error -> {:error, "input data format is not supported"} end end @doc """ Same as `parse/1`, but this will raise when error happen. ## Example rss = File.read!("/path/to/rss") %Fiet.Feed{} = Fiet.parse(rss) """ @spec parse!(data :: binary) :: Fiet.Feed.t() def parse!(data) do case parse(data) do {:ok, feed} -> feed {:error, %module{} = error} when module in [RSS2.Engine.ParsingError, Atom.ParsingError] -> raise(error) {:error, message} -> raise RuntimeError, message end end defp parse_rss2(data) do case RSS2.parse(data) do {:ok, %RSS2.Channel{} = channel} -> {:ok, Fiet.Feed.new(channel)} {:error, _reason} = error -> error end end defp parse_atom(data) do case Atom.parse(data) do {:ok, %Atom.Feed{} = feed} -> {:ok, Fiet.Feed.new(feed)} {:error, _reason} = error -> error end end defp detect_format(data) do Fiet.StackParser.parse(data, [], fn :start_element, {"feed", _, _}, [], _ -> {:stop, :atom} :start_element, {"rss", _, _}, [], _ -> {:stop, :rss2} :start_element, _other, [], _ -> {:stop, false} end) |> case do {:ok, false} -> :error {:ok, type} -> type {:error, _reason} -> :error end end end
lib/fiet.ex
0.858422
0.716863
fiet.ex
starcoder
defmodule BSV.Message do @moduledoc """ The Message module provides functions for encrypting, decrypting, signing and verifying arbitrary messages using Bitcoin keys. Message encryption uses the Electrum-compatible BIE1 ECIES algorithm. Message signing uses the Bitcoin Signed Message algorithm. Both alorithms are broadly supported by popular BSV libraries in other languages. ## Encryption A sender encrypts the message using the recipient's PubKey. The recipient decrypts the message with their PrivKey. iex> msg = "Secret test message" iex> encrypted = Message.encrypt(msg, @bob_keypair.pubkey) iex> Message.decrypt(encrypted, @bob_keypair.privkey) {:ok, "Secret test message"} ## Signing A sender signs a message with their PrivKey. The recipient verifies the message using the sender's PubKey. iex> msg = "Secret test message" iex> sig = Message.sign(msg, @alice_keypair.privkey) iex> Message.verify(sig, msg, @alice_keypair.pubkey) true """ alias BSV.{Address, Hash, KeyPair, PrivKey, PubKey, VarInt} import BSV.Util, only: [decode: 2, decode!: 2, encode: 2] @doc """ Decrypts the given message with the private key. ## Options The accepted options are: * `:encoding` - Optionally decode the binary with either the `:base64` or `:hex` encoding scheme. """ @spec decrypt(binary(), PrivKey.t(), keyword()) :: {:ok, binary()} | {:error, term()} def decrypt(data, %PrivKey{} = privkey, opts \\ []) do encoding = Keyword.get(opts, :encoding) encrypted = decode!(data, encoding) len = byte_size(encrypted) - 69 << "BIE1", # magic bytes ephemeral_pubkey::binary-33, # ephermeral pubkey ciphertext::binary-size(len), # ciphertext mac::binary-32 # mac hash >> = encrypted <<d::big-256>> = privkey.d # Derive ECDH key and sha512 hash ecdh_point = ephemeral_pubkey |> PubKey.from_binary!() |> Map.get(:point) |> Curvy.Point.mul(d) key_hash = %PubKey{point: ecdh_point} |> PubKey.to_binary() |> Hash.sha512() # iv and enc_key used in AES, mac_key used in HMAC <<iv::binary-16, enc_key::binary-16, mac_key::binary-32>> = key_hash with ^mac <- Hash.sha256_hmac("BIE1" <> ephemeral_pubkey <> ciphertext, mac_key), msg when is_binary(msg) <- :crypto.crypto_one_time(:aes_128_cbc, enc_key, iv, ciphertext, false) do {:ok, pkcs7_unpad(msg)} end end @doc """ Encrypts the given message with the public key. ## Options The accepted options are: * `:encoding` - Optionally encode the binary with either the `:base64` or `:hex` encoding scheme. """ @spec encrypt(binary(), PubKey.t(), keyword()) :: binary() def encrypt(message, %PubKey{} = pubkey, opts \\ []) do encoding = Keyword.get(opts, :encoding) # Generate ephemeral keypair ephemeral_key = KeyPair.new() <<d::big-256>> = ephemeral_key.privkey.d # Derive ECDH key and sha512 hash ecdh_point = pubkey.point |> Curvy.Point.mul(d) key_hash = %PubKey{point: ecdh_point} |> PubKey.to_binary() |> Hash.sha512() # iv and enc_key used in AES, mac_key used in HMAC <<iv::binary-16, enc_key::binary-16, mac_key::binary-32>> = key_hash cyphertext = :crypto.crypto_one_time(:aes_128_cbc, enc_key, iv, pkcs7_pad(message), true) encrypted = "BIE1" <> PubKey.to_binary(ephemeral_key.pubkey) <> cyphertext mac = Hash.sha256_hmac(encrypted, mac_key) encode(encrypted <> mac, encoding) end @doc """ Signs the given message with the PrivKey. By default signatures are returned `base64` encoded. Use the `encoding: :raw` option to return a raw binary signature. ## Options The accepted options are: * `:encoding` - Encode the binary with either the `:base64`, `:hex` or `:raw` encoding scheme. """ @spec sign(binary(), PrivKey.t(), keyword()) :: binary() def sign(message, %PrivKey{} = privkey, opts \\ []) do opts = opts |> Keyword.put_new(:encoding, :base64) |> Keyword.merge([ compact: true, compressed: privkey.compressed, hash: false ]) message |> bsm_digest() |> Curvy.sign(privkey.d, opts) end @doc """ Verifies the given signature against the given message using the PubKey. By default signatures are assumed to be `base64` encoded. Use the `:encoding` option to specify a different signature encoding. ## Options The accepted options are: * `:encoding` - Decode the signature with either the `:base64`, `:hex` or `:raw` encoding scheme. """ @spec verify(binary(), binary(), PubKey.t() | Address.t(), keyword()) :: boolean() | {:error, term()} def verify(signature, message, pubkey_or_address, opts \\ []) do encoding = Keyword.get(opts, :encoding, :base64) with {:ok, sig} <- decode(signature, encoding) do case do_verify(sig, bsm_digest(message), pubkey_or_address) do res when is_boolean(res) -> res :error -> false error -> error end end end # Handles signature verification with address or pubkey def do_verify(sig, message, %Address{} = address) do with %Curvy.Key{} = key <- Curvy.recover_key(sig, message, hash: false), ^address <- Address.from_pubkey(%PubKey{point: key.point}) do Curvy.verify(sig, message, key, hash: false) end end def do_verify(sig, message, %PubKey{} = pubkey) do Curvy.verify(sig, message, PubKey.to_binary(pubkey), hash: false) end # Prefixes the message with magic bytes and hashes defp bsm_digest(msg) do prefix = "Bitcoin Signed Message:\n" b1 = VarInt.encode(byte_size(prefix)) b2 = VarInt.encode(byte_size(msg)) Hash.sha256_sha256(<<b1::binary, prefix::binary, b2::binary, msg::binary>>) end # Pads the message using PKCS7 defp pkcs7_pad(msg) do case rem(byte_size(msg), 16) do 0 -> msg pad -> pad = 16 - pad msg <> :binary.copy(<<pad>>, pad) end end # Unpads the message using PKCS7 defp pkcs7_unpad(msg) do case :binary.last(msg) do pad when 0 < pad and pad < 16 -> :binary.part(msg, 0, byte_size(msg) - pad) _ -> msg end end end
lib/bsv/message.ex
0.912646
0.490053
message.ex
starcoder
defmodule Crdt.ORSet do @moduledoc """ An OR-Set Without Tombstones (ORSWOT) allows for insertions and removals of elements. Should an insertion and removal be concurrent, the insertion wins. """ defstruct clock: %{}, entries: %{}, deferred: %{} alias Crdt.VectorClock @type t :: %__MODULE__{ clock: VectorClock.t(), entries: %{any() => any()}, deferred: %{any() => any()} } @doc """ Returns a new, empty OR-Set Without Tombstones. """ @spec new :: t() def new, do: %__MODULE__{clock: VectorClock.new(), entries: %{}, deferred: %{}} @doc """ Merges `s1` and `s2`. """ @spec merge(t(), t()) :: t() def merge(s1, s2) do clock = VectorClock.merge(s1.clock, s2.clock) {keep, entries2} = Enum.reduce(s1.entries, {%{}, s2.entries}, fn {item, clock1}, {keep, entries2} -> case s2.entries[item] do nil -> # `s2` removed item after `s1` added item. if VectorClock.descends?(s2.clock, clock1) do {keep, entries2} # `s2` has not yet witnessed insertion. else {Map.put(keep, item, clock1), entries2} end clock2 -> common_clock = VectorClock.intersection(s1.clock, s2.clock) clock1 = clock1 |> VectorClock.forget(common_clock) |> VectorClock.forget(s2.clock) clock2 = clock2 |> VectorClock.forget(common_clock) |> VectorClock.forget(s1.clock) common_clock = common_clock |> VectorClock.merge(clock1) |> VectorClock.merge(clock2) if common_clock == %{} do {keep, Map.delete(entries2, item)} else {Map.put(keep, item, common_clock), Map.delete(entries2, item)} end end end) keep = Enum.reduce(entries2, keep, fn {item, clock2}, keep -> clock2 = VectorClock.forget(clock2, s1.clock) if clock2 == %{} do keep else Map.put(keep, item, clock2) end end) deferred = Map.merge(s1.deferred, s2.deferred, fn _clock, items1, items2 -> MapSet.union(items1, items2) end) %__MODULE__{clock: clock, entries: keep, deferred: deferred} |> apply_deferred_remove() end @doc """ Adds `item` to `set` using actor `id`.. """ @spec add(t(), any(), any()) :: t() def add(set, item, id) do apply_add(set, item, {id, VectorClock.get(set.clock, id) + 1}) end @doc """ Applies an add operation to `set` using `item` and with `dot` as the birth dot. """ @spec apply_add(t(), any(), {any(), non_neg_integer()}) :: t() def apply_add(set, item, dot) do clock = VectorClock.apply_dot(set.clock, dot) # Apply birth dot to entries. entries = Map.update(set.entries, item, VectorClock.new() |> VectorClock.apply_dot(dot), fn clock -> VectorClock.apply_dot(clock, dot) end) # Try to apply all deferred entries. %__MODULE__{set | entries: entries, clock: clock} |> apply_deferred_remove() end @doc """ Removes `item` from `set`. """ @spec remove(t(), any()) :: t() def remove(set, item) do apply_remove(set, item, set.clock) end @doc """ Applies a remove operation to `set` using `item` and with `clock` as the underlying causal context. """ @spec apply_remove(t(), any(), VectorClock.t()) :: t() def apply_remove(set, item, clock) do # Have not yet seen remove operation, so add to deferred items. set = if VectorClock.descends?(set.clock, clock) do set else deferred = Map.update(set.deferred, clock, MapSet.new([item]), fn deferred_items -> MapSet.put(deferred_items, item) end) %__MODULE__{set | deferred: deferred} end case Map.pop(set.entries, item) do {nil, _entries} -> set {entry_clock, entries} -> entry_clock = VectorClock.forget(entry_clock, clock) # Remove item if the remove clock descends the birth clock, otherwise update the birth # clock. entries = if entry_clock != %{} do Map.put(entries, item, entry_clock) else entries end %__MODULE__{set | entries: entries} end end defp apply_deferred_remove(set) do deferred = set.deferred # Attempt to remove all deferred entries. Enum.reduce(deferred, %__MODULE__{set | deferred: %{}}, fn {clock, items}, acc -> Enum.reduce(items, acc, fn item, acc -> apply_remove(acc, item, clock) end) end) end @doc """ Returns all items in `set`. """ @spec get(t()) :: MapSet.t(any()) def get(set) do set.entries |> Map.keys() |> MapSet.new() end @doc """ Returns `true` if `item` is a member of `set`. """ @spec member?(t(), any()) :: boolean() def member?(set, item) do Map.has_key?(set.entries, item) end end
lib/crdt/or_set.ex
0.868785
0.551091
or_set.ex
starcoder
defmodule Mongo.Collection do @moduledoc """ Module holding operations that can be performed on a collection (find, count...) Usage: iex> _collection = Mongo.Helpers.test_collection("anycoll") ...> Mongo.Helpers.test_collection("anycoll") |> Mongo.Collection.count {:ok, 6} `count()` or `count!()` The first returns `{:ok, value}`, the second returns simply `value` when the call is sucessful. In case of error, the first returns `%Mongo.Error{}` the second raises a `Mongo.Bang` exception. iex> collection = Mongo.Helpers.test_collection("anycoll") ...> {:ok, 6} = collection |> Mongo.Collection.count ...> 6 === collection |> Mongo.Collection.count! true iex> collection = Mongo.Helpers.test_collection("anycoll") ...> {:ok, 2} = collection |> Mongo.Collection.count(a: ['$in': [1,3]]) ...> %Mongo.Error{} = collection |> Mongo.Collection.count(a: ['$in': 1]) # $in should take a list, so this triggers an error ...> collection |> Mongo.Collection.count!(a: ['$in': 1]) ** (Mongo.Bang) :"cmd error" """ use Mongo.Helpers alias Mongo.Server alias Mongo.Db alias Mongo.Request defstruct [ name: nil, db: nil, opts: %{} ] @def_reduce "function(obj, prev){}" @doc """ New collection """ def new(db, name) when is_atom(name), do: new(db, Atom.to_string(name)) def new(db, name), do: %__MODULE__{db: db, name: name, opts: Db.coll_opts(db)} @doc """ Creates a `%Mongo.Find{}` for a given collection, query and projection See `Mongo.Find` for details. """ def find(collection, criteria \\ %{}, projection \\ %{}) do Mongo.Find.new(collection, criteria, projection) end @doc """ Insert one document into the collection returns the document it received. iex> collection = Mongo.Helpers.test_collection("anycoll") ...> %{a: 23} |> Mongo.Collection.insert_one(collection) |> elem(1) %{a: 23} """ def insert_one(doc, collection) when is_map(doc) do case insert([doc], collection) do {:ok, docs} -> {:ok, docs |> hd} error -> error end end defbang insert_one(doc, collection) @doc """ Insert a list of documents into the collection iex> collection = Mongo.Helpers.test_collection("anycoll") ...> [%{a: 23}, %{a: 24, b: 1}] |> Mongo.Collection.insert(collection) |> elem(1) [%{a: 23}, %{a: 24, b: 1}] You can chain it with `Mongo.assign_id/1` when you need ids for further processing. If you don't Mongodb will assign ids automatically. iex> collection = Mongo.Helpers.test_collection("anycoll") ...> [%{a: 23}, %{a: 24, b: 1}] |> Mongo.assign_id |> Mongo.Collection.insert(collection) |> elem(1) |> Enum.at(0) |> Map.has_key?(:_id) true `Mongo.Collection.insert` returns the list of documents it received. """ def insert(docs, collection) do Server.send( collection.db.mongo, Request.insert(collection, docs)) case collection.opts[:wc] do nil -> {:ok, docs} :safe -> case collection.db |> Mongo.Db.getLastError do {:ok, _doc} -> {:ok, docs} error -> error end end end defbang insert(docs, collection) @doc """ Modifies an existing document or documents in the collection iex> collection = Mongo.Helpers.test_collection("anycoll") ...> _ = [%{a: 23}, %{a: 24, b: 1}] |> Mongo.assign_id |> Mongo.Collection.insert(collection) |> elem(1) |> Enum.at(0) |> Map.has_key?(:_id) ...> collection |> Mongo.Collection.update(%{a: 456}, %{a: 123, b: 789}) :ok """ def update(collection, query, update, upsert \\ false, multi \\ false) def update(collection, query, update, upsert, multi) do Server.send( collection.db.mongo, Request.update(collection, query, update, upsert, multi)) case collection.opts[:wc] do nil -> :ok :safe -> collection.db |> Mongo.Db.getLastError end end @doc """ Removes an existing document or documents in the collection (see db.collection.remove) iex> collection = Mongo.Helpers.test_collection("anycoll") ...> _ = [%{a: 23}, %{a: 24, b: 789}] |> Mongo.assign_id |> Mongo.Collection.insert(collection) |> elem(1) |> Enum.at(0) |> Map.has_key?(:_id) ...> collection |> Mongo.Collection.delete(%{b: 789}) :ok """ def delete(collection, query, justOne \\ false) def delete(collection, query, justOne) do Server.send( collection.db.mongo, Request.delete(collection, query, justOne)) case collection.opts[:wc] do nil -> :ok :safe -> collection.db |> Mongo.Db.getLastError end end @doc """ Count documents in the collection If `query` is not specify, it counts all document collection. `skip_limit` is a map that specify Mongodb otions skip and limit """ def count(collection, query \\ %{}, skip_limit \\ %{}) def count(collection, query, skip_limit) do skip_limit = Map.take(skip_limit, [:skip, :limit]) case Mongo.Db.cmd_sync(collection.db, %{count: collection.name}, Map.merge(skip_limit, %{query: query})) do {:ok, resp} -> case resp |> Mongo.Response.count do {:ok, n} -> {:ok, n |> trunc} # _error -> {:ok, -1} error -> error end error -> error end end defbang count(collection) defbang count(collection, query) defbang count(collection, query, skip_limit) @doc """ Finds the distinct values for a specified field across a single collection (see db.collection.distinct) iex> collection = Mongo.Helpers.test_collection("anycoll") ...> collection |> Mongo.Collection.distinct!("value", %{value: %{"$lt": 3}}) [0, 1] """ def distinct(collection, key, query \\ %{}) def distinct(collection, key, query) do case Mongo.Db.cmd_sync(collection.db, %{distinct: collection.name}, %{key: key, query: query}) do {:ok, resp} -> Mongo.Response.distinct(resp) error -> error end end defbang distinct(key, collection) defbang distinct(key, query, collection) @doc """ Provides a wrapper around the mapReduce command Returns `:ok` or an array of documents (with option `:inline` active - set by default). iex> collection = Mongo.Helpers.test_collection("anycoll") ...> Mongo.Collection.mr!(collection, "function(d){emit(this._id, this.value*2)}", "function(k, vs){return Array.sum(vs)}") |> is_list true iex> collection = Mongo.Helpers.test_collection("anycoll") ...> Mongo.Collection.mr!(collection, "function(d){emit('z', 3*this.value)}", "function(k, vs){return Array.sum(vs)}", "mrcoll") :ok """ def mr(collection, map, reduce \\ @def_reduce, out \\ %{inline: true}, params \\ %{}) def mr(collection, map, reduce, out, params) do params = Map.take(params, [:limit, :finalize, :scope, :jsMode, :verbose]) case Mongo.Db.cmd_sync(collection.db, %{mapReduce: collection.name}, Map.merge(params, %{map: map, reduce: reduce, out: out})) do {:ok, resp} -> Mongo.Response.mr resp error -> error end end defbang mr(map, collection) defbang mr(map, reduce, collection) defbang mr(map, reduce, out, collection) defbang mr(map, reduce, out, more, collection) @doc """ Groups documents in the collection by the specified key iex> collection = Mongo.Helpers.test_collection("anycoll") ...> collection |> Mongo.Collection.group!(%{a: true}) |> is_list true [%{a: 0.0}, %{a: 1.0}, %{a: 2.0}, ...] """ def group(collection, key, reduce \\ @def_reduce, initial \\ %{}, params \\ %{}) def group(collection, key, reduce, initial, params) do params = Map.take(params, [:'$keyf', :cond, :finalize]) params = if params[:keyf] do Map.put(params, :'$keyf', params[:keyf]) else params end case Mongo.Db.cmd_sync(collection.db, %{group: Map.merge(params, %{ns: collection.name, key: key, '$reduce': reduce, initial: initial})}) do {:ok, resp} -> Mongo.Response.group resp error -> error end end defbang group(key, collection) defbang group(key, reduce, collection) defbang group(key, reduce, initial, collection) defbang group(key, reduce, initial, params, collection) @doc """ Drops the collection returns `:ok` or a string containing the error message """ def drop(collection) do case Db.cmd_sync(collection.db, %{drop: collection.name}) do {:ok, resp} -> Mongo.Response.success resp error -> error end end defbang drop(collection) @doc """ Calculates aggregate values for the data in the collection (see db.collection.aggregate) iex> collection = Mongo.Helpers.test_collection("anycoll") ...> collection |> Mongo.Collection.aggregate([ ...> %{'$skip': 1}, ...> %{'$limit': 5}, ...> %{'$project': %{_id: false, value: true}} ], %{cursor: %{}}) [%{value: 1}, %{value: 1}, %{value: 1}, %{value: 1}, %{value: 3}] """ def aggregate(collection, pipeline, options \\ %{}) do cmd_args = Map.merge(%{pipeline: pipeline}, options) case Mongo.Db.cmd_sync(collection.db, %{aggregate: collection.name}, cmd_args) do {:ok, resp} -> Mongo.Response.aggregate(resp) error -> error end end defbang aggregate(pipeline, collection) @doc """ Adds options to the collection overwriting database options new_opts must be a map with zero or more pairs represeting one of these options: * read: `:awaitdata`, `:nocursortimeout`, `:slaveok`, `:tailablecursor` * write concern: `:wc` * socket: `:mode`, `:timeout` """ def opts(collection, new_opts) do %__MODULE__{collection| opts: Map.merge(collection.opts, new_opts)} end @doc """ Gets read default options """ def read_opts(collection) do Map.take(collection.opts, [:awaitdata, :nocursortimeout, :slaveok, :tailablecursor, :mode, :timeout]) end @doc """ Gets write default options """ def write_opts(collection) do Map.take(collection.opts, [:wc, :mode, :timeout]) end @doc """ Creates an index for the collection """ def createIndex(collection, name, key, unique \\ false, options \\ %{}) do indexes = %{ key: key, name: name, unique: unique, } |> Map.merge(options) createIndexes(collection, [indexes]) end def createIndexes(collection, indexes) do req = %{ createIndexes: collection.name, indexes: indexes, } case Mongo.Db.cmd_sync(collection.db, req) do {:ok, %{docs: [resp]}} -> resp error -> error end end @doc """ Gets a list of All Indexes, only work at 3.0 """ def getIndexes(collection) do case Mongo.Db.cmd_sync(collection.db, %{listIndexes: collection.name}) do {:ok, %{docs: [%{ok: 1.0} = resp]}} -> resp.cursor.firstBatch {:ok, %{docs: [error]}} -> error error -> error end end @doc """ Remove a Specific Index col = Mongo.connect! |> Mongo.db("AF_VortexShort_2358") |> Mongo.Db.collection("test.test") col |> Mongo.Collection.dropIndex(%{time: 1}) """ def dropIndex(collection, key) do Server.send(collection.db.mongo, Request.cmd(collection.db.name, %{deleteIndexes: collection.name}, %{index: key})) end @doc """ Remove All Indexes """ def dropIndexes(collection) do dropIndex(collection, "*") end end
lib/mongo_collection.ex
0.87877
0.425904
mongo_collection.ex
starcoder
defmodule Hocon.Tokens do @moduledoc """ This module is responsible for pushing tokens to the list of tokens. It handles the cases of whitespaces and new lines. Whitespaces are important in cases of unquoted strings und new lines are important for merging objects and arrays. * whitespace are almost ignored * only allowed in context of unquoted strings and simple values [see](https://github.com/lightbend/config/blob/master/HOCON.md#unquoted-strings) * new lines are used to [see](https://github.com/lightbend/config/blob/master/HOCON.md#array-and-object-concatenation) See also the `tokens_test.exs` for more information. """ alias Hocon.Tokens # coveralls-ignore-start defstruct acc: [], ws: false # coveralls-ignore-stop @doc """ Create a new `Tokens` struct. ## Example ```elixir iex(1)> Hocon.Tokens.new() %Hocon.Tokens{acc: [], ws: false} ``` """ def new() do %Tokens{} end @doc """ Push a token to the Tokens struct. ## Example ```elixir tokens = Tokens.new() seq = tokens |> Tokens.push(1) |> Tokens.push(:ws) |> Tokens.push({:unquoted_string, "2"}) |> Tokens.push(:ws) |> Tokens.push(3) |> Tokens.push(:ws) |> Tokens.push({:unquoted_string, "4"}) assert [{:unquoted_string, "4"}, :ws, 3, :ws, {:unquoted_string, "2"}, :ws, 1] == seq.acc ``` """ def push(%Tokens{} = result, :ws) do %Tokens{result | ws: true} end def push(%Tokens{acc: []} = result, :nl) do result end def push(%Tokens{acc: [:nl|_]} = result, :nl) do result end def push(%Tokens{acc: [{:unquoted_string, _}|_] = acc, ws: true} = result, {:unquoted_string, _} = value) do %Tokens{result | acc: [value, :ws | acc], ws: false} end def push(%Tokens{acc: [{:unquoted_string, _}|_] = acc, ws: true} = result, number) when is_number(number) do %Tokens{result | acc: [number, :ws | acc], ws: false} end def push(%Tokens{acc: [last_number|_] = acc, ws: true} = result, {:unquoted_string, _} = value) when is_number(last_number) do %Tokens{result | acc: [value, :ws | acc], ws: false} end def push(%Tokens{acc: [last_number|_] = acc, ws: true} = result, number) when is_number(number) and is_number(last_number) do %Tokens{result | acc: [number, :ws | acc], ws: false} end def push(%Tokens{acc: acc} = result, token) do %Tokens{result | acc: [token | acc], ws: false} end end
lib/hocon/tokens.ex
0.885139
0.956022
tokens.ex
starcoder
defmodule BSV.OutPoint do @moduledoc """ An OutPoint is a data structure representing a reference to a single `t:BSV.TxOut.t/0`. An OutPoint consists of a 32 byte `t:BSV.Tx.hash/0` and 4 byte `t:BSV.TxOut.vout/0`. Conceptually, an OutPoint can be seen as an edge in a graph of Bitcoin transactions, linking inputs to previous outputs. """ alias BSV.{Serializable, Tx, TxOut} import BSV.Util, only: [decode: 2, encode: 2, reverse_bin: 1] @coinbase_hash <<0::256>> @coinbase_sequence 0xFFFFFFFF defstruct hash: nil, vout: nil @typedoc "OutPoint struct" @type t() :: %__MODULE__{ hash: Tx.hash(), vout: TxOut.vout() } @doc """ Parses the given binary into a `t:BSV.OutPoint.t/0`. Returns the result in an `:ok` / `:error` tuple pair. ## Options The accepted options are: * `:encoding` - Optionally decode the binary with either the `:base64` or `:hex` encoding scheme. """ @spec from_binary(binary(), keyword()) :: {:ok, t()} | {:error, term()} def from_binary(data, opts \\ []) when is_binary(data) do encoding = Keyword.get(opts, :encoding) with {:ok, data} <- decode(data, encoding), {:ok, outpoint, _rest} <- Serializable.parse(%__MODULE__{}, data) do {:ok, outpoint} end end @doc """ Parses the given binary into a `t:BSV.OutPoint.t/0`. As `from_binary/2` but returns the result or raises an exception. """ @spec from_binary!(binary(), keyword()) :: t() def from_binary!(data, opts \\ []) when is_binary(data) do case from_binary(data, opts) do {:ok, outpoint} -> outpoint {:error, error} -> raise BSV.DecodeError, error end end @doc """ Returns the `t:BSV.Tx.txid/0` from the OutPoint. """ @spec get_txid(t()) :: Tx.txid() def get_txid(%__MODULE__{hash: hash}), do: hash |> reverse_bin() |> encode(:hex) @doc """ Checks if the given OutPoint is a null. The first transaction in a block is used to distrbute the block reward to miners. These transactions (known as Coinbase transactions) do not spend a previous output, and thus the OutPoint is null. """ @spec is_null?(t()) :: boolean() def is_null?(%__MODULE__{hash: @coinbase_hash, vout: @coinbase_sequence}), do: true def is_null?(%__MODULE__{}), do: false @doc """ Serialises the given `t:BSV.OutPoint.t/0` into a binary. ## Options The accepted options are: * `:encoding` - Optionally encode the binary with either the `:base64` or `:hex` encoding scheme. """ @spec to_binary(t()) :: binary() def to_binary(%__MODULE__{} = outpoint, opts \\ []) do encoding = Keyword.get(opts, :encoding) outpoint |> Serializable.serialize() |> encode(encoding) end defimpl Serializable do @impl true def parse(outpoint, data) do with <<hash::bytes-32, vout::little-32, rest::binary>> <- data do {:ok, struct(outpoint, [ hash: hash, vout: vout ]), rest} end end @impl true def serialize(%{hash: hash, vout: vout}), do: <<hash::binary, vout::little-32>> end end
lib/bsv/out_point.ex
0.929768
0.77827
out_point.ex
starcoder
defmodule Grizzly.ZWave.Commands.AssociationReport do @moduledoc """ Report the destinations for the given association group Params: * `:grouping_identifier` - the grouping identifier for the the association group (required) * `:max_nodes_supported` - the max number of destinations for the association group (required) * `:reports_to_follow` - if the full destination list is too long for one report this field reports the number of follow up reports (optional default `0`) * `:nodes` - the destination nodes in the association group (required) """ @behaviour Grizzly.ZWave.Command alias Grizzly.ZWave alias Grizzly.ZWave.Command alias Grizzly.ZWave.CommandClasses.Association @default_params [reports_to_follow: 0] @type param :: {:grouping_identifier, byte()} | {:max_nodes_supported, byte()} | {:reports_to_follow, byte()} | {:nodes, [ZWave.node_id()]} @impl true @spec new([param]) :: {:ok, Command.t()} def new(params) do # TODO: validate params command = %Command{ name: :association_report, command_byte: 0x03, command_class: Association, params: Keyword.merge(@default_params, params), impl: __MODULE__ } {:ok, command} end @impl true @spec encode_params(Command.t()) :: binary() def encode_params(command) do gi = Command.param!(command, :grouping_identifier) max_nodes = Command.param!(command, :max_nodes_supported) reports_to_follow = Command.param!(command, :reports_to_follow) nodes_bin = :erlang.list_to_binary(Command.param!(command, :nodes)) <<gi, max_nodes, reports_to_follow>> <> nodes_bin end @impl true @spec decode_params(binary()) :: {:ok, [param]} def decode_params(<<gi, max_nodes, reports_to_follow, nodes_bin::binary>>) do {:ok, [ grouping_identifier: gi, max_nodes_supported: max_nodes, reports_to_follow: reports_to_follow, nodes: :erlang.binary_to_list(nodes_bin) ]} end end
lib/grizzly/zwave/commands/association_report.ex
0.764276
0.424472
association_report.ex
starcoder
defmodule Drop do @moduledoc """ Functions for caclulating free-fall in a vaccuum and in constant gravity """ @doc """ the gravity-parallel speed of a dropped object in a vaccuum. Parameters ---------- A tuple of: { `planemo`: atom identifies the PLANEtary Mass Object (`:earth, :mars, :moon`) to determine the gravitiational acceleration. (defaults to `:earth` if not provided) `distance`: float the 'drop height' in meters. Must be greater than zero. } Returns ------- `speed`: the velocity (parallel to the gravity vector) of the object after falling `distance` assumes gravitiational acceleration is constant over the region of interest """ import :math, only: [sqrt: 1] @neg_err_mess "Uh oh! Failed due to distance <0" def fall_velocity(where) when tuple_size(where) == 1 do {distance} = where fall_velocity(:earth, distance) end def fall_velocity(where) do {planemo, distance} = where fall_velocity(planemo, distance) end defp fall_velocity(_, distance) when distance <0 do IO.puts @neg_err_mess :error end defp fall_velocity(:earth, distance) do sqrt(2 * 9.8 * distance) end defp fall_velocity(:mars, distance) do sqrt(2* 3.71 * distance) end defp fall_velocity(:moon, distance) do sqrt(2 * 1.6 * distance) end def casey_fall_vel(planemo, distance) when distance >= 0 do gravity = case planemo do :earth -> 9.81 :mars -> 3.71 :moon -> 1.6 end speed = sqrt(2 * distance * gravity) if speed > 20 do IO.puts("think fast. Look out below") else IO.puts("think at normal speed") end cond do speed == 0 -> :rooted speed < 5 -> :tortoise speed >= 5 and speed < 10 -> :moovinsum speed >= 10 and speed < 20 -> :faaast speed >= 20 -> :speedyindeedy end end end
drop.ex
0.88981
0.750918
drop.ex
starcoder
defmodule Goodbot.Scenarios.FindShops do @moduledoc """ This module defines a scenario that basically sets the logic that should happen given specific params """ # We alias the Templates module as well as the Apis module, # so that we don't have to write so much later alias Goodbot.Templates alias Goodbot.Apis @doc """ This function runs the scenario by taking a Map with lat and long properties as well as the state It uses the latitude and the longitude then to call the Goodbag Branches API Wrapper to get all branches near those coordinates. Finally, the result is turned into a generic template and then sent using the Facebook Messages Api Endpoint """ def run(%{"lat" => lat, "long" => long}, state) do case Apis.Goodbag.Branches.get_all(lat, long) do :connect_timeout -> IO.puts "A timeout is happening" :timeout -> IO.puts "A timeout is happening" result -> result |> build_generic_template_message |> Apis.Facebook.Messages.send(state.psid) end end @doc """ This helper function gets the goodbot public url and uses URI.parse on it so we get a URI Map """ defp goodbot_public_uri, do: Application.get_env(:goodbot, :goodbot)[:public_url] |> URI.parse @doc """ This function builds message containing a generic template with the shops """ defp build_generic_template_message(shops) do elements = shops |> Enum.map(&(map_shop_to_generic_element(&1))) generic_template = %Templates.GenericTemplate{elements: elements} attachment = %Templates.Attachment{type: "template", payload: generic_template} %{attachment: attachment} end @doc """ This helper function builds an element for a generic template out of a single shop """ defp map_shop_to_generic_element(%{"id" => id, "name" => title, "logo_url" => %{"url" => image_url}, "discount_en" => subtitle}) do button_url = GoodbotWeb.Router.Helpers.shop_url(goodbot_public_uri(), :show, id) button = %Templates.WebUrlButton{title: "Show", url: button_url} %Templates.GenericTemplateElement{ title: title, image_url: image_url, subtitle: subtitle, buttons: [button] } end end
lib/goodbot/scenarios/find_shops.ex
0.748536
0.543045
find_shops.ex
starcoder
defmodule Cldr.Message do @moduledoc """ Implements the [ICU Message Format](http://userguide.icu-project.org/formatparse/messages) with functions to parse and interpolate messages. """ alias Cldr.Message.{Parser, Interpreter, Print} import Kernel, except: [to_string: 1, binding: 1] defdelegate format_list(message, args, options), to: Interpreter @type message :: binary() @type arguments :: list() | map() @type options :: Keyword.t() @doc false def cldr_backend_provider(config) do Cldr.Message.Backend.define_message_module(config) end @doc """ Format a message in the [ICU Message Format](https://unicode-org.github.io/icu/userguide/format_parse/messages) The ICU Message Format uses message `"pattern"` strings with variable-element placeholders enclosed in {curly braces}. The argument syntax can include formatting details, otherwise a default format is used. ## Arguments * `args` is a list of map of arguments that are used to replace placeholders in the message * `options` is a keyword list of options ## Options * `:backend` * `:locale` * `:trim` * `:allow_positional_args` * All other aptions are passed to the `to_string/2` function of a formatting module ## Returns ## Examples """ @spec format(String.t(), arguments(), options()) :: {:ok, String.t()} | {:error, {module(), String.t()}} def format(message, args \\ [],options \\ []) when is_binary(message) do options = default_options() |> Keyword.merge(options) options = if Keyword.has_key?(options, :backend) do options else Keyword.put(options, :backend, default_backend()) end with {:ok, message} <- maybe_trim(message, options[:trim]), {:ok, parsed} <- Parser.parse(message, options[:allow_positional_args]) do {:ok, format_list(parsed, args, options) |> :erlang.iolist_to_binary()} end rescue e in [KeyError] -> {:error, {KeyError, "No argument binding was found for #{inspect(e.key)} in #{inspect(e.term)}"}} e in [Cldr.Message.ParseError, Cldr.FormatCompileError] -> {:error, {e.__struct__, e.message}} end @spec format!(String.t(), arguments(), options()) :: String.t() | no_return def format!(message, args \\ [], options \\ []) when is_binary(message) do case format(message, args, options) do {:ok, message} -> :erlang.iolist_to_binary(message) {:error, {exception, reason}} -> raise exception, reason end end @doc """ Returns the [Jaro distance](https://en.wikipedia.org/wiki/Jaro–Winkler_distance) between two messages. This allows for fuzzy matching of message which can be helpful when a message string is changed but the semantics remain the same. ## Arguments * `message1` is a CLDR message in binary form * `message2` is a CLDR message in binary form * `options` is a keyword list of options. The default is `[]` ## Options * `:trim` determines if the message is trimmed of whitespace before formatting. The default is `false`. ## Returns * `{ok, distance}` where `distance` is a float value between 0.0 (equates to no similarity) and 1.0 (is an exact match) representing Jaro distance between `message1` and `message2` or * `{:error, {exception, reason}}` ## Examples """ def jaro_distance(message1, message2, options \\ []) do with {:ok, message1} <- maybe_trim(message1, options[:trim]), {:ok, message2} <- maybe_trim(message2, options[:trim]), {:ok, message1_ast} <- Parser.parse(message1), {:ok, message2_ast} <- Parser.parse(message2) do canonical_message1 = Print.to_string(message1_ast) canonical_message2 = Print.to_string(message2_ast) {:ok, String.jaro_distance(canonical_message1, canonical_message2)} end end @doc """ Returns the [Jaro distance](https://en.wikipedia.org/wiki/Jaro–Winkler_distance) between two messages or raises. This allows for fuzzy matching of message which can be helpful when a message string is changed but the semantics remain the same. ## Arguments * `message1` is a CLDR message in binary form * `message2` is a CLDR message in binary form * `options` is a keyword list of options. The default is `[]` ## Options * `:trim` determines if the message is trimmed of whitespace before formatting. The default is `false`. ## Returns * `distance` where `distance` is a float value between 0.0 (equates to no similarity) and 1.0 (is an exact match) representing Jaro distance between `message1` and `message2` or * raises an exception ## Examples """ def jaro_distance!(message1, message2, options \\ []) do case jaro_distance(message1, message2, options) do {:ok, distance} -> distance {:error, {exception, reason}} -> raise exception, reason end end @doc """ Formats a message into a canonical form. This allows for messages to be compared directly, or using `Cldr.Message.jaro_distance/3`. ## Arguments * `message` is a CLDR message in binary form * `options` is a keyword list of options. The default is `[]` ## Options * `:trim` determines if the message is trimmed of whitespace before formatting. The default is `true`. * `:pretty` determines if the message if formatted with indentation to aid readability. The default is `false`. ## Returns * `{ok, canonical_message}` where `canonical_message` is a binary or * `{:error, {exception, reason}}` ## Examples """ def canonical_message(message, options \\ []) do options = Keyword.put_new(options, :trim, true) with {:ok, message} <- maybe_trim(message, options[:trim]), {:ok, message_ast} <- Parser.parse(message) do {:ok, Print.to_string(message_ast, options)} end end @doc """ Formats a message into a canonical form or raises if the message cannot be parsed. This allows for messages to be compared directly, or using `Cldr.Message.jaro_distance/3`. ## Arguments * `message` is a CLDR message in binary form * `options` is a keyword list of options. The default is `[]` ## Options * `:trim` determines if the message is trimmed of whitespace before formatting. The default is `true`. * `:pretty` determines if the message if formatted with indentation to aid readability. The default is `false`. ## Returns * `canonical_message` where `canonical_message` is a binary or * raises an exception ## Examples """ def canonical_message!(message, options \\ []) do case canonical_message(message, options) do {:ok, message} -> message {:error, {exception, reason}} -> raise exception, reason end end @doc """ Extract the binding names from a parsed message ## Arguments * `message` is a CLDR message in binary or parsed form ### Returns * A list of variable names or * `{:error, {exception, reason}}` ### Examples iex> Cldr.Message.bindings "This {variable} is in the message" ["variable"] """ def bindings(message) when is_binary(message) do with {:ok, parsed} <- Cldr.Message.Parser.parse(message) do bindings(parsed) end end def bindings(message) when is_list(message) do Enum.reduce(message, [], fn {:named_arg, arg}, acc -> [arg | acc] {:pos_arg, arg}, acc -> [arg | acc] {:select, {_, arg}, selectors}, acc -> [arg, bindings(selectors) | acc] {:plural, {_, arg}, _, selectors}, acc -> [arg, bindings(selectors) | acc] {:select_ordinal, {_, arg}, _, selectors}, acc -> [arg, bindings(selectors) | acc] _other, acc-> acc end) |> List.flatten |> Enum.uniq end def bindings(message) when is_map(message) do Enum.map(message, fn {_selector, message} -> bindings(message) end) end @doc false def default_options do [locale: Cldr.get_locale(), trim: false] end if Code.ensure_loaded?(Cldr) and function_exported?(Cldr, :default_backend!, 0) do def default_backend do Cldr.default_backend!() end else def default_backend do Cldr.default_backend() end end defp maybe_trim(message, true) do {:ok, String.trim(message)} end defp maybe_trim(message, _) do {:ok, message} end end
lib/cldr/messages/messages.ex
0.896744
0.65619
messages.ex
starcoder
defmodule WebDriver.Element do @moduledoc """ This module handles WebDriver calls directed at specific DOM elements. They all take an WebDriver.Element struct as the first argument. The WebDriver.Element struct is supposed to be an opaque data type and is not meant to be manipulated. It contains the internal id of the element used by the webdriver client and a the session name. Elements are associated with a particular session and have no meaning outside that WedDriver session. Accessing an element that does not exist on the page will return a response of ```{ :stale_element_reference, response }``` All the command functions will return ```{:ok, response}``` or ```{error, response}``` where ```error``` is one of those listed in WebDriver.Error. """ defstruct id: "", session: :null @doc """ Click on the specified element. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/click """ def click element do cmd element, :click end @doc """ Submit a FORM element. May be applied to any descendent of a FORM element. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/submit """ def submit element do cmd element, :submit end @doc """ Retreives the visible text of the element. Returns a string. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/text """ def text element do get_value element, :text end @doc """ Send a list of keystrokes to the specified element. https://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element/:id/value Parameters: %{value: String} """ def value element, value do cmd element, :value, %{value: String.codepoints value} end @doc """ Get the name of the specified element. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/name """ def name element do get_value element, :name end @doc """ Clears the specified form field or textarea element. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/clear """ def clear element do cmd element, :clear end @doc """ Returns a boolean denoting if the element is selected or not. Returns {:element_not_selectable, response} if it is not able to be selected. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/selected """ def selected? element do value = get_value element, :selected case value do {:element_not_selectable, _resp} -> nil _ -> value end end @doc """ Returns a boolean denoting if the element is enabled or not. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/enabled """ def enabled? element do get_value element, :enabled end @doc """ Returns the value of the given element's attribute. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/attribute/:name """ def attribute element, attribute_name do get_value element, :attribute, attribute_name end @doc """ Determine if two element ids refer to the same DOM element. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/equals/:other """ def equals? element, other_element do get_value element, :equals, other_element.id end @doc """ Returns a boolean denoting if the element is currently visible. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/displayed """ def displayed? element do get_value element, :displayed end @doc """ Returns the current location of the specified element in pixels from the top left corner. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/location Returns %{x: x, y: y} """ def location element do case get_value element, :location do # Bug with Python Selenium # http://code.google.com/p/selenium/source/detail?r=bbcfab457b13 %{"toString" => _,"x" => x,"y" => y} -> %{x: x, y: y} %{"x" => x, "y" => y} -> %{x: x, y: y} response -> # Pass error responses through. response end end @doc """ Determine an element's location once it has been scrolled into view. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/location_in_view Returns %{x: x, y: y} """ def location_in_view element do do_location_in_view(get_value(element, :location)) end defp do_location_in_view {error, response} do {error, response} end defp do_location_in_view response do # Bugfix # http://code.google.com/p/selenium/source/detail?r=bbcfab457b13 %{x: response["x"], y: response["y"]} end @doc """ Returns size in pixels of the specified element. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/size Returns %{width: w, height: h} """ def size element do do_size(get_value(element, :size)) end defp do_size {error, response} do {error, response} end defp do_size response do %{width: response["width"], height: response["height"]} end @doc """ Get the computed value of an element's CSS property. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/css/:propertyName Returns a string. """ def css element, property_name do get_value element, :css, property_name end # Private Functions # Get a value from the server defp get_value element, command do case :gen_server.call element.session, {command, element.id}, 60000 do {:ok, response} -> response.value response -> response end end defp get_value element, command, params do case :gen_server.call element.session, {command, element.id, params}, 60000 do {:ok, response} -> response.value response -> response end end # Send a command to the server defp cmd element, command do :gen_server.call element.session, {command, element.id}, 20000 end defp cmd element, command, params do :gen_server.call element.session, {command, element.id, params}, 20000 end end
lib/webdriver/element.ex
0.810479
0.825871
element.ex
starcoder
defmodule Supabase.Storage do @moduledoc """ Module to work with Supabase storage and the same API the [storage-js](https://github.com/supabase/storage-js) client provides. """ alias Supabase.Connection alias Supabase.Storage.Buckets alias Supabase.Storage.Objects @spec list_buckets(Supabase.Connection.t()) :: {:error, map} | {:ok, [Supabase.Storage.Bucket.t()]} @doc """ Retrieves the details of all Storage buckets within an existing product. ## Notes * Policy permissions required * `buckets` permissions: `select` * `objects` permissions: none ## Example {:ok, buckets} = Supabase.storage(session.access_token) |> Supabase.Storage.list_buckets() """ def list_buckets(%Connection{} = conn) do Buckets.list(conn) end @spec list_buckets!(Supabase.Connection.t()) :: [Supabase.Storage.Bucket.t()] def list_buckets!(%Connection{} = conn) do case list_buckets(conn) do {:ok, buckets} -> buckets {:error, %{"error" => error}} -> raise error end end @spec get_bucket(Supabase.Connection.t(), binary) :: {:error, map} | {:ok, Supabase.Storage.Bucket.t()} @doc """ Retrieves the details of an existing Storage bucket. ## Notes * Policy permissions required * `buckets` permissions: `select` * `objects` permissions: none ## Example {:ok, bucket} = Supabase.storage() |> Supabase.Storage.get_bucket("avatars") """ def get_bucket(%Connection{} = conn, id) do Buckets.get(conn, id) end @spec get_bucket!(Supabase.Connection.t(), binary) :: Supabase.Storage.Bucket.t() def get_bucket!(%Connection{} = conn, id) do case Buckets.get(conn, id) do {:ok, bucket} -> bucket {:error, %{"error" => error}} -> raise error end end @spec create_bucket(Supabase.Connection.t(), binary) :: {:error, map} | {:ok, map} @doc """ Creates a new Storage bucket ## Notes * Policy permissions required: * `buckets` permissions: `insert` * `objects` permissions: none ## Example Supabase.storage(session.access_token) |> Supabase.Storage.create_bucket("avatars") """ def create_bucket(%Connection{} = conn, id) do Buckets.create(conn, id) end @spec create_bucket!(Supabase.Connection.t(), binary) :: map def create_bucket!(%Connection{} = conn, id) do case Buckets.create(conn, id) do {:ok, resp} -> resp {:error, %{"error" => error}} -> raise error end end @spec empty_bucket(Supabase.Connection.t(), binary | Supabase.Storage.Bucket.t()) :: {:error, map} | {:ok, map} @doc """ Removes all objects inside a single bucket. ## Notes * Policy permissions required * `buckets` permissions: `select` * `objects` permissions: `select` and `delete` ## Example Supabase.storage(session.access_token) |> Supabase.Storage.empty_bucket("avatars") """ def empty_bucket(%Connection{} = conn, id) do Buckets.empty(conn, id) end @spec delete_bucket(Supabase.Connection.t(), binary | Supabase.Storage.Bucket.t()) :: {:error, map} | {:ok, map} @doc """ Deletes an existing bucket. A bucket can't be deleted with existing objects inside it. You must first `empty()` the bucket. ## Notes * Policy permissions required: * `buckets` permsisions: `select` and `delete` * `objects` permissions: none ## Example Supabase.storage() |> Supabase.Storage.delete_bucket("avatars") """ def delete_bucket(%Connection{} = conn, id) do Buckets.delete(conn, id) end def from(%Connection{} = conn, id) do %Connection{conn | bucket: id} end @spec upload(Supabase.Connection.t(), binary, binary, keyword) :: {:error, map} | {:ok, map} @doc """ Uploads a file to an existing bucket. ## Notes * Policy permissions required * `buckets` permissions: none * `objects` permissions: `insert` ## Example ### Basic Supabase.storage() |> Supabase.Storage.from("avatars") |> Supabase.Storage.upload("public/avatar1.png", "/local/path/to/avatar1.png") ### Phoenix Live Upload def handle_event("save", _params, socket) do uploaded_files = consume_uploaded_entries(socket, :avatar, fn %{path: path}, entry -> {:ok, %{"Key" => blob_key}} = Supabase.storage(socket.assigns.access_token) |> Supabase.Storage.from("avatars") |> Supabase.Storage.upload( "public/" <> entry.client_name, path, content_type: entry.client_type) blob_key ) {:noreply, assign(socket, uploaded_files: uploaded_files)} end """ def upload(%Connection{bucket: bucket} = conn, path, file, file_options \\ []) do Objects.create(conn, bucket, path, file, file_options) end @spec download(Supabase.Connection.t(), binary | Supabase.Storage.Object.t()) :: {:error, map} | {:ok, binary} @doc """ Downloads a file. ## Notes * Policy permissions required: * `buckets` permissions: none * `objects` permissions: `select` ## Examples {:ok, blob} = Supabase.storage() |> Supabase.Storage.from("avatars") |> Supabase.Storage.download("public/avatar2.png") File.write("/tmp/avatar2.png", blob) """ def download(%Connection{bucket: bucket} = conn, path) do Objects.get(conn, bucket, path) end @spec download!(Supabase.Connection.t(), binary | Supabase.Storage.Object.t()) :: binary def download!(%Connection{} = conn, path) do case download(conn, path) do {:ok, blob} -> blob {:error, %{"error" => error}} -> raise error end end @doc """ Lists all the files within a bucket. ## Notes * Policy permissions required: * `buckets` permissions: none * `objects` permissions: `select` ## Example Supabase.storage() |> Supabase.Storage.from("avatars") |> Supabase.Storage.list(path: "public") ## Options * `:path` - The folder path """ def list(%Connection{bucket: bucket} = conn, options \\ []) do path = Keyword.get(options, :path, "") Objects.list(conn, bucket, path, options) end @doc """ Replaces an existing file at the specified path with a new one. ## Notes * Policy permissions required: * `buckets` permissions: none * `objects` permissions: `update` and `select` ## Example Supabase.storage() |> Supabase.Storage.from("avatars") |> Supabase.Storage.update("public/avatar1.png", "/my/avatar/file.png") ## Options HTTP headers, for example `:cache_control` """ def update(%Connection{bucket: bucket} = conn, path, file, file_options \\ []) do Objects.update(conn, bucket, path, file, file_options) end @doc """ Moves an existing file, optionally renaming it at the same time. ## Notes * Policy permissions required: * `buckets` permissions: none * `objects` permissions: `update` and `select` ## Example Supabase.storage() |> Supabase.Storage.from("avatars") |> Supabase.Storage.move("public/avatar1.png", "private/avatar2.png") """ def move(%Connection{bucket: bucket} = conn, from_path, to_path) do Objects.move(conn, bucket, from_path, to_path) end @doc """ Deletes files within the same bucket ## Notes * Policy permissions required: * `buckets` permissions: none * `objects` permissions: `delete` and `select` ## Example Supabase.storage() |> Supabase.Storage.from("avatars") |> Supabase.Storage.remove(["public/avatar1", "private/avatar2"]) """ def remove(%Connection{bucket: bucket} = conn, paths) do Objects.delete(conn, bucket, paths) end @doc """ Create signed url to download file without requiring permissions. This URL can be valid for a set number of seconds. ## Notes * Policy permissions required: * `buckets` permissions: none * `objects` permissions: `select` ## Example Supabase.storage() |> Supabase.Storage.from("avatars") |> Supabase.Storage.create_signed_url("public/avatar1", 60) """ def create_signed_url(%Connection{bucket: bucket} = conn, path, expires_in) do Objects.sign(conn, bucket, path, expires_in: expires_in) end end
lib/supabase/storage.ex
0.89737
0.446193
storage.ex
starcoder
defmodule ExlasticSearch.Query do @moduledoc """ Elasticsearch query building functions. Basic usage for queryable Queryable is something like: ``` Queryable.search_query() |> must(math(field, value)) |> should(match_phrash(field, value, opts)) |> filter(term(filter_field, value)) |> realize() ``` An ES query has 3 main clauses, must, should and filter. Must and should are near equivalents except that must clauses will reject records that fail to match. Filters require matches but do not contribute to scoring, while must/should both do. Nesting queries within queries is also supported Currently the module only supports the boolean style of compound query, but we could add support for the others as need be. See https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html for documentation on specific query types. """ defstruct [ type: :bool, queryable: nil, must: [], should: [], filter: [], must_not: [], options: %{}, sort: [], index_type: :read ] @type t :: %__MODULE__{} @query_keys [:must, :should, :filter, :must_not] @doc """ Builds a match phrase query clause """ @spec match_phrase(atom, binary, list) :: map def match_phrase(field, query, opts \\ []), do: %{match_phrase: %{field => Enum.into(opts, %{query: query})}} @doc """ Builds a match query clause """ @spec match(atom, binary) :: map def match(field, query), do: %{match: %{field => query}} def match(field, query, opts), do: %{match: %{field => Enum.into(opts, %{query: query})}} @doc """ Multimatch query clause """ @spec multi_match(atom, binary) :: map def multi_match(fields, query, opts \\ []), do: %{multi_match: Enum.into(opts, %{query: query, fields: fields, type: :best_fields})} @doc """ Term query clause """ @spec term(atom, binary) :: map def term(field, term), do: %{term: %{field => term}} @doc """ ids query clause """ @spec ids(list) :: map def ids(ids), do: %{ids: %{values: ids}} @doc """ Query string query type, that applies ES standard query rewriting """ @spec query_string(atom, binary) :: map def query_string(query, opts \\ []), do: %{query_string: Enum.into(opts, %{query: query})} @doc """ terms query clause """ @spec terms(atom, binary) :: map def terms(field, terms), do: %{terms: %{field => terms}} @doc """ range query clause """ @spec range(atom, map) :: map def range(field, range), do: %{range: %{field => range}} @doc """ Appends a new filter scope to the running query """ @spec filter(t, map) :: t def filter(%__MODULE__{filter: filters} = query, filter), do: %{query | filter: [filter | filters]} @doc """ Appends a new must scope to the runnning query """ @spec must(t, map) :: t def must(%__MODULE__{must: musts} = query, must), do: %{query | must: [must | musts]} @doc """ Appends a new should scope to the running query """ @spec should(t, map) :: t def should(%__MODULE__{should: shoulds} = query, should), do: %{query | should: [should | shoulds]} @doc """ Appends a new must_not scope to the running query """ @spec must_not(t, map) :: t def must_not(%__MODULE__{must_not: must_nots} = query, must_not), do: %{query | must_not: [must_not | must_nots]} @doc """ Adds a sort clause to the ES query """ @spec sort(t, binary | atom, binary) :: t def sort(%__MODULE__{sort: sorts} = query, field, direction \\ "asc"), do: %{query | sort: [{field, direction} | sorts]} @doc """ Converts a query to a function score query and adds the given `script` for scoring """ @spec script_score(t, binary) :: t def script_score(%__MODULE__{options: options} = q, script, opts \\ []) do script = Enum.into(opts, %{source: script}) %{q | type: :function_score, options: Map.put(options, :script, script)} end def function_score(%__MODULE__{options: options} = q, functions, opts \\ []) do funcs = Enum.into(opts, %{functions: functions}) %{q | type: :function_score, options: Map.merge(options, funcs)} end def field_value_factor(%__MODULE__{options: options} = q, fvf, opts \\ []) do funcs = Enum.into(opts, %{field_value_factor: fvf}) %{q | type: :function_score, options: Map.merge(options, funcs)} end def nested(%__MODULE__{options: options} = q, path) do %{q | type: :nested, options: Map.put(options, :path, path)} end @doc """ Converts a `Query` struct into an ES compliant bool or function score compound query """ @spec realize(t) :: map def realize(%__MODULE__{type: :nested} = query) do %{query: query_clause(query)} |> add_sort(query) end def realize(%__MODULE__{type: :function_score, options: %{script: script} = opts} = query) do query = realize(%{query | type: :bool, options: Map.delete(opts, :script)}) |> Map.put(:script_score, %{script: script}) %{query: %{function_score: query}} end def realize(%__MODULE__{type: :bool} = query), do: %{query: query_clause(query)} |> add_sort(query) @doc """ Add options to the current bool compound query (for instance the minimum number of accepted matches) """ @spec options(t, map) :: t def options(%__MODULE__{} = query, opts), do: %{query | options: Map.new(opts)} defp include_if_present(query) do @query_keys |> Enum.reduce(%{}, fn type, acc -> case Map.get(query, type) do [q] -> acc |> Map.put(type, query_clause(q)) [_ | _] = q -> acc |> Map.put(type, query_clause(q)) _ -> acc end end) end defp query_clause(%__MODULE__{type: :function_score} = query), do: %{function_score: transform_query(query)} defp query_clause(%__MODULE__{type: :nested} = query), do: %{nested: transform_query(query)} defp query_clause(%__MODULE__{} = query), do: %{bool: include_if_present(query) |> Map.merge(query.options)} defp query_clause(clauses) when is_list(clauses), do: Enum.map(clauses, &query_clause/1) defp query_clause(clause), do: clause defp add_sort(query, %__MODULE__{sort: []}), do: query defp add_sort(query, %__MODULE__{sort: sort}), do: Map.put(query, :sort, realize_sort(sort)) defp transform_query(%{type: :nested, options: %{path: path} = opts} = query) do realize(%{query | type: :bool, options: Map.delete(opts, :path)}) |> Map.put(:path, path) end defp transform_query(%{type: :function_score, options: %{script: script} = opts} = query) do realize(%{query | type: :bool, options: Map.delete(opts, :script)}) |> Map.put(:script_score, %{script: script}) end defp transform_query(%{type: :function_score, options: opts} = query) do realize(%{query | type: :bool, options: Map.drop(opts, [:functions, :field_value_factor])}) |> Map.merge(Map.take(opts, [:functions, :field_value_factor])) end defp realize_sort(sort), do: Enum.reverse(sort) |> Enum.map(fn {field, direction} -> %{field => direction} end) end
lib/exlasticsearch/query.ex
0.913368
0.818882
query.ex
starcoder
defmodule Sanbase.Clickhouse.Exchanges.Trades do use Ecto.Schema @exchanges ["Binance", "Bitfinex", "Kraken", "Poloniex", "Bitrex"] alias Sanbase.ClickhouseRepo @table "exchange_trades" schema @table do field(:timestamp, :utc_datetime) field(:source, :string) field(:symbol, :string) field(:side, :string) field(:amount, :float) field(:price, :float) field(:cost, :float) end @doc false @spec changeset(any(), any()) :: no_return() def changeset(_, _), do: raise("Should not try to change exchange trades") def last_exchange_trades(exchange, ticker_pair, limit) when exchange in @exchanges do {query, args} = last_exchange_trades_query(exchange, ticker_pair, limit) ClickhouseRepo.query_transform(query, args, fn [timestamp, source, symbol, side, amount, price, cost] -> %{ exchange: source, ticker_pair: symbol, datetime: timestamp |> DateTime.from_unix!(), side: String.to_existing_atom(side), amount: amount, cost: cost, price: price } end) end def exchange_trades(exchange, ticker_pair, from, to) when exchange in @exchanges do {query, args} = exchange_trades_query(exchange, ticker_pair, from, to) ClickhouseRepo.query_transform(query, args, fn [timestamp, source, symbol, side, amount, price, cost] -> %{ exchange: source, ticker_pair: symbol, datetime: timestamp |> DateTime.from_unix!(), side: String.to_existing_atom(side), amount: amount, cost: cost, price: price } end) end def exchange_trades(exchange, ticker_pair, from, to, interval) when exchange in @exchanges do {query, args} = exchange_trades_aggregated_query(exchange, ticker_pair, from, to, interval) ClickhouseRepo.query_transform(query, args, fn [timestamp, total_amount, avg_price, total_cost, side] -> %{ exchange: exchange, ticker_pair: ticker_pair, datetime: timestamp |> DateTime.from_unix!(), side: String.to_existing_atom(side), amount: total_amount, cost: total_cost, price: avg_price } end) end defp last_exchange_trades_query(exchange, ticker_pair, limit) do query = """ SELECT toUnixTimestamp(dt), source, symbol, side, amount, price, cost FROM #{@table} PREWHERE source = ?1 AND symbol = ?2 ORDER BY dt DESC LIMIT ?3 """ args = [ exchange, ticker_pair, limit ] {query, args} end defp exchange_trades_query(exchange, ticker_pair, from, to) do query = """ SELECT toUnixTimestamp(dt), source, symbol, side, amount, price, cost FROM #{@table} PREWHERE source = ?1 AND symbol = ?2 AND dt >= toDateTime(?3) AND dt <= toDateTime(?4) ORDER BY dt """ args = [ exchange, ticker_pair, from |> DateTime.to_unix(), to |> DateTime.to_unix() ] {query, args} end defp exchange_trades_aggregated_query(exchange, ticker_pair, from, to, interval) do interval = Sanbase.DateTimeUtils.str_to_sec(interval) from_datetime_unix = DateTime.to_unix(from) to_datetime_unix = DateTime.to_unix(to) span = div(to_datetime_unix - from_datetime_unix, interval) |> max(1) query = """ SELECT time, side2, sum(total_amount), sum(avg_price), sum(total_cost) FROM ( SELECT toUnixTimestamp(intDiv(toUInt32(?5 + number * ?1), ?1) * ?1) as time, toFloat64(0) AS total_amount, toFloat64(0) AS total_cost, toFloat64(0) AS avg_price, toLowCardinality('sell') as side2 FROM numbers(?2) UNION ALL SELECT toUnixTimestamp(intDiv(toUInt32(?5 + number * ?1), ?1) * ?1) as time, toFloat64(0) AS total_amount, toFloat64(0) AS total_cost, toFloat64(0) AS avg_price, toLowCardinality('buy') as side2 FROM numbers(?2) UNION ALL SELECT toUnixTimestamp(intDiv(toUInt32(dt), ?1) * ?1) as time, sum(total_amount) AS total_amount, sum(total_cost) AS total_cost, avg(avg_price) as avg_price, side as side2 FROM ( SELECT any(source), any(symbol), dt, sum(amount) as total_amount, sum(cost) as total_cost, avg(price) as avg_price, side FROM #{@table} PREWHERE source = ?3 AND symbol = ?4 AND dt >= toDateTime(?5) AND dt < toDateTime(?6) GROUP BY dt, side ) GROUP BY time, side ORDER BY time, side ) GROUP BY time, side2 ORDER BY time, side2 """ args = [ interval, span + 1, exchange, ticker_pair, from_datetime_unix, to_datetime_unix ] {query, args} end end
lib/sanbase/clickhouse/exchanges/trades.ex
0.76555
0.417539
trades.ex
starcoder
defmodule Solid.FileSystem do @moduledoc """ A Solid file system is a way to let your templates retrieve other templates for use with the include tag. You can implement a module that retrieve templates from the database, from the file system using a different path structure, you can provide them as hard-coded inline strings, or any manner that you see fit. You can add additional instance variables, arguments, or methods as needed. Example: ```elixir file_system = Solid.LocalFileSystem.new(template_path) text = Solid.render(template, file_system: {Solid.LocalFileSystem, file_system}) ``` This will render the template with a LocalFileSystem implementation rooted at 'template_path'. """ # Called by Solid to retrieve a template file @callback read_template_file(binary(), options :: any()) :: String.t() | no_return() end defmodule Solid.BlankFileSystem do @moduledoc """ Default file system that raise error on call """ @behaviour Solid.FileSystem @impl true def read_template_file(_template_path, _opts) do raise File.Error, reason: "This solid context does not allow includes." end end defmodule Solid.LocalFileSystem do @moduledoc """ This implements an abstract file system which retrieves template files named in a manner similar to Liquid. ie. with the template name prefixed with an underscore. The extension ".liquid" is also added. For security reasons, template paths are only allowed to contain letters, numbers, and underscore. **Example:** file_system = Solid.LocalFileSystem.new("/some/path") Solid.LocalFileSystem.full_path(file_system, "mypartial") # => "/some/path/_mypartial.liquid" Solid.LocalFileSystem.full_path(file_system,"dir/mypartial") # => "/some/path/dir/_mypartial.liquid" Optionally in the second argument you can specify a custom pattern for template filenames. `%s` will be replaced with template basename Default pattern is "_%s.liquid". **Example:** file_system = Solid.LocalFileSystem.new("/some/path", "%s.html") Solid.LocalFileSystem.full_path( "index", file_system) # => "/some/path/index.html" """ defstruct [:root, :pattern] @behaviour Solid.FileSystem def new(root, pattern \\ "_%s.liquid") do %__MODULE__{ root: root, pattern: pattern } end @impl true def read_template_file(template_path, file_system) do full_path = full_path(template_path, file_system) if File.exists?(full_path) do File.read!(full_path) else raise File.Error, reason: "No such template '#{template_path}'" end end def full_path(template_path, file_system) do if String.match?(template_path, Regex.compile!("^[^./][a-zA-Z0-9_/]+$")) do template_name = String.replace(file_system.pattern, "%s", Path.basename(template_path)) full_path = if String.contains?(template_path, "/") do file_system.root |> Path.join(Path.dirname(template_path)) |> Path.join(template_name) |> Path.expand() else file_system.root |> Path.join(template_name) |> Path.expand() end if String.starts_with?(full_path, Path.expand(file_system.root)) do full_path else raise File.Error, reason: "Illegal template path '#{Path.expand(full_path)}'" end else raise File.Error, reason: "Illegal template name '#{template_path}'" end end end
lib/solid/file_system.ex
0.76947
0.688612
file_system.ex
starcoder
defmodule ExPaint do @moduledoc """ ExPaint provides simple primitive based drawing abilities with a flexible backend system for raterizing. """ alias ExPaint.Image @doc """ Creates an image reference of the given size into which primitives may be drawn, and which may be rendered to a given format. """ def create(w, h) when is_number(w) and is_number(h) do Image.start_link(width: w, height: h) end @doc """ Frees the internal resources being used by the given image. """ defdelegate destroy(image), to: Image @doc """ Removes all queued drawing primitives for this image. Images have an all-white background when empty. """ defdelegate clear(image), to: Image @doc """ Enqueues a line from p1 to p2 of the given color ## Parameters * image: An image reference to draw into * p1: A `{x,y}` integer tuple of the starting point of the line * p2: A `{x,y}` integer tuple of the ending point of the line * color: A ExPaint.Color struct describing the color of the line """ defdelegate line(image, p1, p2, color), to: Image @doc """ Enqueues a rect of the given size and color whose upper left corner is at p ## Parameters * image: An image reference to draw into * p: A `{x,y}` integer tuple of the upper left corner of the rectangle * size: A `{w,h}` integer tuple of the outer size of the rectangle * color: A ExPaint.Color struct describing the color of the rectangle's border """ defdelegate rect(image, p, size, color), to: Image @doc """ Enqueues a filled rect of the given size and color whose upper left corner is at p ## Parameters * image: An image reference to draw into * p: A `{x,y}` integer tuple of the upper left corner of the rectangle * size: A `{w,h}` integer tuple of the outer size of the rectangle * color: A ExPaint.Color struct describing the color of the rectangle's fill """ defdelegate filled_rect(image, p, size, color), to: Image @doc """ Enqueues a filled ellipse of the given size and color whose bounding box's upper left corner is at p ## Parameters * image: An image reference to draw into * p: A `{x,y}` integer tuple of the upper left corner of the ellipse's bounding box * size: A `{w,h}` integer tuple of the outer size of the ellipse's bounding box * color: A ExPaint.Color struct describing the color of the ellipse's fill """ defdelegate filled_ellipse(image, p, size, color), to: Image @doc """ Enqueues a filled triangle of the given color with the specified vertices. Winding of the vertices does not matter ## Parameters * image: An image reference to draw into * p1: A `{x,y}` integer tuple of the first point of the triangle * p2: A `{x,y}` integer tuple of the second point of the triangle * p3: A `{x,y}` integer tuple of the third point of the triangle * color: A ExPaint.Color struct describing the color of the triangle's fill """ defdelegate filled_triangle(image, p1, p2, p3, color), to: Image @doc """ Enqueues a polygon with an arbitrary number of vertices. Winding of the vertices does not matter ## Parameters * image: An image reference to draw into * points: A list of `{x,y}` integer tuples, one for each vertex * color: A ExPaint.Color struct describing the color of the polygon's border """ defdelegate polygon(image, points, color), to: Image @doc """ Enqueues an arc with the given two points on its radius and the given diameter ## Parameters * image: An image reference to draw into * p1: A `{x,y}` integer tuple of a point on the arc's raduis * p2: A `{x,y}` integer tuple of a second point on the arc's raduis * diam: An integer value for the arc's diameter * color: A ExPaint.Color struct describing the color of the arc's border """ defdelegate arc(image, p1, p2, diam, color), to: Image @doc """ Enqueues a text string Parameters: * image: An image reference to draw into * p: A `{x,y}` integer tuple of the upper left point of the text's bounding box * font: A ExPaint.Font struct describing the font to use * text: The string to display * color: A ExPaint.Color struct describing the color of the text """ defdelegate text(image, p, font, text, color), to: Image @doc """ Renders the given image according to the given rasterizer ## Parameters * image: An image reference to draw into * rasterizer: The rasterizer module to use to produce the output. ## Examples iex> ExPaint.render(image, ExPaint.PNGRasterizer) {:ok, png_data} """ def render(image, rasterizer) do image |> Image.primitives() |> Enum.reduce(rasterizer.start(image), &rasterizer.apply/2) |> rasterizer.commit end end
lib/ex_paint.ex
0.959997
0.928862
ex_paint.ex
starcoder
defmodule StatesLanguage.Graph do @moduledoc """ Functions for creating a Graph structure from deserialized JSON. This is used by Serializers and the core library. See `StatesLanguage.Serializer.D3Graph`. """ alias StatesLanguage.{Catch, Choice, Edge, Node} defstruct [:comment, :edges, :nodes, :start] @type t :: %__MODULE__{ comment: String.t(), start: String.t(), nodes: %{required(String.t()) => Node.t()}, edges: [Edge.t()] } @spec serialize(map()) :: t() def serialize(data) do {comment, start, nodes} = parse_data(data) edges = get_edges(nodes) %__MODULE__{comment: comment, edges: edges, nodes: nodes, start: start} end defp parse_data(data) do nodes = data |> Map.get("States") |> to_states() { Map.get(data, "Comment"), Map.get(data, "StartAt"), nodes } end defp to_states(%{} = states) do Enum.reduce(states, %{}, fn {k, v}, acc -> Map.put(acc, k, %Node{ type: Map.get(v, "Type"), default: Map.get(v, "Default"), next: Map.get(v, "Next"), iterator: Map.get(v, "Iterator") |> encode_module_name(), items_path: Map.get(v, "ItemsPath"), branches: Map.get(v, "Branches", []) |> encode_module_name(), seconds: Map.get(v, "Seconds"), timestamp: Map.get(v, "Timestamp") |> get_timestamp(), seconds_path: Map.get(v, "SecondsPath"), timestamp_path: Map.get(v, "TimestampPath"), catch: Map.get(v, "Catch", []) |> parse_catches(), choices: Map.get(v, "Choices", []) |> parse_choices(), resource: Map.get(v, "Resource"), parameters: Map.get(v, "Parameters", %{}) |> Macro.escape(), input_path: Map.get(v, "InputPath", "$"), resource_path: Map.get(v, "ResourcePath", "$"), output_path: Map.get(v, "OutputPath", "$"), is_end: Map.get(v, "End", false), event: Map.get(v, "TransitionEvent", ":transition") |> escape_string() }) end) end defp encode_module_name(list) when is_list(list) do Enum.map(list, &encode_module_name/1) end defp encode_module_name(mod) do Module.safe_concat([mod]) end def get_edges(nodes) do nodes |> Enum.flat_map(fn {k, %Node{} = v} -> get_edges_for_type(k, v) end) end defp get_edges_for_type( name, %Node{type: "Choice", choices: choices, event: event, default: default} ) do choices = get_choices(name, choices) case default do nil -> choices default -> [add_edge(name, default, event) | choices] end end defp get_edges_for_type( name, %Node{next: next, event: event, catch: catches, is_end: false} ) do catches = Enum.flat_map(catches, fn %Catch{next: cat, error_equals: ee} -> Enum.map(ee, fn event -> add_edge(name, cat, event) end) end) [add_edge(name, next, event) | catches] end defp get_edges_for_type(_, %Node{is_end: true}), do: [] defp get_choices(name, choices) do Enum.map(choices, fn %Choice{next: choice, string_equals: event} -> add_edge(name, choice, event) end) end defp add_edge(name, transition, event) do %Edge{source: name, target: transition, event: escape_string(event)} end defp parse_choices(choices) do Enum.map(choices, fn %{"StringEquals" => se, "Next" => next} -> %Choice{string_equals: escape_string(se), next: next} end) end defp parse_catches(catches) do Enum.map(catches, fn %{"ErrorEquals" => ee, "Next" => next} -> %Catch{error_equals: Enum.map(ee, &escape_string/1), next: next} end) end defp get_timestamp(nil), do: nil defp get_timestamp(data) do {:ok, dt, _off} = DateTime.from_iso8601(data) dt end def escape_string(string) when is_binary(string) do string |> Code.eval_string() |> elem(0) |> Macro.escape() end def escape_string(ast) when not is_binary(ast), do: ast end
lib/states_language/graph.ex
0.856962
0.54353
graph.ex
starcoder
defmodule ETH do @moduledoc """ Elixir module that provides Ethereum utility functions """ @doc """ In order to use most of the functions in this library you need to be connected to an ethereum node. This could be your own self-hosted node running locally or a public proxy. ## Examples iex> ETH.block_number 46080211 """ Application.put_env(:ethereumex, :url, Application.get_env(:eth, :url, "http://localhost:8545")) defdelegate block_number, to: ETH.Query defdelegate block_number!, to: ETH.Query defdelegate syncing, to: ETH.Query defdelegate syncing!, to: ETH.Query defdelegate get_accounts, to: ETH.Query defdelegate get_accounts!, to: ETH.Query defdelegate gas_price, to: ETH.Query defdelegate gas_price!, to: ETH.Query defdelegate call(call_params), to: ETH.Query defdelegate call(call_params, state), to: ETH.Query defdelegate call!(call_params), to: ETH.Query defdelegate call!(call_params, state), to: ETH.Query defdelegate get_block, to: ETH.Query defdelegate get_block(identifier), to: ETH.Query defdelegate get_block!, to: ETH.Query defdelegate get_block!(identifier), to: ETH.Query defdelegate get_balance(wallet_or_address), to: ETH.Query defdelegate get_balance(wallet_or_address, state), to: ETH.Query defdelegate get_balance(wallet_or_address, denomination, state), to: ETH.Query defdelegate get_balance!(wallet_or_address), to: ETH.Query defdelegate get_balance!(wallet_or_address, state), to: ETH.Query defdelegate get_balance!(wallet_or_address, denomination, state), to: ETH.Query defdelegate estimate_gas(transaction), to: ETH.Query defdelegate estimate_gas!(transaction), to: ETH.Query defdelegate estimate_gas(transaction, denomination), to: ETH.Query defdelegate estimate_gas!(transaction, denomination), to: ETH.Query defdelegate get_block_transactions(identifier), to: ETH.TransactionQueries defdelegate get_block_transactions!(identifier), to: ETH.TransactionQueries defdelegate get_block_transaction_count(identifier), to: ETH.TransactionQueries defdelegate get_block_transaction_count!(identifier), to: ETH.TransactionQueries defdelegate get_transaction_from_block(identifier, index), to: ETH.TransactionQueries defdelegate get_transaction_from_block!(identifier, index), to: ETH.TransactionQueries defdelegate get_transaction(transaction_hash), to: ETH.TransactionQueries defdelegate get_transaction!(transaction_hash), to: ETH.TransactionQueries defdelegate get_transaction_receipt(transaction_hash), to: ETH.TransactionQueries defdelegate get_transaction_receipt!(transaction_hash), to: ETH.TransactionQueries defdelegate get_transaction_count(wallet_or_address), to: ETH.TransactionQueries defdelegate get_transaction_count(wallet_or_address, state), to: ETH.TransactionQueries defdelegate get_transaction_count!(wallet_or_address), to: ETH.TransactionQueries defdelegate get_transaction_count!(wallet_or_address, state), to: ETH.TransactionQueries defdelegate parse(data), to: ETH.Transaction.Parser defdelegate to_list(data), to: ETH.Transaction.Parser defdelegate build(params), to: ETH.Transaction.Builder defdelegate build(wallet, params), to: ETH.Transaction.Builder defdelegate build(sender_wallet, receiver_wallet, params_or_value), to: ETH.Transaction.Builder defdelegate hash_transaction(transaction), to: ETH.Transaction defdelegate hash_transaction(transaction, include_signature), to: ETH.Transaction defdelegate sign_transaction(transaction, private_key), to: ETH.Transaction.Signer defdelegate decode(rlp_encoded_transaction), to: ETH.Transaction.Signer defdelegate encode(signed_transaction_list), to: ETH.Transaction.Signer defdelegate send_transaction(params_or_wallet, private_key_or_params), to: ETH.Transaction defdelegate send_transaction(sender_wallet, receiver_wallet, value_or_params), to: ETH.Transaction defdelegate send_transaction(sender_wallet, receiver_wallet, value_or_params, private_key), to: ETH.Transaction defdelegate send_transaction!(params_or_wallet, private_key_or_params), to: ETH.Transaction defdelegate send_transaction!(sender_wallet, receiver_wallet, value_or_params), to: ETH.Transaction defdelegate send_transaction!(sender_wallet, receiver_wallet, value_or_params, private_key), to: ETH.Transaction defdelegate send(signature), to: ETH.Transaction defdelegate send!(signature), to: ETH.Transaction defdelegate get_senders_public_key(transaction_input), to: ETH.Transaction defdelegate get_sender_address(transaction_input), to: ETH.Transaction defdelegate get_private_key, to: ETH.Utils defdelegate get_public_key(private_key), to: ETH.Utils defdelegate get_address(private_or_public_key), to: ETH.Utils defdelegate convert(value, denomination), to: ETH.Utils defdelegate secp256k1_signature(hash, private_key), to: ETH.Utils defdelegate keccak256(data), to: ETH.Utils defdelegate encode16(data), to: ETH.Utils defdelegate decode16(decoded_data), to: ETH.Utils defdelegate to_buffer(data), to: ETH.Utils defdelegate buffer_to_int(data), to: ETH.Utils defdelegate pad_to_even(data), to: ETH.Utils defdelegate get_chain_id(v, chain_id), to: ETH.Utils end
lib/eth.ex
0.763219
0.498657
eth.ex
starcoder
defmodule UeberauthToken.Worker do @moduledoc """ UeberauthToken.Worker is a background worker which verifies the authenticity of the cached active tokens. Tokens will be removed after their expiry time when the `:ttl` option is set by the `Cachex.put` function. However, if one wants to be more aggressive in checking the cached token validity then this module can be optionally activated. See full description of the config options in `UeberauthToken.Config` @moduledoc. """ use GenServer alias UeberauthToken.{CheckSupervisor, Config, Strategy} @stagger_phases 30 # public @spec start_link(keyword()) :: :ignore | {:error, any()} | {:ok, pid()} def start_link(opts \\ []) do provider = Keyword.fetch!(opts, :provider) GenServer.start_link(__MODULE__, opts, name: worker_name(provider)) end # callbacks @spec init(nil | keyword() | map()) :: {:ok, {nil, %{provider: any()}}} def init(opts) do periodic_checking(opts[:provider]) {:ok, {nil, %{provider: opts[:provider]}}} end @spec periodic_checking(atom() | binary()) :: :ok def periodic_checking(provider) do GenServer.cast(worker_name(provider), :periodic_checking) end # genserver callbacks def handle_cast(:periodic_checking, {_timer, %{provider: provider} = state}) do do_checks(provider) timer = __MODULE__ |> Process.whereis() |> Process.send_after(:periodic_checking, check_frequency(provider)) {:noreply, {timer, state}, max_checking_time(provider)} end # handles the loop messaging from Process.send_after/3 def handle_info(:periodic_checking, {timer, %{provider: provider} = state}) do timer && Process.cancel_timer(timer) periodic_checking(provider) {:noreply, {timer, state}} end # Handles the messages potentially returned from Task.async_nolink def handle_info({_ref, {:ok, :token_removed}}, {timer, state}) do {:noreply, {timer, state}} end # Handles the messages potentially returned from Task.async_nolink def handle_info({_ref, {:ok, :token_intact}}, {timer, state}) do {:noreply, {timer, state}} end # Handles the messages potentially returned from Task.async_nolink def handle_info({:DOWN, _ref, :process, _pid, :normal}, {timer, state}) do {:noreply, {timer, state}} end def handle_info(:timeout, {timer, %{provider: provider} = state}) do msg = """ #{worker_details(provider)} timed out, #{inspect({timer, state})}, #{location(__ENV__)} """ :erlang.apply(Logger, :bare_log, [Config.background_worker_log_level(provider), msg]) {:noreply, {timer, state}} end def terminate(_reason, {timer, %{provider: provider} = state}) do msg = """ #{worker_details(provider)} terminated, #{inspect({timer, state})}, #{location(__ENV__)} """ :erlang.apply(Logger, :bare_log, [Config.background_worker_log_level(provider), msg]) :ok end # private defp check_frequency(provider) do provider |> Config.background_frequency() |> :timer.seconds() end defp max_checking_time(provider) do check_frequency(provider) + 1000 end # returns the amount of time to stagger the task token checking chunks by in milliseconds defp batch_stagger_time(provider) do provider |> max_checking_time() |> Kernel./(@stagger_phases) |> Kernel.round() end defp token_stagger_time(interval, number_of_tokens) do interval |> Kernel./(number_of_tokens) |> Kernel.round() end defp do_checks(provider) do provider |> Config.cache_name() |> Cachex.keys() |> do_checks_with_keys(provider) end defp do_checks_with_keys({:error, :no_cache}, _provider), do: nil defp do_checks_with_keys({:ok, tokens}, provider) do steps = tokens |> Enum.count() |> Kernel./(@stagger_phases) |> Kernel.round() steps = (steps > 0 && steps) || 1 # Stagger http requests in staggered in time by # 1. batches of tokens and further staggered in time by # 2. individual tokens tokens |> Enum.chunk(steps, steps, []) |> Enum.with_index(1) |> Enum.each(fn {token_batch, index} -> stagger_by = batch_stagger_time(provider) * index validate_batch_of_tokens(token_batch, provider) :timer.sleep(stagger_by) end) end defp validate_batch_of_tokens(token_batch, provider) do token_stagger_by = provider |> batch_stagger_time() |> token_stagger_time(Enum.count(token_batch)) for token <- token_batch do # Fire and forget Task.Supervisor.async_nolink( CheckSupervisor, fn -> remove_token_if_invalid(token, provider) end, timeout: batch_stagger_time(provider) + 1000 ) :timer.sleep(token_stagger_by) end end defp valid_token?(token, provider) when is_binary(token) do Strategy.valid_token?(token, provider) end defp remove_token_if_invalid(token, provider) do with false <- valid_token?(token, provider), {:ok, true} <- remove_token(token, provider) do {:ok, :token_removed} else true -> {:ok, :token_intact} end end defp remove_token(token, provider) when is_binary(token) do Cachex.del(Config.cache_name(provider), token) end defp location(%Macro.Env{} = env) do """ module: #{inspect(env.module)}, function: #{inspect(env.function)}, line: #{inspect(env.line)} """ end @spec worker_details(atom() | binary()) :: String.t() def worker_details(provider) do "worker #{worker_name(provider)} with process_id #{ inspect(Process.whereis(worker_name(provider))) }" end defp worker_name(provider) do __MODULE__ |> Macro.underscore() |> String.replace("/", "_") |> Kernel.<>("_") |> Kernel.<>(String.replace(Macro.underscore(provider), "/", "_")) |> String.to_atom() end end
lib/ueberauth_token/worker.ex
0.777046
0.408129
worker.ex
starcoder
defmodule StarkInfra.IssuingPurchase do alias __MODULE__, as: IssuingPurchase alias StarkInfra.Utils.Rest alias StarkInfra.Utils.Check alias StarkInfra.User.Project alias StarkInfra.User.Organization alias StarkInfra.Error @moduledoc """ # IssuingPurchase struct """ @doc """ Displays the IssuingPurchase structs created in your Workspace. ## Attributes (return-only): - `:id` [string]: unique id returned when IssuingPurchase is created. ex: "5656565656565656" - `:holder_name` [string]: card holder name. ex: "<NAME>" - `:card_id` [string]: unique id returned when IssuingCard is created. ex: "5656565656565656" - `:card_ending` [string]: last 4 digits of the card number. ex: "1234" - `:amount` [integer]: IssuingPurchase value in cents. Minimum = 0. ex: 1234 (= R$ 12.34) - `:tax` [integer]: IOF amount taxed for international purchases. ex: 1234 (= R$ 12.34) - `:issuer_amount` [integer]: issuer amount. ex: 1234 (= R$ 12.34) - `:issuer_currency_code` [string]: issuer currency code. ex: "USD" - `:issuer_currency_symbol` [string]: issuer currency symbol. ex: "$" - `:merchant_amount` [integer]: merchant amount. ex: 1234 (= R$ 12.34) - `:merchant_currency_code` [string]: merchant currency code. ex: "USD" - `:merchant_currency_symbol` [string]: merchant currency symbol. ex: "$" - `:merchant_category_code` [string]: merchant category code. ex: "fastFoodRestaurants" - `:merchant_country_code` [string]: merchant country code. ex: "USA" - `:acquirer_id` [string]: acquirer ID. ex: "5656565656565656" - `:merchant_id` [string]: merchant ID. ex: "5656565656565656" - `:merchant_name` [string]: merchant name. ex: "Google Cloud Platform" - `:merchant_fee` [integer]: fee charged by the merchant to cover specific costs, such as ATM withdrawal logistics, etc. ex: 200 (= R$ 2.00) - `:wallet_id` [string]: virtual wallet ID. ex: "5656565656565656" - `:method_code` [string]: method code. ex: "chip", "token", "server", "manual", "magstripe" or "contactless" - `:score` [float]: internal score calculated for the authenticity of the purchase. nil in case of insufficient data. ex: 7.6 - `:issuing_transaction_ids` [string]: ledger transaction ids linked to this Purchase - `:end_to_end_id` [string]: central bank's unique transaction ID. ex: "E79457883202101262140HHX553UPqeq" - `:status` [string]: current IssuingCard status. ex: "approved", "canceled", "denied", "confirmed", "voided" - `:tags` [string]: list of strings for tagging returned by the sub-issuer during the authorization. ex: ["travel", "food"] - `:updated` [DateTime]: latest update DateTime for the IssuingPurchase. ex: ~U[2020-3-10 10:30:0:0] - `:created` [DateTime]: creation datetime for the IssuingPurchase. ex: ~U[2020-03-10 10:30:0:0] """ @enforce_keys [ :id, :holder_name, :card_id, :card_ending, :amount, :tax, :issuer_amount, :issuer_currency_code, :issuer_currency_symbol, :merchant_amount, :merchant_currency_code, :merchant_currency_symbol, :merchant_category_code, :merchant_country_code, :acquirer_id, :merchant_id, :merchant_name, :merchant_fee, :wallet_id, :method_code, :score, :issuing_transaction_ids, :end_to_end_id, :status, :tags, :updated, :created ] defstruct [ :id, :holder_name, :card_id, :card_ending, :amount, :tax, :issuer_amount, :issuer_currency_code, :issuer_currency_symbol, :merchant_amount, :merchant_currency_code, :merchant_currency_symbol, :merchant_category_code, :merchant_country_code, :acquirer_id, :merchant_id, :merchant_name, :merchant_fee, :wallet_id, :method_code, :score, :issuing_transaction_ids, :end_to_end_id, :status, :tags, :updated, :created ] @type t() :: %__MODULE__{} @doc """ Receive a single IssuingPurchase struct previously created in the Stark Infra API by its id ## Parameters (required): - `:id` [string]: struct unique id. ex: "5656565656565656" ## Options: - `:user` [Organization/Project, default nil]: Organization or Project struct returned from StarkInfra.project(). Only necessary if default project or organization has not been set in configs. ## Return: - IssuingPurchase struct with updated attributes """ @spec get( id: binary, user: Organization.t() | Project.t() | nil ) :: {:ok, IssuingPurchase.t()} | {:error, [Error.t()]} def get(id, options \\ []) do Rest.get_id( resource(), id, options ) end @doc """ Same as get(), but it will unwrap the error tuple and raise in case of errors. """ @spec get!( id: binary, user: Organization.t() | Project.t() | nil ) :: any def get!(id, options \\ []) do Rest.get_id!( resource(), id, options ) end @doc """ Receive a stream of IssuingPurchases structs previously created in the Stark Infra API ## Options: - `:ids` [list of strings, default [], default nil]: purchase IDs - `:limit` [integer, default nil]: maximum number of structs to be retrieved. Unlimited if nil. ex: 35 - `:after` [Date or string, default nil]: date filter for structs created only after specified date. ex: ~D[2020-03-25] - `:before` [Date or string, default nil]: date filter for structs created only before specified date. ex: ~D[2020-03-25] - `:end_to_end_ids` [list of strings, default []]: central bank's unique transaction ID. ex: "E79457883202101262140HHX553UPqeq" - `:holder_ids` [list of strings, default []]: card holder IDs. ex: ["5656565656565656", "4545454545454545"] - `:card_ids` [list of strings, default []]: card IDs. ex: ["5656565656565656", "4545454545454545"] - `:status` [list of strings, default nil]: filter for status of retrieved structs. ex: ["approved", "canceled", "denied", "confirmed", "voided"] - `:user` [Organization/Project, default nil]: Organization or Project struct returned from StarkInfra.project(). Only necessary if default project or organization has not been set in configs. ## Return: - stream of IssuingPurchase structs with updated attributes """ @spec query( ids: [binary], limit: integer, after: Date.t() | binary, before: Date.t() | binary, end_to_end_ids: [binary], holder_ids: [binary], card_ids: [binary], status: [binary], user: Organization.t() | Project.t() | nil ) :: {:ok, {binary, [IssuingPurchase.t()]}} | {:error, [Error.t()]} def query(options \\ []) do Rest.get_list( resource(), options ) end @doc """ Same as query(), but it will unwrap the error tuple and raise in case of errors. """ @spec page!( ids: [binary], limit: integer, after: Date.t() | binary, before: Date.t() | binary, end_to_end_ids: [binary], holder_ids: [binary], card_ids: [binary], status: [binary], user: Organization.t() | Project.t() | nil ) :: any def query!(options \\ []) do Rest.get_list!( resource(), options ) end @doc """ Receive a list of IssuingPurchase structs previously created in the Stark Infra API and the cursor to the next page. ## Options: - `:cursor` [string, default nil]: cursor returned on the previous page function call - `:ids` [list of strings, default [], default nil]: purchase IDs - `:limit` [integer, default 100]: maximum number of structs to be retrieved. Unlimited if nil. ex: 35 - `:after` [Date or string, default nil]: date filter for structs created only after specified date. ex: ~D[2020-03-25] - `:before` [Date or string, default nil]: date filter for structs created only before specified date. ex: ~D[2020-03-25] - `:end_to_end_ids` [list of strings, default []]: central bank's unique transaction ID. ex: "E79457883202101262140HHX553UPqeq" - `:holder_ids` [list of strings, default []]: card holder IDs. ex: ["5656565656565656", "4545454545454545"] - `:card_ids` [list of strings, default []]: card IDs. ex: ["5656565656565656", "4545454545454545"] - `:status` [list of strings, default nil]: filter for status of retrieved structs. ex: ["approved", "canceled", "denied", "confirmed", "voided"] - `:user` [Organization/Project, default nil]: Organization or Project struct returned from StarkInfra.project(). Only necessary if default project or organization has not been set in configs. ## Return: - list of IssuingPurchase structs with updated attributes - cursor to retrieve the next page of IssuingPurchase structs """ @spec page( cursor: binary, ids: [binary], limit: integer, after: Date.t() | binary, before: Date.t() | binary, end_to_end_ids: [binary], holder_ids: [binary], card_ids: [binary], status: [binary], user: Organization.t() | Project.t() | nil ) :: {:ok, {binary, [IssuingPurchase.t()]}} | {:error, [Error.t()]} def page(options \\ []) do Rest.get_page( resource(), options ) end @doc """ Same as page(), but it will unwrap the error tuple and raise in case of errors. """ @spec page!( cursor: binary, ids: [binary], limit: integer, after: Date.t() | binary, before: Date.t() | binary, end_to_end_ids: [binary], holder_ids: [binary], card_ids: [binary], status: [binary], user: Organization.t() | Project.t() | nil ) :: any def page!(options \\ []) do Rest.get_page!( resource(), options ) end @doc false def resource() do { "IssuingPurchase", &resource_maker/1 } end @doc false def resource_maker(json) do %IssuingPurchase{ id: json[:id], holder_name: json[:holder_name], card_id: json[:card_id], card_ending: json[:card_ending], amount: json[:amount], tax: json[:tax], issuer_amount: json[:issuer_amount], issuer_currency_code: json[:issuer_currency_code], issuer_currency_symbol: json[:issuer_currency_symbol], merchant_amount: json[:merchant_amount], merchant_currency_code: json[:merchant_currency_code], merchant_currency_symbol: json[:merchant_currency_symbol], merchant_category_code: json[:merchant_category_code], merchant_country_code: json[:merchant_country_code], acquirer_id: json[:acquirer_id], merchant_id: json[:merchant_id], merchant_name: json[:merchant_name], merchant_fee: json[:merchant_fee], wallet_id: json[:wallet_id], method_code: json[:method_code], score: json[:score], issuing_transaction_ids: json[:issuing_transaction_ids], end_to_end_id: json[:end_to_end_id], status: json[:status], tags: json[:tags], updated: json[:updated] |> Check.datetime(), created: json[:created] |> Check.datetime() } end end
lib/issuing_purchase/issuing_purchase.ex
0.843895
0.563738
issuing_purchase.ex
starcoder
defmodule ExPurpleTiger.Data do @moduledoc false @adjectives [ "attractive", "bald", "beautiful", "rare", "clean", "dazzling", "lucky", "elegant", "fancy", "fit", "fantastic", "glamorous", "gorgeous", "handsome", "long", "magnificent", "muscular", "plain", "able", "quaint", "scruffy", "innocent", "short", "skinny", "acrobatic", "tall", "proper", "alert", "lone", "agreeable", "ambitious", "brave", "calm", "delightful", "eager", "faithful", "gentle", "happy", "jolly", "kind", "lively", "nice", "obedient", "polite", "proud", "silly", "thankful", "winning", "witty", "wonderful", "zealous", "expert", "amateur", "clumsy", "amusing", "vast", "fierce", "real", "helpful", "itchy", "atomic", "basic", "mysterious", "blurry", "perfect", "best", "powerful", "interesting", "decent", "wild", "jovial", "genuine", "broad", "brisk", "brilliant", "curved", "deep", "flat", "high", "hollow", "low", "narrow", "refined", "round", "shallow", "skinny", "square", "steep", "straight", "wide", "big", "colossal", "clever", "gigantic", "great", "huge", "immense", "large", "little", "mammoth", "massive", "micro", "mini", "petite", "puny", "scrawny", "short", "small", "polished", "teeny", "tiny", "crazy", "dancing", "custom", "faint", "harsh", "formal", "howling", "loud", "melodic", "noisy", "upbeat", "quiet", "rapping", "raspy", "rhythmic", "daring", "zany", "digital", "dizzy", "exotic", "fun", "furry", "hidden", "ancient", "brief", "early", "fast", "future", "late", "long", "modern", "old", "prehistoric", "zesty", "rapid", "short", "slow", "swift", "young", "acidic", "bitter", "cool", "creamy", "keen", "tricky", "fresh", "special", "unique", "hot", "magic", "main", "nutty", "pet", "mythical", "ripe", "wobbly", "salty", "savory", "sour", "spicy", "bright", "stale", "sweet", "tangy", "tart", "rich", "rurual", "urban", "breezy", "bumpy", "chilly", "cold", "cool", "cuddly", "damaged", "damp", "restless", "dry", "flaky", "fluffy", "virtual", "merry", "hot", "icy", "shiny", "melted", "joyous", "rough", "shaggy", "sharp", "radiant", "sticky", "strong", "soft", "uneven", "warm", "feisty", "cheery", "energetic", "abundant", "macho", "glorious", "mean", "quick", "precise", "stable", "spare", "sunny", "trendy", "shambolic", "striped", "boxy", "generous", "tame", "joyful", "festive", "bubbly", "soaring", "orbiting", "sparkly", "smooth", "docile", "original", "electric", "funny", "passive", "active", "cheesy", "tangy", "blunt", "dapper", "bent", "curly", "oblong", "sneaky", "overt", "careful", "jumpy", "bouncy", "recumbent", "cheerful", "droll", "odd", "suave", "sleepy" ] @colors [ "white", "pearl", "alabaster", "snowy", "ivory", "cream", "cotton", "chiffon", "lace", "coconut", "linen", "bone", "daisy", "powder", "frost", "porcelain", "parchment", "velvet", "tan", "beige", "macaroon", "hazel", "felt", "metal", "gingham", "sand", "sepia", "latte", "vinyl", "glass", "hazelnut", "canvas", "wool", "yellow", "golden", "daffodil", "flaxen", "butter", "lemon", "mustard", "tartan", "blue", "cloth", "fiery", "banana", "plastic", "dijon", "honey", "blonde", "pineapple", "orange", "tangerine", "marigold", "cider", "rusty", "ginger", "tiger", "bronze", "fuzzy", "opaque", "clay", "carrot", "corduroy", "ceramic", "marmalade", "amber", "sandstone", "concrete", "red", "cherry", "hemp", "merlot", "garnet", "crimson", "ruby", "scarlet", "burlap", "brick", "bamboo", "mahogany", "blood", "sangria", "berry", "currant", "blush", "candy", "lipstick", "pink", "rose", "fuchsia", "punch", "watermelon", "rouge", "coral", "peach", "strawberry", "rosewood", "lemonade", "taffy", "bubblegum", "crepe", "hotpink", "purple", "mauve", "violet", "boysenberry", "lavender", "plum", "magenta", "lilac", "grape", "eggplant", "eggshell", "iris", "heather", "amethyst", "raisin", "orchid", "mulberry", "carbon", "slate", "sky", "navy", "indigo", "cobalt", "cedar", "ocean", "azure", "cerulean", "spruce", "stone", "aegean", "denim", "admiral", "sapphire", "arctic", "green", "chartreuse", "juniper", "sage", "lime", "fern", "olive", "emerald", "pear", "mossy", "shamrock", "seafoam", "pine", "mint", "seaweed", "pickle", "pistachio", "basil", "brown", "coffee", "chrome", "peanut", "carob", "hickory", "wooden", "pecan", "walnut", "caramel", "gingerbread", "syrup", "chocolate", "tortilla", "umber", "tawny", "brunette", "cinnamon", "glossy", "teal", "grey", "shadow", "graphite", "iron", "pewter", "cloud", "silver", "smoke", "gauze", "ash", "foggy", "flint", "charcoal", "pebble", "lead", "tin", "fossilized", "black", "ebony", "midnight", "inky", "oily", "satin", "onyx", "nylon", "fleece", "sable", "jetblack", "coal", "mocha", "obsidian", "jade", "cyan", "leather", "maroon", "carmine", "aqua", "chambray", "holographic", "laurel", "licorice", "khaki", "goldenrod", "malachite", "mandarin", "mango", "taupe", "aquamarine", "turquoise", "vermilion", "saffron", "cinnabar", "myrtle", "neon", "burgundy", "tangelo", "topaz", "wintergreen", "viridian", "vanilla", "paisley", "raspberry", "tweed", "pastel", "opal", "menthol", "champagne", "gunmetal", "infrared", "ultraviolet", "rainbow", "mercurial", "clear", "misty", "steel", "zinc", "citron", "cornflower", "lava", "quartz", "honeysuckle", "chili" ] @animals [ "alligator", "bee", "bird", "camel", "cat", "cheetah", "chicken", "cow", "dog", "corgi", "eagle", "elephant", "fish", "fox", "toad", "giraffe", "hippo", "kangaroo", "kitten", "lobster", "monkey", "octopus", "pig", "puppy", "rabbit", "rat", "scorpion", "seal", "sheep", "snail", "spider", "tiger", "turtle", "newt", "tadpole", "frog", "tarantula", "albatross", "blackbird", "canary", "crow", "cuckoo", "dove", "pigeon", "falcon", "finch", "flamingo", "goose", "seagull", "hawk", "jay", "mockingbird", "kestrel", "kookaburra", "mallard", "nightingale", "nuthatch", "ostrich", "owl", "parakeet", "parrot", "peacock", "pelican", "penguin", "pheasant", "piranha", "raven", "robin", "rooster", "sparrow", "stork", "swallow", "swan", "swift", "turkey", "vulture", "woodpecker", "wren", "butterfly", "barbel", "carp", "cod", "crab", "eel", "goldfish", "haddock", "halibut", "jellyfish", "perch", "pike", "mantaray", "salmon", "sawfish", "scallop", "shark", "shell", "shrimp", "trout", "ant", "aphid", "beetle", "caterpillar", "dragonfly", "cricket", "fly", "grasshopper", "ladybug", "millipede", "moth", "wasp", "anteater", "antelope", "armadillo", "badger", "bat", "beaver", "bull", "chimpanzee", "dachshund", "deer", "dolphin", "elk", "moose", "gazelle", "gerbil", "goat", "bear", "hamster", "hare", "hedgehog", "horse", "hyena", "lion", "llama", "lynx", "mammoth", "marmot", "mink", "mole", "mongoose", "mouse", "mule", "otter", "panda", "platypus", "pony", "porcupine", "puma", "racoon", "reindeer", "rhino", "skunk", "sloth", "squirrel", "weasel", "snake", "wolf", "zebra", "boa", "chameleon", "copperhead", "cottonmouth", "crocodile", "rattlesnake", "gecko", "iguana", "lizard", "python", "salamander", "sidewinder", "whale", "tortoise", "lemur", "rook", "koala", "donkey", "ferret", "tardigrade", "orca", "okapi", "liger", "unicorn", "dragon", "squid", "ape", "gorilla", "baboon", "cormorant", "mantis", "tapir", "capybara", "pangolin", "opossum", "wombat", "aardvark", "starfish", "shetland", "narwhal", "worm", "hornet", "viper", "stallion", "jaguar", "panther", "bobcat", "leopard", "osprey", "cougar", "dalmatian", "terrier", "duck", "sealion", "raccoon", "chipmunk", "loris", "poodle", "orangutan", "gibbon", "meerkat", "huskie", "barracuda", "bison", "caribou", "chinchilla", "coyote", "crane", "dinosaur", "lark", "griffin", "yeti", "troll", "seahorse", "walrus", "yak", "wolverine", "boar", "alpaca", "porpoise", "manatee", "guppy", "condor", "cyborg", "cobra", "locust", "mandrill", "oyster", "urchin", "quail", "sardine", "ram", "starling", "wallaby", "buffalo", "goblin", "tuna", "mustang" ] @doc false def adjectives(), do: @adjectives @doc false def colors(), do: @colors @doc false def animals(), do: @animals end
lib/ex_purple_tiger/data.ex
0.533397
0.574275
data.ex
starcoder
defmodule Pow.Store.Backend.Base do @moduledoc """ Used to set up API for key-value cache store. [Erlang match specification](https://erlang.org/doc/apps/erts/match_spec.html) format is used for the second argument `all/2` callback. The second argument is only for the key match, and will look like `[:namespace_1, :namespace_2, :_]` or `[:namespace_1, :_, :namespace_2]`. ## Usage This is an example using [Cachex](https://hex.pm/packages/cachex): defmodule MyAppWeb.Pow.CachexCache do @behaviour Pow.Store.Backend.Base alias Pow.Config @cachex_tab __MODULE__ @impl true def put(config, record_or_records) do records = record_or_records |> List.wrap() |> Enum.map(fn {key, value} -> {wrap_namespace(config, key), value} end) {:ok, true} = Cachex.put_many(@cachex_tab, records, ttl: Config.get(config, :ttl)) :ok end @impl true def delete(config, key) do key = wrap_namespace(config, key) {:ok, _value} = Cachex.del(@cachex_tab, key) :ok end @impl true def get(config, key) do key = wrap_namespace(config, key) case Cachex.get(@cachex_tab, key) do {:ok, nil} -> :not_found {:ok, value} -> value end end @impl true def all(config, key_match) do query = [{ {:_, wrap_namespace(config, key_match), :"$2", :"$3", :"$4"}, [Cachex.Query.unexpired_clause()], [ :"$_" ] }] @cachex_tab |> Cachex.stream!(query) |> Enum.map(fn {_, key, _, _, value} -> {unwrap_namespace(key), value} end) end defp wrap_namespace(config, key) do namespace = Config.get(config, :namespace, "cache") [namespace | List.wrap(key)] end defp unwrap_namespace([_namespace, key]), do: key defp unwrap_namespace([_namespace | key]), do: key end """ alias Pow.Config @type config() :: Config.t() @type key() :: [binary() | atom()] | binary() @type record() :: {key(), any()} @type key_match() :: [atom() | binary()] @callback put(config(), record() | [record()]) :: :ok @callback delete(config(), key()) :: :ok @callback get(config(), key()) :: any() | :not_found @callback all(config(), key_match()) :: [record()] end
lib/pow/store/backend/base.ex
0.854582
0.457076
base.ex
starcoder
defmodule Twittex.Client do @moduledoc """ Twitter client to work with the Twitter API. The client is started as part of the application and authenticates using the defined configuration. Basically, this means that once started, your application can use function from this module directly without having to handle supervision or authentication work: ```elixir Twitter.Client.search! "#myelixirstatus" ``` Read the `Twittex.Client.Base` documentation for more details on how authentication is implemented. """ use Twittex.Client.Base @doc """ Returns a collection of relevant Tweets matching the given `query`. """ @spec search(String.t, Keyword.t) :: {:ok, %{}} | {:error, HTTPoison.Error.t} def search(query, options \\ []) do get "/search/tweets.json?" <> URI.encode_query(%{q: query} |> Enum.into(options)) end @doc """ Same as `search/2` but raises `HTTPoison.Error` if an error occurs during the request. """ @spec search!(String.t, Keyword.t) :: %{} def search!(query, options \\ []) do get! "/search/tweets.json?" <> URI.encode_query(%{q: query} |> Enum.into(options)) end @doc """ Returns the 20 most recent mentions (tweets containing a users’s `@screen_name`) for the authenticating user. """ @spec mentions_timeline(Keyword.t) :: {:ok, %{}} | {:error, HTTPoison.Error.t} def mentions_timeline(options \\ []) do get "/statuses/mentions_timeline.json?" <> URI.encode_query(options) end @doc """ Same as `mentions_timeline/1` but raises `HTTPoison.Error` if an error occurs during the request. """ @spec mentions_timeline!(Keyword.t) :: %{} def mentions_timeline!(options \\ []) do get! "/statuses/mentions_timeline.json?" <> URI.encode_query(options) end @doc """ Returns a collection of the most recent Tweets posted by the user with the given `screen_name`. """ @spec user_timeline(String.t, Keyword.t) :: {:ok, %{}} | {:error, HTTPoison.Error.t} def user_timeline(screen_name, options \\ []) do get "/statuses/user_timeline.json?" <> URI.encode_query(%{screen_name: screen_name} |> Enum.into(options)) end @doc """ Same as `user_timeline/2` but raises `HTTPoison.Error` if an error occurs during the request. """ @spec user_timeline!(String.t, Keyword.t) :: %{} def user_timeline!(screen_name, options \\ []) do get! "/statuses/user_timeline.json?" <> URI.encode_query(%{screen_name: screen_name} |> Enum.into(options)) end @doc """ Returns a collection of the most recent Tweets and retweets posted by the authenticated user and the users they follow. """ @spec home_timeline(Keyword.t) :: {:ok, %{}} | {:error, HTTPoison.Error.t} def home_timeline(options \\ []) do get "/statuses/home_timeline.json?" <> URI.encode_query(options) end @doc """ Same as `home_timeline/1` but raises `HTTPoison.Error` if an error occurs during the request. """ @spec home_timeline!(Keyword.t) :: %{} def home_timeline!(options \\ []) do get! "/statuses/home_timeline.json?" <> URI.encode_query(options) end @doc """ Returns the most recent tweets authored by the authenticated user that have been retweeted by others. """ @spec retweets_of_me(Keyword.t) :: {:ok, %{}} | {:error, HTTPoison.Error.t} def retweets_of_me(options \\ []) do get "/statuses/retweets_of_me.json?" <> URI.encode_query(options) end @doc """ Same as `retweets_of_me/1` but raises `HTTPoison.Error` if an error occurs during the request. """ @spec retweets_of_me!(Keyword.t) :: %{} def retweets_of_me!(options \\ []) do get! "/statuses/retweets_of_me.json?" <> URI.encode_query(options) end @doc """ Returns a stream of relevant Tweets matching the given `query`. If `query` is set to `:sample` (default), this function returns a small random sample of all public statuses (roughly 1% of all public Tweets). ## Options * `:stage` - Returns the stage pid instead of the stream. * `:min_demand` - Minimum demand for this subscription. * `:max_demand` - Maximum demand for this subscription. """ @spec stream(String.t | :sample | :user | :filter, Keyword.t) :: {:ok, Enumerable.t} | {:error, HTTPoison.Error.t} def stream(query \\ :sample, options \\ []) do {bare_stage, options} = Keyword.pop options, :stage, false {min_demand, options} = Keyword.pop options, :min_demand, 500 {max_demand, options} = Keyword.pop options, :max_demand, 1_000 url = case query do :user -> "https://userstream.twitter.com/1.1/user.json?" <> URI.encode_query(%{delimited: "length"} |> Enum.into(options)) :sample -> "https://stream.twitter.com/1.1/statuses/sample.json?" <> URI.encode_query(%{delimited: "length"} |> Enum.into(options)) :filter -> "https://stream.twitter.com/1.1/statuses/filter.json?" <> URI.encode_query(%{delimited: "length"} |> Enum.into(options)) _ -> "https://stream.twitter.com/1.1/statuses/filter.json?" <> URI.encode_query(%{track: query, delimited: "length"} |> Enum.into(options)) end case stage :post, url do {:ok, stage} -> if bare_stage do {:ok, stage} else {:ok, GenStage.stream([{stage, [min_demand: min_demand, max_demand: max_demand]}])} end {:error, error} -> {:error, error} end end @doc """ Same as `stream/2` but raises `HTTPoison.Error` if an error occurs during the request. """ @spec stream!(String.t |:sample, Keyword.t) :: Enumerable.t def stream!(query \\ :sample, options \\ []) do case stream(query, options) do {:ok, stream} -> stream {:error, error} -> raise error end end @doc """ Returns a stream of tweets authored by the authenticating user. ## Options * `:stage` - Returns the stage pid instead of the stream. * `:min_demand` - Minimum demand for this subscription. * `:max_demand` - Maximum demand for this subscription. """ @spec user_stream(Keyword.t) :: {:ok, Enumerable.t} | {:error, HTTPoison.Error.t} def user_stream(options \\ []) do stream(:user, options) end @doc """ Same as `user_stream/2` but raises `HTTPoison.Error` if an error occurs during the request. """ @spec user_stream(Keyword.t) :: Enumerable.t def user_stream!(options \\ []) do case user_stream(options) do {:ok, stream} -> stream {:error, error} -> raise error end end end
lib/twittex/client.ex
0.891522
0.782663
client.ex
starcoder
defmodule Absinthe.Blueprint.Input do @moduledoc false alias Absinthe.Blueprint alias __MODULE__ import Kernel, except: [inspect: 1] @type leaf :: Input.Integer.t() | Input.Float.t() | Input.Enum.t() | Input.String.t() | Input.Variable.t() | Input.Boolean.t() | Input.Null.t() @type collection :: Blueprint.Input.List.t() | Input.Object.t() @type t :: leaf | collection | Input.Value.t() | Input.Argument.t() @parse_types [ Input.Boolean, Input.Enum, Input.Field, Input.Float, Input.Integer, Input.List, Input.Object, Input.String, Input.Null ] @spec parse(any) :: nil | t def parse(%struct{} = value) when struct in @parse_types do value end def parse(value) when is_integer(value) do %Input.Integer{value: value} end def parse(value) when is_float(value) do %Input.Float{value: value} end def parse(value) when is_nil(value) do %Input.Null{} end # Note: The value may actually be an Enum value and may # need to be manually converted, based on the schema. def parse(value) when is_binary(value) do %Input.String{value: value} end def parse(value) when is_boolean(value) do %Input.Boolean{value: value} end def parse(value) when is_list(value) do %Input.List{ items: Enum.map(value, fn item -> %Input.RawValue{content: parse(item)} end) } end def parse(value) when is_map(value) do %Input.Object{ fields: Enum.map(value, fn {name, field_value} -> %Input.Field{ name: name, input_value: %Input.RawValue{content: parse(field_value)} } end) } end @simple_inspect_types [ Input.Boolean, Input.Float, Input.Integer, Input.String ] @spec inspect(t) :: String.t() def inspect(%str{} = node) when str in @simple_inspect_types do Kernel.inspect(node.value) end def inspect(%Input.Enum{} = node) do node.value end def inspect(%Input.List{} = node) do contents = node.items |> Enum.map(&inspect/1) |> Enum.join(", ") "[#{contents}]" end def inspect(%Input.Object{} = node) do contents = node.fields |> Enum.filter(fn %{input_value: input} -> case input do %Input.RawValue{content: content} -> content %Input.Value{raw: nil} -> false %Input.Value{raw: %{content: content}} -> content end end) |> Enum.map(&inspect/1) |> Enum.join(", ") "{#{contents}}" end def inspect(%Input.Field{} = node) do node.name <> ": " <> inspect(node.input_value) end def inspect(%Input.Value{raw: raw}) do inspect(raw) end def inspect(%Input.RawValue{content: content}) do inspect(content) end def inspect(%Input.Variable{} = node) do "$" <> node.name end def inspect(%Input.Null{}) do "null" end def inspect(nil) do "null" end def inspect(other) do Kernel.inspect(other) end end
lib/absinthe/blueprint/input.ex
0.723798
0.491944
input.ex
starcoder
defmodule SX1509.Registers.IO do use Wafer.Registers @moduledoc """ This module provides a selective register mapping for SX1509 The registers on SX1509 are numbered in such a way that "A" registers are located directly after the B registers. So, rather than needing to sort out which register to write to (A or B) based on the pin number and writing a byte at a time, we can simply write bytes in to the B registers instead and write to both A and B at the same time. The first byte is for B registers and the second byte is for A registers. So, for the ease of programming this code does not differentiate between A and B registers, and treats them as one 16 bit register. """ @doc """ RegInputDisableB - Input buffer disable register - I/O[15-8] (Bank B) (default: 0x00) RegInputDisableA - Input buffer disable register - I/O[7-0] (Bank A) (default: 0x00) Disables the input buffer of each IO 0 : Input buffer is enabled (input actually being used) 1 : Input buffer is disabled (input actually not being used or LED connection) """ defregister(:input_disable, 0x00, 2) @doc """ RegLongSlewB - Output buffer long slew register - I/O[15-8] (Bank B) (default: 0x00) RegLongSlewA - Output buffer long slew register - I/O[7-0] (Bank A) (default: 0x00) Enables increased slew rate of the output buffer of each [output-configured] IO 0 : Increased slew rate is disabled 1 : Increased slew rate is enabled """ defregister(:long_slew, 0x02, 2) @doc """ RegLowDriveB - Output buffer low drive register - I/O[15-8] (Bank B) (default: 0x00) RegLowDriveA - Output buffer low drive register - I/O[7-0] (Bank A) (default: 0x00) Enables reduced drive of the output buffer of each [output-configured] IO 0 : Reduced drive is disabled 1 : Reduced drive is enabled """ defregister(:low_drive, 0x04, 2) @doc """ RegPullUpB - Pull-up register - I/O[15-8] (Bank B) (default: 0x00) RegPullUpA - Pull-up register - I/O[7-0] (Bank A) (default: 0x00) Enables the pull-up for each IO 0 : Pull-up is disabled 1 : Pull-up is enabled """ defregister(:pull_up, 0x06, 2) @doc """ RegPullDownB - Pull-down register - I/O[15-8] (Bank B) (default: 0x00) RegPullDownA - Pull-down register - I/O[7-0] (Bank A) (default: 0x00) Enables the pull-down for each IO 0 : Pull-down is disabled 1 : Pull-down is enabled """ defregister(:pull_down, 0x08, 2) @doc """ RegOpenDrainB - Open drain register - I/O[15-8] (Bank B) (default: 0x00) RegOpenDrainA - Open drain register - I/O[7-0] (Bank A) (default: 0x00) Enables open drain operation for each [output-configured] IO 0 : Regular push-pull operation 1 : Open drain operation """ defregister(:open_drain, 0x0A, 2) @doc """ SX1509 can either deliver current or sink current. SX1509 can sink more current than it can deliver. RegPolarityB - Polarity register - I/O[15-8] (Bank B) (default: 0x00) RegPolarityA - Polarity register - I/O[7-0] (Bank A) (default: 0x00) Enables polarity inversion for each IO 0 : Normal polarity : RegData[x] = IO[x] 1 : Inverted polarity : RegData[x] = !IO[x] (for both input and output configured IOs) """ defregister(:polarity, 0x0C, 2) @doc """ RegDirB - Data register - I/O[15-8] (Bank B) (default: 0xFF) RegDirA - Direction register - I/O[7-0] (Bank A) (default: 0xFF) Configures direction for each IO. By default it's configured for input 0 : IO is configured as an output 1 : IO is configured as an input """ defregister(:dir, 0x0E, 2) @doc """ RegDataB - Data register - I/O[15-8] (Bank B) (default: 0xFF when in output mode) RegDataA - Data register - I/O[7-0] (Bank A) (default: 0xFF when in output mode) In output mode a 0 bit turns the pin on, so it is ACTIVE LOW Write: Data to be output to the output-configured IOs Read: Data seen at the IOs, independent of the direction configured. """ defregister(:data, 0x10, 2) @doc """ RegInterruptMaskB - Interrupt mask register - I/O[15-8] (Bank B) (default: 0xFF == no interrupt triggered) RegInterruptMaskA - Interrupt mask register - I/O[7-0] (Bank A) (default: 0xFF == no interrupt triggered) Configures which [input-configured] IO will trigger an interrupt on NINT pin 0 : An event on this IO will trigger an interrupt 1 : An event on this IO will NOT trigger an interrupt """ defregister(:interrupt_mask, 0x12, 2) @doc """ This is 4 registers in one. Because of the sequencing (High B, Low B, High A, Low A), it is easier to treat this as a 4 byte register at once, and provide logic to set this correctly. RegSenseHighB (0x14) - Sense register for I/O[15:12] (Bank B)(default: 0x00) RegSenseLowB (0x15) - Sense register for I/O[11:8] (Bank B) (default: 0x00) RegSenseHighA (0x16) - Sense register for I/O[7:4] (Bank A) (default: 0x00) RegSenseLowA (0x17) - Sense register for I/O[3:0] (Bank A) (default: 0x00) Each pin has a 2 bit configuration, which works in the following way: Bits | Setting --- | --- 00 | None - essentially no interrupt 01 | Rising 10 | Falling 11 | Both The bit mapping below adapted from [SX1509 Datasheet](http://cdn.sparkfun.com/datasheets/BreakoutBoards/sx1509.pdf): Bit Range | Edge sensitivity of: ----: | :---- 31:30 | RegData[15] 29:28 | RegData[14] 27:26 | RegData[13] 25:24 | RegData[12] 23:22 | RegData[11] 21:20 | RegData[10] 19:18 | RegData[9] 17:16 | RegData[8] 15:14 | RegData[7] 13:12 | RegData[6] 11:10 | RegData[5] 9:8 | RegData[4] 7:6 | RegData[3] 5:4 | RegData[2] 3:2 | RegData[1] 1:0 | RegData[0] """ defregister(:sense_high_low, 0x14, 4) @doc """ RegInterruptSourceB - Interrupt source register - I/O[15-8] (Bank B) (default: 0x00) RegInterruptSourceA - Interrupt source register - I/O[7-0] (Bank A) (default: 0x00) Interrupt source (from IOs set in RegInterruptMask) 0 : No interrupt has been triggered by this IO 1 : An interrupt has been triggered by this IO (an event as configured in relevant RegSense register occurred). Writing '1' clears the bit in RegInterruptSource and in RegEventStatus When all bits are cleared, NINT signal goes back high. """ defregister(:interrupt_source, 0x18, 2) @doc """ RegEventStatusB - Event status register - I/O[15-8] (Bank B) (default: 0x00) RegEventStatusA - Event status register - I/O[7-0] (Bank A) (default: 0x00) Event status of all IOs. 0 : No event has occurred on this IO 1 : An event has occurred on this IO (an edge as configured in relevant RegSense register occurred). Writing '1' clears the bit in RegEventStatus and in RegInterruptSource if relevant. If the edge sensitivity of the IO is changed, the bit(s) will be cleared automatically """ defregister(:event_status, 0x1A, 2) @doc """ RegLevelShifter1 - Level shifter register - I/O[15-8] (Bank B) (default: 0x00) RegLevelShifter2 - Level shifter register - I/O[7-0] (Bank A) (default: 0x00) These 2 registers are combined into one and the options are outlined below: Bits | Setting --- | --- 00 | OFF 01 | A->B 10 | B->A 11 | Reserved The bit mapping below adapted from [SX1509 Datasheet](http://cdn.sparkfun.com/datasheets/BreakoutBoards/sx1509.pdf): Bit Range | Level shifter mode for ----: | :---- 15:14 | IO[7] (Bank A) and IO[15] (Bank B) 13:12 | IO[6] (Bank A) and IO[14] (Bank B) 11:10 | IO[5] (Bank A) and IO[13] (Bank B) 9:8 | IO[4] (Bank A) and IO[12] (Bank B) 7:6 | IO[3] (Bank A) and IO[11] (Bank B) 5:4 | IO[2] (Bank A) and IO[10] (Bank B) 3:2 | IO[1] (Bank A) and IO[9] (Bank B) 1:0 | IO[0] (Bank A) and IO[8] (Bank B) """ defregister(:level_shifter, 0x1C, 2) end
lib/sx1509/registers/io.ex
0.695338
0.636932
io.ex
starcoder
defmodule Plymio.Funcio do @moduledoc ~S""" `Plymio.Funcio` is a collection of functions for various needs, especially enumerables, including mapping the elements concurrently in separate tasks. It was written as a support package for the `Plymio` and `Harnais` family of packages but all of the functions are general purpose. ## Documentation Terms In the documentation below these terms, usually in *italics*, are used to mean the same thing. ### *enum* An *enum* is an ernumerable e.g. `List`, `Map`, `Stream`, etc. ### *opts* and *opzioni* An *opts* is a `Keyword` list. An *opzioni* is a list of *opts*. ### *map/1* A *map/1* is *zero, one or more* arity 1 functions. Multiple functions are usually reduced (by `Plymio.Funcio.Map.Utility.reduce_map1_funs/1`) to create a composite function that runs the individual functions in an pipeline e.g. fn v -> funs |> Enum.reduce(v, fn f,v -> f.(v) end) end ### *index map/1* An *index map/1* is really the same as *map/1* but it is expected that the *first/only* function will be called with `{value, index}`. ### *predicate/1* A *predicate/1* is *one or more* arity 1 functions that each return either `true` or `false`. Multiple predicates are `AND`-ed together by `Plymio.Funcio.Predicate.reduce_and_predicate1_funs/1` to create a composite predicate e.g. fn v -> funs |> Enum.all?(fn f -> f.(v) end) end ### *index tuple predicate/1* A *index tuple predicate/1* is the same as *predicate/1* but it is expected the predeicate will be called with `{value, index}`. ## Standard Processing and Result Patterns Many functions return either `{:ok, any}` or `{:error, error}` where `error` will be an `Exception`. Peer bang functions return either `value` or raises `error`. There are three common function *patterns* described in `Plymio.Fontais`; many of the functions in this package implement those patterns. ## Streams Enumerables Some functions return `{:ok, enum}` where `enum` *may* be a `Stream`. A `Stream` will cause an `Exception` when used / realised (e.g. in `Enum.to_list/1`) if the original *enum* was invalid. """ use Plymio.Fontais.Attribute @type index :: integer @type indices :: [index] @type key :: atom @type keys :: [key] @type error :: struct @type stream :: %Stream{} @type result :: Plymio.Fontais.result() @type opts :: Plymio.Fontais.opts() @type opzioni :: Plymio.Fontais.opzioni() @type fun1_map :: (any -> any) @type fun1_predicate :: (any -> boolean) end
lib/funcio/funcio.ex
0.82887
0.685173
funcio.ex
starcoder
defmodule UnblockMeSolver.Move do alias UnblockMeSolver.Move @moduledoc false @doc """ Determines if the problem is solvable A problem is solvable when there are empty spaces to the right of the solution block ['A', 'A'] ## Examples iex> UnblockMeSolver.Move.solvable?([ ...> ['B', 'B', nil, nil, nil], ...> ['C', 'C', nil, nil, nil], ...> ['A', 'A', nil, nil, nil], ...> ['D', 'D', nil, nil, nil], ...> ['E', 'E', nil, nil, nil], ...>]) true """ def solvable?(problem) do problem |> Move.extract_solution_row() |> Enum.drop_while(fn x -> x != 'A' end) |> Enum.filter(fn x -> x != 'A' end) |> Enum.all?(fn x -> x == nil end) end @doc """ Determines if the problem is solved by checking if the solution block is on the right most column ## Examples iex> UnblockMeSolver.Move.solved?([['A', 'A']], 'A') true iex> UnblockMeSolver.Move.solved?([['A', 'A', nil]], 'A') false """ def solved?(problem, block) do problem |> Enum.find([], fn row -> Enum.any?(row, fn x -> x == block end) end) |> Enum.reverse |> Enum.at(0) == block end @doc """ Extracts the middle row from a problem ## Examples iex> UnblockMeSolver.Move.extract_solution_row([ ...> ['B', 'B', nil, nil, nil], ...> ['C', 'C', nil, nil, nil], ...> ['A', 'A', nil, nil, nil], ...> ['D', 'D', nil, nil, nil], ...> ['E', 'E', nil, nil, nil], ...>]) ['A', 'A', nil, nil, nil] """ def extract_solution_row(problem) do index = (length(problem) / 2) |> floor case Enum.fetch(problem, index) do {:ok, row} -> row _ -> [] end end @doc """ Moves a block in the directation and returns a tuple {blocked_block, updated_problem} of the block in the way (nil if no block is in the way) and the updated problem (assuming it was succesful) ## Examples iex> UnblockMeSolver.Move.with_next([ ...> ['C', 'C', nil], ...> ['A', 'A', nil], ...> ['D', 'D', nil], ...>], :right, 'A') {nil, [ ['C', 'C', nil], [nil, 'A', 'A'], ['D', 'D', nil], ]} iex> UnblockMeSolver.Move.with_next([ ...> ['A', 'A', 'B'], ...> [nil, nil, 'B'], ...> [nil, nil, nil], ...>], :right, 'A') {'B', [ ['A', 'A', 'B'], [nil, nil, 'B'], [nil, nil, nil], ]} """ def with_next(problem, direction, block) do case direction do :right -> Move.Helper.right_with_next(problem, block) :down -> Move.Helper.down_with_next(problem, block) :up -> Move.Helper.up_with_next(problem, block) :left -> Move.Helper.left_with_next(problem, block) _ -> raise "Can not move in the direction #{direction}" end end @doc """ Returns a the direction of the block in a problem I.e. :horizontal, :vertical. nil if otherwise ## Examples iex> UnblockMeSolver.Move.direction([[nil, 'A', 'A', nil]], 'A') :horizontal iex> UnblockMeSolver.Move.direction([[nil], ['A'], ['A'], [nil]], 'A') :vertical """ def direction(problem, block) do has_row? = fn row -> Enum.count(row, fn x -> x == block end) > 1 end cond do Enum.any?(problem, has_row?) -> :horizontal Enum.any?(Move.Helper.rotate_cw(problem), has_row?) -> :vertical true -> nil end end end
lib/unblock_me_solver/move.ex
0.855021
0.565329
move.ex
starcoder
defmodule TtrCore.Cards do @moduledoc """ Handles all card operations related to deck management and assigment to players. """ alias TtrCore.Cards.{ TicketCard, Tickets, TrainCard } alias TtrCore.Players alias TtrCore.Players.Player @type card :: TrainCard.t | TicketCard.t @doc """ Add trains to discard and returned updated discard pile. """ @spec add_trains_to_discard([TrainCard.t], [TrainCard.t]) :: [TrainCard.t] def add_trains_to_discard(discard, to_remove) do discard ++ to_remove end @doc """ Deals 4 train cards to multiple players. Used on initial deal. See `deal_trains/3` for details. """ @spec deal_initial_trains([TrainCard.t], Players.players()) :: {[TrainCard.t], Players.players()} def deal_initial_trains(train_deck, players) do Enum.reduce(players, {train_deck, %{}}, fn {id, player}, {deck, acc} -> {:ok, remainder, player} = deal_trains(deck, player, 4) {remainder, Map.put(acc, id, player)} end) end @doc """ Deals 3 tickets to each player. It returns the remaining tickets and the modified players as a tuple. """ @spec deal_tickets([TicketCard.t], Players.players()) :: {[TicketCard.t], Players.players()} def deal_tickets(ticket_deck, players) do Enum.reduce(players, {ticket_deck, %{}}, fn {id, player}, {deck, acc} -> {remainder, player} = draw_tickets(deck, player) {remainder, Map.put(acc, id, player)} end) end @doc """ Deals train cards to a player. Can deal 1, 2 or 4 (on initial deal) cards. It returns the remaining train cards and the modified player. If you specify another number outside 1, 2 or 4, then an `{:error, :invalid_draw}` tuple is returned. """ @spec deal_trains([TrainCard.t], Player.t, integer()) :: {:ok, TrainCard.deck(), Player.t} | {:error, :invalid_deal} def deal_trains(deck, player, count) do case TrainCard.draw(deck, count) do {:ok, {trains, new_deck}} -> {:ok, new_deck, Players.add_trains(player, trains)} error -> error end end @doc """ Draws 3 tickets cards for a player and adds them to a selection buffer. It returns the remaining tickets and the modified player as a tuple. """ @spec draw_tickets([TicketCard.t], Player.t) :: {[TicketCard.t], Player.t} def draw_tickets(deck, player) do {tickets, new_deck} = TicketCard.draw(deck) updated_player = Players.add_tickets_to_buffer(player, tickets) {new_deck, updated_player} end @doc """ Draw trains for a particular player and adds them to a selection buffer. This also checks to see if player has selected cards from the train display in order not to overdraw. You may ask for up to 2 cards. If more is asked, the player will only get up to the max (including currently selected trains from the display deck). """ @spec draw_trains([TrainDeck.t], Player.t, integer()) :: {[TrainDeck.t], Player.t} def draw_trains(deck, %{trains_selected: selected} = player, count) do real_count = min(count, max(0, 2 - selected)) {:ok, {trains, new_deck}} = TrainCard.draw(deck, real_count) {new_deck, Players.add_trains_on_turn(player, trains)} end @doc """ Checks to see if a set of cards (`deck2`) are a subset of another (`deck1`). """ @spec has_cards?([card()], [card()]) :: boolean() def has_cards?(deck1, deck2) do set1 = MapSet.new(deck2) set2 = MapSet.new(deck1) MapSet.subset?(set1, set2) end @doc """ Return tickets from a selection to the bottom of the deck of tickets """ @spec return_tickets([TicketCard.t], [TicketCard.t]) :: [TicketCard.t] def return_tickets(ticket_deck, to_return) do ticket_deck ++ to_return end @doc """ Removes a set of trains from the displayed set. """ @spec remove_from_display([TrainCard.t], [TrainCard.t]) :: [TrainCard.t] def remove_from_display(displayed, selections) do displayed -- selections end @doc """ Replenish display with train cards (up to 5). Returns a tuple of `{display, train_deck}` where `display` and `train_deck` are both a list of `TrainCard`. """ @spec replenish_display([TrainCard.t], [TrainCard.t]) :: {[TrainCard.t], [TrainCard.t]} def replenish_display(displayed, deck) do {additions, new_deck} = Enum.split(deck, 5 - Enum.count(displayed)) {displayed ++ additions, new_deck} end @doc """ Returns a new list of train cards all shuffled. """ @spec shuffle_trains() :: [TrainCard.t] def shuffle_trains do TrainCard.shuffle() end @doc """ Returns a new list of ticket cards all shuffled. """ @spec shuffle_tickets() :: [TicketCard.t] def shuffle_tickets do Tickets.get_tickets() |> Enum.shuffle() end end
lib/ttr_core/cards.ex
0.860237
0.530054
cards.ex
starcoder
defmodule Geo.WKB.Encoder do @moduledoc false use Bitwise alias Geo.{ Point, PointZ, PointM, PointZM, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon, GeometryCollection, Utils } alias Geo.WKB.Writer @doc """ Takes a Geometry and returns a WKB string. The endian decides what the byte order will be """ @spec encode(binary, Geo.endian()) :: {:ok, binary} | {:error, Exception.t()} def encode(geom, endian \\ :xdr) do {:ok, encode!(geom, endian)} rescue exception -> {:error, exception} end @doc """ Takes a Geometry and returns a WKB string. The endian decides what the byte order will be """ @spec encode!(binary, Geo.endian()) :: binary | no_return def encode!(geom, endian \\ :xdr) do writer = Writer.new(endian) do_encode(geom, writer) end defp do_encode(%GeometryCollection{} = geom, writer) do type = Utils.type_to_hex(geom, geom.srid != nil) |> Integer.to_string(16) |> Utils.pad_left(8) srid = if geom.srid, do: Integer.to_string(geom.srid, 16) |> Utils.pad_left(8), else: "" count = Integer.to_string(Enum.count(geom.geometries), 16) |> Utils.pad_left(8) writer = Writer.write(writer, type) writer = Writer.write(writer, srid) writer = Writer.write(writer, count) coordinates = Enum.map(geom.geometries, fn x -> x = %{x | srid: nil} encode!(x, writer.endian) end) coordinates = Enum.join(coordinates) writer.wkb <> coordinates end defp do_encode(geom, writer) do type = Utils.type_to_hex(geom, geom.srid != nil) |> Integer.to_string(16) |> Utils.pad_left(8) srid = if geom.srid, do: Integer.to_string(geom.srid, 16) |> Utils.pad_left(8), else: "" writer = Writer.write(writer, type) writer = Writer.write(writer, srid) writer = encode_coordinates(writer, geom) writer.wkb end defp encode_coordinates(writer, %Point{coordinates: {0, 0}}) do Writer.write(writer, Utils.repeat("0", 32)) end defp encode_coordinates(writer, %Point{coordinates: {x, y}}) do x = x |> Utils.float_to_hex(64) |> Integer.to_string(16) y = y |> Utils.float_to_hex(64) |> Integer.to_string(16) writer = Writer.write(writer, x) Writer.write(writer, y) end defp encode_coordinates(writer, %PointZ{coordinates: {x, y, z}}) do x = x |> Utils.float_to_hex(64) |> Integer.to_string(16) y = y |> Utils.float_to_hex(64) |> Integer.to_string(16) z = z |> Utils.float_to_hex(64) |> Integer.to_string(16) writer |> Writer.write(x) |> Writer.write(y) |> Writer.write(z) end defp encode_coordinates(writer, %PointM{coordinates: {x, y, m}}) do x = x |> Utils.float_to_hex(64) |> Integer.to_string(16) y = y |> Utils.float_to_hex(64) |> Integer.to_string(16) m = m |> Utils.float_to_hex(64) |> Integer.to_string(16) writer |> Writer.write(x) |> Writer.write(y) |> Writer.write(m) end defp encode_coordinates(writer, %PointZM{coordinates: {x, y, z, m}}) do x = x |> Utils.float_to_hex(64) |> Integer.to_string(16) y = y |> Utils.float_to_hex(64) |> Integer.to_string(16) z = z |> Utils.float_to_hex(64) |> Integer.to_string(16) m = m |> Utils.float_to_hex(64) |> Integer.to_string(16) writer |> Writer.write(x) |> Writer.write(y) |> Writer.write(z) |> Writer.write(m) end defp encode_coordinates(writer, %LineString{coordinates: coordinates}) do number_of_points = Integer.to_string(length(coordinates), 16) |> Utils.pad_left(8) writer = Writer.write(writer, number_of_points) {_nils, writer} = Enum.map_reduce(coordinates, writer, fn pair, acc -> acc = encode_coordinates(acc, %Point{coordinates: pair}) {nil, acc} end) writer end defp encode_coordinates(writer, %Polygon{coordinates: coordinates}) do number_of_lines = Integer.to_string(length(coordinates), 16) |> Utils.pad_left(8) writer = Writer.write(writer, number_of_lines) {_nils, writer} = Enum.map_reduce(coordinates, writer, fn line, acc -> acc = encode_coordinates(acc, %LineString{coordinates: line}) {nil, acc} end) writer end defp encode_coordinates(writer, %MultiPoint{coordinates: coordinates}) do writer = Writer.write(writer, Integer.to_string(length(coordinates), 16) |> Utils.pad_left(8)) geoms = Enum.map(coordinates, fn geom -> encode!(%Point{coordinates: geom}, writer.endian) end) |> Enum.join() Writer.write_no_endian(writer, geoms) end defp encode_coordinates(writer, %MultiLineString{coordinates: coordinates}) do writer = Writer.write(writer, Integer.to_string(length(coordinates), 16) |> Utils.pad_left(8)) geoms = Enum.map(coordinates, fn geom -> encode!(%LineString{coordinates: geom}, writer.endian) end) |> Enum.join() Writer.write_no_endian(writer, geoms) end defp encode_coordinates(writer, %MultiPolygon{coordinates: coordinates}) do writer = Writer.write(writer, Integer.to_string(length(coordinates), 16) |> Utils.pad_left(8)) geoms = Enum.map(coordinates, fn geom -> encode!(%Polygon{coordinates: geom}, writer.endian) end) |> Enum.join() Writer.write_no_endian(writer, geoms) end end
lib/geo/wkb/encoder.ex
0.870865
0.644309
encoder.ex
starcoder
defmodule Plug.Telemetry.ServerTiming do @behaviour Plug @external_resource "README.md" @moduledoc File.read!("README.md") |> String.split(~r/<!--\s*(BEGIN|END)\s*-->/, parts: 3) |> Enum.at(1) import Plug.Conn @impl true @doc false def init(opts), do: opts @impl true @doc false def call(conn, _opts) do enabled = Application.fetch_env!(:plug_telemetry_server_timing, :enabled) if enabled do start = System.monotonic_time(:millisecond) Process.put(__MODULE__, {enabled, []}) register_before_send(conn, &timings(&1, start)) else conn end end @type events() :: [event()] @type event() :: {:telemetry.event_name(), measurement :: atom()} | {:telemetry.event_name(), measurement :: atom(), opts :: keyword() | map()} @doc """ Define which events should be available within response headers. Tuple values are: 1. List of atoms that is the name of the event that we should listen for. 2. Atom that contains the name of the metric that should be recorded. 3. Optionally keyword list or map with additional options. Currently supported options are: - `:name` - alternative name for the metric. By default it will be constructed by joining event name and name of metric with dots. Ex. for `{[:foo, :bar], :baz}` default metric name will be `foo.bar.baz`. - `:description` - string that will be set as `desc`. ## Example ```elixir #{inspect(__MODULE__)}.install([ {[:phoenix, :endpoint, :stop], :duration, description: "Phoenix time"}, {[:my_app, :repo, :query], :total_time, description: "DB request"} ]) ``` """ @spec install(events()) :: :ok def install(events) do for event <- events, {metric_name, metric, opts} = normalise(event) do name = Map.get_lazy(opts, :name, fn -> "#{Enum.join(metric_name, ".")}.#{metric}" end) description = Map.get(opts, :description, "") :ok = :telemetry.attach( {__MODULE__, name}, metric_name, &__MODULE__.__handle__/4, {metric, %{name: name, desc: description}} ) end :ok end defp normalise({name, metric}), do: {name, metric, %{}} defp normalise({name, metric, opts}) when is_map(opts), do: {name, metric, opts} defp normalise({name, metric, opts}) when is_list(opts), do: {name, metric, Map.new(opts)} @doc false def __handle__(_metric_name, measurements, _metadata, {metric, opts}) do with {true, data} <- Process.get(__MODULE__), %{^metric => duration} <- measurements do current = System.monotonic_time(:millisecond) Process.put( __MODULE__, {true, [{duration, current, opts} | data]} ) end :ok end defp timings(conn, start) do case Process.get(__MODULE__) do {true, measurements} -> value = measurements |> Enum.reverse() |> Enum.map_join(",", &encode(&1, start)) put_resp_header(conn, "server-timing", value) _ -> conn end end defp encode({measurement, timestamp, opts}, start) do %{desc: desc, name: name} = opts data = [ {"dur", System.convert_time_unit(measurement, :native, :millisecond)}, {"total", System.convert_time_unit(timestamp - start, :native, :millisecond)}, {"desc", desc} ] IO.iodata_to_binary([name, ?; | build(data)]) end defp build([]), do: [] defp build([{_name, nil} | rest]), do: build(rest) defp build([{name, value}]), do: [name, ?=, to_string(value)] defp build([{name, value} | rest]), do: [name, ?=, to_string(value), ?; | build(rest)] end
lib/plug_telemetry_server_timing.ex
0.893132
0.496277
plug_telemetry_server_timing.ex
starcoder
defmodule Scrivener.HTML do use Phoenix.HTML @defaults [view_style: :bootstrap, action: :index, page_param: :page] @view_styles [:bootstrap, :semantic, :foundation, :bootstrap_v4, :materialize, :bulma] @raw_defaults [distance: 5, next: ">>", previous: "<<", first: true, last: true, ellipsis: raw("&hellip;")] @moduledoc """ For use with Phoenix.HTML, configure the `:routes_helper` module like the following: config :scrivener_html, routes_helper: MyApp.Router.Helpers Import to you view. defmodule MyApp.UserView do use MyApp.Web, :view use Scrivener.HTML end Use in your template. <%= pagination_links @conn, @page %> Where `@page` is a `%Scrivener.Page{}` struct returned from `Repo.paginate/2`. Customize output. Below are the defaults. <%= pagination_links @conn, @page, distance: 5, next: ">>", previous: "<<", first: true, last: true %> See `Scrivener.HTML.raw_pagination_links/2` for option descriptions. For custom HTML output, see `Scrivener.HTML.raw_pagination_links/2`. For SEO related functions, see `Scrivener.HTML.SEO` (these are automatically imported). """ @doc false defmacro __using__(_) do quote do import Scrivener.HTML import Scrivener.HTML.SEO end end defmodule Default do @doc ~S""" Default path function when none provided. Used when automatic path function resolution cannot be performed. iex> Scrivener.HTML.Default.path(%Plug.Conn{}, :index, page: 4) "?page=4" """ def path(_conn, _action, opts \\ []) do ("?" <> Plug.Conn.Query.encode(opts)) end end @doc ~S""" Generates the HTML pagination links for a given paginator returned by Scrivener. The default options are: #{inspect @defaults} The `view_style` indicates which CSS framework you are using. The default is `:bootstrap`, but you can add your own using the `Scrivener.HTML.raw_pagination_links/2` function if desired. The full list of available `view_style`s is here: #{inspect @view_styles} An example of the output data: iex> Scrivener.HTML.pagination_links(%Scrivener.Page{total_pages: 10, page_number: 5}) |> Phoenix.HTML.safe_to_string() "<nav><ul class=\"pagination\"><li class=\"\"><a class=\"\" href=\"?page=4\" rel=\"prev\">&lt;&lt;</a></li><li class=\"\"><a class=\"\" href=\"?page=1\" rel=\"canonical\">1</a></li><li class=\"\"><a class=\"\" href=\"?page=2\" rel=\"canonical\">2</a></li><li class=\"\"><a class=\"\" href=\"?page=3\" rel=\"canonical\">3</a></li><li class=\"\"><a class=\"\" href=\"?page=4\" rel=\"prev\">4</a></li><li class=\"active\"><a class=\"\">5</a></li><li class=\"\"><a class=\"\" href=\"?page=6\" rel=\"next\">6</a></li><li class=\"\"><a class=\"\" href=\"?page=7\" rel=\"canonical\">7</a></li><li class=\"\"><a class=\"\" href=\"?page=8\" rel=\"canonical\">8</a></li><li class=\"\"><a class=\"\" href=\"?page=9\" rel=\"canonical\">9</a></li><li class=\"\"><a class=\"\" href=\"?page=10\" rel=\"canonical\">10</a></li><li class=\"\"><a class=\"\" href=\"?page=6\" rel=\"next\">&gt;&gt;</a></li></ul></nav>" In order to generate links with nested objects (such as a list of comments for a given post) it is necessary to pass those arguments. All arguments in the `args` parameter will be directly passed to the path helper function. Everything within `opts` which are not options will passed as `params` to the path helper function. For example, `@post`, which has an index of paginated `@comments` would look like the following: Scrivener.HTML.pagination_links(@conn, @comments, [@post], view_style: :bootstrap, my_param: "foo") You'll need to be sure to configure `:scrivener_html` with the `:routes_helper` module (ex. MyApp.Routes.Helpers) in Phoenix. With that configured, the above would generate calls to the `post_comment_path(@conn, :index, @post.id, my_param: "foo", page: page)` for each page link. In times that it is necessary to override the automatic path function resolution, you may supply the correct path function to use by adding an extra key in the `opts` parameter of `:path`. For example: Scrivener.HTML.pagination_links(@conn, @comments, [@post], path: &post_comment_path/4) Be sure to supply the function which accepts query string parameters (starts at arity 3, +1 for each relation), because the `page` parameter will always be supplied. If you supply the wrong function you will receive a function undefined exception. """ def pagination_links(conn, paginator, args, opts) do opts = Keyword.merge opts, view_style: opts[:view_style] || Application.get_env(:scrivener_html, :view_style, :bootstrap) merged_opts = Keyword.merge @defaults, opts path = opts[:path] || find_path_fn(conn && paginator.entries, args) params = Keyword.drop opts, (Keyword.keys(@defaults) ++ [:path]) # Ensure ordering so pattern matching is reliable _pagination_links paginator, view_style: merged_opts[:view_style], path: path, args: [conn, merged_opts[:action]] ++ args, page_param: merged_opts[:page_param], params: params end def pagination_links(%Scrivener.Page{} = paginator), do: pagination_links(nil, paginator, [], []) def pagination_links(%Scrivener.Page{} = paginator, opts), do: pagination_links(nil, paginator, [], opts) def pagination_links(conn, %Scrivener.Page{} = paginator), do: pagination_links(conn, paginator, [], []) def pagination_links(conn, paginator, [{_, _} | _] = opts), do: pagination_links(conn, paginator, [], opts) def pagination_links(conn, paginator, [_ | _] = args), do: pagination_links(conn, paginator, args, []) def find_path_fn(nil, _path_args), do: &Default.path/3 def find_path_fn([], _path_args), do: fn _, _, _ -> nil end # Define a different version of `find_path_fn` whenever Phoenix is available. if Code.ensure_loaded(Phoenix.Naming) do def find_path_fn(entries, path_args) do routes_helper_module = Application.get_env(:scrivener_html, :routes_helper) || raise("Scrivener.HTML: Unable to find configured routes_helper module (ex. MyApp.Router.Helper)") path = (path_args) |> Enum.reduce(name_for(List.first(entries), ""), &name_for/2) {path_fn, []} = Code.eval_quoted(quote do: &unquote(routes_helper_module).unquote(:"#{path <> "_path"}")/unquote(length(path_args) + 3)) path_fn end else def find_path_fn(_entries, _args), do: &Default/3 end defp name_for(model, acc) do "#{acc}#{if(acc != "", do: "_")}#{Phoenix.Naming.resource_name(model.__struct__)}" end defp _pagination_links(_paginator, [view_style: style, path: _path, args: _args, page_param: _page_param, params: _params]) when not style in @view_styles do raise "Scrivener.HTML: View style #{inspect style} is not a valid view style. Please use one of #{inspect @view_styles}" end # Bootstrap implementation defp _pagination_links(paginator, [view_style: :bootstrap, path: path, args: args, page_param: page_param, params: params]) do url_params = Keyword.drop params, Keyword.keys(@raw_defaults) content_tag :nav do content_tag :ul, class: "pagination" do raw_pagination_links(paginator, params) |> Enum.map(&page(&1, url_params, args, page_param, path, paginator, :bootstrap)) end end end # Bootstrap implementation defp _pagination_links(paginator, [view_style: :bootstrap_v4, path: path, args: args, page_param: page_param, params: params]) do url_params = Keyword.drop params, Keyword.keys(@raw_defaults) content_tag :nav, "aria-label": "Page navigation" do content_tag :ul, class: "pagination" do raw_pagination_links(paginator, params) |> Enum.map(&page(&1, url_params, args, page_param, path, paginator, :bootstrap_v4)) end end end # Semantic UI implementation defp _pagination_links(paginator, [view_style: :semantic, path: path, args: args, page_param: page_param, params: params]) do url_params = Keyword.drop params, Keyword.keys(@raw_defaults) content_tag :div, class: "ui pagination menu" do raw_pagination_links(paginator, params) |> Enum.map(&page(&1, url_params, args, page_param, path, paginator, :semantic)) end end # Foundation for Sites 6.x implementation defp _pagination_links(paginator, [view_style: :foundation, path: path, args: args, page_param: page_param, params: params]) do url_params = Keyword.drop params, Keyword.keys(@raw_defaults) content_tag :ul, class: "pagination", role: "pagination" do raw_pagination_links(paginator, params) |> Enum.map(&page(&1, url_params, args, page_param, path, paginator, :foundation)) end end # Materialized implementation defp _pagination_links(paginator, [view_style: :materialize, path: path, args: args, page_param: page_param, params: params]) do url_params = Keyword.drop params, Keyword.keys(@raw_defaults) content_tag :ul, class: "pagination" do raw_pagination_links(paginator, params) |> Enum.map(&page(&1, url_params, args, page_param, path, paginator, :materialize)) end end # Bulma implementation defp _pagination_links(paginator, [view_style: :bulma, path: path, args: args, page_param: page_param, params: params]) do url_params = Keyword.drop params, Keyword.keys(@raw_defaults) content_tag :nav, class: "pagination is-centered" do content_tag :ul, class: "pagination-list" do raw_pagination_links(paginator, params) |> Enum.map(&page(&1, url_params, args, page_param, path, paginator, :bulma)) end end end defp page({:ellipsis, true}, url_params, args, page_param, path, paginator, :foundation) do page({:ellipsis, ""}, url_params, args, page_param, path, paginator, :foundation) end defp page({:ellipsis, true}, url_params, args, page_param, path, paginator, style) do page({:ellipsis, unquote(@raw_defaults[:ellipsis])}, url_params, args, page_param, path, paginator, style) end defp page({:ellipsis, text}, _url_params, _args, _page_param, _path, paginator, :semantic) do content_tag(:div, safe(text), class: link_classes_for_style(paginator, :ellipsis, :semantic) |> Enum.join(" ")) end defp page({:ellipsis, text}, _url_params, _args, _page_param, _path, paginator, style) do content_tag(:li, class: li_classes_for_style(paginator, :ellipsis, style) |> Enum.join(" ")) do style |> ellipsis_tag |> content_tag(safe(text), class: link_classes_for_style(paginator, :ellipsis, style) |> Enum.join(" ")) end end defp page({text, page_number}, url_params, args, page_param, path, paginator, :semantic) do params_with_page = url_params ++ [{page_param, page_number}] to = apply(path, args ++ [params_with_page]) if to do if active_page?(paginator, page_number) do content_tag(:a, safe(text), class: li_classes_for_style(paginator, page_number, :semantic) |> Enum.join(" ")) else link(safe(text), to: to, rel: Scrivener.HTML.SEO.rel(paginator, page_number), class: li_classes_for_style(paginator, page_number, :semantic) |> Enum.join(" ")) end else content_tag :a, safe(text), class: li_classes_for_style(paginator, page_number, :semantic) |> Enum.join(" ") end end defp page({text, page_number}, url_params, args, page_param, path, paginator, style) do params_with_page = url_params ++ [{page_param, page_number}] content_tag :li, class: li_classes_for_style(paginator, page_number, style) |> Enum.join(" ") do to = apply(path, args ++ [params_with_page]) if to do if active_page?(paginator, page_number) do content_tag(:a, safe(text), class: link_classes_for_style(paginator, page_number, style) |> Enum.join(" ")) else link(safe(text), to: to, rel: Scrivener.HTML.SEO.rel(paginator, page_number), class: link_classes_for_style(paginator, page_number, style) |> Enum.join(" ")) end else style |> blank_link_tag() |> content_tag(safe(text), class: link_classes_for_style(paginator, page_number, style) |> Enum.join(" ")) end end end defp active_page?(%{page_number: page_number}, page_number), do: true defp active_page?(_paginator, _page_number), do: false defp li_classes_for_style(_paginator, :ellipsis, :bootstrap), do: [] defp li_classes_for_style(paginator, page_number, :bootstrap) do if(paginator.page_number == page_number, do: ["active"], else: []) end defp li_classes_for_style(_paginator, :ellipsis, :bootstrap_v4), do: ["page-item"] defp li_classes_for_style(paginator, page_number, :bootstrap_v4) do if(paginator.page_number == page_number, do: ["active", "page-item"], else: ["page-item"]) end defp li_classes_for_style(_paginator, :ellipsis, :foundation), do: ["ellipsis"] defp li_classes_for_style(paginator, page_number, :foundation) do if(paginator.page_number == page_number, do: ["current"], else: []) end defp li_classes_for_style(_paginator, :ellipsis, :semantic), do: ["ellipsis"] defp li_classes_for_style(paginator, page_number, :semantic) do if(paginator.page_number == page_number, do: ["active", "item"], else: ["item"]) end defp li_classes_for_style(_paginator, :ellipsis, :materialize), do: [] defp li_classes_for_style(paginator, page_number, :materialize) do if(paginator.page_number == page_number, do: ["active"], else: ["waves-effect"]) end defp li_classes_for_style(_paginator, :ellipsis, :bulma), do: [] defp li_classes_for_style(_paginator, _page_number, :bulma), do: [] defp link_classes_for_style(_paginator, _page_number, :bootstrap), do: [] defp link_classes_for_style(_paginator, _page_number, :bootstrap_v4), do: ["page-link"] defp link_classes_for_style(_paginator, _page_number, :foundation), do: [] defp link_classes_for_style(_paginator, _page_number, :materialize), do: [] defp link_classes_for_style(paginator, page_number, :bulma) do if(paginator.page_number == page_number, do: ["pagination-link", "is-current"], else: ["pagination-link"]) end defp link_classes_for_style(_paginator, :ellipsis, :semantic), do: ["disabled", "item"] defp link_classes_for_style(_paginator, :ellipsis, :materialize), do: [] defp link_classes_for_style(_paginator, :ellipsis, :bulma), do: ["pagination-ellipsis"] defp ellipsis_tag(:semantic), do: :div defp ellipsis_tag(_), do: :span defp blank_link_tag(:foundation), do: :span defp blank_link_tag(_), do: :a @doc """ Returns the raw data in order to generate the proper HTML for pagination links. Data is returned in a `{text, page_number}` format where `text` is intended to be the text of the link and `page_number` is the page it should go to. Defaults are already supplied and they are as follows: #{inspect @raw_defaults} `distance` must be a positive non-zero integer or an exception is raised. `next` and `previous` should be strings but can be anything you want as long as it is truthy, falsey values will remove them from the output. `first` and `last` are only booleans, and they just include/remove their respective link from output. An example of the data returned: iex> Scrivener.HTML.raw_pagination_links(%{total_pages: 10, page_number: 5}) [{"<<", 4}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}, {7, 7}, {8, 8}, {9, 9}, {10, 10}, {">>", 6}] iex> Scrivener.HTML.raw_pagination_links(%{total_pages: 20, page_number: 10}, first: ["←"], last: ["→"]) [{"<<", 9}, {["←"], 1}, {:ellipsis, {:safe, "&hellip;"}}, {5, 5}, {6, 6},{7, 7}, {8, 8}, {9, 9}, {10, 10}, {11, 11}, {12, 12}, {13, 13}, {14, 14},{15, 15}, {:ellipsis, {:safe, "&hellip;"}}, {["→"], 20}, {">>", 11}] Simply loop and pattern match over each item and transform it to your custom HTML. """ def raw_pagination_links(paginator, options \\ []) do options = Keyword.merge @raw_defaults, options add_first(paginator.page_number, options[:distance], options[:first]) |> add_first_ellipsis(paginator.page_number, paginator.total_pages, options[:distance], options[:first]) |> add_previous(paginator.page_number) |> page_number_list(paginator.page_number, paginator.total_pages, options[:distance]) |> add_last_ellipsis(paginator.page_number, paginator.total_pages, options[:distance], options[:last]) |> add_last(paginator.page_number, paginator.total_pages, options[:distance], options[:last]) |> add_next(paginator.page_number, paginator.total_pages) |> Enum.map(fn :next -> if options[:next], do: {options[:next], paginator.page_number + 1} :previous -> if options[:previous], do: {options[:previous], paginator.page_number - 1} :first_ellipsis -> if options[:ellipsis] && options[:first], do: {:ellipsis, options[:ellipsis]} :last_ellipsis -> if options[:ellipsis] && options[:last], do: {:ellipsis, options[:ellipsis]} :first -> if options[:first], do: {options[:first], 1} :last -> if options[:last], do: {options[:last], paginator.total_pages} num when is_number(num) -> {num, num} end) |> Enum.filter(&(&1)) end # Computing page number ranges defp page_number_list(list, page, total, distance) when is_integer(distance) and distance >= 1 do list ++ Enum.to_list(beginning_distance(page, total, distance)..end_distance(page, total, distance)) end defp page_number_list(_list, _page, _total, _distance) do raise "Scrivener.HTML: Distance cannot be less than one." end # Beginning distance computation # For low page numbers defp beginning_distance(page, _total, distance) when page - distance < 1 do page - (distance + (page - distance - 1)) end # For medium to high end page numbers defp beginning_distance(page, total, distance) when page <= total do page - distance end # For page numbers over the total number of pages (prevent DOS attack generating too many pages) defp beginning_distance(page, total, distance) when page > total do total - distance end # End distance computation # For high end page numbers (prevent DOS attack generating too many pages) defp end_distance(page, total, distance) when page + distance >= total and total != 0 do total end # For when there is no pages, cannot trust page number because it is supplied by user potentially (prevent DOS attack) defp end_distance(_page, 0, _distance) do 1 end # For low to mid range page numbers (guard here to ensure crash if something goes wrong) defp end_distance(page, total, distance) when page + distance < total do page + distance end # Adding next/prev/first/last links defp add_previous(list, page) when page != 1 do [:previous | list] end defp add_previous(list, _page) do list end defp add_first(page, distance, true) when page - distance > 1 do [1] end defp add_first(page, distance, first) when page - distance > 1 and first != false do [:first] end defp add_first(_page, _distance, _included) do [] end defp add_last(list, page, total, distance, true) when page + distance < total do list ++ [total] end defp add_last(list, page, total, distance, last) when page + distance < total and last != false do list ++ [:last] end defp add_last(list, _page, _total, _distance, _included) do list end defp add_next(list, page, total) when page != total and page < total do list ++ [:next] end defp add_next(list, _page, _total) do list end defp add_first_ellipsis(list, page, total, distance, true) do add_first_ellipsis(list, page,total, distance + 1, nil) end defp add_first_ellipsis(list, page, _total, distance, _first) when page - distance > 1 and page > 1 do list ++ [:first_ellipsis] end defp add_first_ellipsis(list, _page_number, _total, _distance, _first) do list end defp add_last_ellipsis(list, page, total, distance, true) do add_last_ellipsis(list, page, total, distance + 1, nil) end defp add_last_ellipsis(list, page, total, distance, _) when page + distance < total and page != total do list ++ [:last_ellipsis] end defp add_last_ellipsis(list, _page_number, _total, _distance, _last) do list end defp safe({:safe, _string} = whole_string) do whole_string end defp safe(string) when is_binary(string) do string end defp safe(string) do string |> to_string() |> raw() end def defaults(), do: @defaults end
lib/scrivener/html.ex
0.736116
0.40251
html.ex
starcoder
defmodule Cldr.Number.Format.Meta do @moduledoc """ Describes the metadata that drives number formatting and provides functions to update the struct. ## Format definition The `:format` is a keyword list that with two elements: * `:positive` which is a keyword list for formatting a number >= zero * `:negative` which is a keyword list for formatting negtive number There are two formats because we can format in an accounting style (that is, numbers surrounded by `()`) or any other arbitrary style. Typically the format for a negative number is the same as that for a positive number with a prepended minus sign. ## Localisation of number formatting Number formatting is always localised to either the currency processes locale or a locale provided as an option to `Cldr.Number.to_string/3`. The metadata is independent of the localisation process. Signs (`+`/`-`), grouping (`,`), decimal markers (`.`) and exponent signs are all localised when the number is formatted. ## Formatting directives The formats - positive and negative - are defined in the metadata struct, as a keyword list of keywords and values. The simplest formatting list might be: ``` [format: _]` ``` The `:format` keyword indicates that this is where the formatting number will be substituted into the format pattern. Another example would be for formatting a negative number: ``` [minus: _, format: _] ``` which will format with a localised minus sign followed by the formatted number. Note that the keyword value for `:minus` and `:format` are ignored. ## List of formatting keywords The following is the full list of formatting keywords which can be used to format a number. A `_` in the keyword format is used to denote `:dont_care`. * `[format: _]` inserts the formatted number exclusive of any sign * `[minus: _]` inserts a localised minus sign * `[plus: _]` inserts a localised plus sign * `[percent: _]` inserts a localised percent sign * `[permille: _]` inserts a localised permille sign * `[literal: "string"]` inserts `string` into the format without any processing * `[currency: 1..4]` inserts a localised currency symbol of the given `type`. A `:currency` must be provided as an option to `Cldr.Number.Formatter.Decimal.to_string/3`. * `[pad: "char"]` inserts the correct number of `char`s to pad the number format to the width specified by `:padding_length` in the `%Meta{}` struct. The `:pad` can be anywhere in the format list but it is most typically inserted before or after the `:format` keyword. The assumption is tha the `char` is a single binary character but this is not checked. ## Currency symbol formatting Currency are localised and have four ways of being presented. The different types are defined in the `[currency: type]` keyword where `type` is an integer in the range `1..4` These types will insert into the final format: 1. The standard currency symbol like `$`,`¥` or `€` 2. The ISO currency code (like `USD` and `JPY`) 3. The localised and pluralised currency display name like "Australian dollar" or "Australian dollars" 4. The narrow currency symbol if defined for a locale """ defstruct integer_digits: %{max: 0, min: 1}, fractional_digits: %{max: 0, min: 0}, significant_digits: %{max: 0, min: 0}, exponent_digits: 0, exponent_sign: false, scientific_rounding: 0, grouping: %{ fraction: %{first: 0, rest: 0}, integer: %{first: 0, rest: 0} }, round_nearest: 0, padding_length: 0, padding_char: " ", multiplier: 1, format: [ positive: [format: "#"], negative: [minus: '-', format: :same_as_positive] ], number: 0 @typedoc "Metadata type that drives how to format a number" @type t :: %__MODULE__{} @doc """ Returns a new number formatting metadata struct. """ @spec new :: t() def new do %__MODULE__{} end @doc """ Set the minimum, and optionally maximum, integer digits to format. """ @spec put_integer_digits(t(), non_neg_integer, non_neg_integer) :: t() def put_integer_digits(%__MODULE__{} = meta, min, max \\ 0) when is_integer(min) and is_integer(max) do meta |> Map.put(:integer_digits, %{min: min, max: max}) end @doc """ Set the minimum, and optionally maximum, fractional digits to format. """ @spec put_fraction_digits(t(), non_neg_integer, non_neg_integer) :: t() def put_fraction_digits(%__MODULE__{} = meta, min, max \\ 0) when is_integer(min) and is_integer(max) do meta |> Map.put(:fractional_digits, %{min: min, max: max}) end @doc """ Set the minimum, and optionally maximum, significant digits to format. """ @spec put_significant_digits(t(), non_neg_integer, non_neg_integer) :: t() def put_significant_digits(%__MODULE__{} = meta, min, max \\ 0) when is_integer(min) and is_integer(max) do meta |> Map.put(:significant_digits, %{min: min, max: max}) end @doc """ Set the number of exponent digits to format. """ @spec put_exponent_digits(t(), non_neg_integer) :: t() def put_exponent_digits(%__MODULE__{} = meta, digits) when is_integer(digits) do meta |> Map.put(:exponent_digits, digits) end @doc """ Set whether to add the sign of the exponent to the format. """ @spec put_exponent_sign(t(), boolean) :: t() def put_exponent_sign(%__MODULE__{} = meta, flag) when is_boolean(flag) do meta |> Map.put(:exponent_sign, flag) end @doc """ Set the increment to which the number should be rounded. """ @spec put_round_nearest_digits(t(), non_neg_integer) :: t() def put_round_nearest_digits(%__MODULE__{} = meta, digits) when is_integer(digits) do meta |> Map.put(:round_nearest, digits) end @doc """ Set the number of scientific digits to which the number should be rounded. """ @spec put_scientific_rounding_digits(t(), non_neg_integer) :: t() def put_scientific_rounding_digits(%__MODULE__{} = meta, digits) when is_integer(digits) do meta |> Map.put(:scientific_rounding, digits) end @spec put_padding_length(t(), non_neg_integer) :: t() def put_padding_length(%__MODULE__{} = meta, digits) when is_integer(digits) do meta |> Map.put(:padding_length, digits) end @doc """ Set the padding character to be used when padding the formatted number. """ @spec put_padding_char(t(), String.t()) :: t() def put_padding_char(%__MODULE__{} = meta, char) when is_binary(char) do meta |> Map.put(:padding_char, char) end @doc """ Sets the multiplier for the number. Before formatting, the number is multiplied by this amount. This is useful when formatting as a percent or permille. """ @spec put_multiplier(t(), non_neg_integer) :: t() def put_multiplier(%__MODULE__{} = meta, multiplier) when is_integer(multiplier) do meta |> Map.put(:multiplier, multiplier) end @doc """ Sets the number of digits in a group or optionally the first group and subsequent groups for the integer part of a number. The grouping character is defined by the locale defined for the current process or supplied as the `:locale` option to `to_string/3`. """ @spec put_integer_grouping(t(), non_neg_integer, non_neg_integer) :: t() def put_integer_grouping(%__MODULE__{} = meta, first, rest) when is_integer(first) and is_integer(rest) do grouping = meta |> Map.get(:grouping) |> Map.put(:integer, %{first: first, rest: rest}) Map.put(meta, :grouping, grouping) end @spec put_integer_grouping(t(), non_neg_integer) :: t() def put_integer_grouping(%__MODULE__{} = meta, all) when is_integer(all) do grouping = meta |> Map.get(:grouping) |> Map.put(:integer, %{first: all, rest: all}) Map.put(meta, :grouping, grouping) end @doc """ Sets the number of digits in a group or optionally the first group and subsequent groups for the fractional part of a number. The grouping character is defined by the locale defined for the current process or supplied as the `:locale` option to `to_string/3`. """ @spec put_fraction_grouping(t(), non_neg_integer, non_neg_integer) :: t() def put_fraction_grouping(%__MODULE__{} = meta, first, rest) when is_integer(first) and is_integer(rest) do grouping = meta |> Map.get(:grouping) |> Map.put(:fraction, %{first: first, rest: rest}) Map.put(meta, :grouping, grouping) end @spec put_fraction_grouping(t(), non_neg_integer) :: t() def put_fraction_grouping(%__MODULE__{} = meta, all) when is_integer(all) do grouping = meta |> Map.get(:grouping) |> Map.put(:fraction, %{first: all, rest: all}) Map.put(meta, :grouping, grouping) end @doc """ Set the metadata format for the positive and negative number format. Note that this is the parsed format as a simple keyword list, not a binary representation. Its up to each formatting engine to transform its input into this form. See `Cldr.Number.Format.Meta` module documentation for the available keywords. """ @spec put_format(t(), Keyword.t(), Keyword.t()) :: t() def put_format(%__MODULE__{} = meta, positive_format, negative_format) do meta |> Map.put(:format, positive: positive_format, negative: negative_format) end @spec put_format(t(), Keyword.t()) :: t() def put_format(%__MODULE__{} = meta, positive_format) do put_format(meta, positive_format, minus: '-', format: :same_as_positive) end end
lib/cldr/number/format/meta.ex
0.938576
0.954647
meta.ex
starcoder
defmodule Solana.SPL.Token.Mint do @moduledoc """ Functions for interacting with the mint accounts of Solana's [Token Program](https://spl.solana.com/token). """ alias Solana.{Instruction, Account, SPL.Token, SystemProgram} import Solana.Helpers @typedoc "Token Program mint account metadata." @type t :: %__MODULE__{ authority: Solana.key() | nil, supply: non_neg_integer, decimals: byte, initialized?: boolean, freeze_authority: Solana.key() | nil } defstruct [ :authority, :supply, :freeze_authority, decimals: 0, initialized?: false ] @doc """ The size of a serialized token mint account. """ @spec byte_size() :: pos_integer def byte_size(), do: 82 @doc """ Translates the result of a `Solana.RPC.Request.get_account_info/2` into a `t:Solana.SPL.Token.Mint.t/0`. """ @spec from_account_info(info :: map) :: t | :error def from_account_info(info) def from_account_info(%{"data" => %{"parsed" => %{"type" => "mint", "info" => info}}}) do case {from_mint_account_info(info), info["freezeAuthority"]} do {:error, _} -> :error {mint, nil} -> mint {mint, authority} -> %{mint | freeze_authority: B58.decode58!(authority)} end end def from_account_info(_), do: :error defp from_mint_account_info(%{ "supply" => supply, "isInitialized" => initialized?, "mintAuthority" => authority, "decimals" => decimals }) do %__MODULE__{ decimals: decimals, authority: B58.decode58!(authority), initialized?: initialized?, supply: String.to_integer(supply) } end defp from_mint_account_info(_), do: :error @init_schema [ payer: [ type: {:custom, Solana.Key, :check, []}, required: true, doc: "The account that will pay for the mint creation" ], balance: [ type: :non_neg_integer, required: true, doc: "The lamport balance the mint account should have" ], decimals: [ type: {:in, 0..255}, required: true, doc: "decimals for the new mint" ], authority: [ type: {:custom, Solana.Key, :check, []}, required: true, doc: "authority for the new mint" ], freeze_authority: [ type: {:custom, Solana.Key, :check, []}, doc: "freeze authority for the new mint" ], new: [ type: {:custom, Solana.Key, :check, []}, required: true, doc: "public key for the new mint" ] ] @doc """ Genereates the instructions to initialize a mint account. ## Options #{NimbleOptions.docs(@init_schema)} """ def init(opts) do case validate(opts, @init_schema) do {:ok, params} -> [ SystemProgram.create_account( lamports: params.balance, space: byte_size(), from: params.payer, new: params.new, program_id: Token.id() ), initialize_ix(params) ] error -> error end end defp initialize_ix(params) do %Instruction{ program: Token.id(), accounts: [ %Account{key: params.new, writable?: true}, %Account{key: Solana.rent()} ], data: Instruction.encode_data([ 0, params.decimals, params.authority | add_freeze_authority(params) ]) } end defp add_freeze_authority(%{freeze_authority: freeze_authority}) do [1, freeze_authority] end defp add_freeze_authority(_params), do: [0, <<0::32*8>>] end
lib/solana/spl/token/mint.ex
0.865452
0.488649
mint.ex
starcoder
defmodule Analytics.Mixpanel.People do @moduledoc """ This module is responsible for building a struct which is later can be used to send all changes via batch request to the Mixpanel. Whenever batch request is submitted it's validated as whole, so that if one of entries is invalid there would be no changes applied to a user. """ alias Analytics.Mixpanel.People @engage_endpoint "engage" defstruct client: Analytics.Mixpanel.Client, operations: [], distinct_id: nil, ip: nil, token: nil @doc """ Creates a new `People` struct that updates person with a `distinct_id`. """ def new(distinct_id) do [client: client, token: token] = Analytics.Mixpanel.config() %People{distinct_id: distinct_id, client: client, token: token} end @doc """ The IP address associated with a given profile, which Mixpanel uses to guess user geographic location. Ignored if not set. """ def set_ip(%People{} = batch_request, ip), do: %{batch_request | ip: ip_to_string(ip)} defp ip_to_string({a, b, c, d}), do: "#{a}.#{b}.#{c}.#{d}" defp ip_to_string(ip), do: ip @doc """ Updates the profile attribute. If the profile does not exist, it creates it with these properties. If it does exist, it sets the properties to these values, overwriting existing values. For more details see `submit/2`. """ def set(%People{} = batch_request, key, value) do %{batch_request | operations: [{"$set", key, value} | batch_request.operations]} end @doc """ Removes the profile attribute. For more details see `submit/2`. """ def unset(%People{} = batch_request, key) do %{batch_request | operations: [{"$unset", key} | batch_request.operations]} end @doc """ Works just like `set/2`, except it will not overwrite existing property values. This is useful for properties like "First login date". For more details see `submit/2`. """ def set_once(%People{} = batch_request, key, value) do %{batch_request | operations: [{"$set_once", key, value} | batch_request.operations]} end @doc """ When processed, the property values are added to the existing values of the properties on the profile. If the property is not present on the profile, the value will be added to 0. It is possible to decrement by calling "$add" with negative values. This is useful for maintaining the values of properties like "Number of Logins" or "Files Uploaded". For more details see `submit/2`. """ def increment(%People{} = batch_request, key, value \\ 1) do %{batch_request | operations: [{"$add", key, value} | batch_request.operations]} end @doc """ Appends each to a list associated with the corresponding property name. Appending to a property that doesn't exist will result in assigning a list with one element to that property. For more details see `submit/2`. """ def append(%People{} = batch_request, key, value) do %{batch_request | operations: [{"$append", key, value} | batch_request.operations]} end @doc """ The list values in the request are merged with the existing list on the user profile, ignoring duplicates. For more details see `submit/2`. """ def union(%People{} = batch_request, key, list) when is_list(list) do %{batch_request | operations: [{"$union", key, list} | batch_request.operations]} end @doc """ Adds a transactions to the individual user profile, which will also be reflected in the Mixpanel Revenue report. For more details see `submit/2`. """ def track_charge(%People{} = batch_request, amount, metadata \\ %{}) do transaction = metadata |> Map.put("$amount", amount) |> Map.put_new("$time", DateTime.utc_now() |> DateTime.to_iso8601()) append(batch_request, "$transactions", transaction) end @doc """ Creates or updates user profile with operations from `People` struct. ## Options * `:update_last_seen` - If the `:update_last_seen` property is `true`, automatically updates the \ "Last Seen" property of the profile. Otherwise, Mixpanel will add a "Last Seen" property associated \ with the current time for all $set, $append, and $add operations. Default: `false`. """ def submit(%People{} = batch_request, opts \\ []) do payload = build_payload(batch_request, opts) batch_request.client.send_batch(@engage_endpoint, payload) end defp build_payload(batch_request, opts) do %{operations: operations, distinct_id: distinct_id, ip: ip, token: token} = batch_request event_template = Map.new() |> Map.put("$distinct_id", distinct_id) |> Map.put("$token", token) |> maybe_put("$ip", ip) |> maybe_put_last_seen_update(Keyword.get(opts, :update_last_seen, false)) operations |> Enum.reverse() |> Enum.group_by(&elem(&1, 0), &Tuple.delete_at(&1, 0)) |> maybe_merge_set() |> maybe_merge_unset() |> maybe_merge_set_once() |> maybe_merge_add() |> maybe_merge_union() |> maybe_merge_append() |> Enum.flat_map(fn {operation, values} when is_map(values) -> [Map.put(event_template, operation, values)] {"$unset" = operation, values} -> [Map.put(event_template, operation, values)] {operation, values} when is_list(values) -> Enum.map(values, fn value -> Map.put(event_template, operation, value) end) end) end defp maybe_merge_set(%{"$set" => updates} = operations) do set = Enum.reduce(updates, %{}, fn {key, value}, acc -> Map.put(acc, key, value) end) Map.put(operations, "$set", set) end defp maybe_merge_set(operations) do operations end defp maybe_merge_unset(%{"$unset" => updates} = operations) do unset = Enum.reduce(updates, [], fn {key}, acc -> [key] ++ acc end) Map.put(operations, "$unset", unset) end defp maybe_merge_unset(operations) do operations end defp maybe_merge_set_once(%{"$set_once" => updates} = operations) do set_once = Enum.reduce(updates, %{}, fn {key, value}, acc -> Map.put_new(acc, key, value) end) Map.put(operations, "$set_once", set_once) end defp maybe_merge_set_once(operations) do operations end defp maybe_merge_add(%{"$add" => updates} = operations) do increment = Enum.reduce(updates, %{}, fn {key, value}, acc -> if current_value = Map.get(acc, key) do Map.put(acc, key, current_value + value) else Map.put(acc, key, value) end end) Map.put(operations, "$add", increment) end defp maybe_merge_add(operations) do operations end defp maybe_merge_union(%{"$union" => updates} = operations) do union = Enum.reduce(updates, %{}, fn {key, value}, acc -> if current_value = Map.get(acc, key) do Map.put(acc, key, current_value ++ value) else Map.put(acc, key, value) end end) Map.put(operations, "$union", union) end defp maybe_merge_union(operations) do operations end defp maybe_merge_append(%{"$append" => updates} = operations) do {_keys, append} = Enum.reduce(updates, {MapSet.new(), []}, fn {key, value}, {keys, []} -> {MapSet.put(keys, key), [Map.new([{key, value}])]} {key, value}, {keys, [h | t] = acc} -> if MapSet.member?(keys, key) do {keys, acc ++ [Map.new([{key, value}])]} else {MapSet.put(keys, key), [Map.put(h, key, value)] ++ t} end end) Map.put(operations, "$append", append) end defp maybe_merge_append(operations) do operations end defp maybe_put(map, _key, nil), do: map defp maybe_put(map, key, value), do: Map.put(map, key, value) defp maybe_put_last_seen_update(event, true), do: event defp maybe_put_last_seen_update(event, _), do: Map.put(event, "$ignore_time", "true") end
lib/analytics/mixpanel/people.ex
0.84481
0.473414
people.ex
starcoder
defmodule Andy.GM.Perception do @moduledoc "Perception behaviour to unify some of Prediction and PredictionError" alias Andy.GM.{PredictionError, Prediction, Perception} @callback source(perception :: any) :: String.t() @callback conjecture_name(perception :: any) :: String.t() @callback about(perception :: any) :: any @callback carry_overs(perception :: any) :: non_neg_integer @callback prediction_conjecture_name(perception :: any) :: String.t() @callback values(perception :: any) :: map def has_subject?(perception, subject) do subject(perception) == subject end def subject(perception) do {conjecture_name(perception), about(perception)} end def values_match?(perception, match) do values = Perception.values(perception) Enum.all?(match, fn {key, val} -> Map.get(values, key) == val end) end def same_subject?(perception, other) do subject(perception) == subject(other) end def source(perception) do module = Map.get(perception, :__struct__) apply(module, :source, [perception]) end def conjecture_name(perception) do module = Map.get(perception, :__struct__) apply(module, :conjecture_name, [perception]) end def about(perception) do module = Map.get(perception, :__struct__) apply(module, :about, [perception]) end def carry_overs(perception) do module = Map.get(perception, :__struct__) apply(module, :carry_overs, [perception]) end def prediction_conjecture_name(perception) do module = Map.get(perception, :__struct__) apply(module, :prediction_conjecture_name, [perception]) end def values(perception) do module = Map.get(perception, :__struct__) apply(module, :values, [perception]) end def prediction_error?(perception) do Map.get(perception, :__struct__) == PredictionError end def prediction?(perception) do Map.get(perception, :__struct__) == Prediction end def increment_carry_overs(perception) do Map.put(perception, :carry_overs, Perception.carry_overs(perception) + 1) end end
lib/andy/gm/perception.ex
0.723407
0.553988
perception.ex
starcoder
import Kernel, except: [length: 1] defmodule String do @moduledoc %S""" A String in Elixir is a UTF-8 encoded binary. ## String and binary operations The functions in this module act according to the Unicode Standard, version 6.3.0. For example, `capitalize/1`, `downcase/1`, `strip/1` are provided by this module. In addition to this module, Elixir provides more low-level operations that work directly with binaries. Some of those can be found in the `Kernel` module, as: * `Kernel.binary_part/3` - retrieves part of the binary * `Kernel.bit_size/1` and `Kernel.byte_size/1` - size related functions * `Kernel.is_bitstring/1` and `Kernel.is_binary/1` - type checking function * Plus a number of conversion functions, like `Kernel.binary_to_atom/1`, `Kernel.binary_to_integer/2`, `Kernel.binary_to_term/1` and their inverses, like `Kernel.integer_to_binary/2` Finally, the [`:binary` module](http://erlang.org/doc/man/binary.html) provides a few other functions that work on the byte level. ## Codepoints and graphemes As per the Unicode Standard, a codepoint is an Unicode Character, which may be represented by one or more bytes. For example, the character "é" is represented with two bytes: iex> byte_size("é") 2 However, this module returns the proper length: iex> String.length("é") 1 Furthermore, this module also presents the concept of graphemes, which are multiple characters that may be "perceived as a single character" by readers. For example, the same "é" character written above could be represented by the letter "e" followed by the accent ́: iex> string = "\x{0065}\x{0301}" ...> byte_size(string) 3 iex> String.length(string) 1 Although the example above is made of two characters, it is perceived by users as one. Graphemes can also be two characters that are interpreted as one by some languages. For example, some languages may consider "ch" as a grapheme. However, since this information depends on the locale, it is not taken into account by this module. In general, the functions in this module rely on the Unicode Standard, but does not contain any of the locale specific behaviour. More information about graphemes can be found in the [Unicode Standard Annex #29](http://www.unicode.org/reports/tr29/). This current Elixir version implements Extended Grapheme Cluster algorithm. ## Integer codepoints Although codepoints could be represented as integers, this module represents all codepoints as strings. For example: iex> String.codepoints("josé") ["j", "o", "s", "é"] There are a couple of ways to retrieve a character integer codepoint. One may use the `?` special macro: iex> ?j 106 iex> ?é 233 Or also via pattern matching: iex> << eacute :: utf8 >> = "é" ...> eacute 233 As we have seen above, codepoints can be inserted into a string by their hexadecimal code: "jos\x{0065}\x{0301}" #=> "josé" ## Self-synchronization The UTF-8 encoding is self-synchronizing. This means that if malformed data (i.e., data that is not possible according to the definition of the encoding) is encountered, only one codepoint needs to be rejected. This module relies on this behaviour to ignore such invalid characters. For example, `length/1` is going to return a correct result even if an invalid codepoint is fed into it. In other words, this module expects invalid data to be detected when retrieving data from the external source. For example, a driver that reads strings from a database will be the one responsible to check the validity of the encoding. """ @type t :: binary @type codepoint :: t @type grapheme :: t @doc """ Checks if a string is printable considering it is encoded as UTF-8. Returns `true` if so, `false` otherwise. ## Examples iex> String.printable?("abc") true """ @spec printable?(t) :: boolean def printable?(<< h :: utf8, t :: binary >>) when h in ?\040..?\176 when h in 0xA0..0xD7FF when h in 0xE000..0xFFFD when h in 0x10000..0x10FFFF do printable?(t) end def printable?(<<?\n, t :: binary>>), do: printable?(t) def printable?(<<?\r, t :: binary>>), do: printable?(t) def printable?(<<?\t, t :: binary>>), do: printable?(t) def printable?(<<?\v, t :: binary>>), do: printable?(t) def printable?(<<?\b, t :: binary>>), do: printable?(t) def printable?(<<?\f, t :: binary>>), do: printable?(t) def printable?(<<?\e, t :: binary>>), do: printable?(t) def printable?(<<?\a, t :: binary>>), do: printable?(t) def printable?(<<>>), do: true def printable?(_), do: false @doc """ Divides a string into substrings at each Unicode whitespace occurrence with leading and trailing whitespace ignored. ## Examples iex> String.split("foo bar") ["foo", "bar"] iex> String.split("foo" <> <<194, 133>> <> "bar") ["foo", "bar"] iex> String.split(" foo bar ") ["foo", "bar"] """ @spec split(t) :: [t] defdelegate split(binary), to: String.Unicode @doc %S""" Divides a string into substrings based on a pattern, returning a list of these substrings. The pattern can be a string, a list of strings or a regular expression. The string is split into as many parts as possible by default, unless the `global` option is set to `false`. Empty strings are only removed from the result if the `trim` option is set to `true`. ## Examples Splitting with a string pattern: iex> String.split("a,b,c", ",") ["a", "b", "c"] iex> String.split("a,b,c", ",", global: false) ["a", "b,c"] iex> String.split(" a b c ", " ", trim: true) ["a", "b", "c"] A list of patterns: iex> String.split("1,2 3,4", [" ", ","]) ["1", "2", "3", "4"] A regular expression: iex> String.split("a,b,c", %r{,}) ["a", "b", "c"] iex> String.split("a,b,c", %r{,}, global: false) ["a", "b,c"] iex> String.split(" a b c ", %r{\s}, trim: true) ["a", "b", "c"] Splitting on empty patterns returns codepoints: iex> String.split("abc", %r{}) ["a", "b", "c", ""] iex> String.split("abc", "") ["a", "b", "c", ""] iex> String.split("abc", "", trim: true) ["a", "b", "c"] iex> String.split("abc", "", global: false) ["a", "bc"] """ @spec split(t, t | [t] | Regex.t) :: [t] @spec split(t, t | [t] | Regex.t, Keyword.t) :: [t] def split(binary, pattern, options // []) def split("", _pattern, _options), do: [""] def split(binary, "", options), do: split(binary, %r"", options) def split(binary, pattern, options) when is_regex(pattern) do Regex.split(pattern, binary, options) end def split(binary, pattern, options) do opts = if options[:global] != false, do: [:global], else: [] splits = :binary.split(binary, pattern, opts) if Keyword.get(options, :trim, false) do lc split inlist splits, split != "", do: split else splits end end @doc """ Convert all characters on the given string to uppercase. ## Examples iex> String.upcase("abcd") "ABCD" iex> String.upcase("ab 123 xpto") "AB 123 XPTO" iex> String.upcase("josé") "JOSÉ" """ @spec upcase(t) :: t defdelegate upcase(binary), to: String.Unicode @doc """ Convert all characters on the given string to lowercase. ## Examples iex> String.downcase("ABCD") "abcd" iex> String.downcase("AB 123 XPTO") "ab 123 xpto" iex> String.downcase("JOSÉ") "josé" """ @spec downcase(t) :: t defdelegate downcase(binary), to: String.Unicode @doc """ Converts the first character in the given string to uppercase and the remaining to lowercase. This relies on the titlecase information provided by the Unicode Standard. Note this function makes no attempt to capitalize all words in the string (usually known as titlecase). ## Examples iex> String.capitalize("abcd") "Abcd" iex> String.capitalize("fin") "Fin" iex> String.capitalize("josé") "José" """ @spec capitalize(t) :: t def capitalize(string) when is_binary(string) do { char, rest } = String.Unicode.titlecase_once(string) char <> downcase(rest) end @doc """ Returns a string where trailing Unicode whitespace has been removed. ## Examples iex> String.rstrip(" abc ") " abc" """ @spec rstrip(t) :: t defdelegate rstrip(binary), to: String.Unicode @doc """ Returns a string where trailing `char` have been removed. ## Examples iex> String.rstrip(" abc _", ?_) " abc " """ @spec rstrip(t, char) :: t def rstrip("", _char), do: "" # Do a quick check before we traverse the whole # binary. :binary.last is a fast operation (it # does not traverse the whole binary). def rstrip(string, char) when char in 0..127 do if :binary.last(string) == char do do_rstrip(string, "", char) else string end end def rstrip(string, char) do do_rstrip(string, "", char) end defp do_rstrip(<<char :: utf8, string :: binary>>, buffer, char) do <<do_rstrip(string, <<char :: utf8, buffer :: binary>>, char) :: binary>> end defp do_rstrip(<<char :: utf8, string :: binary>>, buffer, another_char) do <<buffer :: binary, char :: utf8, do_rstrip(string, "", another_char) :: binary>> end defp do_rstrip(<<>>, _, _) do <<>> end @doc """ Returns a string where leading Unicode whitespace has been removed. ## Examples iex> String.lstrip(" abc ") "abc " """ defdelegate lstrip(binary), to: String.Unicode @doc """ Returns a string where leading `char` have been removed. ## Examples iex> String.lstrip("_ abc _", ?_) " abc _" """ @spec lstrip(t, char) :: t def lstrip(<<char :: utf8, rest :: binary>>, char) do <<lstrip(rest, char) :: binary>> end def lstrip(other, _char) do other end @doc """ Returns a string where leading/trailing Unicode whitespace has been removed. ## Examples iex> String.strip(" abc ") "abc" """ @spec strip(t) :: t def strip(string) do rstrip(lstrip(string)) end @doc """ Returns a string where leading/trailing `char` have been removed. ## Examples iex> String.strip("a abc a", ?a) " abc " """ @spec strip(t, char) :: t def strip(string, char) do rstrip(lstrip(string, char), char) end @doc %S""" Returns a new string of length `len` with `subject` right justified and padded with `padding`. If `padding` is not present, it defaults to whitespace. When `len` is less than the length of `subject`, `subject` is returned. ## Examples iex> String.rjust("abc", 5) " abc" iex> String.rjust("abc", 5, ?-) "--abc" """ @spec rjust(t, pos_integer) :: t @spec rjust(t, pos_integer, char) :: t def rjust(subject, len) do rjust(subject, len, ?\s) end def rjust(subject, len, padding) when is_integer(padding) do do_justify(subject, len, padding, :right) end @doc %S""" Returns a new string of length `len` with `subject` left justified and padded with `padding`. If `padding` is not present, it defaults to whitespace. When `len` is less than the length of `subject`, `subject` is returned. ## Examples iex> String.ljust("abc", 5) "abc " iex> String.ljust("abc", 5, ?-) "abc--" """ @spec ljust(t, pos_integer) :: t @spec ljust(t, pos_integer, char) :: t def ljust(subject, len) do ljust(subject, len, ?\s) end def ljust(subject, len, padding) when is_integer(padding) do do_justify(subject, len, padding, :left) end defp do_justify(subject, 0, _padding, _type) do subject end defp do_justify(subject, len, padding, type) when is_integer(padding) do subject_len = length(subject) cond do subject_len >= len -> subject subject_len < len -> fill = duplicate(<<padding :: utf8>>, len - subject_len) case type do :left -> subject <> fill :right -> fill <> subject end end end @doc %S""" Returns a new binary based on `subject` by replacing the parts matching `pattern` by `replacement`. By default, it replaces all entries, except if the `global` option is set to `false`. A `pattern` may be a string or a regex. ## Examples iex> String.replace("a,b,c", ",", "-") "a-b-c" iex> String.replace("a,b,c", ",", "-", global: false) "a-b,c" The pattern can also be a regex. In those cases, one can give `\N` in the `replacement` string to access a specific capture in the regex: iex> String.replace("a,b,c", %r/,(.)/, ",\\1\\1") "a,bb,cc" Notice we had to escape the escape character `\`. By giving `&`, one can inject the whole matched pattern in the replacement string. When strings are used as a pattern, a developer can also use the replaced part inside the `replacement` via the `:insert_replaced` option: iex> String.replace("a,b,c", "b", "[]", insert_replaced: 1) "a,[b],c" iex> String.replace("a,b,c", ",", "[]", insert_replaced: 2) "a[],b[],c" iex> String.replace("a,b,c", ",", "[]", insert_replaced: [1, 1]) "a[,,]b[,,]c" """ @spec replace(t, t, t) :: t @spec replace(t, t, t, Keyword.t) :: t def replace(subject, pattern, replacement, options // []) def replace(subject, pattern, replacement, options) when is_regex(pattern) do Regex.replace(pattern, subject, replacement, global: options[:global]) end def replace(subject, pattern, replacement, options) do opts = translate_replace_options(options) :binary.replace(subject, pattern, replacement, opts) end defp translate_replace_options(options) do opts = if options[:global] != false, do: [:global], else: [] if insert = options[:insert_replaced] do opts = [{:insert_replaced, insert}|opts] end opts end @doc """ Reverses the given string. Works on graphemes. ## Examples iex> String.reverse("abcd") "dcba" iex> String.reverse("hello world") "dlrow olleh" iex> String.reverse("hello ∂og") "go∂ olleh" """ @spec reverse(t) :: t def reverse(string) do do_reverse(next_grapheme(string), []) end defp do_reverse({grapheme, rest}, acc) do do_reverse(next_grapheme(rest), [grapheme|acc]) end defp do_reverse(:no_grapheme, acc), do: iolist_to_binary(acc) @doc """ Returns a binary `subject` duplicated `n` times. ## Examples iex> String.duplicate("abc", 0) "" iex> String.duplicate("abc", 1) "abc" iex> String.duplicate("abc", 2) "abcabc" """ @spec duplicate(t, pos_integer) :: t def duplicate(subject, n) when is_integer(n) and n >= 0 do :binary.copy(subject, n) end @doc """ Returns all codepoints in the string. ## Examples iex> String.codepoints("josé") ["j", "o", "s", "é"] iex> String.codepoints("оптими зации") ["о","п","т","и","м","и"," ","з","а","ц","и","и"] iex> String.codepoints("ἅἪῼ") ["ἅ","Ἢ","ῼ"] """ @spec codepoints(t) :: [codepoint] defdelegate codepoints(string), to: String.Unicode @doc """ Returns the next codepoint in a String. The result is a tuple with the codepoint and the remaining of the string or `:no_codepoint` in case the string reached its end. As with other functions in the String module, this function does not check for the validity of the codepoint. That said, if an invalid codepoint is found, it will be returned by this function. ## Examples iex> String.next_codepoint("josé") { "j", "osé" } """ @compile { :inline, next_codepoint: 1 } @spec next_codepoint(t) :: {codepoint, t} | :no_codepoint defdelegate next_codepoint(string), to: String.Unicode @doc %S""" Checks whether `str` contains only valid characters. ## Examples iex> String.valid?("a") true iex> String.valid?("ø") true iex> String.valid?(<<0xffff :: 16>>) false iex> String.valid?("asd" <> <<0xffff :: 16>>) false """ @spec valid?(t) :: boolean noncharacters = Enum.to_list(?\x{FDD0}..?\x{FDEF}) ++ [ ?\x{0FFFE}, ?\x{0FFFF}, ?\x{1FFFE}, ?\x{1FFFF}, ?\x{2FFFE}, ?\x{2FFFF}, ?\x{3FFFE}, ?\x{3FFFF}, ?\x{4FFFE}, ?\x{4FFFF}, ?\x{5FFFE}, ?\x{5FFFF}, ?\x{6FFFE}, ?\x{6FFFF}, ?\x{7FFFE}, ?\x{7FFFF}, ?\x{8FFFE}, ?\x{8FFFF}, ?\x{9FFFE}, ?\x{9FFFF}, ?\x{10FFFE}, ?\x{10FFFF} ] lc noncharacter inlist noncharacters do def valid?(<< unquote(noncharacter) :: utf8, _ :: binary >>), do: false end def valid?(<<_ :: utf8, t :: binary>>), do: valid?(t) def valid?(<<>>), do: true def valid?(_), do: false @doc %S""" Checks whether `str` is a valid character. All characters are codepoints, but some codepoints are not valid characters. They may be reserved, private, or other. More info at: http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Noncharacters ## Examples iex> String.valid_character?("a") true iex> String.valid_character?("ø") true iex> String.valid_character?("\x{ffff}") false """ @spec valid_character?(t) :: boolean def valid_character?(<<_ :: utf8>> = codepoint), do: valid?(codepoint) def valid_character?(_), do: false @doc """ Returns unicode graphemes in the string as per Extended Grapheme Cluster algorithm outlined in the [Unicode Standard Annex #29, Unicode Text Segmentation](http://www.unicode.org/reports/tr29/). ## Examples iex> String.graphemes("Ā̀stute") ["Ā̀","s","t","u","t","e"] """ @spec graphemes(t) :: [grapheme] defdelegate graphemes(string), to: String.Graphemes @doc """ Returns the next grapheme in a String. The result is a tuple with the grapheme and the remaining of the string or `:no_grapheme` in case the String reached its end. ## Examples iex> String.next_grapheme("josé") { "j", "osé" } """ @compile { :inline, next_grapheme: 1 } @spec next_grapheme(t) :: { grapheme, t } | :no_grapheme defdelegate next_grapheme(string), to: String.Graphemes @doc """ Returns the first grapheme from an utf8 string, nil if the string is empty. ## Examples iex> String.first("elixir") "e" iex> String.first("եոգլի") "ե" """ @spec first(t) :: grapheme | nil def first(string) do case next_grapheme(string) do { char, _ } -> char :no_grapheme -> nil end end @doc """ Returns the last grapheme from an utf8 string, `nil` if the string is empty. ## Examples iex> String.last("elixir") "r" iex> String.last("եոգլի") "ի" """ @spec last(t) :: grapheme | nil def last(string) do do_last(next_grapheme(string), nil) end defp do_last({char, rest}, _) do do_last(next_grapheme(rest), char) end defp do_last(:no_grapheme, last_char), do: last_char @doc """ Returns the number of unicode graphemes in an utf8 string. ## Examples iex> String.length("elixir") 6 iex> String.length("եոգլի") 5 """ @spec length(t) :: non_neg_integer def length(string) do do_length(next_grapheme(string)) end defp do_length({_, rest}) do 1 + do_length(next_grapheme(rest)) end defp do_length(:no_grapheme), do: 0 @doc """ Returns the grapheme in the `position` of the given utf8 `string`. If `position` is greater than `string` length, than it returns `nil`. ## Examples iex> String.at("elixir", 0) "e" iex> String.at("elixir", 1) "l" iex> String.at("elixir", 10) nil iex> String.at("elixir", -1) "r" iex> String.at("elixir", -10) nil """ @spec at(t, integer) :: grapheme | nil def at(string, position) when position >= 0 do do_at(next_grapheme(string), position, 0) end def at(string, position) when position < 0 do real_pos = length(string) - abs(position) case real_pos >= 0 do true -> do_at(next_grapheme(string), real_pos, 0) false -> nil end end defp do_at({_ , rest}, desired_pos, current_pos) when desired_pos > current_pos do do_at(next_grapheme(rest), desired_pos, current_pos + 1) end defp do_at({char, _}, desired_pos, current_pos) when desired_pos == current_pos do char end defp do_at(:no_grapheme, _, _), do: nil @doc """ Returns a substring starting at the offset given by the first, and a length given by the second. If the offset is greater than string length, than it returns `nil`. ## Examples iex> String.slice("elixir", 1, 3) "lix" iex> String.slice("elixir", 1, 10) "lixir" iex> String.slice("elixir", 10, 3) nil iex> String.slice("elixir", -4, 4) "ixir" iex> String.slice("elixir", -10, 3) nil iex> String.slice("a", 0, 1500) "a" iex> String.slice("a", 1, 1500) "" iex> String.slice("a", 2, 1500) nil """ @spec slice(t, integer, integer) :: grapheme | nil def slice(string, start, 0) do case abs(start) <= length(string) do true -> "" false -> nil end end def slice(string, start, len) when start >= 0 and len >= 0 do do_slice(next_grapheme(string), start, start + len - 1, 0, "") end def slice(string, start, len) when start < 0 and len >= 0 do real_start_pos = length(string) - abs(start) case real_start_pos >= 0 do true -> do_slice(next_grapheme(string), real_start_pos, real_start_pos + len - 1, 0, "") false -> nil end end @doc """ Returns a substring from the offset given by the start of the range to the offset given by the end of the range. If the start of the range is not a valid offset for the given string or if the range is in reverse order, returns `nil`. ## Examples iex> String.slice("elixir", 1..3) "lix" iex> String.slice("elixir", 1..10) "lixir" iex> String.slice("elixir", 10..3) nil iex> String.slice("elixir", -4..-1) "ixir" iex> String.slice("elixir", 2..-1) "ixir" iex> String.slice("elixir", -4..6) "ixir" iex> String.slice("elixir", -1..-4) nil iex> String.slice("elixir", -10..-7) nil iex> String.slice("a", 0..1500) "a" iex> String.slice("a", 1..1500) "" iex> String.slice("a", 2..1500) nil """ @spec slice(t, Range.t) :: t | nil def slice(string, range) def slice(string, first..last) when first >= 0 and last >= 0 do do_slice(next_grapheme(string), first, last, 0, "") end def slice(string, first..last) do total = length(string) if first < 0 do first = total + first end if last < 0 do last = total + last end if first > 0 do do_slice(next_grapheme(string), first, last, 0, "") end end defp do_slice(_, start_pos, last_pos, _, _) when start_pos > last_pos do nil end defp do_slice({_, rest}, start_pos, last_pos, current_pos, acc) when current_pos < start_pos do do_slice(next_grapheme(rest), start_pos, last_pos, current_pos + 1, acc) end defp do_slice({char, rest}, start_pos, last_pos, current_pos, acc) when current_pos >= start_pos and current_pos < last_pos do do_slice(next_grapheme(rest), start_pos, last_pos, current_pos + 1, acc <> char) end defp do_slice({char, _}, start_pos, last_pos, current_pos, acc) when current_pos >= start_pos and current_pos == last_pos do acc <> char end defp do_slice(:no_grapheme, start_pos, _, current_pos, acc) when start_pos == current_pos do acc end defp do_slice(:no_grapheme, _, _, _, acc) do case acc do "" -> nil _ -> acc end end @doc """ Returns `true` if `string` starts with any of the prefixes given, otherwise `false`. `prefixes` can be either a single prefix or a list of prefixes. ## Examples iex> String.starts_with? "elixir", "eli" true iex> String.starts_with? "elixir", ["erlang", "elixir"] true iex> String.starts_with? "elixir", ["erlang", "ruby"] false """ @spec starts_with?(t, t | [t]) :: boolean def starts_with?(string, prefixes) when is_list(prefixes) do Enum.any?(prefixes, &do_starts_with(string, &1)) end def starts_with?(string, prefix) do do_starts_with(string, prefix) end defp do_starts_with(string, "") when is_binary(string) do true end defp do_starts_with(string, prefix) when is_binary(prefix) do match?({0, _}, :binary.match(string, prefix)) end defp do_starts_with(_, _) do raise ArgumentError end @doc """ Returns `true` if `string` ends with any of the suffixes given, otherwise `false`. `suffixes` can be either a single suffix or a list of suffixes. ## Examples iex> String.ends_with? "language", "age" true iex> String.ends_with? "language", ["youth", "age"] true iex> String.ends_with? "language", ["youth", "elixir"] false """ @spec ends_with?(t, t | [t]) :: boolean def ends_with?(string, suffixes) when is_list(suffixes) do Enum.any?(suffixes, &do_ends_with(string, &1)) end def ends_with?(string, suffix) do do_ends_with(string, suffix) end defp do_ends_with(string, "") when is_binary(string) do true end defp do_ends_with(string, suffix) when is_binary(suffix) do string_size = size(string) suffix_size = size(suffix) scope = {string_size - suffix_size, suffix_size} (suffix_size <= string_size) and (:nomatch != :binary.match(string, suffix, [scope: scope])) end defp do_ends_with(_, _) do raise ArgumentError end @doc """ Returns `true` if `string` contains match, otherwise `false`. `matches` can be either a single string or a list of strings. ## Examples iex> String.contains? "elixir of life", "of" true iex> String.contains? "elixir of life", ["life", "death"] true iex> String.contains? "elixir of life", ["death", "mercury"] false """ @spec contains?(t, t | [t]) :: boolean def contains?(string, matches) when is_list(matches) do Enum.any?(matches, &do_contains(string, &1)) end def contains?(string, match) do do_contains(string, match) end defp do_contains(string, "") when is_binary(string) do true end defp do_contains(string, match) when is_binary(match) do :nomatch != :binary.match(string, match) end defp do_contains(_, _) do raise ArgumentError end defexception UnicodeConversionError, [:encoded, :message] do def exception(opts) do UnicodeConversionError[ encoded: opts[:encoded], message: "#{opts[:kind]} #{detail(opts[:rest])}" ] end defp detail(rest) when is_binary(rest) do "encoding starting at #{inspect rest}" end defp detail([h|_]) do "code point #{h}" end end @doc """ Converts a string into a char list converting each codepoint to its respective integer value. ## Examples iex> String.to_char_list("æß") { :ok, 'æß' } iex> String.to_char_list("abc") { :ok, 'abc' } """ @spec to_char_list(String.t) :: { :ok, char_list } | { :error, list, binary } | { :incomplete, list, binary } def to_char_list(string) when is_binary(string) do case :unicode.characters_to_list(string) do result when is_list(result) -> { :ok, result } { :error, _, _ } = error -> error { :incomplete, _, _ } = incomplete -> incomplete end end @doc """ Converts a string into a char list converting each codepoint to its respective integer value. In case the conversion fails or is incomplete, it raises a `String.UnicodeConversionError`. ## Examples iex> String.to_char_list!("æß") 'æß' iex> String.to_char_list!("abc") 'abc' """ @spec to_char_list!(String.t) :: char_list | no_return def to_char_list!(string) when is_binary(string) do case :unicode.characters_to_list(string) do result when is_list(result) -> result { :error, encoded, rest } -> raise UnicodeConversionError, encoded: encoded, rest: rest, kind: :invalid { :incomplete, encoded, rest } -> raise UnicodeConversionError, encoded: encoded, rest: rest, kind: :incomplete end end @doc """ Converts a list of integer codepoints to a string. ## Examples iex> String.from_char_list([0x00E6, 0x00DF]) { :ok, "æß" } iex> String.from_char_list([0x0061, 0x0062, 0x0063]) { :ok, "abc" } """ @spec from_char_list(char_list) :: { :ok, String.t } | { :error, binary, binary } | { :incomplete, binary, binary } def from_char_list(list) when is_list(list) do case :unicode.characters_to_binary(list) do result when is_binary(result) -> { :ok, result } { :error, _, _ } = error -> error { :incomplete, _, _ } = incomplete -> incomplete end end @doc """ Converts a list of integer codepoints to a string. In case the conversion fails, it raises a `String.UnicodeConversionError`. ## Examples iex> String.from_char_list!([0x00E6, 0x00DF]) "æß" iex> String.from_char_list!([0x0061, 0x0062, 0x0063]) "abc" """ @spec from_char_list!(char_list) :: String.t | no_return def from_char_list!(list) when is_list(list) do case :unicode.characters_to_binary(list) do result when is_binary(result) -> result { :error, encoded, rest } -> raise UnicodeConversionError, encoded: encoded, rest: rest, kind: :invalid { :incomplete, encoded, rest } -> raise UnicodeConversionError, encoded: encoded, rest: rest, kind: :incomplete end end end
lib/elixir/lib/string.ex
0.882592
0.556369
string.ex
starcoder
defmodule Patch.Assertions do alias Patch.MissingCall alias Patch.Mock alias Patch.UnexpectedCall @doc """ Asserts that the given module and function has been called with any arity. ```elixir patch(Example, :function, :patch) Patch.Assertions.assert_any_call(Example, :function) # fails Example.function(1, 2, 3) Patch.Asertions.assert_any_call(Example, :function) # passes ``` There are convenience delegates in the Developer Interface, `Patch.assert_any_call/1` and `Patch.assert_any_call/2` which should be preferred over calling this function directly. """ @spec assert_any_call(module :: module(), function :: atom()) :: nil def assert_any_call(module, function) do unless Mock.called?(module, function) do message = """ \n Expected any call to the following function: #{inspect(module)}.#{to_string(function)} Calls which were received (matching calls are marked with *): #{format_calls_matching_any(module, function)} """ raise MissingCall, message: message end end @doc """ Given a call will assert that a matching call was observed by the patched function. This macro fully supports patterns and will perform non-hygienic binding similar to ExUnit's `assert_receive/3` and `assert_received/2`. ```elixir patch(Example, :function, :patch) Example.function(1, 2, 3) Patch.Assertions.assert_called(Example, :function, [1, 2, 3]) # passes Patch.Assertions.assert_called(Example, :function, [1, _, 3]) # passes Patch.Assertions.assert_called(Example, :function, [4, 5, 6]) # fails Patch.Assertions.assert_called(Example, :function, [4, _, 6]) # fails ``` There is a convenience macro in the Developer Interface, `Patch.assert_called/1` which should be preferred over calling this macro directly. """ @spec assert_called(call :: Macro.t()) :: Macro.t() defmacro assert_called(call) do {module, function, patterns} = Macro.decompose_call(call) quote do unless Patch.Mock.called?(unquote(call)) do history = Patch.Mock.match_history(unquote(call)) message = """ \n Expected but did not receive the following call: #{inspect(unquote(module))}.#{to_string(unquote(function))}(#{Patch.Assertions.format_patterns(unquote(patterns))}) Calls which were received (matching calls are marked with *): #{Patch.Assertions.format_history(unquote(module), history)} """ raise MissingCall, message: message end {:ok, {unquote(function), arguments}} = Patch.Mock.latest_match(unquote(call)) Patch.Macro.match(unquote(patterns), arguments) end end @doc """ Given a call will assert that a matching call was observed exactly the number of times provided by the patched function. This macro fully supports patterns and will perform non-hygienic binding similar to ExUnit's `assert_receive/3` and `assert_received/2`. The value bound will be the from the latest call. ```elixir patch(Example, :function, :patch) Example.function(1, 2, 3) Patch.Assertions.assert_called(Example, :function, [1, 2, 3], 1) # passes Patch.Assertions.assert_called(Example, :function, [1, _, 3], 1) # passes Example.function(1, 2, 3) Patch.Assertions.assert_called(Example, :function, [1, 2, 3], 2) # passes Patch.Assertions.assert_called(Example, :function, [1, _, 3], 2) # passes ``` There is a convenience macro in the Developer Interface, `Patch.assert_called/2` which should be preferred over calling this macro directly. """ @spec assert_called(call :: Macro.t(), count :: non_neg_integer()) :: Macro.t() defmacro assert_called(call, count) do {module, function, patterns} = Macro.decompose_call(call) quote do call_count = Patch.Mock.call_count(unquote(call)) unless call_count == unquote(count) do exception = if call_count < unquote(count) do MissingCall else UnexpectedCall end history = Patch.Mock.match_history(unquote(call)) message = """ \n Expected #{unquote(count)} of the following calls, but found #{call_count}: #{inspect(unquote(module))}.#{to_string(unquote(function))}(#{Patch.Assertions.format_patterns(unquote(patterns))}) Calls which were received (matching calls are marked with *): #{Patch.Assertions.format_history(unquote(module), history)} """ raise exception, message end {:ok, {unquote(function), arguments}} = Patch.Mock.latest_match(unquote(call)) Patch.Macro.match(unquote(patterns), arguments) end end @doc """ Given a call will assert that a matching call was observed exactly once by the patched function. This macro fully supports patterns and will perform non-hygienic binding similar to ExUnit's `assert_receive/3` and `assert_received/2`. ```elixir patch(Example, :function, :patch) Example.function(1, 2, 3) Patch.Assertions.assert_called_once(Example, :function, [1, 2, 3]) # passes Patch.Assertions.assert_called_once(Example, :function, [1, _, 3]) # passes Example.function(1, 2, 3) Patch.Assertions.assert_called_once(Example, :function, [1, 2, 3]) # fails Patch.Assertions.assert_called_once(Example, :function, [1, _, 3]) # fails ``` There is a convenience macro in the Developer Interface, `Patch.assert_called_once/1` which should be preferred over calling this macro directly. """ @spec assert_called_once(call :: Macro.t()) :: Macro.t() defmacro assert_called_once(call) do {module, function, patterns} = Macro.decompose_call(call) quote do call_count = Patch.Mock.call_count(unquote(call)) unless call_count == 1 do exception = if call_count == 0 do MissingCall else UnexpectedCall end history = Patch.Mock.match_history(unquote(call)) message = """ \n Expected the following call to occur exactly once, but call occurred #{call_count} times: #{inspect(unquote(module))}.#{to_string(unquote(function))}(#{Patch.Assertions.format_patterns(unquote(patterns))}) Calls which were received (matching calls are marked with *): #{Patch.Assertions.format_history(unquote(module), history)} """ raise exception, message end {:ok, {unquote(function), arguments}} = Patch.Mock.latest_match(unquote(call)) Patch.Macro.match(unquote(patterns), arguments) end end @doc """ Refutes that the given module and function has been called with any arity. ```elixir patch(Example, :function, :patch) Patch.Assertions.refute_any_call(Example, :function) # passes Example.function(1, 2, 3) Patch.Assertions.refute_any_call(Example, :function) # fails ``` There are convenience delegates in the Developer Interface, `Patch.refute_any_call/1` and `Patch.refute_any_call/2` which should be preferred over calling this function directly. """ @spec refute_any_call(module :: module(), function :: atom()) :: nil def refute_any_call(module, function) do if Mock.called?(module, function) do message = """ \n Unexpected call received, expected no calls: #{inspect(module)}.#{to_string(function)} Calls which were received (matching calls are marked with *): #{format_calls_matching_any(module, function)} """ raise UnexpectedCall, message: message end end @doc """ Given a call will refute that a matching call was observed by the patched function. This macro fully supports patterns. ```elixir patch(Example, :function, :patch) Example.function(1, 2, 3) Patch.Assertions.refute_called(Example, :function, [4, 5, 6]) # passes Patch.Assertions.refute_called(Example, :function, [4, _, 6]) # passes Patch.Assertions.refute_called(Example, :function, [1, 2, 3]) # fails Patch.Assertions.refute_called(Example, :function, [1, _, 3]) # passes ``` There is a convenience macro in the Developer Interface, `Patch.refute_called/1` which should be preferred over calling this macro directly. """ @spec refute_called(call :: Macro.t()) :: Macro.t() defmacro refute_called(call) do {module, function, patterns} = Macro.decompose_call(call) quote do if Patch.Mock.called?(unquote(call)) do history = Patch.Mock.match_history(unquote(call)) message = """ \n Unexpected call received: #{inspect(unquote(module))}.#{to_string(unquote(function))}(#{Patch.Assertions.format_patterns(unquote(patterns))}) Calls which were received (matching calls are marked with *): #{Patch.Assertions.format_history(unquote(module), history)} """ raise UnexpectedCall, message: message end end end @doc """ Given a call will refute that a matching call was observed exactly the number of times provided by the patched function. This macro fully supports patterns. ```elixir patch(Example, :function, :patch) Example.function(1, 2, 3) Patch.Assertions.refute_called(Example, :function, [1, 2, 3], 2) # passes Patch.Assertions.refute_called(Example, :function, [1, _, 3], 2) # passes Example.function(1, 2, 3) Patch.Assertions.refute_called(Example, :function, [1, 2, 3], 1) # passes Patch.Assertions.refute_called(Example, :function, [1, _, 3], 1) # passes ``` There is a convenience macro in the Developer Interface, `Patch.refute_called/2` which should be preferred over calling this macro directly. """ @spec refute_called(call :: Macro.t(), count :: non_neg_integer()) :: Macro.t() defmacro refute_called(call, count) do {module, function, patterns} = Macro.decompose_call(call) quote do call_count = Patch.Mock.call_count(unquote(call)) if call_count == unquote(count) do history = Patch.Mock.match_history(unquote(call)) message = """ \n Expected any count except #{unquote(count)} of the following calls, but found #{call_count}: #{inspect(unquote(module))}.#{to_string(unquote(function))}(#{Patch.Assertions.format_patterns(unquote(patterns))}) Calls which were received (matching calls are marked with *): #{Patch.Assertions.format_history(unquote(module), history)} """ raise UnexpectedCall, message end end end @doc """ Given a call will refute that a matching call was observed exactly once by the patched function. This macro fully supports patterns. ```elixir patch(Example, :function, :patch) Example.function(1, 2, 3) Patch.Assertions.refute_called_once(Example, :function, [1, 2, 3]) # fails Patch.Assertions.refute_called_once(Example, :function, [1, _, 3]) # fails Example.function(1, 2, 3) Patch.Assertions.refute_called_once(Example, :function, [1, 2, 3]) # passes Patch.Assertions.refute_called_once(Example, :function, [1, _, 3]) # passes ``` There is a convenience macro in the Developer Interface, `Patch.refute_called_once/1` which should be preferred over calling this macro directly. """ @spec refute_called_once(call :: Macro.t()) :: Macro.t() defmacro refute_called_once(call) do {module, function, patterns} = Macro.decompose_call(call) quote do call_count = Patch.Mock.call_count(unquote(call)) if call_count == 1 do history = Patch.Mock.match_history(unquote(call)) message = """ \n Expected the following call to occur any number of times but once, but it occurred once: #{inspect(unquote(module))}.#{to_string(unquote(function))}(#{Patch.Assertions.format_patterns(unquote(patterns))}) Calls which were received (matching calls are marked with *): #{Patch.Assertions.format_history(unquote(module), history)} """ raise UnexpectedCall, message end end end @doc """ Formats the AST for a list of patterns AST as they would appear in an argument list. """ @spec format_patterns(patterns :: [term()]) :: String.t() defmacro format_patterns(patterns) do patterns |> Macro.to_string() |> String.slice(1..-2) end @doc """ Formats history entries like those returned by `Patch.Mock.match_history/1`. """ @spec format_history(module :: module(), calls :: [{boolean(), {atom(), [term()]}}]) :: String.t() def format_history(module, calls) do calls |> Enum.reverse() |> Enum.with_index(1) |> Enum.map(fn {{matches, {function, arguments}}, i} -> marker = if matches do "* " else " " end "#{marker}#{i}. #{inspect(module)}.#{function}(#{format_arguments(arguments)})" end) |> case do [] -> " [No Calls Received]" calls -> Enum.join(calls, "\n") end end ## Private @spec format_arguments(arguments :: [term()]) :: String.t() defp format_arguments(arguments) do arguments |> Enum.map(&Kernel.inspect/1) |> Enum.join(", ") end @spec format_calls_matching_any(module :: module(), expected_function :: atom()) :: String.t() defp format_calls_matching_any(module, expected_function) do module |> Patch.history() |> Enum.with_index(1) |> Enum.map(fn {{actual_function, arguments}, i} -> marker = if expected_function == actual_function do "* " else " " end "#{marker}#{i}. #{inspect(module)}.#{actual_function}(#{format_arguments(arguments)})" end) |> case do [] -> " [No Calls Received]" calls -> Enum.join(calls, "\n") end end end
lib/patch/assertions.ex
0.903024
0.860428
assertions.ex
starcoder
defmodule Harald.Host.ATT.FindInformationRsp do @moduledoc """ Reference: version 5.2, Vol 3, Part F, 3.4.3.2 """ def encode(%{format: format, information_data: information_data}) when format == :handle_and_16_bit_uuid do encoded_information_data = encode_information_data(16, information_data) {:ok, <<0x1, encoded_information_data::binary>>} end def encode(%{format: format, information_data: information_data}) when format == :handle_and_128_bit_uuid do encoded_information_data = encode_information_data(128, information_data) {:ok, <<0x2, encoded_information_data::binary>>} end def encode(decoded_find_information_rsp) do {:error, {:encode, {__MODULE__, decoded_find_information_rsp}}} end def encode_information_data(uuid_size, decoded_information_data) do encoded_information_data = for data_element <- decoded_information_data do handle = data_element.handle uuid = data_element.uuid <<handle::little-size(16), uuid::little-size(uuid_size)>> end Enum.join(encoded_information_data) end def decode(<<format::little-size(8), information_data::binary>>) when byte_size(information_data) == 0 do {:error, {:decode, {__MODULE__, <<format>>}}} end def decode(<<format::little-size(8), information_data::binary>>) when format == 0x01 and rem(byte_size(information_data), 4) == 0 do decoded_information_data = for <<handle::little-size(16), uuid::little-size(16) <- information_data>> do %{handle: handle, uuid: uuid} end parameters = %{format: :handle_and_16_bit_uuid, information_data: decoded_information_data} {:ok, parameters} end def decode(<<format::little-size(8), information_data::binary>>) when format == 0x02 and rem(byte_size(information_data), 18) == 0 do decoded_information_data = for <<handle::little-size(16), uuid::little-size(128) <- information_data>> do %{handle: handle, uuid: uuid} end parameters = %{format: :handle_and_128_bit_uuid, information_data: decoded_information_data} {:ok, parameters} end def decode(encoded_find_information_rsp) do {:error, {:decode, {__MODULE__, encoded_find_information_rsp}}} end def opcode(), do: 0x05 end
lib/harald/host/att/find_information_rsp.ex
0.670716
0.462837
find_information_rsp.ex
starcoder
defmodule Credo.Check.Refactor.FunctionArity do @moduledoc """ A function can take as many parameters as needed, but even in a functional language there can be too many parameters. Can optionally ignore private functions (check configuration options). """ @explanation [ check: @moduledoc, params: [ max_arity: "The maximum number of parameters which a function should take.", ignore_defp: "Set to `true` to ignore private functions." ] ] @default_params [max_arity: 8, ignore_defp: false] @def_ops [:def, :defp, :defmacro] use Credo.Check alias Credo.Code.Parameters @doc false def run(source_file, params \\ []) do issue_meta = IssueMeta.for(source_file, params) max_arity = Params.get(params, :max_arity, @default_params) ignore_defp = Params.get(params, :ignore_defp, @default_params) Credo.Code.prewalk( source_file, &traverse(&1, &2, issue_meta, max_arity, ignore_defp) ) end for op <- @def_ops do defp traverse( {unquote(op) = op, meta, arguments} = ast, issues, issue_meta, max_arity, ignore_defp ) when is_list(arguments) do arity = Parameters.count(ast) if issue?(op, ignore_defp, arity, max_arity) do fun_name = CodeHelper.def_name(ast) { ast, issues ++ [issue_for(issue_meta, meta[:line], fun_name, max_arity, arity)] } else {ast, issues} end end end defp traverse(ast, issues, _issue_meta, _max_arity, _ignore_defp) do {ast, issues} end def issue?(:defp, true, _, _), do: false def issue?(_, _, arity, max_arity) when arity > max_arity, do: true def issue?(_, _, _, _), do: false def issue_for(issue_meta, line_no, trigger, max_value, actual_value) do format_issue( issue_meta, message: "Function takes too many parameters (arity is #{actual_value}, max is #{max_value}).", trigger: trigger, line_no: line_no, severity: Severity.compute(actual_value, max_value) ) end end
lib/credo/check/refactor/function_arity.ex
0.821474
0.431884
function_arity.ex
starcoder
defmodule Membrane.Core.OptionsSpecs do @moduledoc false use Bunch alias Bunch.{KVEnum, Markdown} alias Membrane.Pad alias Membrane.Time @default_types_params %{ atom: [spec: quote_expr(atom)], boolean: [spec: quote_expr(boolean)], string: [spec: quote_expr(String.t())], keyword: [spec: quote_expr(keyword)], struct: [spec: quote_expr(struct)], caps: [spec: quote_expr(struct)], time: [spec: quote_expr(Time.t()), inspector: &Time.to_code_str/1] } @spec options_doc() :: String.t() def options_doc do """ Options are defined by a keyword list, where each key is an option name and is described by another keyword list with following fields: * `type:` atom, used for parsing * `spec:` typespec for value in struct. If ommitted, for types: `#{inspect(Map.keys(@default_types_params))}` the default typespec is provided, for others typespec is set to `t:any/0` * `default:` default value for option. If not present, value for this option will have to be provided each time options struct is created * `inspector:` function converting fields' value to a string. Used when creating documentation instead of `inspect/1` * `description:` string describing an option. It will be used for generating the docs """ end @spec def_options(module(), nil | Keyword.t(), :element | :bin) :: Macro.t() def def_options(module, options, child) do {opt_typespecs, escaped_opts} = parse_opts(options) typedoc = generate_opts_doc(escaped_opts) quote do @typedoc """ Struct containing options for `#{inspect(__MODULE__)}` """ @type t :: %unquote(module){unquote_splicing(opt_typespecs)} @membrane_options_moduledoc """ ## #{unquote(child) |> to_string |> String.capitalize()} options Passed via struct `t:#{inspect(__MODULE__)}.t/0` #{unquote(typedoc)} """ @doc """ Returns description of options available for this module """ @spec options() :: keyword def options(), do: unquote(escaped_opts) @enforce_keys unquote(escaped_opts) |> Enum.reject(fn {k, v} -> v |> Keyword.has_key?(:default) end) |> Keyword.keys() defstruct unquote(escaped_opts) |> Enum.map(fn {k, v} -> {k, v[:default]} end) end end @spec def_pad_options(Pad.name_t(), nil | Keyword.t()) :: {Macro.t(), Macro.t()} def def_pad_options(_pad_name, nil) do no_code = quote do end {nil, no_code} end def def_pad_options(pad_name, options) do {opt_typespecs, escaped_opts} = parse_opts(options) pad_opts_type_name = "#{pad_name}_pad_opts_t" |> String.to_atom() type_definiton = quote do @typedoc """ Options for pad `#{inspect(unquote(pad_name))}` """ @type unquote(Macro.var(pad_opts_type_name, nil)) :: unquote(opt_typespecs) end {escaped_opts, type_definiton} end @spec generate_opts_doc(escaped_opts :: Keyword.t()) :: Macro.t() def generate_opts_doc(escaped_opts) do escaped_opts |> Enum.map(&generate_opt_doc/1) |> Enum.reduce(fn opt_doc, acc -> quote do """ #{unquote(acc)} #{unquote(opt_doc)} """ end end) end defp generate_opt_doc({opt_name, opt_definition}) do header = "`#{Atom.to_string(opt_name)}`" spec = """ ``` #{Keyword.fetch!(opt_definition, :spec)} ``` """ default_value_doc = if Keyword.has_key?(opt_definition, :default) do inspector = opt_definition |> Keyword.get( :inspector, @default_types_params[opt_definition[:type]][:inspector] || quote(do: &inspect/1) ) quote do "Default value: `#{unquote(inspector).(unquote(opt_definition)[:default])}`" end else quote_expr("***Required***") end description = Keyword.get(opt_definition, :description, "") quote do description = unquote(description) |> String.trim() doc_parts = [unquote_splicing([spec, default_value_doc]), description] """ - #{unquote(header)} \n #{doc_parts |> Enum.map_join(" \n", &Markdown.indent/1)} """ end end defp parse_opts(opts) when is_list(opts) do opts = KVEnum.map_values(opts, fn definition -> default_spec = @default_types_params[definition[:type]][:spec] || quote_expr(any) Keyword.put_new(definition, :spec, default_spec) end) opts_typespecs = KVEnum.map_values(opts, & &1[:spec]) escaped_opts = KVEnum.map_values(opts, fn definition -> Keyword.update!(definition, :spec, &Macro.to_string/1) end) {opts_typespecs, escaped_opts} end end
lib/membrane/core/options_specs.ex
0.846403
0.682475
options_specs.ex
starcoder
defmodule VintageNet.PropertyTable do @moduledoc """ PropertyTables are in-memory key-value stores Users can subscribe to keys or groups of keys to be notified of changes. Keys are hierarchically layed out with each key being represented as a list for the path to the key. For example, to get the current state of the network interface `eth0`, you would get the value of the key, `["net", "ethernet", "eth0"]`. Values can be any Elixir data structure except for `nil`. `nil` is used to identify non-existent keys. Therefore, setting a property to `nil` deletes the property. Users can get and listen for changes in multiple keys by specifying prefix paths. For example, if you wants to get every network property, run: PropertyTable.get_by_prefix(table, ["net"]) Likewise, you can subscribe to changes in the network status by running: PropertyTable.subscribe(table, ["net"]) Properties can include metadata. `PropertyTable` only specifies that metadata is a map. """ alias VintageNet.PropertyTable.Table @typedoc """ A table_id identifies a group of properties """ @type table_id() :: atom() @typedoc """ Properties """ @type property :: [String.t()] @type value :: any() @type metadata :: map() @spec start_link(name: table_id()) :: {:ok, pid} | {:error, term} def start_link(options) do name = Keyword.get(options, :name) unless !is_nil(name) and is_atom(name) do raise ArgumentError, "expected :name to be given and to be an atom, got: #{inspect(name)}" end VintageNet.PropertyTable.Supervisor.start_link(name) end @doc """ Returns a specification to start a property_table under a supervisor. See `Supervisor`. """ def child_spec(opts) do %{ id: Keyword.get(opts, :name, PropertyTable), start: {VintageNet.PropertyTable, :start_link, [opts]}, type: :supervisor } end @doc """ Subscribe to receive events """ @spec subscribe(table_id(), property()) :: :ok def subscribe(table, name) when is_list(name) do assert_name(name) registry = VintageNet.PropertyTable.Supervisor.registry_name(table) {:ok, _} = Registry.register(registry, name, nil) :ok end @doc """ Stop subscribing to a property """ @spec unsubscribe(table_id(), property()) :: :ok def unsubscribe(table, name) when is_list(name) do registry = VintageNet.PropertyTable.Supervisor.registry_name(table) Registry.unregister(registry, name) end @doc """ Get the current value of a property """ @spec get(table_id(), property(), value()) :: value() def get(table, name, default \\ nil) when is_list(name) do Table.get(table, name, default) end @doc """ Get a list of all properties matching the specified prefix """ @spec get_by_prefix(table_id(), property()) :: [{property(), value()}] def get_by_prefix(table, prefix) when is_list(prefix) do assert_name(prefix) Table.get_by_prefix(table, prefix) end @doc """ Update a property and notify listeners """ @spec put(table_id(), property(), value(), metadata()) :: :ok def put(table, name, value, metadata \\ %{}) when is_list(name) do Table.put(table, name, value, metadata) end @doc """ Clear out a property """ defdelegate clear(table, name), to: Table @doc """ Clear out all properties under a prefix """ defdelegate clear_prefix(table, name), to: Table defp assert_name(name) do Enum.all?(name, &is_binary/1) || raise ArgumentError, "Expected name or prefix to be a list of strings" end end
lib/vintage_net/property_table.ex
0.881053
0.512876
property_table.ex
starcoder
defmodule AWS.EKS do @moduledoc """ Amazon Elastic Kubernetes Service (Amazon EKS) is a managed service that makes it easy for you to run Kubernetes on AWS without needing to stand up or maintain your own Kubernetes control plane. Kubernetes is an open-source system for automating the deployment, scaling, and management of containerized applications. Amazon EKS runs up-to-date versions of the open-source Kubernetes software, so you can use all the existing plugins and tooling from the Kubernetes community. Applications running on Amazon EKS are fully compatible with applications running on any standard Kubernetes environment, whether running in on-premises data centers or public clouds. This means that you can easily migrate any standard Kubernetes application to Amazon EKS without any code modification required. """ @doc """ Creates an Amazon EKS control plane. The Amazon EKS control plane consists of control plane instances that run the Kubernetes software, such as `etcd` and the API server. The control plane runs in an account managed by AWS, and the Kubernetes API is exposed via the Amazon EKS API server endpoint. Each Amazon EKS cluster control plane is single-tenant and unique and runs on its own set of Amazon EC2 instances. The cluster control plane is provisioned across multiple Availability Zones and fronted by an Elastic Load Balancing Network Load Balancer. Amazon EKS also provisions elastic network interfaces in your VPC subnets to provide connectivity from the control plane instances to the worker nodes (for example, to support `kubectl exec`, `logs`, and `proxy` data flows). Amazon EKS worker nodes run in your AWS account and connect to your cluster's control plane via the Kubernetes API server endpoint and a certificate file that is created for your cluster. You can use the `endpointPublicAccess` and `endpointPrivateAccess` parameters to enable or disable public and private access to your cluster's Kubernetes API server endpoint. By default, public access is enabled, and private access is disabled. For more information, see [Amazon EKS Cluster Endpoint Access Control](https://docs.aws.amazon.com/eks/latest/userguide/cluster-endpoint.html) in the * *Amazon EKS User Guide* *. You can use the `logging` parameter to enable or disable exporting the Kubernetes control plane logs for your cluster to CloudWatch Logs. By default, cluster control plane logs aren't exported to CloudWatch Logs. For more information, see [Amazon EKS Cluster Control Plane Logs](https://docs.aws.amazon.com/eks/latest/userguide/control-plane-logs.html) in the * *Amazon EKS User Guide* *. CloudWatch Logs ingestion, archive storage, and data scanning rates apply to exported control plane logs. For more information, see [Amazon CloudWatch Pricing](http://aws.amazon.com/cloudwatch/pricing/). Cluster creation typically takes between 10 and 15 minutes. After you create an Amazon EKS cluster, you must configure your Kubernetes tooling to communicate with the API server and launch worker nodes into your cluster. For more information, see [Managing Cluster Authentication](https://docs.aws.amazon.com/eks/latest/userguide/managing-auth.html) and [Launching Amazon EKS Worker Nodes](https://docs.aws.amazon.com/eks/latest/userguide/launch-workers.html) in the *Amazon EKS User Guide*. """ def create_cluster(client, input, options \\ []) do path_ = "/clusters" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Creates an AWS Fargate profile for your Amazon EKS cluster. You must have at least one Fargate profile in a cluster to be able to run pods on Fargate. The Fargate profile allows an administrator to declare which pods run on Fargate and specify which pods run on which Fargate profile. This declaration is done through the profile’s selectors. Each profile can have up to five selectors that contain a namespace and labels. A namespace is required for every selector. The label field consists of multiple optional key-value pairs. Pods that match the selectors are scheduled on Fargate. If a to-be-scheduled pod matches any of the selectors in the Fargate profile, then that pod is run on Fargate. When you create a Fargate profile, you must specify a pod execution role to use with the pods that are scheduled with the profile. This role is added to the cluster's Kubernetes [Role Based Access Control](https://kubernetes.io/docs/admin/authorization/rbac/) (RBAC) for authorization so that the `kubelet` that is running on the Fargate infrastructure can register with your Amazon EKS cluster so that it can appear in your cluster as a node. The pod execution role also provides IAM permissions to the Fargate infrastructure to allow read access to Amazon ECR image repositories. For more information, see [Pod Execution Role](https://docs.aws.amazon.com/eks/latest/userguide/pod-execution-role.html) in the *Amazon EKS User Guide*. Fargate profiles are immutable. However, you can create a new updated profile to replace an existing profile and then delete the original after the updated profile has finished creating. If any Fargate profiles in a cluster are in the `DELETING` status, you must wait for that Fargate profile to finish deleting before you can create any other profiles in that cluster. For more information, see [AWS Fargate Profile](https://docs.aws.amazon.com/eks/latest/userguide/fargate-profile.html) in the *Amazon EKS User Guide*. """ def create_fargate_profile(client, cluster_name, input, options \\ []) do path_ = "/clusters/#{URI.encode(cluster_name)}/fargate-profiles" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Creates a managed worker node group for an Amazon EKS cluster. You can only create a node group for your cluster that is equal to the current Kubernetes version for the cluster. All node groups are created with the latest AMI release version for the respective minor Kubernetes version of the cluster, unless you deploy a custom AMI using a launch template. For more information about using launch templates, see [Launch template support](https://docs.aws.amazon.com/eks/latest/userguide/launch-templates.html). An Amazon EKS managed node group is an Amazon EC2 Auto Scaling group and associated Amazon EC2 instances that are managed by AWS for an Amazon EKS cluster. Each node group uses a version of the Amazon EKS-optimized Amazon Linux 2 AMI. For more information, see [Managed Node Groups](https://docs.aws.amazon.com/eks/latest/userguide/managed-node-groups.html) in the *Amazon EKS User Guide*. """ def create_nodegroup(client, cluster_name, input, options \\ []) do path_ = "/clusters/#{URI.encode(cluster_name)}/node-groups" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Deletes the Amazon EKS cluster control plane. If you have active services in your cluster that are associated with a load balancer, you must delete those services before deleting the cluster so that the load balancers are deleted properly. Otherwise, you can have orphaned resources in your VPC that prevent you from being able to delete the VPC. For more information, see [Deleting a Cluster](https://docs.aws.amazon.com/eks/latest/userguide/delete-cluster.html) in the *Amazon EKS User Guide*. If you have managed node groups or Fargate profiles attached to the cluster, you must delete them first. For more information, see `DeleteNodegroup` and `DeleteFargateProfile`. """ def delete_cluster(client, name, input, options \\ []) do path_ = "/clusters/#{URI.encode(name)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, nil) end @doc """ Deletes an AWS Fargate profile. When you delete a Fargate profile, any pods running on Fargate that were created with the profile are deleted. If those pods match another Fargate profile, then they are scheduled on Fargate with that profile. If they no longer match any Fargate profiles, then they are not scheduled on Fargate and they may remain in a pending state. Only one Fargate profile in a cluster can be in the `DELETING` status at a time. You must wait for a Fargate profile to finish deleting before you can delete any other profiles in that cluster. """ def delete_fargate_profile(client, cluster_name, fargate_profile_name, input, options \\ []) do path_ = "/clusters/#{URI.encode(cluster_name)}/fargate-profiles/#{URI.encode(fargate_profile_name)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, nil) end @doc """ Deletes an Amazon EKS node group for a cluster. """ def delete_nodegroup(client, cluster_name, nodegroup_name, input, options \\ []) do path_ = "/clusters/#{URI.encode(cluster_name)}/node-groups/#{URI.encode(nodegroup_name)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, nil) end @doc """ Returns descriptive information about an Amazon EKS cluster. The API server endpoint and certificate authority data returned by this operation are required for `kubelet` and `kubectl` to communicate with your Kubernetes API server. For more information, see [Create a kubeconfig for Amazon EKS](https://docs.aws.amazon.com/eks/latest/userguide/create-kubeconfig.html). The API server endpoint and certificate authority data aren't available until the cluster reaches the `ACTIVE` state. """ def describe_cluster(client, name, options \\ []) do path_ = "/clusters/#{URI.encode(name)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Returns descriptive information about an AWS Fargate profile. """ def describe_fargate_profile(client, cluster_name, fargate_profile_name, options \\ []) do path_ = "/clusters/#{URI.encode(cluster_name)}/fargate-profiles/#{URI.encode(fargate_profile_name)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Returns descriptive information about an Amazon EKS node group. """ def describe_nodegroup(client, cluster_name, nodegroup_name, options \\ []) do path_ = "/clusters/#{URI.encode(cluster_name)}/node-groups/#{URI.encode(nodegroup_name)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Returns descriptive information about an update against your Amazon EKS cluster or associated managed node group. When the status of the update is `Succeeded`, the update is complete. If an update fails, the status is `Failed`, and an error detail explains the reason for the failure. """ def describe_update(client, name, update_id, nodegroup_name \\ nil, options \\ []) do path_ = "/clusters/#{URI.encode(name)}/updates/#{URI.encode(update_id)}" headers = [] query_ = [] query_ = if !is_nil(nodegroup_name) do [{"nodegroupName", nodegroup_name} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists the Amazon EKS clusters in your AWS account in the specified Region. """ def list_clusters(client, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/clusters" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"nextToken", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"maxResults", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists the AWS Fargate profiles associated with the specified cluster in your AWS account in the specified Region. """ def list_fargate_profiles(client, cluster_name, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/clusters/#{URI.encode(cluster_name)}/fargate-profiles" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"nextToken", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"maxResults", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists the Amazon EKS managed node groups associated with the specified cluster in your AWS account in the specified Region. Self-managed node groups are not listed. """ def list_nodegroups(client, cluster_name, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/clusters/#{URI.encode(cluster_name)}/node-groups" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"nextToken", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"maxResults", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ List the tags for an Amazon EKS resource. """ def list_tags_for_resource(client, resource_arn, options \\ []) do path_ = "/tags/#{URI.encode(resource_arn)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists the updates associated with an Amazon EKS cluster or managed node group in your AWS account, in the specified Region. """ def list_updates(client, name, max_results \\ nil, next_token \\ nil, nodegroup_name \\ nil, options \\ []) do path_ = "/clusters/#{URI.encode(name)}/updates" headers = [] query_ = [] query_ = if !is_nil(nodegroup_name) do [{"nodegroupName", nodegroup_name} | query_] else query_ end query_ = if !is_nil(next_token) do [{"nextToken", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"maxResults", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Associates the specified tags to a resource with the specified `resourceArn`. If existing tags on a resource are not specified in the request parameters, they are not changed. When a resource is deleted, the tags associated with that resource are deleted as well. Tags that you create for Amazon EKS resources do not propagate to any other resources associated with the cluster. For example, if you tag a cluster with this operation, that tag does not automatically propagate to the subnets and worker nodes associated with the cluster. """ def tag_resource(client, resource_arn, input, options \\ []) do path_ = "/tags/#{URI.encode(resource_arn)}" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Deletes specified tags from a resource. """ def untag_resource(client, resource_arn, input, options \\ []) do path_ = "/tags/#{URI.encode(resource_arn)}" headers = [] {query_, input} = [ {"tagKeys", "tagKeys"}, ] |> AWS.Request.build_params(input) request(client, :delete, path_, query_, headers, input, options, nil) end @doc """ Updates an Amazon EKS cluster configuration. Your cluster continues to function during the update. The response output includes an update ID that you can use to track the status of your cluster update with the `DescribeUpdate` API operation. You can use this API operation to enable or disable exporting the Kubernetes control plane logs for your cluster to CloudWatch Logs. By default, cluster control plane logs aren't exported to CloudWatch Logs. For more information, see [Amazon EKS Cluster Control Plane Logs](https://docs.aws.amazon.com/eks/latest/userguide/control-plane-logs.html) in the * *Amazon EKS User Guide* *. CloudWatch Logs ingestion, archive storage, and data scanning rates apply to exported control plane logs. For more information, see [Amazon CloudWatch Pricing](http://aws.amazon.com/cloudwatch/pricing/). You can also use this API operation to enable or disable public and private access to your cluster's Kubernetes API server endpoint. By default, public access is enabled, and private access is disabled. For more information, see [Amazon EKS Cluster Endpoint Access Control](https://docs.aws.amazon.com/eks/latest/userguide/cluster-endpoint.html) in the * *Amazon EKS User Guide* *. At this time, you can not update the subnets or security group IDs for an existing cluster. Cluster updates are asynchronous, and they should finish within a few minutes. During an update, the cluster status moves to `UPDATING` (this status transition is eventually consistent). When the update is complete (either `Failed` or `Successful`), the cluster status moves to `Active`. """ def update_cluster_config(client, name, input, options \\ []) do path_ = "/clusters/#{URI.encode(name)}/update-config" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Updates an Amazon EKS cluster to the specified Kubernetes version. Your cluster continues to function during the update. The response output includes an update ID that you can use to track the status of your cluster update with the `DescribeUpdate` API operation. Cluster updates are asynchronous, and they should finish within a few minutes. During an update, the cluster status moves to `UPDATING` (this status transition is eventually consistent). When the update is complete (either `Failed` or `Successful`), the cluster status moves to `Active`. If your cluster has managed node groups attached to it, all of your node groups’ Kubernetes versions must match the cluster’s Kubernetes version in order to update the cluster to a new Kubernetes version. """ def update_cluster_version(client, name, input, options \\ []) do path_ = "/clusters/#{URI.encode(name)}/updates" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Updates an Amazon EKS managed node group configuration. Your node group continues to function during the update. The response output includes an update ID that you can use to track the status of your node group update with the `DescribeUpdate` API operation. Currently you can update the Kubernetes labels for a node group or the scaling configuration. """ def update_nodegroup_config(client, cluster_name, nodegroup_name, input, options \\ []) do path_ = "/clusters/#{URI.encode(cluster_name)}/node-groups/#{URI.encode(nodegroup_name)}/update-config" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Updates the Kubernetes version or AMI version of an Amazon EKS managed node group. You can update a node group using a launch template only if the node group was originally deployed with a launch template. If you need to update a custom AMI in a node group that was deployed with a launch template, then update your custom AMI, specify the new ID in a new version of the launch template, and then update the node group to the new version of the launch template. If you update without a launch template, then you can update to the latest available AMI version of a node group's current Kubernetes version by not specifying a Kubernetes version in the request. You can update to the latest AMI version of your cluster's current Kubernetes version by specifying your cluster's Kubernetes version in the request. For more information, see [Amazon EKS-Optimized Linux AMI Versions](https://docs.aws.amazon.com/eks/latest/userguide/eks-linux-ami-versions.html) in the *Amazon EKS User Guide*. You cannot roll back a node group to an earlier Kubernetes version or AMI version. When a node in a managed node group is terminated due to a scaling action or update, the pods in that node are drained first. Amazon EKS attempts to drain the nodes gracefully and will fail if it is unable to do so. You can `force` the update if Amazon EKS is unable to drain the nodes as a result of a pod disruption budget issue. """ def update_nodegroup_version(client, cluster_name, nodegroup_name, input, options \\ []) do path_ = "/clusters/#{URI.encode(cluster_name)}/node-groups/#{URI.encode(nodegroup_name)}/update-version" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @spec request(AWS.Client.t(), binary(), binary(), list(), list(), map(), list(), pos_integer()) :: {:ok, map() | nil, map()} | {:error, term()} defp request(client, method, path, query, headers, input, options, success_status_code) do client = %{client | service: "eks"} host = build_host("eks", client) url = host |> build_url(path, client) |> add_query(query, client) additional_headers = [{"Host", host}, {"Content-Type", "application/x-amz-json-1.1"}] headers = AWS.Request.add_headers(additional_headers, headers) payload = encode!(client, input) headers = AWS.Request.sign_v4(client, method, url, headers, payload) perform_request(client, method, url, payload, headers, options, success_status_code) end defp perform_request(client, method, url, payload, headers, options, success_status_code) do case AWS.Client.request(client, method, url, payload, headers, options) do {:ok, %{status_code: status_code, body: body} = response} when is_nil(success_status_code) and status_code in [200, 202, 204] when status_code == success_status_code -> body = if(body != "", do: decode!(client, body)) {:ok, body, response} {:ok, response} -> {:error, {:unexpected_response, response}} error = {:error, _reason} -> error end end defp build_host(_endpoint_prefix, %{region: "local", endpoint: endpoint}) do endpoint end defp build_host(_endpoint_prefix, %{region: "local"}) do "localhost" end defp build_host(endpoint_prefix, %{region: region, endpoint: endpoint}) do "#{endpoint_prefix}.#{region}.#{endpoint}" end defp build_url(host, path, %{:proto => proto, :port => port}) do "#{proto}://#{host}:#{port}#{path}" end defp add_query(url, [], _client) do url end defp add_query(url, query, client) do querystring = encode!(client, query, :query) "#{url}?#{querystring}" end defp encode!(client, payload, format \\ :json) do AWS.Client.encode!(client, payload, format) end defp decode!(client, payload) do AWS.Client.decode!(client, payload, :json) end end
lib/aws/generated/eks.ex
0.91468
0.664444
eks.ex
starcoder
defmodule Inspect.Algebra do @moduledoc %S""" A set of functions for creating and manipulating algebra documents, as described in ["Strictly Pretty" (2000) by <NAME>][0]. An algebra document is represented by an `Inspect.Algebra` node or a regular string. iex> Inspect.Algebra.empty :doc_nil iex> "foo" "foo" With the functions in this module, we can concatenate different elements together and render them: iex> doc = Inspect.Algebra.concat(Inspect.Algebra.empty, "foo") iex> Inspect.Algebra.pretty(doc, 80) "foo" The functions `nest/2`, `space/2` and `line/2` help you put the document together into a rigid structure. However, the document algebra gets interesting when using functions like `break/2`, which converts the given string into a line break depending on how much space there is to print. Let's glue two docs together with a break and then render it: iex> doc = Inspect.Algebra.glue("a", " ", "b") iex> Inspect.Algebra.pretty(doc, 80) "a b" Notice the break was represented as is, because we haven't reached a line limit. Once we do, it is replaced by a newline: iex> doc = Inspect.Algebra.glue(String.duplicate("a", 20), " ", "b") iex> Inspect.Algebra.pretty(doc, 10) "aaaaaaaaaaaaaaaaaaaa\nb" Finally, this module also contains Elixir related functions, a bit tied to Elixir formatting, namely `surround/3` and `surround_many/5`. ## Implementation details The original Haskell implementation of the algorithm by [Wadler][1] relies on lazy evaluation to unfold document groups on two alternatives: `:flat` (breaks as spaces) and `:break` (breaks as newlines). Implementing the same logic in a strict language such as Elixir leads to an exponential growth of possible documents, unless document groups are encoded explictly as `:flat` or `:break`. Those groups are then reduced to a simple document, where the layout is already decided, per [Lindig][0]. This implementation slightly changes the semantic of Lindig's algorithm to allow elements that belong to the same group to be printed together in the same line, even if they do not fit the line fully. This was achieved by changing `:break` to mean a possible break and `:flat` to force a flat structure. Then deciding if a break works as a newline is just a matter of checking if we have enough space until the next break that is not inside a group (which is still flat). Custom pretty printers can be implemented using the documents returned by this module and by providing their own rendering functions. [0]: http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.34.2200 [1]: http://homepages.inf.ed.ac.uk/wadler/papers/prettier/prettier.pdf """ @surround_separator "," @tail_separator " |" @newline "\n" @nesting 1 @break " " # Functional interface to `doc` records @type t :: :doc_nil | :doc_line | doc_cons_t | doc_nest_t | doc_break_t | doc_group_t | binary defrecordp :doc_cons, left: :doc_nil :: t, right: :doc_nil :: t defrecordp :doc_nest, indent: 1 :: non_neg_integer, doc: :doc_nil :: t defrecordp :doc_break, str: " " :: binary defrecordp :doc_group, doc: :doc_nil :: t defmacrop is_doc(doc) do if __CALLER__.in_guard? do do_is_doc(doc) else var = quote do: doc quote do unquote(var) = unquote(doc) unquote(do_is_doc(var)) end end end defp do_is_doc(doc) do quote do is_binary(unquote(doc)) or unquote(doc) in [:doc_nil, :doc_line] or (is_tuple(unquote(doc)) and elem(unquote(doc), 0) in [:doc_cons, :doc_nest, :doc_break, :doc_group]) end end @doc """ Converts an Elixir structure to an algebra document according to the inspect protocol. """ @spec to_doc(any, Inspect.Opts.t) :: t def to_doc(arg, opts) when is_record(opts, Inspect.Opts) do if is_tuple(arg) do if elem(opts, Inspect.Opts.__record__(:index, :records)) do try do Inspect.inspect(arg, opts) catch _, _ -> Inspect.Tuple.inspect(arg, opts) end else Inspect.Tuple.inspect(arg, opts) end else Inspect.inspect(arg, opts) end end @doc """ Returns `:doc_nil` which is a document entity used to represent nothingness. Takes no arguments. ## Examples iex> Inspect.Algebra.empty :doc_nil """ @spec empty() :: :doc_nil def empty, do: :doc_nil @doc """ Concatenates two document entities. Takes two arguments: left doc and right doc. Returns a DocCons doc ## Examples iex> doc = Inspect.Algebra.concat "Tasteless", "Artosis" iex> Inspect.Algebra.pretty(doc, 80) "TastelessArtosis" """ @spec concat(t, t) :: doc_cons_t def concat(x, y) when is_doc(x) and is_doc(y) do doc_cons(left: x, right: y) end @doc """ Concatenates a list of documents. """ @spec concat([t]) :: doc_cons_t def concat(docs) do folddoc(docs, &concat(&1, &2)) end @doc """ Nests document entity `x` positions deep. Nesting will be appended to the line breaks. ## Examples iex> doc = Inspect.Algebra.nest(Inspect.Algebra.concat(Inspect.Algebra.break, "6"), 5) iex> Inspect.Algebra.pretty(doc, 80) " 6" """ @spec nest(t, non_neg_integer) :: doc_nest_t def nest(x, 0) when is_doc(x) do x end def nest(x, i) when is_doc(x) and is_integer(i) do doc_nest(indent: i, doc: x) end @doc %S""" Document entity representing a break. This break can be rendered as a linebreak or as spaces, depending on the `mode` of the chosen layout or the provided separator. ## Examples Let's glue two docs together with a break and then render it: iex> doc = Inspect.Algebra.glue("a", " ", "b") iex> Inspect.Algebra.pretty(doc, 80) "a b" Notice the break was represented as is, because we haven't reached a line limit. Once we do, it is replaced by a newline: iex> doc = Inspect.Algebra.glue(String.duplicate("a", 20), " ", "b") iex> Inspect.Algebra.pretty(doc, 10) "aaaaaaaaaaaaaaaaaaaa\nb" """ @spec break(binary) :: doc_break_t def break(s) when is_binary(s), do: doc_break(str: s) @spec break() :: doc_break_t def break(), do: doc_break(str: @break) @doc """ Inserts a break between two docs. See `break/1` for more info. """ @spec glue(t, t) :: doc_cons_t def glue(x, y), do: concat(x, concat(break, y)) @doc """ Inserts a break, passed as the second argument, between two docs, the first and the third arguments. """ @spec glue(t, binary, t) :: doc_cons_t def glue(x, g, y) when is_binary(g), do: concat(x, concat(break(g), y)) @doc %S""" Returns a group containing the specified document. ## Examples iex> doc = Inspect.Algebra.group( ...> Inspect.Algebra.concat( ...> Inspect.Algebra.group( ...> Inspect.Algebra.concat( ...> "Hello,", ...> Inspect.Algebra.concat( ...> Inspect.Algebra.break, ...> "A" ...> ) ...> ) ...> ), ...> Inspect.Algebra.concat( ...> Inspect.Algebra.break, ...> "B" ...> ) ...> )) iex> Inspect.Algebra.pretty(doc, 80) "Hello, A B" iex> Inspect.Algebra.pretty(doc, 6) "Hello,\nA B" """ @spec group(t) :: doc_group_t def group(d) when is_doc(d) do doc_group(doc: d) end @doc """ Inserts a mandatory single space between two document entities. ## Examples iex> doc = Inspect.Algebra.space "Hughes", "Wadler" iex> Inspect.Algebra.pretty(doc, 80) "<NAME>" """ @spec space(t, t) :: doc_cons_t def space(x, y), do: concat(x, concat(" ", y)) @doc %S""" Inserts a mandatory linebreak between two document entities. ## Examples iex> doc = Inspect.Algebra.line "Hughes", "Wadler" iex> Inspect.Algebra.pretty(doc, 80) "Hughes\nWadler" """ @spec line(t, t) :: doc_cons_t def line(x, y), do: concat(x, concat(:doc_line, y)) @doc """ Folds a list of document entities into a document entity using a function that is passed as the first argument. ## Examples iex> doc = ["A", "B"] iex> doc = Inspect.Algebra.folddoc(doc, fn(x,y) -> ...> Inspect.Algebra.concat [x, "!", y] ...> end) iex> Inspect.Algebra.pretty(doc, 80) "A!B" """ @spec folddoc([t], ((t, t) -> t)) :: t def folddoc([], _), do: empty def folddoc([doc], _), do: doc def folddoc([d|ds], f), do: f.(d, folddoc(ds, f)) # Elixir conveniences @doc %S""" Surrounds a document with characters. Puts the document between left and right enclosing and nesting it. The document is marked as a group, to show the maximum as possible concisely together. ## Examples iex> doc = Inspect.Algebra.surround "[", Inspect.Algebra.glue("a", "b"), "]" iex> Inspect.Algebra.pretty(doc, 3) "[a\n b]" """ @spec surround(binary, t, binary) :: t def surround(left, doc, right) do group concat left, concat(nest(doc, @nesting), right) end @doc %S""" Maps and glues a collection of items together using the given separator and surrounds them. A limit can be passed which, once reached, stops gluing and outputs "..." instead. ## Examples iex> doc = Inspect.Algebra.surround_many("[", Enum.to_list(1..5), "]", :infinity, &integer_to_binary(&1)) iex> Inspect.Algebra.pretty(doc, 5) "[1,\n 2,\n 3,\n 4,\n 5]" iex> doc = Inspect.Algebra.surround_many("[", Enum.to_list(1..5), "]", 3, &integer_to_binary(&1)) iex> Inspect.Algebra.pretty(doc, 20) "[1, 2, 3, ...]" iex> doc = Inspect.Algebra.surround_many("[", Enum.to_list(1..5), "]", 3, &integer_to_binary(&1), "!") iex> Inspect.Algebra.pretty(doc, 20) "[1! 2! 3! ...]" """ @spec surround_many(binary, [any], binary, integer | :infinity, (term -> t), binary) :: t def surround_many(left, docs, right, limit, fun, separator \\ @surround_separator) def surround_many(left, [], right, _, _fun, _) do concat(left, right) end def surround_many(left, docs, right, limit, fun, sep) do surround(left, surround_many(docs, limit, fun, sep), right) end defp surround_many(_, 0, _fun, _sep) do "..." end defp surround_many([h], _limit, fun, _sep) do fun.(h) end defp surround_many([h|t], limit, fun, sep) when is_list(t) do glue( concat(fun.(h), sep), surround_many(t, decrement(limit), fun, sep) ) end defp surround_many([h|t], _limit, fun, _sep) do glue( concat(fun.(h), @tail_separator), fun.(t) ) end defp decrement(:infinity), do: :infinity defp decrement(counter), do: counter - 1 @doc """ The pretty printing function. Takes the maximum width and a document to print as its arguments and returns the string representation of the best layout for the document to fit in the given width. """ @spec pretty(t, non_neg_integer | :infinity) :: binary def pretty(d, w) do sdoc = format w, 0, [{0, default_mode(w), doc_group(doc: d)}] render(sdoc) end defp default_mode(:infinity), do: :flat defp default_mode(_), do: :break # Rendering and internal helpers # Record representing the document mode to be rendered: flat or broken @typep mode :: :flat | :break @doc false @spec fits?(integer, [{ integer, mode, t }]) :: boolean def fits?(w, _) when w < 0, do: false def fits?(_, []), do: true def fits?(_, [{_, _, :doc_line} | _]), do: true def fits?(w, [{_, _, :doc_nil} | t]), do: fits?(w, t) def fits?(w, [{i, m, doc_cons(left: x, right: y)} | t]), do: fits?(w, [{i, m, x} | [{i, m, y} | t]]) def fits?(w, [{i, m, doc_nest(indent: j, doc: x)} | t]), do: fits?(w, [{i + j, m, x} | t]) def fits?(w, [{i, _, doc_group(doc: x)} | t]), do: fits?(w, [{i, :flat, x} | t]) def fits?(w, [{_, _, s} | t]) when is_binary(s), do: fits?((w - byte_size s), t) def fits?(w, [{_, :flat, doc_break(str: s)} | t]), do: fits?((w - byte_size s), t) def fits?(_, [{_, :break, doc_break(str: _)} | _]), do: true @doc false @spec format(integer | :infinity, integer, [{ integer, mode, t }]) :: [binary] def format(_, _, []), do: [] def format(w, _, [{i, _, :doc_line} | t]), do: [indent(i) | format(w, i, t)] def format(w, k, [{_, _, :doc_nil} | t]), do: format(w, k, t) def format(w, k, [{i, m, doc_cons(left: x, right: y)} | t]), do: format(w, k, [{i, m, x} | [{i, m, y} | t]]) def format(w, k, [{i, m, doc_nest(indent: j, doc: x)} | t]), do: format(w, k, [{i + j, m, x} | t]) def format(w, k, [{i, m, doc_group(doc: x)} | t]), do: format(w, k, [{i, m, x} | t]) def format(w, k, [{_, _, s} | t]) when is_binary(s), do: [s | format(w, (k + byte_size s), t)] def format(w, k, [{_, :flat, doc_break(str: s)} | t]), do: [s | format(w, (k + byte_size s), t)] def format(w, k, [{i, :break, doc_break(str: s)} | t]) do k = k + byte_size(s) if w == :infinity or fits?(w - k, t) do [s | format(w, k, t)] else [indent(i) | format(w, i, t)] end end defp indent(0), do: @newline defp indent(i), do: @newline <> :binary.copy(" ", i) @doc false @spec render([binary]) :: binary def render(sdoc) do iolist_to_binary sdoc end end
lib/elixir/lib/inspect/algebra.ex
0.893872
0.741323
algebra.ex
starcoder
defmodule Set do @moduledoc ~S""" This module specifies the Set API expected to be implemented by different representations. It also provides functions that redirect to the underlying Set, allowing a developer to work with different Set implementations using one API. To create a new set, use the `new` functions defined by each set type: HashSet.new #=> creates an empty HashSet In the examples below, `set_impl` means a specific `Set` implementation, for example `HashSet`. ## Protocols Sets are required to implement both `Enumerable` and `Collectable` protocols. ## Match Sets are required to implement all operations using the match (`===`) operator. """ use Behaviour @type value :: any @type values :: [ value ] @type t :: map defcallback new :: t defcallback delete(t, value) :: t defcallback difference(t, t) :: t defcallback disjoint?(t, t) :: boolean defcallback equal?(t, t) :: boolean defcallback intersection(t, t) :: t defcallback member?(t, value) :: boolean defcallback put(t, value) :: t defcallback size(t) :: non_neg_integer defcallback subset?(t, t) :: boolean defcallback to_list(t) :: list() defcallback union(t, t) :: t defmacrop target(set) do quote do case unquote(set) do %{__struct__: x} when is_atom(x) -> x x -> unsupported_set(x) end end end @doc """ Deletes `value` from `set`. ## Examples iex> s = Enum.into([1, 2, 3], set_impl.new) iex> Set.delete(s, 4) |> Enum.sort [1, 2, 3] iex> s = Enum.into([1, 2, 3], set_impl.new) iex> Set.delete(s, 2) |> Enum.sort [1, 3] """ @spec delete(t, value) :: t def delete(set, value) do target(set).delete(set, value) end @doc """ Returns a set that is `set1` without the members of `set2`. Notice this function is polymorphic as it calculates the difference for of any type. Each set implementation also provides a `difference` function, but they can only work with sets of the same type. ## Examples iex> Set.difference(Enum.into([1, 2], set_impl.new), Enum.into([2, 3, 4], set_impl.new)) |> Enum.sort [1] """ @spec difference(t, t) :: t def difference(set1, set2) do target1 = target(set1) target2 = target(set2) if target1 == target2 do target1.difference(set1, set2) else target2.reduce(set2, {:cont, set1}, fn v, acc -> {:cont, target1.delete(acc, v)} end) |> elem(1) end end @doc """ Checks if `set1` and `set2` have no members in common. Notice this function is polymorphic as it checks for disjoint sets of any type. Each set implementation also provides a `disjoint?` function, but they can only work with sets of the same type. ## Examples iex> Set.disjoint?(Enum.into([1, 2], set_impl.new), Enum.into([3, 4], set_impl.new)) true iex> Set.disjoint?(Enum.into([1, 2], set_impl.new), Enum.into([2, 3], set_impl.new)) false """ @spec disjoint?(t, t) :: boolean def disjoint?(set1, set2) do target1 = target(set1) target2 = target(set2) if target1 == target2 do target1.disjoint?(set1, set2) else target2.reduce(set2, {:cont, true}, fn member, acc -> case target1.member?(set1, member) do false -> {:cont, acc} _ -> {:halt, false} end end) |> elem(1) end end @doc false @spec empty(t) :: t def empty(set) do target(set).empty(set) end @doc """ Checks if two sets are equal using `===`. Notice this function is polymorphic as it compares sets of any type. Each set implementation also provides an `equal?` function, but they can only work with sets of the same type. ## Examples iex> Set.equal?(Enum.into([1, 2], set_impl.new), Enum.into([2, 1, 1], set_impl.new)) true iex> Set.equal?(Enum.into([1, 2], set_impl.new), Enum.into([3, 4], set_impl.new)) false """ @spec equal?(t, t) :: boolean def equal?(set1, set2) do target1 = target(set1) target2 = target(set2) cond do target1 == target2 -> target1.equal?(set1, set2) target1.size(set1) == target2.size(set2) -> do_subset?(target1, target2, set1, set2) true -> false end end @doc """ Returns a set containing only members in common between `set1` and `set2`. Notice this function is polymorphic as it calculates the intersection of any type. Each set implementation also provides a `intersection` function, but they can only work with sets of the same type. ## Examples iex> Set.intersection(Enum.into([1, 2], set_impl.new), Enum.into([2, 3, 4], set_impl.new)) |> Enum.sort [2] iex> Set.intersection(Enum.into([1, 2], set_impl.new), Enum.into([3, 4], set_impl.new)) |> Enum.sort [] """ @spec intersection(t, t) :: t def intersection(set1, set2) do target1 = target(set1) target2 = target(set2) if target1 == target2 do target1.intersection(set1, set2) else target1.reduce(set1, {:cont, target1.new}, fn v, acc -> {:cont, if(target2.member?(set2, v), do: target1.put(acc, v), else: acc)} end) |> elem(1) end end @doc """ Checks if `set` contains `value`. ## Examples iex> Set.member?(Enum.into([1, 2, 3], set_impl.new), 2) true iex> Set.member?(Enum.into([1, 2, 3], set_impl.new), 4) false """ @spec member?(t, value) :: boolean def member?(set, value) do target(set).member?(set, value) end @doc """ Inserts `value` into `set` if it does not already contain it. ## Examples iex> Set.put(Enum.into([1, 2, 3], set_impl.new), 3) |> Enum.sort [1, 2, 3] iex> Set.put(Enum.into([1, 2, 3], set_impl.new), 4) |> Enum.sort [1, 2, 3, 4] """ @spec put(t, value) :: t def put(set, value) do target(set).put(set, value) end @doc """ Returns the number of elements in `set`. ## Examples iex> Set.size(Enum.into([1, 2, 3], set_impl.new)) 3 """ @spec size(t) :: non_neg_integer def size(set) do target(set).size(set) end @doc """ Checks if `set1`'s members are all contained in `set2`. Notice this function is polymorphic as it checks the subset for any type. Each set implementation also provides a `subset?` function, but they can only work with sets of the same type. ## Examples iex> Set.subset?(Enum.into([1, 2], set_impl.new), Enum.into([1, 2, 3], set_impl.new)) true iex> Set.subset?(Enum.into([1, 2, 3], set_impl.new), Enum.into([1, 2], set_impl.new)) false """ @spec subset?(t, t) :: boolean def subset?(set1, set2) do target1 = target(set1) target2 = target(set2) if target1 == target2 do target1.subset?(set1, set2) else do_subset?(target1, target2, set1, set2) end end @doc """ Converts `set` to a list. ## Examples iex> set_impl.to_list(Enum.into([1, 2, 3], set_impl.new)) |> Enum.sort [1, 2, 3] """ @spec to_list(t) :: list def to_list(set) do target(set).to_list(set) end @doc """ Returns a set containing all members of `set1` and `set2`. Notice this function is polymorphic as it calculates the union of any type. Each set implementation also provides a `union` function, but they can only work with sets of the same type. ## Examples iex> Set.union(Enum.into([1, 2], set_impl.new), Enum.into([2, 3, 4], set_impl.new)) |> Enum.sort [1, 2, 3, 4] """ @spec union(t, t) :: t def union(set1, set2) do target1 = target(set1) target2 = target(set2) if target1 == target2 do target1.union(set1, set2) else target2.reduce(set2, {:cont, set1}, fn v, acc -> {:cont, target1.put(acc, v)} end) |> elem(1) end end defp do_subset?(target1, target2, set1, set2) do target1.reduce(set1, {:cont, true}, fn member, acc -> case target2.member?(set2, member) do true -> {:cont, acc} _ -> {:halt, false} end end) |> elem(1) end defp unsupported_set(set) do raise ArgumentError, "unsupported set: #{inspect set}" end end
lib/elixir/lib/set.ex
0.932599
0.633127
set.ex
starcoder
defmodule Day2 do @input "priv/inputs/day2.txt" defp get_input(), do: File.read!(@input) def part1() do get_input() |> get_program() |> compute() end def part2(implementation \\ :beam) do get_input() |> get_program() |> get_params(19690720, implementation) end defp get_program(input) do input |> String.split(",", trim: true) |> Enum.map(&String.to_integer/1) end def compute(program, ip \\ 0) do {_, opcodes} = Enum.split(program, ip) case execute(opcodes, program) do {:ok, p} -> compute(p, ip + 4) {:stop, p} -> p end end def execute([99|_], program) do {:stop, program} end def execute([op, lidx, ridx, dst|_], program) do lhs = Enum.at(program, lidx) rhs = Enum.at(program, ridx) val = case op do 1 -> lhs + rhs 2 -> lhs * rhs end {:ok, replace(program, dst, val)} end defp replace(lst, idx, val) do {left, [_|right]} = Enum.split(lst, idx) left ++ [val|right] end def get_params(program, expected, :comprehension) do try do for noun <- 1..99, verb <- 1..99 do program = replace(program, 1, noun) program = replace(program, 2, verb) case compute(program) do [actual|_] when actual == expected -> throw({:noun, noun, :verb, verb, :result, actual}) _ -> :noop end end catch x -> x end end def get_params(program, expected, :beam) do pid = self() for noun <- 1..99, verb <- 1..99 do spawn fn -> program = replace(program, 1, noun) program = replace(program, 2, verb) case compute(program) do [actual|_] when actual == expected -> send pid, {:noun, noun, :verb, verb, :result, actual} other -> other end end end receive do {:noun, noun, :verb, verb, :result, actual} -> {:noun, noun, :verb, verb, :result, actual} after 5_000 -> {:error, :cannot_find_solution} end end def get_params(program, expected, :recursion) do get_params_rec(program, expected, 1, 1) end defp get_params_rec(_, _, 99, 100) do {:error, :cannot_find_solution} end defp get_params_rec(program, expected, noun, 100) do get_params_rec(program, expected, noun + 1, 1) end defp get_params_rec(program, expected, noun, verb) do program = replace(program, 1, noun) program = replace(program, 2, verb) case compute(program) do [actual|_] when actual == expected -> {:noun, noun, :verb, verb, :result, actual} _ -> get_params_rec(program, expected, noun, verb+1) end end end
lib/Day2.ex
0.593963
0.460653
Day2.ex
starcoder
defmodule Benchee.Formatters.TaggedSave do @moduledoc """ Store the whole suite in the Erlang `ExternalTermFormat` while tagging the scenarios of the current run with a specified tag - can be used for storing and later loading the results of previous runs with `Benchee.ScenarioLoader`. Automatically configured as the last formatter to run when specifying the `save` option in the configuration - see `Benchee.Configuration`. """ @behaviour Benchee.Formatter alias Benchee.Scenario alias Benchee.Suite alias Benchee.Utility.FileCreation @doc """ Tags all scenario with the desired tag and returns it in term_to_binary along with save path. """ @impl true @spec format(Suite.t(), map) :: {binary, String.t()} def format(suite = %Suite{scenarios: scenarios}, formatter_config) do tag = determine_tag(scenarios, formatter_config) tagged_scenarios = tag_scenarios(scenarios, tag) tagged_suite = %Suite{suite | scenarios: tagged_scenarios} {:erlang.term_to_binary(tagged_suite), formatter_config.path} end defp determine_tag(scenarios, %{tag: desired_tag}) do scenarios |> Enum.map(fn scenario -> scenario.tag end) |> Enum.uniq() |> Enum.filter(fn tag -> tag != nil && tag =~ ~r/#{Regex.escape(desired_tag)}/ end) |> choose_tag(desired_tag) end defp choose_tag([], desired_tag), do: desired_tag defp choose_tag(tags, desired_tag) do max = get_maximum_tag_increaser(tags, desired_tag) "#{desired_tag}-#{max + 1}" end defp get_maximum_tag_increaser(tags, desired_tag) do tags |> Enum.map(fn tag -> String.replace(tag, ~r/#{Regex.escape(desired_tag)}-?/, "") end) |> Enum.map(&tag_increaser/1) |> Enum.max() end defp tag_increaser(""), do: 1 defp tag_increaser(string_number), do: String.to_integer(string_number) defp tag_scenarios(scenarios, tag) do Enum.map(scenarios, fn scenario -> scenario |> tagged_scenario(tag) |> update_name end) end defp tagged_scenario(scenario = %Scenario{tag: nil}, desired_tag) do %Scenario{scenario | tag: desired_tag} end defp tagged_scenario(scenario, _desired_tag) do scenario end defp update_name(scenario) do %Scenario{scenario | name: Scenario.display_name(scenario)} end @doc """ Writes the binary returned by `format/2` to the indicated location, telling you where that is. """ @spec write({binary, String.t()}, map) :: :ok @impl true def write({term_binary, filename}, _) do FileCreation.ensure_directory_exists(filename) return_value = File.write(filename, term_binary) IO.puts("Suite saved in external term format at #{filename}") return_value end end
lib/benchee/formatters/tagged_save.ex
0.86757
0.506713
tagged_save.ex
starcoder
defmodule OffBroadwayOtpDistribution.Client do @doc """ A base module for implementing the client for `OffBroadwayOtpDistribution.Receiver`. ## Example The client process implemented using this module communicates to the receiver process implemented as `OffBroadwayOtpDistribution.Receiver` via message passings each other. If the producer implemented as `OffBroadwayOtpDistribution.Producer` runs on `:pull` mode and the demand it has is not fully met, it sends `:pull_message` message to the client via the receiver. You must implement a callback for the message if the producer runs on `:pull` mode. If the producer runs on `:push` mode, you can freely push a message regardless of whether the Broadway producer has demand or not. ``` defmodule ExamplesClient do use OffBroadwayOtpDistribution.Client @impl GenServer def handle_cast(:pull_message, state) do Logger.debug("received: :pull_message") GenServer.cast(state.receiver, {:send_message, "I'm alive!"}) {:noreply, state} end @impl GenServer def handle_cast({:push_message, message}, state) do GenServer.cast(state.receiver, {:push_message, message}) {:noreply, state} end def start(opts \\ []) do [ {__MODULE__, opts} ] |> Supervisor.start_link( strategy: :one_for_one, name: ExamplesClient.Supervisor ) end def push_message(message) do GenServer.cast(__MODULE__, {:push_message, message}) end end ``` """ defmacro __using__(_opts) do quote do use GenServer require Logger @default_receiver_name :off_broadway_otp_distribution_receiver @default_max_retry_count 10 @impl GenServer def init(opts \\ []) do receiver_name = opts[:receiver_name] || @default_receiver_name max_retry_count = opts[:max_retry_count] || @default_max_retry_count receiver = connect_to_receiver(receiver_name, max_retry_count) {:ok, %{ receiver: receiver }} end def start_link(opts \\ []) do GenServer.start_link(__MODULE__, opts, name: __MODULE__) end @impl GenServer def handle_info({:DOWN, _, _, _, reason}, state) do Logger.error("Server is down: #{reason}") {:noreply, %{state | receiver: nil}} end @impl GenServer def terminate(reason, state) do Logger.error("Client is terminating: #{inspect(reason)}") end defp connect_to_receiver(receiver_name, retry_count) do receiver = try_connect_to_receiver(receiver_name, retry_count) GenServer.call(receiver, :register) Logger.info("Register this client to #{inspect(receiver)}") # To reboot this process when the receiver process terminates Process.monitor(receiver) receiver end defp try_connect_to_receiver(receiver_name, retry_count) do if retry_count > 0 do :global.sync() receiver = :global.whereis_name(receiver_name) if receiver == :undefined do Logger.debug("Waiting for the receiver is up.") Process.sleep(500) try_connect_to_receiver(receiver_name, retry_count - 1) else receiver end else raise("Couldn't connect to #{receiver_name}") end end end end end
lib/off_broadway_otp_distribution/client.ex
0.877
0.668701
client.ex
starcoder
defmodule Rummage.Ecto.Hooks.Sort do @moduledoc """ `Rummage.Ecto.Hooks.Sort` is the default sort hook that comes shipped with `Rummage.Ecto`. Usage: For a regular sort: This returns a `queryable` which upon running will give a list of `Parent`(s) sorted by ascending `field_1` ```elixir alias Rummage.Ecto.Hooks.Sort sorted_queryable = Sort.run(Parent, %{"sort" => %{"assoc" => [], "field" => "field_1.asc"}}) ``` For a case-insensitive sort: This returns a `queryable` which upon running will give a list of `Parent`(s) sorted by ascending case insensitive `field_1`. Keep in mind that `case_insensitive` can only be called for `text` fields ```elixir alias Rummage.Ecto.Hooks.Sort sorted_queryable = Sort.run(Parent, %{"sort" => %{"assoc" => [], "field" => "field_1.asc.ci"}}) ``` This module can be overridden with a custom module while using `Rummage.Ecto` in `Ecto` struct module. In the `Ecto` module: ```elixir Rummage.Ecto.rummage(queryable, rummage, sort: CustomHook) ``` OR Globally for all models in `config.exs`: ```elixir config :rummage_ecto, Rummage.Ecto, default_sort: CustomHook ``` The `CustomHook` must implement behaviour `Rummage.Ecto.Hook`. For examples of `CustomHook`, check out some `custom_hooks` that are shipped with elixir: `Rummage.Ecto.CustomHooks.SimpleSearch`, `Rummage.Ecto.CustomHooks.SimpleSort`, Rummage.Ecto.CustomHooks.SimplePaginate """ import Ecto.Query @behaviour Rummage.Ecto.Hook @doc """ Builds a sort `queryable` on top of the given `queryable` from the rummage parameters from the given `rummage` struct. ## Examples When rummage `struct` passed doesn't have the key `"sort"`, it simply returns the `queryable` itself: iex> alias Rummage.Ecto.Hooks.Sort iex> import Ecto.Query iex> Sort.run(Parent, %{}) Parent When the `queryable` passed is not just a `struct`: iex> alias Rummage.Ecto.Hooks.Sort iex> import Ecto.Query iex> queryable = from u in "parents" #Ecto.Query<from p in "parents"> iex> Sort.run(queryable, %{}) #Ecto.Query<from p in "parents"> When rummage `struct` passed has the key `"sort"`, but with a value of `{}`, `""` or `[]` it simply returns the `queryable` itself: iex> alias Rummage.Ecto.Hooks.Sort iex> import Ecto.Query iex> Sort.run(Parent, %{"sort" => {}}) Parent iex> alias Rummage.Ecto.Hooks.Sort iex> import Ecto.Query iex> Sort.run(Parent, %{"sort" => ""}) Parent iex> alias Rummage.Ecto.Hooks.Sort iex> import Ecto.Query iex> Sort.run(Parent, %{"sort" => %{}}) Parent When rummage `struct` passed has the key `"sort"`, but empty associations array it just orders it by the passed `queryable`: iex> alias Rummage.Ecto.Hooks.Sort iex> import Ecto.Query iex> rummage = %{"sort" => %{"assoc" => [], "field" => "field_1.asc"}} %{"sort" => %{"assoc" => [], "field" => "field_1.asc"}} iex> queryable = from u in "parents" #Ecto.Query<from p in "parents"> iex> Sort.run(queryable, rummage) #Ecto.Query<from p in subquery(from p in "parents"), order_by: [asc: p.field_1]> iex> alias Rummage.Ecto.Hooks.Sort iex> import Ecto.Query iex> rummage = %{"sort" => %{"assoc" => [], "field" => "field_1.desc"}} %{"sort" => %{"assoc" => [], "field" => "field_1.desc"}} iex> queryable = from u in "parents" #Ecto.Query<from p in "parents"> iex> Sort.run(queryable, rummage) #Ecto.Query<from p in subquery(from p in "parents"), order_by: [desc: p.field_1]> When no `order` is specified, it returns the `queryable` itself: iex> alias Rummage.Ecto.Hooks.Sort iex> import Ecto.Query iex> rummage = %{"sort" => %{"assoc" => [], "field" => "field_1"}} %{"sort" => %{"assoc" => [], "field" => "field_1"}} iex> queryable = from u in "parents" #Ecto.Query<from p in "parents"> iex> Sort.run(queryable, rummage) #Ecto.Query<from p in subquery(from p in "parents")> When rummage `struct` passed has the key `"sort"`, with `field` and `order` it returns a sorted version of the `queryable` passed in as the argument: iex> alias Rummage.Ecto.Hooks.Sort iex> import Ecto.Query iex> rummage = %{"sort" => %{"assoc" => ["parent", "parent"], "field" => "field_1.asc"}} %{"sort" => %{"assoc" => ["parent", "parent"], "field" => "field_1.asc"}} iex> queryable = from u in "parents" #Ecto.Query<from p in "parents"> iex> Sort.run(queryable, rummage) #Ecto.Query<from p0 in subquery(from p in "parents"), join: p1 in assoc(p0, :parent), join: p2 in assoc(p1, :parent), order_by: [asc: p2.field_1]> iex> alias Rummage.Ecto.Hooks.Sort iex> import Ecto.Query iex> rummage = %{"sort" => %{"assoc" => ["parent", "parent"], "field" => "field_1.desc"}} %{"sort" => %{"assoc" => ["parent", "parent"], "field" => "field_1.desc"}} iex> queryable = from u in "parents" #Ecto.Query<from p in "parents"> iex> Sort.run(queryable, rummage) #Ecto.Query<from p0 in subquery(from p in "parents"), join: p1 in assoc(p0, :parent), join: p2 in assoc(p1, :parent), order_by: [desc: p2.field_1]> When no `order` is specified even with the associations, it returns the `queryable` itself: iex> alias Rummage.Ecto.Hooks.Sort iex> import Ecto.Query iex> rummage = %{"sort" => %{"assoc" => ["parent", "parent"], "field" => "field_1"}} %{"sort" => %{"assoc" => ["parent", "parent"], "field" => "field_1"}} iex> queryable = from u in "parents" #Ecto.Query<from p in "parents"> iex> Sort.run(queryable, rummage) #Ecto.Query<from p0 in subquery(from p in "parents"), join: p1 in assoc(p0, :parent), join: p2 in assoc(p1, :parent)> When rummage `struct` passed has `case-insensitive` sort, it returns a sorted version of the `queryable` with `case_insensitive` arguments: iex> alias Rummage.Ecto.Hooks.Sort iex> import Ecto.Query iex> rummage = %{"sort" => %{"assoc" => ["parent", "parent"], "field" => "field_1.asc.ci"}} %{"sort" => %{"assoc" => ["parent", "parent"], "field" => "field_1.asc.ci"}} iex> queryable = from u in "parents" #Ecto.Query<from p in "parents"> iex> Sort.run(queryable, rummage) #Ecto.Query<from p0 in subquery(from p in "parents"), join: p1 in assoc(p0, :parent), join: p2 in assoc(p1, :parent), order_by: [asc: fragment("lower(?)", p2.field_1)]> """ @spec run(Ecto.Query.t(), map) :: {Ecto.Query.t(), map} def run(queryable, rummage) do case Map.get(rummage, "sort") do a when a in [nil, [], {}, [""], "", %{}] -> queryable sort_params -> sort_params = case sort_params["assoc"] do s when s in [nil, ""] -> Map.put(sort_params, "assoc", []) _ -> sort_params end case Regex.match?(~r/\w.ci+$/, sort_params["field"]) do true -> order_param = sort_params["field"] |> String.split(".") |> Enum.drop(-1) |> Enum.join(".") sort_params = {sort_params["assoc"], order_param} handle_sort(queryable, sort_params, true) _ -> handle_sort(queryable, {sort_params["assoc"], sort_params["field"]}) end end end @doc """ Implementation of `before_hook` for `Rummage.Ecto.Hooks.Sort`. This just returns back `rummage` at this point. It doesn't matter what `queryable` or `opts` are, it just returns back `rummage`. ## Examples iex> alias Rummage.Ecto.Hooks.Sort iex> Sort.before_hook(Parent, %{}, %{}) %{} """ @spec before_hook(Ecto.Query.t(), map, map) :: map def before_hook(_queryable, rummage, _opts), do: rummage defp handle_sort(queryable, sort_params, ci \\ false) do order_param = sort_params |> elem(1) association_names = sort_params |> elem(0) queryable = from(e in subquery(queryable)) association_names |> Enum.reduce(queryable, &join_by_association(&1, &2)) |> handle_ordering(order_param, ci) end defmacrop case_insensitive(field) do quote do fragment("lower(?)", unquote(field)) end end # defp applied_associations(queryable) when is_atom(queryable), do: [] # defp applied_associations(queryable), do: Enum.map(queryable.joins, & Atom.to_string(elem(&1.assoc, 1))) defp handle_ordering(queryable, order_param, ci) do case Regex.match?(~r/\w.asc+$/, order_param) or Regex.match?(~r/\w.desc+$/, order_param) do true -> parsed_field = order_param |> String.split(".") |> Enum.drop(-1) |> Enum.join(".") order_type = order_param |> String.split(".") |> Enum.at(-1) queryable |> order_by_assoc(order_type, parsed_field, ci) _ -> queryable end end defp join_by_association(association, queryable) do join(queryable, :inner, [..., p1], p2 in assoc(p1, ^String.to_atom(association))) end defp order_by_assoc(queryable, order_type, parsed_field, false) do order_by(queryable, [p0, ..., p2], [ {^String.to_atom(order_type), field(p2, ^String.to_atom(parsed_field))} ]) end defp order_by_assoc(queryable, order_type, parsed_field, true) do order_by(queryable, [p0, ..., p2], [ {^String.to_atom(order_type), case_insensitive(field(p2, ^String.to_atom(parsed_field)))} ]) end end
lib/rummage_ecto/hooks/sort.ex
0.780871
0.852199
sort.ex
starcoder
defmodule Optimal.Doc do @moduledoc """ Automatic opt documentation, to be placed into your function docstrings """ alias Optimal.Schema @document_opts Optimal.schema( opts: [name: :string, header_depth: :int], defaults: [name: "Opts", header_depth: 1], describe: [ name: "The top level header for the opts documentation", header_depth: "How many `#` to prepend before any heading" ] ) # These opts cannot be auto-documented, so must be regenerated manually @doc """ --- ## Opts * `name`(`:string`): The top level header for the opts documentation - Default: "Opts" * `header_depth`(`:int`): How many `#` to prepend before any heading - Default: 1 --- """ @spec document(schema :: Optimal.schema(), doc_opts :: Keyword.t()) :: String.t() def document(schema, doc_opts \\ []) def document(%Schema{opts: [], extra_keys?: false}, doc_opts) do doc_opts = Optimal.validate!(doc_opts, @document_opts) "---\n" <> header(1, doc_opts[:header_depth]) <> doc_opts[:name] <> "\n\nAccepts no options.\n" <> "---" end def document(%Schema{opts: [], extra_keys?: true}, doc_opts) do doc_opts = Optimal.validate!(doc_opts, @document_opts) "---\n" <> header(1, doc_opts[:header_depth]) <> doc_opts[:name] <> "\n\nAccepts any options.\n" <> "---" end def document(schema, doc_opts) do doc_opts = Optimal.validate!(doc_opts, @document_opts) prefix = "---\n" <> header(1, doc_opts[:header_depth]) <> doc_opts[:name] <> "\n\n" documented_opts = prefix <> document_opts(schema.opts, schema, doc_opts) <> "\n" with_extra_keys = if schema.extra_keys? do documented_opts <> "\nAlso accepts extra opts that are not named here.\n" else documented_opts end with_extra_keys <> "\n---" end defp document_opts([], _, _), do: "" defp document_opts(opts, schema, doc_opts) do opts |> Enum.group_by(fn opt -> schema.annotations[opt] end) |> Enum.sort_by(&elem(&1, 0)) |> Enum.map_join("\n", fn {annotation, opts} -> if annotation do "\n" <> header(3, doc_opts[:header_depth]) <> to_string(annotation) <> "\n\n" <> do_document_opts(opts, schema) else do_document_opts(opts, schema) end end) end defp do_document_opts(opts, schema) do opts |> Enum.sort_by(fn opt -> not (opt in schema.required) end) |> Enum.map_join("\n", fn opt -> string_opt = "`" <> Atom.to_string(opt) <> "`" string_type = "`" <> inspect(schema.types[opt]) <> "`" description = schema.describe[opt] required = if opt in schema.required do " **Required**" else "" end prefix = "* " <> string_opt <> "(" <> string_type <> ")" with_description_and_type = if description do prefix <> required <> ": " <> description else prefix <> required end if Keyword.has_key?(schema.defaults, opt) do with_description_and_type <> " - Default: " <> inspect(schema.defaults[opt]) else with_description_and_type end end) end defp header(depth, header_depth_opt), do: String.duplicate("#", header_depth_opt + depth) <> " " end
lib/optimal/doc.ex
0.75985
0.410549
doc.ex
starcoder
defmodule ComplexNum.Polar do # Uses the `real` part of the ComplexNum struct to store the `magnitude` # And uses the `imaginary` part of the ComplexNum struct to store the `angle`. alias ComplexNum.{Cartesian, Polar} alias Numbers, as: N @doc """ Creates a new Complex Numbers in Polar Form from the given `magnitude` and `angle`, which can be written as: `magnitude * e^{angle * i}` """ def new(magnitude, angle \\ 0) def new(magnitude, angle) when is_number(magnitude) and is_number(angle) do %ComplexNum{mode: Polar, real: magnitude, imaginary: angle} end def new(magnitude = %numeric{}, angle = %numeric{}) do %ComplexNum{mode: Polar, real: magnitude, imaginary: angle} end def new(magnitude = %numeric{}, angle) when is_number(angle) do %ComplexNum{mode: Polar, real: magnitude, imaginary: numeric.new(angle)} end def new(magnitude, angle = %numeric{}) when is_number(magnitude) do %ComplexNum{mode: Polar, real: numeric.new(magnitude), imaginary: angle} end @doc """ Retrieves the magnitude of the Complex Number in Polar form. For `r * e^(i * angle)` this is `r` This is a precise operation. (In stark contrast to computing the magnitude on a Complex Number in Cartesian form!) """ def magnitude(pa = %ComplexNum{mode: Polar}), do: pa.real def magnitude(number), do: number @doc """ Computes the square of the magnitude of the Complex number in Polar Form. For `r * e^(i * angle)` this is `r²` """ def magnitude_squared(pa = %ComplexNum{mode: Polar}), do: N.mult(pa.real, pa.real) @doc """ Retrieves the angle of the Complex number in Polar form. For `r * e^{i * angle}` this is `angle`. This is a precise operation. (In stark contrast to computing the magnitude on a Complex Number in Cartesian form!) """ def angle(pa = %ComplexNum{mode: Polar}), do: pa.imaginary def angle(number), do: number @doc """ Adds two Complex Numbers in Polar Form. This is a lossy operation, as the two numbers need first to both be converted to Cartesian Form, and the result is then converted back to Polar form. """ def add(pa = %ComplexNum{mode: Polar}, pb = %ComplexNum{mode: Polar}) do Cartesian.add(to_cartesian(pa), to_cartesian(pb)) |> Cartesian.to_polar end @doc """ Subtracts a Complex Number in Polar Form from another. This is a lossy operation, as the two numbers need first to both be converted to Cartesian Form, and the result is then converted back to Polar form. """ def sub(pa = %ComplexNum{mode: Polar}, pb = %ComplexNum{mode: Polar}) do Cartesian.sub(to_cartesian(pa), to_cartesian(pb)) |> Cartesian.to_polar end @doc """ Multiplies two Complex Numbers in Polar form. This is a precise and very fast operation: `(r1 * e^{i * angle1}) * (r2 * e^{i * angle2}) = (r1 * r2) * e^{i * (angle1 + angle2)}` """ def mult(pa = %ComplexNum{mode: Polar}, pb = %ComplexNum{mode: Polar}) do new(N.mult(pa.real, pb.real), N.add(pa.imaginary, pb.imaginary)) end @doc """ Divides a Complex Numbers in Polar form by another. This is a precise and very fast operation: `(r1 * e^{i * angle1}) / (r2 * e^{i * angle2}) = (r1 / r2) * e^{i * (angle1 - angle2)}` """ def div(pa = %ComplexNum{mode: Polar}, pb = %ComplexNum{mode: Polar}) do new(N.div(pa.real, pb.real), N.sub(pa.imaginary, pb.imaginary)) end @doc """ Integer exponentiation of a number in Polar form. This is a precise and very fast operation: `(r1 * e^{i * angle1}) ^ (r2 * e^{i * angle2}) = (r1^r2) * e^{i * (angle1 * angle2)}` """ def pow(pa = %ComplexNum{mode: Polar}, exponent) when is_integer(exponent) do new(N.pow(pa.real, exponent), N.mult(pa.imaginary, exponent)) end @doc """ Returns a Complex Number with the same magnitude as this one, but with the imaginary part being `0`. """ def abs(pa = %ComplexNum{mode: Polar}) do ComplexNum.new(pa.real, 0) end @doc """ Converts a Complex Number in Polar form to Cartesian form. This is a lossy operation, as `cos` and `sin` have to be used: """ def to_cartesian(pa = %ComplexNum{mode: Polar}) do real = N.mult(pa.real, :math.cos(N.to_float(pa.imaginary))) imaginary = N.mult(pa.real, :math.sin(N.to_float(pa.imaginary))) ComplexNum.new(real, imaginary) end end
lib/complex_num/polar.ex
0.942639
0.982757
polar.ex
starcoder
defmodule Bolt.Sips.Router do @moduledoc """ This "driver" works in tandem with Neo4j's [Causal Clustering](https://neo4j.com/docs/operations-manual/current/clustering/>) feature by directing read and write behaviour to appropriate cluster members """ use GenServer require Logger alias Bolt.Sips.Routing.RoutingTable alias Bolt.Sips.{Protocol, ConnectionSupervisor, LoadBalancer, Response, Error} defmodule State do @moduledoc """ todo: this is work in progress and will be used for defining the state of the Router (Gen)Server """ @type role :: atom @type t :: %__MODULE__{ connections: %{ role => %{String.t() => non_neg_integer}, updated_at: non_neg_integer, ttl: non_neg_integer } } @enforce_keys [:connections] defstruct @enforce_keys end @no_routing nil @routing_table_keys [:read, :write, :route, :updated_at, :ttl, :error] def configure(opts), do: GenServer.call(__MODULE__, {:configure, opts}) def get_connection(role, prefix \\ :direct) def get_connection(role, prefix), do: GenServer.call(__MODULE__, {:get_connection, role, prefix}) def terminate_connections(role, prefix \\ :default) def terminate_connections(role, prefix), do: GenServer.call(__MODULE__, {:terminate_connections, role, prefix}) def info(), do: GenServer.call(__MODULE__, :info) def routing_table(prefix), do: GenServer.call(__MODULE__, {:routing_table_info, prefix}) @spec start_link(Keyword.t()) :: :ignore | {:error, Keyword.t()} | {:ok, pid()} def start_link(init_args) do GenServer.start_link(__MODULE__, init_args, name: __MODULE__) end @impl true @spec init(Keyword.t()) :: {:ok, State.t(), {:continue, :post_init}} def init(options) do {:ok, options, {:continue, :post_init}} end @impl true def handle_call({:configure, opts}, _from, state) do prefix = Keyword.get(opts, :prefix, :default) %{connections: current_connections} = Map.get(state, prefix, %{connections: %{}}) %{user_options: user_options, connections: connections} = try do _configure(opts) # %{prefix => %{user_options: user_options, connections: connections}} |> Map.get(prefix) rescue e in Bolt.Sips.Exception -> %{user_options: opts, connections: %{error: e.message}} end updated_connections = Map.merge(current_connections, connections) new_state = Map.put(state, prefix, %{user_options: user_options, connections: updated_connections}) {:reply, new_state, new_state} end # getting connections for role in [:route, :read, :write] @impl true def handle_call({:get_connection, role, prefix}, _from, state) when role in [:route, :read, :write] do with %{connections: connections} <- Map.get(state, prefix), {:ok, conn, updated_connections} <- _get_connection(role, connections, prefix) do {:reply, {:ok, conn}, put_in(state, [prefix, :connections], updated_connections)} else e -> err_msg = error_no_connection_available_for_role(role, e, prefix) {:reply, {:error, err_msg}, state} end end # getting connections for any user defined roles, or: `:direct` @impl true def handle_call({:get_connection, role, prefix}, _from, state) do with %{connections: connections} <- Map.get(state, prefix), true <- Map.has_key?(connections, role), [url | _none] <- connections |> Map.get(role) |> Map.keys(), {:ok, pid} <- ConnectionSupervisor.find_connection(role, url, prefix) do {:reply, {:ok, pid}, state} else e -> err_msg = error_no_connection_available_for_role(role, e, prefix) {:reply, {:error, err_msg}, state} end end @impl true def handle_call({:terminate_connections, role, prefix}, _from, state) do %{connections: connections} = Map.get(state, prefix, %{}) with true <- Map.has_key?(connections, role), :ok <- connections |> Map.get(role) |> Map.keys() |> Enum.each(&ConnectionSupervisor.terminate_connection(role, &1, prefix)) do new_connections = Map.delete(connections, role) new_state = put_in(state, [prefix, :connections], new_connections) {:reply, :ok, new_state} else _e -> {:reply, {:error, :not_found}, state} end end @impl true def handle_call(:info, _from, state), do: {:reply, state, state} def handle_call({:routing_table_info, prefix}, _from, state) do routing_table = with connections when not is_nil(connections) <- get_in(state, [prefix, :connections]) do Map.take(connections, @routing_table_keys) end {:reply, routing_table, state} end @impl true @spec handle_continue(:post_init, Keyword.t()) :: {:noreply, map} def handle_continue(:post_init, opts), do: {:noreply, _configure(opts)} defp _configure(opts) do options = Bolt.Sips.Utils.default_config(opts) prefix = Keyword.get(options, :prefix, :default) ssl_or_sock = if(Keyword.get(options, :ssl), do: :ssl, else: Keyword.get(options, :socket)) user_options = Keyword.put(options, :socket, ssl_or_sock) with_routing? = Keyword.get(user_options, :schema, "bolt") =~ ~r/(^neo4j$)|(^bolt\+routing$)/i with {:ok, routing_table} <- get_routing_table(user_options, with_routing?), {:ok, connections} <- start_connections(user_options, routing_table) do connections = Map.put(connections, :routing_query, routing_table[:routing_query]) %{prefix => %{user_options: user_options, connections: connections}} else {:error, msg} -> Logger.error("cannot load the routing table. Error: #{msg}") %{prefix => %{user_options: user_options, connections: %{error: "Not a router"}}} end end defp get_routing_table( %{routing_query: %{params: props, query: query}} = connections, _, prefix ) do with {:ok, conn, updated_connections} <- _get_connection(:route, connections, prefix), {:ok, %Response{} = results} <- Bolt.Sips.query(conn, query, props) do {:ok, Response.first(results), updated_connections} else {:error, %Error{code: code, message: message}} -> err_msg = "#{code}; #{message}" Logger.error(err_msg) {:error, err_msg} {:error, msg, _updated_connections} -> Logger.error(msg) {:error, :routing_table_not_available} e -> Logger.error("get_routing_table error: #{inspect(e)}") {:error, :routing_table_not_available_at_all} end end defp get_routing_table(_opts, false), do: {:ok, @no_routing} defp get_routing_table(opts, _) do prefix = Keyword.get(opts, :prefix, :default) with {:ok, %Protocol.ConnData{configuration: configuration}} <- Protocol.connect(opts), # DON'T> :ok <- Protocol.disconnect(:stop, conn), {_long, short} <- parse_server_version(configuration[:server_version]) do {query, params} = if Version.match?(short, ">= 3.2.3") do props = Keyword.get(opts, :routing_context, %{}) {"CALL dbms.cluster.routing.getRoutingTable({context})", %{context: props}} else {"CALL dbms.cluster.routing.getServers()", %{}} end with {:ok, pid} <- DBConnection.start_link(Protocol, Keyword.delete(opts, :name)), {:ok, %Response{} = results} <- Bolt.Sips.query(pid, query, params), true <- Process.exit(pid, :normal) do table = results |> Response.first() |> Map.put(:routing_query, %{query: query, params: params}) ttl = Map.get(table, :ttl, 300) * 1000 # may overwrite the ttl, when desired in exceptional situations: tests, for example. ttl = Keyword.get(opts, :ttl, ttl) Process.send_after(self(), {:refresh, prefix}, ttl) {:ok, table} else {:error, %Error{message: message}} -> Logger.error(message) {:error, message} _e -> "Are you sure you're connected to a Neo4j cluster? The routing table, is not available." |> Logger.error() {:error, :routing_table_not_available} end end end @doc """ start a new (DB)Connection process, supervised registered under a name following this convention: - "role@hostname:port", the `role`, `hostname` and the `port` are collected from the user's configuration: `opts`. The `role` parameter is ignored when the `routing_table` parameter represents a neo4j map containing the definition for a neo4j cluster! It defaults to: `:direct`, when not specified! """ def start_connections(opts, routing_table) def start_connections(opts, routing_table) when is_nil(routing_table) do url = "#{opts[:hostname]}:#{opts[:port]}" role = Keyword.get(opts, :role, :direct) with {:ok, _pid} <- ConnectionSupervisor.start_child(role, url, opts) do {:ok, %{role => %{url => 0}}} end end def start_connections(opts, routing_table) do connections = with %Bolt.Sips.Routing.RoutingTable{roles: roles} = rt <- RoutingTable.parse(routing_table) do roles |> Enum.reduce(%{}, fn {role, addresses}, acc -> addresses |> Enum.reduce(acc, fn {address, count}, acc -> # interim hack; force the schema to be `bolt`, otherwise the parse is not happening url = "bolt://" <> address %URI{host: host, port: port} = URI.parse(url) # Important! # We remove the url from the routing-specific configs, because the port and the address where the # socket will be opened, is using the host and the port returned by the routing table, and not by the # initial url param. The Utils will overwrite them if the `url` is defined! config = opts |> Keyword.put(:host, String.to_charlist(host)) |> Keyword.put(:port, port) |> Keyword.put(:name, role) |> Keyword.put(:hits, count) |> Keyword.delete(:url) with {:ok, _pid} <- ConnectionSupervisor.start_child(role, address, config) do Map.update(acc, role, %{address => 0}, fn urls -> Map.put(urls, address, 0) end) else _ -> acc end end) |> Map.merge(acc) end) |> Map.put(:ttl, rt.ttl) |> Map.put(:updated_at, rt.updated_at) end {:ok, connections} end @with_routing true @impl true def handle_info({:refresh, prefix}, state) do %{connections: connections, user_options: user_options} = Map.get(state, prefix) %{ttl: ttl} = connections # may overwrite the ttl, when desired in exceptional situations: tests, for example. ttl = Keyword.get(user_options, :ttl, ttl) state = with {:ok, routing_table, _updated_connections} <- get_routing_table(connections, @with_routing, prefix), {:ok, new_connections} <- start_connections(user_options, routing_table) do connections = connections |> Map.put(:updated_at, Bolt.Sips.Utils.now()) |> merge_connections_maps(new_connections, prefix) ttl = Keyword.get(user_options, :ttl, ttl * 1000) Process.send_after(self(), {:refresh, prefix}, ttl) new_state = %{user_options: user_options, connections: connections} Map.put(state, prefix, new_state) else e -> Logger.error("Cannot create any connections. Error: #{inspect(e)}") Map.put(state, prefix, %{user_options: user_options, connections: %{}}) end {:noreply, state} end def handle_info(req, state) do Logger.warn("An unusual request: #{inspect(req)}") {:noreply, state} end defp parse_server_version(%{"server" => server_version_string}) do %{"M" => major, "m" => minor, "p" => patch} = Regex.named_captures(~r/Neo4j\/(?<M>\d+)\.(?<m>\d+)\.(?<p>\d+)/, server_version_string) {server_version_string, "#{major}.#{minor}.#{patch}"} end defp parse_server_version(some_version), do: raise(ArgumentError, "not a Neo4J version info: " <> inspect(some_version)) defp error_no_connection_available_for_role(role, _e, prefix \\ :default) defp error_no_connection_available_for_role(role, _e, prefix) do "no connection exists with this role: #{role} (prefix: #{prefix})" end @routing_roles ~w{read write route}a @spec merge_connections_maps(any(), any(), any()) :: any() def merge_connections_maps(current_connections, new_connections, prefix \\ :default) def merge_connections_maps(current_connections, new_connections, prefix) do @routing_roles |> Enum.flat_map(fn role -> new_urls = Map.keys(new_connections[role]) Map.keys(current_connections[role]) |> Enum.flat_map(fn url -> remove_old_urls(role, url, new_urls) end) end) |> close_connections(prefix) @routing_roles |> Enum.reduce(current_connections, fn role, acc -> Map.put(acc, role, new_connections[role]) end) end defp remove_old_urls(role, url, urls), do: if(url in urls, do: [], else: [{role, url}]) # [ # read: "localhost:7689", # write: "localhost:7687", # write: "localhost:7690", # route: "localhost:7688", # route: "localhost:7689" # ] defp close_connections(connections, prefix) do connections |> Enum.each(fn {role, url} -> with {:ok, _pid} = r <- ConnectionSupervisor.terminate_connection(role, url, prefix) do r else {:error, :not_found} -> Logger.debug("#{role}: #{url}; not a valid connection/process. It can't be terminated") end end) end @spec _get_connection(role :: String.t() | atom, state :: map, prefix :: atom) :: {:ok, pid, map} | {:error, any, map} defp _get_connection(role, connections, prefix) do with true <- Map.has_key?(connections, role), {:ok, url} <- LoadBalancer.least_reused_url(Map.get(connections, role)), {:ok, pid} <- ConnectionSupervisor.find_connection(role, url, prefix) do {_, updated_connections} = connections |> get_and_update_in([role, url], fn hits -> {hits, hits + 1} end) {:ok, pid, updated_connections} else e -> err_msg = error_no_connection_available_for_role(role, e) {:error, err_msg, connections} end end end
lib/bolt_sips/router.ex
0.754599
0.405331
router.ex
starcoder
defmodule MetricsReporter.LatencyStatsCalculator.Percentage do import String, only: [to_integer: 1] import MetricsReporter.LatencyStatsCalculator, only: [sorted_keys_by_numeric_value: 1] def calculate(bins, keys) do bins |> aggregate() |> do_calculate(keys) end def default_data(keys), do: Map.new(keys, &({&1, 0})) defp aggregate(bins_list) do bins_list |> Enum.map(&(&1["latency_bins"])) |> Enum.reduce(%{}, &(Map.merge(&1, &2, fn(_k, v1, v2) -> v1 + v2 end))) end defp do_calculate(aggregated_bin, keys) do aggregated_bin |> build_aggregated_map(sorted_keys_by_numeric_value(keys)) |> percentilize_vals(keys, totalize(aggregated_bin)) end defp build_aggregated_map(aggregated_bin, expected_keys) do aggregated_keys = sorted_keys_by_numeric_value(aggregated_bin) expected_keys |> Enum.reduce({aggregated_keys, %{}}, &(reductor(&1, &2, aggregated_bin))) |> elem(1) end defp reductor(bin, {keys_list, acc_map} , aggregated_bins) do {sum, updated_keys_list} = aggregate_at_key_up_to_bin_sum(keys_list, bin, aggregated_bins) {updated_keys_list, Map.put(acc_map, bin, sum)} end defp aggregate_at_key_up_to_bin_sum(keys, bin, aggregated_bins) do Enum.reduce_while(keys, {0, keys}, fn (key, {acc, remaining_keys}) -> if to_integer(key) <= to_integer(bin) do {:cont, {acc + Map.get(aggregated_bins, key), List.delete(remaining_keys, key)}} else {:halt, {acc, remaining_keys}} end end) end defp percentilize_vals(map, keys, total) do keys |> default_data() |> Map.merge(map, fn(_, _, v) -> calculate_percentile(v, total) end) |> Map.new(fn {k, v} -> {square_and_stringify(k), v} end) end defp totalize(bins), do: Map.values(bins) |> Enum.sum() defp square_and_stringify(k), do: :math.pow(2, to_integer(k)) |> round() |> to_string() defp calculate_percentile(_, 0), do: 0 defp calculate_percentile(value, count), do: Float.round((value / count) * 100, 4) end
monitoring_hub/apps/metrics_reporter/lib/metrics_reporter/latency_stats_calculator/percentage.ex
0.604749
0.550305
percentage.ex
starcoder
defmodule Concentrate.StopTimeUpdate do @moduledoc """ Structure for representing an update to a StopTime (e.g. a predicted arrival or departure) """ import Concentrate.StructHelpers alias Concentrate.Filter.GTFS.Stops defstruct_accessors([ :trip_id, :stop_id, :arrival_time, :departure_time, :stop_sequence, :status, :track, :platform_id, :uncertainty, schedule_relationship: :SCHEDULED ]) @doc """ Returns a time for the StopTimeUpdate: arrival if present, otherwise departure. """ @spec time(%__MODULE__{}) :: non_neg_integer | nil def time(%__MODULE__{arrival_time: time}) when is_integer(time), do: time def time(%__MODULE__{departure_time: time}), do: time @compile inline: [time: 1] @doc """ Marks the update as skipped (when the stop is closed, for example). """ @spec skip(%__MODULE__{}) :: t def skip(%__MODULE__{} = stu) do %{stu | schedule_relationship: :SKIPPED, arrival_time: nil, departure_time: nil, status: nil} end defimpl Concentrate.Mergeable do def key(%{trip_id: trip_id, stop_id: stop_id, stop_sequence: stop_sequence}) do parent_station_id = if stop_id do Stops.parent_station_id(stop_id) end {trip_id, parent_station_id, stop_sequence} end def merge(first, second) do %{ first | arrival_time: time(:lt, first.arrival_time, second.arrival_time), departure_time: time(:gt, first.departure_time, second.departure_time), status: first.status || second.status, track: first.track || second.track, schedule_relationship: if first.schedule_relationship == :SCHEDULED do second.schedule_relationship else first.schedule_relationship end, stop_id: max(first.stop_id, second.stop_id), platform_id: first.platform_id || second.platform_id, uncertainty: first.uncertainty || second.uncertainty } end defp time(_, nil, time), do: time defp time(_, time, nil), do: time defp time(_, time, time), do: time defp time(:lt, first, second) when first < second, do: first defp time(:gt, first, second) when first > second, do: first defp time(_, _, second), do: second end end
lib/concentrate/stop_time_update.ex
0.808332
0.447823
stop_time_update.ex
starcoder
defmodule BreakerBox do @moduledoc """ Server for circuit breakers. Maintains state of registered breakers and their configurations, and allows for querying the status of breakers, as well as enabling and disabling. Modules can be automatically registered if they implement the `BreakerBox.BreakerConfiguration` behaviour and are passed in to `start_link/1`. """ use GenServer require Behave require Logger alias :fuse, as: Fuse alias BreakerBox.BreakerConfiguration @typep fuse_status :: {:ok, breaker_name :: term} | {:error, {:breaker_tripped, breaker_name :: term}} | {:error, {:breaker_not_found, breaker_name :: term}} @typep ok_or_not_found :: :ok | {:error, {:breaker_not_found, breaker_name :: term}} ### PUBLIC API @doc """ Wrapper around `GenServer.start_link/3`. Passes the list of modules received to `init/1`, which will attempt to register the circuit breakers inside those modules. Modules passed in are expected to implement the `BreakerBox.BreakerConfiguration` behaviour via `@behaviour BreakerBox.BreakerConfiguration`, which will require them to have a method named `registration/0` that returns a 2-tuple containing the breaker's name and configuration options. """ @spec start_link(circuit_breaker_modules :: list(module)) :: {:ok, pid} | {:error, {:already_started, pid}} | {:error, reason :: term} | {:stop, reason :: term} | :ignore def start_link(circuit_breaker_modules) do GenServer.start_link(__MODULE__, circuit_breaker_modules, name: __MODULE__) end @doc """ Initializes the breaker box state, attempting to call `registration/0` on every argument passed in, assuming they're a module implementing the `BreakerBox.BreakerConfiguration` behaviour. If they are not a module, or don't implement the behaviour, a warning will be logged indicating how to fix the issue, and that item will be skipped. """ @spec init(circuit_breaker_modules :: list(module)) :: {:ok, %{optional(term) => BreakerConfiguration.t()}} def init(circuit_breaker_modules) do state = Enum.reduce(circuit_breaker_modules, %{}, &register_or_warn/2) {:ok, state} end @doc """ Register a circuit breaker given its name and options. \\__MODULE__ is a good default breaker name, but can be a string, atom, or anything you want. Re-using a breaker name in multiple places will overwrite with the last configuration. """ @spec register(breaker_name :: term, breaker_options :: BreakerConfiguration.t()) :: :ok | :reset | {:error, reason :: term} def register(breaker_name, %BreakerConfiguration{} = breaker_options) do GenServer.call(__MODULE__, {:register, breaker_name, breaker_options}) end @doc """ Remove a circuit breaker. """ @spec remove(breaker_name :: term) :: ok_or_not_found def remove(breaker_name) do GenServer.call(__MODULE__, {:remove, breaker_name}) end @doc """ Retrieve the configuration for a breaker. """ @spec get_config(breaker_name :: term) :: {:ok, BreakerConfiguration.t()} | {:error, :not_found} def get_config(breaker_name) do GenServer.call(__MODULE__, {:get_config, breaker_name}) end @doc """ Retrieve a map with breaker names as keys and `BreakerBox.BreakerConfiguration` structs as values. """ @spec registered() :: %{optional(term) => BreakerConfiguration.t()} def registered do GenServer.call(__MODULE__, :registered) end @doc """ Retrieve the status of a single breaker. """ @spec status(breaker_name :: term) :: fuse_status() def status(breaker_name) do GenServer.call(__MODULE__, {:status, breaker_name}) end @doc """ Retrieve the current status of all registered breakers. """ @spec status() :: %{optional(term) => fuse_status()} def status do GenServer.call(__MODULE__, :status) end @doc """ Reset a breaker that has been tripped. This will only reset breakers that have been blown via exceeding the error limit in a given time window, and will not re-enable a breaker that has been disabled via `disable/1`. """ @spec reset(breaker_name :: term) :: ok_or_not_found() def reset(breaker_name) do GenServer.call(__MODULE__, {:reset, breaker_name}) end @doc """ Disable a circuit breaker. Sets the breaker's status to `:breaker_tripped` until `enable/1` is called for the same breaker, or the application is restarted. Will not be reset by calling `reset/1`. """ @spec disable(breaker_name :: term) :: :ok def disable(breaker_name) do GenServer.call(__MODULE__, {:disable, breaker_name}) end @doc """ Enable a circuit breaker. Sets the breaker's status to `:ok`. """ @spec enable(breaker_name :: term) :: :ok def enable(breaker_name) do GenServer.call(__MODULE__, {:enable, breaker_name}) end @doc """ Increment the error counter for a circuit breaker. If this causes the breaker to go over its error limit for its time window, the breaker will trip, and subsequent calls to `status/1` will show it as {:error, {:breaker_tripped, breaker_name}}`. """ @spec increment_error(breaker_name :: term) :: :ok def increment_error(breaker_name) do GenServer.call(__MODULE__, {:increment_error, breaker_name}) end ### PRIVATE API def handle_call( {:register, breaker_name, %BreakerConfiguration{} = options}, _from, state ) do {result, new_state} = register_breaker(breaker_name, options, state) {:reply, result, new_state} end def handle_call({:remove, breaker_name}, _from, state) do result = case breaker_status(breaker_name) do {:error, {:breaker_not_found, ^breaker_name}} = not_found -> not_found _ -> Fuse.remove(breaker_name) end {:reply, result, Map.delete(state, breaker_name)} end def handle_call({:get_config, breaker_name}, _from, state) do result = case Map.fetch(state, breaker_name) do :error -> {:error, :not_found} ok_tuple -> ok_tuple end {:reply, result, state} end def handle_call(:registered, _from, state) do registered_breakers = Enum.into(state, %{}, fn {breaker_name, breaker_options} -> {breaker_name, fuse_options_to_breaker_configuration(breaker_options)} end) {:reply, registered_breakers, state} end def handle_call({:status, breaker_name}, _from, state) do {:reply, breaker_status(breaker_name), state} end def handle_call(:status, _from, state) do all_statuses = Enum.into(state, %{}, fn {breaker_name, _} -> {breaker_name, breaker_status(breaker_name)} end) {:reply, all_statuses, state} end def handle_call({:reset, breaker_name}, _from, state) do result = case breaker_status(breaker_name) do {:error, {:breaker_not_found, ^breaker_name}} = not_found -> not_found _ -> Fuse.reset(breaker_name) end {:reply, result, state} end def handle_call({:disable, breaker_name}, _from, state) do result = case breaker_status(breaker_name) do {:error, {:breaker_not_found, ^breaker_name}} = not_found -> not_found _ -> Fuse.circuit_disable(breaker_name) end {:reply, result, state} end def handle_call({:enable, breaker_name}, _from, state) do result = case breaker_status(breaker_name) do {:error, {:breaker_not_found, ^breaker_name}} = not_found -> not_found _ -> Fuse.circuit_enable(breaker_name) end {:reply, result, state} end def handle_call({:increment_error, breaker_name}, _from, state) do result = case breaker_status(breaker_name) do {:error, {:breaker_not_found, ^breaker_name}} = not_found -> not_found _status -> Fuse.melt(breaker_name) end {:reply, result, state} end defp fuse_options_to_breaker_configuration( {{:standard, maximum_failures, failure_window}, {:reset, reset_window}} ) do %BreakerConfiguration{} |> BreakerConfiguration.trip_on_failure_number(maximum_failures) |> BreakerConfiguration.within_milliseconds(failure_window) |> BreakerConfiguration.reset_after_milliseconds(reset_window) end defp fuse_options_to_breaker_configuration(%BreakerConfiguration{} = config), do: config defp register_or_warn(breaker_module, state) do case Behave.behaviour_implemented?(breaker_module, BreakerConfiguration) do {:error, :not_a_module, ^breaker_module} -> breaker_module |> non_module_warning |> Logger.warn() state {:error, :behaviour_not_implemented} -> breaker_module |> missing_behaviour_warning |> Logger.warn() state :ok -> {breaker_name, breaker_options} = breaker_module.registration() {_, new_state} = register_breaker(breaker_name, breaker_options, state) new_state end end defp register_breaker(breaker_name, %BreakerConfiguration{} = breaker_options, state) do fuse_options = BreakerConfiguration.to_fuse_options(breaker_options) result = Fuse.install(breaker_name, fuse_options) new_state = Map.put(state, breaker_name, breaker_options) {result, new_state} end defp breaker_status(breaker_name) do case Fuse.ask(breaker_name, :sync) do :ok -> {:ok, breaker_name} :blown -> {:error, {:breaker_tripped, breaker_name}} {:error, :not_found} -> {:error, {:breaker_not_found, breaker_name}} end end ### Error/Warning messages defp non_module_warning(breaker_module) do breaker_module |> registration_failure_warning("it is not a module") end defp missing_behaviour_warning(breaker_module) do breaker_module |> registration_failure_warning( "it does not implement #{inspect(BreakerConfiguration)} behaviour" ) end defp registration_failure_warning(breaker_module, reason) do "BreakerBox: #{inspect(breaker_module)} failed to register via init/1 because " <> reason end end
lib/breaker_box.ex
0.872089
0.415017
breaker_box.ex
starcoder
defmodule Typelixir.NewBuilder do require IEx import Typelixir.Macros require Typelixir.Macros def pre(:expression, ast) do case ast do {:=, _, [ast1, ast2]} -> [pattern: ast1, expression: ast2, match: 2] asts when is_list(asts) -> Enum.map(asts, &{:expression, &1}) ++ [list: length(asts)] {:%{}, _, ast} -> Enum.map(ast, &{:key, elem(&1,0)}) ++ Enum.map(ast, &{:expression, elem(&1,1)}) ++ [map: length(ast)*2] {:|, _, [ast1, ast2]} -> [expression: ast1, expression: ast2, cons: 2] [] -> [:nil] {:^, _, _} -> {:error, :expression} {:_, _, _} -> {:error, :expression} {k, _, nil} when is_atom(k) -> [ok: {:identifier, k}] k when is_key(k) -> [key: k] k when is_float(k) -> [ok: {:float, k}] {{:., [line: 1], [Access, :get]}, [expr_ast, key_ast]} -> [key: key_ast, expression: expr_ast, map_app: 2] {:if, _, [cond_ast, [do: if_ast]]} -> [expression: cond_ast, expression: if_ast, if: 2] {:if, _, [cond_ast, [do: if_ast, else: else_ast]]} -> [expression: cond_ast, expression: if_ast, expression: else_ast, if: 3] {:cond, _, [[do: branches_ast]]} when is_list(branches_ast)-> Enum.map(branches_ast, &{:cond_branch, &1}) ++ [cond: length(branches_ast)] {:case, _, [pat_ast, [do: branches_ast]]} when is_list(branches_ast) -> [pattern: pat_ast] ++ Enum.map(branches_ast, &{:case_branch, &1}) ++ [case: length(branches_ast) + 1] {:__block__, _, asts} when is_list(asts) -> Enum.map(asts,&{:expression, &1}) ++ [seq: length(asts)] {op, _, args} when is_list(args) and is_atom(op) -> case op do :+ -> Enum.map(args, &{:expression, &1}) ++ [{{:app, op}, 2}] _ -> {:error, :expression} end ast when is_tuple(ast) -> asts = Tuple.to_list(ast); Enum.map(asts, &{:expression, &1}) ++ [tuple: length(asts)] _ -> {:error, :expression} end end def pre(:pattern, ast) do case ast do asts when is_list(asts) -> Enum.map(asts, &[expression: &1]) ++ [list: length(asts)] {:%{}, _, ast} -> Enum.map(ast, fn {k_ast, v_ast} -> [key: k_ast, expression: v_ast] end) ++ [map: 1] [] -> [:nil] {:^, _, {k, _, nil}} when is_atom(k) -> [ok: {:identifier, k}] {:_, _, _} -> [ok: :wild] {k, _, nil} when is_atom(k) -> [ok: {:identifier, k}] k when is_key(k) -> [key: k] k when is_float(k) -> [ok: {:float, k}] _ -> {:error, :pattern} end end def pre(:function, ast) do case ast do {:def, _, [{name, _, args}, [do: body_ast]]} -> [ok: name] ++ Enum.map(args, &{:pattern, &1}) ++ [expression: body_ast] ++ [def: length(args) + 2] {:@, _, [{:spec, _, [{:"::", _, [{name, _, specs_ast}, spec_ast]}]}]} -> [spec: spec_ast] ++ Enum.map(specs_ast, &{:spec, &1}) ++ [{{:def_spec, name}, length(specs_ast) + 1}] end end def pre(:cond_branch, ast) do case ast do {:-> ,_, [[clause], expr]} -> [expression: clause, expression: expr, to_list: 2] _ -> {:error, :cond_branch} end end def pre(:case_branch, ast) do case ast do {:-> ,_, [[clause], expr]} -> [pattern: clause, expression: expr, to_list: 2] _ -> {:error, :case_branch} end end def pre(:key, ast) do case ast do {k, _, nil} when is_atom(k) and k not in [:^,:_] -> [ok: {:identifier, k}] k when is_atom(k) -> [ok: k] k when is_integer(k) -> [ok: k] _ -> {:error, :key} end end def pre(:spec, ast) do case ast do {atom, _, nil} when atom in [:integer, :float, :string, :boolean, :atom, :term, :any] -> [ok: atom] {:%{}, _, ast} when is_list(ast) -> Enum.map(ast, fn {k_ast, v_ast} -> [key: k_ast, spec: v_ast] end) ++ [map: length(ast)] [{:->, _, [asts, ast]}] when is_list(asts) -> Enum.map(asts, &{:spec, &1}) ++ [spec: ast] ++ [arrow: length(asts) + 1] [ast] -> [spec: ast, list: 1] k when is_key(k) -> [spec_key: k] ast when is_tuple(ast) -> ast = Tuple.to_list(ast); Enum.map(ast, &{:spec, &1}) ++ [tuple: length(ast)] _ -> {:error, :spec} end end def pre(:module, ast) do f = fn ast -> case ast do {:def, _, _} -> {:function, ast} {:@, _, _} -> {:function, ast} {:defmodule, _, _} -> {:module, ast} _ -> {:expression, ast} end end case ast do {:defmodule, _, [{:__aliases__, _, _}, [do: {:__block__, _, block_ast}]]} -> Enum.map(block_ast, f) ++ [mod: length(block_ast)] {:defmodule, _, [{:__aliases__, _, _}, [do: ast]]} -> [f.(ast)] ++ [mod: 1] end end def post(:to_list, args) do args end def post(:map, args) do {keys, values} = Enum.split(args,div(length(args),2)) {:map, Enum.zip(keys,values) |> Enum.map(&Tuple.to_list/1)} end def post(:def, args) do [name|params] = args {params, body} = Enum.split(params, length(params) - 1) {{:def, name}, [params, body]} end def post({:def_spec, name}, args) do [spec|specs] = args {{:def_spec, name}, [[specs], spec]} end def post(op, args), do: {op, args} def process(ast), do: process([ast], []) def process(pending, processed) do case pending do [] -> [res] = processed; res [head|pending] -> case head do {:ok, x} -> process(pending, [x | processed]) {type, ast} when type in [ :expression, :pattern, :cond_branch, :case_branch, :key, :spec, :function, :module ] -> process(pre(type, ast) ++ pending, processed) {op, n} when is_integer(n) -> {args, processed} = Enum.split(processed, n) process(pending, [post(op, Enum.reverse(args)) | processed]) {:error, message} -> {:error, message} end end end end
lib/typelixir/new_builder.ex
0.503174
0.587588
new_builder.ex
starcoder
defmodule Academy.User do @moduledoc ~S""" Defines a user model. Composition ----------- A user is composed of a name, a biography, his availability and his avatar (handled by the `Academy.Avatar` module). A user also has a number of skill levels, which are defined in the `Academy.SkillLevel` module. You can also get his bare skills (without their levels) and his skill categories (without the skills) Getting the associations ------------------------ In order to get his skill levels, skills or skill categories, one must use the `Academy.Repo.Preload/1` function like so: alias Academy.Repo alias Academy.User # Will get the user and his skill levels (but not his skills, so you # won't have their name) Repo.get(User, id) |> Repo.preload(:skill_levels) # Will get the user and his skill levels and skills Repo.get(User, id) |> Repo.preload(:skills) # Will get the user and his skill levels, skills and skill categories Repo.get(User, id) |> Repo.preload(:skill_categories) """ use Academy.Web, :model use Arc.Ecto.Schema schema "users" do field :name, :string field :bio, :string field :available, :boolean field :avatar, Academy.Avatar.Type field :email, :string field :show_email, :boolean, default: false field :github_username, :string has_many :skill_levels, Academy.SkillLevel has_many :skills, through: [:skill_levels, :skill] has_many :skill_categories, through: [:skills, :category] timestamps end @required_fields ~w(name show_email)a @optional_fields ~w(bio available email github_username)a @fields @required_fields ++ @optional_fields @doc ~S""" Creates a changeset based on the `model` and `params`. Examples: alias Academy.User alias Academy.Repo # Create a new user with name "guest" and insert it in the database User.changeset(%User{}, name: "guest") |> Repo.insert! # Rename a user Repo.get_by(User, name: "guest") |> User.changeset(name: "guest1") |> Repo.update! """ def changeset(model, params \\ %{}) do model |> cast(params, @fields) |> validate_required(@required_fields) |> cast_attachments(params, [:avatar]) |> validate_length(:bio, min: 10, max: 140) |> validate_email(:email) |> validate_github_username(:github_username) #|> validate_avatar(params) end def validate_email(changeset, field) do email = get_field(changeset, field) if email !== nil do validate_format(changeset, :email, ~r/\A([\w+\-].?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i) else changeset end end @doc ~S""" Validate a github username in a changeset. """ def validate_github_username(changeset, field) do username = get_field(changeset, field) if username !== nil do valid? = case String.length username do 0 -> false 1 -> Regex.match?(~r/^[[:alnum:]]+$/, username) 2 -> Regex.match?(~r/^[[:alnum:]]+$/, username) _ -> Regex.match?(~r/^[[:alnum:]][[:alnum:]-]+[[:alnum:]]$/, username) and not String.contains?(username, "--") end if valid? do changeset else add_error(changeset, field, "does not look like a Github username") end else changeset end end @doc ~S""" Validate an avatar Currently not working. """ def validate_avatar(changeset, params) do # TODO: validate the size/space usage of the image changeset end end
web/models/user.ex
0.624637
0.430267
user.ex
starcoder
# Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. defmodule CFXXL do @moduledoc """ A module containing functions to interact with the CFSSL API. For more information on the contents of the results of each call, see the relative [cfssl API documentation](https://github.com/cloudflare/cfssl/tree/master/doc/api) """ alias CFXXL.Client @authsign_opts [:timestamp, :remote_address, :bundle] @bundle_cert_opts [:domain, :private_key, :flavor, :ip] @bundle_domain_opts [:ip] @info_opts [:profile] @init_ca_opts [:CN, :key, :ca] @newcert_opts [:label, :profile, :bundle] @newkey_opts [:CN, :key] @scan_opts [:ip, :timeout, :family, :scanner] @sign_opts [:hosts, :subject, :serial_sequence, :label, :profile, :bundle] @doc """ Request to sign a CSR with authentication. ## Arguments * `client`: the `CFXXL.Client` to use for the call * `token`: the authentication token * `csr`: the CSR as a PEM encoded string * `opts`: a keyword list of optional parameters ## Options * `timestamp`: a Unix timestamp * `remote_address`: an address used in making the request * `bundle`: a boolean specifying whether to include an "optimal" certificate bundle along with the certificate * all the opts supported in `sign/3` ## Return * `{:ok, result}` with the contents of the `result` key of the API * `{:error, reason}` if it fails """ def authsign(client, token, csr, opts \\ []) do body = opts |> filter_opts(@authsign_opts) |> Enum.into(%{token: token, request: sign_request(csr, opts)}) post(client, "authsign", body) end @doc """ Request a certificate bundle ## Arguments * `client`: the `CFXXL.Client` to use for the call * `opts`: a keyword list of parameters ## Options `opts` must contain one of these two keys * `certificate`: the PEM-encoded certificate to be bundled * `domain`: a domain name indicating a remote host to retrieve a certificate for If `certificate` is given, the following options are available: * `private_key`: the PEM-encoded private key to be included with the bundle. This is valid only if the server is not running in "keyless" mode * `flavor`: one of `:ubiquitous`, `:force`, or `:optimal`, with a default value of `:ubiquitous`. A ubiquitous bundle is one that has a higher probability of being verified everywhere, even by clients using outdated or unusual trust stores. Force will cause the endpoint to use the bundle provided in the `certificate` parameter, and will only verify that the bundle is a valid (verifiable) chain * `domain`: the domain name to verify as the hostname of the certificate * `ip`: the IP address to verify against the certificate IP SANs Otherwise, using `domain`, the following options are available: * `ip`: the IP address of the remote host; this will fetch the certificate from the IP, and verify that it is valid for the domain name ## Return * `{:ok, result}` with the contents of the `result` key of the API * `{:error, reason}` if it fails """ def bundle(client, opts) when is_list(opts) do cond do Keyword.has_key?(opts, :certificate) -> body = opts |> filter_opts(@bundle_cert_opts) |> Enum.into(%{certificate: opts[:certificate]}) post(client, "bundle", body) Keyword.has_key?(opts, :domain) -> body = opts |> filter_opts(@bundle_domain_opts) |> Enum.into(%{domain: opts[:domain]}) post(client, "bundle", body) true -> {:error, :no_certificate_or_domain} end end def bundle(_client, _opts), do: {:error, :no_certificate_or_domain} @doc """ Request information about a certificate ## Arguments * `client`: the `CFXXL.Client` to use for the call * `opts`: a keyword list of parameters ## Options `opts` must contain one of these two keys * `certificate`: the PEM-encoded certificate to be parsed * `domain`: a domain name indicating a remote host to retrieve a certificate for ## Return * `{:ok, result}` with the contents of the `result` key of the API * `{:error, reason}` if it fails """ def certinfo(client, opts) when is_list(opts) do cond do Keyword.has_key?(opts, :certificate) -> cert = opts[:certificate] post(client, "certinfo", %{certificate: cert}) Keyword.has_key?(opts, :domain) -> domain = opts[:domain] post(client, "certinfo", %{domain: domain}) true -> {:error, :no_certificate_or_domain} end end def certinfo(_client, _opts), do: {:error, :no_certificate_or_domain} @doc """ Generate a CRL from the database ## Arguments * `client`: the `CFXXL.Client` to use for the call * `expiry`: an optional string to specify the time after which the CRL should expire from the moment of the request ## Return * `{:ok, result}` with the contents of the `result` key of the API * `{:error, reason}` if it fails """ def crl(client, expiry \\ nil) do if expiry do get(client, "crl", %{expiry: expiry}) else get(client, "crl") end end @doc """ Perform a generic GET to the CFSSL API. ## Arguments * `client`: the `CFXXL.Client` to use for the call * `route`: the part to be appended to the url to make the call, without a leading slash * `params`: a map with the parameters to be appended to the URL of the GET ## Return * `{:ok, result}` with the contents of the `result` key of the API * `{:error, reason}` if it fails """ def get(%Client{endpoint: endpoint, options: options}, route, params \\ %{}) do HTTPoison.get("#{endpoint}/#{route}", [], [{:params, params} | options]) |> process_response() end @doc """ Get signer information ## Arguments * `client`: the `CFXXL.Client` to use for the call * `label`: a string specifying the signer * `opts`: a keyword list of optional parameters ## Options * `profile`: a string specifying the signing profile for the signer. Signing profile specifies what key usages should be used and how long the expiry should be set ## Return * `{:ok, result}` with the contents of the `result` key of the API * `{:error, reason}` if it fails """ def info(client, label, opts \\ []) do body = opts |> filter_opts(@info_opts) |> Enum.into(%{label: label}) post(client, "info", body) end @doc """ Request a new CA key/certificate pair. ## Arguments * `client`: the `CFXXL.Client` to use for the call * `hosts`: a list of strings representing SAN (subject alternative names) for the CA certificate * `dname`: a `CFXXL.DName` struct representing the DN for the CA certificate * `opts`: a keyword list of optional parameters ## Options * `CN`: a string representing the CN for the certificate * `key`: a `CFXXL.KeyConfig` to configure the key, default to ECDSA-256 * `ca`: a `CFXXL.CAConfig` to configure the CA ## Return * `{:ok, result}` with the contents of the `result` key of the API * `{:error, reason}` if it fails """ def init_ca(client, hosts, dname, opts \\ []) do body = opts |> filter_opts(@init_ca_opts) |> Enum.into(%{hosts: hosts, names: dname}) post(client, "init_ca", body) end @doc """ Request a new key/signed certificate pair. ## Arguments * `client`: the `CFXXL.Client` to use for the call * `hosts`: a list of strings representing SAN (subject alternative names) for the certificate * `dname`: a `CFXXL.DName` struct representing the DN for the certificate * `opts`: a keyword list of optional parameters ## Options * `label`: a string specifying which signer to be appointed to sign the CSR, useful when interacting with a remote multi-root CA signer * `profile`: a string specifying the signing profile for the signer, useful when interacting with a remote multi-root CA signer * `bundle`: a boolean specifying whether to include an "optimal" certificate bundle along with the certificate * all the opts supported in `newkey/4` ## Return * `{:ok, result}` with the contents of the `result` key of the API * `{:error, reason}` if it fails """ def newcert(client, hosts, dname, opts \\ []) do body = opts |> filter_opts(@newcert_opts) |> Enum.into(%{request: newkey_request(hosts, dname, opts)}) post(client, "newcert", body) end @doc """ Request a new key/CSR pair. ## Arguments * `client`: the `CFXXL.Client` to use for the call * `hosts`: a list of strings representing SAN (subject alternative names) for the certificate * `dname`: a `CFXXL.DName` struct representing the DN for the certificate * `opts`: a keyword list of optional parameters ## Options * `CN`: a string representing the CN for the certificate * `key`: a `CFXXL.KeyConfig` to configure the key, default to ECDSA-256 ## Return * `{:ok, result}` with the contents of the `result` key of the API * `{:error, reason}` if it fails """ def newkey(client, hosts, dname, opts \\ []) do body = newkey_request(hosts, dname, opts) post(client, "newkey", body) end @doc """ Perform a generic POST to the CFSSL API. ## Arguments * `client`: the `CFXXL.Client` to use for the call * `route`: the part to be appended to the url to make the call, without a leading slash * `body`: a map that will be serialized to JSON and used as the body of the request ## Return * `{:ok, result}` with the contents of the `result` key of the API * `{:error, reason}` if it fails """ def post(%Client{endpoint: endpoint, options: options}, route, body) do HTTPoison.post("#{endpoint}/#{route}", Poison.encode!(body), [], options) |> process_response() end @doc """ Request to revoke a certificate. ## Arguments * `client`: the `CFXXL.Client` to use for the call * `serial`: the serial of the certificate to be revoked * `aki`: the AuthorityKeyIdentifier of the certificate to be revoked * `reason`: a string representing the reason of the revocation, see ReasonFlags in Section 4.2.1.13 of RFC5280 ## Return * `:ok` on success * `{:error, reason}` if it fails """ def revoke(client, serial, aki, reason) do body = %{serial: serial, authority_key_id: normalize_aki(aki), reason: reason} case post(client, "revoke", body) do {:ok, _} -> :ok error -> error end end @doc """ Scan an host ## Arguments * `client`: the `CFXXL.Client` to use for the call * `host`: the hostname (optionally including port) to scan * `opts`: a keyword list of optional parameters ## Options * `ip`: IP Address to override DNS lookup of host * `timeout`: The amount of time allotted for the scan to complete (default: 1 minute) * `family`: regular expression specifying scan famil(ies) to run * `scanner`: regular expression specifying scanner(s) to run ## Return * `{:ok, result}` with the contents of the `result` key of the API * `{:error, reason}` if it fails """ def scan(client, host, opts \\ []) do params = opts |> filter_opts(@scan_opts) |> Enum.into(%{host: host}) get(client, "scan", params) end @doc """ Get information on scan families ## Arguments * `client`: the `CFXXL.Client` to use for the call ## Return * `{:ok, result}` with the contents of the `result` key of the API * `{:error, reason}` if it fails """ def scaninfo(client) do get(client, "scaninfo") end @doc """ Request to sign a CSR. ## Arguments * `client`: the `CFXXL.Client` to use for the call * `csr`: the CSR as a PEM encoded string * `opts`: a keyword list of optional parameters ## Options * `hosts`: a list of strings representing SAN (subject alternative names) which overrides the ones in the CSR * `subject`: a `CFXXL.Subject` that overrides the ones in the CSR * `serial_sequence`: a string specifying the prefix which the generated certificate serial should have * `label`: a string specifying which signer to be appointed to sign the CSR, useful when interacting with a remote multi-root CA signer * `profile`: a string specifying the signing profile for the signer, useful when interacting with a remote multi-root CA signer * `bundle`: a boolean specifying whether to include an "optimal" certificate bundle along with the certificate ## Return * `{:ok, result}` with the contents of the `result` key of the API * `{:error, reason}` if it fails """ def sign(client, csr, opts \\ []) do body = sign_request(csr, opts) post(client, "sign", body) end defp process_response({:error, _} = response), do: response defp process_response({:ok, %HTTPoison.Response{body: body}}), do: extract_result(body) defp extract_result(""), do: {:error, :empty_response} defp extract_result(body) do case Poison.decode(body) do {:error, _} -> {:error, :invalid_response} {:ok, %{"success" => false} = decoded} -> {:error, extract_error_message(decoded)} {:ok, %{"success" => true, "result" => result}} -> {:ok, result} end end defp extract_error_message(%{"errors" => errors}) do case errors do [%{"message" => msg} | _] -> msg [] -> :generic_error end end defp normalize_aki(aki) do aki |> String.downcase() |> String.replace(":", "") end defp filter_opts(opts, accepted_opts) do opts |> Enum.filter(fn {k, _} -> k in accepted_opts end) end defp newkey_request(hosts, dname, opts) do opts |> filter_opts(@newkey_opts) |> Enum.into(%{hosts: hosts, names: dname}) end defp sign_request(csr, opts) do opts |> filter_opts(@sign_opts) |> Enum.into(%{certificate_request: csr}) end end
lib/cfxxl.ex
0.816443
0.58522
cfxxl.ex
starcoder
defmodule Lotus.Shared.Width do @moduledoc """ Helper for width related UIKit classes. These utility functions will be consumed by any component that has width or responsiveness mixed in. They are defined at https://getuikit.com/docs/width """ alias Lotus.Shared.Prefix @responsive_widths ~w/small medium large extra_large/a @width_specs ~w/ 1-1 1-2 1-3 2-3 1-4 3-4 1-5 2-5 3-5 4-5 1-6 5-6 small medium large xlarge 2xlarge auto expand / @doc """ Returns a list of width specs. """ def width_specs, do: @width_specs @doc """ Returns UIKit specific width classes ## Examples iex> Lotus.Shared.Width.width_class("1-1") "uk-width-1-1" iex> Lotus.Shared.Width.width_class("expand") "uk-width-expand" """ def width_class(width) when width in @width_specs, do: Prefix.prefixed("width", width) @doc """ Returns UIKit specific child width classes ## Examples iex> Lotus.Shared.Width.child_width_class("1-1") "uk-child-width-1-1" iex> Lotus.Shared.Width.child_width_class("expand") "uk-child-width-expand" """ def child_width_class(width) when width in @width_specs, do: Prefix.prefixed("child-width", width) @doc """ Returns the @ appended responsive width class given width metric and target width. ## Examples iex> Lotus.Shared.Width.responsive_width_class("1-1", :small) "uk-width-1-1@s" iex> Lotus.Shared.Width.responsive_width_class("expand", :large) "uk-width-expand@l" """ def responsive_width_class(width, target), do: responsive_width_for(width, target, &width_class/1) @doc """ Returns the @ appended responsive child width class given width metric and target width. ## Examples iex> Lotus.Shared.Width.responsive_child_width_class("1-1", :small) "uk-child-width-1-1@s" iex> Lotus.Shared.Width.responsive_child_width_class("expand", :large) "uk-child-width-expand@l" """ def responsive_child_width_class(width, target), do: responsive_width_for(width, target, &child_width_class/1) defp responsive_width_for(width, target, fun) when target in @responsive_widths do suffix = case target do :small -> "s" :medium -> "m" :large -> "l" :extra_large -> "xl" end "#{fun.(width)}@#{suffix}" end @doc """ Helper function to get a list of width related classes from `assigns`. ## Examples iex> Lotus.Shared.Width.assigns_to_width_classes(%{}) [] iex> Lotus.Shared.Width.assigns_to_width_classes(%{width: "1-1"}) ["uk-width-1-1"] iex> Lotus.Shared.Width.assigns_to_width_classes(%{small: "1-1"}) ["uk-width-1-1@s"] iex> Lotus.Shared.Width.assigns_to_width_classes(%{small: "1-1", medium: "1-2", large: "1-3", extra_large: "1-1"}) ["uk-width-1-1@xl", "uk-width-1-3@l", "uk-width-1-2@m", "uk-width-1-1@s"] iex> Lotus.Shared.Width.assigns_to_width_classes(%{small: "1-1", medium: "1-2", width: "1-3"}) ["uk-width-1-3", "uk-width-1-2@m", "uk-width-1-1@s"] """ def assigns_to_width_classes(assigns) do assigns_to_width(assigns) ++ responsive_assigns_to_width(assigns) end @doc """ Helper function to get a list of width related child classes from `assigns`. ## Examples iex> Lotus.Shared.Width.assigns_to_child_width_classes(%{}) [] iex> Lotus.Shared.Width.assigns_to_child_width_classes(%{width: "1-1"}) ["uk-child-width-1-1"] iex> Lotus.Shared.Width.assigns_to_child_width_classes(%{small: "1-1"}) ["uk-child-width-1-1@s"] iex> Lotus.Shared.Width.assigns_to_child_width_classes(%{small: "1-1", medium: "1-2", large: "1-3", extra_large: "1-1"}) ["uk-child-width-1-1@xl", "uk-child-width-1-3@l", "uk-child-width-1-2@m", "uk-child-width-1-1@s"] iex> Lotus.Shared.Width.assigns_to_child_width_classes(%{small: "1-1", medium: "1-2", width: "1-3"}) ["uk-child-width-1-3", "uk-child-width-1-2@m", "uk-child-width-1-1@s"] """ def assigns_to_child_width_classes(assigns) do assigns_to_width(assigns, true) ++ responsive_assigns_to_width(assigns, true) end defp assigns_to_width(_, child \\ false) defp assigns_to_width(%{width: width}, child) when width in @width_specs, do: [(child && child_width_class(width)) || width_class(width)] defp assigns_to_width(_, _), do: [] defp responsive_assigns_to_width(assigns, child \\ false) do assigns |> Map.take(@responsive_widths) |> Enum.flat_map(fn {_, nil} -> [] {target, width} -> [ (child && responsive_child_width_class(width, target)) || responsive_width_class(width, target) ] end) end end
lib/lotus/shared/width.ex
0.886368
0.454291
width.ex
starcoder
defmodule Modbux.Tcp.Client do @moduledoc """ API for Modbus TCP Client. """ alias Modbux.Tcp.Client alias Modbux.Tcp use GenServer, restart: :transient, shutdown: 500 require Logger @timeout 2000 @port 502 @ip {0, 0, 0, 0} @active false @to 2000 defstruct ip: nil, tcp_port: nil, socket: nil, timeout: @to, active: false, transid: 0, status: nil, d_pid: nil, msg_len: 0, pending_msg: %{}, cmd: nil @type client_option :: {:ip, {byte(), byte(), byte(), byte()}} | {:active, boolean} | {:tcp_port, non_neg_integer} | {:timeout, non_neg_integer} @doc """ Starts a Modbus TCP Client process. The following options are available: * `ip` - is the internet address of the desired Modbux TCP Server. * `tcp_port` - is the desired Modbux TCP Server tcp port number. * `timeout` - is the connection timeout. * `active` - (`true` or `false`) specifies whether data is received as messages (mailbox) or by calling `confirmation/1` each time `request/2` is called. The messages (when active mode is true) have the following form: `{:modbus_tcp, cmd, values}` ## Example ```elixir Modbux.Tcp.Client.start_link(ip: {10,77,0,2}, port: 502, timeout: 2000, active: true) ``` """ def start_link(params, opts \\ []) do GenServer.start_link(__MODULE__, params, opts) end @doc """ Stops the Client. """ def stop(pid) do GenServer.stop(pid) end @doc """ Gets the state of the Client. """ def state(pid) do GenServer.call(pid, :state) end @doc """ Configure the Client (`status` must be `:closed`). The following options are available: * `ip` - is the internet address of the desired Modbux TCP Server. * `tcp_port` - is the Modbux TCP Server tcp port number . * `timeout` - is the connection timeout. * `active` - (`true` or `false`) specifies whether data is received as messages (mailbox) or by calling `confirmation/1` each time `request/2` is called. """ def configure(pid, params) do GenServer.call(pid, {:configure, params}) end @doc """ Connect the Client to a Server. """ def connect(pid) do GenServer.call(pid, :connect) end @doc """ Close the tcp port of the Client. """ def close(pid) do GenServer.call(pid, :close) end @doc """ Send a request to Modbux TCP Server. `cmd` is a 4 elements tuple, as follows: - `{:rc, slave, address, count}` read `count` coils. - `{:ri, slave, address, count}` read `count` inputs. - `{:rhr, slave, address, count}` read `count` holding registers. - `{:rir, slave, address, count}` read `count` input registers. - `{:fc, slave, address, value}` force single coil. - `{:phr, slave, address, value}` preset single holding register. - `{:fc, slave, address, values}` force multiple coils. - `{:phr, slave, address, values}` preset multiple holding registers. """ def request(pid, cmd) do GenServer.call(pid, {:request, cmd}) end @doc """ In passive mode (active: false), reads the confirmation of the connected Modbux Server. """ def confirmation(pid) do GenServer.call(pid, :confirmation) end @doc """ In passive mode (active: false), flushed the pending messages. """ def flush(pid) do GenServer.call(pid, :flush) end # callbacks def init(args) do port = args[:tcp_port] || @port ip = args[:ip] || @ip timeout = args[:timeout] || @timeout status = :closed active = if args[:active] == nil do @active else args[:active] end state = %Client{ip: ip, tcp_port: port, timeout: timeout, status: status, active: active} {:ok, state} end def handle_call(:state, from, state) do Logger.debug("(#{__MODULE__}, :state) from: #{inspect(from)}") {:reply, state, state} end def handle_call({:configure, args}, _from, state) do case state.status do :closed -> port = args[:tcp_port] || state.tcp_port ip = args[:ip] || state.ip timeout = args[:timeout] || state.timeout d_pid = args[:d_pid] || state.d_pid active = if args[:active] == nil do state.active else args[:active] end new_state = %Client{state | ip: ip, tcp_port: port, timeout: timeout, active: active, d_pid: d_pid} {:reply, :ok, new_state} _ -> {:reply, :error, state} end end def handle_call(:connect, {from, _ref}, state) do Logger.debug("(#{__MODULE__}, :connect) state: #{inspect(state)}") Logger.debug("(#{__MODULE__}, :connect) from: #{inspect(from)}") case :gen_tcp.connect( state.ip, state.tcp_port, [:binary, packet: :raw, active: state.active], state.timeout ) do {:ok, socket} -> ctrl_pid = if state.d_pid == nil do from else state.d_pid end # state new_state = %Client{state | socket: socket, status: :connected, d_pid: ctrl_pid} {:reply, :ok, new_state} {:error, reason} -> Logger.error("(#{__MODULE__}, :connect) reason #{inspect(reason)}") # state {:reply, {:error, reason}, state} end end def handle_call(:close, _from, state) do Logger.debug("(#{__MODULE__}, :close) state: #{inspect(state)}") if state.socket != nil do new_state = close_socket(state) {:reply, :ok, new_state} else Logger.error("(#{__MODULE__}, :close) No port to close") # state {:reply, {:error, :closed}, state} end end def handle_call({:request, cmd}, _from, state) do Logger.debug("(#{__MODULE__}, :request) state: #{inspect(state)}") case state.status do :connected -> request = Tcp.pack_req(cmd, state.transid) length = Tcp.res_len(cmd) case :gen_tcp.send(state.socket, request) do :ok -> new_state = if state.active do new_msg = Map.put(state.pending_msg, state.transid, cmd) n_msg = if state.transid + 1 > 0xFFFF do 0 else state.transid + 1 end %Client{state | msg_len: length, cmd: cmd, pending_msg: new_msg, transid: n_msg} else %Client{state | msg_len: length, cmd: cmd} end {:reply, :ok, new_state} {:error, :closed} -> new_state = close_socket(state) {:reply, {:error, :closed}, new_state} {:error, reason} -> {:reply, {:error, reason}, state} end :closed -> {:reply, {:error, :closed}, state} end end # only in passive mode def handle_call(:confirmation, _from, state) do Logger.debug("(#{__MODULE__}, :confirmation) state: #{inspect(state)}") if state.active do {:reply, :error, state} else case state.status do :connected -> case :gen_tcp.recv(state.socket, state.msg_len, state.timeout) do {:ok, response} -> values = Tcp.parse_res(state.cmd, response, state.transid) Logger.debug("(#{__MODULE__}, :confirmation) response: #{inspect(response)}") n_msg = if state.transid + 1 > 0xFFFF do 0 else state.transid + 1 end new_state = %Client{state | transid: n_msg, cmd: nil, msg_len: 0} case values do # escribió algo nil -> {:reply, :ok, new_state} # leemos algo _ -> {:reply, {:ok, values}, new_state} end {:error, reason} -> Logger.error("(#{__MODULE__}, :confirmation) reason: #{inspect(reason)}") # cerrar? new_state = close_socket(state) new_state = %Client{new_state | cmd: nil, msg_len: 0} {:reply, {:error, reason}, new_state} end :closed -> {:reply, {:error, :closed}, state} end end end def handle_call(:flush, _from, state) do new_state = %Client{state | pending_msg: %{}} {:reply, {:ok, state.pending_msg}, new_state} end # only for active mode (active: true) def handle_info({:tcp, _port, response}, state) do Logger.debug("(#{__MODULE__}, :message_active) response: #{inspect(response)}") Logger.debug("(#{__MODULE__}, :message_active) state: #{inspect(state)}") h = :binary.at(response, 0) l = :binary.at(response, 1) transid = h * 256 + l Logger.debug("(#{__MODULE__}, :message_active) transid: #{inspect(transid)}") case Map.fetch(state.pending_msg, transid) do :error -> Logger.error("(#{__MODULE__}, :message_active) unknown transaction id") {:noreply, state} {:ok, cmd} -> values = Tcp.parse_res(cmd, response, transid) msg = {:modbus_tcp, cmd, values} send(state.d_pid, msg) new_pending_msg = Map.delete(state.pending_msg, transid) new_state = %Client{state | cmd: nil, msg_len: 0, pending_msg: new_pending_msg} {:noreply, new_state} end end def handle_info({:tcp_closed, _port}, state) do Logger.info("(#{__MODULE__}, :tcp_close) Server close the port") new_state = close_socket(state) {:noreply, new_state} end def handle_info(msg, state) do Logger.error("(#{__MODULE__}, :random_msg) msg: #{inspect(msg)}") {:noreply, state} end defp close_socket(state) do :ok = :gen_tcp.close(state.socket) new_state = %Client{state | socket: nil, status: :closed} new_state end end
lib/tcp/client.ex
0.844794
0.583915
client.ex
starcoder
defmodule MatrixReloaded.Vector do @moduledoc """ Provides a set of functions to work with vectors. Mostly functions is written for a row vectors. So if you'll need a similar functionality even for a column vectors you can use `transpose` function on row vector. """ alias MatrixReloaded.Matrix @type t :: [number] @type column() :: [[number]] @type subvector :: number | t() @doc """ Create a row vector of the specified size. Default values of vector is set to `0`. This value can be changed. Returns list of numbers. ## Examples iex> MatrixReloaded.Vector.row(4) [0, 0, 0, 0] iex> MatrixReloaded.Vector.row(4, 3.9) [3.9, 3.9, 3.9, 3.9] """ @spec row(pos_integer, number) :: t() def row(size, val \\ 0) do List.duplicate(val, size) end @doc """ Create a column vector of the specified size. Default values of vector is set to `0`. This value can be changed. Returns list of list number. ## Examples iex> MatrixReloaded.Vector.col(3) [[0], [0], [0]] iex> MatrixReloaded.Vector.col(3, 4) [[4], [4], [4]] """ @spec col(pos_integer, number) :: column() def col(size, val \\ 0) do val |> List.duplicate(size) |> Enum.chunk_every(1) end @doc """ Convert (transpose) a row vector to column and vice versa. ## Examples iex> MatrixReloaded.Vector.transpose([1, 2, 3]) [[1], [2], [3]] iex(23)> MatrixReloaded.Vector.transpose([[1], [2], [3]]) [1, 2, 3] """ @spec transpose(t() | column()) :: column() | t() def transpose([hd | _] = vec) when is_list(hd) do List.flatten(vec) end def transpose(vec) do Enum.chunk_every(vec, 1) end @doc """ Create row vector of alternating sequence of numbers. ## Examples iex> MatrixReloaded.Vector.row(5) |> MatrixReloaded.Vector.alternate_seq(1) [1, 0, 1, 0, 1] iex> MatrixReloaded.Vector.row(7) |> MatrixReloaded.Vector.alternate_seq(1, 3) [1, 0, 0, 1, 0, 0, 1] """ @spec alternate_seq(t(), number, pos_integer) :: t() def alternate_seq(vec, val, step \\ 2) do Enum.map_every(vec, step, fn x -> x + val end) end @doc """ Addition of two a row vectors. These two vectors must have a same size. Otherwise you get an error message. Returns result, it means either tuple of `{:ok, vector}` or `{:error, "msg"}`. ## Examples iex> MatrixReloaded.Vector.add([1, 2, 3], [4, 5, 6]) {:ok, [5, 7, 9]} """ @spec add(t(), t()) :: Result.t(String.t(), t()) def add([hd1 | _], [hd2 | _]) when is_list(hd1) or is_list(hd2) do Result.error("Vectors must be row type!") end def add(vec1, vec2) do if size(vec1) == size(vec2) do [vec1, vec2] |> List.zip() |> Enum.map(fn {x, y} -> x + y end) |> Result.ok() else Result.error("Size both vectors must be same!") end end @doc """ Subtraction of two a row vectors. These two vectors must have a same size. Otherwise you get an error message. Returns result, it means either tuple of `{:ok, vector}` or `{:error, "msg"}`. ## Examples iex> MatrixReloaded.Vector.sub([1, 2, 3], [4, 5, 6]) {:ok, [-3, -3, -3]} """ @spec sub(t(), t()) :: Result.t(String.t(), t()) def sub([hd1 | _], [hd2 | _]) when is_list(hd1) or is_list(hd2) do Result.error("Vectors must be row type!") end def sub(vec1, vec2) do if size(vec1) == size(vec2) do [vec1, vec2] |> List.zip() |> Enum.map(fn {x, y} -> x - y end) |> Result.ok() else Result.error("Size both vectors must be same!") end end @doc """ Scalar product of two a row vectors. These two vectors must have a same size. Otherwise you get an error message. Returns result, it means either tuple of `{:ok, number}` or `{:error, "msg"}`. ## Examples iex> MatrixReloaded.Vector.dot([1, 2, 3], [4, 5, 6]) {:ok, 32} """ @spec dot(t(), t()) :: Result.t(String.t(), number) def dot([hd1 | _], [hd2 | _]) when is_list(hd1) or is_list(hd2) do Result.error("Vectors must be row type!") end def dot(vec1, vec2) do if size(vec1) == size(vec2) do [vec1, vec2] |> List.zip() |> Enum.map(fn {x, y} -> x * y end) |> Enum.sum() |> Result.ok() else Result.error("Size both vectors must be same!") end end @doc """ Inner product of two a row vectors. It produces a row vector where each element `i, j` is the product of elements `i, j` of the original two row vectors. These two vectors must have a same size. Otherwise you get an error message. Returns result, it means either tuple of `{:ok, vector}` or `{:error, "msg"}`. ## Examples iex> MatrixReloaded.Vector.inner_product([1, 2, 3], [4, 5, 6]) {:ok, [4, 10, 18]} """ @spec inner_product(t(), t()) :: Result.t(String.t(), t()) def inner_product([hd1 | _], [hd2 | _]) when is_list(hd1) or is_list(hd2) do Result.error("Vectors must be row type!") end def inner_product(vec1, vec2) do if size(vec1) == size(vec2) do [vec1, vec2] |> List.zip() |> Enum.map(fn {x, y} -> x * y end) |> Result.ok() else Result.error("Size both vectors must be same!") end end @doc """ Outer product of two a row vectors. It produces a matrix of dimension `{m, n}` where `m` and `n` are length (size) of row vectors. If input vectors aren't a row type you get an error message. Returns result, it means either tuple of `{:ok, matrix}` or `{:error, "msg"}`. ## Examples iex> MatrixReloaded.Vector.outer_product([1, 2, 3, 4], [1, 2, 3]) {:ok, [ [1, 2, 3], [2, 4, 6], [3, 6, 9], [4, 8, 12] ] } """ @spec outer_product(t(), t()) :: Result.t(String.t(), Matrix.t()) def outer_product([hd1 | _], [hd2 | _]) when is_list(hd1) or is_list(hd2) do Result.error("Vectors must be row type!") end def outer_product(vec1, vec2) do if 1 < size(vec1) and 1 < size(vec2) do vec1 |> Enum.map(fn el -> mult_by_num(vec2, el) end) |> Result.ok() else Result.error("Vectors must contain at least two values!") end end @doc """ Multiply a vector by number. ## Examples iex> MatrixReloaded.Vector.row(3, 2) |> MatrixReloaded.Vector.mult_by_num(3) [6, 6, 6] iex> MatrixReloaded.Vector.col(3, 2) |> MatrixReloaded.Vector.mult_by_num(3) [[6], [6], [6]] """ @spec mult_by_num(t() | column(), number) :: t() | column() def mult_by_num([hd | _] = vec, val) when is_list(hd) do vec |> transpose() |> mult_by_num(val) |> transpose() end def mult_by_num(vec, val) do Enum.map(vec, fn x -> x * val end) end @doc """ Update row vector by given a row subvector (list) of numbers or just by one number. The vector elements you want to change are given by the index. The index is a non-negative integer and determines the position of the element in the vector. Returns result, it means either tuple of `{:ok, vector}` or `{:error, "msg"}`. ## Example: iex> vec = 0..10 |> Enum.to_list() iex> MatrixReloaded.Vector.update(vec, [0, 0, 0], 5) {:ok, [0, 1, 2, 3, 4, 0, 0, 0, 8, 9, 10]} iex> vec = 0..10 |> Enum.to_list() iex> MatrixReloaded.Vector.update(vec, 0, 5) {:ok, [0, 1, 2, 3, 4, 0, 6, 7, 8, 9, 10]} """ @spec update(t(), number() | t(), non_neg_integer()) :: Result.t(String.t(), t()) def update(vec, subvec, index) when is_list(vec) and is_number(subvec) and is_integer(index) do update(vec, [subvec], index) end def update(vec, subvec, index) when is_list(vec) and is_list(subvec) and is_integer(index) do len_vec = Kernel.length(vec) vec |> is_index_ok?(index) |> Result.and_then(&is_index_at_vector?(&1, len_vec, index)) |> Result.and_then(&is_subvec_in_vec?(&1, len_vec, Kernel.length(subvec), index)) |> Result.map(&make_update(&1, subvec, index)) end @doc """ Update row vector by given a row subvector (list) of numbers or by one number. The elements you want to change are given by the vector of indices. These indices must be a non-negative integers and determine the positions of the element in the vector. Returns result, it means either tuple of `{:ok, vector}` or `{:error, "msg"}`. ## Example: iex> vec = 0..10 |> Enum.to_list() iex> MatrixReloaded.Vector.update_map(vec, [0, 0], [2, 7]) {:ok, [0, 1, 0, 0, 4, 5, 6, 0, 0, 9, 10]} iex> vec = 0..10 |> Enum.to_list() iex> MatrixReloaded.Vector.update_map(vec, 0, [2, 7]) {:ok, [0, 1, 0, 3, 4, 5, 6, 0, 8, 9, 10]} """ @spec update_map(t(), number() | t(), list(non_neg_integer())) :: Result.t(String.t(), t()) def update_map(vec, subvec, position_indices) do Enum.reduce(position_indices, {:ok, vec}, fn position, acc -> Result.and_then(acc, &update(&1, subvec, position)) end) end @doc """ The size of the vector. Returns a positive integer. ## Example: iex> MatrixReloaded.Vector.row(3) |> MatrixReloaded.Vector.size() 3 iex> MatrixReloaded.Vector.col(4, -1) |> MatrixReloaded.Vector.size() 4 """ @spec size(t()) :: non_neg_integer def size(vec), do: length(vec) defp make_update(vec, subvec, index) do len_subvec = Kernel.length(subvec) vec |> Enum.with_index() |> Enum.map(fn {val, i} -> if i in index..(index + len_subvec - 1) do subvec |> Enum.at(i - index) else val end end) end defp is_index_ok?(vec, idx) when is_integer(idx) and 0 <= idx do Result.ok(vec) end defp is_index_ok?(_vec, idx) when is_number(idx) do Result.error("The index must be integer number greater or equal to zero!") end defp is_index_at_vector?( vec, len, index, method \\ :update ) defp is_index_at_vector?(vec, len, idx, _method) when idx <= len do Result.ok(vec) end defp is_index_at_vector?( _vec, _len, _idx, method ) do Result.error( "You can not #{Atom.to_string(method)} the #{vec_or_subvec(method)}. The index is outside of vector!" ) end defp is_subvec_in_vec?( vec, len_vec, len_subvec, index, method \\ :update ) defp is_subvec_in_vec?( vec, len_vec, len_subvec, idx, _method ) when len_subvec + idx <= len_vec do Result.ok(vec) end defp is_subvec_in_vec?( _vec, _len_vec, _len_subvec, idx, method ) do Result.error( "You can not #{Atom.to_string(method)} #{vec_or_subvec(method)} on given position #{idx}. A part of subvector is outside of matrix!" ) end defp vec_or_subvec(:update) do "vector" end # defp vec_or_subvec(:get) do # "subvector or element" # end end
lib/matrix_reloaded/vector.ex
0.947381
0.819244
vector.ex
starcoder
defmodule Brando.Type.Status do @moduledoc """ Defines a type for managing status in post schemas. """ use Ecto.Type import Brando.Gettext @type status :: :disabled | :draft | :pending | :published @status_codes [draft: 0, published: 1, pending: 2, disabled: 3] @doc """ Returns the internal type representation of our `Role` type for pg """ def type, do: :integer @doc """ Cast should return OUR type no matter what the input. """ def cast(atom) when is_atom(atom), do: {:ok, atom} def cast(binary) when is_binary(binary) do atom = String.to_existing_atom(binary) {:ok, atom} end def cast(status) when is_integer(status) do case status do 0 -> {:ok, :draft} 1 -> {:ok, :published} 2 -> {:ok, :pending} 3 -> {:ok, :disabled} end end # Cast anything else is a failure def cast(_), do: :error @spec translate(status) :: binary def translate(:draft), do: gettext("draft") def translate(:published), do: gettext("published") def translate(:pending), do: gettext("pending") def translate(:disabled), do: gettext("disabled") # Integers are never considered blank def blank?(_), do: false @doc """ When loading `roles` from the database, we are guaranteed to receive an integer (as database are stricts) and we will just return it to be stored in the schema struct. """ def load(status) when is_integer(status) do case status do 0 -> {:ok, :draft} 1 -> {:ok, :published} 2 -> {:ok, :pending} 3 -> {:ok, :disabled} end end @doc """ When dumping data to the database we expect a `list`, but check for other options as well. """ def dump(atom) when is_atom(atom), do: {:ok, @status_codes[atom]} def dump(binary) when is_binary(binary), do: {:ok, String.to_integer(binary)} def dump(integer) when is_integer(integer), do: {:ok, integer} def dump(_), do: :error # just a dummy to establish :published_and_pending as an existing atom # so we don't fail in String.to_existing_atom def dummy(:published_and_pending), do: nil end
lib/brando/types/status.ex
0.806815
0.436982
status.ex
starcoder
defmodule XmlToMap do @moduledoc """ Simple convenience module for getting a map out of an XML string. """ alias XmlToMap.NaiveMap @doc """ `naive_map/1` utility is inspired by `Rails Hash.from_xml()` but is "naive" in that it is convenient (requires no setup) but carries the same drawbacks. For example no validation over what should be a collection. If and only if nodes are repeated at the same level will they become a list. If a node has attributes we'll prepend a "-" in front of them and merge them into the map and take the node value and nest that inside "#content" key. """ @defaults %{namespace_match_fn: &__MODULE__.default_namespace_match_fn/0} def naive_map(xml, opts \\ []) do params = Enum.into(opts, @defaults) tree = get_generic_data_structure(xml, params) NaiveMap.parse(tree) end # Default function to handle namespace in xml # This fuction invokes an anonymous function that has this parameters: Name, Namespace, Prefix. # Usually, the namespace appears at the top of xml file, e.g `xmlns:g="http://base.google.com/ns/1.0"`, # where `g` is the Prefix and `"http://base.google.com/ns/1.0"` the Namespace, # the Name is the key tag in xml. # It should return a term. It is called for each tag and attribute name. # The result will be used in the output. # When a namespace and prefix is found, it'll return a term like "#{prefix}:#{name}", # otherwise it will return only the name. # The default behavior in :erlsom.simple_form/2 is Name if Namespace == undefined, and a string {Namespace}Name otherwise. def default_namespace_match_fn do fn(name, namespace, prefix) -> cond do namespace != [] && prefix != [] -> "#{prefix}:#{name}" true -> name end end end defp get_generic_data_structure(xml, %{namespace_match_fn: namespace_match_fn}) do {:ok, element, _tail} = :erlsom.simple_form(xml, [{:nameFun, namespace_match_fn.()}]) element end # erlsom simple_form returns a kind of tree: # Result = {ok, Element, Tail}, # where Element = {Tag, Attributes, Content}, # Tag is a string # Attributes = [{AttributeName, Value}], # Content is a list of Elements and/or strings. defp get_generic_data_structure(xml, _opts) do {:ok, element, _tail} = :erlsom.simple_form(xml) element end end
lib/elixir_xml_to_map.ex
0.825941
0.521349
elixir_xml_to_map.ex
starcoder
defmodule StrawHat.Response do @moduledoc """ Utilities for working with "result tuples". * `{:ok, value}` * `{:error, reason}` """ @type t(ok, error) :: {:ok, ok} | {:error, error} @type ok_tuple :: {:ok, any} @type error_tuple :: {:error, any} @type result_tuple :: ok_tuple | error_tuple @doc ~S""" Calls the next function only if it receives an ok tuple. Otherwise it skips the call and returns the error tuple. ## Examples iex> business_logic = fn x -> StrawHat.Response.ok(x * 2) end ...> 21 |> StrawHat.Response.ok() |> StrawHat.Response.and_then(business_logic) {:ok, 42} iex> business_logic = fn x -> StrawHat.Response.ok(x * 2) end ...> "oops" |> StrawHat.Response.error() |> StrawHat.Response.and_then(business_logic) {:error, "oops"} """ @spec and_then(result_tuple, (any -> result_tuple)) :: result_tuple def and_then({:ok, data}, function), do: function.(data) def and_then({:error, _} = error, _function), do: error @doc ~S""" Calls the first function if it receives an error tuple, and the second one if it receives an ok tuple. ## Examples iex> on_ok = fn x -> "X is #{x}" end ...> on_error = fn e -> "Error: #{e}" end ...> 42 |> StrawHat.Response.ok() |> StrawHat.Response.either(on_error, on_ok) "X is 42" iex> on_ok = fn x -> "X is #{x}" end ...> on_error = fn e -> "Error: #{e}" end ...> "oops" |> StrawHat.Response.error() |> StrawHat.Response.either(on_error, on_ok) "Error: oops" """ @spec either(result_tuple, (any -> any), (any -> any)) :: any def either({:ok, data}, _, on_ok), do: on_ok.(data) def either({:error, error}, on_error, _), do: on_error.(error) @doc ~S""" Creates a new error result tuple. ## Examples iex> StrawHat.Response.error("oops") {:error, "oops"} """ @spec error(any) :: error_tuple def error(value), do: {:error, value} @doc ~S""" Checks if a `result_tuple` is an error. ## Examples iex> 1 |> StrawHat.Response.ok() |> StrawHat.Response.error?() false iex> 2 |>StrawHat.Response.error() |> StrawHat.Response.error?() true """ @spec error?(result_tuple) :: boolean def error?({:error, _}), do: true def error?({:ok, _}), do: false @doc ~S""" Promotes any value to a result tuple. It excludes `nil` for the ok tuples. ## Examples iex> StrawHat.Response.from_value(nil) {:error, :no_value} iex> StrawHat.Response.from_value(nil, "Missing") {:error, "Missing"} iex> StrawHat.Response.from_value(42) {:ok, 42} iex> StrawHat.Response.from_value({:ok, 123}) {:ok, 123} iex> StrawHat.Response.from_value({:error, "my error"}) {:error, "my error"} """ @spec from_value(any) :: result_tuple def from_value(value, on_nil_value \\ :no_value) def from_value({:ok, _value} = response, _on_nil_value), do: response def from_value({:error, _value} = response, _on_nil_value), do: response def from_value(nil, on_nil_value), do: error(on_nil_value) def from_value(value, _on_nil_value), do: ok(value) @doc ~S""" Converts an `Ok` value to an `Error` value if the `predicate` is not valid. ## Examples iex> res = StrawHat.Response.ok(10) ...> StrawHat.Response.keep_if(res, &(&1 > 5)) {:ok, 10} iex> res = StrawHat.Response.ok(10) ...> StrawHat.Response.keep_if(res, &(&1 > 10), "must be > of 10") {:error, "must be > of 10"} iex> res = StrawHat.Response.error(:no_value) ...> StrawHat.Response.keep_if(res, &(&1 > 10), "must be > of 10") {:error, :no_value} """ @spec keep_if(result_tuple, (any -> boolean), any) :: result_tuple def keep_if(result, predicate, error_message \\ :invalid) def keep_if({:error, _} = error, _predicate, _error_message), do: error def keep_if({:ok, value} = ok, predicate, error_message) do if predicate.(value), do: ok, else: error(error_message) end @doc ~S""" Calls the next function only if it receives an ok tuple. The function unwraps the value from the tuple, calls the next function and wraps it back into an ok tuple. ## Examples iex> business_logic = fn x -> x * 2 end ...> 21 |> StrawHat.Response.ok() |> StrawHat.Response.map(business_logic) {:ok, 42} iex> business_logic = fn x -> x * 2 end ...> "oops" |> StrawHat.Response.error() |> StrawHat.Response.map(business_logic) {:error, "oops"} """ @spec map(result_tuple, (any -> any)) :: result_tuple def map({:ok, data}, function), do: ok(function.(data)) def map({:error, _} = error, _function), do: error @doc ~S""" Calls the next function only if it receives an error tuple. The function unwraps the value from the tuple, calls the next function and wraps it back into an error tuple. ## Examples iex> better_error = fn _ -> "A better error message" end ...> 42 |> StrawHat.Response.ok() |> StrawHat.Response.map_error(better_error) {:ok, 42} iex> better_error = fn _ -> "A better error message" end ...> "oops" |> StrawHat.Response.error() |> StrawHat.Response.map_error(better_error) {:error, "A better error message"} """ @spec map_error(result_tuple, (any -> any)) :: result_tuple def map_error({:ok, _} = data, _function), do: data def map_error({:error, _} = error, function) do or_else(error, fn x -> error(function.(x)) end) end @doc ~S""" Creates a new ok result tuple. ## Examples iex> StrawHat.Response.ok(42) {:ok, 42} """ @spec ok(any) :: ok_tuple def ok(value), do: {:ok, value} @doc ~S""" Checks if a `result_tuple` is ok. ## Examples iex> 1 |> StrawHat.Response.ok() |> StrawHat.Response.ok?() true iex> 2 |> StrawHat.Response.error() |>StrawHat.Response.ok?() false """ @spec ok?(result_tuple) :: boolean def ok?({:ok, _}), do: true def ok?({:error, _}), do: false @doc ~S""" Calls the next function only if it receives an ok tuple but discards the result. It always returns the original tuple. ## Examples iex> some_logging = fn x -> "Success #{x}" end ...> {:ok, 42} |> StrawHat.Response.tap(some_logging) {:ok, 42} iex> some_logging = fn _ -> "Not called logging" end ...> {:error, "oops"} |> StrawHat.Response.tap(some_logging) {:error, "oops"} """ @spec tap(result_tuple, (any -> any)) :: result_tuple def tap(data, function), do: map(data, &StrawHat.tap(&1, function)) @doc ~S""" Calls the next function only if it receives an error tuple but discards the result. It always returns the original tuple. ## Examples iex> some_logging = fn x -> "Failed #{x}" end ...> {:error, "oops"} |> StrawHat.Response.tap_error(some_logging) {:error, "oops"} iex> some_logging = fn _ -> "Not called logging" end ...> {:ok, 42} |> StrawHat.Response.tap_error(some_logging) {:ok, 42} """ @spec tap_error(result_tuple, (any -> any)) :: result_tuple def tap_error(data, function), do: map_error(data, &StrawHat.tap(&1, function)) @doc ~S""" Calls the next function only if it receives an error tuple. Otherwise it skips the call and returns the ok tuple. It expects the function to return a new result tuple. ## Examples iex> business_logic = fn _ -> {:error, "a better error message"} end ...> {:ok, 42} |> StrawHat.Response.or_else(business_logic) {:ok, 42} iex> business_logic = fn _ -> {:error, "a better error message"} end ...> {:error, "oops"} |> StrawHat.Response.or_else(business_logic) {:error, "a better error message"} iex> default_value = fn _ -> {:ok, []} end ...> {:error, "oops"} |> StrawHat.Response.or_else(default_value) {:ok, []} """ @spec or_else(result_tuple, (any -> result_tuple)) :: result_tuple def or_else({:ok, _} = data, _function), do: data def or_else({:error, reason}, function), do: function.(reason) @doc ~S""" Converts an `Ok` value to an `Error` value if the `predicate` is valid. ## Examples iex> res = StrawHat.Response.ok([]) ...> StrawHat.Response.reject_if(res, &Enum.empty?/1) {:error, :invalid} iex> res = StrawHat.Response.ok([1]) ...> StrawHat.Response.reject_if(res, &Enum.empty?/1) {:ok, [1]} iex> res = StrawHat.Response.ok([]) ...> StrawHat.Response.reject_if(res, &Enum.empty?/1, "list cannot be empty") {:error, "list cannot be empty"} """ @spec reject_if(result_tuple, (any -> boolean), any) :: result_tuple def reject_if(result, predicate, error_message \\ :invalid) do keep_if(result, &(not predicate.(&1)), error_message) end @doc ~S""" Transforms a list of result tuple to a result tuple containing either the first error tuple or an ok tuple containing the list of values. ### Examples iex> StrawHat.Response.sequence([StrawHat.Response.ok(42), StrawHat.Response.ok(1337)]) {:ok, [42, 1337]} iex> StrawHat.Response.sequence([StrawHat.Response.ok(42), StrawHat.Response.error("oops"), StrawHat.Response.ok(1337)]) {:error, "oops"} """ @spec sequence([result_tuple]) :: {:ok, [any()]} | {:error, any()} def sequence(list) do case Enum.reduce_while(list, [], &do_sequence/2) do {:error, _} = error -> error result -> ok(Enum.reverse(result)) end end @doc ~S""" Returns the content of an ok tuple if the value is correct. Otherwise it returns the default value. ### Examples iex> 42 |> StrawHat.Response.ok |> StrawHat.Response.with_default(1337) 42 iex> "oops" |> StrawHat.Response.error |> StrawHat.Response.with_default(1337) 1337 """ @spec with_default(result_tuple, any) :: any def with_default({:ok, data}, _default_data), do: data def with_default({:error, _}, default_data), do: default_data defp do_sequence(element, elements) do case element do {:ok, value} -> {:cont, [value | elements]} {:error, _} -> {:halt, element} end end end
lib/straw_hat/response.ex
0.874707
0.450057
response.ex
starcoder
defmodule OptionParser do @moduledoc """ This module contains functions to parse command line arguments. """ @type argv :: [String.t] @type parsed :: Keyword.t @type errors :: [{String.t, String.t | nil}] @type options :: [switches: Keyword.t, strict: Keyword.t, aliases: Keyword.t] @doc """ Parses `argv` into a keywords list. It returns the parsed values, remaining arguments and the invalid options. ## Examples iex> OptionParser.parse(["--debug"]) {[debug: true], [], []} iex> OptionParser.parse(["--source", "lib"]) {[source: "lib"], [], []} iex> OptionParser.parse(["--source-path", "lib", "test/enum_test.exs", "--verbose"]) {[source_path: "lib", verbose: true], ["test/enum_test.exs"], []} By default, Elixir will try to automatically parse switches. Switches without an argument, like `--debug` will automatically be set to `true`. Switches followed by a value will be assigned to the value, always as strings. Note Elixir also converts the switches to underscore atoms, as `--source-path` becomes `:source_path`, to better suit Elixir conventions. This means that option names on the command line cannot contain underscores; such options will be reported as `:undefined` (in strict mode) or `:invalid` (in basic mode). ## Switches Many times though, it is better to explicitly list the available switches and their formats. The switches can be specified via two different options: * `:strict` - the switches are strict. Any switch that does not exist in the switch list is treated as an error. * `:switches` - defines some switches. Switches that does not exist in the switch list are still attempted to be parsed. Note only `:strict` or `:switches` may be given at once. For each switch, the following types are supported: * `:boolean` - marks the given switch as a boolean. Boolean switches never consume the following value unless it is `true` or `false`. * `:integer` - parses the switch as an integer. * `:float` - parses the switch as a float. * `:string` - returns the switch as a string. If a switch can't be parsed or is not specified in the strict case, the option is returned in the invalid options list (third element of the returned tuple). The following extra "types" are supported: * `:keep` - keeps duplicated items in the list instead of overriding Examples: iex> OptionParser.parse(["--unlock", "path/to/file"], strict: [unlock: :boolean]) {[unlock: true], ["path/to/file"], []} iex> OptionParser.parse(["--unlock", "--limit", "0", "path/to/file"], ...> strict: [unlock: :boolean, limit: :integer]) {[unlock: true, limit: 0], ["path/to/file"], []} iex> OptionParser.parse(["--limit", "3"], strict: [limit: :integer]) {[limit: 3], [], []} iex> OptionParser.parse(["--limit", "xyz"], strict: [limit: :integer]) {[], [], [{"--limit", "xyz"}]} iex> OptionParser.parse(["--unknown", "xyz"], strict: []) {[], ["xyz"], [{"--unknown", nil}]} iex> OptionParser.parse(["--limit", "3", "--unknown", "xyz"], ...> switches: [limit: :integer]) {[limit: 3, unknown: "xyz"], [], []} ## Negation switches In case a switch is declared as boolean, it may be passed as `--no-SWITCH` which will set the option to `false`: iex> OptionParser.parse(["--no-op", "path/to/file"], switches: [op: :boolean]) {[op: false], ["path/to/file"], []} ## Aliases A set of aliases can be given as options too: iex> OptionParser.parse(["-d"], aliases: [d: :debug]) {[debug: true], [], []} """ @spec parse(argv, options) :: {parsed, argv, errors} def parse(argv, opts \\ []) when is_list(argv) and is_list(opts) do do_parse(argv, compile_config(opts), [], [], [], true) end @doc """ Similar to `parse/2` but only parses the head of `argv`; as soon as it finds a non-switch, it stops parsing. See `parse/2` for more information. ## Example iex> OptionParser.parse_head(["--source", "lib", "test/enum_test.exs", "--verbose"]) {[source: "lib"], ["test/enum_test.exs", "--verbose"], []} iex> OptionParser.parse_head(["--verbose", "--source", "lib", "test/enum_test.exs", "--unlock"]) {[verbose: true, source: "lib"], ["test/enum_test.exs", "--unlock"], []} """ @spec parse_head(argv, options) :: {parsed, argv, errors} def parse_head(argv, opts \\ []) when is_list(argv) and is_list(opts) do do_parse(argv, compile_config(opts), [], [], [], false) end defp do_parse([], _config, opts, args, invalid, _all?) do {Enum.reverse(opts), Enum.reverse(args), Enum.reverse(invalid)} end defp do_parse(argv, {aliases, switches, strict}=config, opts, args, invalid, all?) do case next(argv, aliases, switches, strict) do {:ok, option, value, rest} -> # the option exist and it was successfully parsed kinds = List.wrap Keyword.get(switches, option) new_opts = do_store_option(opts, option, value, kinds) do_parse(rest, config, new_opts, args, invalid, all?) {:invalid, option, value, rest} -> # the option exist but it has wrong value do_parse(rest, config, opts, args, [{option, value}|invalid], all?) {:undefined, option, _value, rest} -> # the option does not exist (for strict cases) do_parse(rest, config, opts, args, [{option, nil}|invalid], all?) {:error, ["--"|rest]} -> {Enum.reverse(opts), Enum.reverse(args, rest), Enum.reverse(invalid)} {:error, [arg|rest]=remaining_args} -> # there is no option if all? do do_parse(rest, config, opts, [arg|args], invalid, all?) else {Enum.reverse(opts), Enum.reverse(args, remaining_args), Enum.reverse(invalid)} end end end @doc """ Low-level function that parses one option. It accepts the same options as `parse/2` and `parse_head/2` as both functions are built on top of next. This function may return: * `{:ok, key, value, rest}` - the option `key` with `value` was successfully parsed * `{:invalid, key, value, rest}` - the option `key` is invalid with `value` (returned when the switch type does not match the one given via the command line) * `{:undefined, key, value, rest}` - the option `key` is undefined (returned on strict cases and the switch is unknown) * `{:error, rest}` - there are no switches at the top of the given argv """ @spec next(argv, options) :: {:ok, key :: atom, value :: term, argv} | {:invalid, String.t, String.t | nil, argv} | {:undefined, String.t, String.t | nil, argv} | {:error, argv} def next(argv, opts \\ []) when is_list(argv) and is_list(opts) do {aliases, switches, strict} = compile_config(opts) next(argv, aliases, switches, strict) end defp next([], _aliases, _switches, _strict) do {:error, []} end defp next(["--"|_]=argv, _aliases, _switches, _strict) do {:error, argv} end defp next(["-"|_]=argv, _aliases, _switches, _strict) do {:error, argv} end defp next(["- " <> _|_]=argv, _aliases, _switches, _strict) do {:error, argv} end defp next(["-" <> option|rest], aliases, switches, strict) do {option, value} = split_option(option) opt_name_bin = "-" <> option tagged = tag_option(option, switches, aliases) if strict and not option_defined?(tagged, switches) do {:undefined, opt_name_bin, value, rest} else {opt_name, kinds, value} = normalize_option(tagged, value, switches) {value, kinds, rest} = normalize_value(value, kinds, rest, strict) case validate_option(value, kinds) do {:ok, new_value} -> {:ok, opt_name, new_value, rest} :invalid -> {:invalid, opt_name_bin, value, rest} end end end defp next(argv, _aliases, _switches, _strict) do {:error, argv} end @doc """ Receives a key-value enumerable and convert it to argv. Keys must be atoms. Keys with nil value are discarded, boolean values are converted to `--key` or `--no-key` and all other values are converted using `to_string/1`. ## Examples iex> OptionParser.to_argv([foo_bar: "baz"]) ["--foo-bar", "baz"] iex> OptionParser.to_argv([bool: true, bool: false, discarded: nil]) ["--bool", "--no-bool"] """ @spec to_argv(Enumerable.t) :: argv def to_argv(enum) do Enum.flat_map(enum, fn {_key, nil} -> [] {key, true} -> [to_switch(key)] {key, false} -> [to_switch(key, "--no-")] {key, value} -> [to_switch(key), to_string(value)] end) end defp to_switch(key, prefix \\ "--") when is_atom(key) do prefix <> String.replace(Atom.to_string(key), "_", "-") end @doc ~S""" Splits a string into argv chunks. ## Examples iex> OptionParser.split("foo bar") ["foo", "bar"] iex> OptionParser.split("foo \"bar baz\"") ["foo", "bar baz"] """ @spec split(String.t) :: argv def split(string) do do_split(strip_leading_spaces(string), "", [], nil) end # If we have a escaped quote, simply remove the escape defp do_split(<<?\\, quote, t :: binary>>, buffer, acc, quote), do: do_split(t, <<buffer::binary, quote>>, acc, quote) # If we have a quote and we were not in a quote, start one defp do_split(<<quote, t :: binary>>, buffer, acc, nil) when quote in [?", ?'], do: do_split(t, buffer, acc, quote) # If we have a quote and we were inside it, close it defp do_split(<<quote, t :: binary>>, buffer, acc, quote), do: do_split(t, buffer, acc, nil) # If we have a escaped quote/space, simply remove the escape as long as we are not inside a quote defp do_split(<<?\\, h, t :: binary>>, buffer, acc, nil) when h in [?\s, ?', ?"], do: do_split(t, <<buffer::binary, h>>, acc, nil) # If we have space and we are outside of a quote, start new segment defp do_split(<<?\s, t :: binary>>, buffer, acc, nil), do: do_split(strip_leading_spaces(t), "", [buffer|acc], nil) # All other characters are moved to buffer defp do_split(<<h, t::binary>>, buffer, acc, quote) do do_split(t, <<buffer::binary, h>>, acc, quote) end # Finish the string expecting a nil marker defp do_split(<<>>, "", acc, nil), do: Enum.reverse(acc) defp do_split(<<>>, buffer, acc, nil), do: Enum.reverse([buffer|acc]) # Otherwise raise defp do_split(<<>>, _, _acc, marker) do raise "argv string did not terminate properly, a #{<<marker>>} was opened but never closed" end defp strip_leading_spaces(" " <> t), do: strip_leading_spaces(t) defp strip_leading_spaces(t), do: t ## Helpers defp compile_config(opts) do aliases = opts[:aliases] || [] {switches, strict} = cond do s = opts[:switches] -> {s, false} s = opts[:strict] -> {s, true} true -> {[], false} end {aliases, switches, strict} end defp validate_option(value, kinds) do {is_invalid, value} = cond do :invalid in kinds -> {true, value} :boolean in kinds -> case value do t when t in [true, "true"] -> {nil, true} f when f in [false, "false"] -> {nil, false} _ -> {true, value} end :integer in kinds -> case Integer.parse(value) do {value, ""} -> {nil, value} _ -> {true, value} end :float in kinds -> case Float.parse(value) do {value, ""} -> {nil, value} _ -> {true, value} end true -> {nil, value} end if is_invalid do :invalid else {:ok, value} end end defp do_store_option(dict, option, value, kinds) do cond do :keep in kinds -> [{option, value}|dict] true -> [{option, value}|Keyword.delete(dict, option)] end end defp tag_option(<<?-, option :: binary>>, switches, _aliases) do get_negated(option, switches) end defp tag_option(option, _switches, aliases) when is_binary(option) do opt = get_option(option) if alias = aliases[opt] do {:default, alias} else :unknown end end defp option_defined?(:unknown, _switches) do false end defp option_defined?({:negated, option}, switches) do Keyword.has_key?(switches, option) end defp option_defined?({:default, option}, switches) do Keyword.has_key?(switches, option) end defp normalize_option(:unknown, value, _switches) do {nil, [:invalid], value} end defp normalize_option({:negated, option}, value, switches) do if value do {option, [:invalid], value} else {option, List.wrap(switches[option]), false} end end defp normalize_option({:default, option}, value, switches) do {option, List.wrap(switches[option]), value} end defp normalize_value(nil, kinds, t, strict) do nil_or_true = if strict, do: nil, else: true cond do :boolean in kinds -> {true, kinds, t} value_in_tail?(t) -> [h|t] = t {h, kinds, t} kinds == [] -> {nil_or_true, kinds, t} true -> {nil, [:invalid], t} end end defp normalize_value(value, kinds, t, _) do {value, kinds, t} end defp value_in_tail?(["-"|_]), do: true defp value_in_tail?(["- " <> _|_]), do: true defp value_in_tail?(["-" <> _|_]), do: false defp value_in_tail?([]), do: false defp value_in_tail?(_), do: true defp split_option(option) do case :binary.split(option, "=") do [h] -> {h, nil} [h, t] -> {h, t} end end defp to_underscore(option), do: to_underscore(option, <<>>) defp to_underscore("_" <> _rest, _acc), do: nil defp to_underscore("-" <> rest, acc), do: to_underscore(rest, acc <> "_") defp to_underscore(<<c>> <> rest, acc), do: to_underscore(rest, <<acc::binary, c>>) defp to_underscore(<<>>, acc), do: acc defp get_option(option) do if str = to_underscore(option) do String.to_atom(str) end end defp get_negated("no-" <> rest = original, switches) do cond do (negated = get_option(rest)) && :boolean in List.wrap(switches[negated]) -> {:negated, negated} option = get_option(original) -> {:default, option} true -> :unknown end end defp get_negated(rest, _switches) do if option = get_option(rest) do {:default, option} else :unknown end end end
lib/elixir/lib/option_parser.ex
0.856092
0.426441
option_parser.ex
starcoder