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 Cog.Repository.PipelineHistory do
@moduledoc """
Behavioral API for interacting with pipeline history
records.
"""
import Ecto.Query, only: [from: 2]
alias Cog.Repo
alias Cog.Models.PipelineHistory
@allowed_states ["running", "waiting", "finished"]
@doc """
Updates any pipelines in "running" or "waiting" states to "finished". This is intended
to handle cases where Cog crashes (or similarly shuts down quickly) and leaves pipeline
history records in an inconsistent state. This function should only be called when Cog
is starting up.
"""
def update_orphans() do
{count, _} = from(ph in PipelineHistory,
where: ph.state != "finished",
update: [set: [state: "finished"]]) |> Repo.update_all([])
count
end
def new(attr) do
attr = Map.put(attr, :started_at, now_timestamp_ms())
cs = PipelineHistory.changeset(%PipelineHistory{}, attr)
Repo.insert!(cs)
end
def increment_count(id, incr) do
case Repo.get_by(PipelineHistory, id: id) do
nil ->
:ok
ph ->
cs = PipelineHistory.changeset(ph, %{count: ph.count + incr})
Repo.update!(cs)
end
end
def update_state(id, state) when state in @allowed_states do
case Repo.get_by(PipelineHistory, id: id) do
nil ->
:ok
ph ->
args = if state == "finished" do
%{state: state, finished_at: now_timestamp_ms()}
else
%{state: state}
end
cs = PipelineHistory.changeset(ph, args)
Repo.update!(cs)
end
end
def all_pipelines(limit \\ 20) do
query = from ph in PipelineHistory,
where: ph.state != "finished",
order_by: [desc: :started_at],
limit: ^limit,
preload: [:user]
Repo.all(query)
end
def pipelines_for_user(user_id, limit \\ 20) do
query = from ph in PipelineHistory,
where: ph.user_id == ^user_id and ph.state != "finished",
order_by: [desc: :started_at],
limit: ^limit,
preload: [:user]
Repo.all(query)
end
def by_short_id(short_id, except_state \\ nil) when is_binary(short_id) do
query = if except_state != nil do
from ph in PipelineHistory,
where: ph.state != ^except_state and like(ph.id, ^"#{short_id}%"),
preload: [:user]
else
from ph in PipelineHistory,
where: like(ph.id, ^"#{short_id}%"),
preload: [:user]
end
Repo.one(query)
end
def history_for_user(user_id, hist_start, hist_end, limit \\ 20) do
query = from(ph in PipelineHistory,
limit: ^limit,
order_by: [desc: :idx],
select: [ph.idx, ph.text],
where: ph.user_id == ^user_id and ph.state == "finished")
|> history_where(hist_start, hist_end)
Repo.all(query)
end
def history_entry(user_id, index) do
query = from ph in PipelineHistory,
where: ph.user_id == ^user_id and ph.idx == ^index
Repo.one(query)
end
defp now_timestamp_ms() do
DateTime.to_unix(DateTime.utc_now(), :milliseconds)
end
defp history_where(query, nil, nil),
do: query
defp history_where(query, nil, hist_end),
do: from q in query, where: q.idx <= ^hist_end
defp history_where(query, hist_start, nil),
do: from q in query, where: q.idx >= ^hist_start
defp history_where(query, hist_start, hist_end),
do: from q in query, where: q.idx >= ^hist_start and q.idx <= ^hist_end
end
|
lib/cog/repository/pipeline_history.ex
| 0.682679 | 0.412175 |
pipeline_history.ex
|
starcoder
|
defmodule Sqlitex do
@type connection :: {:connection, reference, String.t}
@type string_or_charlist :: String.t | char_list
@type sqlite_error :: {:error, {:sqlite_error, char_list}}
@moduledoc """
Sqlitex gives you a way to create and query sqlite databases.
## Basic Example
```
iex> {:ok, db} = Sqlitex.open(":memory:")
iex> Sqlitex.exec(db, "CREATE TABLE t (a INTEGER, b INTEGER, c INTEGER)")
:ok
iex> Sqlitex.exec(db, "INSERT INTO t VALUES (1, 2, 3)")
:ok
iex> Sqlitex.query(db, "SELECT * FROM t")
{:ok, [[a: 1, b: 2, c: 3]]}
iex> Sqlitex.query(db, "SELECT * FROM t", into: %{})
{:ok, [%{a: 1, b: 2, c: 3}]}
```
"""
@spec close(connection) :: :ok
def close(db) do
:esqlite3.close(db)
end
@spec open(String.t) :: {:ok, connection}
@spec open(char_list) :: {:ok, connection} | {:error, {atom, char_list}}
def open(path) when is_binary(path), do: open(String.to_char_list(path))
def open(path) do
:esqlite3.open(path)
end
def with_db(path, fun) do
{:ok, db} = open(path)
res = fun.(db)
close(db)
res
end
@spec exec(connection, string_or_charlist) :: :ok | sqlite_error
def exec(db, sql) do
:esqlite3.exec(sql, db)
end
def query(db, sql, opts \\ []), do: Sqlitex.Query.query(db, sql, opts)
def query!(db, sql, opts \\ []), do: Sqlitex.Query.query!(db, sql, opts)
def query_rows(db, sql, opts \\ []), do: Sqlitex.Query.query_rows(db, sql, opts)
def query_rows!(db, sql, opts \\ []), do: Sqlitex.Query.query_rows!(db, sql, opts)
@doc """
Create a new table `name` where `table_opts` are a list of table constraints
and `cols` are a keyword list of columns. The following table constraints are
supported: `:temp` and `:primary_key`. Example:
**[:temp, {:primary_key, [:id]}]**
Columns can be passed as:
* name: :type
* name: {:type, constraints}
where constraints is a list of column constraints. The following column constraints
are supported: `:primary_key`, `:not_null` and `:autoincrement`. Example:
**id: :integer, name: {:text, [:not_null]}**
"""
def create_table(db, name, table_opts \\ [], cols) do
stmt = Sqlitex.SqlBuilder.create_table(name, table_opts, cols)
exec(db, stmt)
end
end
|
deps/sqlitex/lib/sqlitex.ex
| 0.838515 | 0.546617 |
sqlitex.ex
|
starcoder
|
defmodule Membrane.Element.Base.Mixin.CommonBehaviour do
@moduledoc """
Module defining behaviour common to all elements.
When used declares behaviour implementation, provides default callback definitions
and imports macros.
For more information on implementing elements, see `Membrane.Element.Base`.
"""
alias Membrane.{Action, Core, Element, Event}
alias Core.CallbackHandler
alias Element.{Action, CallbackContext, Pad}
@typedoc """
Type that defines all valid return values from most callbacks.
"""
@type callback_return_t :: CallbackHandler.callback_return_t(Action.t(), Element.state_t())
@doc """
Automatically implemented callback returning specification of pads exported
by the element.
Generated by `Membrane.Element.Base.Mixin.SinkBehaviour.def_input_pads/1`
and `Membrane.Element.Base.Mixin.SourceBehaviour.def_output_pads/1` macro.
"""
@callback membrane_pads() :: [{Pad.name_t(), Core.Element.PadsSpecsParser.parsed_pad_specs_t()}]
@doc """
Automatically implemented callback used to determine if module is a membrane element.
"""
@callback membrane_element? :: true
@doc """
Automatically implemented callback determining whether element is a source,
a filter or a sink.
"""
@callback membrane_element_type :: Element.type_t()
@doc """
Callback invoked on initialization of element process. It should parse options
and initialize element internal state. Internally it is invoked inside
`c:GenServer.init/1` callback.
"""
@callback handle_init(options :: Element.options_t()) ::
{:ok, Element.state_t()}
| {:error, any}
@doc """
Callback invoked when element goes to `:prepared` state from state `:stopped` and should get
ready to enter `:playing` state.
Usually most resources used by the element are allocated here.
For example, if element opens a file, this is the place to try to actually open it
and return error if that has failed. Such resources should be released in `c:handle_prepared_to_stopped/1`.
"""
@callback handle_stopped_to_prepared(
context :: CallbackContext.PlaybackChange.t(),
state :: Element.state_t()
) :: callback_return_t
@doc """
Callback invoked when element goes to `:prepared` state from state `:playing` and should get
ready to enter `:stopped` state.
All resources allocated in `c:handle_prepared_to_playing/2` callback should be released here, and no more buffers or
demands should be sent.
"""
@callback handle_playing_to_prepared(
context :: CallbackContext.PlaybackChange.t(),
state :: Element.state_t()
) :: callback_return_t
@doc """
Callback invoked when element is supposed to start playing (goes from state `:prepared` to `:playing`).
This is moment when initial demands are sent and first buffers are generated
if there are any pads in the push mode.
"""
@callback handle_prepared_to_playing(
context :: CallbackContext.PlaybackChange.t(),
state :: Element.state_t()
) :: callback_return_t
@doc """
Callback invoked when element is supposed to stop (goes from state `:prepared` to `:stopped`).
Usually this is the place for releasing all remaining resources
used by the element. For example, if element opens a file in `c:handle_stopped_to_prepared/2`,
this is the place to close it.
"""
@callback handle_prepared_to_stopped(
context :: CallbackContext.PlaybackChange.t(),
state :: Element.state_t()
) :: callback_return_t
@doc """
Callback invoked when element receives a message that is not recognized
as an internal membrane message.
Useful for receiving ticks from timer, data sent from NIFs or other stuff.
"""
@callback handle_other(
message :: any(),
context :: CallbackContext.Other.t(),
state :: Element.state_t()
) :: callback_return_t
@doc """
Callback that is called when new pad has beed added to element. Executed
ONLY for dynamic pads.
"""
@callback handle_pad_added(
pad :: Pad.ref_t(),
context :: CallbackContext.PadAdded.t(),
state :: Element.state_t()
) :: callback_return_t
@doc """
Callback that is called when some pad of the element has beed removed. Executed
ONLY for dynamic pads.
"""
@callback handle_pad_removed(
pad :: Pad.ref_t(),
context :: CallbackContext.PadRemoved.t(),
state :: Element.state_t()
) :: callback_return_t
@doc """
Callback that is called when event arrives.
Events may arrive from both sinks and sources. In filters by default event is
forwarded to all sources or sinks, respectively. If event is either
`Membrane.Event.StartOfStream` or `Membrane.Event.EndOfStream`, notification
is sent, to notify the pipeline that data processing is started or finished.
This behaviour can be overriden, e.g. by sending end of stream notification
after elements internal buffers become empty.
"""
@callback handle_event(
pad :: Pad.ref_t(),
event :: Event.t(),
context :: CallbackContext.Event.t(),
state :: Element.state_t()
) :: callback_return_t
@doc """
Callback invoked when element is shutting down just before process is exiting.
Internally called in `c:GenServer.termintate/2` callback.
"""
@callback handle_shutdown(state :: Element.state_t()) :: :ok
@default_quoted_specs %{
atom:
quote do
atom()
end,
boolean:
quote do
boolean()
end,
string:
quote do
String.t()
end,
keyword:
quote do
keyword()
end,
struct:
quote do
struct()
end,
caps:
quote do
struct()
end
}
@doc """
Macro that defines options that parametrize element.
It automatically generates appropriate struct.
`def_options/1` should receive keyword list, where each key is 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_quoted_specs))}` 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
* `description:` string describing an option. It will be present in value returned by `options/0`
and in typedoc for the struct.
"""
defmacro def_options(options) do
{opt_specs, escaped_opts} = extract_specs(options)
opt_typespec_ast = {:%{}, [], Keyword.put(opt_specs, :__struct__, __CALLER__.module)}
# opt_typespec_ast is equivalent of typespec %__CALLER__.module{key: value, ...}
typedoc =
escaped_opts
|> Enum.map(fn {k, v} ->
desc =
v
|> Keyword.get(:description, "")
|> String.trim()
default_val_desc =
if Keyword.has_key?(v, :default) do
quote do
"\n\n Defaults to `#{inspect(unquote(v)[:default])}`"
end
else
""
end
quote do
"* `#{Atom.to_string(unquote(k))}`: #{unquote(desc)}#{unquote(default_val_desc)}"
end
end)
|> Enum.reduce(fn x, acc ->
quote do
unquote(x) <> "\n" <> unquote(acc)
end
end)
quote do
@typedoc """
Struct containing options for `#{inspect(__MODULE__)}`
#{unquote(typedoc)}
"""
@type t :: unquote(opt_typespec_ast)
@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
defp extract_specs(kw) when is_list(kw) do
with_default_specs =
kw
|> Enum.map(fn {k, v} ->
quoted_any =
quote do
any()
end
default_val = @default_quoted_specs |> Map.get(v[:type], quoted_any)
{k, v |> Keyword.put_new(:spec, default_val)}
end)
opt_typespecs =
with_default_specs
|> Enum.map(fn {k, v} -> {k, v[:spec]} end)
escaped_opts =
with_default_specs
|> Enum.map(fn {k, v} ->
{k, v |> Keyword.update!(:spec, &Macro.to_string/1)}
end)
{opt_typespecs, escaped_opts}
end
defmacro __using__(_) do
quote location: :keep do
@behaviour unquote(__MODULE__)
use Membrane.Log, tags: :element, import: false
alias Membrane.Element.CallbackContext, as: Ctx
import unquote(__MODULE__), only: [def_options: 1]
@impl true
def membrane_element?, do: true
@impl true
def handle_init(%opt_struct{} = options), do: {:ok, options |> Map.from_struct()}
def handle_init(options), do: {:ok, options}
@impl true
def handle_stopped_to_prepared(_context, state), do: {:ok, state}
@impl true
def handle_playing_to_prepared(_context, state), do: {:ok, state}
@impl true
def handle_prepared_to_playing(_context, state), do: {:ok, state}
@impl true
def handle_prepared_to_stopped(_context, state), do: {:ok, state}
@impl true
def handle_other(_message, _context, state), do: {:ok, state}
@impl true
def handle_pad_added(_pad, _context, state), do: {:ok, state}
@impl true
def handle_pad_removed(_pad, _context, state), do: {:ok, state}
@impl true
def handle_event(pad, %Event.StartOfStream{}, _context, state),
do: {{:ok, notify: {:start_of_stream, pad}}, state}
@impl true
def handle_event(pad, %Event.EndOfStream{}, _context, state),
do: {{:ok, notify: {:end_of_stream, pad}}, state}
def handle_event(_pad, _event, _context, state), do: {:ok, state}
@impl true
def handle_shutdown(_state), do: :ok
defoverridable handle_init: 1,
handle_stopped_to_prepared: 2,
handle_playing_to_prepared: 2,
handle_prepared_to_playing: 2,
handle_prepared_to_stopped: 2,
handle_other: 3,
handle_pad_added: 3,
handle_pad_removed: 3,
handle_event: 4,
handle_shutdown: 1
end
end
end
|
lib/membrane/element/base/mixin/common_behaviour.ex
| 0.919208 | 0.403714 |
common_behaviour.ex
|
starcoder
|
defmodule BetterParams do
@behaviour Plug
@moduledoc """
Implementation of the `BetterParams` plug and its core logic.
See the [`README`](https://github.com/sheharyarn/better_params) for
installation and usage instructions.
"""
@doc """
Initializes the Plug.
"""
@impl Plug
def init(opts) do
opts
end
@doc """
Implementation of the Plug
This implements the `call` callback of the Plug. It calls the
`symbolize_merge/2` method on the `Plug.Conn` params map, so
they are available both with String and Atom keys.
"""
@impl Plug
def call(%{params: params} = conn, opts) do
%{ conn | params: symbolize_merge(params, opts) }
end
@doc """
Converts String keys of a Map to Atoms
Takes a Map with String keys and an optional keyword list
of options. Returns a new map with all values accessible
by both String and Atom keys. If the map is nested, it
symbolizes all sub-maps as well.
The only option supported at this time is `drop_string_keys`
which defaults to `false`. When set `true`, it will
return a new map with only Atom version of the keys.
## Example
```
map = %{"a" => 1, "b" => %{"c" => 2, "d" => 3}}
mixed_map = BetterParams.symbolize_merge(map)
# => %{:a => 1, :b => %{c: 2, d: 3}, "a" => 1, "b" => %{"c" => 2, "d" => 3}}
atom_map = BetterParams.symbolize_merge(map, drop_string_keys: true)
# => %{a: 1, b: %{c: 2, d: 3}}
mixed_map[:a] # => 1
mixed_map[:b][:c] # => 2
mixed_map.b.d # => 3
```
"""
@spec symbolize_merge(map :: map, opts :: Keyword.t) :: map
def symbolize_merge(map, opts \\ []) when is_map(map) do
atom_map =
map
|> Map.delete(:__struct__)
|> symbolize_keys
if Keyword.get(opts, :drop_string_keys, false) do
atom_map
else
Map.merge(map, atom_map)
end
end
## Private Methods
defp symbolize_keys(%{__struct__: _module} = struct) do
struct
end
defp symbolize_keys(map) when is_map(map) do
Enum.reduce(map, %{}, fn {k, v}, m ->
map_put(m, k, symbolize_keys(v))
end)
end
defp symbolize_keys(list) when is_list(list) do
Enum.map(list, &symbolize_keys/1)
end
defp symbolize_keys(term), do: term
defp map_put(map, k, v) when is_map(map) do
cond do
is_binary(k) -> Map.put(map, String.to_existing_atom(k), v)
true -> Map.put(map, k, v)
end
rescue
ArgumentError -> map
end
end
|
lib/better_params.ex
| 0.834103 | 0.904355 |
better_params.ex
|
starcoder
|
defmodule Finitomata do
@moduledoc "README.md" |> File.read!() |> String.split("\n---") |> Enum.at(1)
require Logger
use Boundary, top_level?: true, deps: [], exports: [Supervisor, Transition]
alias Finitomata.Transition
defmodule State do
@moduledoc """
Carries the state of the FSM.
"""
alias Finitomata.Transition
@typedoc "The payload that has been passed to the FSM instance on startup"
@type payload :: any()
@typedoc "The internal representation of the FSM state"
@type t :: %{
__struct__: State,
current: Transition.state(),
payload: payload(),
history: [Transition.state()]
}
defstruct [:current, :payload, history: []]
end
@typedoc "The payload that can be passed to each call to `transition/3`"
@type event_payload :: any()
@doc """
This callback will be called from each transition processor.
"""
@callback on_transition(
Transition.state(),
Transition.event(),
event_payload(),
State.payload()
) ::
{:ok, Transition.state(), State.payload()} | :error
@doc """
This callback will be called if the transition failed to complete to allow
the consumer to take an action upon failure.
"""
@callback on_failure(Transition.event(), event_payload(), State.t()) :: :ok
@doc """
This callback will be called on entering the state.
"""
@callback on_enter(Transition.state(), State.t()) :: :ok
@doc """
This callback will be called on exiting the state.
"""
@callback on_exit(Transition.state(), State.t()) :: :ok
@doc """
This callback will be called on transition to the final state to allow
the consumer to perform some cleanup, or like.
"""
@callback on_terminate(State.t()) :: :ok
@doc """
Starts the FSM instance.
The arguments are
- the implementation of FSM (the module, having `use Finitomata`)
- the name of the FSM (might be any term, but it must be unique)
- the payload to be carried in the FSM state during the lifecycle
The FSM is started supervised.
"""
@spec start_fsm(module(), any(), any()) :: DynamicSupervisor.on_start_child()
def start_fsm(impl, name, payload),
do:
DynamicSupervisor.start_child(Finitomata.Manager, {impl, name: fqn(name), payload: payload})
@doc """
Initiates the transition.
The arguments are
- the name of the FSM
- `{event, event_payload}` tuple; the payload will be passed to the respective
`on_transition/4` call
"""
@spec transition(GenServer.name(), {Transition.event(), State.payload()}) :: :ok
def transition(target, {event, payload}),
do: target |> fqn() |> GenServer.cast({event, payload})
@doc """
The state of the FSM.
"""
@spec state(GenServer.name()) :: State.t()
def state(target), do: target |> fqn() |> GenServer.call(:state)
@doc """
Returns `true` if the transition to the state `state` is possible, `false` otherwise.
"""
@spec allowed?(GenServer.name(), Transition.state()) :: boolean()
def allowed?(target, state), do: target |> fqn() |> GenServer.call({:allowed?, state})
@doc """
Returns `true` if the transition by the event `event` is possible, `false` otherwise.
"""
@spec responds?(GenServer.name(), Transition.event()) :: boolean()
def responds?(target, event), do: target |> fqn() |> GenServer.call({:responds?, event})
@doc """
Returns `true` if the supervision tree is alive, `false` otherwise.
"""
@spec alive? :: boolean()
def alive?, do: is_pid(Process.whereis(Registry.Finitomata))
@doc """
Returns `true` if the FSM specified is alive, `false` otherwise.
"""
@spec alive?(GenServer.name()) :: boolean()
def alive?(target), do: target |> fqn() |> GenServer.whereis() |> is_pid()
@doc false
@spec child_spec(non_neg_integer()) :: Supervisor.child_spec()
def child_spec(id \\ 0),
do: Supervisor.child_spec({Finitomata.Supervisor, []}, id: {Finitomata, id})
@doc false
defmacro __using__({plant, syntax}), do: ast(plant, syntax: syntax)
defmacro __using__(plant), do: ast(plant, [])
@doc false
def ast(plant, options \\ []) do
quote location: :keep, generated: true do
require Logger
alias Finitomata.Transition, as: Transition
use GenServer, restart: :transient, shutdown: 5_000
@before_compile Finitomata.Hook
@syntax Keyword.get(
unquote(options),
:syntax,
Application.compile_env(:finitomata, :syntax, Finitomata.Mermaid)
)
@md_syntax @syntax
|> Module.split()
|> List.last()
|> Macro.underscore()
@plant (case @syntax.parse(unquote(plant)) do
{:ok, result} ->
result
{:error, description, snippet, _, {line, column}, _} ->
raise SyntaxError,
file: "lib/finitomata.ex",
line: line,
column: column,
description: description,
snippet: %{content: snippet, offset: 0}
{:error, error} ->
raise TokenMissingError,
description: "description is incomplete, error: #{error}"
end)
@doc false
def start_link(payload: payload, name: name),
do: start_link(name: name, payload: payload)
@doc ~s"""
Starts an _FSM_ alone with `name` and `payload` given.
Usually one does not want to call this directly, the most common way would be
to start a `Finitomata` supervision tree with `Finitomata.Supervisor.start_link/1`
or even better embed it into the existing supervision tree _and_
start _FSM_ with `Finitomata.start_fsm/3` passing `#{__MODULE__}` as the first
parameter.
FSM representation
```#{@md_syntax}
#{@syntax.lint(unquote(plant))}
```
"""
def start_link(name: name, payload: payload),
do: GenServer.start_link(__MODULE__, payload, name: name)
@doc false
@impl GenServer
def init(payload) do
# Process.flag(:trap_exit, true)
{:ok, %State{current: Transition.entry(@plant), payload: payload}}
end
@doc false
@impl GenServer
def handle_call(:state, _from, state), do: {:reply, state, state}
@doc false
@impl GenServer
def handle_call({:allowed?, to}, _from, state),
do: {:reply, Transition.allowed?(@plant, state.current, to), state}
@doc false
@impl GenServer
def handle_call({:responds?, event}, _from, state),
do: {:reply, Transition.responds?(@plant, state.current, event), state}
@doc false
@impl GenServer
def handle_cast({event, payload}, state) do
with {:on_exit, :ok} <- {:on_exit, safe_on_exit(state.current, state)},
{:ok, new_current, new_payload} <-
safe_on_transition(state.current, event, payload, state.payload),
{:allowed, true} <-
{:allowed, Transition.allowed?(@plant, state.current, new_current)},
state <- %State{
state
| payload: new_payload,
current: new_current,
history: [state.current | state.history]
},
{:on_entry, :ok} <- {:on_entry, safe_on_enter(new_current, state)} do
case new_current do
:* ->
{:stop, :normal, state}
_ ->
{:noreply, state}
end
else
err ->
Logger.warn("[⚐ ⇄] transition failed " <> inspect(err))
safe_on_failure(event, payload, state)
{:noreply, state}
end
end
@doc false
@impl GenServer
def terminate(reason, state) do
safe_on_terminate(state)
end
@spec safe_on_transition(
Transition.state(),
Transition.event(),
Finitomata.event_payload(),
State.payload()
) ::
{:ok, Transition.state(), State.payload()} | :error
defp safe_on_transition(current, event, event_payload, state_payload) do
on_transition(current, event, event_payload, state_payload)
rescue
err ->
case err do
%{__exception__: true} ->
{:error, Exception.message(err)}
_ ->
Logger.warn("[⚑ ⇄] on_transition raised " <> inspect(err))
{:error, :on_transition_raised}
end
end
@spec safe_on_failure(Transition.event(), Finitomata.event_payload(), State.t()) :: :ok
defp safe_on_failure(event, event_payload, state_payload) do
on_failure(event, event_payload, state_payload)
rescue
err -> Logger.warn("[⚑ ⇄] on_failure raised " <> inspect(err))
end
@spec safe_on_enter(Transition.state(), State.t()) :: :ok
defp safe_on_enter(state, state_payload) do
on_enter(state, state_payload)
rescue
err -> Logger.warn("[⚑ ⇄] on_enter raised " <> inspect(err))
end
@spec safe_on_exit(Transition.state(), State.t()) :: :ok
defp safe_on_exit(state, state_payload) do
on_exit(state, state_payload)
rescue
err -> Logger.warn("[⚑ ⇄] on_exit raised " <> inspect(err))
end
@spec safe_on_terminate(State.t()) :: :ok
defp safe_on_terminate(state) do
on_terminate(state)
rescue
err -> Logger.warn("[⚑ ⇄] on_terminate raised " <> inspect(err))
end
@behaviour Finitomata
end
end
@typedoc """
Error types of FSM validation
"""
@type validation_error :: :initial_state | :final_state | :orphan_from_state | :orphan_to_state
@doc false
@spec validate([{:transition, [binary()]}]) ::
{:ok, [Transition.t()]} | {:error, validation_error()}
def validate(parsed) do
from_states = parsed |> Enum.map(fn {:transition, [from, _, _]} -> from end) |> Enum.uniq()
to_states = parsed |> Enum.map(fn {:transition, [_, to, _]} -> to end) |> Enum.uniq()
cond do
Enum.count(parsed, &match?({:transition, ["[*]", _, _]}, &1)) != 1 ->
{:error, :initial_state}
Enum.count(parsed, &match?({:transition, [_, "[*]", _]}, &1)) < 1 ->
{:error, :final_state}
from_states -- to_states != [] ->
{:error, :orphan_from_state}
to_states -- from_states != [] ->
{:error, :orphan_to_state}
true ->
{:ok, Enum.map(parsed, &(&1 |> elem(1) |> Transition.from_parsed()))}
end
end
@spec fqn(any()) :: {:via, module(), {module, any()}}
defp fqn(name), do: {:via, Registry, {Registry.Finitomata, name}}
end
|
lib/finitomata.ex
| 0.871721 | 0.64699 |
finitomata.ex
|
starcoder
|
defmodule WMS.Placement do
@moduledoc """
`WMS.Placement` is a process that handles cart delivery placement from acquiring to cells.
"""
require KVS
require ERP
require BPE
require Record
Record.defrecord(:placement, [:path, :item])
def auth(_), do: true
def clear(proc) do
feed = '/wms/in/' ++ :nitro.compact(BPE.process(proc, :name))
things = :kvs.all(feed)
:lists.map(fn x -> :kvs.append(ERP."Item"(x, status: :incart), feed) end, things)
IO.inspect(things)
end
def findPlacement(order) do
feed = '/wms/in/' ++ :nitro.compact(order)
things = :kvs.all(feed)
case :lists.partition(fn ERP."Item"(status: x) -> x == :incart end, things) do
{[], _} -> {[], feed, []}
{[h], _} -> {h, feed, :last}
{[h | _], _} -> {h, feed, []}
end
end
def allocateCell(_item) do
'/wms/cells/1/2/3'
end
def def() do
BPE.process(
name: "Default Name",
flows: [
BPE.sequenceFlow(name: :First, source: :Created, target: :Main),
BPE.sequenceFlow(name: :Second, source: :Main, target: :Final)
],
tasks: [
BPE.beginEvent(name: :Created, module: WMS.Placement),
BPE.userTask(name: :Main, module: WMS.Placement),
BPE.endEvent(name: :Final, module: WMS.Placement)
],
beginEvent: :Created,
endEvent: :Final,
events: [BPE.messageEvent(name: :AsyncEvent),
BPE.boundaryEvent(name: :*, timeout: BPE.timeout(spec: {0, {10, 0, 10}}))]
)
end
def action({:request, :Created, _}, proc) do
IO.inspect("CREATED")
clear(proc)
{:reply, proc}
end
def action({:request, :Main, _}, proc) do
case :bpe.doc({:order}, proc) do
{:order, id} ->
IO.inspect id
case findPlacement(id) do
{[], _, _} ->
{:reply, :Final, BPE.process(proc, docs: [{:close}])}
{item, feed, _} ->
path = allocateCell(item)
place = placement(path: path, item: item)
item = ERP."Item"(item, status: :placed)
:kvs.append(item, feed)
:kvs.append(item, path)
{:reply, :Main, BPE.process(proc, docs: [place,{:order,id}])}
end
[] ->
{:reply, :Main, proc}
end
end
def action({:request, :Final, _}, proc) do
IO.inspect("FINAL")
{:stop, BPE.process(proc, docs: [{:close}])}
end
def action(_, proc), do: {:reply, proc}
end
|
lib/actors/placement.ex
| 0.53777 | 0.433262 |
placement.ex
|
starcoder
|
defmodule Nile do
@doc """
Expand each item into 0..n items
iex> Nile.expand(0..10, &([&1, &1])) |> Enum.take(12)
[0,0,1,1,2,2,3,3,4,4,5,5]
"""
def expand(stream, fun) do
Stream.resource(
fn -> {stream, fun} end,
fn ({stream, fun} = s) ->
case Nile.Utils.next(stream) do
{status, _} when status in [:done, :halted] ->
{:halt, s}
{:suspended, item, stream} ->
{fun.(item), {stream, fun}}
end
end,
fn (_) -> :ok end
)
end
@doc """
Duplicate each element in a stream "n" times
iex> Nile.duplicate(0..3, 3) |> Enum.take(12)
[0,0,0,1,1,1,2,2,2,3,3,3]
"""
def duplicate(stream, n \\ 2) do
expand(stream, fn(item) ->
Stream.repeatedly(fn -> item end)
|> Stream.take(n)
end)
end
@doc """
Loop a stream repeatedly
iex> Nile.repeat(0..3) |> Enum.take(10)
[0,1,2,3,0,1,2,3,0,1]
iex> Nile.repeat(0..3, 2) |> Enum.take(10)
[0,1,2,3,0,1,2,3]
"""
def repeat(stream, n \\ :infinity) do
Stream.resource(
fn -> 0 end,
fn
(count) when count < n ->
{stream, count + 1}
(count) ->
{:halt, count}
end,
fn(_) -> :ok end
)
end
@doc """
Loop a stream with alternating directions
iex> Nile.ping_pong(0..3) |> Enum.take(10)
[0,1,2,3,2,1,0,1,2,3]
iex> Nile.ping_pong(0..3, 1) |> Enum.take(10)
[0,1,2,3,2,1]
iex> Nile.ping_pong(0..3, 1, :inclusive) |> Enum.take(10)
[0,1,2,3,3,2,1,0]
"""
def ping_pong(stream, n \\ :infinity, mode \\ :exclusive) do
Stream.resource(
fn -> {stream, nil, 0} end,
fn
({s, rev, count}) when count < n ->
case Nile.Utils.next(s) do
{status, _} when status in [:done, :halted] ->
list = case mode do
:exclusive ->
tl(rev)
:inclusive ->
rev
end
{list, {stream, nil, count + 1}}
{:suspended, item, s} when is_list(rev) ->
{[item], {s, [item | rev], count}}
{:suspended, item, s} when mode == :exclusive ->
{[item], {s, [], count}}
{:suspended, item, s} when mode == :inclusive ->
{[item], {s, [item], count}}
end
(state) ->
{:halt, state}
end,
fn({s, _, _}) -> Nile.Utils.halt(s) end
)
end
@doc """
Emit a sequence of values n times
iex> Nile.emit(foo: 2, bar: 3) |> Enum.to_list()
[:foo,:foo,:bar,:bar,:bar]
"""
def emit(values) do
values
|> Stream.flat_map(fn({value, times}) ->
Stream.repeatedly(fn -> value end)
|> Stream.take(times)
end)
end
@doc """
Reset a stream with a control stream
iex> 0..100 |> Nile.reset(Nile.emit(false: 3, true: 1) |> Nile.repeat()) |> Enum.take(10)
[0,1,2,0,1,2,0,1,2,0]
"""
def reset(source, control) do
Stream.resource(
fn -> {source, control} end,
fn ({s, c}) ->
case Nile.Utils.next(c) do
{status, c} when status in [:done, :halted] ->
{:halt, {s, c}}
{:suspended, true, c} ->
Nile.Utils.halt(s)
{[], {source, c}}
{:suspended, _, c} ->
case Nile.Utils.next(s) do
{status, s} when status in [:done, :halted] ->
{:halt, {s, c}}
{:suspended, item, s} ->
{[item], {s, c}}
end
end
end,
fn({s, c}) ->
Nile.Utils.halt(s)
Nile.Utils.halt(c)
end
)
end
@doc """
Concatenate streams lazily
iex> Nile.lazy_concat(fn -> 1..3 end) |> Enum.take(9)
[1,2,3,1,2,3,1,2,3]
"""
def lazy_concat(fun) do
Stream.resource(
fn -> nil end,
fn(s) ->
case fun.() do
nil ->
{:halt, s}
stream ->
{stream, s}
end
end,
fn(_) -> :ok end
)
end
@doc """
Concatenate streams lazily with state
iex> Nile.lazy_concat(0, &{&1..&1+2, &1+1}) |> Enum.take(12)
[0,1,2,1,2,3,2,3,4,3,4,5]
"""
def lazy_concat(state, fun) do
Stream.resource(
fn -> state end,
fn(s) ->
case fun.(s) do
nil ->
{:halt, s}
{stream, s} ->
{stream, s}
end
end,
fn(_) -> :ok end
)
end
@doc """
Merge a stream of streams with a function
iex> [1..3, 4..7] |> Nile.merge(&Enum.sum/1) |> Enum.to_list()
[5,7,9]
"""
def merge(streams, fun) do
Stream.resource(
fn -> Enum.to_list(streams) end,
fn (streams) ->
streams
|> Enum.map_reduce([], fn
(stream, {:halt, acc}) ->
{nil, {:halt, [stream | acc]}}
(stream, acc) ->
case Nile.Utils.next(stream) do
{:suspended, v, stream} ->
{v, [stream | acc]}
{_status, stream} ->
{nil, {:halt, [stream | acc]}}
end
end)
|> case do
{_, {:halt, streams}} ->
{:halt, :lists.reverse(streams)}
{values, streams} ->
{[fun.(values)], :lists.reverse(streams)}
end
end,
fn(streams) ->
Enum.each(streams, &Nile.Utils.halt/1)
end
)
end
@doc """
Routes items in a stream into a map of lazily created collectables.
This eagerly evaluates the stream
iex> Nile.route_into(0..26, &(rem(&1, 3)), fn(_) -> [] end)
%{0 => [0, 3, 6, 9, 12, 15, 18, 21, 24],
1 => [1, 4, 7, 10, 13, 16, 19, 22, 25],
2 => [2, 5, 8, 11, 14, 17, 20, 23, 26]}
"""
defdelegate route_into(stream, router, factory), to: Nile.Router
defdelegate pmap(stream, fun), to: Nile.Pmap
@doc """
Map over a stream in parallel, spawning a pool of workers.
Options include:
* concurrency (defaults to infinity)
* timeout (defaults to infinity)
Before using, consider the cost of message passing between processes
iex> Nile.pmap(0..26, fn(t) -> :timer.sleep(t); t end) |> Enum.take(5)
[0,1,2,3,4]
"""
defdelegate pmap(stream, fun, opts), to: Nile.Pmap
@doc """
Returns the identity of the stream
"""
def identity(stream) do
stream |> Stream.map(&(&1))
end
end
|
lib/nile.ex
| 0.709221 | 0.452657 |
nile.ex
|
starcoder
|
defmodule Satchel do
@moduledoc """
Satchel is a library for serializing and de-serializing values. Currently,
only little endian is supported (for my own convenience). The following
types are supported:
* `bool` (unsigned 8-bit int)
* `int8`
* `uint8`
* `int16`
* `uint16`
* `int32`
* `uint32`
* `int64`
* `uint64`
* `float32`
* `float64`
* `string`
* `time`, a tuple of secs and nsecs where both are `uint32`s.
* `duration`, a tuple of secs and nsecs where both are `int32`s.
"""
@doc """
Pack an Elixir value as a binary.
"""
@spec pack(any(), atom()) :: binary()
def pack(data, type)
def pack(b, :bool), do: <<b::unsigned-little-integer-8>>
def pack(n, :int8), do: <<n::signed-little-integer-8>>
def pack(n, :uint8), do: <<n::unsigned-little-integer-8>>
def pack(n, :int16), do: <<n::signed-little-integer-16>>
def pack(n, :uint16), do: <<n::unsigned-little-integer-16>>
def pack(n, :int32), do: <<n::signed-little-integer-32>>
def pack(n, :uint32), do: <<n::unsigned-little-integer-32>>
def pack(n, :int64), do: <<n::signed-little-integer-64>>
def pack(n, :uint64), do: <<n::unsigned-little-integer-64>>
def pack(f, :float32), do: <<f::signed-little-float-32>>
def pack(f, :float64), do: <<f::signed-little-float-64>>
def pack(str, :string), do: str
def pack({secs, nsecs}, :time),
do: <<secs::unsigned-little-integer-32, nsecs::unsigned-little-integer-32>>
def pack({secs, nsecs}, :duration),
do: <<secs::signed-little-integer-32, nsecs::signed-little-integer-32>>
# TODO examples in @doc tag
@doc """
Unpack a binary value.
"""
@spec unpack(binary(), atom()) :: any()
def unpack(data, type)
def unpack(str, :string), do: str
def unpack(data, type) do
{value, _rest} = unpack_take(data, type)
value
end
@doc """
Unpack a binary which potentially contains other terms. Returns the value
parsed and the rest of the binary.
> This does not accept variable-sized types like `string`.
"""
@spec unpack_take(binary(), atom()) :: {any(), binary()}
def unpack_take(binary, type)
def unpack_take(<<b::unsigned-little-integer-8, rest::binary>>, :bool),
do: {b == 1, rest}
def unpack_take(<<n::signed-little-integer-8, rest::binary>>, :int8),
do: {n, rest}
def unpack_take(<<n::unsigned-little-integer-8, rest::binary>>, :uint8),
do: {n, rest}
def unpack_take(<<n::signed-little-integer-16, rest::binary>>, :int16),
do: {n, rest}
def unpack_take(<<n::unsigned-little-integer-16, rest::binary>>, :uint16),
do: {n, rest}
def unpack_take(<<n::signed-little-integer-32, rest::binary>>, :int32),
do: {n, rest}
def unpack_take(<<n::unsigned-little-integer-32, rest::binary>>, :uint32),
do: {n, rest}
def unpack_take(<<n::signed-little-integer-64, rest::binary>>, :int64),
do: {n, rest}
def unpack_take(<<n::unsigned-little-integer-64, rest::binary>>, :uint64),
do: {n, rest}
def unpack_take(<<f::signed-little-float-32, rest::binary>>, :float32),
do: {f, rest}
def unpack_take(<<f::signed-little-float-64, rest::binary>>, :float64),
do: {f, rest}
def unpack_take(
<<secs::unsigned-little-integer-32, nsecs::unsigned-little-integer-32,
rest::binary>>,
:time
),
do: {{secs, nsecs}, rest}
def unpack_take(
<<secs::signed-little-integer-32, nsecs::signed-little-integer-32,
rest::binary>>,
:duration
),
do: {{secs, nsecs}, rest}
end
|
lib/satchel.ex
| 0.733738 | 0.533944 |
satchel.ex
|
starcoder
|
defmodule Tzdata.PeriodBuilder do
@moduledoc false
alias Tzdata.Util, as: Util
# the last year to use when precalcuating rules that go into the future
# indefinitely
@years_in_the_future_where_precompiled_periods_are_used 40
@extra_years_to_precompile 4
@future_years_in_seconds (@years_in_the_future_where_precompiled_periods_are_used +
@extra_years_to_precompile) * 31_556_736
@max_gregorian_for_rules :calendar.universal_time()
|> :calendar.datetime_to_gregorian_seconds()
|> Kernel.+(@future_years_in_seconds)
defmodule State do
defstruct utc_off: 0,
std_off: 0,
letter: :undefined,
utc_from: :min
end
alias __MODULE__.State
def calc_periods(btz_data, zone_name) do
{:ok, zone} = Map.fetch(btz_data.zones, zone_name)
{periods, _} =
Enum.flat_map_reduce(zone.zone_lines, %State{}, &calc_periods_for_line(btz_data, &1, &2))
combine_periods(periods, [])
end
def calc_periods_for_line(_btz_data, %{rules: nil} = zone_line, state) do
state = %{state | std_off: 0}
build_period(zone_line, state)
end
def calc_periods_for_line(_btz_data, %{rules: {:amount, std_off}} = zone_line, state) do
state = %{state | std_off: std_off}
build_period(zone_line, state)
end
def calc_periods_for_line(btz_data, %{rules: {:named_rules, rule_name}} = zone_line, state) do
{:ok, rules} = Map.fetch(btz_data.rules, rule_name)
calc_named_rule_periods(zone_line, state, rules)
end
def combine_periods([first, second | rest], acc) do
if first.std_off == second.std_off and first.utc_off == second.utc_off and
first.zone_abbr == second.zone_abbr do
combined = Map.put(first, :until, second.until)
combine_periods([combined | rest], acc)
else
combine_periods([second | rest], [first | acc])
end
end
def combine_periods(rest, acc) do
Enum.reverse(acc, rest)
end
defp calc_named_rule_periods(zone_line, state, [_ | _] = rules) do
utc_off = zone_line.gmtoff
std_off = state.std_off
zone_until = zone_until(zone_line, utc_off, std_off)
state = ensure_letter(state, rules)
rules = Enum.sort_by(rules, &{&1.in, &1.from})
case next_rule_by_time(rules, state.utc_from, utc_off, std_off) do
nil ->
# no rule for the rest of the year. the current period goes until the
# start of next year, or the end of the period, whichever comes first
end_of_year = end_of_year_utc(state.utc_from, utc_off, std_off)
{[period], state} = build_period(zone_line, state, min(end_of_year, zone_until))
{periods, state} =
if end_of_year < zone_until and end_of_year < @max_gregorian_for_rules do
rules = filter_rules_after(rules, period)
calc_named_rule_periods(zone_line, state, rules)
else
{[], state}
end
{[period | periods], state}
{utc_until, rule} when utc_until < zone_until ->
# transition happens at utc_until, and the new state should have the values from rule
{[period], state} = build_period(zone_line, state, utc_until)
state = %{state | std_off: rule.save, letter: rule.letter}
rules = filter_rules_after(rules, period)
{periods, state} = calc_named_rule_periods(zone_line, state, rules)
{[period | periods], state}
{^zone_until, rule} ->
# next transition happens when the zone ends: update the state but
# otherwise build a normal period
{periods, state} = build_period(zone_line, state)
state = %{state | std_off: rule.save, letter: rule.letter}
{periods, state}
{_, _} ->
# next transition happens after the zone ends: build a normal period
build_period(zone_line, state)
end
end
defp calc_named_rule_periods(zone_line, state, []) do
# no more valid rules; the current one goes to the end of the zone line
build_period(zone_line, state)
end
defp filter_rules_after(rules, period) do
{{year, _, _}, _} = :calendar.gregorian_seconds_to_datetime(period.until.standard)
Enum.filter(rules, &Util.rule_applies_after_year?(&1, year))
end
defp build_period(zone_line, state, until \\ nil) do
%{
gmtoff: utc_off,
format: format
} = zone_line
%{
utc_from: utc_from,
std_off: std_off,
letter: letter
} = state
utc_until =
if until do
until
else
zone_until(zone_line, utc_off, std_off)
end
period = %{
std_off: std_off,
utc_off: utc_off,
zone_abbr: Util.period_abbrevation(format, std_off, letter),
from: times_from_utc(utc_from, utc_off, std_off),
until: times_from_utc(utc_until, utc_off, std_off)
}
state = %{state | utc_off: utc_off, utc_from: utc_until}
{[period], state}
end
defp zone_until(%{until: datetime}, utc_off, std_off) do
Util.datetime_to_utc(datetime, utc_off, std_off)
end
defp zone_until(%{}, _, _) do
:max
end
defp times_from_utc(utc_time, utc_off, std_off) when is_integer(utc_time) do
%{utc: utc_time, standard: utc_time + utc_off, wall: utc_time + utc_off + std_off}
end
defp times_from_utc(utc_time, _, _) when utc_time in [:min, :max] do
%{utc: utc_time, standard: utc_time, wall: utc_time}
end
defp end_of_year_utc(seconds, utc_off, std_off) do
{{year, _, _}, _} = :calendar.gregorian_seconds_to_datetime(seconds + utc_off)
Util.datetime_to_utc({{{year + 1, 1, 1}, {0, 0, 0}}, :standard}, utc_off, std_off)
end
defp ensure_letter(%{letter: binary} = state, _) when is_binary(binary) do
state
end
defp ensure_letter(%{letter: :undefined} = state, rules) do
letter = Enum.find_value(rules, &(&1.save == 0 && &1.letter))
%{state | letter: letter}
end
defp next_rule_by_time(rules, utc_seconds, utc_off, std_off) when is_integer(utc_seconds) do
{wall_day, _} = :calendar.gregorian_seconds_to_datetime(utc_seconds + utc_off + std_off)
next_rule_by_date(rules, wall_day, utc_seconds, utc_off, std_off)
end
defp next_rule_by_time(rules, :min, utc_off, std_off) do
# we transition at the start of the first rule
rule = Enum.min_by(rules, &{&1.from, &1.in})
rule_dt = Util.time_for_rule(rule, rule.from)
rule_utc = Util.datetime_to_utc(rule_dt, utc_off, std_off)
{rule_utc, rule}
end
defp next_rule_by_date([rule | rules], date, utc_seconds, utc_off, std_off) do
{wall_year, wall_month, wall_day} = date
result =
if Util.rule_applies_for_year(rule, wall_year) do
{{{_, month, day}, _}, _} = rule_dt = Util.time_for_rule(rule, wall_year)
if {month, day} > {wall_month, wall_day} do
rule_utc = Util.datetime_to_utc(rule_dt, utc_off, std_off)
if rule_utc > utc_seconds do
{rule_utc, rule}
end
end
end
if result do
result
else
next_rule_by_date(rules, date, utc_seconds, utc_off, std_off)
end
end
defp next_rule_by_date([], _, _, _, _) do
nil
end
end
|
deps/tzdata/lib/tzdata/period_builder.ex
| 0.742515 | 0.564098 |
period_builder.ex
|
starcoder
|
defmodule Support.Harness.Validation do
import ExUnit.Assertions
alias Absinthe.{Blueprint, Schema, Phase, Pipeline, Language}
@type error_checker_t :: ([{Blueprint.t, Blueprint.Error.t}] -> boolean)
defmacro __using__(_) do
quote do
import unquote(__MODULE__)
def bad_value(node_kind, message, line, check \\ []) do
location = case List.wrap(line) do
[single] ->
"(from line ##{single})"
multiple when is_list(multiple) ->
numbers = multiple |> Enum.join(", #")
"(from lines ##{numbers})"
nil ->
"(at any line number)"
end
expectation_banner = "\nExpected #{node_kind} node with error #{location}:\n---\n#{message}\n---"
check_fun = node_check_function(check)
fn
pairs ->
assert !Enum.empty?(pairs), "No errors were found.\n#{expectation_banner}"
matched = Enum.any?(pairs, fn
{%str{} = node, %Phase.Error{phase: @rule, message: ^message} = err} when str == node_kind ->
if check_fun.(node) do
if !line do
true
else
List.wrap(line)
|> Enum.all?(fn
l ->
Enum.any?(err.locations, fn
%{line: ^l} ->
true
_ ->
false
end)
end)
end
else
false
end
_ ->
false
end)
formatted_errors = Enum.map(pairs, fn
{_, error} ->
error.message
end)
assert matched, "Could not find error.\n#{expectation_banner}\n\n Did find these errors...\n ---\n " <> Enum.join(formatted_errors, "\n ") <> "\n ---"
end
end
defp node_check_function(check) when is_list(check) do
fn
node ->
Enum.all?(check, fn {key, value} -> Map.get(node, key) == value end)
end
end
defp node_check_function(check) when is_function(check) do
check
end
end
end
@spec assert_valid(Schema.t, [Phase.t], Language.Source.t, map) :: no_return
def assert_valid(schema, rules, document, options) do
result = case run(schema, rules, document, options) do
{:ok, result} ->
result
# :jump, etc
{_other, result, _config} ->
result
end
formatted_errors = Enum.map(error_pairs(result), fn
{_, error} ->
error.message
end)
assert Enum.empty?(formatted_errors), "Expected no errors, found:\n ---\n " <> Enum.join(formatted_errors, "\n ") <> "\n ---"
end
@spec assert_invalid(Schema.t, [Phase.t], Language.Source.t, map, [error_checker_t] | error_checker_t) :: no_return
def assert_invalid(schema, rules, document, options, error_checkers) do
result = case run(schema, rules, document, options) do
{:ok, result, _} ->
result
# :jump, etc
{_other, result, _config} ->
result
end
pairs = error_pairs(result)
List.wrap(error_checkers)
|> Enum.each(&(&1.(pairs)))
end
@spec assert_passes_rule(Phase.t, Language.Source.t, map) :: no_return
def assert_passes_rule(rule, document, options) do
assert_valid(Support.Harness.Validation.Schema, [rule], document, options)
end
@spec assert_fails_rule(Phase.t, Language.Source.t, map, [error_checker_t] | error_checker_t) :: no_return
def assert_fails_rule(rule, document, options, error_checker) do
assert_invalid(Support.Harness.Validation.Schema, [rule], document, options, error_checker)
end
@spec assert_passes_rule_with_schema(Schema.t, Phase.t, Language.Source.t, map) :: no_return
def assert_passes_rule_with_schema(schema, rule, document, options) do
assert_valid(schema, [rule], document, options)
end
@spec assert_fails_rule_with_schema(Schema.t, Phase.t, Language.Source.t, map, error_checker_t) :: no_return
def assert_fails_rule_with_schema(schema, rule, document, options, error_checker) do
assert_invalid(schema, [rule], document, options, error_checker)
end
defp run(schema, rules, document, options) do
pipeline = pre_validation_pipeline(schema, options)
Pipeline.run(document, pipeline ++ rules)
end
defp pre_validation_pipeline(schema, :schema) do
Pipeline.for_schema(schema)
|> Pipeline.upto(Phase.Schema)
end
defp pre_validation_pipeline(schema, options) do
Pipeline.for_document(schema, options)
|> Pipeline.upto(Phase.Document.Validation.Result)
|> Pipeline.reject(~r/Validation/)
end
# Build a map of node => errors
defp nodes_with_errors(input) do
{_, errors} = Blueprint.prewalk(input, [], &do_nodes_with_errors/2)
errors
end
defp error_pairs(input) do
nodes_with_errors(input)
|> Enum.flat_map(fn
%{errors: errors} = node ->
Enum.map(errors, &{node, &1})
end)
end
defp do_nodes_with_errors(%{errors: []} = node, acc) do
{node, acc}
end
defp do_nodes_with_errors(%{errors: _} = node, acc) do
{node, [node | acc]}
end
defp do_nodes_with_errors(node, acc) do
{node, acc}
end
end
|
test/support/harness/validation.ex
| 0.70304 | 0.446796 |
validation.ex
|
starcoder
|
defmodule ExAws.Boto.Util do
@doc """
Converts a service ID and shape name into an Elixir module
## Examples
iex> ExAws.Boto.Util.module_name("SomeService", "TestObject")
ExAws.SomeService.TestObject
"""
def module_name(service_id, shape \\ nil)
def module_name(service_id, nil) do
["Elixir", "ExAws", Macro.camelize(service_id), "Api"]
|> Enum.join(".")
|> String.to_atom()
end
def module_name(service_id, %{"shape" => shape_name}) do
module_name(service_id, shape_name)
end
def module_name(service_id, shape_name) when is_binary(shape_name) do
["Elixir", "ExAws", Macro.camelize(service_id), Macro.camelize(shape_name)]
|> Enum.join(".")
|> String.to_atom()
end
def module_name(_, module) when is_atom(module) do
module
end
@doc """
Converts a string key from an AWS spec into an atom,
such as for a function call or struct property
## Examples
iex> ExAws.Boto.Util.key_to_atom("UserName")
:user_name
iex> ExAws.Boto.Util.key_to_atom("NotificationARNs")
:notification_arns
iex> ExAws.Boto.Util.key_to_atom("TestARNs")
:test_arns
iex> ExAws.Boto.Util.key_to_atom("VpcID")
:vpc_id
"""
def key_to_atom("NotificationARNs"), do: :notification_arns
def key_to_atom(key) when is_binary(key) do
key
|> to_charlist()
|> underscorify([])
|> :erlang.list_to_atom()
end
def key_to_atom(nil) do
nil
end
@doc """
Determines whether a single erlang character is a lowercase ASCII letter
"""
defguard is_lower(letter) when letter >= 97 and letter <= 122
@doc """
Determines whether a single erlang character is an uppercase ASCII letter
"""
defguard is_upper(letter) when letter >= 65 and letter <= 90
defp underscorify([lower, upper | rest], acc) when is_lower(lower) and is_upper(upper) do
# don't forget to append in reverse order
underscorify(rest, [upper + 32, 95, lower | acc])
end
defp underscorify([upper | rest], acc) when is_upper(upper) do
underscorify(rest, [upper + 32 | acc])
end
defp underscorify([lower | rest], acc) do
underscorify(rest, [lower | acc])
end
defp underscorify([], acc) do
acc
|> Enum.reverse()
end
end
|
lib/ex_aws/boto/util.ex
| 0.685318 | 0.497925 |
util.ex
|
starcoder
|
defmodule Aecore.Account.Tx.SpendTx do
@moduledoc """
Module defining the Spend transaction
"""
@behaviour Aecore.Tx.Transaction
alias Aecore.Account.{Account, AccountStateTree}
alias Aecore.Account.Tx.SpendTx
alias Aecore.Chain.{Identifier, Chainstate}
alias Aecore.Keys
alias Aecore.Tx.{DataTx, SignedTx}
require Logger
@version 1
@typedoc "Expected structure for the Spend Transaction"
@type payload :: %{
receiver: Keys.pubkey() | Identifier.t(),
amount: non_neg_integer(),
version: non_neg_integer(),
payload: binary()
}
@typedoc "Reason of the error"
@type reason :: String.t()
@typedoc "Version of SpendTx"
@type version :: non_neg_integer()
@typedoc "Structure that holds specific transaction info in the chainstate.
In the case of SpendTx we don't have a subdomain chainstate."
@type tx_type_state() :: map()
@typedoc "Structure of the Spend Transaction type"
@type t :: %SpendTx{
receiver: Keys.pubkey() | Identifier.t(),
amount: non_neg_integer(),
version: non_neg_integer(),
payload: binary()
}
@doc """
Definition of the SpendTx structure
# Parameters
- receiver: the account to receive the transaction amount
- amount: the amount of coins to be sent
- version: specifies the version of the transaction
- payload: any binary data (a message, a picture etc.)
"""
defstruct [:receiver, :amount, :version, :payload]
# Callbacks
@spec get_chain_state_name() :: atom()
def get_chain_state_name, do: :accounts
@spec init(payload()) :: SpendTx.t()
def init(%{
receiver: %Identifier{} = identified_receiver,
amount: amount,
version: version,
payload: payload
}) do
%SpendTx{receiver: identified_receiver, amount: amount, payload: payload, version: version}
end
def init(%{receiver: receiver, amount: amount, version: version, payload: payload}) do
identified_receiver = Identifier.create_identity(receiver, :account)
%SpendTx{receiver: identified_receiver, amount: amount, payload: payload, version: version}
end
@doc """
Validates the transaction without considering state
"""
@spec validate(SpendTx.t(), DataTx.t()) :: :ok | {:error, String.t()}
def validate(
%SpendTx{receiver: receiver, amount: amount, version: version, payload: payload},
%DataTx{} = data_tx
) do
senders = DataTx.senders(data_tx)
cond do
amount < 0 ->
{:error, "#{__MODULE__}: The amount cannot be a negative number"}
version != get_tx_version() ->
{:error, "#{__MODULE__}: Invalid version"}
!Keys.key_size_valid?(receiver) ->
{:error, "#{__MODULE__}: Wrong receiver key size"}
length(senders) != 1 ->
{:error, "#{__MODULE__}: Invalid senders number"}
!is_binary(payload) ->
{:error,
"#{__MODULE__}: Invalid payload type , expected binary , got: #{inspect(payload)} "}
true ->
:ok
end
end
@doc """
Deducts the transaction amount from the sender account state and adds it to the receiver
"""
@spec process_chainstate(
Chainstate.accounts(),
tx_type_state(),
non_neg_integer(),
SpendTx.t(),
DataTx.t()
) :: {:ok, {Chainstate.accounts(), tx_type_state()}}
def process_chainstate(
accounts,
%{},
block_height,
%SpendTx{amount: amount, receiver: %Identifier{value: receiver}},
%DataTx{} = data_tx
) do
sender = DataTx.main_sender(data_tx)
new_accounts =
accounts
|> AccountStateTree.update(sender, fn acc ->
Account.apply_transfer!(acc, block_height, amount * -1)
end)
|> AccountStateTree.update(receiver, fn acc ->
Account.apply_transfer!(acc, block_height, amount)
end)
{:ok, {new_accounts, %{}}}
end
@doc """
Validates the transaction with state considered
"""
@spec preprocess_check(
Chainstate.accounts(),
tx_type_state(),
non_neg_integer(),
SpendTx.t(),
DataTx.t()
) :: :ok | {:error, reason()}
def preprocess_check(
accounts,
%{},
_block_height,
%SpendTx{amount: amount},
%DataTx{fee: fee} = data_tx
) do
%Account{balance: balance} = AccountStateTree.get(accounts, DataTx.main_sender(data_tx))
if balance - (fee + amount) < 0 do
{:error, "#{__MODULE__}: Negative balance"}
else
:ok
end
end
@spec deduct_fee(
Chainstate.accounts(),
non_neg_integer(),
SpendTx.t(),
DataTx.t(),
non_neg_integer()
) :: Chainstate.accounts()
def deduct_fee(accounts, block_height, _tx, %DataTx{} = data_tx, fee) do
DataTx.standard_deduct_fee(accounts, block_height, data_tx, fee)
end
@spec is_minimum_fee_met?(SignedTx.t()) :: boolean()
def is_minimum_fee_met?(%SignedTx{data: %DataTx{fee: fee}}) do
fee >= Application.get_env(:aecore, :tx_data)[:minimum_fee]
end
@spec get_tx_version() :: version()
def get_tx_version, do: Application.get_env(:aecore, :spend_tx)[:version]
@spec encode_to_list(SpendTx.t(), DataTx.t()) :: list()
def encode_to_list(%SpendTx{receiver: receiver, amount: amount, payload: payload}, %DataTx{
senders: [sender],
fee: fee,
ttl: ttl,
nonce: nonce
}) do
[
:binary.encode_unsigned(@version),
Identifier.encode_to_binary(sender),
Identifier.encode_to_binary(receiver),
:binary.encode_unsigned(amount),
:binary.encode_unsigned(fee),
:binary.encode_unsigned(ttl),
:binary.encode_unsigned(nonce),
payload
]
end
@spec decode_from_list(non_neg_integer(), list()) :: {:ok, DataTx.t()} | {:error, reason()}
def decode_from_list(@version, [
encoded_sender,
encoded_receiver,
amount,
fee,
ttl,
nonce,
payload
]) do
case Identifier.decode_from_binary(encoded_receiver) do
{:ok, receiver} ->
DataTx.init_binary(
SpendTx,
%{
receiver: receiver,
amount: :binary.decode_unsigned(amount),
version: @version,
payload: payload
},
[encoded_sender],
:binary.decode_unsigned(fee),
:binary.decode_unsigned(nonce),
:binary.decode_unsigned(ttl)
)
{:error, _} = error ->
error
end
end
def decode_from_list(@version, data) do
{:error, "#{__MODULE__}: decode_from_list: Invalid serialization: #{inspect(data)}"}
end
def decode_from_list(version, _) do
{:error, "#{__MODULE__}: decode_from_list: Unknown version #{version}"}
end
end
|
apps/aecore/lib/aecore/account/tx/spend_tx.ex
| 0.868088 | 0.481515 |
spend_tx.ex
|
starcoder
|
defmodule Unicode.Property do
@moduledoc """
Functions to introspect Unicode properties for binaries
(Strings) and codepoints.
"""
@behaviour Unicode.Property.Behaviour
@type string_or_codepoint :: String.t() | non_neg_integer
alias Unicode.{Utils, GeneralCategory, Emoji}
@derived_properties Utils.derived_properties()
|> Utils.remove_annotations()
@properties Utils.properties()
|> Utils.remove_annotations()
@all_properties @derived_properties
|> Map.merge(@properties)
|> Map.merge(Emoji.emoji())
@doc """
Returns the map of Unicode
properties.
The property name is the map
key and a list of codepoint
ranges as tuples as the value.
"""
def properties do
@all_properties
end
@doc """
Returns a list of known Unicode
property names.
This function does not return the
names of any property aliases.
"""
@known_properties Map.keys(@all_properties)
def known_properties do
@known_properties
end
@doc """
Returns a map of aliases for
Unicode blocks.
An alias is an alternative name
for referring to a block. Aliases
are resolved by the `fetch/1` and
`get/1` functions.
"""
@property_alias Utils.property_alias()
|> Utils.atomize_values()
|> Utils.add_canonical_alias()
@impl Unicode.Property.Behaviour
def aliases do
@property_alias
end
@doc """
Returns a map of properties to the module
that serves that property.
"""
@servers Utils.property_servers()
def servers do
@servers
end
@doc """
Returns the Unicode ranges for
a given block as a list of
ranges as 2-tuples.
Aliases are resolved by this function.
Returns either `{:ok, range_list}` or
`:error`.
"""
@impl Unicode.Property.Behaviour
def fetch(property) when is_atom(property) do
Map.fetch(properties(), property)
end
def fetch(property) do
property = Utils.downcase_and_remove_whitespace(property)
property = Map.get(aliases(), property, property)
Map.fetch(properties(), property)
end
@doc """
Returns the Unicode ranges for
a given block as a list of
ranges as 2-tuples.
Aliases are resolved by this function.
Returns either `range_list` or
`nil`.
"""
@impl Unicode.Property.Behaviour
def get(property) do
case fetch(property) do
{:ok, property} -> property
_ -> nil
end
end
@doc """
Returns the count of the number of characters
for a given property.
## Example
iex> Unicode.Property.count(:lowercase)
2471
"""
@impl Unicode.Property.Behaviour
def count(property) do
properties()
|> Map.get(property)
|> Enum.reduce(0, fn {from, to}, acc -> acc + to - from + 1 end)
end
@doc """
Returns `:numeric` or `nil` based upon
whether the given codepoint or binary
is all numeric characters.
This is useful when the desired result is
`truthy` or `falsy`
## Example
iex> Unicode.Property.numeric "123"
:numeric
iex> Unicode.Property.numeric "123a"
nil
"""
def numeric(codepoint_or_binary) do
if numeric?(codepoint_or_binary), do: :numeric, else: nil
end
@doc """
Returns `:alphanumeric` or `nil` based upon
whether the given codepoint or binary
is all alphanumeric characters.
This is useful when the desired result is
`truthy` or `falsy`
## Example
iex> Unicode.Property.alphanumeric "123abc"
:alphanumeric
iex> Unicode.Property.alphanumeric "???"
nil
"""
def alphanumeric(codepoint_or_binary) do
if alphanumeric?(codepoint_or_binary), do: :alphanumeric, else: nil
end
@doc """
Returns `:extended_numeric` or `nil` based upon
whether the given codepoint or binary
is all alphanumeric characters.
Extended numberic includes fractions, superscripts,
subscripts and other characters in the category `No`.
This is useful when the desired result is
`truthy` or `falsy`
## Example
iex> Unicode.Property.extended_numeric "123"
:extended_numeric
iex> Unicode.Property.extended_numeric "⅔"
:extended_numeric
iex> Unicode.Property.extended_numeric "-123"
nil
"""
def extended_numeric(codepoint_or_binary) do
if extended_numeric?(codepoint_or_binary), do: :extended_numeric, else: nil
end
@numeric_ranges GeneralCategory.get(:Nd)
@doc """
Returns a boolean based upon
whether the given codepoint or binary
is all numeric characters.
## Example
iex> Unicode.Property.numeric? "123"
true
iex> Unicode.Property.numeric? "123a"
false
"""
def numeric?(codepoint)
when unquote(Utils.ranges_to_guard_clause(@numeric_ranges)),
do: true
def numeric?(string) when is_binary(string) do
string_has_property?(string, &numeric?/1)
end
def numeric?(_), do: false
@extended_numeric_ranges @numeric_ranges ++ GeneralCategory.get(:Nl) ++ GeneralCategory.get(:No)
@doc """
Returns a boolean based upon
whether the given codepoint or binary
is all numberic characters.
## Example
iex> Unicode.Property.extended_numeric? "123"
true
iex> Unicode.Property.extended_numeric? "⅔"
true
"""
def extended_numeric?(codepoint_or_binary)
def extended_numeric?(codepoint)
when unquote(Utils.ranges_to_guard_clause(@extended_numeric_ranges)),
do: true
def extended_numeric?(string) when is_binary(string) do
string_has_property?(string, &extended_numeric?/1)
end
def extended_numeric?(_), do: false
@doc """
Returns a boolean based upon
whether the given codepoint or binary
is all alphanumeric characters.
## Example
iex> Unicode.Property.alphanumeric? "123abc"
true
iex> Unicode.Property.alphanumeric? "⅔"
false
"""
def alphanumeric?(codepoint_or_binary)
def alphanumeric?(codepoint) when is_integer(codepoint) do
alphabetic?(codepoint) or numeric?(codepoint)
end
def alphanumeric?(string) when is_binary(string) do
string_has_property?(string, &alphanumeric?/1)
end
def alphanumeric?(_), do: false
@property_names Map.keys(@all_properties)
@properties_code @property_names
|> Enum.map(fn fun ->
quote do
unquote(fun)(var!(codepoint))
end
end)
for {property, ranges} <- @all_properties,
property in @property_names do
boolean_function = String.to_atom("#{property}?")
@doc """
Returns a boolean indicating if the
codepoint or string has the property
`#{inspect(property)}`.
For string parameters, all codepoints in
the string must have the `#{inspect(property)}`
property in order for the result to be `true`.
"""
def unquote(boolean_function)(codepoint)
when is_integer(codepoint) and unquote(Utils.ranges_to_guard_clause(ranges)) do
true
end
def unquote(boolean_function)(codepoint)
when is_integer(codepoint) and codepoint in 0..0x10FFFF do
false
end
def unquote(boolean_function)(string) when is_binary(string) do
string_has_property?(string, &unquote(boolean_function)(&1))
end
@doc """
Returns `#{inspect(property)}` or `nil` indicating
if the codepoint or string has the property
`#{inspect(property)}`.
For string parameters, all codepoints in
the string must have the `#{inspect(property)}`
property in order for the result to `#{inspect(property)}`.
"""
def unquote(property)(codepoint) do
if unquote(boolean_function)(codepoint), do: unquote(property), else: nil
end
end
@doc """
Returns the property name(s) for the
given binary or codepoint.
In the case of a codepoint, a single
list of properties for that codepoint name is returned.
For a binary a list of list for each
codepoint in the binary is returned.
"""
def properties(codepoint) when is_integer(codepoint) do
unquote(@properties_code)
|> Enum.reject(&is_nil/1)
|> Enum.sort()
end
@spec properties(string_or_codepoint) :: [atom, ...] | [[atom, ...], ...]
def properties(string) when is_binary(string) do
string
|> String.to_charlist()
|> Enum.map(&properties/1)
|> Enum.uniq()
end
@doc false
def string_has_property?(string, function) do
case String.next_codepoint(string) do
nil ->
false
{<<codepoint::utf8>>, ""} ->
function.(codepoint)
{<<codepoint::utf8>>, rest} ->
function.(codepoint) && function.(rest)
end
end
end
|
lib/unicode/property.ex
| 0.938717 | 0.45538 |
property.ex
|
starcoder
|
defmodule Nostrum.Cache.ChannelCache do
@moduledoc """
Cache for channels.
The ETS table name associated with the Channel Cache is `:channels`. Besides the
methods provided below you can call any other ETS methods on the table.
## Example
```elixir
info = :ets.info(:channels)
[..., heir: :none, name: :channels, size: 1, ...]
size = info[:size]
1
```
"""
alias Nostrum.Cache.GuildCache
alias Nostrum.Struct.Channel
alias Nostrum.Util
import Nostrum.Snowflake, only: [is_snowflake: 1]
@doc ~S"""
Retrieves a channel from the cache.
Internally, the ChannelCache process only stores
`t:Nostrum.Struct.Channel.dm_channel/0` references. To get channel
information, a call is made to a `Nostrum.Cache.GuildCache`.
If successful, returns `{:ok, channel}`. Otherwise, returns `{:error, reason}`
## Example
```elixir
case Nostrum.Cache.ChannelCache.get(133333333337) do
{:ok, channel} ->
"We found " <> channel.name
{:error, _reason} ->
"Donde esta"
end
```
"""
@spec get(Channel.id() | Nostrum.Struct.Message.t()) :: {:error, atom} | {:ok, Channel.t()}
def get(%Nostrum.Struct.Message{channel_id: channel_id}), do: get(channel_id)
def get(id) when is_snowflake(id) do
case lookup(id) do
{:ok, channel} -> {:ok, convert(channel)}
error -> error
end
end
@doc ~S"""
Same as `get/1`, but raises `Nostrum.Error.CacheError` in case of a failure.
"""
@spec get!(Channel.id() | Nostrum.Struct.Message.t()) :: no_return | Channel.t()
def get!(%Nostrum.Struct.Message{channel_id: channel_id}), do: get!(channel_id)
def get!(id) when is_snowflake(id), do: id |> get |> Util.bangify_find(id, __MODULE__)
@doc false
@spec create(map) :: Channel.t()
def create(channel) do
:ets.insert(:channels, {channel["id"], channel})
convert(channel)
end
@doc false
@spec update(Channel.t()) :: :noop | {Channel.t(), Channel.t()}
def update(channel) do
case lookup(channel.id) do
{:ok, old_channel} ->
{convert(old_channel), convert(channel)}
_ ->
:noop
end
end
@doc false
@spec delete(Channel.id()) :: :noop | Channel.t()
def delete(id) do
case lookup(id) do
{:ok, channel} ->
:ets.delete(:channels, id)
convert(channel)
_ ->
:noop
end
end
@doc false
@spec lookup(Channel.id()) :: {:error, :channel_not_found} | {:ok, map}
def lookup(id) do
case :ets.lookup(:channels, id) do
[] ->
[channel_id: id]
|> GuildCache.select_by(fn %{channels: channels} ->
Map.get(channels, id, {:error, :id_not_found})
end)
|> case do
{:error, :id_not_found} ->
{:error, :channel_not_found}
res ->
res
end
[{^id, channel}] ->
{:ok, channel}
end
end
@doc false
def convert(%{__struct__: _} = struct), do: struct
def convert(map), do: Channel.to_struct(map)
end
|
lib/nostrum/cache/channel_cache.ex
| 0.932691 | 0.807499 |
channel_cache.ex
|
starcoder
|
defmodule Vector do
@moduledoc """
Functions that work on vectors.
This datastructure wraps Erlang's `array` type for fast random
lookup and update to large collections.
The point of this module is not meant to be a 1:1 wrapper, but to be
a useful set of higher-level API operations.
Note that this module is implemented as a struct with an `array` field,
pointing to the underlying Erlang `array` implementation. This field
is private, so you should use the functions in this module
to perform operations.
"""
# this is not great, but `array()` is not available in Elixir
@opaque t :: %__MODULE__{array: :array.array()}
@type index :: integer
@type value :: any
@type acc :: any
@type array_reducing_fn :: ((non_neg_integer, value, acc) -> acc)
@behaviour Access
defstruct array: :array.new()
@doc """
Constructs a array-backed vector
## Examples
iex> Vector.new()
#Vector<[]>
iex> Vector.new(Vector.new())
#Vector<[]>
iex> Vector.new([1,2,3])
#Vector<[1, 2, 3]>
iex> Vector.new(%{a: 1, b: 2})
#Vector<[a: 1, b: 2]>
iex> Vector.new(0)
#Vector<[]>
# this is exposing a bit of implementation, but I am
# unsure how else to test it
iex> Vector.new(5).array
{:array, 5, 10, :undefined, 10}
"""
def new(), do: %__MODULE__{}
def new(%__MODULE__{} = vector), do: vector
def new(size) when is_integer(size) and size >= 0 do
%__MODULE__{
array: :array.new([
{:size, size},
{:fixed, false},
{:default, :undefined}
])
}
end
def new(list) when is_list(list) do
%Vector{array: :array.from_list(list)}
end
def new(enumerable) do
enumerable
|> Enum.to_list
|> new
end
@doc """
Converts a `vector` to a list
## Examples
iex> Vector.new() |> Vector.to_list
[]
iex> Vector.to_list(Vector.new([1,2,3]))
[1,2,3]
iex> Vector.new(100) |> Vector.put(39, 1) |> Vector.to_list
[1]
"""
def to_list(%Vector{array: array}) do
:array.sparse_to_list(array)
end
@doc """
Returns the count of initialized elements in the vector. Does not count uninitialized elements.
This function takes time linear to the number of uninitialized elements.
## Examples
iex> Vector.count(Vector.new())
0
iex> Vector.count(Vector.new([1,2,3,4,5]))
5
iex> Vector.new(100) |> Vector.count
0
iex> Vector.new(100)
...> |> Vector.put(43, 1)
...> |> Vector.count
1
"""
@spec count(t) :: non_neg_integer
def count(%__MODULE__{} = vector) do
reduce(vector, 0, fn(_index, _val, acc) -> acc + 1 end)
end
@doc """
Returns the total size of a vector, including all uninitialized/default values.
This function is a reflection of the total memory size of the underlying Erlang array. It does
not say anything about the elements of the array. For a count of non-default elements in the vector,
see `count/1`.
## Examples
iex> Vector.size(Vector.new())
0
iex> Vector.size(Vector.new([1,2,3,4,5]))
5
iex> Vector.new(100) |> Vector.size
100
iex> Vector.new(100) |> Vector.put(43, 1) |> Vector.size
100
"""
def size(%Vector{array: array}), do: array.size
@doc """
Checks if `vector` contains `value`
## Examples
iex> Vector.member?(Vector.new([1,2,3]), 99)
false
iex> Vector.member?(Vector.new([1,2,3]), 2)
true
"""
def member?(%Vector{array: array}, value) do
array
|> :array.sparse_to_list
|> MapSet.new()
|> MapSet.member?(value)
end
@doc """
Finds the element at the given `index` (zero-based) in logarithmic time.
Returns `{:ok, element}` if found, otherwise `:error`.
A negative index can be passed, in which case the index is counted from the end (e.g. -1 finds the last element).
## Examples
iex> Vector.fetch(Vector.new([1,2,3]), 9)
:error
iex> Vector.fetch(Vector.new([1,2,3]), 2)
{:ok, 3}
iex> Vector.fetch(Vector.new([1,2,3,4,5]), -2)
{:ok, 4}
iex> Vector.fetch(Vector.new([1,2,3,4,5]), -6)
:error
"""
@spec fetch(t, index) :: {:ok, any} | :error
def fetch(%__MODULE__{} = vector, index) when is_integer(index) and index < 0 do
size = Vector.size(vector)
if (index * -1) > size do
:error
else
fetch(vector, size + index)
end
end
def fetch(%Vector{array: array}, index) when is_integer(index) and index >= 0 do
case :array.get(index, array) do
:undefined -> :error
value -> {:ok, value}
end
end
@doc """
Finds the element at the given `index` (zero-based) in logarithmic time.
Raises `OutOfBoundsError` if the given `index` is outside the range of
the enumerable.
A negative index can be passed, in which case the index is counted from the end (e.g. -1 finds the last element).
## Examples
iex> Vector.fetch!(Vector.new([1,2,3]), 1)
2
iex> Vector.fetch!(Vector.new([1,2,3]), -1)
3
iex> Vector.fetch!(Vector.new([1,2,3]), 99)
** (Enum.OutOfBoundsError) out of bounds error
"""
@spec fetch!(t, index) :: value | no_return
def fetch!(%Vector{} = vector, index) do
case fetch(vector, index) do
{:ok, value} -> value
:error -> raise Enum.OutOfBoundsError
end
end
@doc """
Puts the given value under index in vector in logarithmic time
A negative index can be passed, in which case the index is counted from the end (e.g. -1 finds the last element).
## Examples
iex> Vector.put(Vector.new([1,2,3]), 3, 99)
#Vector<[1, 2, 3, 99]>
iex> Vector.put(Vector.new([1,2,3]), 0, 3)
#Vector<[3, 2, 3]>
iex> Vector.put(Vector.new([1,2,3]), -1, 101)
#Vector<[1, 2, 101]>
iex> Vector.put(Vector.new(3), -99, "hi")
** (ArgumentError) negative index out of bounds
"""
@spec put(t, index, value) :: t
def put(%__MODULE__{} = vector, index, value) when is_integer(index) and index < 0 do
new_size = Vector.size(vector) + index
cond do
new_size >= 0 ->
put(vector, new_size, value)
true ->
raise ArgumentError, "negative index out of bounds"
end
end
def put(%__MODULE__{array: array} = vector, index, value) when is_integer(index) and index >= 0 do
%{vector | array: :array.set(index, value, array)}
end
@doc """
Updates the value in vector with the given function in logarithmic time.
If index is present in vector with value, fun is invoked with
argument value and its result is used as the new value of index. If index is
not present in vector, initial is inserted as the value of index.
A negative index can be passed, in which case the index is counted from the end (e.g. -1 finds the last element).
## Examples
iex> Vector.update(Vector.new([1,2,3]), 0, 13, &(&1 * 2))
#Vector<[2, 2, 3]>
iex> Vector.update(Vector.new([1,2,3]), 5, 11, &(&1 * 2))
#Vector<[1, 2, 3, 11]>
iex> Vector.update(Vector.new([1,2,3]), -2, 11, &(&1 * 2))
#Vector<[1, 4, 3]>
"""
@spec update(t, index, value, (value -> value)) :: t
def update(vector, index, initial, fun) when is_function(fun, 1) do
case fetch(vector, index) do
{:ok, value} ->
put(vector, index, fun.(value))
:error ->
put(vector, index, initial)
end
end
@doc """
Updates index with the given function in logarithmic time.
If index is present in vector with value, fun is invoked with argument value
and its result is used as the new value of index. If index is not present in vector,
a Enum.OutOfBoundsError exception is raised.
## Examples
iex> Vector.update!(Vector.new([1,2,3]), 0, &(&1 * 2))
#Vector<[2, 2, 3]>
iex> Vector.update!(Vector.new([1,2,3]), 5, &(&1 * 2))
** (Enum.OutOfBoundsError) out of bounds error
iex> Vector.update!(Vector.new([1,2,3]), -2, &(&1 * 2))
#Vector<[1, 4, 3]>
"""
@spec update!(t, index, (value -> value)) :: t | no_return
def update!(vector, index, fun) when is_function(fun, 1) do
case fetch(vector, index) do
{:ok, value} ->
put(vector, index, fun.(value))
:error ->
raise Enum.OutOfBoundsError
end
end
@doc """
Gets the value at an index in logarithmic time, returning a default if it does not exist.
## Examples
iex> Vector.get(Vector.new([1,2,3]), 0)
1
iex> Vector.get(Vector.new([1,2,3]), 9)
nil
iex> Vector.get(Vector.new([1,2,3]), 9, 1000)
1000
"""
@spec get(t, index, default :: value) :: value
def get(vector, index, default \\ nil) do
case fetch(vector, index) do
{:ok, value} -> value
:error -> default
end
end
@doc """
Returns either the vector without the value at index, or the original vector
if no value is present at index.
## Examples
iex> Vector.delete(Vector.new([1,2,3,4,5]), 2)
#Vector<[1, 2, 4, 5]>
iex> Vector.delete(Vector.new([1,2,3]), 9)
#Vector<[1, 2, 3]>
"""
@spec delete(t, index) :: t
def delete(%Vector{array: array} = vector, index) do
%{vector | array: :array.reset(index, array)}
end
@doc """
Gets and updates a value at the same time.
## Examples
iex> {val, new_vector} = Vector.get_and_update(Vector.new([1,2,3]), 0, fn(value) -> {value, value + 100} end)
iex> {val, Vector.to_list(new_vector)}
{1, [101, 2, 3]}
iex> {val, new_vector} = Vector.get_and_update(Vector.new([1,2,3]), 0, fn(_) -> :pop end)
iex> {val, Vector.to_list(new_vector)}
{1, [2, 3]}
"""
@spec get_and_update(t, index, (value -> {value, value} | :pop)) :: {value, t}
def get_and_update(vector, index, fun) do
case fun.(get(vector, index)) do
{value_to_return, new_value} -> {value_to_return, put(vector, index, new_value)}
:pop -> pop(vector, index)
end
end
@doc """
Deletes a value at index, returning the new vector and the value that was deleted
## Examples
iex> {value, new} = Vector.pop(Vector.new([1,2,3]), 2)
iex> {value, Vector.to_list(new)} # arrays cannot be checked for value equality
{3, [1, 2]}
iex> {value, new} = Vector.pop(Vector.new([1,2,3]), 99)
iex> {value, Vector.to_list(new)}
{nil, [1, 2, 3]}
"""
def pop(vector, index, default \\ nil) do
value = get(vector, index, default)
{value, delete(vector, index)}
end
@doc """
Append an item to to a vector
## Examples
iex> Vector.new([1, 2, 3]) |> Vector.append(9)
Vector.new([1, 2, 3, 9])
iex> Vector.new() |> Vector.append("hi")
Vector.new(["hi"])
iex> Vector.new([1, 2, 3]) |> Vector.append(9) |> Vector.size
4
"""
@spec append(t, value) :: t
def append(%__MODULE__{} = vector, value) do
Vector.put(vector, Vector.size(vector), value)
end
@doc """
Reverse every element in a vector, not including the uninitialized elements.
Preserves `count`, does not preserve `size`.
## Examples
iex> vector = Vector.new([1,2,3])
iex> vector |> Vector.reverse |> Vector.reverse
#Vector<[1, 2, 3]>
iex> Vector.reverse(Vector.new())
#Vector<[]>
iex> Vector.reverse(Vector.new([1, 2, 3]))
#Vector<[3, 2, 1]>
iex> vector = Vector.new(50) |> Vector.put(39, "hi")
iex> reversed = Vector.reverse(vector)
iex> Vector.count(vector) == Vector.count(reversed)
true
"""
@spec reverse(t) :: t
def reverse(%__MODULE__{} = vector) do
%{vector | array: :array.from_list(Enum.reverse(vector))}
end
@doc """
Run a function (`fun`) over a vector which takes two arguments: the accumulated results so far (`acc`) and the current vector value (`val`).
Hits only the initialized elements of the vector. Note that `fun` is arity-3, taking the `index`, `value`, and `acc` in that order.
Think of this function as the equivalent of the following pseudocode:
```
vector |> filter(initialized?) |> reduce
```
without the intermediate filter, due to sparse folding being an array primitive.
## Examples
iex> Vector.new([1, 2, 3]) |> Vector.reduce(0, fn(_index, val, acc) -> val + acc end)
6
iex> Vector.new([1, 2, 3]) |> Vector.reduce(Vector.new(), fn(_index, val, acc) -> Vector.append(acc, val + 1) end)
#Vector<[2, 3, 4]>
iex> Vector.new(100)
...> |> Vector.put(25, 1)
...> |> Vector.put(50, 1)
...> |> Vector.put(75, 1)
...> |> Vector.put(90, 1)
...> |> Vector.reduce(0, fn(_index, val, acc) -> acc + val end)
4
"""
@spec reduce(t, acc, array_reducing_fn) :: acc
def reduce(%__MODULE__{array: array}, initial, fun) when is_function(fun, 3) do
:array.sparse_foldl(fun, initial, array)
end
@doc """
Run a function over the elements of the vector, not including the uninitialized ones,
and return the result in a new vector.
Good for large vectors where only a few elements are set.
## Examples
iex> Vector.new() |> Vector.map(fn(_i, val) -> val + 1 end)
#Vector<[]>
iex> Vector.new([1, 2, 3]) |> Vector.map(fn(_i, val) -> val + 1 end)
#Vector<[2, 3, 4]>
iex> Vector.new(100) |> Vector.map(fn(_i, _val) -> 1 end) |> Enum.sum
0
"""
def map(%__MODULE__{array: array} = vector, fun) when is_function(fun, 2) do
%{vector | array: :array.sparse_map(fun, array)}
end
defimpl Enumerable do
def count(vector), do: {:ok, Vector.count(vector)}
def member?(vector, val), do: {:ok, Vector.member?(vector, val)}
def reduce(vector, acc, fun), do: Enumerable.List.reduce(Vector.to_list(vector), acc, fun)
end
defimpl Collectable do
def into(original) do
{original, fn
vector, {:cont, value} -> Vector.put(vector, Vector.count(vector) + 1, value)
vector, :done -> vector
_, :halt -> :ok
end}
end
end
defimpl Inspect do
import Inspect.Algebra
def inspect(set, opts) do
concat(["#Vector<", Inspect.List.inspect(Vector.to_list(set), opts), ">"])
end
end
end
|
lib/vector.ex
| 0.951919 | 0.756268 |
vector.ex
|
starcoder
|
defmodule ResxDropbox.Utility do
@moduledoc """
General helpers.
### Dropbox Content Hash
This module provides an implementation of the [Dropbox Content Hash](https://www.dropbox.com/developers/reference/content-hash).
For use externally or with `Resx.Resource`.
"""
@type algos :: :crypto.sha1 | :crypto.sha2 | :crypto.sha3 | :crypto.compatibility_only_hash | :ripemd160
@type state :: { algos, binary, binary }
@block_size 4 * 1024 * 1024
@doc """
Initializes the context for streaming hash operations following the dropbox
content hashing algorithm.
By default the algorithm used is `:sha256` as this is the current one used
by dropbox, this however can be overridden.
The state can then be passed to `hash_update/2` and `hash_final/1`.
iex> ResxDropbox.Utility.hash_init |> ResxDropbox.Utility.hash_update("foo") |> ResxDropbox.Utility.hash_update("bar") |> ResxDropbox.Utility.hash_final
"3f2c7ccae98af81e44c0ec419659f50d8b7d48c681e5d57fc747d0461e42dda1"
iex> ResxDropbox.Utility.hash_init |> ResxDropbox.Utility.hash_final
"5df6e0e2761359d30a8275058e299fcc0381534545f55cf43e41983f5d4c9456"
"""
@spec hash_init(algos) :: state
def hash_init(algo \\ :sha256) do
{ algo, <<>>, <<>> }
end
@doc """
Updates the digest represented by state using the given data. State must have
been generated using `hash_init/1` or a previous call to this function. Data
can be any length. New state must be passed into the next call to `hash_update/2`
or `hash_final/1`.
"""
@spec hash_update(state, iodata) :: state
def hash_update(state, []), do: state
def hash_update(state, [data|list]), do: hash_update(state, data) |> hash_update(list)
def hash_update({ algo, <<block :: binary-size(@block_size), chunks :: binary>>, hashes }, data), do: hash_update({ algo, chunks <> data, hashes <> :crypto.hash(algo, block) }, <<>>)
def hash_update(state, <<>>), do: state
def hash_update({ algo, chunks, hashes }, data), do: hash_update({ algo, chunks <> data, hashes }, <<>>)
@doc """
Finalizes the hash operation referenced by state returned from a previous call
to `hash_update/2`. The digest will be encoded as a lowercase hexadecimal string
as required by the dropbox content hashing algorithm.
"""
@spec hash_final(state) :: String.t
def hash_final({ algo, <<block :: binary-size(@block_size), chunks :: binary>>, hashes }), do: hash_final({ algo, chunks, hashes <> :crypto.hash(algo, block) })
def hash_final({ algo, block, hashes }) do
hashes = hashes <> :crypto.hash(algo, block)
:crypto.hash(algo, hashes) |> Base.encode16(case: :lower)
end
@doc """
Hash the content following the dropbox content hashing algorithm.
By default the algorithm used is `:sha256` as this is the current one used
by dropbox, this however can be overridden.
iex> ResxDropbox.Utility.hash("foobar")
"3f2c7ccae98af81e44c0ec419659f50d8b7d48c681e5d57fc747d0461e42dda1"
iex> ResxDropbox.Utility.hash("")
"5df6e0e2761359d30a8275058e299fcc0381534545f55cf43e41983f5d4c9456"
iex> ResxDropbox.Utility.hash(:sha, "foobar")
"9b500343bc52e2911172eb52ae5cf4847604c6e5"
iex> ResxDropbox.Utility.hash(["f", "", [[[[["oo"], [["b"]]], ""], ""], "a"], [[],[]], ["r"]])
ResxDropbox.Utility.hash("foobar")
iex> ResxDropbox.Utility.hash([])
ResxDropbox.Utility.hash("")
"""
@spec hash(algos, iodata) :: String.t
def hash(algo \\ :sha256, data), do: hash_init(algo) |> hash_update(data) |> hash_final
@doc """
A resx resource hasher for the dropbox content hashing algorithm.
Generally you'll want to use the `streamable_hasher/1` instead.
This can be applied globally as follows:
config :resx,
hash: ResxDropbox.Utility.hasher
Or on individual resources:
iex> Resx.Resource.open!("data:,foobar") |> Resx.Resource.hash(ResxDropbox.Utility.hasher)
{ :dropbox, ResxDropbox.Utility.hash("foobar") }
iex> Resx.Resource.open!("data:,foobar") |> Resx.Resource.hash(ResxDropbox.Utility.hasher(:sha))
{ :dropbox, ResxDropbox.Utility.hash(:sha, "foobar") }
"""
@spec hasher(algos) :: Resx.Resource.hasher
def hasher(algo \\ :sha256), do: { :dropbox, { ResxDropbox.Utility, :hash, [algo] } }
@doc """
A resx resource streamable hasher for the dropbox content hashing algorithm.
This can be applied globally as follows:
config :resx,
hash: ResxDropbox.Utility.streamable_hasher
Or on individual resources:
iex> Resx.Resource.open!("data:,foobar") |> Resx.Resource.hash(ResxDropbox.Utility.streamable_hasher)
{ :dropbox, ResxDropbox.Utility.hash("foobar") }
iex> Resx.Resource.open!("data:,foobar") |> Resx.Resource.hash(ResxDropbox.Utility.streamable_hasher(:sha))
{ :dropbox, ResxDropbox.Utility.hash(:sha, "foobar") }
"""
@spec streamable_hasher(algos) :: Resx.Resource.streamable_hasher
def streamable_hasher(algo \\ :sha256), do: { :dropbox, { ResxDropbox.Utility, :hash_init, [algo], nil }, { ResxDropbox.Utility, :hash_update, 2 }, { ResxDropbox.Utility, :hash_final, 1 } }
end
|
lib/resx_dropbox/utility.ex
| 0.89077 | 0.551453 |
utility.ex
|
starcoder
|
defmodule Snitch.Data.Schema.Card do
@moduledoc """
Models Credit and Debit cards.
A `User` can save cards by setting the `:card_name`, even if the card is not
saved, it is associated with the user.
"""
use Snitch.Data.Schema
alias Snitch.Data.Schema.{CardPayment, User}
@typedoc """
## `:is_disabled` and `:card_name`
These fields together decide if the card is listed as a "saved card" to the user.
| `:is_disabled` | `:card_name` | Listed as a saved card? |
|----------------|---------------------|-------------------------|
| `false` | **not `nil` or `""` | yes |
| `false` | `nil` or `""` | no |
| `true` | `any` | no |
## Note
A `Card` is never deleted, because `CardPayments` are never deleted.
"""
@type t :: %__MODULE__{}
schema "snitch_cards" do
field(:name_on_card, :string)
field(:year, :integer)
field(:month, :integer)
field(:brand, :string)
field(:is_disabled, :boolean, default: false)
field(:number, :string)
field(:card_name, :string)
field(:last_digits, :string, virtual: true)
field(:first_digits, :string, virtual: true)
belongs_to(:user, User)
has_many(:card_payments, CardPayment)
timestamps()
end
@required_fields ~w(name_on_card brand user_id month year number)a
@update_fields ~w(is_disabled card_name)a
@cast_fields @required_fields ++ @update_fields
@doc """
Returns a `Card` changeset.
The `card_number` should be a string of digits whose length is between 8 to 19
digits (inclusive), according to [ISO/IEC
7812](https://www.iso.org/obp/ui/#iso:std:iso-iec:7812:-1:ed-5:v1:en)
"""
@spec changeset(t, map, :create | :update) :: Ecto.Changeset.t()
def changeset(card, params, action)
def changeset(%__MODULE__{} = card, params, :create) do
%{year: current_year, month: current_month} = DateTime.utc_now()
card
|> cast(params, @cast_fields)
|> validate_required(@required_fields)
|> validate_number(
:month,
less_than_or_equal_to: 12,
greater_than_or_equal_to: current_month
)
|> validate_number(:year, greater_than_or_equal_to: current_year)
|> validate_format(:number, ~r/^\d+$/)
|> validate_length(:number, max: 19, min: 8)
|> foreign_key_constraint(:user_id)
|> mask_card
end
def changeset(%__MODULE__{} = card, params, :update) do
cast(card, params, @update_fields)
end
defp mask_card(%Ecto.Changeset{} = card_changeset) do
{:ok, number} = fetch_change(card_changeset, :number)
card_changeset
|> put_change(:last_digits, String.slice(number, -4..-1))
|> put_change(:first_digits, String.slice(number, 0..5))
end
end
|
apps/snitch_core/lib/core/data/schema/card.ex
| 0.885885 | 0.593285 |
card.ex
|
starcoder
|
alias Maru.Entity.Utils
alias Maru.Entity.Struct.{Batch, Serializer, Exposure}
alias Maru.Entity.Struct.Exposure.{Runtime, Information}
defmodule Maru.Entity do
@moduledoc ~S"""
## Defining Entities
### Basic Exposure
expose :id
expose with `Map.get(instance, :id)`
`%{id: 1}` => `%{id: 1}`
### Exposing with a Presenter
expose field with another entity and another key:
expose :response, source: :reply, using: Reply.Entity
`%{reply: reply}` => `%{response: Reply.Entity.serializer(reply)}`
expose list-type field with another entity:
expose :replies, using: List[Reply.Entity]
`%{replies: [reply1, reply2]}` => `%{replies: [Reply.Entity.serializer(reply1), Reply.Entity.serializer(reply2)]}`
### Conditional Exposure
Use `:if` or `:unless` to expose fields conditionally.
expose :username, if: fn(user, _options) -> user[:public?] end
`%{username: "user1", public?: true}` => `%{username: "user1"}`
`%{username: "user1", public?: false}` => `%{}`
### Custom Present Function
expose :username, [], fn user, _options ->
"#{user[:first_name]} #{user[:last_name]}"
end
`%{first_name: "X", last_name: "Y"}` => `%{username: "X Y"}`
"""
@type instance :: map
@type object :: map
@type options :: map
@type group :: list(atom)
@type one_or_many :: :one | :many
@doc false
defmacro __using__(_) do
quote do
Module.register_attribute(__MODULE__, :exposures, persist: true)
@group []
@exposures []
import unquote(__MODULE__)
@before_compile unquote(__MODULE__)
@doc """
Serialize given instance into an object.
"""
@spec serialize(Entity.instance(), Entity.options(), Keyword.t()) :: Maru.Entity.object()
def serialize(instance, options \\ %{}, entity_options \\ []) do
%Serializer{
module: __MODULE__,
type: (is_list(instance) && :many) || :one,
options: options
}
|> Maru.Entity.Runtime.serialize(instance, entity_options)
end
defoverridable serialize: 1, serialize: 2, serialize: 3
@doc """
Default error handler.
"""
@spec handle_error(list(atom()), Exception.t(), Maru.Entity.object()) :: any()
def handle_error(_attr_group, exception, _data) do
raise exception
end
defoverridable handle_error: 3
@doc """
Before finish hook.
"""
@spec before_finish(Maru.Entity.object(), Maru.Entity.options()) :: any()
def before_finish(item, _options), do: item
defoverridable before_finish: 2
@doc """
Before serialize hook.
"""
@spec before_serialize(Maru.Entity.object(), Maru.Entity.options()) ::
{:ok, Maru.Entity.object(), Maru.Entity.options(), Maru.Entity.object()}
| {:halt, any()}
def before_serialize(item, options), do: {:ok, item, options, %{}}
defoverridable before_serialize: 2
end
end
@doc """
Extend another entity.
Example:
defmodule UserData do
use Maru.Entity
expose :name
expose :address do
expose :address1
expose :address2
expose :address_state
expose :address_city
end
expose :email
expose :phone
end
defmodule MailingAddress do
use Maru.Entity
extend UserData, only: [
address: [:address1, :address2]
]
end
defmodule BasicInfomation do
use Maru.Entity
extend UserData, except: [:address]
end
"""
defmacro extend(module, options \\ []) do
func =
case {options[:only], options[:except]} do
{nil, nil} ->
quote do
fn _ -> true end
end
{nil, except} ->
quote do
fn i -> not Utils.attr_match?(i.information.attr_group, unquote(except)) end
end
{only, nil} ->
quote do
fn i -> Utils.attr_match?(i.information.attr_group, unquote(only)) end
end
{_, _} ->
raise ":only and :except conflict"
end
quote do
unquote(module).__info__(:attributes)
|> Keyword.get(:exposures)
|> Enum.filter(unquote(func))
|> Enum.each(fn exposure ->
@exposures @exposures ++ [exposure]
end)
end
end
@doc """
Expose a field or a set of fields with Map.get.
"""
defmacro expose(attr_or_attrs) do
do_expose(attr_or_attrs, [], nil, __CALLER__)
end
defmacro expose(group, do: block) when is_atom(group) do
quote do
group = @group
@group @group ++ [unquote(group)]
@exposures @exposures ++
[
%Exposure{
runtime: default_runtime(:group, @group),
information: %Information{attr_group: @group}
}
]
unquote(block)
@group group
end
end
@doc """
Depends on the second parameter is a function or list:
1. Expose a field or a set of fields with Map.get and options.
2. Expose a field or a set of fields with custom function without options.
"""
defmacro expose(attr_or_attrs, options) when is_list(options) do
do_expose(attr_or_attrs, options, nil, __CALLER__)
end
defmacro expose(attr_or_attrs, {:fn, _, _} = do_func) do
do_expose(attr_or_attrs, [], do_func, __CALLER__)
end
defmacro expose(attr_or_attrs, {:&, _, _} = do_func) do
do_expose(attr_or_attrs, [], do_func, __CALLER__)
end
@doc """
Expose a field or a set of fields with custom function and options.
"""
defmacro expose(attr_or_attrs, options, do_func) when is_list(options) do
do_expose(attr_or_attrs, options, do_func, __CALLER__)
end
defp do_expose(attr_or_attrs, options, do_func, caller) when is_list(options) do
quote bind_quoted: [
attr_or_attrs: attr_or_attrs,
do_func: Macro.escape(expand_alias(do_func, caller)),
options: Macro.escape(expand_alias(options, caller))
] do
for attr_name <- to_attr_list(attr_or_attrs) do
@exposures @exposures ++
[
options
|> Keyword.put(:attr_name, attr_name)
|> Keyword.put(:group, @group ++ [attr_name])
|> Keyword.put(:do_func, do_func)
|> parse()
]
end
end
end
def to_attr_list(attrs) when is_list(attrs), do: attrs
def to_attr_list(attr) when is_atom(attr), do: [attr]
@spec parse(Keyword.t()) :: Maru.Entity.Struct.Exposure.t()
def parse(options) do
pipeline = [
:attr_name,
:serializer,
:if_func,
:do_func,
:default,
:build_struct
]
accumulator = %{
options: options,
runtime:
quote do
%Runtime{}
end,
information: %Information{}
}
Enum.reduce(pipeline, accumulator, &do_parse(&1, &2))
end
defp do_parse(:attr_name, %{options: options, runtime: runtime, information: information}) do
group = options |> Keyword.fetch!(:group)
attr_name = options |> Keyword.fetch!(:attr_name)
param_key = options |> Keyword.get(:source, attr_name)
options =
options |> Keyword.drop([:attr_name, :group, :source]) |> Keyword.put(:param_key, param_key)
%{
options: options,
runtime:
quote do
%{unquote(runtime) | attr_group: unquote(group)}
end,
information: %{information | attr_group: group}
}
end
defp do_parse(:default, %{options: options, runtime: runtime, information: information}) do
default = Keyword.get(options, :default)
options = Keyword.drop(options, [:default])
%{
options: options,
runtime:
quote do
%{unquote(runtime) | default: unquote(default)}
end,
information: %{information | default: default}
}
end
defp do_parse(:if_func, %{options: options, runtime: runtime, information: information}) do
if_func = options |> Keyword.get(:if)
unless_func = options |> Keyword.get(:unless)
options = options |> Keyword.drop([:if, :unless])
is_nil(if_func) or is_nil(unless_func) || raise ":if and :unless conflict"
func =
case {if_func, unless_func} do
{nil, nil} ->
quote do
fn _, _ -> true end
end
{nil, f} ->
quote do
fn instance, options ->
case unquote(f).(instance, options) do
x when x in [false, nil] -> true
_ -> false
end
end
end
{f, nil} ->
quote do
fn instance, options ->
case unquote(f).(instance, options) do
x when x in [false, nil] -> false
_ -> true
end
end
end
end
%{
options: options,
runtime:
quote do
%{unquote(runtime) | if_func: unquote(func)}
end,
information: information
}
end
defp do_parse(:serializer, %{options: options, runtime: runtime, information: information}) do
serializer =
case Keyword.get(options, :using, nil) do
nil ->
nil
{{:., _, [Access, :get]}, _, [List, module]} ->
%Serializer{module: module, type: :many}
module ->
%Serializer{module: module, type: :one}
end
%{
options: options |> Keyword.drop([:using]),
runtime:
quote do
%{unquote(runtime) | serializer: unquote(Macro.escape(serializer))}
end,
information: information
}
end
defp do_parse(:do_func, %{options: options, runtime: runtime, information: information}) do
do_func = options |> Keyword.get(:do_func)
param_key = options |> Keyword.fetch!(:param_key)
batch = Keyword.get(options, :batch)
options = options |> Keyword.drop([:do_func, :param_key, :batch])
func =
cond do
not is_nil(batch) ->
quote do
fn instance, options ->
%Batch{
module: unquote(batch),
key: unquote(batch).key(instance, options)
}
end
end
is_nil(do_func) ->
quote do
fn instance, _options ->
Map.get(instance, unquote(param_key))
end
end
true ->
do_func
end
%{
options: options,
runtime:
quote do
%{unquote(runtime) | do_func: unquote(func)}
end,
information: information
}
end
defp do_parse(:build_struct, %{runtime: runtime, information: information}) do
%Exposure{runtime: runtime, information: information}
end
defp expand_alias(ast, caller) do
Macro.prewalk(ast, fn
{:__aliases__, _, _} = module -> Macro.expand(module, caller)
other -> other
end)
end
@doc """
Generate default runtime struct.
"""
@spec default_runtime(atom(), group()) :: Macro.t()
def default_runtime(:group, group) do
quote do
%Runtime{
attr_group: unquote(group),
if_func: fn _, _ -> true end,
do_func: fn _, _ -> %{} end
}
end
end
defmacro __before_compile__(env) do
exposures =
Module.get_attribute(env.module, :exposures)
|> Enum.map(fn e ->
e.runtime
end)
quote do
@doc """
Return list of exposures.
"""
@spec __exposures__ :: list(Runtime.t())
def __exposures__ do
unquote(exposures)
end
end
end
end
|
lib/maru/entity.ex
| 0.848612 | 0.455622 |
entity.ex
|
starcoder
|
defmodule PhxComponentHelpers do
@moduledoc """
`PhxComponentHelpers` are helper functions meant to be used within Phoenix
LiveView live_components to make your components more configurable and extensible
from your templates.
It provides following features:
* set HTML or data attributes from component assigns
* set phx_* attributes from component assigns
* set attributes with any custom prefix such as `@click` or `x-bind:` from [alpinejs](https://github.com/alpinejs/alpine)
* encode attributes as JSON from an Elixir structure assign
* validate mandatory attributes
* set and extend CSS classes from component assigns
"""
import PhxComponentHelpers.{SetAttributes, CSS, Forms, Forward}
import Phoenix.HTML, only: [html_escape: 1]
import Phoenix.HTML.Form, only: [input_id: 2, input_name: 2, input_value: 2]
@doc ~S"""
Extends assigns with raw_* attributes that can be interpolated within
your component markup.
## Parameters
* `assigns` - your component assigns
* `attributes` - a list of attributes (atoms) that will be fetched from assigns.
Attributes can either be single atoms or tuples in the form `{:atom, default}` to
provide default values.
## Options
* `:required` - raises if required attributes are absent from assigns
* `:json` - when true, will JSON encode the assign value
* `:data` - when true, HTML attributes are prefixed with `data-`
* `:into` - merges all assigns in a single one that can be interpolated at once
## Example
```
assigns
|> set_attributes(
[:id, :name, label: "default label"],
required: [:id, :name],
into: :attributes
)
|> set_attributes([:value], json: true)
```
`assigns` now contains `@raw_id`, `@raw_name`, `@raw_label` and `@raw_value`.
It also contains `@raw_attributes` which holds the values if `:id`, `:name` and `:label`.
"""
def set_attributes(assigns, attributes, opts \\ []) do
assigns
|> do_set_attributes(attributes, opts)
|> validate_required_attributes(opts[:required])
end
@doc ~S"""
Extends assigns with prefixed attributes that can be interpolated within
your component markup. It will automatically detect any attribute prefixed by
any of the given prefixes from input assigns.
Can be used for intance to easily map `alpinejs` html attributes.
## Parameters
* `assigns` - your component assigns
* `prefixes` - a list of prefix as binaries
## Options
* `:init` - a list of attributes that will be initialized if absent from assigns
* `:required` - raises if required attributes are absent from assigns
* `:into` - merges all assigns in a single one that can be interpolated at once
## Example
```
assigns
|> set_prefixed_attributes(
["@click", "x-bind:"],
required: ["x-bind:class"],
into: :alpine_attributes
)
```
`assigns` now contains `@raw_click`, `@raw_x-bind:class` and `@raw_alpine_attributes`.
"""
def set_prefixed_attributes(assigns, prefixes, opts \\ []) do
phx_attributes =
prefixes
|> Enum.flat_map(&find_assigns_with_prefix(assigns, &1))
|> Enum.uniq()
assigns
|> do_set_attributes(phx_attributes, opts)
|> set_empty_attributes(opts[:init])
|> validate_required_attributes(opts[:required])
end
@doc ~S"""
Just a convenient method built on top of `set_prefixed_attributes/3` for phx attributes.
It will automatically detect any attribute prefixed by `phx_` from input assigns.
By default, the `:into` option of `set_prefixed_attributes/3` is `:phx_attributes`
## Example
```
assigns
|> set_phx_attributes(required: [:phx_submit], init: [:phx_change])
```
`assigns` now contains `@raw_phx_change`, `@raw_phx_submit` and `@raw_phx_attributes`.
"""
def set_phx_attributes(assigns, opts \\ []) do
opts = Keyword.put_new(opts, :into, :phx_attributes)
set_prefixed_attributes(assigns, ["phx_"], opts)
end
@doc ~S"""
Validates that attributes are present in assigns.
Raises an `ArgumentError` if any attribute is missing.
## Example
```
assigns
|> validate_required_attributes([:id, :label])
```
"""
def validate_required_attributes(assigns, required)
def validate_required_attributes(assigns, nil), do: assigns
def validate_required_attributes(assigns, required) do
if Enum.all?(required, &Map.has_key?(assigns, &1)) do
assigns
else
raise ArgumentError, "missing required attributes"
end
end
@doc ~S"""
Set assigns with class attributes.
The class attribute will take provided `default_classes` as a default value and will
be extended, on a class-by-class basis, by your assigns.
This function will identify default classes to be replaced by assigns on a prefix basis:
- "bg-gray-200" will be overwritten by "bg-blue-500" because they share the same "bg-" prefix
- "hover:bg-gray-200" will be overwritten by "hover:bg-blue-500" because they share the same
"hover:bg-" prefix
- "m-1" would not be overwritten by "mt-1" because they don't share the same prefix ("m-" vs "mt-")
## Parameters
* `assigns` - your component assigns
* `default_classes` - the default classes that will be overridden by your assigns.
This parameter can be a binary or a single parameter function that receives all assigns and
returns a binary
## Options
* `:attribute` - read & write css classes from & into this key
* `:error_class` - extra class that will be added if assigns contain form/field keys
and field is faulty.
## Example
```
assigns
|> extend_class("bg-blue-500 mt-8")
|> extend_class("py-4 px-2 divide-y-8 divide-gray-200", attribute: :wrapper_class)
|> extend_class("form-input", error_class: "form-input-error", attribute: :input_class)
|> extend_class(fn assigns ->
default = "p-2 m-4 text-sm "
if assigns[:active], do: default <> "bg-indigo-500", else: default <> "bg-gray-200"
end)
```
`assigns` now contains `@raw_class` and `@raw_wrapper_class`.
If your input assigns were `%{class: "mt-2", wrapper_class: "divide-none"}` then:
* `@raw_class` would contain `"bg-blue-500 mt-2"`
* `@raw_wrapper_class` would contain `"py-4 px-2 divide-none"`
"""
def extend_class(assigns, default_classes, opts \\ []) do
class_attribute_name = Keyword.get(opts, :attribute, :class)
new_class =
assigns
|> handle_error_class_option(opts[:error_class], class_attribute_name)
|> do_css_extend_class(default_classes, class_attribute_name)
assigns
|> Map.put(:"#{class_attribute_name}", new_class)
|> Map.put(:"raw_#{class_attribute_name}", {:safe, "class=#{escaped(new_class)}"})
end
@doc ~S"""
Extends assigns with form related attributes.
If assigns contain `:form` and `:field` keys then it will set `:id`, `:name`, ':for',
`:value`, and `:errors` from received `Phoenix.HTML.Form`.
## Parameters
* `assigns` - your component assigns
## Example
```
assigns
|> set_form_attributes()
```
"""
def set_form_attributes(assigns) do
with_form_fields(
assigns,
fn assigns, form, field ->
assigns
|> put_if_new_or_nil(:id, input_id(form, field))
|> put_if_new_or_nil(:name, input_name(form, field))
|> put_if_new_or_nil(:for, input_name(form, field))
|> put_if_new_or_nil(:value, input_value(form, field))
|> put_if_new_or_nil(:errors, form_errors(form, field))
end,
fn assigns ->
assigns
|> put_if_new_or_nil(:form, nil)
|> put_if_new_or_nil(:field, nil)
|> put_if_new_or_nil(:id, nil)
|> put_if_new_or_nil(:name, nil)
|> put_if_new_or_nil(:for, nil)
|> put_if_new_or_nil(:value, nil)
|> put_if_new_or_nil(:errors, [])
end
)
end
@doc ~S"""
Forward and filter assigns to sub components.
By default it doesn't forward anything unless you provide it with any combination
of the options described below.
## Parameters
* `assigns` - your component assigns
## Options
* `prefix` - will only forward assigns prefixed by the given prefix. Forwarded assign key will no longer have the prefix
* `take`- is a list of key (without prefix) that will be picked from assigns to be forwarded
* `merge`- takes a map that will be merged as-is to the output assigns
If both options are given at the same time, the resulting assigns will be the union of the two.
## Example
Following will forward an assign map containing `%{button_id: 42, button_label: "label", phx_click: "save"}` as `%{id: 42, label: "label", phx_click: "save"}`
```
forward_assigns(assigns, prefix: :button, take: [:phx_click])
```
"""
def forward_assigns(assigns, opts) do
for option <- opts, reduce: %{} do
acc ->
assigns = handle_forward_option(assigns, option)
Map.merge(acc, assigns)
end
end
defp escaped(val) do
{:safe, escaped_val} = html_escape(val)
"\"#{escaped_val}\""
end
defp put_if_new_or_nil(map, key, val) do
Map.update(map, key, val, fn
nil -> val
current -> current
end)
end
defp find_assigns_with_prefix(assigns, prefix) do
for key <- Map.keys(assigns),
key_s = to_string(key),
String.starts_with?(key_s, prefix),
do: key
end
end
|
lib/phx_component_helpers.ex
| 0.918893 | 0.853547 |
phx_component_helpers.ex
|
starcoder
|
defmodule LexibombServer.Board.Grid do
@moduledoc """
Acts as the glue between the high-level board interface and the low-level
square states.
The grid module is responsible for establishing and manipulating the
underlying data structure of a board's coordinate system. The squares within
a grid are referred to using 0-based indexes for both the rows and columns.
These squares are stored within a `MapSet` using a `{row, col}` tuple as the
key.
An extra border of inactive squares is added to the a board's size in order
to simplify functions that would otherwise have to perform complicated
boundary checks. This border means that a 15 x 15 sized board, will utilize
a 17 x 17 grid underneath.
"""
alias LexibombServer.Board.Square
alias LexibombServer.Utils
@type row :: non_neg_integer
@type col :: non_neg_integer
@type coord :: {row, col}
@type t :: %{coord => Square.t}
@border 2
@doc """
Initializes a new grid of squares with a deactivated border.
"""
@spec init(pos_integer) :: t
def init(size) do
empty_grid(size + @border) |> deactivate_border
end
@doc """
Returns the size of the game board.
This does *not* include the additional rows/cols of the deactivated border.
"""
@spec board_size(t) :: pos_integer
def board_size(grid) do
size(grid) - @border
end
@doc """
Returns the size of the grid.
This *does* include the additional rows/cols of the deactivated border.
"""
@spec size(t) :: pos_integer
def size(grid) do
grid
|> map_size
|> :math.sqrt
|> round
end
@doc """
Places a bomb on the grid square at the given coordinate.
"""
@spec place_bomb(t, coord) :: t
def place_bomb(grid, coord) do
square = Map.get(grid, coord)
if square.bomb? do
grid
else
grid
|> Map.update!(coord, &Square.place_bomb/1)
|> inc_adjacent_bombs(adjacent_coords(coord))
end
end
@doc """
Places a bomb on each of the grid squares at the given coordinates.
"""
@spec place_bombs(t, [coord]) :: t
def place_bombs(grid, coords) do
Enum.reduce(coords, grid, fn(coord, grid) ->
place_bomb(grid, coord)
end)
end
@doc """
Places a tile on the grid square at the given coordinate.
This triggers a cascading reveal.
"""
@spec place_tile(t, coord, String.t) :: t
def place_tile(grid, coord, tile) do
Map.update!(grid, coord, fn square ->
Square.place_tile(square, tile)
end)
|> cascading_reveal(coord)
end
@doc """
Reveal the square at the given coordinate; if no bombs are adjacent,
recursively reveal all adjacent squares.
"""
@spec cascading_reveal(t, coord) :: t
def cascading_reveal(grid, coord) do
square = Map.get(grid, coord)
if Square.no_adjacent_bombs?(square) do
adjacent_coords(coord) |> Enum.reduce(grid, &do_cascading_reveal/2)
else
reveal(grid, coord)
end
end
defp do_cascading_reveal(coord, grid) do
square = Map.get(grid, coord)
if Square.revealed?(square) do
# stopping criterion
grid
else
reveal(grid, coord) |> cascading_reveal(coord)
end
end
@doc """
Reveals the grid square at the given coordinate.
"""
@spec reveal(t, coord) :: t
def reveal(grid, coord) do
Map.update!(grid, coord, fn square ->
Square.reveal(square)
end)
end
@doc """
Returns a map containing just the active squares on the given `grid`.
"""
@spec active_squares(t) :: t
def active_squares(grid) do
grid
|> Stream.filter(fn {_, square} -> Square.active?(square) end)
|> Map.new
end
@doc """
Returns `true` if the given coordinate points to an anchor square.
"""
@spec anchor_square?(t, coord) :: boolean
def anchor_square?(grid, coord) do
cond do
Map.get(grid, coord) |> Square.played? ->
false
any_cardinals_played?(grid, coord) ->
true
true ->
false
end
end
@doc"""
Returns `true` if any of the squares located in the cardinal directions from
the given coordinate have a tile played on them.
"""
@spec any_cardinals_played?(t, coord) :: boolean
def any_cardinals_played?(grid, coord) do
coord
|> cardinal_coords
|> Enum.any?(fn coord ->
Map.get(grid, coord) |> Square.played?
end)
end
@doc"""
Returns the four adjacent coordinates that are in the cardinal directions
(N, E, S, W) from the given `coord`.
"""
@spec cardinal_coords(coord) :: [coord]
def cardinal_coords({row, col}) do
[
{row - 1, col},
{row + 1, col},
{row, col - 1},
{row, col + 1},
]
end
@doc """
Returns a list of all the coordinates on the grid that are anchor squares.
"""
@spec all_anchor_squares(t) :: [coord]
def all_anchor_squares(grid) do
grid
|> active_squares
|> Map.keys
|> Enum.filter(&anchor_square?(grid, &1))
end
@spec valid_coord?(t, coord) :: boolean
def valid_coord?(grid, coord) do
grid
|> active_squares
|> Map.has_key?(coord)
end
# Creates an empty grid of squares in the dimension given by `size`.
@spec empty_grid(pos_integer) :: t
defp empty_grid(size) do
for row <- 0 .. (size - 1),
col <- 0 .. (size - 1),
into: %{},
do: {{row, col}, %Square{}}
end
# Deactivates the grid square at the given coordinate.
@spec deactivate(coord, t) :: t
defp deactivate(coord, grid) do
Map.update!(grid, coord, &Square.deactivate/1)
end
# Deactivates all of the squares in the first and last rows/cols of the grid.
@spec deactivate_border(t) :: t
defp deactivate_border(grid) do
coords = Map.keys(grid)
grid_size = size(grid)
border_coords = Enum.filter(coords, &border_square?(&1, grid_size))
Enum.reduce(border_coords, grid, &deactivate/2)
end
# Validates whether the given coordinate is along the border of a `grid_size`
# sized grid.
@spec border_square?(coord, pos_integer) :: boolean
defp border_square?(coord, grid_size) do
{row, col} = coord
cond do
row |> Utils.first_or_last?(grid_size) -> true
col |> Utils.first_or_last?(grid_size) -> true
true -> false
end
end
# Increments the adjacent bombs count for each the squares adjacent to the
# given coordinate.
@spec inc_adjacent_bombs(t, [coord]) :: t
defp inc_adjacent_bombs(grid, [head|tail]) do
grid
|> Map.update!(head, &Square.inc_adjacent_bombs/1)
|> inc_adjacent_bombs(tail)
end
defp inc_adjacent_bombs(grid, []), do: grid
# Returns the coordinates of the squares adjacent to the given coordinate.
@spec adjacent_coords(coord) :: [coord]
defp adjacent_coords({row, col}) do
for r <- (row - 1)..(row + 1),
c <- (col - 1)..(col + 1),
{r, c} != {row, col},
do: {r, c}
end
# Reveal all the squares on a `grid` for debugging.
@doc false
@spec __reveal__(t) :: t
def __reveal__(grid) do
Enum.into(grid, %{}, fn {coord, square} ->
{coord, Square.reveal(square)}
end)
end
end
|
apps/lexibomb_server/lib/lexibomb_server/board/grid.ex
| 0.949553 | 0.834609 |
grid.ex
|
starcoder
|
defmodule Cashtrail.Contacts.Contact do
@moduledoc """
This is an `Ecto.Schema` struct that represents a contact of the entity.
## Definition
According to the [BusinessDictionary.com](http://www.businessdictionary.com/definition/contact.html),
this term can be used to describe reaching out to or being in touch with another
person, business, or entity. So you can use this module to relate transactions to
a person, business, or entity only to know who you received money from or to whom
you paid some money, and contact them if necessary.
## Fields
* `:id` - The unique id of the contact.
* `:name` - This is the name that you refer to the contact. It can be the most know
name of the contact, like the trade name of the company, or a nickname by which
the person is well known.
* `:type` - The type of contact. This can be:
* `:company` - Used if the contact is a company. This is the default value if
no type is chosen
* `:person` - Used if the contact is an individual.
* `:legal_name` - This is the name of register in government agencies. This can
be the registered name of people or the legal name of companies.
* `:tax_id` - This is a number used by governments to as unique identifier of
individuals, be a person, be a company.
* `:customer` - Says if this contact is a customer. It can be used to filter data.
* `:supplier` - Says if this contact is a supplier. It can be used to filter data.
* `:email` - The email of the contact.
* `:phone` - The phone number of the contact. This field can receive and represents
any phone number format.
* `:category` - The category of the contact, which is related to `Cashtrail.Contacts.Category`.
* `:category_id` - The id of the category witch the contact belongs to.
* `:address` - The address of the contact, represented by the `Cashtrail.Contacts.Address`
struct.
* `:inserted_at` - When the contact was inserted at the first time.
* `:updated_at` - When the contact was updated at the last time.
See `Cashtrail.Contacts` to know how to list, get, insert, update, and delete contacts.
"""
use Ecto.Schema
import Ecto.Changeset
alias Cashtrail.Contacts
@type type :: :company | :person
@type t :: %Cashtrail.Contacts.Contact{
id: Ecto.UUID.t() | nil,
name: String.t() | nil,
type: type() | nil,
legal_name: String.t() | nil,
tax_id: String.t() | nil,
customer: boolean | nil,
supplier: boolean | nil,
email: String.t() | nil,
phone: String.t() | nil,
category: Ecto.Association.NotLoaded.t() | Contacts.Category.t() | nil,
category_id: Ecto.UUID.t() | nil,
address: Contacts.Address.t() | nil,
inserted_at: NaiveDateTime.t() | nil,
updated_at: NaiveDateTime.t() | nil,
__meta__: Ecto.Schema.Metadata.t()
}
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "contacts" do
field :name, :string
field :type, Ecto.Enum, values: [:company, :person], default: :company
field :legal_name, :string
field :tax_id, :string
field :customer, :boolean, default: false
field :supplier, :boolean, default: false
field :email, :string
field :phone, :string
embeds_one :address, Contacts.Address, on_replace: :update
belongs_to :category, Contacts.Category
timestamps()
end
@doc false
@spec changeset(t | Ecto.Changeset.t(), map()) :: Ecto.Changeset.t()
def changeset(contact, attrs) do
contact
|> cast(attrs, [
:name,
:legal_name,
:tax_id,
:type,
:customer,
:supplier,
:phone,
:email,
:category_id
])
|> validate_required([:name, :type])
|> cast_embed(:address)
|> foreign_key_constraint(:category_id)
end
end
|
apps/cashtrail/lib/cashtrail/contacts/contact.ex
| 0.81648 | 0.66993 |
contact.ex
|
starcoder
|
defmodule Protobuf.TypeUtil do
require Record
Record.defrecord(
:proto_type,
code: 0,
label: :DEFAULT_TYPE,
type: :default,
elixir_type: "any()"
)
@type t :: record(
:proto_type,
code: non_neg_integer(),
label: atom(),
type: atom(),
elixir_type: String.t() | :dynamic
)
defp proto_types(), do: [
proto_type(label: :TYPE_DOUBLE, code: 1, type: :double, elixir_type: "float()"),
proto_type(label: :TYPE_FLOAT, code: 2, type: :float, elixir_type: "float()"),
proto_type(label: :TYPE_INT64, code: 3, type: :int64, elixir_type: "integer()"),
proto_type(label: :TYPE_UINT64, code: 4, type: :uint64, elixir_type: "non_neg_integer()"),
proto_type(label: :TYPE_INT32, code: 5, type: :int32, elixir_type: "integer()"),
proto_type(label: :TYPE_FIXED64, code: 6, type: :fixed64, elixir_type: "non_neg_integer()"),
proto_type(label: :TYPE_FIXED32, code: 7, type: :fixed32, elixir_type: "non_neg_integer()"),
proto_type(label: :TYPE_BOOL, code: 8, type: :bool, elixir_type: "boolean()"),
proto_type(label: :TYPE_STRING, code: 9, type: :string, elixir_type: "String.t()"),
proto_type(label: :TYPE_GROUP, code: 10, type: :group),
proto_type(label: :TYPE_MESSAGE, code: 11, type: :message, elixir_type: :dynamic),
proto_type(label: :TYPE_BYTES, code: 12, type: :bytes, elixir_type: "String.t()"),
proto_type(label: :TYPE_UINT32, code: 13, type: :uint32, elixir_type: "non_neg_integer()"),
proto_type(label: :TYPE_ENUM, code: 14, type: :enum, elixir_type: "integer()"),
proto_type(label: :TYPE_SFIXED32, code: 15, type: :sfixed32, elixir_type: "integer()"),
proto_type(label: :TYPE_SFIXED64, code: 16, type: :sfixed64, elixir_type: "integer()"),
proto_type(label: :TYPE_SINT32, code: 17, type: :sint32, elixir_type: "integer()"),
proto_type(label: :TYPE_SINT64, code: 18, type: :sint64, elixir_type: "integer()")
]
@spec find_type(pos_integer() | atom()) :: t()
defp find_type(data) do
predicate = case is_atom(data) do
true -> fn (type) -> proto_type(type, :label) === data end
false -> fn (type) -> proto_type(type, :code) === data end
end
case Enum.find(proto_types(), predicate) do
nil -> proto_type()
type -> type
end
end
def number_to_atom(data), do: data |> find_type() |> proto_type(:type)
def str_to_spec(data, type) do
case find_type(data) |> proto_type(:elixir_type) do
:dynamic -> "#{type}.t()"
type -> type
end
end
end
|
lib/protobuf/type_util.ex
| 0.612657 | 0.472014 |
type_util.ex
|
starcoder
|
defmodule Day12 do
def part1(path) do
solve(path, &move/2, {1, 0})
end
def part2(path) do
solve(path, &move_waypoint/2, {10, 1})
end
def solve(path, move, start) do
path
|> File.stream!()
|> Enum.map(&parse/1)
|> Enum.reduce({{0, 0}, start}, move)
|> elem(0)
|> manhattan({0, 0})
end
def parse(line) do
{op, arg} =
line
|> String.trim_trailing()
|> String.split_at(1)
{op, String.to_integer(arg)}
end
# part 1
def move({"N", amount}, {pos, direction}), do: {add(pos, {0, amount}), direction}
def move({"S", amount}, {pos, direction}), do: {add(pos, {0, -amount}), direction}
def move({"E", amount}, {pos, direction}), do: {add(pos, {amount, 0}), direction}
def move({"W", amount}, {pos, direction}), do: {add(pos, {-amount, 0}), direction}
def move({"L", angle}, {pos, direction}), do: {pos, rotate(direction, angle)}
def move({"R", angle}, {pos, direction}), do: {pos, rotate(direction, -angle)}
def move({"F", scalar}, {pos, direction}), do: {add(pos, direction, scalar), direction}
# part 2
def move_waypoint({"N", amount}, {pos, waypoint}), do: {pos, add(waypoint, {0, amount})}
def move_waypoint({"S", amount}, {pos, waypoint}), do: {pos, add(waypoint, {0, -amount})}
def move_waypoint({"E", amount}, {pos, waypoint}), do: {pos, add(waypoint, {amount, 0})}
def move_waypoint({"W", amount}, {pos, waypoint}), do: {pos, add(waypoint, {-amount, 0})}
def move_waypoint({"L", angle}, {pos, waypoint}), do: {pos, rotate(waypoint, angle)}
def move_waypoint({"R", angle}, {pos, waypoint}), do: {pos, rotate(waypoint, -angle)}
def move_waypoint({"F", scalar}, {pos, waypoint}), do: {add(pos, waypoint, scalar), waypoint}
defp add({x1, y1}, {x2, y2}, scalar \\ 1), do: {x1 + scalar * x2, y1 + scalar * y2}
defp manhattan({x, y}, {x0, y0}), do: abs(x - x0) + abs(y - y0)
defp rotate({x, y}, angle) do
sin = Math.sin_deg(angle)
cos = Math.cos_deg(angle)
{x * cos - y * sin, x * sin + y * cos}
end
end
|
lib/day_12.ex
| 0.722625 | 0.732927 |
day_12.ex
|
starcoder
|
defmodule Curvy.Point do
@moduledoc """
Module used for manipulating ECDSA point coordinates.
"""
use Bitwise, only_operators: true
import Curvy.Util, only: [mod: 2, inv: 2, ipow: 2]
alias Curvy.{Curve, Key, Signature}
defstruct [:x, :y]
@typedoc "Point Coordinates"
@type t :: %__MODULE__{
x: integer,
y: integer
}
@typedoc "Jacobian Point Coordiantes"
@type jacobian :: %{
x: integer,
y: integer,
z: integer
}
@crv Curve.secp256k1
@doc """
Converts the signature to a [`Point`](`t:t`) using the given hash integer and
recovery ID.
"""
@spec from_signature(Signature.t, integer, Signature.recovery_id) :: t | :error
def from_signature(%Signature{r: r, s: s}, _e, _recid)
when r == 0 or s == 0,
do: :error
def from_signature(%Signature{r: r, s: s}, e, recid) do
rinv = inv(r, @crv.n)
prefix = 2 + (recid &&& 1)
sp = <<prefix, r::big-size(256)>>
|> Key.from_pubkey()
|> Map.get(:point)
|> mul(s)
hg = @crv[:G]
|> mul(e)
|> negate()
sp
|> add(hg)
|> mul(rinv)
end
@doc """
Adds two elliptic curve points.
Returns a [`Point`](`t:t`).
"""
@spec add(t, t) :: t
def add(%__MODULE__{} = point, %__MODULE__{} = other) do
jacobian_add(to_jacobian(point), to_jacobian(other))
|> from_jacobian()
end
@doc """
Doubles an elliptic curve point.
Returns a [`Point`](`t:t`).
"""
@spec double(t) :: t
def double(%__MODULE__{} = point) do
point
|> to_jacobian()
|> jacobian_double()
|> from_jacobian()
end
@doc """
Compares two elliptic curve points.
Returns a `t:boolean`.
"""
@spec equals(point :: t, other :: t) :: boolean
def equals(%__MODULE__{} = p, %__MODULE__{} = q) do
p.x == q.x and p.y == q.y
end
@doc """
Mutiplies an elliptic curve point with the given scalar.
Returns a [`Point`](`t:t`).
"""
@spec mul(t, integer) :: t
def mul(%__MODULE__{} = point, scalar) do
point
|> to_jacobian()
|> jacobian_mul(scalar)
|> from_jacobian()
end
@doc """
Flips the elliptic curve point to `(x, -y)`.
Returns a [`Point`](`t:t`).
"""
@spec negate(point :: t) :: t
def negate(%__MODULE__{x: x, y: y}),
do: %__MODULE__{x: x, y: mod(-y, @crv.p)}
@doc """
Subtracts the second elliptic curve point from the first.
Returns a [`Point`](`t:t`).
"""
@spec subtract(t, t) :: t
def subtract(%__MODULE__{} = point, %__MODULE__{} = other),
do: add(point, negate(other))
# Converts the Point to Jacobian Point Coordianets
defp to_jacobian(%__MODULE__{x: x, y: y}), do: %{x: x, y: y, z: 1}
# Converts the Jacobian Point to Affine Coordiantes
defp from_jacobian(%{x: x, y: y, z: z}) do
z = inv(z, @crv.p)
%__MODULE__{
x: (x * ipow(z, 2)) |> mod(@crv.p),
y: (y * ipow(z, 3)) |> mod(@crv.p)
}
end
# Fast way to add two elliptic curve points
defp jacobian_add(%{y: py} = p, %{y: qy}) when py == 0 or qy == 0, do: p
defp jacobian_add(%{} = p, %{} = q) do
u1 = (p.x * ipow(q.z, 2)) |> mod(@crv.p)
u2 = (q.x * ipow(p.z, 2)) |> mod(@crv.p)
s1 = (p.y * ipow(q.z, 3)) |> mod(@crv.p)
s2 = (q.y * ipow(p.z, 3)) |> mod(@crv.p)
cond do
u1 == u2 and s1 != s2 ->
%{x: 0, y: 0, z: 1}
u1 == u2 ->
jacobian_double(p)
true ->
h = u2 - u1
r = s2 - s1
h2 = mod(h * h, @crv.p)
h3 = mod(h * h2, @crv.p)
u1h2 = mod(u1 * h2, @crv.p)
x = (ipow(r, 2) - h3 - 2 * u1h2) |> mod(@crv.p)
y = (r * (u1h2 - x) - s1 * h3) |> mod(@crv.p)
z = (h * p.z * q.z) |> mod(@crv.p)
%{x: x, y: y, z: z}
end
end
# Fast way to doubles an elliptic curve point
defp jacobian_double(%{y: 0}), do: %{x: 0, y: 0, z: 0}
defp jacobian_double(%{} = p) do
ysq = ipow(p.y, 2) |> mod(@crv.p)
s = (4 * p.x * ysq) |> mod(@crv.p)
m = (3 * ipow(p.x, 2) + @crv.a * ipow(p.z, 4)) |> mod(@crv.p)
x = (ipow(m, 2) - 2 * s) |> mod(@crv.p)
y = (m * (s - x) - 8 * ipow(ysq, 2)) |> mod(@crv.p)
z = (2 * p.y * p.z) |> mod(@crv.p)
%{x: x, y: y, z: z}
end
# Fast way to multiply the point with a scalar
defp jacobian_mul(%{}, 0), do: %{x: 0, y: 0, z: 1}
defp jacobian_mul(%{y: 0}, s) when s == 1, do: %{x: 0, y: 0, z: 1}
defp jacobian_mul(%{} = p, s) when s == 1, do: p
defp jacobian_mul(%{y: 0}, s) when s < 0 or @crv.n <= s, do: %{x: 0, y: 0, z: 1}
defp jacobian_mul(%{} = p, s) when s < 0 or @crv.n <= s, do: jacobian_mul(p, mod(s, @crv.n))
defp jacobian_mul(%{y: 0}, s) when rem(s, 2) == 0, do: %{x: 0, y: 0, z: 1}
defp jacobian_mul(%{} = p, s) when rem(s, 2) == 0, do: jacobian_mul(p, div(s, 2)) |> jacobian_double()
defp jacobian_mul(%{y: 0}, _s), do: %{x: 0, y: 0, z: 1}
defp jacobian_mul(%{} = p, s), do: jacobian_mul(p, div(s, 2)) |> jacobian_double() |> jacobian_add(p)
end
|
lib/curvy/point.ex
| 0.90546 | 0.668759 |
point.ex
|
starcoder
|
if Version.match?(System.version(), ">= 1.3.0") do
defmodule Faker.Date do
@moduledoc """
Functions for generating dates
"""
@seconds_per_day 86400
@doc """
Returns a random date of birth for a person with an age specified by a number or range
## Examples
date_of_birth #=> ~D[1961-05-09]
date_of_birth(1) #=> ~D[2015-12-06]
date_of_birth(10..19) #=> ~D[2004-05-15]
"""
@spec date_of_birth() :: Date.t
def date_of_birth(age_or_range \\ 18..99)
@spec date_of_birth(integer) :: Date.t
def date_of_birth(age) when is_integer(age) do
date_of_birth(%Range{first: age, last: age + 1})
end
@spec date_of_birth(Range.t) :: Date.t
def date_of_birth(%Range{first: first, last: last}) do
{{ current_year, current_month, current_day }, _time } = :calendar.local_time()
random_month = :crypto.rand_uniform(1, 13)
random_day = :crypto.rand_uniform(1, 29)
already_aged_this_year = current_month > random_month || current_month == random_month && random_day >= current_day
random_year = current_year - :crypto.rand_uniform(first, last) + (if already_aged_this_year, do: 1, else: 0)
{ :ok, date } = Date.new random_year, random_month, random_day
date
end
@doc """
Returns a random date in the past up to today in NaiveDateTime
"""
@spec backward(NaiveDateTime.t) :: NaiveDateTime.t
def backward(date = %NaiveDateTime{}) do
naive_now = NaiveDateTime.utc_now
diff = naive_now
|> NaiveDateTime.diff(date)
unix_now = DateTime.utc_now
|> DateTime.to_unix
case diff do
0 -> naive_now
_ ->
:crypto.rand_uniform(unix_now - diff, unix_now)
|> DateTime.from_unix!
|> DateTime.to_naive
end
end
@doc """
Returns a random date in the past up to today in DateTime
"""
@spec backward(DateTime.t) :: DateTime.t
def backward(date = %DateTime{}) do
date_naive = DateTime.to_naive(date)
diff = NaiveDateTime.utc_now
|> NaiveDateTime.diff(date_naive)
utc_now = DateTime.utc_now
unix_now = utc_now
|> DateTime.to_unix
case diff do
0 -> utc_now
_ ->
:crypto.rand_uniform(unix_now - diff, unix_now)
|> DateTime.from_unix!
end
end
@doc """
Returns a random date in the past up to N days, today not included
"""
@spec backward(integer) :: Date.t
def backward(days) do
forward(-days)
end
@doc """
Returns a random date in the future up to N days, today not included
"""
@spec forward(integer) :: Date.t
def forward(days) do
unix_now =
DateTime.utc_now()
|> DateTime.to_unix()
sign = if days < 0, do: -1, else: 1
unix_now + sign * @seconds_per_day * :crypto.rand_uniform(1, abs(days))
|> DateTime.from_unix!()
|> DateTime.to_date()
end
end
end
|
lib/faker/date.ex
| 0.804367 | 0.451387 |
date.ex
|
starcoder
|
defmodule Parques.Core.Game do
@moduledoc """
A Game is the primary piece of data, representing a match of Parqués.
"""
use TypedStruct
import Parques.Core.Color, only: [is_color: 1]
alias Parques.Core.Color
alias Parques.Core.Player
@max_players Color.count()
@type id :: String.t()
@type state :: :created | :playing | :finished
typedstruct enforce: true do
field :id, id()
field :name, String.t(), default: "New game"
field :state, state(), default: :created
field :players, %{Player.id() => Player.t()}, default: %{}
field :color_map, %{Color.t() => Player.id()}, default: %{}
field :creator_id, Player.id(), enforce: false
end
@spec max_players :: pos_integer()
def max_players, do: @max_players
@spec new(Enum.t()) :: t()
def new(fields \\ []) do
fields =
fields
|> Map.new()
|> Map.put_new_lazy(:id, &UUID.uuid4/0)
struct!(__MODULE__, fields)
end
@spec set_name(t(), String.t()) :: t()
def set_name(game, new_name) do
%__MODULE__{game | name: new_name}
end
defguard is_game_player(game, player) when is_map_key(game.players, player.id)
@spec players(t()) :: [Player.t()]
def players(%__MODULE__{players: players, color_map: color_map}) do
Color.list()
|> Enum.map(fn color ->
player_id = color_map[color]
players[player_id]
end)
|> Enum.reject(&is_nil/1)
end
@spec creator(t()) :: Player.t() | nil
def creator(%__MODULE__{creator_id: nil}), do: nil
def creator(%__MODULE__{} = game), do: Map.fetch!(game.players, game.creator_id)
@spec add_player(t(), Player.t()) :: t()
def add_player(game, player) when is_game_player(game, player), do: game
def add_player(%__MODULE__{players: players, state: :created} = game, player)
when map_size(players) < @max_players do
color_chosen = available_color(game)
player_with_color = Player.set_color(player, color_chosen)
new_players = Map.put(players, player.id, player_with_color)
new_color_map = Map.put(game.color_map, color_chosen, player.id)
creator_id = game.creator_id || player.id
%__MODULE__{game | players: new_players, color_map: new_color_map, creator_id: creator_id}
end
@spec available_color(t()) :: Color.t()
defp available_color(game), do: Color.available(colors_taken(game))
@spec colors_taken(t()) :: [Color.t()]
defp colors_taken(%{color_map: color_map}), do: Map.keys(color_map)
@spec remove_player(t(), Player.t()) :: t()
def remove_player(%__MODULE__{players: players} = game, player)
when is_game_player(game, player) do
{player, new_players} = Map.pop!(players, player.id)
new_color_map = Map.delete(game.color_map, player.color)
creator_id =
case game do
%{creator_id: creator_id} when creator_id == player.id ->
new_players
|> Map.keys()
|> List.first()
%{creator_id: creator_id} ->
creator_id
end
%__MODULE__{game | players: new_players, color_map: new_color_map, creator_id: creator_id}
end
def remove_player(%__MODULE__{} = game, _player), do: game
@spec set_player_color(t(), Player.t(), Color.t()) :: t()
def set_player_color(game, player, color) when is_color(color) do
case find_player_by_color(game, color) do
nil ->
game
|> update_player(Player.set_color(player, color))
|> update_color_map()
another_player ->
player_color = game.players[player.id].color
game
|> update_player(Player.set_color(player, color))
|> update_player(Player.set_color(another_player, player_color))
|> update_color_map()
end
end
@spec find_player_by_color(t(), Color.t()) :: Player.t() | nil
defp find_player_by_color(game, color) do
game.players[game.color_map[color]]
end
@spec update_player(t(), Player.t()) :: t()
defp update_player(game, updated_player) do
new_players = %{game.players | updated_player.id => updated_player}
%__MODULE__{game | players: new_players}
end
@spec update_color_map(t()) :: t()
defp update_color_map(%__MODULE__{players: players} = game) do
new_color_map =
Enum.reduce(players, %{}, fn {_id, player}, color_map ->
Map.put(color_map, player.color, player.id)
end)
%__MODULE__{game | color_map: new_color_map}
end
end
|
lib/parques/core/game.ex
| 0.817137 | 0.439086 |
game.ex
|
starcoder
|
defimpl String.Chars, for: ExPcap.MagicNumber do
@doc """
Returns a human readable representation of the magic number.
"""
@spec to_string(ExPcap.MagicNumber.t()) :: String.t()
def to_string(magic_number) do
"""
magic number: 0x#{magic_number.magic |> Integer.to_string(16) |> String.downcase()}
nanoseconds? #{magic_number.nanos}
reverse bytes? #{magic_number.reverse_bytes}
"""
|> String.trim()
end
end
defmodule ExPcap.MagicNumber do
@moduledoc """
This module represents a 'magic number' from a pcap header. The magic number
not only contains a known value, but the value indicates the order in which
bytes should be read AND whether or not datetimes use milliseconds or
nanoseconds.
"""
defstruct reverse_bytes: false,
nanos: false,
magic: 0x00000000
@type t :: %ExPcap.MagicNumber{
reverse_bytes: boolean,
nanos: boolean,
magic: non_neg_integer
}
@bytes_in_magic 4
@doc """
Returns the number of bytes contained in the magic number.
"""
@spec bytes_in_magic() :: non_neg_integer
def bytes_in_magic() do
@bytes_in_magic
end
@doc """
Returns a magic number that indicates wheather the bytes need to be reversed.
"""
@spec magic_number(0xD4, 0xC3, 0xB2, 0xA1) :: ExPcap.MagicNumber.t()
def magic_number(0xD4, 0xC3, 0xB2, 0xA1) do
%ExPcap.MagicNumber{
reverse_bytes: true,
nanos: false,
magic: 0xD4C3B2A1
}
end
@spec magic_number(0xA1, 0xB2, 0xC3, 0xD4) :: ExPcap.MagicNumber.t()
def magic_number(0xA1, 0xB2, 0xC3, 0xD4) do
%ExPcap.MagicNumber{
reverse_bytes: false,
nanos: false,
magic: 0xA1B2C3D4
}
end
@spec magic_number(0xA1, 0xB2, 0x3C, 0x4D) :: ExPcap.MagicNumber.t()
def magic_number(0xA1, 0xB2, 0x3C, 0x4D) do
%ExPcap.MagicNumber{
reverse_bytes: false,
nanos: true,
magic: 0xA1B2C3D4
}
end
@spec magic_number(0x4D, 0x3C, 0xB2, 0xA1) :: ExPcap.MagicNumber.t()
def magic_number(0x4D, 0x3C, 0xB2, 0xA1) do
%ExPcap.MagicNumber{
reverse_bytes: true,
nanos: true,
magic: 0xA1B2C3D4
}
end
@doc """
This reads the bytes of the magic number and matches them with the appropriate
interpretation of the magic number.
"""
@spec read_magic(binary) :: ExPcap.MagicNumber.t()
def read_magic(data) do
<<
magic1::unsigned-integer-size(8),
magic2::unsigned-integer-size(8),
magic3::unsigned-integer-size(8),
magic4::unsigned-integer-size(8)
>> = data
magic_number(magic1, magic2, magic3, magic4)
end
@doc """
Reads the magic number from the file passed in.
"""
@spec from_file(IO.device()) :: ExPcap.MagicNumber.t()
def from_file(f) do
f |> IO.binread(@bytes_in_magic) |> read_magic
end
end
|
lib/expcap/magic_number.ex
| 0.831656 | 0.574335 |
magic_number.ex
|
starcoder
|
defmodule PlugCacheControl do
@moduledoc """
A plug + helpers for overwriting the default `cache-control` header. The plug
supports all the response header directives defined in [RFC7234, section
5.2.2](https://datatracker.ietf.org/doc/html/rfc7234#section-5.2.2).
## Header directives
The `PlugCacheControl` plug takes a `directives` option which can specify
either _static_ or _dynamic_ header directives. Static directives are useful
when you don't need per-request directives. Static directives are defined very
similarly to a struct's key.
plug PlugCacheControl, directives: [:public, max_age: {1, :hour}]
As seen in the above example, directive names with hyphens are mapped to atoms
by replacing the hyphens with underscores.
Boolean directives like `public`, `private`, `must-revalidate`, `no-store` and
so on can be included in the header value by simply including them in the
directives list e.g. no need for explicit `no_store: true` value. Note that as
per the standard, `no-cache` can also specify one or more fields. This is
supported via the definition below.
plug PlugCacheControl, directives: [no_cache: ["somefield", "otherfield"]]
The `public` and `private` directives also have somewhat special handling so
you won't need to explicitly define `private: false` when you've used
`:public` in the "boolean section" of the directives list. Another important
thing is that if a directive is not included in the directives list, the
directive will be _omitted_ from the header's value.
The values of the directives which have a delta-seconds values can be defined
directly as an integer representing the delta-seconds.
plug PlugCacheControl, directives: [:public, max_age: 3600]
A unit tuple can also be used to specify delta-seconds. The supported time
units are `second`, `seconds`, `minute`, `minutes`, `hour`, `hours`, `day`,
`days`, `week`, `weeks`, `year`, `years`. The following example shows how unit
tuples can be used as a conveniece to define delta-seconds.
plug PlugCacheControl,
directives: [
:public,
max_age: {1, :hour},
stale_while_revalidate: {20, :minutes}
]
Dynamic directives are useful when you might want to derive cache control
directives per-request. Maybe there's some other header value which you care
about or a dynamic configuration governing caching behaviour, dynamic
directives are the way to go.
plug PlugCacheControl, directives: &__MODULE__.dyn_cc/1
# ...somewhere in the module...
defp dyn_cc(_conn) do
[:public, max_age: Cache.get(:max_age)]
end
As seen in the previous example, the only difference between static and
dynamic directives definition is that the latter is a unary function which
returns a directives list. The exact same rules that apply to the static
directives apply to the function's return value.
## A note on behaviour
The first time the plug is called on a connection, the existing value of the
Cache-Control header is _replaced_ by the user-defined one. A private field
which signifies the header value is overwritten is put on the connection
struct. On subsequent calls of the plug, the provided directives' definitions
are _merged_ with the header values. This allows the user to build up the
Cache-Control header value.
Of course, if one wants to replace the header value on a connection that has an
already overwritten value, one can use the
`PlugCacheControl.Helpers.put_cache_control` function or provide a `replace:
true` option to the plug.
plug PlugCacheControl, directives: [...], replace: true
The latter approach allows for a finer-grained control and conditional
replacement of header values.
plug PlugCacheControl, [directives: [...], replace: true] when action == :index
plug PlugCacheControl, [directives: [...]] when action == :show
"""
@behaviour Plug
alias Plug.Conn
alias PlugCacheControl.Helpers
@typep static :: Helpers.directive_opt()
@typep dynamic :: (Plug.Conn.t() -> Helpers.directive_opt())
@impl Plug
@spec init([{:directives, static | dynamic}]) :: %{directives: dynamic, replace: boolean()}
def init(opts) do
opts
|> Enum.into(%{})
|> with_default_opts()
|> validate_opts!()
end
@impl Plug
@spec call(Conn.t(), %{directives: static() | dynamic(), replace: boolean()}) :: Conn.t()
def call(conn, %{directives: fun} = opts) when is_function(fun, 1) do
opts = Map.put(opts, :directives, fun.(conn))
call(conn, opts)
end
def call(%Conn{} = conn, %{directives: dir, replace: true}) do
conn
|> Helpers.put_cache_control(dir)
|> Conn.put_private(:cache_control_overwritten, true)
end
def call(%Conn{private: %{cache_control_overwritten: true}} = conn, %{directives: dir}) do
Helpers.patch_cache_control(conn, dir)
end
def call(%Conn{} = conn, %{directives: dir}) do
conn
|> Helpers.put_cache_control(dir)
|> Conn.put_private(:cache_control_overwritten, true)
end
defp with_default_opts(opts) do
default_opts = %{
replace: false
}
Map.merge(default_opts, opts)
end
defp validate_opts!(%{directives: dir, replace: replace} = opts)
when (is_list(dir) or is_function(dir, 1)) and is_boolean(replace) do
opts
end
defp validate_opts!(_) do
raise ArgumentError,
"Provide a \"directives\" option with list of directives or a unary \
function taking connection as first argument and returning a list of \
directives."
end
end
|
lib/plug_cache_control.ex
| 0.867787 | 0.670706 |
plug_cache_control.ex
|
starcoder
|
defmodule ExSieve.Builder.Where do
@moduledoc false
alias Ecto.Query.Builder.Filter
alias ExSieve.Node.{Attribute, Grouping, Condition}
@true_values [1, '1', 'T', 't', true, 'true', 'TRUE', "1", "T", "t", "true",
"TRUE"]
@spec build(Ecto.Queryable.t, Grouping.t, Macro.t) :: Ecto.Query.t
def build(query, %Grouping{combinator: combinator} = grouping, binding) when combinator in ~w(and or)a do
exprs = grouping |> List.wrap |> groupings_expr
:where
|> Filter.build(combinator, Macro.escape(query), binding, exprs, __ENV__)
|> Code.eval_quoted
|> elem(0)
end
defp grouping_expr(%Grouping{conditions: []}) do
[]
end
defp grouping_expr(%Grouping{combinator: combinator, conditions: conditions}) do
conditions |> Enum.map(&condition_expr/1) |> combinator_expr(combinator)
end
defp condition_expr(%Condition{attributes: attrs, values: vals, predicat: predicat, combinator: combinator}) do
attrs
|> Enum.map(&predicat_expr(predicat, &1, vals))
|> combinator_expr(combinator)
end
defp groupings_expr(groupings), do: groupings_expr(groupings, [], nil)
defp groupings_expr([%{groupings: []} = parent], [], nil), do: grouping_expr(parent)
defp groupings_expr([%{groupings: []} = parent | tail], acc, combinator_acc) do
groupings_expr(tail, acc ++ [grouping_expr(parent)], combinator_acc)
end
defp groupings_expr([%{combinator: combinator, groupings: children} = parent|tail], acc, combinator_acc) do
children_exprs = groupings_expr(children, acc ++ [grouping_expr(parent)], combinator)
groupings_expr(tail, children_exprs, combinator_acc)
end
defp groupings_expr([], acc, nil), do: acc
defp groupings_expr([], acc, combinator), do: combinator_expr(acc, combinator)
defp combinator_expr(exprs, combinator, acc \\ [])
defp combinator_expr([first_expr, second_expr|tail], combinator, acc) do
tail_exprs = combinator_expr(tail, combinator, quote do
unquote(combinator)(unquote_splicing([first_expr, second_expr]))
end)
combinator_expr([tail_exprs], combinator, acc)
end
defp combinator_expr([expr], _combinator, []),
do: expr
defp combinator_expr([expr], combinator, acc),
do: quote(do: unquote(combinator)(unquote(expr), unquote(acc)))
defp combinator_expr([], _combinator, acc),
do: acc
defp field_expr(%Attribute{name: name, parent: parent}) do
quote do: field(unquote(Macro.var(parent, Elixir)), unquote(name))
end
for basic_predicat <- Condition.basic_predicates do
for {name, combinator} <- [all: :and, any: :or] do
basic_predicat = basic_predicat |> String.to_atom
predicat = "#{basic_predicat}_#{name}" |> String.to_atom
defp predicat_expr(unquote(predicat), attribute, values) do
values
|> Enum.map(&predicat_expr(unquote(basic_predicat), attribute, List.wrap(&1)))
|> combinator_expr(unquote(combinator))
end
end
end
defp predicat_expr(:eq, attribute, [value|_]) do
quote(do: unquote(field_expr(attribute)) == ^unquote(value))
end
defp predicat_expr(:not_eq, attribute, [value|_]) do
quote do: unquote(field_expr(attribute)) != ^unquote(value)
end
defp predicat_expr(:cont, attribute, [value|_]) do
quote do: ilike(unquote(field_expr(attribute)), unquote("%#{value}%"))
end
defp predicat_expr(:not_cont, attribute, [value|_]) do
quote do: not(ilike(unquote(field_expr(attribute)), unquote("%#{value}%")))
end
defp predicat_expr(:lt, attribute, [value|_]) do
quote do: unquote(field_expr(attribute)) < ^unquote(value)
end
defp predicat_expr(:lteq, attribute, [value|_]) do
quote do: unquote(field_expr(attribute)) <= ^unquote(value)
end
defp predicat_expr(:gt, attribute, [value|_]) do
quote do: unquote(field_expr(attribute)) > ^unquote(value)
end
defp predicat_expr(:gteq, attribute, [value|_]) do
quote do: unquote(field_expr(attribute)) >= ^unquote(value)
end
defp predicat_expr(:in, attribute, values) do
quote do: unquote(field_expr(attribute)) in unquote(values)
end
defp predicat_expr(:not_in, attribute, values) do
quote do: not(unquote(field_expr(attribute)) in unquote(values))
end
defp predicat_expr(:matches, attribute, [value|_]) do
quote do: ilike(unquote(field_expr(attribute)), unquote(value))
end
defp predicat_expr(:does_not_match, attribute, [value|_]) do
quote do: not(ilike(unquote(field_expr(attribute)), unquote(value)))
end
defp predicat_expr(:start, attribute, [value|_]) do
quote do: ilike(unquote(field_expr(attribute)), unquote("#{value}%"))
end
defp predicat_expr(:not_start, attribute, [value|_]) do
quote do: not(ilike(unquote(field_expr(attribute)), unquote("#{value}%")))
end
defp predicat_expr(:end, attribute, [value|_]) do
quote do: ilike(unquote(field_expr(attribute)), unquote("%#{value}%"))
end
defp predicat_expr(:not_end, attribute, [value|_]) do
quote do: not(ilike(unquote(field_expr(attribute)), unquote("%#{value}%")))
end
defp predicat_expr(:true, attribute, [value|_]) when value in @true_values do
predicat_expr(:not_eq, attribute, [true])
end
defp predicat_expr(:not_true, attribute, [value|_]) when value in @true_values do
predicat_expr(:not_eq, attribute, [true])
end
defp predicat_expr(:false, attribute, [value|_]) when value in @true_values do
predicat_expr(:eq, attribute, [false])
end
defp predicat_expr(:not_false, attribute, [value|_]) when value in @true_values do
predicat_expr(:not_eq, attribute, [false])
end
defp predicat_expr(:present, attribute, [value|_] = values) when value in @true_values do
quote(do: not(unquote(predicat_expr(:blank, attribute, values))))
end
defp predicat_expr(:blank, attribute, [value|_]) when value in @true_values do
quote(do: is_nil(unquote(field_expr(attribute))) or unquote(field_expr(attribute)) == ^'')
end
defp predicat_expr(:null, attribute, [value|_]) when value in @true_values do
quote(do: is_nil(unquote(field_expr(attribute))))
end
defp predicat_expr(:not_null, attribute, [value|_] = values) when value in @true_values do
quote(do: not(unquote(predicat_expr(:null, attribute, values))))
end
end
|
lib/ex_sieve/builder/where.ex
| 0.635336 | 0.550909 |
where.ex
|
starcoder
|
defmodule Hunter do
@moduledoc """
A Elixir client for Mastodon, a GNU Social compatible micro-blogging service
"""
@hunter_version Mix.Project.config()[:version]
@doc """
Retrieve account of authenticated user
## Parameters
* `conn` - connection credentials
"""
@spec verify_credentials(Hunter.Client.t()) :: Hunter.Account.t()
defdelegate verify_credentials(conn), to: Hunter.Account
@doc """
Make changes to the authenticated user
## Parameters
* `conn` - connection credentials
* `data` - data payload
## Possible keys for payload
* `display_name` - name to display in the user's profile
* `note` - new biography for the user
* `avatar` - base64 encoded image to display as the user's avatar (e.g. `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAUoAAADrCAYAAAA...`)
* `header` - base64 encoded image to display as the user's header image (e.g. `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAUoAAADrCAYAAAA...`)
"""
@spec update_credentials(Hunter.Client.t(), map) :: Hunter.Account.t()
defdelegate update_credentials(conn, data), to: Hunter.Account
@doc """
Retrieve account
## Parameters
* `conn` - connection credentials
* `id` - account identifier
"""
@spec account(Hunter.Client.t(), non_neg_integer) :: Hunter.Account.t()
defdelegate account(conn, id), to: Hunter.Account
@doc """
Get a list of followers
## Parameters
* `conn` - connection credentials
* `id` - account identifier
* `options` - options list
## Options
* `max_id` - get a list of followers with id less than or equal this value
* `since_id` - get a list of followers with id greater than this value
* `limit` - maximum number of followers to get, default: 40, maximum: 80
"""
@spec followers(Hunter.Client.t(), non_neg_integer, Keyword.t()) :: [Hunter.Account.t()]
defdelegate followers(conn, id, options \\ []), to: Hunter.Account
@doc """
Get a list of followed accounts
## Parameters
* `conn` - connection credentials
* `id` - account identifier
* `options` - options list
## Options
* `max_id` - get a list of followings with id less than or equal this value
* `since_id` - get a list of followings with id greater than this value
* `limit` - maximum number of followings to get, default: 40, maximum: 80
"""
@spec following(Hunter.Client.t(), non_neg_integer, Keyword.t()) :: [Hunter.Account.t()]
defdelegate following(conn, id, options \\ []), to: Hunter.Account
@doc """
Follow a remote user
## Parameters
* `conn` - connection credentials
* `uri` - URI of the remote user, in the format of `username@domain`
"""
@spec follow_by_uri(Hunter.Client.t(), String.t()) :: Hunter.Account.t()
defdelegate follow_by_uri(conn, uri), to: Hunter.Account
@doc """
Search for accounts
## Parameters
* `conn` - connection credentials
* `options` - option list
## Options
* `q`: what to search for
* `limit`: maximum number of matching accounts to return, default: 40
"""
@spec search_account(Hunter.Client.t(), Keyword.t()) :: [Hunter.Account.t()]
defdelegate search_account(conn, options), to: Hunter.Account
@doc """
Retrieve user's blocks
## Parameters
* `conn` - connection credentials
## Options
* `max_id` - get a list of blocks with id less than or equal this value
* `since_id` - get a list of blocks with id greater than this value
* `limit` - maximum number of blocks to get, default: 40, max: 80
"""
@spec blocks(Hunter.Client.t(), Keyword.t()) :: [Hunter.Account.t()]
defdelegate blocks(conn, options \\ []), to: Hunter.Account
@doc """
Retrieve a list of follow requests
## Parameters
* `conn` - connection credentials
* `options` - option list
## Options
* `max_id` - get a list of follow requests with id less than or equal this value
* `since_id` - get a list of follow requests with id greater than this value
* `limit` - maximum number of requests to get, default: 40, max: 80
"""
@spec follow_requests(Hunter.Client.t(), Keyword.t()) :: [Hunter.Account.t()]
defdelegate follow_requests(conn, options \\ []), to: Hunter.Account
@doc """
Retrieve user's mutes
## Parameters
* `conn` - connection credentials
* `options` - option list
## Options
* `max_id` - get a list of mutes with id less than or equal this value
* `since_id` - get a list of mutes with id greater than this value
* `limit` - maximum number of mutes to get, default: 40, max: 80
"""
@spec mutes(Hunter.Client.t(), Keyword.t()) :: [Hunter.Account.t()]
defdelegate mutes(conn, options \\ []), to: Hunter.Account
@doc """
Accepts a follow request
## Parameters
* `conn` - connection credentials
* `id` - follow request id
"""
@spec accept_follow_request(Hunter.Client.t(), non_neg_integer) :: boolean
defdelegate accept_follow_request(conn, id), to: Hunter.Account
@doc """
Rejects a follow request
## Parameters
* `conn` - connection credentials
* `id` - follow request id
"""
@spec reject_follow_request(Hunter.Client.t(), non_neg_integer) :: boolean
defdelegate reject_follow_request(conn, id), to: Hunter.Account
## Application
@doc """
Register a new OAuth client app on the target instance
## Parameters
* `name` - name of your application
* `redirect_uri` - where the user should be redirected after authorization,
default: `urn:ietf:wg:oauth:2.0:oob` (no redirect)
* `scopes` - scope list, see the scope section for more details, default: `read`
* `website` - URL to the homepage of your app, default: `nil`
* `options` - option list
## Scopes
* `read` - read data
* `write` - post statuses and upload media for statuses
* `follow` - follow, unfollow, block, unblock
Multiple scopes can be requested during the authorization phase with the `scope` query param
## Options
* `save?` - persists your application information to a file, so, you can use
them later. default: `false`
* `api_base_url` - specifies if you want to register an application on a
different instance. default: `https://mastodon.social`
"""
@spec create_app(String.t(), String.t(), [String.t()], String.t(), Keyword.t()) ::
Hunter.Application.t() | no_return
defdelegate create_app(
name,
redirect_uri \\ "urn:ietf:wg:oauth:2.0:oob",
scopes \\ ["read"],
website \\ nil,
options \\ []
),
to: Hunter.Application
@doc """
Load persisted application's credentials
## Parameters
* `name` - application's name
"""
@spec load_credentials(String.t()) :: Hunter.Application.t()
defdelegate load_credentials(name), to: Hunter.Application
@doc """
Initializes a client
## Options
* `base_url` - URL of the instance you want to connect to
* `bearer_token` - [String] OAuth access token for your authenticated user
"""
@spec new(Keyword.t()) :: Hunter.Client.t()
defdelegate new(options \\ []), to: Hunter.Client
@doc """
User agent of the client
"""
@spec user_agent() :: String.t()
defdelegate user_agent, to: Hunter.Client
@doc """
Upload a media file
## Parameters
* `conn` - connection credentials
* `file` - media to be uploaded
* `options` - option list
## Options
* `description` - plain-text description of the media for accessibility (max 420 chars)
* `focus` - two floating points, comma-delimited.
"""
@spec upload_media(Hunter.Client.t(), Path.t(), Keyword.t()) :: Hunter.Attachment.t()
defdelegate upload_media(conn, file, options \\ []), to: Hunter.Attachment
@doc """
Get the relationships of authenticated user towards given other users
## Parameters
* `conn` - connection credentials
* `id` - list of relationship IDs
"""
@spec relationships(Hunter.Client.t(), [non_neg_integer]) :: [Hunter.Relationship.t()]
defdelegate relationships(conn, ids), to: Hunter.Relationship
@doc """
Follow a user
## Parameters
* `conn` - connection credentials
* `id` - user identifier
"""
@spec follow(Hunter.Client.t(), non_neg_integer) :: Hunter.Relationship.t()
defdelegate follow(conn, id), to: Hunter.Relationship
@doc """
Unfollow a user
## Parameters
* `conn` - connection credentials
* `id` - user identifier
"""
@spec unfollow(Hunter.Client.t(), non_neg_integer) :: Hunter.Relationship.t()
defdelegate unfollow(conn, id), to: Hunter.Relationship
@doc """
Block a user
## Parameters
* `conn` - connection credentials
* `id` - user identifier
"""
@spec block(Hunter.Client.t(), non_neg_integer) :: Hunter.Relationship.t()
defdelegate block(conn, id), to: Hunter.Relationship
@doc """
Unblock a user
* `conn` - connection credentials
* `id` - user identifier
"""
@spec unblock(Hunter.Client.t(), non_neg_integer) :: Hunter.Relationship.t()
defdelegate unblock(conn, id), to: Hunter.Relationship
@doc """
Mute a user
## Parameters
* `conn` - connection credentials
* `id` - user identifier
"""
@spec mute(Hunter.Client.t(), non_neg_integer) :: Hunter.Relationship.t()
defdelegate mute(conn, id), to: Hunter.Relationship
@doc """
Unmute a user
## Parameters
* `conn` - connection credentials
* `id` - user identifier
"""
@spec unmute(Hunter.Client.t(), non_neg_integer) :: Hunter.Relationship.t()
defdelegate unmute(conn, id), to: Hunter.Relationship
@doc """
Search for content
## Parameters
* `conn` - connection credentials
* `q` - the search query
* `options` - option list
## Options
* `resolve` - whether to resolve non-local accounts
"""
@spec search(Hunter.Client.t(), String.t(), Keyword.t()) :: Hunter.Result.t()
defdelegate search(conn, query, options \\ []), to: Hunter.Result
@doc """
Create new status
## Parameters
* `conn` - connection credentials
* `status` - text of the status
* `options` - option list
## Options
* `in_reply_to_id` - local ID of the status you want to reply to
* `media_ids` - list of media IDs to attach to the status (maximum: 4)
* `sensitive` - whether the media of the status is NSFW
* `spoiler_text` - text to be shown as a warning before the actual content
* `visibility` - either `direct`, `private`, `unlisted` or `public`
"""
@spec create_status(Hunter.Client.t(), String.t(), Keyword.t()) :: Hunter.Status.t() | no_return
defdelegate create_status(conn, status, options \\ []), to: Hunter.Status
@doc """
Retrieve status
## Parameters
* `conn` - connection credentials
* `id` - status identifier
"""
@spec status(Hunter.Client.t(), non_neg_integer) :: Hunter.Status.t()
defdelegate status(conn, id), to: Hunter.Status
@doc """
Destroy status
## Parameters
* `conn` - connection credentials
* `id` - status identifier
"""
@spec destroy_status(Hunter.Client.t(), non_neg_integer) :: boolean
defdelegate destroy_status(conn, id), to: Hunter.Status
@doc """
Reblog a status
## Parameters
* `conn` - connection credentials
* `id` - status identifier
"""
@spec reblog(Hunter.Client.t(), non_neg_integer) :: Hunter.Status.t()
defdelegate reblog(conn, id), to: Hunter.Status
@doc """
Undo a reblog of a status
## Parameters
* `conn` - connection credentials
* `id` - status identifier
"""
@spec unreblog(Hunter.Client.t(), non_neg_integer) :: Hunter.Status.t()
defdelegate unreblog(conn, id), to: Hunter.Status
@doc """
Fetch the list of users who reblogged the status.
## Parameters
* `conn` - connection credentials
* `id` - status identifier
* `options` - option list
## Options
* `max_id` - get a list of *reblogged by* ids less than or equal this value
* `since_id` - get a list of *reblogged by* ids greater than this value
* `limit` - maximum number of *reblogged by* to get, default: 40, max: 80
"""
@spec reblogged_by(Hunter.Client.t(), non_neg_integer, Keyword.t()) :: [Hunter.Account.t()]
defdelegate reblogged_by(conn, id, options \\ []), to: Hunter.Account
@doc """
Favorite a status
## Parameters
* `conn` - connection credentials
* `id` - status identifier
"""
@spec favourite(Hunter.Client.t(), non_neg_integer) :: Hunter.Status.t()
defdelegate favourite(conn, id), to: Hunter.Status
@doc """
Undo a favorite of a status
## Parameters
* `conn` - connection credentials
* `id` - status identifier
"""
@spec unfavourite(Hunter.Client.t(), non_neg_integer) :: Hunter.Status.t()
defdelegate unfavourite(conn, id), to: Hunter.Status
@doc """
Fetch a user's favourites
## Parameters
* `conn` - connection credentials
* `options` - option list
## Options
* `max_id` - get a list of favourites with id less than or equal this value
* `since_id` - get a list of favourites with id greater than this value
* `limit` - maximum of favourites to get, default: 20, max: 40
"""
@spec favourites(Hunter.Client.t(), Keyword.t()) :: [Hunter.Status.t()]
defdelegate favourites(conn, options \\ []), to: Hunter.Status
@doc """
Fetch the list of users who favourited the status
## Parameters
* `conn` - connection credentials
* `id` - status identifier
* `options` - option list
## Options
* `max_id` - get a list of *favourited by* ids less than or equal this value
* `since_id` - get a list of *favourited by* ids greater than this value
* `limit` - maximum number of *favourited by* to get, default: 40, max: 80
"""
@spec favourited_by(Hunter.Client.t(), non_neg_integer, Keyword.t()) :: [Hunter.Account.t()]
defdelegate favourited_by(conn, id, options \\ []), to: Hunter.Account
@doc """
Get a list of statuses by a user
## Parameters
* `conn` - connection credentials -
* `account_id` - account identifier
* `options` - option list
## Options
* `only_media` - only return `Hunter.Status.t` that have media attachments
* `exclude_replies` - skip statuses that reply to other statuses
* `max_id` - get a list of statuses with id less than or equal this value
* `since_id` - get a list of statuses with id greater than this value
* `limit` - maximum number of statuses to get, default: 20, max: 40
"""
@spec statuses(Hunter.Client.t(), non_neg_integer, Keyword.t()) :: [Hunter.Status.t()]
defdelegate statuses(conn, account_id, options \\ []), to: Hunter.Status
@doc """
Retrieve statuses from the home timeline
## Parameters
* `conn` - connection credentials
* `options` - option list
## Options
* `max_id` - get a list of timelines with id less than or equal this value
* `since_id` - get a list of timelines with id greater than this value
* `limit` - maximum number of statuses on the requested timeline to get, default: 20, max: 40
"""
@spec home_timeline(Hunter.Client.t(), Keyword.t()) :: [Hunter.Status.t()]
defdelegate home_timeline(conn, options \\ []), to: Hunter.Status
@doc """
Retrieve statuses from the public timeline
## Parameters
* `conn` - connection credentials
* `options` - option list
## Options
* `local` - only return statuses originating from this instance
* `max_id` - get a list of timelines with id less than or equal this value
* `since_id` - get a list of timelines with id greater than this value
* `limit` - maximum number of statuses on the requested timeline to get, default: 20, max: 40
"""
@spec public_timeline(Hunter.Client.t(), Keyword.t()) :: [Hunter.Status.t()]
defdelegate public_timeline(conn, options \\ []), to: Hunter.Status
@doc """
Retrieve statuses from a hashtag
## Parameters
* `conn` - connection credentials
* `hashtag` - string list
* `options` - option list
## Options
* `local` - only return statuses originating from this instance
* `max_id` - get a list of timelines with id less than or equal this value
* `since_id` - get a list of timelines with id greater than this value
* `limit` - maximum number of statuses on the requested timeline to get, default: 20, max: 40
"""
@spec hashtag_timeline(Hunter.Client.t(), [String.t()], Keyword.t()) :: [Hunter.Status.t()]
defdelegate hashtag_timeline(conn, hashtag, options \\ []), to: Hunter.Status
@doc """
Retrieve instance information
## Parameters
* `conn` - connection credentials
"""
@spec instance_info(Hunter.Client.t()) :: Hunter.Instance.t()
defdelegate instance_info(conn), to: Hunter.Instance
@doc """
Retrieve user's notifications
## Parameters
* `conn` - connection credentials
* `options` - option list
## Options
* `max_id` - get a list of notifications with id less than or equal this value
* `since_id` - get a list of notifications with id greater than this value
* `limit` - maximum number of notifications to get, default: 15, max: 30
"""
@spec notifications(Hunter.Client.t(), Keyword.t()) :: [Hunter.Notification.t()]
defdelegate notifications(conn, options \\ []), to: Hunter.Notification
@doc """
Retrieve single notification
## Parameters
* `conn` - connection credentials
* `id` - notification identifier
"""
@spec notification(Hunter.Client.t(), non_neg_integer) :: Hunter.Notification.t()
defdelegate notification(conn, id), to: Hunter.Notification
@doc """
Deletes all notifications from the Mastodon server for the authenticated user
## Parameters
* `conn` - connection credentials
"""
@spec clear_notifications(Hunter.Client.t()) :: boolean
defdelegate clear_notifications(conn), to: Hunter.Notification
@doc """
Dismiss a single notification
## Parameters
* `conn` - connection credentials
* `id` - notification id
"""
@spec clear_notification(Hunter.Client.t(), non_neg_integer) :: boolean
defdelegate clear_notification(conn, id), to: Hunter.Notification
@doc """
Retrieve a user's reports
## Parameters
* `conn` - connection credentials
"""
@spec reports(Hunter.Client.t()) :: [Hunter.Report.t()]
defdelegate reports(conn), to: Hunter.Report
@doc """
Report a user
## Parameters
* `conn` - connection credentials
* `account_id` - the ID of the account to report
* `status_ids` - the IDs of statuses to report
* `comment` - a comment to associate with the report
"""
@spec report(Hunter.Client.t(), non_neg_integer, [non_neg_integer], String.t()) ::
Hunter.Report.t()
defdelegate report(conn, account_id, status_ids, comment), to: Hunter.Report
@doc """
Retrieve status context
## Parameters
* `conn` - connection credentials
* `id` - status identifier
"""
@spec status_context(Hunter.Client.t(), non_neg_integer) :: Hunter.Context.t()
defdelegate status_context(conn, id), to: Hunter.Context
@doc """
Retrieve a card associated with a status
## Parameters
* `conn` - connection credentials
* `id` - status id
"""
@spec card_by_status(Hunter.Client.t(), non_neg_integer) :: Hunter.Card.t()
defdelegate card_by_status(conn, id), to: Hunter.Card
@doc """
Retrieve access token
## Parameters
* `app` - application details, see: `Hunter.Application.create_app/5` for more details.
* `username` - account's email
* `password` - account's password
* `base_url` - API base url, default: `https://mastodon.social`
"""
defdelegate log_in(app, username, password, base_url \\ nil), to: Hunter.Client
@doc """
Fetch user's blocked domains
## Parameters
* `conn` - connection credentials
* `options` - option list
## Options
* `max_id` - get a list of blocks with id less than or equal this value
* `since_id` - get a list of blocks with id greater than this value
* `limit` - maximum number of blocks to get, default: 40, max: 80
"""
defdelegate blocked_domains(conn, options \\ []), to: Hunter.Domain
@doc """
Block a domain
## Parameters
* `conn` - connection credentials
* `domain` - domain to block
"""
defdelegate block_domain(conn, domain), to: Hunter.Domain
@doc """
Unblock a domain
## Parameters
* `conn` - connection credentials
* `domain` - domain to unblock
"""
defdelegate unblock_domain(conn, domain), to: Hunter.Domain
@doc """
Returns Hunter version
"""
@spec version() :: String.t()
def version(), do: @hunter_version
end
|
lib/hunter.ex
| 0.903661 | 0.534916 |
hunter.ex
|
starcoder
|
defmodule GeoDistance do
@moduledoc """
Using the [Haversine
formula](http://rosettacode.org/wiki/Haversine_formula#Erlang)
calculate the distance between two point of latitude/longititude.
To and From parameters may be specified as
(from_lat, from_long, to_lat, to_long)
or
({from_lat, from_long}, {to_lat, to_long})
Latitude and Longitude bounding coordinates can be computed using
the [formulae
provided](http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates)
by <NAME>.
For this library the radius of the earth is taken to be 6372.8 KM;
miles to KM conversions are done with the value 0.621371192237.
"""
@radius 6372.8
@mk_conversion 0.621371192237
@doc """
Computes {{min_lat, max_lat}, {min_long, max_long}} given
origin_lat, origin_long, and distance (in KM)
"""
def bounds_km(origin_lat, origin_long, distance) do
{latitude_bounds(origin_lat, distance),
longitude_bounds(origin_lat, origin_long, distance)}
end
@doc """
Computes {{min_lat, max_lat}, {min_long, max_long}} given
origin_lat, origin_long, and distance (in miles)
"""
def bounds_mi(origin_lat, origin_long, distance) do
bounds_km(origin_lat, origin_long, miles_to_km(distance))
end
@doc "Returns the {minimum,maximum} latitude of the bounding box."
def latitude_bounds(origin_lat, distance) do
r = distance/@radius
{r2d(d2r(origin_lat) - r), r2d(d2r(origin_lat) + r)}
end
@doc "Returns the {minimum,maximum} longititude of the bounding box."
def longitude_bounds(origin_lat, origin_long, distance) do
r = distance/@radius
delta = :math.asin(:math.sin(r) / :math.cos(d2r(origin_lat)))
{r2d(d2r(origin_long) - delta), r2d(d2r(origin_long) + delta)}
end
@doc """
Returns distance between two points in KMs.
From and to are 2-tuples {lat, long}.
"""
def km(from, to), do: haversine(from, to)
@doc "Returns distance between two points in KMs."
def km(lat1, long1, lat2, long2), do: km({lat1, long1}, {lat2, long2})
@doc """
Returns distance between two points in miles.
From and to are 2-tuples {lat, long}.
"""
def mi(from, to), do: km(from, to) |> km_to_miles
@doc "Returns distance between two points in miles."
def mi(lat1, long1, lat2, long2), do: mi({lat1, long1}, {lat2, long2})
@doc """
Returns true if distance between from and to is within the specified
radius (measured in KMs).
"""
def in_radius_km?(from, to, radius), do: km(from, to) < radius
@doc "Same as `in_radius_km?/3`."
def in_radius_km?(lat1, long1, lat2, long2, radius) do
in_radius_km?({lat1, long1}, {lat2, long2}, radius)
end
@doc """
Returns true if distance between from and two is within the
specified radius (measured in miles).
"""
def in_radius_mi?(from, to, radius), do: mi(from, to) < radius
@doc "Same as `in_radius_mi?/3`."
def in_radius_mi?(lat1, long1, lat2, long2, radius) do
in_radius_mi?({lat1, long1}, {lat2, long2}, radius)
end
@doc """
Print boundry output in a format suitable for feeing to mapcustomizer.com.
Arguments are origin_lat, origin_long, and the output from `bounds_km/3`
or `bounds_mi/3`.
"""
def mapcustomizer_format(lat, long, {{lat_min, lat_max},
{lon_min, lon_max}}) do
print_coordinates(lat, long, "Origin")
print_coordinates(lat_min, lon_min, "min/min")
print_coordinates(lat_min, lon_max, "min/max")
print_coordinates(lat_max, lon_max, "max/max")
print_coordinates(lat_max, lon_min, "max/min")
end
defp print_coordinates(lat, long, desc) do
IO.puts "#{ lat } #{ long }" <> if desc, do: " {#{desc}}", else: ""
end
@doc "Convert radians to degrees."
def r2d(x), do: x * 180 / :math.pi
@doc "Convert degrees to radians."
def d2r(x), do: x * :math.pi / 180
@doc "Convert KMs to miles."
def km_to_miles(x), do: x * @mk_conversion
@doc "Convert miles to KMs."
def miles_to_km(x), do: x / @mk_conversion
defp haversine({lat_1, long_1}, {lat_2, long_2}) do
v = :math.pi/180
r = @radius
diff_lat = (lat_2 - lat_1) * v
diff_long = (long_2 - long_1) * v
nlat = lat_1 * v
nlong = lat_2 * v
a = (:math.sin(diff_lat/2) * :math.sin(diff_lat/2) +
:math.sin(diff_long/2) * :math.sin(diff_long/2) *
:math.cos(nlat) * :math.cos(nlong))
c = 2 * :math.asin(:math.sqrt(a))
r * c
end
end
|
lib/geo_distance.ex
| 0.954616 | 0.920576 |
geo_distance.ex
|
starcoder
|
defmodule VexValidators.Number do
@moduledoc """
Ensure a value is a number.
## Options
The `options` can be a keyword list with any of the following keys:
* `:is`: A boolean value whether the value must be or not a number.
* `:==`: A number where must be equal to the value.
* `:>`: A number where must be greater than the value.
* `:>=`: A number where must be greater than or equal to the value.
* `:<`: A number where must be less than the value.
* `:<=`: A number where must be less than or equal to the value.
When multiple keys are set in the option than the validator will do a logic "and" between them.
The `options` can also be a boolean instead of the keyword list, which will be the value of the `:is` option.
## Examples
Examples when using the `:is` option:
iex> VexValidators.Number.validate("not_a_number", is: true)
{:error, "must be a number"}
iex> VexValidators.Number.validate(3.14, is: true)
:ok
iex> VexValidators.Number.validate("not_a_number", is: false)
:ok
iex> VexValidators.Number.validate(3.14, is: false)
{:error, "must not be a number"}
Examples when using the boolean value in options for the `:is` option:
iex> VexValidators.Number.validate("not_a_number", true)
{:error, "must be a number"}
iex> VexValidators.Number.validate(3.14, true)
:ok
iex> VexValidators.Number.validate("not_a_number", false)
:ok
iex> VexValidators.Number.validate(3.14, false)
{:error, "must not be a number"}
Examples when using the `:==` option:
iex> VexValidators.Number.validate(3.14, ==: 1.41)
{:error, "must be a number equal to 1.41"}
iex> VexValidators.Number.validate(3.14, ==: 3.14)
:ok
iex> VexValidators.Number.validate(3.14, ==: 6.28)
{:error, "must be a number equal to 6.28"}
Examples when using the `:>` option:
iex> VexValidators.Number.validate(3.14, >: 1.41)
:ok
iex> VexValidators.Number.validate(3.14, >: 3.14)
{:error, "must be a number greater than 3.14"}
iex> VexValidators.Number.validate(3.14, >: 6.28)
{:error, "must be a number greater than 6.28"}
Examples when using the `:>=` option:
iex> VexValidators.Number.validate(3.14, >=: 1.41)
:ok
iex> VexValidators.Number.validate(3.14, >=: 3.14)
:ok
iex> VexValidators.Number.validate(3.14, >=: 6.28)
{:error, "must be a number greater or equal than 6.28"}
Examples when using the `:<` option:
iex> VexValidators.Number.validate(3.14, <: 1.41)
{:error, "must be a number less than 1.41"}
iex> VexValidators.Number.validate(3.14, <: 3.14)
{:error, "must be a number less than 3.14"}
iex> VexValidators.Number.validate(3.14, <: 6.28)
:ok
Examples when using the `:<=` option:
iex> VexValidators.Number.validate(3.14, <=: 1.41)
{:error, "must be a number less or equal than 1.41"}
iex> VexValidators.Number.validate(3.14, <=: 3.14)
:ok
iex> VexValidators.Number.validate(3.14, <=: 6.28)
:ok
Examples when using the combinations of the above options:
iex> VexValidators.Number.validate("not_a_number", is: true, >: 0, <=: 3.14)
{:error, "must be a number"}
iex> VexValidators.Number.validate(0, is: true, >: 0, <=: 3.14)
{:error, "must be a number greater than 0"}
iex> VexValidators.Number.validate(1.41, is: true, >: 0, <=: 3.14)
:ok
iex> VexValidators.Number.validate(3.14, is: true, >: 0, <=: 3.14)
:ok
iex> VexValidators.Number.validate(6.28, is: true, >: 0, <=: 3.14)
{:error, "must be a number less or equal than 3.14"}
## Custom Error Messages
Custom error messages (in EEx format), provided as :message, can use the following values:
iex> VexValidators.Number.__validator__(:message_fields)
[
value: "Bad value",
is: "Is number",
==: "Equal to",
>: "Greater than",
>=: "Greater or equal than",
<: "Less than",
<=: "Less or equal than"
]
For examples please see the [Vex documentation](https://github.com/CargoSense/vex#custom-eex-error-renderer-messages).
"""
use Vex.Validator
@option_keys [:is, :==, :>, :>=, :<, :<=]
@message_fields [
value: "Bad value",
is: "Is number",
==: "Equal to",
>: "Greater than",
>=: "Greater or equal than",
<: "Less than",
<=: "Less or equal than"
]
@doc false
def validate(value, options) when is_boolean(options), do: validate(value, is: options)
def validate(value, options) when is_list(options) do
unless_skipping value, options do
Enum.reduce_while(options, :ok, fn
{k, o}, _ when k in @option_keys ->
case do_validate(value, k, o) do
:ok ->
{:cont, :ok}
{:error, reason} ->
fields =
options
|> Keyword.take(@option_keys)
|> Keyword.put(:value, value)
error = {:error, message(options, reason, fields)}
{:halt, error}
end
_, _ ->
{:cont, :ok}
end)
end
end
defp do_validate(_, :is, nil), do: :ok
defp do_validate(v, :is, o) when is_number(v) === o, do: :ok
defp do_validate(_, :is, true), do: {:error, "must be a number"}
defp do_validate(_, :is, false), do: {:error, "must not be a number"}
defp do_validate(_, :==, nil), do: :ok
defp do_validate(v, :==, o) when is_number(v) and v == o, do: :ok
defp do_validate(_, :==, o), do: {:error, "must be a number equal to #{o}"}
defp do_validate(_, :>, nil), do: :ok
defp do_validate(v, :>, o) when is_number(v) and v > o, do: :ok
defp do_validate(_, :>, o), do: {:error, "must be a number greater than #{o}"}
defp do_validate(_, :>=, nil), do: :ok
defp do_validate(v, :>=, o) when is_number(v) and v >= o, do: :ok
defp do_validate(_, :>=, o), do: {:error, "must be a number greater or equal than #{o}"}
defp do_validate(_, :<, nil), do: :ok
defp do_validate(v, :<, o) when is_number(v) and v < o, do: :ok
defp do_validate(_, :<, o), do: {:error, "must be a number less than #{o}"}
defp do_validate(_, :<=, nil), do: :ok
defp do_validate(v, :<=, o) when is_number(v) and v <= o, do: :ok
defp do_validate(_, :<=, o), do: {:error, "must be a number less or equal than #{o}"}
end
|
lib/vex_validators/number.ex
| 0.911972 | 0.714728 |
number.ex
|
starcoder
|
defmodule Arfficionado do
@moduledoc """
Reader for [ARFF (Attribute Relation File Format)](https://waikato.github.io/weka-wiki/arff/) data.
Adaptable to application-specific needs through custom handler behaviour implementations.
```
{:ok, instances} =
File.stream!("data.arff")
|> Arfficionado.read(Arfficionado.ListHandler)
```
Current limitations:
- ISO-8601 is the only supported `date` format, but you can pass a custom date parsing function to read other formats
- no support for attributes of type `relational` (not widely used)
- no support for sparse format
"""
@doc ~s"""
Parses an enumerable/stream of ARFF lines, invokes `Arfficionado.Handler` callbacks and returns final handler state.
Initializes handler state by invoking `init(arg)` and then modifies the state through invocations of the other `handler` callbacks.
Returns `{:ok, final_handler_state}` or `{:error, reason, final_handler_state}`.
A custom date parsing function can be given via `parse_date`. This function is expected to take two strings: a `date` and a `date_format` and to return either a `DateTime` or `{:error, reason}`. The default `parse_date` function will return `{:error, "Please pass in a function for parsing non-iso_8601 dates."}`.
## Examples
Using `Arfficionado.ListHandler` to collect the instances (with weights) from the following ARFF input:
```
@relation example
@attribute a1 numeric
@attribute a2 string
@attribute a3 {red, blue}
@data
1, Hello, red
2, "Hi there!", blue
?, ?, ? % missing values
3.1415, 'What\\'s up?', red % escaped '
4, abc, blue, {7} % instance weight 7
```
iex> [
...> ~s[@relation example],
...> ~s[@attribute a1 numeric],
...> ~s[@attribute a2 string],
...> ~s[@attribute a3 {red, blue}],
...> ~s[@data],
...> ~s[1, Hello, red],
...> ~s[2, "Hi there!", blue],
...> ~s[?, ?, ? % missing values],
...> ~s[3.1415, 'What\\\\'s up?', red % escaped '],
...> ~s[4, abc, blue, {7} % instance weight 7]
...> ] |>
...> Arfficionado.read(Arfficionado.ListHandler)
{:ok, [
{[1, "Hello", :red], 1},
{[2, "Hi there!", :blue], 1},
{[:missing, :missing, :missing], 1},
{[3.1415, "What's up?", :red], 1},
{[4, "abc", :blue], 7}
]}
"""
@spec read(Enumerable.t(), Arfficionado.Handler.t(), any()) ::
{:ok, Arfficionado.Handler.state()} | {:error, String.t(), Arfficionado.Handler.state()}
def read(arff, handler, arg \\ nil, parse_date \\ &custom_date_parse/2) do
initial_handler_state = handler.init(arg)
case Enum.reduce_while(
arff,
{handler, initial_handler_state, :"@relation", [], parse_date, 1},
&process_line/2
) do
{_, {:error, reason, handler_state}, _, _, _, line_number} ->
final_state = handler.close(:error, handler_state)
{:error, ~s"Line #{line_number}: #{reason}", final_state}
{_, handler_state, stage, _, _, line_number} when stage != :instance ->
final_state = handler.close(:error, handler_state)
{:error, ~s"Line #{line_number}: Expected #{Atom.to_string(stage)}.", final_state}
{_, handler_state, _, _, _, _} ->
final_state = handler.close(:ok, handler_state)
{:ok, final_state}
end
end
defp process_line(line, {handler, handler_state, stage, attributes, date_parse, line_number}) do
parsed =
line
|> tokenize()
|> parse()
{cont_or_halt, updated_handler_state, updated_stage, updated_attributes, updated_line_number} =
case parsed do
:empty_line ->
{:cont, handler_state, stage, attributes, line_number + 1}
{:comment, comment} ->
if function_exported?(handler, :line_comment, 2) do
{coh, uhs} = handler.line_comment(comment, handler_state)
{coh, uhs, stage, attributes, line_number + 1}
else
{:cont, handler_state, stage, attributes, line_number + 1}
end
{:relation, name, comment} when stage == :"@relation" ->
if function_exported?(handler, :relation, 3) do
{coh, uhs} = handler.relation(name, comment, handler_state)
{coh, uhs, :"@attribute", attributes, line_number + 1}
else
{:cont, handler_state, :"@attribute", attributes, line_number + 1}
end
{:attribute, name, :relational, _comment} = attribute
when stage == :"@attribute" or stage == :"@attribute or @data" ->
halt_with_error(
"Attribute type relational is not currently supported.",
handler,
handler_state,
{:halt, attributes, line_number}
)
# rough outline for handling relational attributes:
# set stage=:"@attribute or @end"
# accumulate sub attributes until @end is encountered
# parsing/casting will need to be adapted, too
{:attribute, name, _type, _comment} = attribute
when stage == :"@attribute" or stage == :"@attribute or @data" ->
# TODO: make this check more clear and efficient; sort out that internal state... header_finished is not needed anymore; maybe use a map
if Enum.find(attributes, false, fn {:attribute, an, _, _} -> an == name end) do
halt_with_error(
"Duplicate attribute name #{name}.",
handler,
handler_state,
{:halt, attributes, line_number}
)
else
{:cont, handler_state, :"@attribute or @data", [attribute | attributes],
line_number + 1}
end
{:data, comment} when length(attributes) > 0 and stage == :"@attribute or @data" ->
finished_attributes = Enum.reverse(attributes)
{cont_or_halt, updated_handler_state} =
handler.attributes(finished_attributes, handler_state)
case cont_or_halt do
:halt ->
{:halt, updated_handler_state, :halt, finished_attributes, line_number + 1}
:cont ->
if function_exported?(handler, :begin_data, 2) do
{coh, uhs} = handler.begin_data(comment, updated_handler_state)
{coh, uhs, :instance, finished_attributes, line_number + 1}
else
{:cont, updated_handler_state, :instance, finished_attributes, line_number + 1}
end
end
{:raw_instance, _, _, _} = ri when stage == :instance ->
case cast(ri, attributes, date_parse) do
{:error, reason} ->
halt_with_error(reason, handler, handler_state, {:halt, attributes, line_number})
{:instance, values, weight, comment} ->
{coh, uhs} = handler.instance(values, weight, comment, handler_state)
{coh, uhs, :instance, attributes, line_number + 1}
end
{:error, reason} ->
halt_with_error(reason, handler, handler_state, {:halt, attributes, line_number})
_ ->
halt_with_error(
~s"Expected #{Atom.to_string(stage)}.",
handler,
handler_state,
{:halt, attributes, line_number}
)
end
{cont_or_halt,
{handler, updated_handler_state, updated_stage, updated_attributes, date_parse,
updated_line_number}}
end
# TODO: flatten internal state argument...
defp halt_with_error(reason, _handler, handler_state, {stage, attributes, line_number}) do
{:halt, {:error, reason, handler_state}, stage, attributes, line_number}
end
@doc false
def cast({:raw_instance, raw_values, weight, comment}, attributes, date_parse) do
case cv(raw_values, attributes, [], date_parse) do
{:error, _reason} = err -> err
cast_values -> {:instance, cast_values, weight, comment}
end
end
defp cv([], [], acc, _), do: Enum.reverse(acc)
defp cv([v | vs], [a | as], acc, date_parse) do
case c(v, a, date_parse) do
{:error, _reason} = err ->
err
cast_value ->
cv(vs, as, [cast_value | acc], date_parse)
end
end
defp cv([_v | _vs], [], _, _), do: {:error, "More values than attributes."}
defp cv([], [_a | _as], _, _), do: {:error, "Fewer values than attributes."}
defp c({:unclosed_quote, quoted}, {:attribute, name, _, _}, _),
do: {:error, ~s"#{quoted} is missing closing quote for attribute #{name}."}
defp c(:missing, _, _), do: :missing
defp c("." <> v, {:attribute, _, :numeric, _} = att, date_parse),
do: c("0." <> v, att, date_parse)
defp c("-." <> v, {:attribute, _, :numeric, _} = att, date_parse),
do: c("-0." <> v, att, date_parse)
defp c(v, {:attribute, name, :numeric, _}, _) do
case Integer.parse(v) do
{i, ""} ->
i
_ ->
case Float.parse(v) do
{f, ""} ->
f
{_f, remainder} ->
{:error,
~s"Nonempty remainder #{remainder} when parsing #{v} as integer/real for attribute #{
name
}."}
:error ->
{:error, ~s"Cannot cast #{v} to integer/real for attribute #{name}."}
end
end
end
# could use a set here instead of a list....
defp c(v, {:attribute, name, {:nominal, enum}, _}, _) do
if v in enum do
String.to_atom(v)
else
{:error, ~s"Unexpected nominal value #{v} for attribute #{name}."}
end
end
defp c(v, {:attribute, _, :string, _}, _), do: v
defp c(v, {:attribute, name, {:date, :iso_8601}, _}, _) do
case DateTime.from_iso8601(v) do
{:ok, dt, _} ->
dt
{:error, :invalid_format} ->
{:error, ~s"Cannot parse #{v} as ISO-8601 date for attribute #{name}."}
end
end
defp c(v, {:attribute, name, {:date, custom_format}, _}, date_parse) do
case date_parse.(v, custom_format) do
{:error, reason} ->
{:error, ~s"Attribute #{name} / #{custom_format}: #{reason}"}
date ->
date
end
end
@doc false
def custom_date_parse(d, format) do
{:error, "Please pass in a function for parsing non-iso_8601 dates."}
end
@doc false
def parse([:line_break]), do: :empty_line
def parse([:open_curly | _rest]), do: {:error, "Sparse format is not currently supported."}
def parse([{:comment, _comment} = comment]), do: comment
def parse([{:string, <<c::utf8, _::binary>> = s} | rest]) when c == ?@ do
case String.downcase(s) do
"@relation" ->
parse_relation(rest)
"@attribute" ->
parse_attribute(rest)
"@end" ->
parse_end(rest)
"@data" ->
# TODO: this is going to be repeated x times! Is there some nicer, less repetitive way of expressing this?
case parse_optional_comment(rest) do
{:error, _reason} = err -> err
comment -> {:data, comment}
end
end
end
def parse(instance), do: parse_raw_instance(instance)
defp parse_relation([{:unclosed_quote, _quoted}]),
do: {:error, "Unclosed quote in @relation."}
defp parse_relation([{:string, name} | rest]) do
case parse_optional_comment(rest) do
{:error, _reason} = err ->
err
comment ->
{:relation, name, comment}
end
end
defp parse_attribute([{:unclosed_quote, _quoted}]),
do: {:error, "Unclosed quote in @attribute."}
defp parse_attribute([{:string, name}, {:string, type} | rest]) do
case String.downcase(type) do
n when n in ["integer", "real", "numeric"] ->
# TODO: try to get rid of the repeated case {:error, reason} blocks
case parse_optional_comment(rest) do
{:error, _reason} = err -> err
comment -> {:attribute, name, :numeric, comment}
end
"string" ->
case parse_optional_comment(rest) do
{:error, _reason} = err -> err
comment -> {:attribute, name, :string, comment}
end
"date" ->
parse_date(rest, name)
"relational" ->
case parse_optional_comment(rest) do
{:error, _reason} = err -> err
comment -> {:attribute, name, :relational, comment}
end
# this needs to be reflected in the main loop's state, i.e. accumulated sub-attributes & await 'end'
end
end
defp parse_attribute([{:string, name}, :open_curly | rest]) do
case pn(rest, []) do
{:error, _reason} = err -> err
{enum, comment} -> {:attribute, name, {:nominal, enum}, comment}
end
end
defp parse_attribute([{:string, _name} = n, :tab | rest]), do: parse_attribute([n | rest])
defp pn([:close_curly | rest], acc) do
case parse_optional_comment(rest) do
{:error, _reason} = err -> err
comment -> {Enum.reverse(acc), comment}
end
end
defp pn([{:string, const}, :comma | rest], acc), do: pn(rest, [const | acc])
defp pn([{:string, const}, :close_curly | rest], acc) do
case parse_optional_comment(rest) do
{:error, _reason} = err -> err
comment -> {Enum.reverse([const | acc]), comment}
end
end
defp parse_date([{:string, format} | rest], name) do
# TODO: find way to reduce this duplication
case parse_optional_comment(rest) do
{:error, _reason} = err ->
err
comment ->
{:attribute, name, {:date, format}, comment}
end
end
defp parse_date(rest, name) do
# TODO: find way to reduce this duplication
case parse_optional_comment(rest) do
{:error, _reason} = err -> err
comment -> {:attribute, name, {:date, :iso_8601}, comment}
end
end
defp parse_end([{:string, name} | rest]) do
case parse_optional_comment(rest) do
{:error, _reason} = err -> err
comment -> {:end, name, comment}
end
end
defp parse_optional_comment([:tab | rest]), do: parse_optional_comment(rest)
defp parse_optional_comment([:line_break]), do: nil
defp parse_optional_comment([{:comment, comment}]), do: comment
defp parse_optional_comment(unexpected), do: {:error, ~s"Unexpected: #{inspect(unexpected)}"}
defp parse_raw_instance(rest), do: pri(rest, [])
defp pri([val, sep, :open_curly, {:string, weight}, :close_curly | rest], acc)
when sep == :tab or sep == :comma do
case parse_optional_comment(rest) do
{:error, _reason} = err ->
err
comment ->
{:raw_instance, Enum.reverse([value(val) | acc]), Integer.parse(weight) |> elem(0),
comment}
end
end
defp pri([:comma | rest], acc),
do: pri(rest, [:missing | acc])
defp pri([val, sep | rest], acc) when sep == :tab or sep == :comma,
do: pri(rest, [value(val) | acc])
defp pri([{:comment, _} | _rest] = cr, acc) do
case parse_optional_comment(cr) do
{:error, _reason} = err -> err
comment -> {:raw_instance, Enum.reverse(acc), 1, comment}
end
end
defp pri([:tab | rest], acc),
do: pri(rest, acc)
defp pri([{:unclosed_quote, _quoted} = uq], acc),
do: {:raw_instance, Enum.reverse([uq | acc]), 1, nil}
defp pri([val | rest], acc) do
case parse_optional_comment(rest) do
{:error, _reason} = err -> err
comment -> {:raw_instance, Enum.reverse([value(val) | acc]), 1, comment}
end
end
defp value({:string, v}), do: v
defp value(:missing), do: :missing
@doc false
def tokenize(line) do
line
|> t([])
|> Enum.reverse()
end
defp t(<<>>, acc), do: [:line_break | acc]
defp t(<<c::utf8, _rest::binary>> = comment, acc) when c == ?%, do: [{:comment, comment} | acc]
defp t(<<c::utf8, rest::binary>>, acc) when c == 32, do: t(rest, acc)
defp t(<<c::utf8>>, acc) when c == ?\n, do: [:line_break | acc]
defp t(<<c::utf8, rest::binary>>, acc) when c == ?\t, do: t(rest, [:tab | acc])
defp t(<<c::utf8, rest::binary>>, acc) when c == ?,, do: t(rest, [:comma | acc])
defp t(<<c::utf8, rest::binary>>, acc) when c == ?{, do: t(rest, [:open_curly | acc])
defp t(<<c::utf8, rest::binary>>, acc) when c == ?}, do: t(rest, [:close_curly | acc])
defp t(<<c::utf8, rest::binary>>, acc) when c == ??, do: t(rest, [:missing | acc])
defp t(<<c::utf8, rest::binary>> = quoted, acc) when c == ?' or c == ?" do
case q(rest, c, <<>>) do
:unclosed_quote ->
[{:unclosed_quote, quoted} | acc]
{string, remainder} ->
t(remainder, [{:string, string} | acc])
end
end
defp t(bin, acc) do
case :binary.match(bin, [" ", "\t", ",", "\r", "\n", "}"]) do
{pos, _length} ->
{string, rest} = String.split_at(bin, pos)
t(rest, [{:string, string} | acc])
:nomatch ->
[:line_break, {:string, bin} | acc]
end
end
defp q(<<bs::utf8, q::utf8, rest::binary>>, qc, acc) when bs == 92 and q == qc,
do: q(rest, qc, <<acc::binary, q>>)
defp q(<<q::utf8, rest::binary>>, qc, acc) when q == qc, do: {acc, rest}
defp q(<<c::utf8, rest::binary>>, qc, acc), do: q(rest, qc, <<acc::binary, c>>)
defp q(<<>>, _, _), do: :unclosed_quote
end
|
lib/arfficionado.ex
| 0.838812 | 0.827793 |
arfficionado.ex
|
starcoder
|
defmodule Maze.Server do
@moduledoc """
Provides an API to create one or more mazes.
"""
require Logger
use GenServer
alias Maze.{Path}
defstruct mazes: []
def canvas_options(maze, paint_mode \\ :solve, paint_interval \\ 100) do
[
title: 'Elixir Maze #{maze.rows} x #{maze.columns}',
width: maze.columns * Maze.Painter.room_size * Maze.Painter.scale,
height: maze.rows * Maze.Painter.room_size *Maze. Painter.scale,
paint_interval: paint_interval,
painter_module: Maze.Painter,
painter_state: %{maze: maze, paint_mode: paint_mode},
brushes: %{
black: {0, 0, 0, 255},
red: {150, 0, 0, 255},
green: {0, 150, 0, 255},
blue: {0, 0, 150, 255},
cyan: {0, 251, 255, 255},
yellow: {255, 255, 0, 255},
grey: {146, 166, 173, 255}
}
]
end
## Client API
@doc """
Starts the maze server.The Supervisor calls this functions
when the application starts.
"""
def start_link(args \\ %__MODULE__{}) do
GenServer.start_link(__MODULE__, args, timeout: :infinity, name: __MODULE__)
end
@default_create_args {:init,
rows = 20,
columns = 20,
name = nil,
goal_position = [20, 20],
start_position = [1, 1],
paint_mode = :solve,
paint_interval = 100
}
@doc """
Creates a maze. You can skip the arguments in which
case @default_create_args will be passed.`paint_mode`
will solve the maze but only paint the building of the maze,
not the solved path.Solved path is painted with `paint_mode`
set to `:solve`.`paint_interval` is the time interval in
milliseconds for the GUI frame rate.
Returns %Maze{} struct.
## Examples
iex> Maze.Server.create_maze
iex> Maze.Server.create_maze({:init,
rows = 30,
columns = 20,
name = nil,
goal_position = [15, 10],
start_position = [1, 1],
paint_mode = :build,
paint_interval = 100
})
"""
def create_maze(args \\ @default_create_args) do
GenServer.call(__MODULE__, args, :infinity)
end
@doc """
Concurrently creates and solves a number of mazes,then paints their path.
## Examples
iex> Maze.Server.create_mazes 10
iex> Maze.Server.create_mazes(10, {:init,
rows = 30,
columns = 20,
name = nil,
goal_position = [15, 10],
start_position = [1, 1],
paint_mode = :build,
paint_interval = 100
})
Returns `:ok` if mazes were creates successfully.
"""
def create_mazes(n, args \\ @default_create_args)
def create_mazes( n, args ) when (is_integer(n) and n > 0) do
Enum.each((1..n), fn i ->
Task.start_link(fn ->
create_maze args
end)
end)
end
def create_mazes(_, _) do
{:error, "You must create at least one maze."}
end
## Server Callbacks
def init(maze_server_state) do
{:ok, maze_server_state}
end
def handle_call(
{
:init,
rows,
columns,
name ,
goal_position,
start_position,
paint_mode,
paint_interval
},
_from,
maze_server_state
) do
maze =
Maze.initialize( rows, columns, name )
|> Maze.set_goal_and_start( goal_position, start_position )
|> Maze.build
|> Maze.reset_rooms_visits_from
|> Maze.reset_visited_positions( start_position )
|> Maze.solve
|> Maze.set_build_and_solve_path_state
if Mix.env != :test do
Canvas.GUI.start_link(canvas_options(maze, paint_mode, paint_interval))
end
new_maze_server_state = %{ maze_server_state | mazes:
[maze | maze_server_state.mazes] }
{:reply, maze, new_maze_server_state}
end
end
|
lib/maze/server.ex
| 0.778439 | 0.461259 |
server.ex
|
starcoder
|
defmodule Stops.Nearby do
@moduledoc "Functions for retrieving and organizing stops relative to a location."
import Util.Distance
alias Routes.Route
alias Stops.Stop
alias Util.{Distance, Position}
@default_timeout 10_000
@mile_in_degrees 0.02
@total 12
@type route_with_direction :: %{direction_id: 0 | 1 | nil, route: Route.t()}
defmodule Options do
@moduledoc "Defines shared options and defaults for this module's functions."
defstruct api_fn: &Stops.Nearby.api_around/2,
keys_fn: &Stops.Nearby.keys/1,
fetch_fn: &Stops.Repo.get_parent/1,
routes_fn: &Routes.Repo.by_stop_and_direction/2,
limit: nil
end
@doc """
Returns a list of %Stops.Stop{} around the given latitude/longitude.
The algorithm should return 12 or fewer results:
* Return 4 nearest CR or Subway stops
** for CR use 50 mile radius
** for subway - 30 mile radius
** return at least 1 CR stop and 1 Subway stop
* Return all Bus stops with 1 mi radius
** limit to 2 stops per line-direction
* Return Subway stops in 5 mi radius
"""
@spec nearby_with_varying_radius_by_mode(Position.t()) :: [Stop.t()]
def nearby_with_varying_radius_by_mode(position, opts \\ []) do
opts =
%Options{}
|> Map.merge(Map.new(opts))
commuter_rail_stops = api_task(position, opts, radius: @mile_in_degrees * 50, route_type: 2)
subway_stops = api_task(position, opts, radius: @mile_in_degrees * 10, route_type: "0,1")
bus_stops = api_task(position, opts, radius: @mile_in_degrees, route_type: 3)
position
|> gather_stops(
Task.await(commuter_rail_stops),
subway_stops |> Task.await() |> sort(position) |> no_more_than(1, opts.keys_fn),
bus_stops |> Task.await() |> sort(position) |> no_more_than(2, opts.keys_fn)
)
|> Task.async_stream(&opts.fetch_fn.(&1.id))
|> Enum.map(fn {:ok, result} -> result end)
end
@spec nearby_with_routes(Position.t(), float, keyword) :: [
%{stop: Stop.t(), routes_with_direction: [route_with_direction]}
]
def nearby_with_routes(position, radius, opts \\ []) do
opts =
%Options{}
|> Map.merge(Map.new(opts))
stops =
position
|> opts.api_fn.(radius: radius)
|> Task.async_stream(&opts.fetch_fn.(&1.id))
|> Enum.map(fn {:ok, result} -> result end)
stops
|> Enum.map(fn stop ->
%{
stop: stop,
distance:
Distance.haversine(position, %{longitude: stop.longitude, latitude: stop.latitude})
}
end)
|> Enum.reject(&(&1.distance == 0))
|> Enum.take(opts.limit || length(stops))
|> Task.async_stream(fn %{stop: stop, distance: distance} ->
case merge_routes(stop.id, opts.routes_fn) do
{:ok, routes_with_direction} ->
%{
stop: stop,
distance: distance,
routes_with_direction: routes_with_direction
}
{:error, :timeout} ->
%{
stop: stop,
distance: distance,
routes_with_direction: []
}
end
end)
|> Enum.map(fn {:ok, result} -> result end)
end
def routes_for_stop_direction(routes_fn, stop_id, direction_id) do
stop_id
|> routes_fn.(direction_id)
|> do_routes_for_stop_direction(direction_id)
end
def do_routes_for_stop_direction(routes, direction_id) when is_list(routes) do
Enum.map(routes, &%{direction_id: direction_id, route: &1})
end
def do_routes_for_stop_direction(_, _), do: :error
@spec merge_routes(String.t(), fun()) :: {:ok | :error, [route_with_direction] | :timeout}
def merge_routes(stop_id, routes_fn) do
# Find the routes for a stop in both directions.
# Merge the routes such that if a route exists for a stop in both
# directions, set the direction_id to nil
direction_0_task = Task.async(__MODULE__, :routes_for_stop_direction, [routes_fn, stop_id, 0])
direction_1_task = Task.async(__MODULE__, :routes_for_stop_direction, [routes_fn, stop_id, 1])
result =
Util.yield_or_default_many(
%{
direction_0_task => {:direction_0_routes, {:error, :timeout}},
direction_1_task => {:direction_1_routes, {:error, :timeout}}
},
__MODULE__,
@default_timeout
)
case result do
%{direction_0_routes: direction_0_routes, direction_1_routes: direction_1_routes}
when is_list(direction_0_routes) and is_list(direction_1_routes) ->
routes =
[direction_0_routes | direction_1_routes]
|> List.flatten()
|> Enum.reduce(%{}, fn %{route: route} = route_with_direction, merged_routes ->
# credo:disable-for-lines:4 Credo.Check.Refactor.Nesting
direction_id =
if Map.has_key?(merged_routes, route.id),
do: nil,
else: route_with_direction.direction_id
Map.put(merged_routes, route.id, %{route_with_direction | direction_id: direction_id})
end)
|> Map.values()
{:ok, routes}
_ ->
{:error, :timeout}
end
end
def api_task(position, %{api_fn: api_fn}, opts) do
Task.async(Kernel, :apply, [api_fn, [position, opts]])
end
@spec api_around(Position.t(), keyword) :: [
%{id: String.t(), latitude: float, longitude: float}
]
def api_around(position, opts) do
opts =
opts
|> Keyword.merge(
latitude: Position.latitude(position),
longitude: Position.longitude(position),
include: "parent_station"
)
|> Keyword.put(:"fields[stop]", "latitude,longitude")
|> Keyword.put(:"fields[parent_station]", "latitude,longitude")
|> Keyword.put(:sort, "distance")
opts
|> V3Api.Stops.all()
|> Map.get(:data)
|> Enum.map(&item_to_position/1)
|> Enum.uniq()
end
defp item_to_position(%JsonApi.Item{relationships: %{"parent_station" => [station]}}) do
item_to_position(station)
end
defp item_to_position(%JsonApi.Item{
id: id,
attributes: %{"latitude" => latitude, "longitude" => longitude}
}) do
%{
id: id,
latitude: latitude,
longitude: longitude
}
end
def keys(%{id: id}) do
0..1
|> Enum.flat_map(fn direction_id ->
id
|> Routes.Repo.by_stop(direction_id: direction_id)
|> Enum.map(&{&1.id, direction_id})
end)
end
@doc """
Given a list of commuter rail, subway, and bus stops, organize them
according to the algorithm.
"""
@spec gather_stops(Position.t(), [Position.t()], [Position.t()], [Position.t()]) :: [
Position.t()
]
def gather_stops(_, [], [], []) do
[]
end
def gather_stops(position, commuter_rail, subway, bus) do
main_stops = gather_main_stops(position, commuter_rail, subway)
bus = gather_non_duplicates(position, bus, main_stops)
subway = gather_non_duplicates(position, subway, bus ++ main_stops)
[main_stops, bus, subway]
|> Enum.concat()
|> sort(position)
end
defp gather_main_stops(position, commuter_rail, subway) do
{first_cr, sorted_commuter_rail} = closest_and_rest(commuter_rail, position)
{first_subway, sorted_subway} = closest_and_rest(subway, position)
initial = (first_cr ++ first_subway) |> Enum.uniq()
rest = (sorted_commuter_rail ++ sorted_subway) |> Enum.uniq()
next_four =
position
|> gather_non_duplicates(rest, initial)
|> Enum.take(4 - length(initial))
initial ++ next_four
end
defp gather_non_duplicates(position, items, existing) do
items
|> Enum.reject(&(&1 in existing))
|> closest(position, @total - length(existing))
end
# Returns the closest item (in a list) as well as the rest of the list. In
# the case of an empty initial list, returns a tuple of two empty lists.
# The first list represents a kind of Maybe: [item] :: Just item and [] :: Nothing
@spec closest_and_rest([Position.t()], Position.t()) :: {[Position.t()], [Position.t()]}
defp closest_and_rest([], _) do
{[], []}
end
defp closest_and_rest(items, position) do
[first | rest] = sort(items, position)
{[first], rest}
end
@doc """
Filters an enumerable such that the keys (returned by `keys_fn`) do not
appear more than `max_count` times.
iex> Stops.Nearby.no_more_than([1, 2, 3, 4, 5], 2, fn i -> [rem(i, 2)] end)
[1, 2, 3, 4]
iex> Stops.Nearby.no_more_than([1, 2, 3, 4, 5], 2, fn i -> [rem(i, 2), div(i, 2)] end)
[1, 2, 4, 5]
iex> Stops.Nearby.no_more_than([1, 2, 3, 4, 5], 1, fn i -> [rem(i, 2)] end)
[1, 2]
"""
@spec no_more_than(Enum.t(), pos_integer, (any -> [any])) :: Enum.t()
def no_more_than(enum, max_count, keys_fn) do
{items, _} =
enum
|> Task.async_stream(fn item -> {item, keys_fn.(item)} end)
|> Enum.reduce({[], %{}}, fn {:ok, {item, keys}}, {existing, all_keys} ->
still_valid_keys = Enum.reject(keys, &(Map.get(all_keys, &1) == max_count))
if still_valid_keys == [] do
{existing, all_keys}
else
updated_keys =
still_valid_keys
|> Enum.reduce(all_keys, fn key, keys ->
Map.update(keys, key, 1, &(&1 + 1))
end)
{[item | existing], updated_keys}
end
end)
Enum.reverse(items)
end
end
|
apps/stops/lib/nearby.ex
| 0.866641 | 0.400163 |
nearby.ex
|
starcoder
|
defmodule Kino.DataTable do
@moduledoc """
A widget for interactively viewing enumerable data.
The data must be an enumerable of records, where each
record is either map, struct, keyword list or tuple.
## Examples
data = [
%{id: 1, name: "Elixir", website: "https://elixir-lang.org"},
%{id: 2, name: "Erlang", website: "https://www.erlang.org"}
]
Kino.DataTable.new(data)
The tabular view allows you to quickly preview the data
and analyze it thanks to sorting capabilities.
data = Process.list() |> Enum.map(&Process.info/1)
Kino.DataTable.new(
data,
keys: [:registered_name, :initial_call, :reductions, :stack_size]
)
"""
@doc false
use GenServer, restart: :temporary
alias Kino.Utils.Table
defstruct [:pid]
@type t :: %__MODULE__{pid: pid()}
@typedoc false
@type state :: %{
parent_monitor_ref: reference(),
data: Enum.t(),
total_rows: non_neg_integer()
}
@doc """
Starts a widget process with enumerable tabular data.
## Options
* `:keys` - a list of keys to include in the table for each record.
The order is reflected in the rendered table. For tuples use 0-based
indices. Optional.
* `:sorting_enabled` - whether the widget should support sorting the data.
Sorting requires traversal of the whole enumerable, so it may not be
desirable for lazy enumerables. Defaults to `true` if data is a list
and `false` otherwise.
* `:show_underscored` - whether to include record keys starting with underscore.
This option is ignored if `:keys` is also given. Defaults to `false`.
"""
@spec new(Enum.t(), keyword()) :: t()
def new(data, opts \\ []) do
validate_data!(data)
parent = self()
keys = opts[:keys]
sorting_enabled = Keyword.get(opts, :sorting_enabled, is_list(data))
show_underscored = Keyword.get(opts, :show_underscored, false)
opts = [
data: data,
parent: parent,
keys: keys,
sorting_enabled: sorting_enabled,
show_underscored: show_underscored
]
{:ok, pid} = DynamicSupervisor.start_child(Kino.WidgetSupervisor, {__MODULE__, opts})
%__MODULE__{pid: pid}
end
# TODO: remove in v0.3.0
@deprecated "Use Kino.DataTable.new/2 instead"
def start(data, opts \\ []), do: new(data, opts)
# Validate data only if we have a whole list upfront
defp validate_data!(data) when is_list(data) do
Enum.reduce(data, nil, fn record, type ->
case record_type(record) do
:other ->
raise ArgumentError,
"expected record to be either map, struct, tuple or keyword list, got: #{inspect(record)}"
first_type when type == nil ->
first_type
^type ->
type
other_type ->
raise ArgumentError,
"expected records to have the same data type, found #{type} and #{other_type}"
end
end)
end
defp validate_data!(_data), do: :ok
defp record_type(record) do
cond do
is_struct(record) -> :struct
is_map(record) -> :map
is_tuple(record) -> :tuple
Keyword.keyword?(record) -> :keyword_list
true -> :other
end
end
@doc false
def start_link(opts) do
GenServer.start_link(__MODULE__, opts)
end
@impl true
def init(opts) do
data = Keyword.fetch!(opts, :data)
parent = Keyword.fetch!(opts, :parent)
keys = Keyword.fetch!(opts, :keys)
sorting_enabled = Keyword.fetch!(opts, :sorting_enabled)
show_underscored = Keyword.fetch!(opts, :show_underscored)
parent_monitor_ref = Process.monitor(parent)
total_rows = Enum.count(data)
{:ok,
%{
parent_monitor_ref: parent_monitor_ref,
data: data,
total_rows: total_rows,
keys: keys,
sorting_enabled: sorting_enabled,
show_underscored: show_underscored
}}
end
@impl true
def handle_info({:connect, pid}, state) do
columns =
if state.keys do
Table.keys_to_columns(state.keys)
else
[]
end
features = Kino.Utils.truthy_keys(pagination: true, sorting: state.sorting_enabled)
send(pid, {:connect_reply, %{name: "Data", columns: columns, features: features}})
{:noreply, state}
end
def handle_info({:get_rows, pid, rows_spec}, state) do
records = get_records(state.data, rows_spec)
{columns, keys} =
if state.keys do
{:initial, state.keys}
else
columns = Table.columns_for_records(records)
columns =
if state.show_underscored,
do: columns,
else: Enum.reject(columns, &underscored?(&1.key))
keys = Enum.map(columns, & &1.key)
{columns, keys}
end
rows = Enum.map(records, &Table.record_to_row(&1, keys))
send(pid, {:rows, %{rows: rows, total_rows: state.total_rows, columns: columns}})
{:noreply, state}
end
def handle_info({:DOWN, ref, :process, _object, _reason}, %{parent_monitor_ref: ref} = state) do
{:stop, :shutdown, state}
end
defp get_records(data, rows_spec) do
sorted_data =
if order_by = rows_spec[:order_by] do
Enum.sort_by(data, &Table.get_field(&1, order_by), rows_spec.order)
else
data
end
Enum.slice(sorted_data, rows_spec.offset, rows_spec.limit)
end
defp underscored?(key) when is_atom(key) do
key |> Atom.to_string() |> String.starts_with?("_")
end
defp underscored?(_key), do: false
end
|
lib/kino/data_table.ex
| 0.768168 | 0.625266 |
data_table.ex
|
starcoder
|
defmodule ExCoveralls.Local do
@moduledoc """
Locally displays the result to screen.
"""
defmodule Count do
@moduledoc """
Stores count information for calculating coverage values.
"""
defstruct lines: 0, relevant: 0, covered: 0
end
@doc """
Provides an entry point for the module.
"""
def execute(stats, options \\ []) do
print_summary(stats)
if options[:detail] == true do
source(stats, options[:filter]) |> IO.puts
end
ExCoveralls.Stats.ensure_minimum_coverage(stats)
end
@doc """
Format the source code with color for the files that matches with
the specified patterns.
"""
def source(stats, _patterns = nil), do: source(stats)
def source(stats, _patterns = []), do: source(stats)
def source(stats, patterns) do
Enum.filter(stats, fn(stat) -> String.contains?(stat[:name], patterns) end) |> source
end
def source(stats) do
stats |> Enum.map(&format_source/1)
|> Enum.join("\n")
end
@doc """
Prints summary statistics for given coverage.
"""
def print_summary(stats) do
file_width = ExCoveralls.Settings.get_file_col_width
IO.puts "----------------"
IO.puts print_string("~-6s ~-#{file_width}s ~8s ~8s ~8s", ["COV", "FILE", "LINES", "RELEVANT", "MISSED"])
coverage(stats) |> IO.puts
IO.puts "----------------"
end
defp format_source(stat) do
"\n\e[33m--------#{stat[:name]}--------\e[m\n" <> colorize(stat)
end
defp colorize([{:name, _name}, {:source, source}, {:coverage, coverage}]) do
lines = String.split(source, "\n")
Enum.zip(lines, coverage)
|> Enum.map(&do_colorize/1)
|> Enum.join("\n")
end
defp do_colorize({line, coverage}) do
case coverage do
nil -> line
0 -> "\e[31m#{line}\e[m"
_ -> "\e[32m#{line}\e[m"
end
end
@doc """
Format the source coverage stats into string.
"""
def coverage(stats) do
stats = Enum.sort(stats, fn(x, y) -> x[:name] <= y[:name] end)
count_info = Enum.map(stats, fn(stat) -> [stat, calculate_count(stat[:coverage])] end)
Enum.join(format_body(count_info), "\n") <> "\n" <> format_total(count_info)
end
defp format_body(info) do
Enum.map(info, &format_info/1)
end
defp format_info([stat, count]) do
coverage = get_coverage(count)
file_width = ExCoveralls.Settings.get_file_col_width
print_string("~5.1f% ~-#{file_width}s ~8w ~8w ~8w",
[coverage, stat[:name], count.lines, count.relevant, count.relevant - count.covered])
end
defp format_total(info) do
totals = Enum.reduce(info, %Count{}, fn([_, count], acc) -> append(count, acc) end)
coverage = get_coverage(totals)
print_string("[TOTAL] ~5.1f%", [coverage])
end
defp append(a, b) do
%Count{
lines: a.lines + b.lines,
relevant: a.relevant + b.relevant,
covered: a.covered + b.covered
}
end
defp get_coverage(count) do
case count.relevant do
0 -> default_coverage_value()
_ -> (count.covered / count.relevant) * 100
end
end
defp default_coverage_value do
options = ExCoveralls.Settings.get_coverage_options
case Map.fetch(options, "treat_no_relevant_lines_as_covered") do
{:ok, false} -> 0.0
_ -> 100.0
end
end
@doc """
Calucate count information from thhe coverage stats.
"""
def calculate_count(coverage) do
do_calculate_count(coverage, 0, 0, 0)
end
defp do_calculate_count([], lines, relevant, covered) do
%Count{lines: lines, relevant: relevant, covered: covered}
end
defp do_calculate_count([h|t], lines, relevant, covered) do
case h do
nil -> do_calculate_count(t, lines + 1, relevant, covered)
0 -> do_calculate_count(t, lines + 1, relevant + 1, covered)
n when is_number(n)
-> do_calculate_count(t, lines + 1, relevant + 1, covered + 1)
_ -> raise "Invalid data - #{h}"
end
end
defp print_string(format, params) do
char_list = :io_lib.format(format, params)
List.to_string(char_list)
end
end
|
lib/excoveralls/local.ex
| 0.655667 | 0.49707 |
local.ex
|
starcoder
|
defmodule Zaryn.Mining.StandaloneWorkflow do
@moduledoc """
Transaction validation is performed in a single node processing.
This workflow should be executed only when the network is bootstrapping (only 1 validation node)
The single node will auto validate the transaction
"""
use Task
alias Zaryn.Crypto
alias Zaryn.Mining.PendingTransactionValidation
alias Zaryn.Mining.TransactionContext
alias Zaryn.Mining.ValidationContext
alias Zaryn.P2P
alias Zaryn.P2P.Message.ReplicateTransaction
alias Zaryn.P2P.Node
alias Zaryn.Replication
alias Zaryn.TransactionChain.Transaction
require Logger
def start_link(opts \\ []) do
Task.start_link(__MODULE__, :run, [opts])
end
def run(opts) do
tx = Keyword.get(opts, :transaction)
Logger.info("Start mining", transaction: Base.encode16(tx.address))
chain_storage_nodes = Replication.chain_storage_nodes_with_type(tx.address, tx.type)
beacon_storage_nodes = Replication.beacon_storage_nodes(tx.address, DateTime.utc_now())
{prev_tx, unspent_outputs, previous_storage_nodes, chain_storage_nodes_view,
beacon_storage_nodes_view,
validation_nodes_view} =
TransactionContext.get(
Transaction.previous_address(tx),
Enum.map(chain_storage_nodes, & &1.last_public_key),
Enum.map(beacon_storage_nodes, & &1.last_public_key),
[Crypto.last_node_public_key()]
)
valid_pending_transaction? =
case PendingTransactionValidation.validate(tx) do
:ok ->
true
_ ->
false
end
ValidationContext.new(
transaction: tx,
welcome_node: P2P.get_node_info(),
validation_nodes: [P2P.get_node_info()],
chain_storage_nodes: chain_storage_nodes,
beacon_storage_nodes: beacon_storage_nodes
)
|> ValidationContext.set_pending_transaction_validation(valid_pending_transaction?)
|> ValidationContext.put_transaction_context(
prev_tx,
unspent_outputs,
previous_storage_nodes,
chain_storage_nodes_view,
beacon_storage_nodes_view,
validation_nodes_view
)
|> validate()
|> replicate()
end
defp validate(context = %ValidationContext{}) do
context
|> ValidationContext.create_validation_stamp()
|> ValidationContext.cross_validate()
end
defp replicate(context) do
validated_tx = ValidationContext.get_validated_transaction(context)
storage_nodes = ValidationContext.get_storage_nodes(context)
Logger.debug(
"Send validated transaction to #{storage_nodes |> Enum.map(fn {node, roles} -> "#{Node.endpoint(node)} as #{Enum.join(roles, ",")}" end) |> Enum.join(",")}",
transaction: "#{validated_tx.type}@#{Base.encode16(validated_tx.address)}"
)
Task.async_stream(
storage_nodes,
fn {node, roles} ->
P2P.send_message(node, %ReplicateTransaction{
transaction: validated_tx,
roles: roles,
ack_storage?: true,
welcome_node_public_key: Crypto.last_node_public_key()
})
end,
on_timeout: :kill_task,
ordered: false
)
|> Stream.run()
end
end
|
lib/zaryn/mining/standalone_workflow.ex
| 0.798423 | 0.432303 |
standalone_workflow.ex
|
starcoder
|
defmodule TimeZoneInfo.Transformer.Rule do
@moduledoc """
This module handles and transforms the IANA rules.
"""
alias TimeZoneInfo.{
IanaDateTime,
IanaParser,
Transformer.RuleSet,
UtcDateTime
}
@doc """
Returns a map of rule-set for the given map of `rules`.
"""
@spec to_rule_sets(%{String.t() => [TimeZoneInfo.rule()]}, non_neg_integer()) ::
%{String.t() => RuleSet.t()}
def to_rule_sets(rules, lookahead) when is_integer(lookahead) do
Enum.into(rules, %{}, fn {name, rules} ->
{name, to_rule_set(rules, lookahead)}
end)
end
@doc """
Returns a rule-set for the given `rules`.
"""
@spec to_rule_set([TimeZoneInfo.rule()], non_neg_integer) :: RuleSet.t()
def to_rule_set(rules, lookahead) when is_integer(lookahead) do
now = UtcDateTime.now()
rule_set =
Enum.flat_map(rules, fn rule ->
from = rule[:from]
to =
case rule[:to] do
:max -> max(now.year + lookahead, from + 1)
:only -> rule[:from]
year -> year
end
Enum.into(from..to, [], fn year ->
at = IanaDateTime.to_gregorian_seconds(year, rule[:in], rule[:on], rule[:at])
{at, {rule[:time_standard], rule[:std_offset], rule[:letters]}}
end)
end)
|> Enum.sort_by(fn {at, _} -> at end)
{_, first} = first_standard(rule_set)
[{-1, first} | rule_set]
end
defp first_standard(rule_set) do
Enum.find(rule_set, fn
{_, {_, 0, _}} -> true
_ -> false
end)
end
@doc """
Transforms a `IanaParser.rule` to a `TimeZoneInfo.rule`. If the function gets
a list then all rules will be transformed.
"""
@spec transform(rule | rules) :: TimeZoneInfo.rule() | [TimeZoneInfo.rule()]
when rule: IanaParser.rule(), rules: [IanaParser.rule()]
def transform(rule) when is_list(rule) do
case Keyword.keyword?(rule) do
true ->
{
{rule[:in], rule[:on], rule[:at]},
rule[:time_standard],
rule[:std_offset],
rule[:letters]
}
false ->
rule |> Enum.map(&transform/1) |> Enum.reverse()
end
end
@doc """
Returns all rules form the rule set that are for now valid until end of time.
"""
@spec max([IanaParser.rule()]) :: [IanaParser.rule()]
def max(rules), do: Enum.filter(rules, &max?/1)
@doc """
Returns `true` if `rule` is valid until end of time or one of the `rules` is valid
until end of time.
"""
@spec max?(rule | rules) :: boolean when rule: IanaParser.rule(), rules: [IanaParser.rule()]
def max?(rule_or_rules) when is_list(rule_or_rules) do
case Keyword.keyword?(rule_or_rules) do
true -> rule_or_rules[:to] == :max
false -> Enum.any?(rule_or_rules, &max?/1)
end
end
def max?(_), do: false
end
|
lib/time_zone_info/transformer/rule.ex
| 0.905909 | 0.531513 |
rule.ex
|
starcoder
|
defmodule Crew.Periods do
@moduledoc """
The Periods context.
"""
import Ecto.Query, warn: false
import Ecto.Changeset
alias Crew.Repo
alias Crew.Periods.Period
def period_query(site_id), do: from(p in Period, where: p.site_id == ^site_id)
@doc """
Returns the list of periods.
## Examples
iex> list_periods()
[%Period{}, ...]
"""
def list_periods(site_id) do
Repo.all(period_query(site_id))
end
@doc """
Gets a single period.
Raises `Ecto.NoResultsError` if the Period does not exist.
## Examples
iex> get_period!(123)
%Period{}
iex> get_period!(456)
** (Ecto.NoResultsError)
"""
def get_period!(id), do: Repo.get!(Period, id)
def get_period_by(attrs, site_id), do: Repo.get_by(period_query(site_id), attrs)
@doc """
Creates a period.
## Examples
iex> create_period(%{field: value})
{:ok, %Period{}}
iex> create_period(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_period(attrs \\ %{}, site_id) do
%Period{}
|> Period.changeset(attrs)
|> put_change(:site_id, site_id)
|> Repo.insert()
end
@doc """
Updates a period.
## Examples
iex> update_period(period, %{field: new_value})
{:ok, %Period{}}
iex> update_period(period, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_period(%Period{} = period, attrs) do
period
|> Period.changeset(attrs)
|> Repo.update()
end
def upsert_period(update_attrs \\ %{}, find_attrs = %{}, site_id) do
case get_period_by(find_attrs, site_id) do
nil -> create_period(Map.merge(find_attrs, update_attrs), site_id)
existing -> update_period(existing, update_attrs)
end
end
@doc """
Deletes a period.
## Examples
iex> delete_period(period)
{:ok, %Period{}}
iex> delete_period(period)
{:error, %Ecto.Changeset{}}
"""
def delete_period(%Period{} = period) do
Repo.delete(period)
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking period changes.
## Examples
iex> change_period(period)
%Ecto.Changeset{data: %Period{}}
"""
def change_period(%Period{} = period, attrs \\ %{}) do
Period.changeset(period, attrs)
end
alias Crew.Periods.PeriodGroup
def period_group_query(site_id), do: from(pg in PeriodGroup, where: pg.site_id == ^site_id)
@doc """
Returns the list of period_groups.
## Examples
iex> list_period_groups()
[%PeriodGroup{}, ...]
"""
def list_period_groups(site_id) do
Repo.all(period_group_query(site_id))
end
@doc """
Gets a single period_group.
Raises `Ecto.NoResultsError` if the Period group does not exist.
## Examples
iex> get_period_group!(123)
%PeriodGroup{}
iex> get_period_group!(456)
** (Ecto.NoResultsError)
"""
def get_period_group!(id), do: Repo.get!(PeriodGroup, id)
def get_period_group_by(attrs, site_id), do: Repo.get_by(period_group_query(site_id), attrs)
@doc """
Creates a period_group.
## Examples
iex> create_period_group(%{field: value})
{:ok, %PeriodGroup{}}
iex> create_period_group(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_period_group(attrs \\ %{}, site_id) do
%PeriodGroup{}
|> PeriodGroup.changeset(attrs)
|> put_change(:site_id, site_id)
|> Repo.insert()
end
@doc """
Updates a period_group.
## Examples
iex> update_period_group(period_group, %{field: new_value})
{:ok, %PeriodGroup{}}
iex> update_period_group(period_group, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_period_group(%PeriodGroup{} = period_group, attrs) do
period_group
|> PeriodGroup.changeset(attrs)
|> Repo.update()
end
def upsert_period_group(update_attrs \\ %{}, find_attrs = %{}, site_id) do
case get_period_group_by(find_attrs, site_id) do
nil -> create_period_group(Map.merge(find_attrs, update_attrs), site_id)
existing -> update_period_group(existing, update_attrs)
end
end
@doc """
Deletes a period_group.
## Examples
iex> delete_period_group(period_group)
{:ok, %PeriodGroup{}}
iex> delete_period_group(period_group)
{:error, %Ecto.Changeset{}}
"""
def delete_period_group(%PeriodGroup{} = period_group) do
Repo.delete(period_group)
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking period_group changes.
## Examples
iex> change_period_group(period_group)
%Ecto.Changeset{data: %PeriodGroup{}}
"""
def change_period_group(%PeriodGroup{} = period_group, attrs \\ %{}) do
PeriodGroup.changeset(period_group, attrs)
end
end
|
lib/crew/periods.ex
| 0.906965 | 0.572155 |
periods.ex
|
starcoder
|
defmodule Sanbase.MapUtils do
@doc ~s"""
Return a subset of `left` map that has only the keys that are also present in `right`.
#### Examples:
iex> Sanbase.MapUtils.drop_diff_keys(%{}, %{})
%{}
iex> Sanbase.MapUtils.drop_diff_keys(%{a: 1}, %{a: 1})
%{a: 1}
iex> Sanbase.MapUtils.drop_diff_keys(%{a: 1, b: 2}, %{a: 1})
%{a: 1}
iex> Sanbase.MapUtils.drop_diff_keys(%{a: 1}, %{a: "ASDASDASDA"})
%{a: 1}
iex> Sanbase.MapUtils.drop_diff_keys(%{a: 1, d: 555, e: "string"}, %{b: 2, c: 3, f: 19})
%{}
"""
def drop_diff_keys(left, right) do
Map.drop(left, Map.keys(left) -- Map.keys(right))
end
@doc ~s"""
Find where a given name-value pair is located in a deeply nested list-map data
structures.
#### Examples:
iex> %{a: %{b: %{"name" => "ivan"}}} |> Sanbase.MapUtils.find_pair_path("name", "ivan")
[[:a, :b, "name"]]
iex> %{a: %{b: [%{"name" => "ivan"}]}} |> Sanbase.MapUtils.find_pair_path("name", "ivan")
[[:a, :b, {:at, 0}, "name"]]
iex> %{a: [%{b: [%{"name" => "ivan"}]}]} |> Sanbase.MapUtils.find_pair_path("name", "ivan")
[[:a, {:at, 0}, :b, {:at, 0}, "name"]]
iex>%{
...> "foo" => %{"last" => [%{b: [%{"name" => "ivan"}]}]},
...> a: %{"some" => %{a: 2, c: 12}, "key" => [1, 2, 3, 4, 5, 6]}
...> } |> Sanbase.MapUtils.find_pair_path("name", "ivan")
[["foo", "last", {:at, 0}, :b, {:at, 0}, "name"]]
iex> %{a: %{b: [%{"name" => ""}]}} |> Sanbase.MapUtils.find_pair_path("name", "not_existing")
[]
iex> %{a: %{b: [%{"name" => ""}]}} |> Sanbase.MapUtils.find_pair_path("not_existing", "ivan")
[]
"""
def find_pair_path(map, key, value) when is_map(map) do
do_find_pair_path(map, key, value, [])
|> Enum.map(&(&1 |> List.flatten() |> Enum.reverse()))
|> Enum.reject(&(&1 == nil || &1 == []))
end
defp do_find_pair_path(map, key, value, path) when is_map(map) do
keys = Map.keys(map)
if key in keys and Map.get(map, key) == value do
[key | path]
else
Enum.map(keys, fn subkey ->
Map.get(map, subkey)
|> do_find_pair_path(key, value, [subkey | path])
end)
end
end
defp do_find_pair_path(list, key, value, path) when is_list(list) do
Enum.with_index(list)
|> Enum.map(fn {elem, index} ->
do_find_pair_path(elem, key, value, [{:at, index} | path])
end)
end
defp do_find_pair_path(_, _, _, _), do: []
end
|
lib/map_utils.ex
| 0.858481 | 0.597872 |
map_utils.ex
|
starcoder
|
defmodule Oban.Plugins.Stager do
@moduledoc """
Transition jobs to the `available` state when they reach their scheduled time.
This module is necessary for the execution of scheduled and retryable jobs.
## Options
* `:interval` - the number of milliseconds between database updates. This is directly tied to
the resolution of _scheduled_ jobs. For example, with an `interval` of `5_000ms`, scheduled
jobs are checked every 5 seconds. The default is `1_000ms`.
* `:limit` — the number of jobs that will be staged each time the plugin runs. Defaults to
`5,000`, which you can increase if staging can't keep up with your insertion rate or decrease
if you're experiencing staging timeouts.
## Instrumenting with Telemetry
The `Oban.Plugins.Stager` plugin adds the following metadata to the `[:oban, :plugin, :stop]` event:
* :staged_count - the number of jobs that were staged in the database
"""
use GenServer
import Ecto.Query,
only: [
distinct: 2,
from: 2,
join: 5,
limit: 2,
select: 2,
subquery: 1,
where: 3
]
alias Oban.{Config, Job, Query, Repo}
@type option :: {:conf, Config.t()} | {:name, GenServer.name()} | {:interval, pos_integer()}
defmodule State do
@moduledoc false
defstruct [
:conf,
:name,
:timer,
limit: 5_000,
interval: :timer.seconds(1),
lock_key: 1_149_979_440_242_868_003
]
end
@doc false
@spec start_link([option()]) :: GenServer.on_start()
def start_link(opts) do
GenServer.start_link(__MODULE__, opts, name: opts[:name])
end
@impl GenServer
def init(opts) do
Process.flag(:trap_exit, true)
state =
State
|> struct!(opts)
|> schedule_staging()
{:ok, state}
end
@impl GenServer
def terminate(_reason, %State{timer: timer}) do
if is_reference(timer), do: Process.cancel_timer(timer)
:ok
end
@impl GenServer
def handle_info(:stage, %State{} = state) do
meta = %{conf: state.conf, plugin: __MODULE__}
:telemetry.span([:oban, :plugin], meta, fn ->
case lock_and_stage(state) do
{:ok, staged_count} when is_integer(staged_count) ->
{:ok, Map.put(meta, :staged_count, staged_count)}
{:ok, false} ->
{:ok, Map.put(meta, :staged_count, 0)}
error ->
{:error, Map.put(meta, :error, error)}
end
end)
{:noreply, schedule_staging(state)}
end
defp lock_and_stage(state) do
Query.with_xact_lock(state.conf, state.lock_key, fn ->
{sched_count, nil} = stage_scheduled(state)
notify_queues(state)
sched_count
end)
end
defp stage_scheduled(state) do
subquery =
Job
|> where([j], j.state in ["scheduled", "retryable"])
|> where([j], not is_nil(j.queue))
|> where([j], j.scheduled_at <= ^DateTime.utc_now())
|> limit(^state.limit)
Repo.update_all(
state.conf,
join(Job, :inner, [j], x in subquery(subquery), on: j.id == x.id),
set: [state: "available"]
)
end
@pg_notify "pg_notify(?, json_build_object('queue', ?)::text)"
defp notify_queues(state) do
channel = "#{state.conf.prefix}.oban_insert"
subquery =
Job
|> where([j], j.state == "available")
|> where([j], not is_nil(j.queue))
|> select([:queue])
|> distinct(true)
query = from job in subquery(subquery), select: fragment(@pg_notify, ^channel, job.queue)
Repo.all(state.conf, query)
:ok
end
defp schedule_staging(state) do
timer = Process.send_after(self(), :stage, state.interval)
%{state | timer: timer}
end
end
|
lib/oban/plugins/stager.ex
| 0.84691 | 0.622961 |
stager.ex
|
starcoder
|
defmodule Queutils.BlockingQueue do
use GenServer
@moduledoc """
A queue with a fixed length that blocks on `Queutils.BlockingQueue.push/2` if the queue is full.
## Usage
Add it to your application supervisor's `start/2` function, like this:
def start(_type, _args) do
children = [
...
{Queutils.BlockingQueue, name: MessageQueue, max_length: 10_000},
...
]
opts = [strategy: :one_for_one, name: MyApplication.Supervisor]
Supervisor.start_link(children, opts)
end
Then you can push and pop from the queue like this:
:ok = Queutils.Blockingqueue.push(MessageQueue, :my_message)
[:my_message] = Queutils.Blockingqueue.pop(MessageQueue, 1)
Use with `Queutils.BlockingQueueProducer` for more fun,
or use `Queutils.BlockingProducer` for the effect of both.
## Options
- `:name` - the ID of the queue. This will be the first argument to the `push/2` function. Default is `BlockingQueue`.
- `:max_length` - The maximum number of messages that this process will store until it starts blocking. Default is 1,000.
"""
@doc """
Start a blocking queue process.
## Options
- `:name` - the ID of the queue. This will be the first argument to the `push/2` function. Default is `BlockingQueue`.
- `:max_length` - The maximum number of messages that this process will store until it starts blocking. Default is 1,000.
"""
def start_link(opts) do
name = Keyword.get(opts, :name)
GenServer.start_link(__MODULE__, opts, name: name)
end
def child_spec(opts) do
%{
id: Keyword.get(opts, :name, BlockingQueue),
start: {__MODULE__, :start_link, [opts]},
type: :supervisor
}
end
def init(opts) do
max_length = Keyword.get(opts, :max_length, 1_000)
{:ok, %{max_length: max_length, queue: [], waiting: [], pushed_count: 0, popped_count: 0}}
end
@doc """
Push an item onto the queue.
This function will block if the queue is full, and unblock once it's not.
"""
@spec push(any(), any()) :: :ok
def push(queue, msg) do
GenServer.call(queue, {:push, msg})
end
@doc """
Get the count of elements that have been pushed to a queue over the queue's lifetime.
"""
@spec pushed_count(any()) :: integer()
def pushed_count(queue) do
GenServer.call(queue, :pushed_count)
end
@doc """
Pop an item off of the queue. Never blocks, and returns a list.
The returned list will be empty if the queue is empty.
"""
@spec pop(term(), non_neg_integer()) :: list()
def pop(queue, count \\ 1) do
GenServer.call(queue, {:pop, count})
end
@doc """
Get the count of elements that have been popped from a queue over the queue's lifetime.
"""
@spec popped_count(any()) :: integer()
def popped_count(queue) do
GenServer.call(queue, :popped_count)
end
@doc """
Get the current length of the queue.
"""
@spec length(term()) :: non_neg_integer()
def length(queue) do
GenServer.call(queue, :length)
end
def handle_call(:length, _from, state) do
{:reply, Enum.count(state.queue), state}
end
def handle_call({:push, msg}, from, state) do
if Enum.count(state.queue) >= state.max_length do
waiting = state.waiting ++ [{from, msg}]
{:noreply, %{state | waiting: waiting}}
else
queue = state.queue ++ [msg]
{:reply, :ok, %{state | queue: queue, pushed_count: state.pushed_count + 1}}
end
end
def handle_call(:pushed_count, _from, state) do
{:reply, state.pushed_count, state}
end
def handle_call({:pop, count}, _from, state) do
{popped, remaining} = Enum.split(state.queue, count)
{popped_waiters, still_waiting} = Enum.split(state.waiting, count)
msgs_from_waiters = Enum.map(popped_waiters, fn {from, msg} ->
GenServer.reply(from, :ok)
msg
end)
popped_count = state.popped_count + Kernel.length(popped)
queue = remaining ++ msgs_from_waiters
{:reply, popped, %{state | queue: queue, waiting: still_waiting, popped_count: popped_count}}
end
def handle_call(:popped_count, _from, state) do
{:reply, state.popped_count, state}
end
end
|
lib/queutils/blocking_queue.ex
| 0.835651 | 0.449755 |
blocking_queue.ex
|
starcoder
|
defmodule Exco do
@moduledoc ~S"""
Concurrent versions of some of the functions in the `Enum` module.
See further discussion in the [readme section](readme.html).
## Options
* `max_concurrency` - the maximum number of items to run at the same time. Set it to an integer or one of the following:
* `:schedulers` (default) - set to `System.schedulers_online/1`
* `:full` - tries to run all items at the same time
"""
@type ok() :: {:ok, any}
@type ex() :: {:ex, any}
import Exco.Runner, only: [run: 4]
@default_options [
max_concurrency: :schedulers,
ordered: true
]
@doc ~S"""
Concurrent version of `Enum.map/2`.
The applied function runs in a new process for each item.
The caller and the spawned processes will be linked.
The return value is a list of either `{:ok, value}` or
`{:exit, reason}` if the caller is trapping exits. Each
`value` is a result of invoking `fun` on each corresponding
item of `enumerable`.
The ordering is retained.
See the [options](#module-options).
## Examples:
iex(1)> Exco.map(1..3, fn x -> x*2 end)
[ok: 2, ok: 4, ok: 6]
"""
@spec map(Enumerable.t, (any -> any), keyword) :: [ok | ex]
def map(enumerable, fun, opts \\ []) do
run(:map, enumerable, fun, opts)
end
@doc ~S"""
Concurrent version of `Enum.map/2`.
The applied function runs in a new process for each item.
The caller and the spawned processes will not be linked.
The return value is a list consisting of either `{:ok, value}` or `{:exit, reason}` tuples.
The ordering is retained.
See the [options](#module-options).
## Examples:
iex(1)> Exco.map_nolink(1..3, fn x -> x*2 end)
[ok: 2, ok: 4, ok: 6]
"""
@spec map_nolink(Enumerable.t, (any -> any), keyword) :: [ok | ex]
def map_nolink(enumerable, fun, opts \\ []) do
run(:map, enumerable, fun, opts)
end
@doc ~S"""
Concurrent version of `Enum.each/2`.
The applied function runs in a new process for each item.
The caller and the spawned processes will be linked.
Returns `:ok`.
See the [options](#module-options).
## Examples
Exco.each(1..3, fn x -> IO.puts x*2 end)
2
4
6
#=> :ok
"""
@spec each(Enumerable.t, (any -> any), keyword) :: :ok
def each(enumerable, fun, opts \\ []) do
run(:each, enumerable, fun, opts)
end
@doc ~S"""
Concurrent version of `Enum.each/2`.
The applied function runs in a new process for each item.
The caller and the spawned processes will not be linked.
Returns `:ok`.
See the [options](#module-options).
## Examples
Exco.each_nolink(1..3, fn x -> IO.puts x*2 end)
2
4
6
#=> :ok
"""
@spec each_nolink(Enumerable.t, (any -> any), keyword) :: :ok
def each_nolink(enumerable, fun, opts \\ []) do
run(:each, enumerable, fun, opts)
end
@doc ~S"""
Concurrent version of `Enum.filter/2`.
The applied function runs in a new process for each item.
The caller and the spawned processes will be linked.
The return value is a list of `{:ok, value}` tuples where
`value` is the original value for which the applied function
returned a truthy value.
The ordering is retained.
See the [options](#module-options).
## Examples:
iex(1)> Exco.filter(1..3, fn x -> x < 3 end)
[ok: 1, ok: 2]
"""
@spec filter(Enumerable.t, (any -> as_boolean(any)), keyword) :: [ok]
def filter(enumerable, fun, opts \\ []) do
run(:filter, enumerable, fun, opts)
end
@doc ~S"""
Concurrent version of `Enum.filter/2`.
The applied function runs in a new process for each item.
The caller and the spawned processes will not be linked.
The return value is the same as in the case of `Exco.filter/3`.
Thus, falsy return values from the function or failing task processes are ignored.
No indication is provided whether a value was dropped due to falsy return value
from the function or because of a failing process. If you need to separate
failing processes from falsy return values, consider using `Exco.map_nolink/3`
and filtering separately.
The ordering is retained.
See the [options](#module-options).
## Examples:
iex(1)> Exco.filter_nolink(1..3, fn x -> x < 3 end)
[ok: 1, ok: 2]
"""
@spec filter_nolink(Enumerable.t, (any -> as_boolean(any)), keyword) :: [ok]
def filter_nolink(enumerable, fun, opts \\ []) do
run(:filter, enumerable, fun, opts)
end
end
|
lib/exco.ex
| 0.88136 | 0.815637 |
exco.ex
|
starcoder
|
defmodule AWS.Neptune do
@moduledoc """
Amazon Neptune
Amazon Neptune is a fast, reliable, fully-managed graph database service that
makes it easy to build and run applications that work with highly connected
datasets.
The core of Amazon Neptune is a purpose-built, high-performance graph database
engine optimized for storing billions of relationships and querying the graph
with milliseconds latency. Amazon Neptune supports popular graph models Property
Graph and W3C's RDF, and their respective query languages Apache TinkerPop
Gremlin and SPARQL, allowing you to easily build queries that efficiently
navigate highly connected datasets. Neptune powers graph use cases such as
recommendation engines, fraud detection, knowledge graphs, drug discovery, and
network security.
This interface reference for Amazon Neptune contains documentation for a
programming or command line interface you can use to manage Amazon Neptune. Note
that Amazon Neptune is asynchronous, which means that some interfaces might
require techniques such as polling or callback functions to determine when a
command has been applied. In this reference, the parameter descriptions indicate
whether a command is applied immediately, on the next instance reboot, or during
the maintenance window. The reference structure is as follows, and we list
following some related topics from the user guide.
"""
@doc """
Associates an Identity and Access Management (IAM) role from an Neptune DB
cluster.
"""
def add_role_to_d_b_cluster(client, input, options \\ []) do
request(client, "AddRoleToDBCluster", input, options)
end
@doc """
Adds a source identifier to an existing event notification subscription.
"""
def add_source_identifier_to_subscription(client, input, options \\ []) do
request(client, "AddSourceIdentifierToSubscription", input, options)
end
@doc """
Adds metadata tags to an Amazon Neptune resource.
These tags can also be used with cost allocation reporting to track cost
associated with Amazon Neptune resources, or used in a Condition statement in an
IAM policy for Amazon Neptune.
"""
def add_tags_to_resource(client, input, options \\ []) do
request(client, "AddTagsToResource", input, options)
end
@doc """
Applies a pending maintenance action to a resource (for example, to a DB
instance).
"""
def apply_pending_maintenance_action(client, input, options \\ []) do
request(client, "ApplyPendingMaintenanceAction", input, options)
end
@doc """
Copies the specified DB cluster parameter group.
"""
def copy_d_b_cluster_parameter_group(client, input, options \\ []) do
request(client, "CopyDBClusterParameterGroup", input, options)
end
@doc """
Copies a snapshot of a DB cluster.
To copy a DB cluster snapshot from a shared manual DB cluster snapshot,
`SourceDBClusterSnapshotIdentifier` must be the Amazon Resource Name (ARN) of
the shared DB cluster snapshot.
"""
def copy_d_b_cluster_snapshot(client, input, options \\ []) do
request(client, "CopyDBClusterSnapshot", input, options)
end
@doc """
Copies the specified DB parameter group.
"""
def copy_d_b_parameter_group(client, input, options \\ []) do
request(client, "CopyDBParameterGroup", input, options)
end
@doc """
Creates a new Amazon Neptune DB cluster.
You can use the `ReplicationSourceIdentifier` parameter to create the DB cluster
as a Read Replica of another DB cluster or Amazon Neptune DB instance.
Note that when you create a new cluster using `CreateDBCluster` directly,
deletion protection is disabled by default (when you create a new production
cluster in the console, deletion protection is enabled by default). You can only
delete a DB cluster if its `DeletionProtection` field is set to `false`.
"""
def create_d_b_cluster(client, input, options \\ []) do
request(client, "CreateDBCluster", input, options)
end
@doc """
Creates a new DB cluster parameter group.
Parameters in a DB cluster parameter group apply to all of the instances in a DB
cluster.
A DB cluster parameter group is initially created with the default parameters
for the database engine used by instances in the DB cluster. To provide custom
values for any of the parameters, you must modify the group after creating it
using `ModifyDBClusterParameterGroup`. Once you've created a DB cluster
parameter group, you need to associate it with your DB cluster using
`ModifyDBCluster`. When you associate a new DB cluster parameter group with a
running DB cluster, you need to reboot the DB instances in the DB cluster
without failover for the new DB cluster parameter group and associated settings
to take effect.
After you create a DB cluster parameter group, you should wait at least 5
minutes before creating your first DB cluster that uses that DB cluster
parameter group as the default parameter group. This allows Amazon Neptune to
fully complete the create action before the DB cluster parameter group is used
as the default for a new DB cluster. This is especially important for parameters
that are critical when creating the default database for a DB cluster, such as
the character set for the default database defined by the
`character_set_database` parameter. You can use the *Parameter Groups* option of
the [Amazon Neptune console](https://console.aws.amazon.com/rds/) or the
`DescribeDBClusterParameters` command to verify that your DB cluster parameter
group has been created or modified.
"""
def create_d_b_cluster_parameter_group(client, input, options \\ []) do
request(client, "CreateDBClusterParameterGroup", input, options)
end
@doc """
Creates a snapshot of a DB cluster.
"""
def create_d_b_cluster_snapshot(client, input, options \\ []) do
request(client, "CreateDBClusterSnapshot", input, options)
end
@doc """
Creates a new DB instance.
"""
def create_d_b_instance(client, input, options \\ []) do
request(client, "CreateDBInstance", input, options)
end
@doc """
Creates a new DB parameter group.
A DB parameter group is initially created with the default parameters for the
database engine used by the DB instance. To provide custom values for any of the
parameters, you must modify the group after creating it using
*ModifyDBParameterGroup*. Once you've created a DB parameter group, you need to
associate it with your DB instance using *ModifyDBInstance*. When you associate
a new DB parameter group with a running DB instance, you need to reboot the DB
instance without failover for the new DB parameter group and associated settings
to take effect.
After you create a DB parameter group, you should wait at least 5 minutes before
creating your first DB instance that uses that DB parameter group as the default
parameter group. This allows Amazon Neptune to fully complete the create action
before the parameter group is used as the default for a new DB instance. This is
especially important for parameters that are critical when creating the default
database for a DB instance, such as the character set for the default database
defined by the `character_set_database` parameter. You can use the *Parameter
Groups* option of the Amazon Neptune console or the *DescribeDBParameters*
command to verify that your DB parameter group has been created or modified.
"""
def create_d_b_parameter_group(client, input, options \\ []) do
request(client, "CreateDBParameterGroup", input, options)
end
@doc """
Creates a new DB subnet group.
DB subnet groups must contain at least one subnet in at least two AZs in the AWS
Region.
"""
def create_d_b_subnet_group(client, input, options \\ []) do
request(client, "CreateDBSubnetGroup", input, options)
end
@doc """
Creates an event notification subscription.
This action requires a topic ARN (Amazon Resource Name) created by either the
Neptune console, the SNS console, or the SNS API. To obtain an ARN with SNS, you
must create a topic in Amazon SNS and subscribe to the topic. The ARN is
displayed in the SNS console.
You can specify the type of source (SourceType) you want to be notified of,
provide a list of Neptune sources (SourceIds) that triggers the events, and
provide a list of event categories (EventCategories) for events you want to be
notified of. For example, you can specify SourceType = db-instance, SourceIds =
mydbinstance1, mydbinstance2 and EventCategories = Availability, Backup.
If you specify both the SourceType and SourceIds, such as SourceType =
db-instance and SourceIdentifier = myDBInstance1, you are notified of all the
db-instance events for the specified source. If you specify a SourceType but do
not specify a SourceIdentifier, you receive notice of the events for that source
type for all your Neptune sources. If you do not specify either the SourceType
nor the SourceIdentifier, you are notified of events generated from all Neptune
sources belonging to your customer account.
"""
def create_event_subscription(client, input, options \\ []) do
request(client, "CreateEventSubscription", input, options)
end
@doc """
The DeleteDBCluster action deletes a previously provisioned DB cluster.
When you delete a DB cluster, all automated backups for that DB cluster are
deleted and can't be recovered. Manual DB cluster snapshots of the specified DB
cluster are not deleted.
Note that the DB Cluster cannot be deleted if deletion protection is enabled. To
delete it, you must first set its `DeletionProtection` field to `False`.
"""
def delete_d_b_cluster(client, input, options \\ []) do
request(client, "DeleteDBCluster", input, options)
end
@doc """
Deletes a specified DB cluster parameter group.
The DB cluster parameter group to be deleted can't be associated with any DB
clusters.
"""
def delete_d_b_cluster_parameter_group(client, input, options \\ []) do
request(client, "DeleteDBClusterParameterGroup", input, options)
end
@doc """
Deletes a DB cluster snapshot.
If the snapshot is being copied, the copy operation is terminated.
The DB cluster snapshot must be in the `available` state to be deleted.
"""
def delete_d_b_cluster_snapshot(client, input, options \\ []) do
request(client, "DeleteDBClusterSnapshot", input, options)
end
@doc """
The DeleteDBInstance action deletes a previously provisioned DB instance.
When you delete a DB instance, all automated backups for that instance are
deleted and can't be recovered. Manual DB snapshots of the DB instance to be
deleted by `DeleteDBInstance` are not deleted.
If you request a final DB snapshot the status of the Amazon Neptune DB instance
is `deleting` until the DB snapshot is created. The API action
`DescribeDBInstance` is used to monitor the status of this operation. The action
can't be canceled or reverted once submitted.
Note that when a DB instance is in a failure state and has a status of `failed`,
`incompatible-restore`, or `incompatible-network`, you can only delete it when
the `SkipFinalSnapshot` parameter is set to `true`.
You can't delete a DB instance if it is the only instance in the DB cluster, or
if it has deletion protection enabled.
"""
def delete_d_b_instance(client, input, options \\ []) do
request(client, "DeleteDBInstance", input, options)
end
@doc """
Deletes a specified DBParameterGroup.
The DBParameterGroup to be deleted can't be associated with any DB instances.
"""
def delete_d_b_parameter_group(client, input, options \\ []) do
request(client, "DeleteDBParameterGroup", input, options)
end
@doc """
Deletes a DB subnet group.
The specified database subnet group must not be associated with any DB
instances.
"""
def delete_d_b_subnet_group(client, input, options \\ []) do
request(client, "DeleteDBSubnetGroup", input, options)
end
@doc """
Deletes an event notification subscription.
"""
def delete_event_subscription(client, input, options \\ []) do
request(client, "DeleteEventSubscription", input, options)
end
@doc """
Returns a list of `DBClusterParameterGroup` descriptions.
If a `DBClusterParameterGroupName` parameter is specified, the list will contain
only the description of the specified DB cluster parameter group.
"""
def describe_d_b_cluster_parameter_groups(client, input, options \\ []) do
request(client, "DescribeDBClusterParameterGroups", input, options)
end
@doc """
Returns the detailed parameter list for a particular DB cluster parameter group.
"""
def describe_d_b_cluster_parameters(client, input, options \\ []) do
request(client, "DescribeDBClusterParameters", input, options)
end
@doc """
Returns a list of DB cluster snapshot attribute names and values for a manual DB
cluster snapshot.
When sharing snapshots with other AWS accounts,
`DescribeDBClusterSnapshotAttributes` returns the `restore` attribute and a list
of IDs for the AWS accounts that are authorized to copy or restore the manual DB
cluster snapshot. If `all` is included in the list of values for the `restore`
attribute, then the manual DB cluster snapshot is public and can be copied or
restored by all AWS accounts.
To add or remove access for an AWS account to copy or restore a manual DB
cluster snapshot, or to make the manual DB cluster snapshot public or private,
use the `ModifyDBClusterSnapshotAttribute` API action.
"""
def describe_d_b_cluster_snapshot_attributes(client, input, options \\ []) do
request(client, "DescribeDBClusterSnapshotAttributes", input, options)
end
@doc """
Returns information about DB cluster snapshots.
This API action supports pagination.
"""
def describe_d_b_cluster_snapshots(client, input, options \\ []) do
request(client, "DescribeDBClusterSnapshots", input, options)
end
@doc """
Returns information about provisioned DB clusters, and supports pagination.
This operation can also return information for Amazon RDS clusters and Amazon
DocDB clusters.
"""
def describe_d_b_clusters(client, input, options \\ []) do
request(client, "DescribeDBClusters", input, options)
end
@doc """
Returns a list of the available DB engines.
"""
def describe_d_b_engine_versions(client, input, options \\ []) do
request(client, "DescribeDBEngineVersions", input, options)
end
@doc """
Returns information about provisioned instances, and supports pagination.
This operation can also return information for Amazon RDS instances and Amazon
DocDB instances.
"""
def describe_d_b_instances(client, input, options \\ []) do
request(client, "DescribeDBInstances", input, options)
end
@doc """
Returns a list of `DBParameterGroup` descriptions.
If a `DBParameterGroupName` is specified, the list will contain only the
description of the specified DB parameter group.
"""
def describe_d_b_parameter_groups(client, input, options \\ []) do
request(client, "DescribeDBParameterGroups", input, options)
end
@doc """
Returns the detailed parameter list for a particular DB parameter group.
"""
def describe_d_b_parameters(client, input, options \\ []) do
request(client, "DescribeDBParameters", input, options)
end
@doc """
Returns a list of DBSubnetGroup descriptions.
If a DBSubnetGroupName is specified, the list will contain only the descriptions
of the specified DBSubnetGroup.
For an overview of CIDR ranges, go to the [Wikipedia Tutorial](http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing).
"""
def describe_d_b_subnet_groups(client, input, options \\ []) do
request(client, "DescribeDBSubnetGroups", input, options)
end
@doc """
Returns the default engine and system parameter information for the cluster
database engine.
"""
def describe_engine_default_cluster_parameters(client, input, options \\ []) do
request(client, "DescribeEngineDefaultClusterParameters", input, options)
end
@doc """
Returns the default engine and system parameter information for the specified
database engine.
"""
def describe_engine_default_parameters(client, input, options \\ []) do
request(client, "DescribeEngineDefaultParameters", input, options)
end
@doc """
Displays a list of categories for all event source types, or, if specified, for
a specified source type.
"""
def describe_event_categories(client, input, options \\ []) do
request(client, "DescribeEventCategories", input, options)
end
@doc """
Lists all the subscription descriptions for a customer account.
The description for a subscription includes SubscriptionName, SNSTopicARN,
CustomerID, SourceType, SourceID, CreationTime, and Status.
If you specify a SubscriptionName, lists the description for that subscription.
"""
def describe_event_subscriptions(client, input, options \\ []) do
request(client, "DescribeEventSubscriptions", input, options)
end
@doc """
Returns events related to DB instances, DB security groups, DB snapshots, and DB
parameter groups for the past 14 days.
Events specific to a particular DB instance, DB security group, database
snapshot, or DB parameter group can be obtained by providing the name as a
parameter. By default, the past hour of events are returned.
"""
def describe_events(client, input, options \\ []) do
request(client, "DescribeEvents", input, options)
end
@doc """
Returns a list of orderable DB instance options for the specified engine.
"""
def describe_orderable_d_b_instance_options(client, input, options \\ []) do
request(client, "DescribeOrderableDBInstanceOptions", input, options)
end
@doc """
Returns a list of resources (for example, DB instances) that have at least one
pending maintenance action.
"""
def describe_pending_maintenance_actions(client, input, options \\ []) do
request(client, "DescribePendingMaintenanceActions", input, options)
end
@doc """
You can call `DescribeValidDBInstanceModifications` to learn what modifications
you can make to your DB instance.
You can use this information when you call `ModifyDBInstance`.
"""
def describe_valid_d_b_instance_modifications(client, input, options \\ []) do
request(client, "DescribeValidDBInstanceModifications", input, options)
end
@doc """
Forces a failover for a DB cluster.
A failover for a DB cluster promotes one of the Read Replicas (read-only
instances) in the DB cluster to be the primary instance (the cluster writer).
Amazon Neptune will automatically fail over to a Read Replica, if one exists,
when the primary instance fails. You can force a failover when you want to
simulate a failure of a primary instance for testing. Because each instance in a
DB cluster has its own endpoint address, you will need to clean up and
re-establish any existing connections that use those endpoint addresses when the
failover is complete.
"""
def failover_d_b_cluster(client, input, options \\ []) do
request(client, "FailoverDBCluster", input, options)
end
@doc """
Lists all tags on an Amazon Neptune resource.
"""
def list_tags_for_resource(client, input, options \\ []) do
request(client, "ListTagsForResource", input, options)
end
@doc """
Modify a setting for a DB cluster.
You can change one or more database configuration parameters by specifying these
parameters and the new values in the request.
"""
def modify_d_b_cluster(client, input, options \\ []) do
request(client, "ModifyDBCluster", input, options)
end
@doc """
Modifies the parameters of a DB cluster parameter group.
To modify more than one parameter, submit a list of the following:
`ParameterName`, `ParameterValue`, and `ApplyMethod`. A maximum of 20 parameters
can be modified in a single request.
Changes to dynamic parameters are applied immediately. Changes to static
parameters require a reboot without failover to the DB cluster associated with
the parameter group before the change can take effect.
After you create a DB cluster parameter group, you should wait at least 5
minutes before creating your first DB cluster that uses that DB cluster
parameter group as the default parameter group. This allows Amazon Neptune to
fully complete the create action before the parameter group is used as the
default for a new DB cluster. This is especially important for parameters that
are critical when creating the default database for a DB cluster, such as the
character set for the default database defined by the `character_set_database`
parameter. You can use the *Parameter Groups* option of the Amazon Neptune
console or the `DescribeDBClusterParameters` command to verify that your DB
cluster parameter group has been created or modified.
"""
def modify_d_b_cluster_parameter_group(client, input, options \\ []) do
request(client, "ModifyDBClusterParameterGroup", input, options)
end
@doc """
Adds an attribute and values to, or removes an attribute and values from, a
manual DB cluster snapshot.
To share a manual DB cluster snapshot with other AWS accounts, specify `restore`
as the `AttributeName` and use the `ValuesToAdd` parameter to add a list of IDs
of the AWS accounts that are authorized to restore the manual DB cluster
snapshot. Use the value `all` to make the manual DB cluster snapshot public,
which means that it can be copied or restored by all AWS accounts. Do not add
the `all` value for any manual DB cluster snapshots that contain private
information that you don't want available to all AWS accounts. If a manual DB
cluster snapshot is encrypted, it can be shared, but only by specifying a list
of authorized AWS account IDs for the `ValuesToAdd` parameter. You can't use
`all` as a value for that parameter in this case.
To view which AWS accounts have access to copy or restore a manual DB cluster
snapshot, or whether a manual DB cluster snapshot public or private, use the
`DescribeDBClusterSnapshotAttributes` API action.
"""
def modify_d_b_cluster_snapshot_attribute(client, input, options \\ []) do
request(client, "ModifyDBClusterSnapshotAttribute", input, options)
end
@doc """
Modifies settings for a DB instance.
You can change one or more database configuration parameters by specifying these
parameters and the new values in the request. To learn what modifications you
can make to your DB instance, call `DescribeValidDBInstanceModifications` before
you call `ModifyDBInstance`.
"""
def modify_d_b_instance(client, input, options \\ []) do
request(client, "ModifyDBInstance", input, options)
end
@doc """
Modifies the parameters of a DB parameter group.
To modify more than one parameter, submit a list of the following:
`ParameterName`, `ParameterValue`, and `ApplyMethod`. A maximum of 20 parameters
can be modified in a single request.
Changes to dynamic parameters are applied immediately. Changes to static
parameters require a reboot without failover to the DB instance associated with
the parameter group before the change can take effect.
After you modify a DB parameter group, you should wait at least 5 minutes before
creating your first DB instance that uses that DB parameter group as the default
parameter group. This allows Amazon Neptune to fully complete the modify action
before the parameter group is used as the default for a new DB instance. This is
especially important for parameters that are critical when creating the default
database for a DB instance, such as the character set for the default database
defined by the `character_set_database` parameter. You can use the *Parameter
Groups* option of the Amazon Neptune console or the *DescribeDBParameters*
command to verify that your DB parameter group has been created or modified.
"""
def modify_d_b_parameter_group(client, input, options \\ []) do
request(client, "ModifyDBParameterGroup", input, options)
end
@doc """
Modifies an existing DB subnet group.
DB subnet groups must contain at least one subnet in at least two AZs in the AWS
Region.
"""
def modify_d_b_subnet_group(client, input, options \\ []) do
request(client, "ModifyDBSubnetGroup", input, options)
end
@doc """
Modifies an existing event notification subscription.
Note that you can't modify the source identifiers using this call; to change
source identifiers for a subscription, use the
`AddSourceIdentifierToSubscription` and `RemoveSourceIdentifierFromSubscription`
calls.
You can see a list of the event categories for a given SourceType by using the
**DescribeEventCategories** action.
"""
def modify_event_subscription(client, input, options \\ []) do
request(client, "ModifyEventSubscription", input, options)
end
@doc """
Not supported.
"""
def promote_read_replica_d_b_cluster(client, input, options \\ []) do
request(client, "PromoteReadReplicaDBCluster", input, options)
end
@doc """
You might need to reboot your DB instance, usually for maintenance reasons.
For example, if you make certain modifications, or if you change the DB
parameter group associated with the DB instance, you must reboot the instance
for the changes to take effect.
Rebooting a DB instance restarts the database engine service. Rebooting a DB
instance results in a momentary outage, during which the DB instance status is
set to rebooting.
"""
def reboot_d_b_instance(client, input, options \\ []) do
request(client, "RebootDBInstance", input, options)
end
@doc """
Disassociates an Identity and Access Management (IAM) role from a DB cluster.
"""
def remove_role_from_d_b_cluster(client, input, options \\ []) do
request(client, "RemoveRoleFromDBCluster", input, options)
end
@doc """
Removes a source identifier from an existing event notification subscription.
"""
def remove_source_identifier_from_subscription(client, input, options \\ []) do
request(client, "RemoveSourceIdentifierFromSubscription", input, options)
end
@doc """
Removes metadata tags from an Amazon Neptune resource.
"""
def remove_tags_from_resource(client, input, options \\ []) do
request(client, "RemoveTagsFromResource", input, options)
end
@doc """
Modifies the parameters of a DB cluster parameter group to the default value.
To reset specific parameters submit a list of the following: `ParameterName` and
`ApplyMethod`. To reset the entire DB cluster parameter group, specify the
`DBClusterParameterGroupName` and `ResetAllParameters` parameters.
When resetting the entire group, dynamic parameters are updated immediately and
static parameters are set to `pending-reboot` to take effect on the next DB
instance restart or `RebootDBInstance` request. You must call `RebootDBInstance`
for every DB instance in your DB cluster that you want the updated static
parameter to apply to.
"""
def reset_d_b_cluster_parameter_group(client, input, options \\ []) do
request(client, "ResetDBClusterParameterGroup", input, options)
end
@doc """
Modifies the parameters of a DB parameter group to the engine/system default
value.
To reset specific parameters, provide a list of the following: `ParameterName`
and `ApplyMethod`. To reset the entire DB parameter group, specify the
`DBParameterGroup` name and `ResetAllParameters` parameters. When resetting the
entire group, dynamic parameters are updated immediately and static parameters
are set to `pending-reboot` to take effect on the next DB instance restart or
`RebootDBInstance` request.
"""
def reset_d_b_parameter_group(client, input, options \\ []) do
request(client, "ResetDBParameterGroup", input, options)
end
@doc """
Creates a new DB cluster from a DB snapshot or DB cluster snapshot.
If a DB snapshot is specified, the target DB cluster is created from the source
DB snapshot with a default configuration and default security group.
If a DB cluster snapshot is specified, the target DB cluster is created from the
source DB cluster restore point with the same configuration as the original
source DB cluster, except that the new DB cluster is created with the default
security group.
"""
def restore_d_b_cluster_from_snapshot(client, input, options \\ []) do
request(client, "RestoreDBClusterFromSnapshot", input, options)
end
@doc """
Restores a DB cluster to an arbitrary point in time.
Users can restore to any point in time before `LatestRestorableTime` for up to
`BackupRetentionPeriod` days. The target DB cluster is created from the source
DB cluster with the same configuration as the original DB cluster, except that
the new DB cluster is created with the default DB security group.
This action only restores the DB cluster, not the DB instances for that DB
cluster. You must invoke the `CreateDBInstance` action to create DB instances
for the restored DB cluster, specifying the identifier of the restored DB
cluster in `DBClusterIdentifier`. You can create DB instances only after the
`RestoreDBClusterToPointInTime` action has completed and the DB cluster is
available.
"""
def restore_d_b_cluster_to_point_in_time(client, input, options \\ []) do
request(client, "RestoreDBClusterToPointInTime", input, options)
end
@doc """
Starts an Amazon Neptune DB cluster that was stopped using the AWS console, the
AWS CLI stop-db-cluster command, or the StopDBCluster API.
"""
def start_d_b_cluster(client, input, options \\ []) do
request(client, "StartDBCluster", input, options)
end
@doc """
Stops an Amazon Neptune DB cluster.
When you stop a DB cluster, Neptune retains the DB cluster's metadata, including
its endpoints and DB parameter groups.
Neptune also retains the transaction logs so you can do a point-in-time restore
if necessary.
"""
def stop_d_b_cluster(client, input, options \\ []) do
request(client, "StopDBCluster", input, options)
end
@spec request(AWS.Client.t(), binary(), map(), list()) ::
{:ok, map() | nil, map()}
| {:error, term()}
defp request(client, action, input, options) do
client = %{client | service: "rds"}
host = build_host("rds", client)
url = build_url(host, client)
headers = [
{"Host", host},
{"Content-Type", "application/x-www-form-urlencoded"}
]
input = Map.merge(input, %{"Action" => action, "Version" => "2014-10-31"})
payload = encode!(client, input)
headers = AWS.Request.sign_v4(client, "POST", url, headers, payload)
post(client, url, payload, headers, options)
end
defp post(client, url, payload, headers, options) do
case AWS.Client.request(client, :post, url, payload, headers, options) do
{:ok, %{status_code: 200, body: body} = response} ->
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, %{:proto => proto, :port => port}) do
"#{proto}://#{host}:#{port}/"
end
defp encode!(client, payload) do
AWS.Client.encode!(client, payload, :query)
end
defp decode!(client, payload) do
AWS.Client.decode!(client, payload, :xml)
end
end
|
lib/aws/generated/neptune.ex
| 0.868353 | 0.678094 |
neptune.ex
|
starcoder
|
defmodule Unicode.GeneralCategory do
@moduledoc """
Functions to introspect Unicode
general categories for binaries
(Strings) and codepoints.
"""
@behaviour Unicode.Property.Behaviour
alias Unicode.Utils
alias Unicode.GeneralCategory.Derived
@categories Utils.categories()
|> Utils.remove_annotations()
@super_categories @categories
|> Map.keys()
|> Enum.map(&to_string/1)
|> Enum.group_by(&String.slice(&1, 0, 1))
|> Enum.map(fn {k, v} ->
{String.to_atom(k),
Enum.flat_map(v, &Map.get(@categories, String.to_atom(&1))) |> Enum.sort()}
end)
|> Map.new()
@all_categories Map.merge(@categories, @super_categories)
|> Map.merge(Derived.categories())
@doc """
Returns the map of Unicode
character categories.
The category name is the map
key and a list of codepoint
ranges as tuples as the value.
"""
def categories do
@all_categories
end
@doc """
Returns a list of known Unicode
category names.
This function does not return the
names of any category aliases.
"""
@known_categories Map.keys(@all_categories)
def known_categories do
@known_categories
end
@category_alias Utils.property_value_alias()
|> Map.get("gc")
|> Utils.capitalize_values()
|> Utils.atomize_values()
|> Utils.downcase_keys_and_remove_whitespace()
|> Utils.add_canonical_alias()
|> Map.merge(Derived.aliases())
@doc """
Returns a map of aliases for
Unicode categories.
An alias is an alternative name
for referring to a category. Aliases
are resolved by the `fetch/1` and
`get/1` functions.
"""
@impl Unicode.Property.Behaviour
def aliases do
@category_alias
end
@doc """
Returns the Unicode ranges for
a given category as a list of
ranges as 2-tuples.
Aliases are resolved by this function.
Returns either `{:ok, range_list}` or
`:error`.
"""
@impl Unicode.Property.Behaviour
def fetch(category) when is_atom(category) do
Map.fetch(categories(), category)
end
def fetch(category) do
category = Utils.downcase_and_remove_whitespace(category)
category = Map.get(aliases(), category, category)
Map.fetch(categories(), category)
end
@doc """
Returns the Unicode ranges for
a given category as a list of
ranges as 2-tuples.
Aliases are resolved by this function.
Returns either `range_list` or
`nil`.
"""
@impl Unicode.Property.Behaviour
def get(category) do
case fetch(category) do
{:ok, category} -> category
_ -> nil
end
end
@doc """
Return the count of characters in a given
category.
## Example
iex> Unicode.GeneralCategory.count(:Ll)
2155
iex> Unicode.GeneralCategory.count(:Nd)
650
"""
@impl Unicode.Property.Behaviour
def count(category) do
with {:ok, category} <- fetch(category) do
Enum.reduce(category, 0, fn {from, to}, acc -> acc + to - from + 1 end)
end
end
@doc """
Returns the category name(s) for the
given binary or codepoint.
In the case of a codepoint, a single
category name is returned.
For a binary a list of distinct category
names represented by the graphemes in
the binary is returned.
Only concrete general categories are considered,
derived categories (:all, :ascii, :assigned etc)
are not considered.
"""
def category(string) when is_binary(string) do
string
|> String.to_charlist()
|> Enum.map(&category/1)
|> Enum.uniq()
end
for {category, ranges} <- @categories do
def category(codepoint) when unquote(Utils.ranges_to_guard_clause(ranges)) do
unquote(category)
end
end
def category(codepoint) when is_integer(codepoint) and codepoint in 0..0x10FFFF do
:Cn
end
end
|
lib/unicode/category.ex
| 0.91384 | 0.459076 |
category.ex
|
starcoder
|
defmodule Exexif.Data.Gps do
@moduledoc """
Internal representation of GPS tag in the EXIF.
"""
@type t :: %Exexif.Data.Gps{
gps_version_id: any(),
gps_latitude_ref: any(),
gps_latitude: any(),
gps_longitude_ref: any(),
gps_longitude: any(),
gps_altitude_ref: any(),
gps_altitude: any(),
gps_time_stamp: any(),
gps_satellites: any(),
gps_status: any(),
gps_measure_mode: any(),
gps_dop: any(),
gps_speed_ref: any(),
gps_speed: any(),
gps_track_ref: any(),
gps_track: any(),
gps_img_direction_ref: any(),
gps_img_direction: any(),
gps_map_datum: any(),
gps_dest_latitude_ref: any(),
gps_dest_latitude: any(),
gps_dest_longitude_ref: any(),
gps_dest_longitude: any(),
gps_dest_bearing_ref: any(),
gps_dest_bearing: any(),
gps_dest_distance_ref: any(),
gps_dest_distance: any(),
gps_processing_method: any(),
gps_area_information: any(),
gps_date_stamp: any(),
gps_differential: any(),
gps_h_positioning_error: any()
}
@fields [
:gps_version_id,
:gps_latitude_ref,
:gps_latitude,
:gps_longitude_ref,
:gps_longitude,
:gps_altitude_ref,
:gps_altitude,
:gps_time_stamp,
:gps_satellites,
:gps_status,
:gps_measure_mode,
:gps_dop,
:gps_speed_ref,
:gps_speed,
:gps_track_ref,
:gps_track,
:gps_img_direction_ref,
:gps_img_direction,
:gps_map_datum,
:gps_dest_latitude_ref,
:gps_dest_latitude,
:gps_dest_longitude_ref,
:gps_dest_longitude,
:gps_dest_bearing_ref,
:gps_dest_bearing,
:gps_dest_distance_ref,
:gps_dest_distance,
:gps_processing_method,
:gps_area_information,
:gps_date_stamp,
:gps_differential,
:gps_h_positioning_error
]
@spec fields :: [atom()]
@doc false
def fields, do: @fields
defstruct @fields
@spec inspect(data :: t()) :: String.t()
@doc """
Returns the human-readable representation of GPS data, e. g. "41°23´16˝N,2°11´50˝E".
"""
def inspect(%Exexif.Data.Gps{gps_latitude: nil} = _data), do: ""
def inspect(%Exexif.Data.Gps{gps_longitude: nil} = _data), do: ""
def inspect(%Exexif.Data.Gps{} = data) do
# gps_latitude: [41, 23, 16.019], gps_latitude_ref: "N",
# gps_longitude: [2, 11, 49.584], gps_longitude_ref: "E"
# 41 deg 23' 16.02" N, 2 deg 11' 49.58" E
[lat_d, lat_m, lat_s] = data.gps_latitude
[lon_d, lon_m, lon_s] = data.gps_longitude
[
~s|#{lat_d}°#{lat_m}´#{round(lat_s)}˝#{data.gps_latitude_ref || "N"}|,
~s|#{lon_d}°#{lon_m}´#{round(lon_s)}˝#{data.gps_longitude_ref || "N"}|
]
|> Enum.join(",")
end
defimpl String.Chars, for: Exexif.Data.Gps do
@moduledoc false
alias Exexif.Data.Gps
@spec to_string(Gps.t()) :: String.t()
def to_string(data), do: Gps.inspect(data)
end
end
|
lib/exexif/data/gps.ex
| 0.765023 | 0.50061 |
gps.ex
|
starcoder
|
defmodule Temp do
@type options :: nil | Path.t | map
@doc """
Returns `:ok` when the tracking server used to track temporary files started properly.
"""
@pdict_key :"$__temp_tracker__"
@spec track :: Agent.on_start
def track() do
case Process.get(@pdict_key) do
nil ->
start_tracker()
v ->
{:ok, v}
end
end
defp start_tracker() do
case GenServer.start_link(Temp.Tracker, nil, []) do
{:ok, pid} ->
Process.put(@pdict_key, pid)
{:ok, pid}
err ->
err
end
end
@doc """
Same as `track/1`, but raises an exception on failure. Otherwise, returns `:ok`
"""
@spec track! :: pid | no_return
def track!() do
case track() do
{:ok, pid} -> pid
{:error, err} -> raise Temp.Error, message: err
end
end
@doc """
Return the paths currently tracked.
"""
@spec tracked :: Set.t
def tracked(tracker \\ get_tracker!()) do
GenServer.call(tracker, :tracked)
end
@doc """
Cleans up the temporary files tracked.
"""
@spec cleanup(pid, Keyword.t) :: :ok | {:error, any}
def cleanup(tracker \\ get_tracker!(), opts \\ []) do
GenServer.call(tracker, :cleanup, opts[:timeout] || :infinity)
end
@doc """
Returns a `{:ok, path}` where `path` is a path that can be used freely in the
system temporary directory, or `{:error, reason}` if it fails to get the
system temporary directory.
## Options
The following options can be used to customize the generated path
* `:prefix` - prepends the given prefix to the path
* `:suffix` - appends the given suffix to the path,
this is useful to generate a file with a particular extension
"""
@spec path(options) :: {:ok, Path.t} | {:error, String.t}
def path(options \\ nil) do
case generate_name(options, "f") do
{:ok, path, _} -> {:ok, path}
err -> err
end
end
@doc """
Same as `path/1`, but raises an exception on failure. Otherwise, returns a temporary path.
"""
@spec path!(options) :: Path.t | no_return
def path!(options \\ nil) do
case path(options) do
{:ok, path} -> path
{:error, err} -> raise Temp.Error, message: err
end
end
@doc """
Returns `{:ok, fd, file_path}` if no callback is passed, or `{:ok, file_path}`
if callback is passed, where `fd` is the file descriptor of a temporary file
and `file_path` is the path of the temporary file.
When no callback is passed, the file descriptor should be closed.
Returns `{:error, reason}` if a failure occurs.
## Options
See `path/1`.
"""
@spec open(options, nil | (File.io_device -> any)) :: {:ok, Path.t} | {:ok, File.io_device, Path.t} | {:error, any}
def open(options \\ nil, func \\ nil) do
case generate_name(options, "f") do
{:ok, path, options} ->
options = Map.put(options, :mode, options[:mode] || [:read, :write])
ret = if func do
File.open(path, options[:mode], func)
else
File.open(path, options[:mode])
end
case ret do
{:ok, res} ->
if tracker = get_tracker(), do: register_path(tracker, path)
if func, do: {:ok, path}, else: {:ok, res, path}
err -> err
end
err -> err
end
end
@doc """
Same as `open/1`, but raises an exception on failure.
"""
@spec open!(options, pid | nil) :: Path.t | {File.io_device, Path.t} | no_return
def open!(options \\ nil, func \\ nil) do
case open(options, func) do
{:ok, res, path} -> {res, path}
{:ok, path} -> path
{:error, err} -> raise Temp.Error, message: err
end
end
@doc """
Returns `{:ok, dir_path}` where `dir_path` is the path is the path of the
created temporary directory.
Returns `{:error, reason}` if a failure occurs.
## Options
See `path/1`.
"""
@spec mkdir(options) :: {:ok, Path.t} | {:error, any}
def mkdir(options \\ %{}) do
case generate_name(options, "d") do
{:ok, path, _} ->
case File.mkdir path do
:ok ->
if tracker = get_tracker(), do: register_path(tracker, path)
{:ok, path}
err -> err
end
err -> err
end
end
@doc """
Same as `mkdir/1`, but raises an exception on failure. Otherwise, returns
a temporary directory path.
"""
@spec mkdir!(options) :: Path.t | no_return
def mkdir!(options \\ %{}) do
case mkdir(options) do
{:ok, path} ->
if tracker = get_tracker(), do: register_path(tracker, path)
path
{:error, err} -> raise Temp.Error, message: err
end
end
@spec generate_name(options, Path.t) :: {:ok, Path.t, map | Keyword.t} | {:error, String.t}
defp generate_name(options, default_prefix)
defp generate_name(options, default_prefix) when is_list(options) do
generate_name(Enum.into(options,%{}), default_prefix)
end
defp generate_name(options, default_prefix) do
case prefix(options) do
{:ok, path} ->
affixes = parse_affixes(options, default_prefix)
parts = [timestamp(), "-", :os.getpid(), "-", random_string()]
parts =
if affixes[:prefix] do
[affixes[:prefix], "-"] ++ parts
else
parts
end
parts = add_suffix(parts, affixes[:suffix])
name = Path.join(path, Enum.join(parts))
{:ok, name, affixes}
err -> err
end
end
defp add_suffix(parts, suffix)
defp add_suffix(parts, nil), do: parts
defp add_suffix(parts, ("." <> _suffix) = suffix), do: parts ++ [suffix]
defp add_suffix(parts, suffix), do: parts ++ ["-", suffix]
defp prefix(%{basedir: dir}), do: {:ok, dir}
defp prefix(_) do
case System.tmp_dir do
nil -> {:error, "no tmp_dir readable"}
path -> {:ok, path}
end
end
defp parse_affixes(nil, default_prefix), do: %{prefix: default_prefix}
defp parse_affixes(affixes, _) when is_bitstring(affixes), do: %{prefix: affixes, suffix: nil}
defp parse_affixes(affixes, default_prefix) when is_map(affixes) do
affixes
|> Map.put(:prefix, affixes[:prefix] || default_prefix)
|> Map.put(:suffix, affixes[:suffix] || nil)
end
defp parse_affixes(_, default_prefix) do
%{prefix: default_prefix, suffix: nil}
end
defp get_tracker do
Process.get(@pdict_key)
end
defp get_tracker!() do
case get_tracker() do
nil ->
raise Temp.Error, message: "temp tracker not started"
pid ->
pid
end
end
defp register_path(tracker, path) do
GenServer.call(tracker, {:add, path})
end
defp timestamp do
{ms, s, _} = :os.timestamp
Integer.to_string(ms * 1_000_000 + s)
end
defp random_string do
Integer.to_string(rand_uniform(0x100000000), 36) |> String.downcase
end
if :erlang.system_info(:otp_release) >= '18' do
defp rand_uniform(num) do
:rand.uniform(num)
end
else
defp rand_uniform(num) do
:random.uniform(num)
end
end
end
|
lib/temp.ex
| 0.79653 | 0.451266 |
temp.ex
|
starcoder
|
defmodule Cldr.AcceptLanguage do
@moduledoc """
Tokenizer and parser for HTTP `Accept-Language` header values as defined in
[rfc2616](https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4).
The Accept-Language request-header field is similar to Accept, but restricts
the set of natural languages that are preferred as a response to the request.
Language tags function are provided in `Cldr.LanguageTag`.
The format of an `Accept-Language` header is as follows in `ABNF` format:
Accept-Language = "Accept-Language" ":"
1#( language-range [ ";" "q" "=" qvalue ] )
language-range = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" )
Each language-range MAY be given an associated quality value which represents an
estimate of the user's preference for the languages specified by that range. The
quality value defaults to "q=1". For example,
Accept-Language: da, en-gb;q=0.8, en;q=0.7
would mean: "I prefer Danish, but will accept British English and other types of English."
"""
alias Cldr.Locale
alias Cldr.LanguageTag
@default_quality 1.0
@low_quality 0.2
@doc """
Splits the language ranges for an `Accept-Language` header
value into tuples `{quality, language}`.
* `accept-language` is any string in the format defined by [rfc2616](https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4)
## Example
iex> Cldr.AcceptLanguage.tokenize "da,zh-TW;q=0.3"
[{1.0, "da"}, {0.3, "zh-tw"}]
"""
@spec tokenize(String.t()) :: [{float(), String.t()}, ...]
@language_separator ","
def tokenize(accept_language) do
accept_language
|> String.downcase()
|> remove_whitespace
|> String.split(@language_separator)
|> Enum.reject(&is_nil/1)
|> Enum.reject(&String.starts_with?(&1, "*"))
|> Enum.map(&token_tuple/1)
end
@quality_separator ";q="
defp token_tuple(language) do
case String.split(language, @quality_separator) do
[language, quality] ->
{parse_quality(quality), language}
[language] ->
{@default_quality, language}
[language | _rest] ->
{@low_quality, language}
end
end
@doc """
Parses an `Accept-Language` header value in its string
or tokenized form to return a tuple of the form
`{:ok, [{quality, %Cldr.LanguageTag{}}, ...]}` sorted by quality.
## Arguments
* `accept-language` is any string in the format defined by
[rfc2616](https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4)
* `backend` is any module that includes `use Cldr` and therefore
is a `Cldr` backend module
## Returns
* `{:ok, [{quality, language_tag}, ...]}` or
* `{:error, {Cldr.AcceptLanguageError, String.t}}`
If at least one valid language tag is found but errors are also
detected on one more more tags, an `{ok, list}` tuple is returned
wuth an error tuple for each invalid tag added at the end of the list.
## Example
iex> Cldr.AcceptLanguage.parse("da,zh-TW;q=0.3", TestBackend.Cldr)
{:ok,
[
{1.0,
%Cldr.LanguageTag{
canonical_locale_name: "da-Latn-DK",
cldr_locale_name: "da",
language_subtags: [],
extensions: %{},
gettext_locale_name: nil,
language: "da",
locale: %{},
private_use: [],
rbnf_locale_name: "da",
requested_locale_name: "da",
script: "Latn",
territory: "DK",
transform: %{},
language_variant: nil
}},
{0.3,
%Cldr.LanguageTag{
canonical_locale_name: "zh-Hant-TW",
cldr_locale_name: "zh-Hant",
language_subtags: [],
extensions: %{},
gettext_locale_name: nil,
language: "zh",
locale: %{},
private_use: [],
rbnf_locale_name: "zh-Hant",
requested_locale_name: "zh-TW",
script: "Hant",
territory: "TW",
transform: %{},
language_variant: nil
}}
]}
iex> Cldr.AcceptLanguage.parse("invalid_tag", TestBackend.Cldr)
{:error,
{Cldr.LanguageTag.ParseError,
"Expected a BCP47 language tag. Could not parse the remaining \\"g\\" starting at position 11"}}
iex> Cldr.AcceptLanguage.parse("da,zh-TW;q=0.3,invalid_tag", TestBackend.Cldr)
{:ok,
[
{1.0,
%Cldr.LanguageTag{
canonical_locale_name: "da-Latn-DK",
cldr_locale_name: "da",
language_subtags: [],
extensions: %{},
gettext_locale_name: nil,
language: "da",
locale: %{},
private_use: [],
rbnf_locale_name: "da",
requested_locale_name: "da",
script: "Latn",
territory: "DK",
transform: %{},
language_variant: nil
}},
{0.3,
%Cldr.LanguageTag{
canonical_locale_name: "zh-Hant-TW",
cldr_locale_name: "zh-Hant",
language_subtags: [],
extensions: %{},
gettext_locale_name: nil,
language: "zh",
locale: %{},
private_use: [],
rbnf_locale_name: "zh-Hant",
requested_locale_name: "zh-TW",
script: "Hant",
territory: "TW",
transform: %{},
language_variant: nil
}},
{:error,
{Cldr.LanguageTag.ParseError,
"Expected a BCP47 language tag. Could not parse the remaining \\"g\\" starting at position 11"}}
]}
"""
@spec parse([{float(), String.t()}, ...] | String.t(), Cldr.backend()) ::
{:ok,
[
{float(), LanguageTag.t()} | {:error, {Cldr.InvalidLanguageTag, String.t()}},
...
]}
| {:error, {Cldr.AcceptLanguageError, String.t()}}
def parse(tokens, backend) when is_list(tokens) do
accept_language =
tokens
|> parse_language_tags(backend)
|> sort_by_quality
case accept_language do
[error: reason] ->
{:error, reason}
_ ->
{:ok, accept_language}
end
end
def parse(string, backend) when is_binary(string) do
string
|> tokenize
|> parse(backend)
end
@doc """
Parses an `Accept-Language` header value in its string
or tokenized form to produce a list of tuples of the form
`[{quality, %Cldr.LanguageTag{}}, ...]` sorted by quality
in decending order.
* `accept-language` is any string in the format defined by [rfc2616](https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4)
Returns:
* `{:ok, [{quality, language_tag}, ...]}` or
* raises a `Cldr.AcceptLanguageError` exception
If at least one valid language tag is found but errors are also
detected on one more more tags, an `{ok, list}` tuple is returned
wuth an error tuple for each invalid tag added at the end of the list.
## Example
iex> Cldr.AcceptLanguage.parse!("da,zh-TW;q=0.3", TestBackend.Cldr)
[
{1.0,
%Cldr.LanguageTag{
canonical_locale_name: "da-Latn-DK",
cldr_locale_name: "da",
language_subtags: [],
extensions: %{},
gettext_locale_name: nil,
language: "da",
locale: %{},
private_use: [],
rbnf_locale_name: "da",
requested_locale_name: "da",
script: "Latn",
territory: "DK",
transform: %{},
language_variant: nil
}},
{0.3,
%Cldr.LanguageTag{
canonical_locale_name: "zh-Hant-TW",
cldr_locale_name: "zh-Hant",
language_subtags: [],
extensions: %{},
gettext_locale_name: nil,
language: "zh",
locale: %{},
private_use: [],
rbnf_locale_name: "zh-Hant",
requested_locale_name: "zh-TW",
script: "Hant",
territory: "TW",
transform: %{},
language_variant: nil
}}
]
Cldr.AcceptLanguage.parse! "invalid_tag"
** (Cldr.AcceptLanguageError) "Expected a BCP47 language tag. Could not parse the remaining "g" starting at position 11
(ex_cldr) lib/cldr/accept_language.ex:304: Cldr.AcceptLanguage.parse!/1
iex> Cldr.AcceptLanguage.parse!("da,zh-TW;q=0.3,invalid_tag", TestBackend.Cldr)
[
{1.0,
%Cldr.LanguageTag{
canonical_locale_name: "da-Latn-DK",
cldr_locale_name: "da",
language_subtags: [],
extensions: %{},
gettext_locale_name: nil,
language: "da",
locale: %{},
private_use: [],
rbnf_locale_name: "da",
requested_locale_name: "da",
script: "Latn",
territory: "DK",
transform: %{},
language_variant: nil
}},
{0.3,
%Cldr.LanguageTag{
canonical_locale_name: "zh-Hant-TW",
cldr_locale_name: "zh-Hant",
language_subtags: [],
extensions: %{},
gettext_locale_name: nil,
language: "zh",
locale: %{},
private_use: [],
rbnf_locale_name: "zh-Hant",
requested_locale_name: "zh-TW",
script: "Hant",
territory: "TW",
transform: %{},
language_variant: nil
}},
{:error,
{Cldr.LanguageTag.ParseError,
"Expected a BCP47 language tag. Could not parse the remaining \\"g\\" starting at position 11"}}
]
"""
def parse!(accept_language, backend) do
case parse(accept_language, backend) do
{:ok, parse_result} -> parse_result
{:error, {exception, reason}} -> raise exception, reason
end
end
@doc """
Parse an `Accept-Language` string and return the best match for
a configured `Cldr` locale.
* `accept_langauge` is a string representing an accept language header
Returns:
* `{:ok, language_tag}` or
* `{:error, reason}`
## Examples
iex> Cldr.AcceptLanguage.best_match("da;q=0.1,zh-TW;q=0.3", TestBackend.Cldr)
{:ok,
%Cldr.LanguageTag{
canonical_locale_name: "zh-Hant-TW",
cldr_locale_name: "zh-Hant",
language_subtags: [],
extensions: %{},
gettext_locale_name: nil,
language: "zh",
locale: %{},
private_use: [],
rbnf_locale_name: "zh-Hant",
requested_locale_name: "zh-TW",
script: "Hant",
territory: "TW",
transform: %{},
language_variant: nil
}}
iex(4)> Cldr.AcceptLanguage.best_match("da;q=0.1,zh-TW;q=0.3", TestBackend.Cldr)
{:ok,
%Cldr.LanguageTag{
canonical_locale_name: "zh-Hant-TW",
cldr_locale_name: "zh-Hant",
language_subtags: [],
extensions: %{},
gettext_locale_name: nil,
language: "zh",
locale: %{},
private_use: [],
rbnf_locale_name: "zh-Hant",
requested_locale_name: "zh-TW",
script: "Hant",
territory: "TW",
transform: %{},
language_variant: nil
}}
iex> Cldr.AcceptLanguage.best_match("xx,yy;q=0.3", TestBackend.Cldr)
{:error,
{Cldr.NoMatchingLocale,
"No configured locale could be matched to \\"xx,yy;q=0.3\\""}}
iex> Cldr.AcceptLanguage.best_match("invalid_tag", TestBackend.Cldr)
{:error, {Cldr.LanguageTag.ParseError,
"Expected a BCP47 language tag. Could not parse the remaining \\"g\\" starting at position 11"}}
"""
@spec best_match(String.t(), Cldr.backend()) ::
{:ok, LanguageTag.t()} | {:error, {Cldr.AcceptLanguageError, String.t()}}
def best_match(accept_language, backend) when is_binary(accept_language) do
with {:ok, languages} <- parse(accept_language, backend) do
candidates =
Enum.filter(languages, fn
{priority, %LanguageTag{cldr_locale_name: locale_name}}
when is_float(priority) and not is_nil(locale_name) ->
true
_ ->
false
end)
case candidates do
[{_priority, language_tag} | _] ->
{:ok, language_tag}
_ ->
{
:error,
{
Cldr.NoMatchingLocale,
"No configured locale could be matched to #{inspect(accept_language)}"
}
}
end
else
{:error, reason} -> {:error, reason}
end
end
@doc """
Filters the returned results of `parse/1` to return
only the error tuples.
## Example
iex> Cldr.AcceptLanguage.parse!("da,zh-TW;q=0.3,invalid_tag", TestBackend.Cldr)
...> |> Cldr.AcceptLanguage.errors
[
error: {Cldr.LanguageTag.ParseError,
"Expected a BCP47 language tag. Could not parse the remaining \\"g\\" starting at position 11"}
]
"""
@spec errors([tuple(), ...]) :: [{:error, {Cldr.InvalidLanguageTag, String.t()}}, ...]
def errors(parse_result) when is_list(parse_result) do
Enum.filter(parse_result, fn
{:error, _} -> true
_ -> false
end)
end
defp parse_quality(quality_string) do
case Float.parse(quality_string) do
:error -> @low_quality
{quality, _} -> quality
end
end
defp parse_language_tags(tokens, backend) do
Enum.map(tokens, fn {quality, language_tag} ->
case Locale.canonical_language_tag(language_tag, backend) do
{:ok, tag} ->
{quality, tag}
{:error, reason} ->
{:error, reason}
end
end)
end
defp remove_whitespace(accept_language) do
String.replace(accept_language, " ", "")
end
def sort_by_quality(tokens) do
Enum.sort(tokens, fn
{:error, _}, {_quality_2, _} -> false
{_quality_2, _}, {:error, _} -> true
{quality_1, _}, {quality_2, _} when quality_1 == quality_2 -> true
{quality_1, _}, {quality_2, _} -> quality_1 > quality_2
end)
end
end
|
lib/cldr/accept_language.ex
| 0.905022 | 0.464659 |
accept_language.ex
|
starcoder
|
defmodule Alchemetrics.Annotation do
alias Alchemetrics.Annotation.InstrumentedFunctionList
alias Alchemetrics.Annotation.Function
@moduledoc """
Annotations allow you to automatically report the amount of calls and time spent on a particular function.
They work with multiple clauses, guard clauses, recursion, function heads, and so on. However, only public functions can be annotated. The return value of annotated functions does not change.
## Example
To annotate a function simply mark it with the tag `@alchemetrics instrument_function: true`. All functions defined in the module with the same name and arity will also be marked for instrumentation.
```elixir
defmodule AnnotatedModule do
use Alchemetrics.Annotation
@alchemetrics instrument_function: true
def annotated_function, do: IO.puts "I will be instrumented :)"
def not_annotated, do: IO.puts "I will not be instrumented :("
@alchemetrics instrument_function: true
def multiple_clauses(a) when a > 3, do: a*2
def multiple_clauses(a), do: a*4
@alchemetrics instrument_function: true
def recursive_function([]), do: nil
def recursive_function([_|t]), do: recursive_function(t)
@alchemetrics instrument_function: true
def head(a \\ 1)
def head(a) when a > 2, do: a*2
def head(a), do: a
end
```
## Report Format
The annotated functions will be reported in the following formats:
- `function_time_spent: "Elixir.Module.function/arity"`
- `function_calls: "Elixir.Module.function/arity"`
```elixir
iex(1)> Alchemetrics.ConsoleBackend.enable
iex(2)> AnnotatedModule.annotated_function
I will be instrumented :)
:ok
iex(3)>
%{datapoint: :last_interval, function_calls: "Elixir.AnnotatedModule.annotated_function/0", value: 1}
%{datapoint: :total, function_calls: "Elixir.AnnotatedModule.annotated_function/0", value: 1}
%{datapoint: :avg, function_time_spent: "Elixir.AnnotatedModule.annotated_function/0", value: 0}
%{datapoint: :max, function_time_spent: "Elixir.AnnotatedModule.annotated_function/0", value: 0}
%{datapoint: :min, function_time_spent: "Elixir.AnnotatedModule.annotated_function/0", value: 0}
%{datapoint: :p95, function_time_spent: "Elixir.AnnotatedModule.annotated_function/0", value: 0}
%{datapoint: :p99, function_time_spent: "Elixir.AnnotatedModule.annotated_function/0", value: 0}
%{datapoint: :last_interval, function_time_spent: "Elixir.AnnotatedModule.annotated_function/0", value: 4541}
%{datapoint: :total, function_time_spent: "Elixir.AnnotatedModule.annotated_function/0", value: 4541}
```
"""
defmacro __using__(_options) do
quote do
InstrumentedFunctionList.track_module(__MODULE__)
@before_compile Alchemetrics.Annotation
@on_definition Alchemetrics.Annotation
end
end
def __on_definition__(env, kind, name, args, guards, body) do
if !is_nil(body) do
function = Alchemetrics.Annotation.Function.new(env, kind, name, args, guards, body)
if Function.has_metric_tag?(function) || Function.similar_functions_marked_for_instrumentation?(function) do
Function.mark_for_instrumentation(function)
end
end
end
defmacro __before_compile__(env) do
functions_in_ast_format =
InstrumentedFunctionList.get_all(env.module)
|> Enum.reverse
|> Enum.map(fn(%Function{} = function) ->
function
|> Function.inject_code_in_the_begining(quote do
function = unquote(Macro.escape(function))
alchemetrics_internal_function_call_start_time__ = System.monotonic_time()
alchemetrics_internal_function_name__ = "#{function.module}.#{function.name}/#{function.arity}"
Alchemetrics.increment(function_calls: alchemetrics_internal_function_name__)
end)
|> Function.inject_code_in_the_end(quote do
alchemetrics_internal_function_call_end_time__ =
(System.monotonic_time() - alchemetrics_internal_function_call_start_time__)
|> System.convert_time_unit(:native, :micro_seconds)
|> Alchemetrics.report(function_time_spent: alchemetrics_internal_function_name__)
end)
|> Function.transform_to_ast
end)
quote do
unquote_splicing(functions_in_ast_format)
end
end
end
|
lib/alchemetrics/annotation/annotation.ex
| 0.881825 | 0.926835 |
annotation.ex
|
starcoder
|
defmodule Bodyguard do
@moduledoc """
Authorize actions at the boundary of a context
Please see the [README](readme.html).
"""
@type opts :: keyword | %{optional(atom) => any}
@doc """
Authorize a user's action.
Returns `:ok` on success, and `{:error, reason}` on failure.
If `params` is a keyword list, it is converted to a map before passing down
to the `c:Bodyguard.Policy.authorize/3` callback. Otherwise, `params` is not
changed.
"""
@spec permit(policy :: module, action :: atom, user :: any, params :: any) ::
:ok | {:error, any} | no_return()
def permit(policy, action, user, params \\ []) do
params = try_to_mapify(params)
policy
|> apply(:authorize, [action, user, params])
|> resolve_result()
end
@doc """
The same as `permit/4`, but raises `Bodyguard.NotAuthorizedError` on
authorization failure.
Returns `:ok` on success.
If `params` is a keyword list, it is converted to a map before passing down
to the `c:Bodyguard.Policy.authorize/3` callback. Otherwise, `params` is not
changed.
## Options
* `error_message` – a string to describe the error (default "not authorized")
* `error_status` – the HTTP status code to raise with the error (default 403)
"""
@spec permit!(policy :: module, action :: atom, user :: any, params :: any, opts :: opts) ::
:ok | no_return()
def permit!(policy, action, user, params \\ [], opts \\ []) do
params = try_to_mapify(params)
opts = Enum.into(opts, %{})
{error_message, params} =
get_option("Bodyguard.permit!/5", params, opts, :error_message, "not authorized")
{error_status, params} = get_option("Bodyguard.permit!/5", params, opts, :error_status, 403)
case permit(policy, action, user, params) do
:ok ->
:ok
error ->
raise Bodyguard.NotAuthorizedError,
message: error_message,
status: error_status,
reason: error
end
end
@doc """
The same as `permit/4`, but returns a boolean.
"""
@spec permit?(policy :: module, action :: atom, user :: any, params :: any) :: boolean
def permit?(policy, action, user, params \\ []) do
case permit(policy, action, user, params) do
:ok -> true
_ -> false
end
end
@doc """
Filter a query down to user-accessible items.
The `query` is introspected by Bodyguard in an attempt to automatically
determine the schema type. To succeed, `query` must be an atom (schema
module name), an `Ecto.Query`, or a list of structs.
This function exists primarily as a helper to `import` into a context and
gain access to scoping for all schemas.
defmodule MyApp.Blog do
import Bodyguard
def list_user_posts(user) do
Blog.Post
|> scope(user) # <-- defers to MyApp.Blog.Post.scope/3
|> where(draft: false)
|> Repo.all
end
end
If `params` is a keyword list, it is converted to a map before passing down
to the `c:Bodyguard.Policy.authorize/3` callback. Otherwise, `params` is not
changed.
#### Options
* `schema` - if the schema of the `query` cannot be determined, you must
manually specify the schema here
"""
@spec scope(query :: any, user :: any, params :: any, opts :: opts) :: any
def scope(query, user, params \\ [], opts \\ []) do
params = try_to_mapify(params)
opts = Enum.into(opts, %{})
{schema, params} =
get_option("Bodyguard.scope/4", params, opts, :schema, resolve_schema(query))
apply(schema, :scope, [query, user, params])
end
# Private
# Attempts to convert a keyword list to a map
defp try_to_mapify(params) do
cond do
Keyword.keyword?(params) -> Enum.into(params, %{})
true -> params
end
end
# Pulls an option from the `params` argument if possible, falling back on
# the new `opts` argument. Returns {option_value, params}
defp get_option(name, params, opts, key, default) do
if is_map(params) and Map.has_key?(params, key) do
# Treat the new `params` as the old `opts`
IO.puts(
"DEPRECATION WARNING - Please pass the #{inspect(key)} option to the new `opts` argument in #{
name
}."
)
Map.pop(params, key, default)
else
# Ignore `params` and just get it from `opts`
{Map.get(opts, key, default), params}
end
end
# Ecto query (this feels dirty...)
defp resolve_schema(%{__struct__: Ecto.Query, from: {_source, schema}})
when is_atom(schema) and not is_nil(schema),
do: schema
# List of structs
defp resolve_schema([%{__struct__: schema} | _rest]), do: schema
# Schema module itself
defp resolve_schema(schema) when is_atom(schema), do: schema
# Unable to determine
defp resolve_schema(unknown) do
raise ArgumentError, "Cannot automatically determine the schema of
#{inspect(unknown)} - specify the :schema option"
end
# Coerce auth results
defp resolve_result(true), do: :ok
defp resolve_result(:ok), do: :ok
defp resolve_result(false), do: {:error, :unauthorized}
defp resolve_result(:error), do: {:error, :unauthorized}
defp resolve_result({:error, reason}), do: {:error, reason}
defp resolve_result(invalid), do: raise("Unexpected authorization result: #{inspect(invalid)}")
end
|
lib/bodyguard.ex
| 0.878164 | 0.516778 |
bodyguard.ex
|
starcoder
|
defmodule Issues.TableFormatter do
import Enum, only: [ each: 2, map: 2, map_join: 3, max: 1 ]
@doc """
Takes a list of row data, where each row is a HashDict, and a list of
headers. Prints a table to STDOUT of the data from each row
identified by each header. That is, each header identifies a column,
and those columns are extracted and printed from the rows.
We calculate the width of each column to fit the longest element
in that column.
"""
def print_table_for_columns(rows, headers) do
data_by_columns = split_into_columns(rows, headers)
columns_widths = widths_of(data_by_columns)
format = format_for(columns_widths)
puts_one_line_in_columns headers, format
IO.puts separator(columns_widths)
puts_in_columns data_by_columns, format
end
@doc """
Given a list of rows, where each row contains a keyed list
of columns, return a list containing lists of the data in
each column. The `headers` parameter contains the
list of columns to extract
## Example
iex> list = [Enum.into([{"a", "1"},{"b", "2"},{"c", "3"}], HashDict.new),
...> Enum.into([{"a", "4"},{"b", "5"},{"c", "6"}], HashDict.new)]
iex> Issues.TableFormatter.split_into_columns(list, [ "a", "b", "c" ])
[ ["1", "4"], ["2", "5"], ["3", "6"] ]
"""
def split_into_columns(rows, headers) do
for header <- headers do
for row <- rows, do: printable(row[header])
end
end
@doc """
Return a binary (string) version of our parameter.
## Examples
iex> Issues.TableFormatter.printable("a")
"a"
iex> Issues.TableFormatter.printable(99)
"99"
"""
def printable(str) when is_binary(str), do: str
def printable(str), do: to_string(str)
@doc """
Given a list containing sublists, where each sublist contains the data for
a column, return a list containing the maximum width of each column
## Example
iex> data = [ [ "cat", "wombat", "elk"], ["mongoose", "ant", "gnu"]]
iex> Issues.TableFormatter.widths_of(data)
[ 6, 8 ]
"""
def widths_of(columns) do
for column <- columns, do: column |> map(&String.length/1) |> max
end
def format_for(column_widths) do
map_join(column_widths, " | ", fn width -> "~-#{width}s" end) <> "~n"
end
def separator(column_widths) do
map_join(column_widths, "-+-", fn width -> List.duplicate("-", width) end)
end
def puts_in_columns(data_by_columns, format) do
data_by_columns
|> List.zip
|> map(&Tuple.to_list/1)
|> each(&puts_one_line_in_columns(&1, format))
end
def puts_one_line_in_columns(fields, format) do
:io.format(format, fields)
end
end
|
programming_elixir/issues/lib/issues/table_formatter.ex
| 0.870198 | 0.811452 |
table_formatter.ex
|
starcoder
|
defmodule BoardingStatus do
@moduledoc """
Structure to represent the status of a single train
"""
require Logger
import ConfigHelpers
defstruct scheduled_time: :unknown,
predicted_time: :unknown,
route_id: :unknown,
trip_id: :unknown,
direction_id: :unknown,
stop_id: :unknown,
stop_sequence: :unknown,
status: :unknown,
track: "",
added?: false
@type route_id :: binary
@type trip_id :: binary
@type stop_id :: binary
@type direction_id :: 0 | 1
@typedoc """
* scheduled_time: When the train is supposed to leave the station
* predicted_time: When we expect the train to leave the station
* route_id: GTFS route ID
* trip_id: GTFS trip ID, or some other value for added trips
* direction_id: GTFS direction ID
* stop_id: GTFS stop ID
* status: atom representing what appears on the big board in the station
* track: the track the train will be on, or empty if not provided
* added?: true if the trip isn't included in the GTFS schedule
"""
@type t :: %__MODULE__{
scheduled_time: :unknown | DateTime.t(),
predicted_time: :unknown | DateTime.t(),
route_id: :unknown | route_id,
trip_id: :unknown | trip_id,
direction_id: :unknown | direction_id,
stop_id: :unknown | stop_id,
stop_sequence: :unknown | non_neg_integer,
status: String.t() | :unknown,
track: String.t(),
added?: boolean
}
@doc """
Builds a BoardingStatus from the data we get out of Firebase.
Firebase keys, and their mappings to BoardingStatus fields:
* `gtfs_departure_time`: an ISO DateTime, maps to `scheduled_time`
* `gtfs_trip_id`: maps to `trip_id` (and `route_id`/`direction_id`)
* `gtfsrt_departure`: an ISO DateTime, maps to `predicted_time`
(will use the scheduled_time if empty)
* `status`: maps to `status`
* `track`: maps to `track
There are examples of this data in test/fixtures/firebase.json
"""
@spec from_firebase(map) :: {:ok, t} | :ignore | :error
def from_firebase(
%{
"gtfs_departure_time" => schedule_time_iso,
"gtfs_stop_name" => stop_name,
"gtfsrt_departure" => predicted_time_iso,
"status" => status,
"track" => track
} = map
) do
with :ok <- validate_movement_type(map),
:ok <- validate_is_stopping(map),
:ok <- validate_route_id(map),
:ok <- validate_status(status),
{:ok, scheduled_time, _} <- DateTime.from_iso8601(schedule_time_iso),
{:ok, trip_id, route_id, direction_id, added?} <-
trip_route_direction_id(map, scheduled_time) do
{:ok,
%__MODULE__{
scheduled_time: scheduled_time,
predicted_time: predicted_time(predicted_time_iso, scheduled_time, status),
route_id: route_id,
trip_id: trip_id,
stop_id: stop_id(stop_name, track),
stop_sequence: stop_sequence(trip_id, stop_name, added?),
direction_id: direction_id,
status: status_string(status),
track: track,
added?: added?
}}
else
:ignore ->
:ignore
error ->
_ =
Logger.warn(fn ->
"unable to parse firebase map: #{inspect(map)}: #{inspect(error)}"
end)
:error
end
end
def from_firebase(%{} = map) do
_ =
Logger.warn(fn ->
"unable to match firebase map: #{inspect(map)}"
end)
:error
end
def validate_movement_type(%{"movement_type" => type})
when type in ~w(O B E) do
# O - Originating
# B - Both End Train and Detrain
# E - End Train only
:ok
end
def validate_movement_type(%{"movement_type" => _}) do
# other movement types shouldn't get boarding statuses
:ignore
end
def validate_movement_type(%{}) do
# without a movement type, treat it as okay
:ok
end
# We can ignore any object with is_Stopping False
def validate_is_stopping(%{"is_Stopping" => "False"}), do: :ignore
def validate_is_stopping(%{"is_stopping" => "False"}), do: :ignore
def validate_is_stopping(_), do: :ok
# ignore the Downeaster
def validate_route_id(%{"gtfs_route_id" => "ADE"}), do: :ignore
def validate_route_id(_), do: :ok
# Ignore statuses "Bus substitution" and "Not stopping here"
def validate_status(status) do
case status_string(status) do
"Bus substitution" -> :ignore
"Not stopping here" -> :ignore
_ -> :ok
end
end
defp trip_route_direction_id(
%{
"gtfs_route_id" => route_id,
"gtfs_trip_short_name" => trip_name,
"trip_id" => keolis_trip_id
},
dt
) do
{:ok, trip_id, direction_id, added?} = create_trip_id(route_id, trip_name, keolis_trip_id, dt)
{:ok, trip_id, route_id, direction_id, added?}
end
defp create_trip_id(route_id, "", keolis_trip_id, _dt) do
# no trip name, build a new trip_id
_ =
Logger.warn(fn ->
"creating trip for Keolis trip #{route_id} (#{keolis_trip_id})"
end)
{:ok, "CRB_" <> keolis_trip_id, :unknown, true}
end
defp create_trip_id(route_id, trip_name, keolis_trip_id, dt) do
case TripCache.route_trip_name_to_id(route_id, trip_name, dt) do
{:ok, trip_id, direction_id} ->
{:ok, trip_id, direction_id, false}
:error ->
# couldn't match the trip name: log a warning but build a trip ID
# anyways.
_ =
Logger.warn(fn ->
"unexpected missing GTFS trip ID: \
route #{route_id}, name #{trip_name}, trip ID #{keolis_trip_id}"
end)
{:ok, "CRB_#{keolis_trip_id}_#{trip_name}", :unknown, true}
end
end
defp stop_sequence(_trip_id, _stop_name, true) do
# added trips don't have a stop sequence
:unknown
end
defp stop_sequence(trip_id, stop_name, _added?) do
# get the stop ID as though there was no track assignment, since only the "generic" stop IDs
# are in the static schedule
stop_id = stop_id(stop_name, "")
case ScheduleCache.stop_sequence(trip_id, stop_id) do
{:ok, sequence} -> sequence
:error -> :unknown
end
end
defp predicted_time(iso_dt, scheduled_time, status)
defp predicted_time(_, _, "CX") do
# cancelled trips don't have a predictions
:unknown
end
defp predicted_time("", scheduled_time, _) do
scheduled_time
end
defp predicted_time(iso_dt, scheduled_time, _) do
case DateTime.from_iso8601(iso_dt) do
{:ok, predicted_time, _} ->
predicted_time
_ ->
scheduled_time
end
end
def stop_id(stop_name, track) do
case Map.get(config(:stop_ids), stop_name) do
nil -> stop_name
stop_id when is_binary(stop_id) -> stop_id
stop_ids when is_map(stop_ids) -> Map.get(stop_ids, track, stop_name)
end
end
statuses = Application.get_env(:commuter_rail_boarding, :statuses)
for {status, string} <- statuses do
# build a function for each status in the map
def status_string(unquote(status)) do
unquote(string)
end
end
def status_string(status) do
_ = Logger.warn(fn -> "unknown status: #{inspect(status)}" end)
:unknown
end
end
|
apps/commuter_rail_boarding/lib/boarding_status.ex
| 0.833121 | 0.513485 |
boarding_status.ex
|
starcoder
|
defmodule Hammox do
@moduledoc """
Hammox is a library for rigorous unit testing using mocks, explicit
behaviours and contract tests.
See the [README](readme.html) page for usage guide and examples.
Most of the functions in this module come from
[Mox](https://hexdocs.pm/mox/Mox.html) for backwards compatibility. As of
v0.1.0, the only Hammox-specific functions are `protect/2` and `protect/3`.
"""
alias Hammox.Utils
alias Hammox.TypeEngine
alias Hammox.TypeMatchError
defmodule TypespecNotFoundError do
@moduledoc false
defexception [:message]
end
@doc """
See [Mox.allow/3](https://hexdocs.pm/mox/Mox.html#allow/3).
"""
defdelegate allow(mock, owner_pid, allowed_via), to: Mox
@doc """
See [Mox.defmock/2](https://hexdocs.pm/mox/Mox.html#defmock/2).
"""
defdelegate defmock(name, options), to: Mox
@doc """
See [Mox.expect/4](https://hexdocs.pm/mox/Mox.html#expect/4).
"""
def expect(mock, name, n \\ 1, code) do
arity = :erlang.fun_info(code)[:arity]
hammox_code =
case fetch_typespecs_for_mock(mock, name, arity) do
# This is really an error case where we're trying to mock a function
# that does not exist in the behaviour. Mox will flag it better though
# so just let it pass through.
[] -> code
typespecs -> protected(code, typespecs, arity)
end
Mox.expect(mock, name, n, hammox_code)
end
@doc """
See [Mox.set_mox_from_context/1](https://hexdocs.pm/mox/Mox.html#set_mox_from_context/1).
"""
defdelegate set_mox_from_context(context), to: Mox
@doc """
See [Mox.set_mox_global/1](https://hexdocs.pm/mox/Mox.html#set_mox_global/1).
"""
defdelegate set_mox_global(context \\ %{}), to: Mox
@doc """
See [Mox.set_mox_private/1](https://hexdocs.pm/mox/Mox.html#set_mox_private/1).
"""
defdelegate set_mox_private(context \\ %{}), to: Mox
@doc """
See [Mox.stub/3](https://hexdocs.pm/mox/Mox.html#stub/3).
"""
defdelegate stub(mock, name, code), to: Mox
@doc """
See [Mox.stub_with/2](https://hexdocs.pm/mox/Mox.html#stub_with/2).
"""
defdelegate stub_with(mock, module), to: Mox
@doc """
See [Mox.verify!/0](https://hexdocs.pm/mox/Mox.html#verify!/0).
"""
defdelegate verify!(), to: Mox
@doc """
See [Mox.verify!/1](https://hexdocs.pm/mox/Mox.html#verify!/1).
"""
defdelegate verify!(mock), to: Mox
@doc """
See [Mox.verify_on_exit!/1](https://hexdocs.pm/mox/Mox.html#verify_on_exit!/1).
"""
defdelegate verify_on_exit!(context \\ %{}), to: Mox
@doc since: "0.1.0"
@doc """
Takes the function provided by a module, function, arity tuple and
decorates it with Hammox type checking.
Returns a new anonymous function.
Example:
```elixir
defmodule Calculator do
@callback add(integer(), integer()) :: integer()
end
defmodule TestCalculator do
def add(a, b), do: a + b
end
add_2 = Hammox.protect({TestCalculator, :add, 2}, Calculator)
add_2.(1.5, 2.5) # throws Hammox.TypeMatchError
```
A common tactic is to put behaviour callbacks and the "default"
implementations for these callbacks in the same module. For these kinds of
modules, you can also use `protect/2` as a shortcut for `protect/3`:
```elixir
# calling this
Hammox.protect(SomeModule, foo: 1)
# works the same as this
Hammox.protect(SomeModule, SomeModule, foo: 1)
```
"""
def protect(mfa, behaviour_name)
@spec protect(module_name :: module(), funs :: [{atom(), arity() | [arity()]}]) :: map()
def protect(module_name, funs) when is_atom(module_name and is_list(funs)),
do: protect(module_name, module_name, funs)
@spec protect(mfa :: mfa(), behaviour_name :: module()) :: fun()
def protect({module_name, function_name, arity}, behaviour_name)
when is_atom(module_name) and is_atom(function_name) and is_integer(arity) and
is_atom(behaviour_name) do
code = {module_name, function_name}
typespecs = fetch_typespecs!(behaviour_name, function_name, arity)
protected(code, typespecs, arity)
end
@doc since: "0.1.0"
@doc """
Same as `protect/2`, but allows decorating multiple functions at the same
time.
Provide a list of functions to decorate as third argument.
Returns a map where the keys are atoms of the form
`:{function_name}_{arity}` and values are the decorated anonymous
functions.
Example:
```elixir
defmodule Calculator do
@callback add(integer(), integer()) :: integer()
@callback add(integer(), integer(), integer()) :: integer()
@callback multiply(integer(), integer()) :: integer()
end
defmodule TestCalculator do
def add(a, b), do: a + b
def add(a, b, c), do: a + b + c
def multiply(a, b), do: a * b
end
%{
add_2: add_2,
add_3: add_3,
multiply_2: multiply_2
} = Hammox.protect(TestCalculator, Calculator, add: [2, 3], multiply: 2)
```
"""
@spec protect(
module_name :: module(),
behaviour_name :: module(),
funs :: [{atom(), arity() | [arity()]}]
) ::
map()
def protect(module_name, behaviour_name, funs)
when is_atom(module_name) and is_atom(behaviour_name) and is_list(funs) do
funs
|> Enum.flat_map(fn {function_name, arity_or_arities} ->
arity_or_arities
|> List.wrap()
|> Enum.map(fn arity ->
key =
function_name
|> Atom.to_string()
|> Kernel.<>("_#{arity}")
|> String.to_atom()
value = protect({module_name, function_name, arity}, behaviour_name)
{key, value}
end)
end)
|> Enum.into(%{})
end
defp protected(code, typespecs, 0) do
fn ->
protected_code(code, typespecs, [])
end
end
defp protected(code, typespecs, 1) do
fn arg1 ->
protected_code(code, typespecs, [arg1])
end
end
defp protected(code, typespecs, 2) do
fn arg1, arg2 ->
protected_code(code, typespecs, [arg1, arg2])
end
end
defp protected(code, typespecs, 3) do
fn arg1, arg2, arg3 ->
protected_code(code, typespecs, [arg1, arg2, arg3])
end
end
defp protected(code, typespecs, 4) do
fn arg1, arg2, arg3, arg4 ->
protected_code(code, typespecs, [arg1, arg2, arg3, arg4])
end
end
defp protected(code, typespecs, 5) do
fn arg1, arg2, arg3, arg4, arg5 ->
protected_code(code, typespecs, [arg1, arg2, arg3, arg4, arg5])
end
end
defp protected(code, typespecs, 6) do
fn arg1, arg2, arg3, arg4, arg5, arg6 ->
protected_code(code, typespecs, [arg1, arg2, arg3, arg4, arg5, arg6])
end
end
defp protected(code, typespecs, 7) do
fn arg1, arg2, arg3, arg4, arg5, arg6, arg7 ->
protected_code(code, typespecs, [arg1, arg2, arg3, arg4, arg5, arg6, arg7])
end
end
defp protected(code, typespecs, 8) do
fn arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 ->
protected_code(code, typespecs, [arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8])
end
end
defp protected(code, typespecs, 9) do
fn arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 ->
protected_code(code, typespecs, [arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9])
end
end
defp protected(_code, _typespec, arity) when arity > 9 do
raise "Hammox only supports protecting functions with arity up to 9. Why do you need over 9 parameters anyway?"
end
defp protected_code(code, typespecs, args) do
return_value =
case code do
{module_name, function_name} -> apply(module_name, function_name, args)
anonymous when is_function(anonymous) -> apply(anonymous, args)
end
check_call(args, return_value, typespecs)
return_value
end
defp check_call(args, return_value, typespecs) when is_list(typespecs) do
typespecs
|> Enum.reduce_while({:error, []}, fn typespec, {:error, reasons} = result ->
case match_call(args, return_value, typespec) do
:ok ->
{:halt, :ok}
{:error, new_reasons} = new_result ->
{:cont, if(length(reasons) >= length(new_reasons), do: result, else: new_result)}
end
end)
|> case do
{:error, _} = error -> raise TypeMatchError, error
:ok -> :ok
end
end
defp match_call(args, return_value, typespec) do
with :ok <- match_args(args, typespec),
:ok <- match_return_value(return_value, typespec) do
:ok
end
end
defp match_args([], _typespec) do
:ok
end
defp match_args(args, typespec) do
args
|> Enum.zip(0..(length(args) - 1))
|> Enum.map(fn {arg, index} ->
arg_type = arg_typespec(typespec, index)
case TypeEngine.match_type(arg, arg_type) do
{:error, reasons} ->
{:error, [{:arg_type_mismatch, index, arg, arg_type} | reasons]}
:ok ->
:ok
end
end)
|> Enum.max_by(fn
{:error, reasons} -> length(reasons)
:ok -> 0
end)
end
defp match_return_value(return_value, typespec) do
{:type, _, :fun, [_, return_type]} = typespec
case TypeEngine.match_type(return_value, return_type) do
{:error, reasons} ->
{:error, [{:return_type_mismatch, return_value, return_type} | reasons]}
:ok ->
:ok
end
end
defp fetch_typespecs!(behaviour_name, function_name, arity) do
case fetch_typespecs(behaviour_name, function_name, arity) do
[] ->
raise TypespecNotFoundError,
message:
"Could not find typespec for #{Utils.module_to_string(behaviour_name)}.#{
function_name
}/#{arity}."
typespecs ->
typespecs
end
end
defp fetch_typespecs(behaviour_module_name, function_name, arity) do
{:ok, callbacks} = Code.Typespec.fetch_callbacks(behaviour_module_name)
callbacks
|> Enum.find_value([], fn
{{^function_name, ^arity}, typespecs} -> typespecs
_ -> false
end)
|> Enum.map(fn typespec ->
Utils.replace_user_types(typespec, behaviour_module_name)
end)
end
defp fetch_typespecs_for_mock(mock_name, function_name, arity)
when is_atom(mock_name) and is_atom(function_name) and is_integer(arity) do
mock_name.__mock_for__()
|> Enum.map(fn behaviour ->
fetch_typespecs(behaviour, function_name, arity)
end)
|> List.flatten()
end
defp arg_typespec(function_typespec, arg_index) do
{:type, _, :fun, [{:type, _, :product, arg_typespecs}, _]} = function_typespec
Enum.at(arg_typespecs, arg_index)
end
end
|
lib/hammox.ex
| 0.859295 | 0.893913 |
hammox.ex
|
starcoder
|
defmodule SanbaseWeb.Graphql.Complexity do
require Logger
@compile inline: [
calculate_complexity: 3,
interval_seconds: 1,
years_difference_weighted: 2,
get_metric_name: 1
]
@doc ~S"""
Returns the complexity as a real number.
For basic authorization:
Internal services use basic authentication. Return complexity = 0 to allow them
to access everything without limits.
For apikey/jwt/anon authorized users:
Returns the complexity of the query. It is the number of intervals in the period
'from-to' multiplied by the child complexity. The child complexity is the number
of fields that will be returned for a single price point. The calculation is done
based only on the supplied arguments and avoids accessing the DB if the query
is rejected.
"""
def from_to_interval(_, _, %{context: %{auth: %{auth_method: :basic}}}) do
# Does not pattern match on `%Absinthe.Complexity{}` so `%Absinthe.Resolution{}`
# can be passed. This is possible because only the context is used
0
end
def from_to_interval(
args,
child_complexity,
%{context: %{auth: %{subscription: subscription}}} = struct
)
when not is_nil(subscription) do
complexity = calculate_complexity(args, child_complexity, struct)
case Sanbase.Billing.Plan.plan_atom_name(subscription.plan) do
:free -> complexity
:basic -> div(complexity, 4)
:pro -> div(complexity, 5)
:pro_plus -> div(complexity, 5)
:premium -> div(complexity, 6)
:custom -> div(complexity, 7)
end
end
def from_to_interval(%{} = args, child_complexity, struct) do
calculate_complexity(args, child_complexity, struct)
end
# Private functions
defp calculate_complexity(%{from: from, to: to} = args, child_complexity, struct) do
seconds_difference = Timex.diff(from, to, :seconds) |> abs
years_difference_weighted = years_difference_weighted(from, to)
interval_seconds = interval_seconds(args) |> max(1)
metric = get_metric_name(struct)
complexity_weight =
with metric when is_binary(metric) <- metric,
weight when is_number(weight) <- Sanbase.Metric.complexity_weight(metric) do
weight
else
_ -> 1
end
(child_complexity * (seconds_difference / interval_seconds) * years_difference_weighted *
complexity_weight)
|> Sanbase.Math.to_integer()
end
# This case is important as here the flow comes from `timeseries_data_complexity`
# and it will be handled by extracting the name from the %Absinthe.Resolution{}
# struct manually passed. This is done because otherwise the same `getMetric`
# resolution flow could pass twice through this code and remove 2 metrics instead
# of just one. This happens if both timeseries_data and timeseries_data_complexity
# are queried
defp get_metric_name(%{source: %{metric: metric}}), do: metric
defp get_metric_name(_) do
case Process.get(:__metric_name_from_get_metric_api__) do
[metric | rest] ->
# If there are batched requests they will be resolved in the same order
# as their are in the list. When computing complexity for a metric put back
# the list without this one metric so the next one can be properly fetched.
Process.put(:__metric_name_from_get_metric_api__, rest)
metric
_ ->
nil
end
end
defp interval_seconds(args) do
case Map.get(args, :interval, "") do
"" -> "1d"
interval -> interval
end
|> Sanbase.DateTimeUtils.str_to_sec()
end
defp years_difference_weighted(from, to) do
Timex.diff(from, to, :years) |> abs |> max(2) |> div(2)
end
end
|
lib/sanbase_web/graphql/complexity/complexity.ex
| 0.910002 | 0.672202 |
complexity.ex
|
starcoder
|
defmodule ScrapyCloudEx.Endpoints.Storage.Requests do
@moduledoc """
Wraps the [Requests](https://doc.scrapinghub.com/api/requests.html) endpoint.
The requests API allows you to work with request and response data from your crawls.
"""
import ScrapyCloudEx.Endpoints.Guards
alias ScrapyCloudEx.Endpoints.Helpers
alias ScrapyCloudEx.Endpoints.Storage.QueryParams
alias ScrapyCloudEx.HttpAdapter.RequestConfig
@typedoc """
A request object.
Map with the following keys:
* `"time"` - request start timestamp in milliseconds (`t:integer/0`).
* `"method"` - HTTP method. Defaults to `"GET"` (`t:String.t/0`).
* `"url"` - request URL (`t:String.t/0`).
* `"status"` - HTTP response code (`t:integer/0`).
* `"duration"` - request duration in milliseconds (`t:integer/0`).
* `"rs"` - response size in bytes (`t:integer/0`).
* `"parent"` - index of the parent request (`t:integer/0`).
* `"fp"` - request fingerprint (`t:String.t/0`).
"""
@type request_object :: %{required(String.t()) => integer() | String.t()}
@base_url "https://storage.scrapinghub.com/requests"
@doc """
Retrieves request data for a given job.
The `composite_id` may have up to 4 sections: the first 3 refering to project/spider/job
ids with the last refering to the request number.
The following parameters are supported in the `params` argument:
* `:format` - the [format](ScrapyCloudEx.Endpoints.Storage.html#module-format) to be used
for returning results. Can be `:json` or `:jl`. Defaults to `:json`.
* `:pagination` - [pagination parameters](ScrapyCloudEx.Endpoints.Storage.html#module-pagination).
* `:meta` - [meta parameters](ScrapyCloudEx.Endpoints.Storage.html#module-meta-parameters) to show.
* `:nodata` - if set, no data will be returned other than specified `:meta` keys.
The `opts` value is documented [here](ScrapyCloudEx.Endpoints.html#module-options).
A warning will be logged if the `composite_id` has fewer than 4 sections and no
[pagination parameters](ScrapyCloudEx.Endpoints.Storage.html#module-pagination) were provided.
See docs [here](https://doc.scrapinghub.com/api/requests.html#requests-project-id-spider-id-job-id-request-no)
and [here](https://doc.scrapinghub.com/api/requests.html#requests-project-id-spider-id-job-id).
## Example
```
ScrapyCloudEx.Endpoints.Storage.Requests.get("API_KEY", "14")
ScrapyCloudEx.Endpoints.Storage.Requests.get("API_KEY", "14/13")
ScrapyCloudEx.Endpoints.Storage.Requests.get("API_KEY", "14/13/12")
ScrapyCloudEx.Endpoints.Storage.Requests.get("API_KEY", "14/13/12/3456")
```
"""
@spec get(String.t(), String.t(), Keyword.t(), Keyword.t()) ::
ScrapyCloudEx.result([request_object()])
def get(api_key, composite_id, params \\ [], opts \\ [])
when is_api_key(api_key)
when is_binary(composite_id) and composite_id != ""
when is_list(params)
when is_list(opts) do
with %QueryParams{error: nil} = query_params <- params |> QueryParams.from_keywords() do
query_string =
query_params
|> warn_if_no_pagination(composite_id)
|> QueryParams.to_query()
base_url = [@base_url, composite_id] |> Enum.join("/")
RequestConfig.new()
|> RequestConfig.put(:api_key, api_key)
|> RequestConfig.put(:url, "#{base_url}?#{query_string}")
|> RequestConfig.put(:headers, Keyword.get(opts, :headers, []))
|> RequestConfig.put(:opts, opts)
|> Helpers.make_request()
else
%QueryParams{error: error} -> {:error, error}
error -> {:error, error}
end
end
@doc """
Retrives request stats for a given job.
The `composite_id` must have 3 sections (i.e. refer to a job).
The `opts` value is documented [here](ScrapyCloudEx.Endpoints.html#module-options).
The response will contain the following information:
| Field | Description |
| --------------------- | ---------------------------------------- |
| `counts[field]` | The number of times the field occurs. |
| `totals.input_bytes` | The total size of all requests in bytes. |
| `totals.input_values` | The total number of requests. |
See docs [here](https://doc.scrapinghub.com/api/requests.html#requests-project-id-spider-id-job-id-stats).
## Example
```
ScrapyCloudEx.Endpoints.Storage.Requests.stats("API_KEY", "14/13/12")
```
## Example return value
```
%{
"counts" => %{
"duration" => 2888,
"fp" => 2888,
"method" => 2888,
"parent" => 2886,
"rs" => 2888,
"status" => 2888,
"url" => 2888
},
"totals" => %{"input_bytes" => 374000, "input_values" => 2888}
}
```
"""
@spec stats(String.t(), String.t(), Keyword.t()) :: ScrapyCloudEx.result(map())
def stats(api_key, composite_id, opts \\ [])
when is_api_key(api_key)
when is_binary(composite_id)
when is_list(opts) do
with 3 <- composite_id |> String.split("/") |> length() do
RequestConfig.new()
|> RequestConfig.put(:api_key, api_key)
|> RequestConfig.put(:opts, opts)
|> RequestConfig.put(:url, [@base_url, composite_id, "stats"] |> Enum.join("/"))
|> Helpers.make_request()
else
_ ->
error =
"expected `id` param to have exactly 3 sections"
|> Helpers.invalid_param_error(:id)
{:error, error}
end
end
@spec warn_if_no_pagination(QueryParams.t(), String.t()) :: QueryParams.t()
defp warn_if_no_pagination(%QueryParams{} = query_params, id) when is_binary(id) do
case id |> String.split("/") |> length() do
count when count < 4 -> warn_if_no_pagination(query_params)
_count -> :ok
end
query_params
end
@spec warn_if_no_pagination(QueryParams.t()) :: QueryParams.t()
defp warn_if_no_pagination(%QueryParams{} = query_params) do
query_params |> QueryParams.warn_if_no_pagination("#{__MODULE__}.get/4")
end
end
|
lib/endpoints/storage/requests.ex
| 0.807878 | 0.681217 |
requests.ex
|
starcoder
|
defmodule Phoenix.LiveView.Router do
@moduledoc """
Provides LiveView routing for Phoenix routers.
"""
@cookie_key "__phoenix_flash__"
@doc """
Defines a LiveView route.
A LiveView can be routed to by using the `live` macro with a path and
the name of the LiveView:
live "/thermostat", ThermostatLive
By default, you can generate a route to this LiveView by using the `live_path` helper:
live_path(@socket, ThermostatLive)
## Actions and live navigation
It is common for a LiveView to have multiple states and multiple URLs.
For example, you can have a single LiveView that lists all articles on
your web app. For each article there is an "Edit" button which, when
pressed, opens up a modal on the same page to edit the article. It is a
best practice to use live navigation in those cases, so when you click
edit, the URL changes to "/articles/1/edit", even though you are still
within the same LiveView. Similarly, you may also want to show a "New"
button, which opens up the modal to create new entries, and you want
that to reflect in the URL as "/articles/new".
In order to make it easier to recognize the current "action" your
LiveView is on, you can pass the action option when defining LiveViews
too:
live "/articles", ArticleLive.Index, :index
live "/articles/new", ArticleLive.Index, :new
live "/articles/1/edit", ArticleLive.Index, :edit
When an action is given, the generated route helpers are named after
the LiveView itself (the same as in a controller). For the example
above, we will have:
article_index_path(@socket, :index)
article_index_path(@socket, :new)
article_index_path(@socket, :edit, 123)
The current action will always be available inside the LiveView as
the `@live_view_action` assign. `@live_view_action` will be `nil`
if no action is given on the route definition.
## Layout
When a layout isn't explicitly set, a default layout is inferred similar to
controllers. For example, the layout for the router `MyAppWeb.Router`
would be inferred as `MyAppWeb.LayoutView` and would use the `:app` template.
## Options
* `:session` - a map of strings keys and values to be merged into the session.
* `:layout` - the optional tuple for specifying a layout to render the
LiveView. Defaults to `{LayoutView, :app}` where LayoutView is relative to
your application's namespace.
* `:container` - the optional tuple for the HTML tag and DOM attributes to
be used for the LiveView container. For example: `{:li, style: "color: blue;"}`.
See `Phoenix.LiveView.live_render/3` for more information on examples.
* `:as` - optionally configures the named helper. Defaults to `:live` when
using a LiveView without actions or default to the LiveView name when using
actions.
* `:metadata` - a map to optional feed metadata used on telemetry events and route info
for example: `%{route_name: :foo, access: :user}`
## Examples
defmodule MyApp.Router
use Phoenix.Router
import Phoenix.LiveView.Router
scope "/", MyApp do
pipe_through [:browser]
live "/thermostat", ThermostatLive
live "/clock", ClockLive
live "/dashboard", DashboardLive, layout: {MyApp.AlternativeView, "app.html"}
end
end
iex> MyApp.Router.Helpers.live_path(MyApp.Endpoint, MyApp.ThermostatLive)
"/thermostat"
"""
defmacro live(path, live_view, action \\ nil, opts \\ []) do
quote bind_quoted: binding() do
{action, router_options} =
Phoenix.LiveView.Router.__live__(__MODULE__, live_view, action, opts)
Phoenix.Router.get(path, Phoenix.LiveView.Plug, action, router_options)
end
end
@doc """
Configures the layout to use for `live` routes.
## Examples
defmodule AppWeb.Router do
use LiveGenWeb, :router
import Phoenix.LiveView.Router
pipeline :browser do
...
plug :put_live_layout, {AppWeb.LayoutView, "root.html"}
end
...
end
"""
def put_live_layout(%Plug.Conn{} = conn, {layout_mod, template})
when is_atom(layout_mod) and is_binary(template) do
Plug.Conn.put_private(conn, :phoenix_live_layout, {layout_mod, template})
end
@doc """
Fetches the LiveView and merges with the controller flash.
Replaces the default `:fetch_flash` plug used by `Phoenix.Router`.
## Examples
defmodule AppWeb.Router do
use LiveGenWeb, :router
import Phoenix.LiveView.Router
pipeline :browser do
...
plug :fetch_live_flash
end
...
end
"""
def fetch_live_flash(%Plug.Conn{} = conn, _) do
case cookie_flash(conn) do
{conn, nil} ->
Phoenix.Controller.fetch_flash(conn, [])
{conn, flash} ->
conn
|> Phoenix.Controller.fetch_flash([])
|> Phoenix.Controller.merge_flash(flash)
end
end
@doc false
def __live__(router, live_view, action, opts) when is_list(action) and is_list(opts) do
__live__(router, live_view, nil, Keyword.merge(action, opts))
end
def __live__(router, live_view, action, opts) when is_atom(action) and is_list(opts) do
live_view = Phoenix.Router.scoped_alias(router, live_view)
{metadata, opts} = Keyword.pop(opts, :metadata, %{})
opts =
opts
|> Keyword.put(:router, router)
|> Keyword.put(:action, action)
|> Keyword.put(:inferred_layout, inferred_layout(router))
{as_helper, as_action} = inferred_as(live_view, action)
{as_action,
as: opts[:as] || as_helper,
private: %{phoenix_live_view: {live_view, opts}},
alias: false,
metadata: Map.put(metadata, :phoenix_live_view, {live_view, action})}
end
defp inferred_as(live_view, nil), do: {:live, live_view}
defp inferred_as(live_view, action) do
live_view
|> Module.split()
|> Enum.drop_while(&(not String.ends_with?(&1, "Live")))
|> Enum.map(&(&1 |> String.replace_suffix("Live", "") |> Macro.underscore()))
|> Enum.join("_")
|> case do
"" ->
raise ArgumentError,
"could not infer :as option because a live action was given and the LiveView " <>
"does not have a \"Live\" suffix. Please pass :as explicitly or make sure your " <>
"LiveView is named like \"FooLive\" or \"FooLive.Index\""
as ->
{String.to_atom(as), action}
end
end
defp inferred_layout(router) do
layout_view =
router
|> Atom.to_string()
|> String.split(".")
|> Enum.drop(-1)
|> Kernel.++(["LayoutView"])
|> Module.concat()
{layout_view, :app}
end
defp cookie_flash(%Plug.Conn{cookies: %{@cookie_key => token}} = conn) do
endpoint = Phoenix.Controller.endpoint_module(conn)
flash =
case Phoenix.LiveView.Utils.verify_flash(endpoint, token) do
%{} = flash when flash != %{} -> flash
%{} -> nil
end
{Plug.Conn.delete_resp_cookie(conn, @cookie_key), flash}
end
defp cookie_flash(%Plug.Conn{} = conn), do: {conn, nil}
end
|
lib/phoenix_live_view/router.ex
| 0.909849 | 0.587884 |
router.ex
|
starcoder
|
defmodule Akin do
@moduledoc """
Akin
=======
Functions for comparing two strings for similarity using a collection of string comparison algorithms for Elixir. Algorithms can be called independently or in total to return a map of metrics.
## Options
Options accepted in a keyword list (i.e. [ngram_size: 3]).
1. `algorithms`: algorithms to use in comparision. Accepts the name or a keyword list. Default is algorithms/0.
1. `metric` - algorithm metric. Default is both
- "string": uses string algorithms
- "phonetic": uses phonetic algorithms
1. `unit` - algorithm unit. Default is both.
- "whole": uses algorithms best suited for whole string comparison (distance)
- "partial": uses algorithms best suited for partial string comparison (substring)
1. `level` - level for double phonetic matching. Default is "normal".
- "strict": both encodings for each string must match
- "strong": the primary encoding for each string must match
- "normal": the primary encoding of one string must match either encoding of other string (default)
- "weak": either primary or secondary encoding of one string must match one encoding of other string
1. `match_at`: an algorith score equal to or above this value is condsidered a match. Default is 0.9
1. `ngram_size`: number of contiguous letters to split strings into. Default is 2.
1. `short_length`: qualifies as "short" to recieve a shortness boost. Used by Name Metric. Default is 8.
1. `stem`: boolean representing whether to compare the stemmed version the strings; uses Stemmer. Default `false`
"""
import Akin.Util,
only: [list_algorithms: 1, modulize: 1, compose: 1, opts: 2, r: 1, default_opts: 0]
alias Akin.Corpus
alias Akin.Names
@spec compare(binary() | %Corpus{}, binary() | %Corpus{}, keyword()) :: float()
@doc """
Compare two strings. Return map of algorithm metrics.
Options accepted as a keyword list. If no options are given, default values will be used.
"""
def compare(left, right, opts \\ default_opts())
def compare(left, right, opts) when is_binary(left) and is_binary(right) do
if opts(opts, :stem) do
left = compose(left).stems |> Enum.join(" ")
right = compose(right).stems |> Enum.join(" ")
compare(compose(left), compose(right), opts)
else
compare(compose(left), compose(right), opts)
end
end
def compare(%Corpus{} = left, %Corpus{} = right, opts) do
Enum.reduce(list_algorithms(opts), %{}, fn algorithm, acc ->
Map.put(acc, algorithm, apply(modulize(algorithm), :compare, [left, right, opts]))
end)
|> Enum.reduce([], fn {k, v}, acc ->
if is_nil(v) do
acc
else
[{String.replace(k, ".", ""), v} | acc]
end
end)
|> Enum.map(fn {k, v} -> {String.to_atom(k), r(v)} end)
|> Enum.into(%{})
end
@spec match_names(binary() | %Corpus{}, binary() | %Corpus{} | list(), keyword()) :: float()
@doc """
Compare a string against a list of strings. Matches are determined by algorithem metrics equal to or higher than the
`match_at` option. Return a list of strings that are a likely match.
"""
def match_names(left, rights, opts \\ default_opts())
def match_names(_, [], _), do: []
def match_names(left, rights, opts) when is_binary(left) and is_list(rights) do
rights = Enum.map(rights, fn right -> compose(right) end)
match_names(compose(left), rights, opts)
end
def match_names(%Corpus{} = left, rights, opts) do
Enum.reduce(rights, [], fn right, acc ->
%{scores: scores} = Names.compare(left, right, opts)
if Enum.any?(scores, fn {_algo, score} -> score > opts(opts, :match_at) end) do
[right.original | acc]
else
acc
end
end)
end
@spec match_names_metrics(binary(), list(), keyword()) :: float()
@doc """
Compare a string against a list of strings. Matches are determined by algorithem metrics equal to or higher than the
`match_at` option. Return a list of strings that are a likely match and their algorithm metrics.
"""
def match_names_metrics(left, rights, opts \\ default_opts())
def match_names_metrics(left, rights, opts) when is_binary(left) and is_list(rights) do
Enum.reduce(rights, [], fn right, acc ->
%{left: left, right: right, metrics: scores, match: match} =
match_name_metrics(left, right, opts)
if match == 1 do
[%{left: left, right: right, metrics: scores, match: 1} | acc]
else
[%{left: left, right: right, metrics: scores, match: 0} | acc]
end
end)
end
@spec match_name_metrics(binary(), binary(), Keyword.t()) :: %{
:left => binary(),
:match => 0 | 1,
:metrics => [any()],
:right => binary()
}
@doc """
Compare a string to a string with logic specific to names. Matches are determined by algorithem
metrics equal to or higher than the `match_at` option. Return a list of strings that are a likely
match and their algorithm metrics.
"""
def match_name_metrics(left, rights, opts \\ default_opts())
def match_name_metrics(left, right, opts) when is_binary(left) and is_binary(right) do
left = compose(left)
right = compose(right)
%{scores: scores} = Names.compare(left, right, opts)
left = Enum.join(left.list, " ")
right = Enum.join(right.list, " ")
if Enum.any?(scores, fn {_algo, score} -> score > opts(opts, :match_at) end) do
%{left: left, right: right, metrics: scores, match: 1}
else
%{left: left, right: right, metrics: scores, match: 0}
end
end
@spec phonemes(binary() | %Corpus{}) :: list()
@doc """
Returns list of unique phonetic encodings produces by the single and
double metaphone algorithms.
"""
def phonemes(string) when is_binary(string) do
phonemes(compose(string), string)
end
defp phonemes(%Corpus{string: string}, _original_string) do
single = Akin.Metaphone.Single.compute(string)
double = Akin.Metaphone.Double.parse(string) |> Tuple.to_list()
[single | double]
|> List.flatten()
|> Enum.uniq()
end
end
|
lib/akin.ex
| 0.911974 | 0.718446 |
akin.ex
|
starcoder
|
defmodule Nostrum.Cache.PresenceCache do
@default_cache_implementation Nostrum.Cache.PresenceCache.ETS
@moduledoc """
Cache behaviour & dispatcher for Discord presences.
By default, `#{@default_cache_implementation}` will be use for caching
presences. You can override this in the `:caches` option of the `nostrum`
application by setting the `:presences` fields to a different module
implementing the `Nostrum.Cache.PresenceCache` behaviour. Any module below
`Nostrum.Cache.PresenceCache` implements this behaviour and can be used as a
cache.
## Writing your own presence cache
As with the other caches, the presence cache API consists of two parts:
- The functions that the user calls, currently only `c:get/2`.
- The functions that nostrum calls, such as `c:create/1` or `c:update/1`.
These **do not create any objects in the Discord API**, they are purely
created to update the cached data from data that Discord sends us. If you
want to create objects on Discord, use the functions exposed by `Nostrum.Api`
instead.
You need to implement both of them for nostrum to work with your custom
cache. **You also need to implement `Supervisor` callbacks**, which will
start your cache as a child under `Nostrum.Cache.CacheSupervisor`: As an
example, the `Nostrum.Cache.PresenceCache.ETS` implementation uses this to to
set up its ETS table it uses for caching. See the callbacks section for every
nostrum-related callback you need to implement.
"""
@moduledoc since: "0.5"
@configured_cache :nostrum
|> Application.compile_env(:caches, %{})
|> Map.get(:presences, @default_cache_implementation)
alias Nostrum.Struct.{Guild, User}
alias Nostrum.Util
import Nostrum.Snowflake, only: [is_snowflake: 1]
## Supervisor callbacks
# These set up the backing cache.
@doc false
defdelegate init(init_arg), to: @configured_cache
@doc false
defdelegate start_link(init_arg), to: @configured_cache
@doc false
defdelegate child_spec(opts), to: @configured_cache
# Types
@typedoc """
Represents a presence as received from Discord.
See [Presence Update](https://discord.com/developers/docs/topics/gateway#presence-update).
"""
@typedoc since: "0.5"
@opaque presence :: map()
# Callbacks
@doc ~S"""
Retreives a presence for a user from the cache by guild and id.
If successful, returns `{:ok, presence}`. Otherwise returns `{:error, reason}`.
## Example
```elixir
case Nostrum.Cache.PresenceCache.get(111133335555, 222244446666) do
{:ok, presence} ->
"They're #{presence.status}"
{:error, _reason} ->
"They're dead Jim"
end
```
"""
@callback get(User.id(), Guild.id()) :: {:ok, presence()} | {:error, :presence_not_found}
@doc """
Create a presence in the cache.
"""
@callback create(presence) :: :ok
@doc """
Bulk create multiple presences for the given guild in the cache.
"""
@callback bulk_create(Guild.id(), [presence()]) :: :ok
@doc """
Update the given presence in the cache from upstream data.
## Return value
Return the guild ID along with the old presence (if it was cached, otherwise
`nil`) and the updated presence structure. If the `:activities` or `:status`
fields of the presence did not change, return `:noop`.
"""
@callback update(map()) ::
{Guild.id(), old_presence :: presence() | nil, new_presence :: presence()} | :noop
# Dispatch
@doc section: :reading
defdelegate get(user_id, guild_id), to: @configured_cache
defdelegate create(presence), to: @configured_cache
defdelegate update(presence), to: @configured_cache
defdelegate bulk_create(guild_id, presences), to: @configured_cache
# Dispatch helpers
@doc "Same as `get/1`, but raise `Nostrum.Error.CacheError` in case of a failure."
@doc section: :reading
@spec get!(User.id(), Guild.id()) :: presence() | no_return()
def get!(user_id, guild_id) when is_snowflake(user_id) and is_snowflake(guild_id) do
user_id
|> @configured_cache.get(guild_id)
|> Util.bangify_find({user_id, guild_id}, @configured_cache)
end
end
|
lib/nostrum/cache/presence_cache.ex
| 0.827689 | 0.624508 |
presence_cache.ex
|
starcoder
|
defmodule Fixate do
@moduledoc """
Insert fixtures into your ExUnit context in a clean manner.
## Usage
Start Fixate by adding `Fixate.start()` to your `test/test_helper.exs` file.
```elixir
ExUnit.start()
Fixate.start()
```
Then inside your test files add `use Fixate.Case` to allow the fixture attribute.
```elixir
defmodule MyAppTest do
use ExUnit.Case
use Fixate.Case
...
```
Now you can load fixtures before each test using the `@fixture` attribute. The attribute takes either a `"path"` or a `key: "path"` values. If no key is provided the key will be generated using the base filename before the first dot. The files will be loaded from your `priv/fixtures` folder.
```elixir
@fixture "text.txt"
@fixture named_text: "text.txt"
@fixture "subdirectory/subtext.txt"
test "reads basic files", ctx do
assert "FILE_BODY" == ctx.text
assert ctx.text == ctx.named_text
assert "FILE_BODY_IN_SUBFOLDER" == ctx.subtext
end
```
### Adding parsers for fixtures
By default Fixate will simply load the file as a binary. However this is unlikely to be enough for most tests. Instead of Fixate trying to support various file types we give you a simple way to define parsers for files by their "full" extensions.
To do this add parsers to your `test/test_helper.exs` using the `Fixate.add_parser/2` command.
```elixir
ExUnit.start()
Fixate.start()
# This will be used to parse all *.integer.txt files
Fixate.add_parser("integer.txt", &( String.to_integer(&1) ))
# This will be used to parse all *.json files
Fixate.add_parser("json", &( Jason.decode!(&1) ))
# This will be used to parse all *.geojson.json files
Fixate.add_parser("geojson.json", &( Jason.decode!(&1) |> Geo.JSON.decode! ))
```
And now the parsed values will appear instead of the binary data
```elixir
defmodule MyAppTest do
use ExUnit.Case
use Fixate.Case
@fixture "text.txt"
@fixture "text2.txt"
test "reads basic files", ctx do
assert "FILE_BODY" == ctx.text
assert "OTHER_BODY" == ctx.text
end
@fixture answer: "answer_to_everything.integer.txt"
test "has all the answers", ctx do
assert 42 == ctx.answer
end
@fixture myhouse: "geo/location.geojson.json"
test "locations", ctx do
assert MyApp.get_home == ctx.myhouse
end
end
```
For more complex parsers create a module, for example in `test/support`, and reference it.
```elixir
Fixate.add_parser("complex.xml", &MyFixtureParser.parse_complex/1)
```
## Examples
For an example of usage in an actual project check out [Geo.Turf](https://github.com/JonGretar/GeoTurf/tree/master/test)'s tests.
"""
use Agent
@spec start() :: {:error, any()} | {:ok, pid()}
def start() do
Fixate.start_link(%{})
end
@spec start_link(any()) :: {:error, any()} | {:ok, pid()}
def start_link(initial) do
Agent.start_link(fn -> initial end, name: __MODULE__)
end
def parse(extension, data) when is_binary(extension) do
Agent.get(__MODULE__, fn state -> parse(state, extension, data) end )
end
defp parse(state, extension, data) do
fun = state |> Map.get(extension, & &1)
fun.(data)
end
def add_parser(extension, fun) when is_binary(extension) and is_function(fun, 1) do
Agent.update(__MODULE__, fn state -> add_parser(state, extension, fun) end)
end
defp add_parser(state, extension, fun) do
state |> Map.put(extension, fun)
end
end
|
lib/fixate.ex
| 0.910304 | 0.78374 |
fixate.ex
|
starcoder
|
defmodule Ecto.Adapter.Queryable do
@moduledoc """
Specifies the query API required from adapters.
"""
@typedoc "Proxy type to the adapter meta"
@type adapter_meta :: Ecto.Adapter.adapter_meta()
@typedoc "Ecto.Query metadata fields (stored in cache)"
@type query_meta :: %{sources: tuple, preloads: term, select: map}
@typedoc "Cache query metadata"
@type query_cache :: {:nocache, prepared}
| {:cache, (cached -> :ok), prepared}
| {:cached, (cached -> :ok), (prepared -> :ok), cached}
@type prepared :: term
@type cached :: term
@type options :: Keyword.t()
@doc """
Commands invoked to prepare a query for `all`, `update_all` and `delete_all`.
The returned result is given to `execute/6`.
"""
@callback prepare(atom :: :all | :update_all | :delete_all, query :: Ecto.Query.t()) ::
{:cache, prepared} | {:nocache, prepared}
@doc """
Executes a previously prepared query.
It must return a tuple containing the number of entries and
the result set as a list of lists. The result set may also be
`nil` if a particular operation does not support them.
The `adapter_meta` field is a map containing some of the fields found
in the `Ecto.Query` struct.
"""
@callback execute(adapter_meta, query_meta, query_cache, params :: list(), options) ::
{integer, [[term]] | nil}
@doc """
Streams a previously prepared query.
It returns a stream of values.
The `adapter_meta` field is a map containing some of the fields found
in the `Ecto.Query` struct.
"""
@callback stream(adapter_meta, query_meta, query_cache, params :: list(), options) ::
Enumerable.t
@doc """
Plans and prepares a query for the given repo, leveraging its query cache.
This operation uses the query cache if one is available.
"""
def prepare_query(operation, repo_name_or_pid, queryable) do
{adapter, %{cache: cache}} = Ecto.Repo.Registry.lookup(repo_name_or_pid)
{_meta, prepared, params} =
queryable
|> Ecto.Queryable.to_query()
|> Ecto.Query.Planner.ensure_select(operation == :all)
|> Ecto.Query.Planner.query(operation, cache, adapter, 0)
{prepared, params}
end
@doc """
Plans a query using the given adapter.
This does not expect the repository and therefore does not leverage the cache.
"""
def plan_query(operation, adapter, queryable) do
query = Ecto.Queryable.to_query(queryable)
{query, params, _key} = Ecto.Query.Planner.plan(query, operation, adapter, 0)
{query, _} = Ecto.Query.Planner.normalize(query, operation, adapter, 0)
{query, params}
end
end
|
lib/ecto/adapter/queryable.ex
| 0.898541 | 0.417954 |
queryable.ex
|
starcoder
|
defmodule Protobuf do
@moduledoc """
`protoc` should always be used to generate code instead of writing the code by hand.
By `use` this module, macros defined in `Protobuf.DSL` will be injected. Most of thee macros
are equal to definition in .proto files.
defmodule Foo do
use Protobuf, syntax: :proto3
defstruct [:a, :b]
field :a, 1, type: :int32
field :b, 2, type: :string
end
Your Protobuf message(module) is just a normal Elixir struct. Some useful functions are also injected,
see "Callbacks" for details. Examples:
foo1 = Foo.new!(%{a: 1})
foo1.b == ""
bin = Foo.encode(foo1)
foo1 == Foo.decode(bin)
Except functions in "Callbacks", some other functions may be defined:
* Extension functions when your Protobuf message use extensions. See `Protobuf.Extension` for details.
* `put_extension(struct, extension_mod, field, value)`
* `get_extension(struct, extension_mod, field, default \\ nil)`
"""
defmacro __using__(opts) do
quote location: :keep do
import Protobuf.DSL, only: [field: 3, field: 2, oneof: 2, extend: 4, extensions: 1]
Module.register_attribute(__MODULE__, :fields, accumulate: true)
Module.register_attribute(__MODULE__, :oneofs, accumulate: true)
Module.register_attribute(__MODULE__, :extends, accumulate: true)
Module.register_attribute(__MODULE__, :extensions, [])
@options unquote(opts)
@before_compile Protobuf.DSL
@behaviour Protobuf
@impl unquote(__MODULE__)
def new() do
Protobuf.Builder.new(__MODULE__)
end
@impl unquote(__MODULE__)
def new(attrs) do
Protobuf.Builder.new(__MODULE__, attrs)
end
@impl unquote(__MODULE__)
def new!(attrs) do
Protobuf.Builder.new!(__MODULE__, attrs)
end
@impl unquote(__MODULE__)
def transform_module() do
nil
end
defoverridable transform_module: 0
@impl unquote(__MODULE__)
def decode(data), do: Protobuf.Decoder.decode(data, __MODULE__)
@impl unquote(__MODULE__)
def encode(struct), do: Protobuf.Encoder.encode(struct)
end
end
@doc """
Builds a blank struct with default values. This and other "new" functions are
preferred than raw building struct method like `%Foo{}`.
In proto3, the zero values are the default values.
"""
@callback new() :: struct()
@doc """
Builds and updates the struct with passed fields.
This function will:
* Recursively call `c:new/1` for embedded fields
* Create structs using `struct/2` for keyword lists and maps
* Create the correct struct if passed the wrong struct
* Call `c:new/1` for each element in the list for repeated fields
## Examples
MyMessage.new(field1: "foo")
#=> %MyMessage{field1: "foo", ...}
MyMessage.new(field1: [field2: "foo"])
#=> %MyMessage{field1: %MySubMessage{field2: "foo"}}
MyMessage.new(field1: %WrongStruct{field2: "foo"})
#=> %MyMessage{field1: %MySubMessage{field2: "foo"}}
MyMessage.new(repeated: [%{field1: "foo"}, %{field1: "bar"}])
#=> %MyMessage{repeated: [%MyRepeated{field1: "foo"}, %MyRepeated{field1: "bar"}]}
"""
@callback new(Enum.t()) :: struct
@doc """
Similar to `c:new/1`, but use `struct!/2` to build the struct, so
errors will be raised if unknown keys are passed.
"""
@callback new!(Enum.t()) :: struct()
@doc """
Encodes the given struct into to a Protobuf binary.
Errors may be raised if there's something wrong in the struct.
If you want to encode to iodata instead of to a binary, use `encode_to_iodata/1`.
"""
@callback encode(struct()) :: binary()
@doc """
Decodes a Protobuf binary into a struct.
Errors may be raised if there's something wrong in the binary.
"""
@callback decode(binary()) :: struct()
@doc """
Returns `nil` or a transformer module that implements the `Protobuf.TransformModule`
behaviour.
This function is overridable in your module.
"""
@callback transform_module() :: module() | nil
@doc """
Decodes the given binary data interpreting it as the Protobuf message `module`.
It's preferrable to use the message's `c:decode/1` function. For a message `MyMessage`:
MyMessage.decode(<<...>>)
#=> %MyMessage{...}
This function raises an error if anything goes wrong with decoding.
## Examples
Protobuf.decode(<<...>>, MyMessage)
#=> %MyMessage{...}
Protobuf.decode(<<"bad data">>, MyMessage)
#=> ** (Protobuf.DecodeError) ...
"""
@spec decode(binary(), message) :: %{required(:__struct__) => message} when message: module()
defdelegate decode(data, module), to: Protobuf.Decoder
@doc """
Encodes the given Protobuf struct into a binary.
If you want to encode to iodata instead, see `encode_to_iodata/1`.
## Examples
struct = MyMessage.new()
Protobuf.encode(struct)
#=> <<...>>
"""
@spec encode(struct()) :: binary()
defdelegate encode(struct), to: Protobuf.Encoder
@doc """
Encodes the given Protobuf struct into iodata.
## Examples
struct = MyMessage.new()
Protobuf.encode_to_iodata(struct)
#=> [...]
"""
@spec encode_to_iodata(struct()) :: iodata()
defdelegate encode_to_iodata(struct), to: Protobuf.Encoder
@doc """
Returns the unknown fields that were decoded but were not understood from the schema.
In Protobuf, you can decode a payload (for the same message) encoded with a different version of
the schema for that message. This can result in, for example, the payload containing fields that
cannot be decoded correctly because they're not present in the schema used for decoding. These
fields are skipped, but in some cases you might wish to preserve them in order to re-encode
them, log them, or other. A common case is having to do "round-trips" with messages: you decode
a payload, update the resulting message somehow, and re-encode it for future use. In these
cases, you would probably want to re-encode the unknown fields to maintain symmetry.
The returned value of this function is a list of `{field_number, field_value}` tuples where
`field_number` is the number of the unknown field in the schema used for its encoding and
`field_value` is its value. The library does not make any assumptions on the value of the
field since it can't know for sure. This means that, for example, it can't properly decode
an integer as signed or unsigned. The only guarantee is that the unknown fields are re-encoded
correctly.
The reason why these fields need to be accessed through this function is that the way they
are stored in the struct is private.
## Examples
Imagine you have this Protobuf schema:
message User {
string email = 1;
}
You encode this:
payload = Protobuf.encode(User.new!(email: "<EMAIL>))
#=> <<...>>
Now, you try to decode this payload using this schema instead:
message User {
string full_name = 2;
}
In this case, this function will return the decoded unknown field:
message = User.decode(<<...>>)
Protobuf.get_unknown_fields(message)
#=> [{_field_number = 1, _wire_type = 3, "<EMAIL>}]
"""
@doc since: "0.10.0"
@spec get_unknown_fields(struct()) :: [unknown_field]
when unknown_field:
{field_number :: integer(), Protobuf.Wire.Types.wire_type(), value :: any()}
def get_unknown_fields(message)
def get_unknown_fields(%_{__unknown_fields__: unknown_fields}) do
unknown_fields
end
def get_unknown_fields(%mod{}) do
raise ArgumentError,
"can't retrieve unknown fields for struct #{inspect(mod)}, which " <>
"likely means that its definition was not compiled with :protobuf 0.10.0+, which is the " <>
"version that introduced implicit struct generation"
end
@doc """
Loads extensions modules.
This function should be called in your application's `c:Application.start/2` callback,
as seen in the example below, if you wish to use extensions.
## Example
@impl Application
def start(_type, _args) do
Protobuf.load_extensions()
Supervisor.start_link([], strategy: :one_for_one)
end
"""
@spec load_extensions() :: :ok
def load_extensions() do
Protobuf.Extension.__cal_extensions__()
:ok
end
end
|
lib/protobuf.ex
| 0.924108 | 0.481759 |
protobuf.ex
|
starcoder
|
defmodule Highlander do
@moduledoc """
Highlander allows you to run a single globally unique process in a cluster.
Highlander uses erlang's `:global` module to ensure uniqueness, and uses `child_spec.id` as the uniqueness key.
Highlander will start its child process just once in a cluster. The first Highlander process will start its child, all other Highlander processes will monitor the first process and attempt to take over when it goes down.
_Note: You can also use Highlander to start a globally unique supervision tree._
## Usage
Simply wrap a child process with `{Highlander, child}`.
Before:
```
children = [
child_spec
]
Supervisor.init(children, strategy: :one_for_one)
```
After:
```
children = [
{Highlander, child_spec}
]
Supervisor.init(children, strategy: :one_for_one)
```
See the [documentation on Supervisor.child_spec/1](https://hexdocs.pm/elixir/Supervisor.html#module-child_spec-1) for more information.
## `child_spec.id` is used to determine global uniqueness
Ensure that `child_spec.id` has the correct value! Check the debug logs if you are unsure what is being used.
## Globally unique supervisors
You can also have Highlander run a supervisor:
```
children = [
{Highlander, {MySupervisor, arg}},
]
```
## Handling netsplits
If there is a netsplit in your cluster, then Highlander will think that the other process has died, and start a new one. When the split heals, `:global` will recognize that there is a naming conflict, and will take action to rectify that. To deal with this, Highlander simply terminates one of the two child processes with reason `:shutdown`.
To catch this, simply trap exits in your process and add a `terminate/2` callback.
Note: The `terminate/2` callback will also run when your application is terminating.
```
def init(arg) do
Process.flag(:trap_exit, true)
{:ok, initial_state(arg)}
end
def terminate(_reason, _state) do
# this will run when the process receives an exit signal from its parent
end
```
## Finding your process' PID
Your process is registered under a globally unique supervisor name, like `{Highlander, MyServer}`. In order to send a message to your server however, you need to find the PID of the server itself, not the wrapping `Highlander` process. You can do so as follows:
highlander_pid = :global.whereis_name({Highlander, MyServer})
my_actual_server_pid = GenServer.call(highlander_pid, :get_pid)
"""
use GenServer
require Logger
def child_spec(child_child_spec) do
child_child_spec = Supervisor.child_spec(child_child_spec, [])
Logger.debug("Starting Highlander with #{inspect(child_child_spec.id)} as uniqueness key")
%{
id: child_child_spec.id,
start: {GenServer, :start_link, [__MODULE__, child_child_spec, []]}
}
end
@impl true
def init(child_spec) do
Process.flag(:trap_exit, true)
{:ok, register(%{child_spec: child_spec})}
end
@impl true
def handle_info({:DOWN, ref, :process, _, _}, %{ref: ref} = state) do
{:noreply, register(state)}
end
def handle_info({:EXIT, _pid, :name_conflict}, %{pid: pid} = state) do
:ok = Supervisor.stop(pid, :shutdown)
{:stop, {:shutdown, :name_conflict}, Map.delete(state, :pid)}
end
@impl true
def handle_call(:get_pid, _from, state) do
pid =
state.pid
|> Supervisor.which_children()
|> case do
[{_, pid, _, _}] when pid not in [:restarting, :undefined] -> pid
_ -> nil
end
{:reply, pid, state}
end
@impl true
def terminate(reason, %{pid: pid}) do
:ok = Supervisor.stop(pid, reason)
end
def terminate(_, _), do: nil
defp name(%{child_spec: %{id: global_name}}) do
{__MODULE__, global_name}
end
defp handle_conflict(_name, pid1, pid2) do
Process.exit(pid2, :name_conflict)
pid1
end
defp register(state) do
case :global.register_name(name(state), self(), &handle_conflict/3) do
:yes -> start(state)
:no -> monitor(state)
end
end
defp start(state) do
{:ok, pid} = Supervisor.start_link([state.child_spec], strategy: :one_for_one)
Map.put(state, :pid, pid)
end
defp monitor(state) do
case :global.whereis_name(name(state)) do
:undefined ->
register(state)
pid ->
ref = Process.monitor(pid)
%{child_spec: state.child_spec, ref: ref}
end
end
end
|
lib/highlander.ex
| 0.824885 | 0.926901 |
highlander.ex
|
starcoder
|
defmodule MerklePatriciaTree.Trie.Node do
@moduledoc """
This module encodes and decodes nodes from a
trie encoding back into RLP form. We effectively implement
`c(I, i)` from the Yellow Paper.
"""
alias MerklePatriciaTree.Trie.Storage
alias MerklePatriciaTree.{HexPrefix, Trie}
@type trie_node ::
:empty
| {:leaf, [integer()], binary()}
| {:ext, [integer()], binary()}
| {:branch, [binary()]}
defguardp is_branch(nodes) when length(nodes) == 17
@doc """
Given a node, this function will encode the node
and put the value to storage (for nodes that are
greater than 32 bytes encoded). This implements
`c(I, i)`, Eq.(193) of the Yellow Paper.
## Examples
iex> trie = MerklePatriciaTree.Trie.new(MerklePatriciaTree.Test.random_ets_db())
iex> MerklePatriciaTree.Trie.Node.encode_node(:empty, trie)
<<>>
iex> trie = MerklePatriciaTree.Trie.new(MerklePatriciaTree.Test.random_ets_db())
iex> MerklePatriciaTree.Trie.Node.encode_node({:leaf, [5,6,7], "ok"}, trie)
["5g", "ok"]
iex> trie = MerklePatriciaTree.Trie.new(MerklePatriciaTree.Test.random_ets_db())
iex> MerklePatriciaTree.Trie.Node.encode_node({:branch, [<<>>, <<>>, <<>>, <<>>, <<>>, <<>>, <<>>, <<>>, <<>>, <<>>, <<>>, <<>>, <<>>, <<>>, <<>>, <<>>, <<>>]}, trie)
["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]
iex> trie = MerklePatriciaTree.Trie.new(MerklePatriciaTree.Test.random_ets_db())
iex> MerklePatriciaTree.Trie.Node.encode_node({:ext, [1, 2, 3], <<>>}, trie)
[<<17, 35>>, ""]
"""
@spec encode_node(trie_node, Trie.t()) :: nil | binary()
def encode_node(trie_node, trie) do
trie_node
|> encode_node_type()
|> Storage.put_node(trie)
end
defp encode_node_type({:leaf, key, value}) do
[HexPrefix.encode({key, true}), value]
end
defp encode_node_type({:branch, nodes}) when is_branch(nodes) do
nodes
end
defp encode_node_type({:ext, shared_prefix, next_node}) do
[HexPrefix.encode({shared_prefix, false}), next_node]
end
defp encode_node_type(:empty) do
<<>>
end
@doc """
Decodes the root of a given trie, effectively
inverting the encoding from `c(I, i)` defined in
Eq.(179) of the Yellow Paper.
## Examples
iex> MerklePatriciaTree.Trie.new(MerklePatriciaTree.Test.random_ets_db(), <<128>>)
iex> |> MerklePatriciaTree.Trie.Node.decode_trie()
:empty
iex> MerklePatriciaTree.Trie.new(MerklePatriciaTree.Test.random_ets_db(), <<198, 130, 53, 103, 130, 111, 107>>)
iex> |> MerklePatriciaTree.Trie.Node.decode_trie()
{:leaf, [5,6,7], "ok"}
iex> MerklePatriciaTree.Trie.new(MerklePatriciaTree.Test.random_ets_db(), <<209, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128>>)
iex> |> MerklePatriciaTree.Trie.Node.decode_trie()
{:branch, [<<>>, <<>>, <<>>, <<>>, <<>>, <<>>, <<>>, <<>>, <<>>, <<>>, <<>>, <<>>, <<>>, <<>>, <<>>, <<>>, <<>>]}
iex> MerklePatriciaTree.Trie.new(MerklePatriciaTree.Test.random_ets_db(), <<196, 130, 17, 35, 128>>)
iex> |> MerklePatriciaTree.Trie.Node.decode_trie()
{:ext, [1, 2, 3], <<>>}
"""
@spec decode_trie(Trie.t()) :: trie_node
def decode_trie(trie) do
case Storage.get_node(trie) do
nil ->
:empty
<<>> ->
:empty
# Empty branch node
[] ->
:empty
:not_found ->
:empty
node ->
decode_node(node)
end
end
defp decode_node(nodes) when is_branch(nodes) do
{:branch, nodes}
end
# Extension or leaf node
defp decode_node([hp_key, value]) do
{prefix, is_leaf} = HexPrefix.decode(hp_key)
type = if is_leaf, do: :leaf, else: :ext
{type, prefix, value}
end
end
|
apps/merkle_patricia_tree/lib/merkle_patricia_tree/trie/node.ex
| 0.859649 | 0.521349 |
node.ex
|
starcoder
|
defmodule AWS.ApplicationAutoScaling do
@moduledoc """
With Application Auto Scaling, you can configure automatic scaling for the
following resources:
<ul> <li> Amazon ECS services
</li> <li> Amazon EC2 Spot Fleet requests
</li> <li> Amazon EMR clusters
</li> <li> Amazon AppStream 2.0 fleets
</li> <li> Amazon DynamoDB tables and global secondary indexes throughput
capacity
</li> <li> Amazon Aurora Replicas
</li> <li> Amazon SageMaker endpoint variants
</li> <li> Custom resources provided by your own applications or services
</li> <li> Amazon Comprehend document classification endpoints
</li> <li> AWS Lambda function provisioned concurrency
</li> <li> Amazon Keyspaces (for Apache Cassandra) tables
</li> </ul> **API Summary**
The Application Auto Scaling service API includes three key sets of
actions:
<ul> <li> Register and manage scalable targets - Register AWS or custom
resources as scalable targets (a resource that Application Auto Scaling can
scale), set minimum and maximum capacity limits, and retrieve information
on existing scalable targets.
</li> <li> Configure and manage automatic scaling - Define scaling policies
to dynamically scale your resources in response to CloudWatch alarms,
schedule one-time or recurring scaling actions, and retrieve your recent
scaling activity history.
</li> <li> Suspend and resume scaling - Temporarily suspend and later
resume automatic scaling by calling the
[RegisterScalableTarget](https://docs.aws.amazon.com/autoscaling/application/APIReference/API_RegisterScalableTarget.html)
API action for any Application Auto Scaling scalable target. You can
suspend and resume (individually or in combination) scale-out activities
that are triggered by a scaling policy, scale-in activities that are
triggered by a scaling policy, and scheduled scaling.
</li> </ul> To learn more about Application Auto Scaling, including
information about granting IAM users required permissions for Application
Auto Scaling actions, see the [Application Auto Scaling User
Guide](https://docs.aws.amazon.com/autoscaling/application/userguide/what-is-application-auto-scaling.html).
"""
@doc """
Deletes the specified scaling policy for an Application Auto Scaling
scalable target.
Deleting a step scaling policy deletes the underlying alarm action, but
does not delete the CloudWatch alarm associated with the scaling policy,
even if it no longer has an associated action.
For more information, see [Delete a Step Scaling
Policy](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-step-scaling-policies.html#delete-step-scaling-policy)
and [Delete a Target Tracking Scaling
Policy](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-target-tracking.html#delete-target-tracking-policy)
in the *Application Auto Scaling User Guide*.
"""
def delete_scaling_policy(client, input, options \\ []) do
request(client, "DeleteScalingPolicy", input, options)
end
@doc """
Deletes the specified scheduled action for an Application Auto Scaling
scalable target.
For more information, see [Delete a Scheduled
Action](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-scheduled-scaling.html#delete-scheduled-action)
in the *Application Auto Scaling User Guide*.
"""
def delete_scheduled_action(client, input, options \\ []) do
request(client, "DeleteScheduledAction", input, options)
end
@doc """
Deregisters an Application Auto Scaling scalable target when you have
finished using it. To see which resources have been registered, use
[DescribeScalableTargets](https://docs.aws.amazon.com/autoscaling/application/APIReference/API_DescribeScalableTargets.html).
<note> Deregistering a scalable target deletes the scaling policies and the
scheduled actions that are associated with it.
</note>
"""
def deregister_scalable_target(client, input, options \\ []) do
request(client, "DeregisterScalableTarget", input, options)
end
@doc """
Gets information about the scalable targets in the specified namespace.
You can filter the results using `ResourceIds` and `ScalableDimension`.
"""
def describe_scalable_targets(client, input, options \\ []) do
request(client, "DescribeScalableTargets", input, options)
end
@doc """
Provides descriptive information about the scaling activities in the
specified namespace from the previous six weeks.
You can filter the results using `ResourceId` and `ScalableDimension`.
"""
def describe_scaling_activities(client, input, options \\ []) do
request(client, "DescribeScalingActivities", input, options)
end
@doc """
Describes the Application Auto Scaling scaling policies for the specified
service namespace.
You can filter the results using `ResourceId`, `ScalableDimension`, and
`PolicyNames`.
For more information, see [Target Tracking Scaling
Policies](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-target-tracking.html)
and [Step Scaling
Policies](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-step-scaling-policies.html)
in the *Application Auto Scaling User Guide*.
"""
def describe_scaling_policies(client, input, options \\ []) do
request(client, "DescribeScalingPolicies", input, options)
end
@doc """
Describes the Application Auto Scaling scheduled actions for the specified
service namespace.
You can filter the results using the `ResourceId`, `ScalableDimension`, and
`ScheduledActionNames` parameters.
For more information, see [Scheduled
Scaling](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-scheduled-scaling.html)
in the *Application Auto Scaling User Guide*.
"""
def describe_scheduled_actions(client, input, options \\ []) do
request(client, "DescribeScheduledActions", input, options)
end
@doc """
Creates or updates a scaling policy for an Application Auto Scaling
scalable target.
Each scalable target is identified by a service namespace, resource ID, and
scalable dimension. A scaling policy applies to the scalable target
identified by those three attributes. You cannot create a scaling policy
until you have registered the resource as a scalable target.
Multiple scaling policies can be in force at the same time for the same
scalable target. You can have one or more target tracking scaling policies,
one or more step scaling policies, or both. However, there is a chance that
multiple policies could conflict, instructing the scalable target to scale
out or in at the same time. Application Auto Scaling gives precedence to
the policy that provides the largest capacity for both scale out and scale
in. For example, if one policy increases capacity by 3, another policy
increases capacity by 200 percent, and the current capacity is 10,
Application Auto Scaling uses the policy with the highest calculated
capacity (200% of 10 = 20) and scales out to 30.
We recommend caution, however, when using target tracking scaling policies
with step scaling policies because conflicts between these policies can
cause undesirable behavior. For example, if the step scaling policy
initiates a scale-in activity before the target tracking policy is ready to
scale in, the scale-in activity will not be blocked. After the scale-in
activity completes, the target tracking policy could instruct the scalable
target to scale out again.
For more information, see [Target Tracking Scaling
Policies](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-target-tracking.html)
and [Step Scaling
Policies](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-step-scaling-policies.html)
in the *Application Auto Scaling User Guide*.
<note> If a scalable target is deregistered, the scalable target is no
longer available to execute scaling policies. Any scaling policies that
were specified for the scalable target are deleted.
</note>
"""
def put_scaling_policy(client, input, options \\ []) do
request(client, "PutScalingPolicy", input, options)
end
@doc """
Creates or updates a scheduled action for an Application Auto Scaling
scalable target.
Each scalable target is identified by a service namespace, resource ID, and
scalable dimension. A scheduled action applies to the scalable target
identified by those three attributes. You cannot create a scheduled action
until you have registered the resource as a scalable target.
When start and end times are specified with a recurring schedule using a
cron expression or rates, they form the boundaries of when the recurring
action starts and stops.
To update a scheduled action, specify the parameters that you want to
change. If you don't specify start and end times, the old values are
deleted.
For more information, see [Scheduled
Scaling](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-scheduled-scaling.html)
in the *Application Auto Scaling User Guide*.
<note> If a scalable target is deregistered, the scalable target is no
longer available to run scheduled actions. Any scheduled actions that were
specified for the scalable target are deleted.
</note>
"""
def put_scheduled_action(client, input, options \\ []) do
request(client, "PutScheduledAction", input, options)
end
@doc """
Registers or updates a scalable target.
A scalable target is a resource that Application Auto Scaling can scale out
and scale in. Scalable targets are uniquely identified by the combination
of resource ID, scalable dimension, and namespace.
When you register a new scalable target, you must specify values for
minimum and maximum capacity. Application Auto Scaling scaling policies
will not scale capacity to values that are outside of this range.
After you register a scalable target, you do not need to register it again
to use other Application Auto Scaling operations. To see which resources
have been registered, use
[DescribeScalableTargets](https://docs.aws.amazon.com/autoscaling/application/APIReference/API_DescribeScalableTargets.html).
You can also view the scaling policies for a service namespace by using
[DescribeScalableTargets](https://docs.aws.amazon.com/autoscaling/application/APIReference/API_DescribeScalableTargets.html).
If you no longer need a scalable target, you can deregister it by using
[DeregisterScalableTarget](https://docs.aws.amazon.com/autoscaling/application/APIReference/API_DeregisterScalableTarget.html).
To update a scalable target, specify the parameters that you want to
change. Include the parameters that identify the scalable target: resource
ID, scalable dimension, and namespace. Any parameters that you don't
specify are not changed by this update request.
"""
def register_scalable_target(client, input, options \\ []) do
request(client, "RegisterScalableTarget", input, options)
end
@spec request(AWS.Client.t(), 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: "application-autoscaling"}
host = build_host("application-autoscaling", client)
url = build_url(host, client)
headers = [
{"Host", host},
{"Content-Type", "application/x-amz-json-1.1"},
{"X-Amz-Target", "AnyScaleFrontendService.#{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, %HTTPoison.Response{status_code: 200, body: ""} = response} ->
{:ok, nil, response}
{:ok, %HTTPoison.Response{status_code: 200, body: body} = response} ->
{:ok, Poison.Parser.parse!(body, %{}), response}
{:ok, %HTTPoison.Response{body: body}} ->
error = Poison.Parser.parse!(body, %{})
{:error, error}
{:error, %HTTPoison.Error{reason: reason}} ->
{:error, %HTTPoison.Error{reason: reason}}
end
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, %{:proto => proto, :port => port}) do
"#{proto}://#{host}:#{port}/"
end
end
|
lib/aws/application_auto_scaling.ex
| 0.930789 | 0.605799 |
application_auto_scaling.ex
|
starcoder
|
defmodule Scenic.Math.Matrix.Utils do
@moduledoc """
Helper functions for working with matrices.
The matrix format for the main Scenic.Math.Matrix functions is a 64 byte binary
blob containing 16 4-byte floats. This is great for doing the math in code,
but not so great for reading or understanding the values by a human.
These functions transform more readable/writable formats into the binary blob
and vice versa.
"""
alias Scenic.Math
# @default_major :row
# @matrix_size 4 * 16
# --------------------------------------------------------
# binary format is column-major
@doc """
Convert a readable format into a binary blob.
Parameters:
* matrix_list - a list of 16 numbers
Returns:
A binary matrix blob
"""
@spec to_binary(matrix :: Math.matrix_list()) :: Math.matrix()
def to_binary(matrix_list)
# --------------------------------------------------------
# binary format is column-major
def to_binary([
a00,
a10,
a20,
a30,
a01,
a11,
a21,
a31,
a02,
a12,
a22,
a32,
a03,
a13,
a23,
a33
]) do
<<
a00::float-size(32)-native,
a10::float-size(32)-native,
a20::float-size(32)-native,
a30::float-size(32)-native,
a01::float-size(32)-native,
a11::float-size(32)-native,
a21::float-size(32)-native,
a31::float-size(32)-native,
a02::float-size(32)-native,
a12::float-size(32)-native,
a22::float-size(32)-native,
a32::float-size(32)-native,
a03::float-size(32)-native,
a13::float-size(32)-native,
a23::float-size(32)-native,
a33::float-size(32)-native
>>
end
@doc """
Convert a binary matrix into a list of 16 numbers.
Parameters:
* matrix - a binary matrix
Returns:
A list of 16 nubmers
"""
def to_list(matrix)
def to_list(<<
a00::float-size(32)-native,
a10::float-size(32)-native,
a20::float-size(32)-native,
a30::float-size(32)-native,
a01::float-size(32)-native,
a11::float-size(32)-native,
a21::float-size(32)-native,
a31::float-size(32)-native,
a02::float-size(32)-native,
a12::float-size(32)-native,
a22::float-size(32)-native,
a32::float-size(32)-native,
a03::float-size(32)-native,
a13::float-size(32)-native,
a23::float-size(32)-native,
a33::float-size(32)-native
>>) do
[
a00,
a10,
a20,
a30,
a01,
a11,
a21,
a31,
a02,
a12,
a22,
a32,
a03,
a13,
a23,
a33
]
end
end
|
lib/scenic/math/matrix_utils.ex
| 0.867556 | 0.480052 |
matrix_utils.ex
|
starcoder
|
defmodule D3 do
def p1(input) do
list_of_numbers = String.split(input)
frequencies = calc_frequencies(list_of_numbers)
gamma = rate_value(Enum.reverse(frequencies), {0, 0}, :gamma)
epsilon = rate_value(Enum.reverse(frequencies), {0, 0}, :epsilon)
gamma * epsilon
end
def p2(input) do
oxygen = String.split(input) |> rating_value(0, :oxygen)
co2 = String.split(input) |> rating_value(0, :co2)
oxygen * co2
end
defp calc_frequencies(list_of_numbers) do
list_of_numbers
|> Enum.map(&String.graphemes/1)
|> Enum.zip()
|> Enum.map(&Tuple.to_list/1)
|> Enum.map(&Enum.frequencies/1)
end
defp rate_value([head | tail], {digits_count, acc}, rate_type) do
rate_fn =
case rate_type do
:gamma -> &Enum.max/1
:epsilon -> &Enum.min/1
end
saught_val = head |> Map.values() |> rate_fn.()
digit = head |> Enum.find(fn {_, val} -> val == saught_val end) |> elem(0)
acc =
case digit do
"1" -> acc + Integer.pow(2, digits_count)
"0" -> acc
end
rate_value(tail, {digits_count + 1, acc}, rate_type)
end
defp rate_value([], {_, acc}, _) do
acc
end
defp rating_value([single_elem], _, _) do
{int_val, _} = Integer.parse(single_elem, 2)
int_val
end
defp rating_value([head | tail], digit_index, rating_type) do
list_of_numbers = [head | tail]
frequencies = calc_frequencies(list_of_numbers)
rating_fn =
case rating_type do
:oxygen -> &Enum.max/1
:co2 -> &Enum.min/1
end
digits_at_index = frequencies |> Enum.at(digit_index)
digit =
if length(digits_at_index |> Map.values() |> Enum.uniq()) == 1 do
case rating_type do
:oxygen -> "1"
:co2 -> "0"
end
else
saught_val = digits_at_index |> Map.values() |> rating_fn.()
digits_at_index
|> Enum.find(fn {_, val} -> val == saught_val end)
|> elem(0)
end
list_of_numbers
|> Enum.filter(fn x -> Enum.at(String.graphemes(x), digit_index) == digit end)
|> rating_value(digit_index + 1, rating_type)
end
end
|
d03/lib/d3.ex
| 0.544075 | 0.540378 |
d3.ex
|
starcoder
|
defmodule Lumberjack do
@moduledoc """
Documentation for `Lumberjack`.
"""
@doc """
Hello world.
## Examples
iex> Lumberjack.hello()
:world
"""
def hello do
:world
end
def split(seq) do split(seq, 0, [], []) end
def split([], l, left, right) do
[{left, right, l}]
end
def split([s|rest], l, left, right) do
split(rest, l+s, [s|left], right) ++ split(rest, l+s, left, [s|right])
end
def cost([]) do 0 end
def cost([h]) do {0, h} end
def cost(seq) do cost(seq, 0, [], []) end
def cost([], l, left, right) do
{cl, tl} = cost(left)
{cr, tr} = cost(right)
{cl+cr+l, {tl, tr}}
end
def cost([s], l, [], right) do
{cr, tr} = cost(right)
{cr+l+s, {s, tr}}
end
def cost([s], l, left, []) do
{cl, tl} = cost(left)
{cl+l+s, {s, tl}}
end
def cost([s|rest], l, left, right) do
{costl, tl} = cost(rest, l+s, [s|left], right)
{costr, tr} = cost(rest, l+s, left, [s|right])
if costl < costr do
{costl, tl}
else
{costr, tr}
end
end
def cost2_0([]) do {0, :nope} end
def cost2_0(seq) do
{cost, tree, _} = cost2_0(Enum.sort(seq), Memo.new())
{cost, tree}
end
def cost2_0([s], mem) do {0, s, mem} end
def cost2_0([s|rest]=seq, mem) do
{c, t, mem} = cost2_0(rest, s, [s], [], mem)
{c, t, Memo.add(mem, seq, {c, t})}
end
def cost2_0([], l, left, right, mem) do
{cl, tl, mem} = check(Enum.reverse(left), mem)
{cr, tr, mem} = check(Enum.reverse(right), mem)
{cr+cl+l, {tl, tr}, mem}
end
def cost2_0([s], l, left, [], mem) do
{c, t, mem} = check(Enum.reverse(left), mem)
{c+s+l, {t, s}, mem}
end
def cost2_0([s], l, [], right, mem) do
{c, t, mem} = check(Enum.reverse(right), mem)
{c+s+l, {t, s}, mem}
end
def cost2_0([s|rest], l, left, right, mem) do
{cl, tl, mem} = cost2_0(rest, l+s, [s|left], right, mem)
{cr, tr, mem} = cost2_0(rest, l+s, left, [s|right], mem)
if cl < cr do
{cl, tl, mem}
else
{cr, tr, mem}
end
end
def check(seq, mem) do
case Memo.lookup(mem, seq) do
nil ->
cost2_0(seq, mem)
{c, t} ->
{c, t, mem}
end
end
def bench(n) do
for i <- 1..n do
{t,_} = :timer.tc(fn() -> cost2_0(Enum.to_list(1..i)) end)
IO.puts(" n = #{i}\t t = #{t} us")
end
end
end
|
lumberjack/lib/lumberjack.ex
| 0.728362 | 0.652982 |
lumberjack.ex
|
starcoder
|
defmodule Textwrap do
@moduledoc """
`Textwrap` provides a set of functions for wrapping, indenting, and dedenting text. It wraps the Rust [`textwrap`](https://lib.rs/textwrap) crate.
## Wrapping
Use `wrap/2` to turn a `String` into a list of `String`s each no more
than `width` characters long.
iex> Textwrap.wrap("foo bar baz", 3)
["foo", "bar", "baz"]
iex> Textwrap.wrap("foo bar baz", 7)
["foo bar", "baz"]
`fill/2` is like `wrap/2`, except that it retuns the wrapped text
as a single `String`.
iex> Textwrap.fill("foo bar baz", 3)
"foo\\nbar\\nbaz"
iex> Textwrap.fill("foo bar baz", 7)
"foo bar\\nbaz"
Both `wrap/2` and `fill/2` can either take the width to wrap too
as their second argument, or take a keyword list including a `:width`
key and any number of other options. See the docs for `wrap/2` for
details.
## Displayed Width vs Byte Width
`Textwrap` wraps text based on measured display width, not simply counting bytes.
For ascii text this gives exactly the same result, but many non-ASCII characters
take up more than one byte in the UTF-8 encoding.
See the documentation of the [`textwrap` crate](https://docs.rs/textwrap/0.13.2/textwrap/index.html#displayed-width-vs-byte-size) for more details.
## Terminal Width
The `width` passed to `wrap/2` or `fill/2` can either by a positive integer, or
the atom `:termwidth`. When standard output is connected to a terminal, passing
`:termwidth` will wrap the text to the width of the terminal. Otherwise, it
will use a width of 80 characters as a fallback.
## Indenting and Dedenting
Use `indent/2` and `dedent/1` to indent and dedent text:
iex> Textwrap.indent("hello\\nworld\\n", " ")
" hello\\n world\\n"
iex> Textwrap.dedent(" hello\\n world\\n")
"hello\\nworld\\n"
"""
use Rustler, otp_app: :textwrap, crate: "textwrap_nif"
@type wrap_opts() :: pos_integer() | :termwidth | [wrap_opt()]
@type wrap_opt() ::
{:width, pos_integer() | :termwidth}
| {:break_words, boolean()}
| {:initial_indent, String.t()}
| {:splitter, nil | :en_us | false}
| {:subsequent_indent, String.t()}
| {:wrap_algorithm, wrap_algorithm()}
@type wrap_algorithm() :: :first_fit | :optimal_fit
@spec wrap(text :: String.t(), opts :: wrap_opts()) :: [String.t()]
@doc """
Wraps text to the given width.
`wrap/2` returns a list of `Strings`, each of no more than `width` charecters.
Options can be either passed as a keyword list (which must include the key `:width`),
or, if using no options other than `:width`, the width can be passed on its own as
the second argument.
`width` can either by a positive integer or the atom `:termwidth`. See the
[module docs](#module-terminal-width) on `:termwidth` for more details.
## Options
- `:width` — the width to wrap at, a positive integer.
- `:break_words` — allow long words to be broken, if they won't fit on a single line. Setting this to false may cause some lines to be longer than `:width`.
- `:inital_indent` — will be added as a prefix to the first line of the result.
- `:subsequent_indent` — will be added as a prefix to each line other than the first line of the result.
- `:splitter` — when set to `false`, hyphens within words won't be treated specially as a place to split words. When set to `:en_us`, a language-aware hyphenation system will be used to try to break words in appropriate places.
- `:wrap_algorithm` — by default, or when set to `:optimal_fit`, `wrap/2` will do its best to
balance the gaps left at the ends of lines. When set to `:first_fit`, a simpler greedy algorithm
is used instead. See the docs in the [`textwrap` crate](https://docs.rs/textwrap/0.13.2/textwrap/core/enum.WrapAlgorithm.html) for more details.
## Examples
iex> Textwrap.wrap("hello world", 5)
["hello", "world"]
iex> Textwrap.wrap("hello world", width: 5)
["hello", "world"]
iex> Textwrap.wrap("Antidisestablishmentarianism", width: 10)
["Antidisest", "ablishment", "arianism"]
iex> Textwrap.wrap("Antidisestablishmentarianism", width: 10, break_words: false)
["Antidisestablishmentarianism"]
iex> Textwrap.wrap("Antidisestablishmentarianism", width: 10, splitter: :en_us)
["Antidis-", "establish-", "mentarian-", "ism"]
iex> Textwrap.wrap("foo bar baz",
...> width: 5,
...> initial_indent: "> ",
...> subsequent_indent: " ")
["> foo", " bar", " baz"]
iex> Textwrap.wrap("Lorem ipsum dolor sit amet, consectetur adipisicing elit",
...> width: 25,
...> wrap_algorithm: :optimal_fit)
["Lorem ipsum dolor", "sit amet, consectetur", "adipisicing elit"]
iex> Textwrap.wrap("Lorem ipsum dolor sit amet, consectetur adipisicing elit",
...> width: 25,
...> wrap_algorithm: :first_fit)
["Lorem ipsum dolor sit", "amet, consectetur", "adipisicing elit"]
"""
def wrap(text, width_or_opts)
def wrap(text, width) when is_integer(width) or width == :termwidth do
wrap(text, width: width)
end
def wrap(text, opts) do
width = fetch_width!(opts)
wrap_nif(text, width, opts)
end
@spec fill(text :: String.t(), opts :: wrap_opts()) :: String.t()
@doc """
Fills text to the given width.
The result is a `String`, with lines seperated by newline.
The `wrap/2` function does the same thing, except that it returns a list of `Strings`,
one for each line.
See the docs for `wrap/2` for details about the options it takes.
## Examples
iex> Textwrap.fill("hello world", 5)
"hello\\nworld"
iex> Textwrap.fill("hello world", width: 5)
"hello\\nworld"
iex> Textwrap.fill("Antidisestablishmentarianism", width: 10)
"Antidisest\\nablishment\\narianism"
iex> Textwrap.fill("Antidisestablishmentarianism", width: 10, break_words: false)
"Antidisestablishmentarianism"
iex> Textwrap.fill("Antidisestablishmentarianism", width: 10, splitter: :en_us)
"Antidis-\\nestablish-\\nmentarian-\\nism"
iex> Textwrap.fill("foo bar baz",
...> width: 5,
...> initial_indent: "> ",
...> subsequent_indent: " ")
"> foo\\n bar\\n baz"
iex> Textwrap.fill("Lorem ipsum dolor sit amet, consectetur adipisicing elit",
...> width: 25,
...> wrap_algorithm: :optimal_fit)
"Lorem ipsum dolor\\nsit amet, consectetur\\nadipisicing elit"
iex> Textwrap.fill("Lorem ipsum dolor sit amet, consectetur adipisicing elit",
...> width: 25,
...> wrap_algorithm: :first_fit)
"Lorem ipsum dolor sit\\namet, consectetur\\nadipisicing elit"
"""
def fill(text, width_or_opts)
def fill(text, width) when is_integer(width) or width == :termwidth do
fill(text, width: width)
end
def fill(text, opts) do
width = fetch_width!(opts)
fill_nif(text, width, opts)
end
@spec dedent(text :: String.t()) :: String.t()
@doc """
Removes as much common leading whitespace as possible from each line.
Each non-empty line has an equal amount of whitespace removed from its start.
Empty lines (containing only whitespace) are normalized to a single `\\n`, with no other whitespace on the line.
## Examples:
iex> Textwrap.dedent(" hello world")
"hello world"
iex> Textwrap.dedent("
...> foo
...> bar
...> baz
...> ")
"\\nfoo\\n bar\\nbaz\\n"
"""
def dedent(_text), do: :erlang.nif_error(:nif_not_loaded)
@spec indent(text :: String.t(), prefix :: String.t()) :: String.t()
@doc """
Adds a given prefix to each non-empty line.
Empty lines (containing only whitespace) are normalized to a single `\\n`, and not indented.
Any leading and trailing whitespace on non-empty lines is left unchanged.
Examples:
iex> Textwrap.indent("hello world", ">")
">hello world"
iex> Textwrap.indent("foo\\nbar\\nbaz\\n", " ")
" foo\\n bar\\n baz\\n"
"""
def indent(_text, _prefix), do: :erlang.nif_error(:nif_not_loaded)
defp fill_nif(_text, _width, _opts), do: :erlang.nif_error(:nif_not_loaded)
defp wrap_nif(_text, _width, _opts), do: :erlang.nif_error(:nif_not_loaded)
defp fetch_width!(opts) do
case Keyword.fetch!(opts, :width) do
:termwidth -> termwidth()
width -> width
end
end
defp termwidth, do: :erlang.nif_error(:nif_not_loaded)
end
|
lib/textwrap.ex
| 0.936901 | 0.521959 |
textwrap.ex
|
starcoder
|
defmodule Ockam.Services.Kafka.Provider do
@moduledoc """
Implementation for Ockam.Services.Provider
providing kafka stream services, :stream_kafka and :stream_kafka_index
Services arguments:
stream_kafka:
address_prefix: optional<string>, worker address prefix
stream_prefix: optional<string>, kafka topic prefix
endpoints: optional<string | [string] | [{string, integer}]>, kafka bootstrap endpoints, defaults to "localhost:9092"
user: optional<string>, kafka SASL username
password: optional<string>, kafka SASL password, defaults to "" if only user is set
sasl: optional<atom|string>, kafka sasl mode, defaults to "plain"
ssl: optional<boolean>, if kafka server using ssl, defaults to false
replication_factor: optional<integer> replication factor for topics, defaults to 1
stream_kafka_index:
address_prefix: optional<string>, worker address prefix
stream_prefix: optional<string>, kafka topic prefix
endpoints: optional<string | [string] | [{string, integer}]>, kafka bootstrap endpoints, defaults to "localhost:9092"
user: optional<string>, kafka SASL username
password: optional<string>, kafka SASL password, defaults to "" if only user is set
sasl: optional<atom|string>, kafka sasl mode, defaults to "plain"
ssl: optional<boolean> if kafka server using ssl, defaults to false
"""
@behaviour Ockam.Services.Provider
alias Ockam.Kafka.Config, as: KafkaConfig
alias Ockam.Stream.Index.Service, as: StreamIndexService
alias Ockam.Stream.Workers.Service, as: StreamService
@services [:stream_kafka, :stream_kafka_index]
@impl true
def services() do
@services
end
@impl true
def child_spec(service_name, args) do
options = service_options(service_name, args)
mod = service_mod(service_name)
{mod, options}
end
def service_mod(:stream_kafka) do
StreamService
end
def service_mod(:stream_kafka_index) do
StreamIndexService
end
def service_options(:stream_kafka, args) do
address = make_address(args, "stream_kafka")
stream_options = [
storage_mod: Ockam.Stream.Storage.Kafka,
storage_options: storage_options(args)
]
[address: address, stream_options: stream_options]
end
def service_options(:stream_kafka_index, args) do
address = make_address(args, "stream_kafka_index")
[
address: address,
storage_mod: Ockam.Stream.Index.KafkaOffset,
storage_options: storage_options(args)
]
end
def make_address(args, default_address) do
address_prefix = Keyword.get(args, :address_prefix, "")
base_address = Keyword.get(args, :address, default_address)
prefix_address(base_address, address_prefix)
end
def prefix_address(base_address, "") do
base_address
end
def prefix_address(base_address, prefix) do
prefix <> "_" <> base_address
end
def storage_options(args) do
stream_prefix = KafkaConfig.stream_prefix(args)
client_config = KafkaConfig.client_config(args)
replication_factor = KafkaConfig.replication_factor(args)
endpoints = KafkaConfig.endpoints(args)
[
replication_factor: replication_factor,
endpoints: endpoints,
client_config: client_config,
topic_prefix: stream_prefix
]
end
end
|
implementations/elixir/ockam/ockam_kafka/lib/services/provider.ex
| 0.830353 | 0.407864 |
provider.ex
|
starcoder
|
defmodule Bolt.Sips.Response do
@moduledoc """
Support for transforming a Bolt response to a list of Bolt.Sips.Types or arbitrary values.
A Bolt.Sips.Response is used for mapping any response received from a Neo4j server into a an Elixir struct.
You'll interact with this module every time you're needing to get and manipulate the data resulting from your queries.
For example, a simple Cypher query like this:
Bolt.Sips.query(Bolt.Sips.conn(), "RETURN [10,11,21] AS arr")
will return:
{:ok,
%Bolt.Sips.Response{
bookmark: "neo4j:bookmark:v1:tx21868",
fields: ["arr"],
notifications: [],
plan: nil,
profile: nil,
records: [[[10, 11, 21]]],
results: [%{"arr" => [10, 11, 21]}],
stats: [],
type: "r"
}}
and while you have now access to the full data returned by Neo4j, most of the times you'll just want the results:
iex» %Bolt.Sips.Response{results: results} = Bolt.Sips.query!(Bolt.Sips.conn(), "RETURN [10,11,21] AS arr")
iex» results
[%{"arr" => [10, 11, 21]}]
More complex queries, i.e.:
MATCH p=({name:'Alice'})-[r:KNOWS]->({name:'Bob'}) RETURN r
will return `results` like this:
[%{"r" => %Bolt.Sips.Types.Relationship{end: 647, id: 495,
properties: %{}, start: 646, type: "KNOWS"}}]
Note: the `Path` has also functionality for "drawing" a graph, from a given node-relationship path
Our Bolt.Sips.Response is implementing Elixir's [Enumerable Protocol](https://hexdocs.pm/elixir/Enumerable.html), to help you accessing the results. Hence something like this, is possible:
iex» Bolt.Sips.query!(Bolt.Sips.conn(), "RETURN [10,11,21] AS arr") |>
...» Enum.reduce(0, &(Enum.sum(&1["arr"]) + &2))
42
an overly complicated example, but you get the point?! :)
You can also quickly get the `first` of the results, returned by Neo4j. Example:
iex» Bolt.Sips.query!(Bolt.Sips.conn(), "UNWIND range(1, 10) AS n RETURN n") |>
...» Bolt.Sips.Response.first()
%{"n" => 1}
"""
@type t :: %__MODULE__{
results: list,
fields: list,
records: list,
plan: map,
notifications: list,
stats: list,
profile: any,
type: String.t(),
bookmark: String.t()
}
@type key :: any
@type value :: any
@type acc :: any
@type element :: any
defstruct results: [],
fields: nil,
records: [],
plan: nil,
notifications: [],
stats: [],
profile: nil,
type: nil,
bookmark: nil
alias Bolt.Sips.Error
require Logger
require Integer
def first(%__MODULE__{results: []}), do: nil
def first(%__MODULE__{results: [head | _tail]}), do: head
@doc false
# transform a raw Bolt response to a list of Responses
def transform!(records, stats \\ :no) do
with {:ok, %__MODULE__{} = records} <- transform(records, stats) do
records
else
e -> e
end
end
def transform(records, _stats \\ :no) do
# records |> IO.inspect(label: "raw>> lib/bolt_sips/response.ex:44")
with %__MODULE__{fields: fields, records: records} = response <- parse(records) do
{:ok, %__MODULE__{response | results: create_results(fields, records)}}
else
e -> {:error, e}
end
rescue
e in Bolt.Sips.Exception -> {:error, e.message}
e -> {:error, e}
end
def fetch(%Bolt.Sips.Response{fields: fields, results: results}, key) do
with true <- Enum.member?(fields, key) do
findings =
Enum.map(results, fn map ->
Map.get(map, key)
end)
|> Enum.filter(&(&1 != nil))
{:ok, findings}
else
_ -> nil
end
end
def fetch!(%Bolt.Sips.Response{} = r, key) do
with {:ok, findings} = fetch(r, key) do
findings
end
end
defp parse(records) do
with {err_type, error} when err_type in ~w(halt error failure)a <- Error.new(records) do
{:error, error}
else
records ->
response =
records
|> Enum.reduce(%__MODULE__{}, fn {type, record}, acc ->
with {:error, e} <- parse_record(type, record, acc) do
raise Bolt.Sips.Exception, e
else
acc -> acc
end
end)
%__MODULE__{response | records: response.records |> :lists.reverse()}
end
end
# defp parse_record(:success, %{"fields" => fields, "t_first" => 0}, response) do
defp parse_record(:success, %{"fields" => fields}, response) do
%{response | fields: fields}
end
defp parse_record(:success, %{"profile" => profile, "stats" => stats, "type" => type}, response) do
%{response | profile: profile, stats: stats, type: type}
end
defp parse_record(:success, %{"notifications" => n, "plan" => plan, "type" => type}, response) do
%{response | plan: plan, notifications: n, type: type}
end
defp parse_record(:success, %{"plan" => plan, "type" => type}, response) do
%{response | plan: plan, type: type}
end
defp parse_record(:success, %{"stats" => stats, "type" => type}, response) do
%{response | stats: stats, type: type}
end
defp parse_record(:success, %{"bookmark" => bookmark, "type" => type}, response) do
%{response | bookmark: bookmark, type: type}
end
defp parse_record(:success, %{"type" => type}, response) do
%{response | type: type}
end
defp parse_record(:success, %{}, response) do
%{response | type: "boltkit?"}
end
defp parse_record(:success, record, _response) do
line =
"; around: #{
String.replace_leading("#{__ENV__.file}", "#{File.cwd!()}", "") |> Path.relative()
}:#{__ENV__.line()}"
err_msg = "UNKNOWN success type: " <> inspect(record) <> line
Logger.error(err_msg)
{:error, Bolt.Sips.Error.new(err_msg)}
end
# defp parse_record(:record, %{"bookmark" => "neo4j:bookmark:v1:tx14519", "t_last" => 1, "type" => "r"}, response) do
defp parse_record(:record, record, response) do
%{response | records: [record | response.records]}
end
defp parse_record(_type, record, _response) do
line =
"; around: #{
String.replace_leading("#{__ENV__.file}", "#{File.cwd!()}", "") |> Path.relative()
}:#{__ENV__.line()}"
err_msg = "UNKNOWN `:record`: " <> inspect(record) <> line
Logger.error(err_msg)
{:error, Bolt.Sips.Error.new(err_msg)}
end
defp create_results(fields, records) do
records
|> Enum.map(fn recs -> Enum.zip(fields, recs) end)
|> Enum.map(fn data -> Enum.into(data, %{}) end)
end
end
|
lib/bolt_sips/response.ex
| 0.730386 | 0.557243 |
response.ex
|
starcoder
|
defmodule WhereTZ do
@moduledoc """
**WhereTZ** is Elixir version of Ruby gem for lookup of timezone by georgraphic coordinates.
## Example
iex(1)> WhereTZ.lookup(50.004444, 36.231389)
"Europe/Kiev"
iex(2)> WhereTZ.get(50.004444, 36.231389)
#<TimezoneInfo(Europe/Kiev - EET (+02:00:00))>
"""
require Logger
@doc """
Time zone name by coordinates.
- lat Latitude (floating point number)
- lng Longitude (floating point number)
@return {String, nil, Array<String>} time zone name, or `nil` if no time zone corresponds
to (lat, lng); in rare (yet existing) cases of ambiguous timezones may return an array of names
## Example
iex(1)> WhereTZ.lookup(50.004444, 36.231389)
"Europe/Kiev"
"""
@spec lookup(-90..90, -180..180) :: String.t() | nil
def lookup(lat, lng) do
# where = :ets.fun2ms(fn({:geo, zone_name, minx, maxx, miny, maxy, geo_object}) when lng>=minx and lng<=maxx and lat>=miny and lat<=maxy -> {zone_name, geo_object} end)
where = [
{{:geo, :"$1", :"$2", :"$3", :"$4", :"$5", :"$6"},
[
{:andalso,
{:andalso,
{:andalso, {:>=, {:const, lng}, :"$2"},
{:"=<", {:const, lng}, :"$3"}},
{:>=, {:const, lat}, :"$4"}}, {:"=<", {:const, lat}, :"$5"}}
], [{{:"$1", :"$6"}}]}
]
{:atomic, candidates} = :mnesia.transaction(fn() -> :mnesia.select(:geo, where) end)
cond do
length(candidates) == 0 ->
nil
length(candidates) == 1 ->
{zone_name, _geo_object} = hd(candidates)
zone_name
true ->
lookup_geo(lat, lng, candidates)
|> simplify_result()
end
end
@doc """
Timex.TimezoneInfo object by coordinates.
- lat Latitude (floating point number)
- lng Longitude (floating point number)
@return Timex.TimezoneInfo
## Example
iex(1)> WhereTZ.get(50.004444, 36.231389)
#<TimezoneInfo(Europe/Kiev - EET (+02:00:00))>
"""
@spec get(-90..90, -180..180) :: Timex.TimezoneInfo.t() | nil
def get(lat, lng) do
lookup(lat, lng)
|> to_timezone()
end
defp to_timezone(zone) when is_bitstring(zone) do
to_timezone([zone])
end
defp to_timezone(zone) when is_list(zone) do
zone
|> Enum.map(&(Timex.Timezone.get(&1)))
|> Enum.reject(&(&1==nil))
|> simplify_result()
end
defp to_timezone(_), do: nil
defp simplify_result([]), do: nil
defp simplify_result([item]), do: item
defp simplify_result(items), do: items
defp lookup_geo(lat, lng, candidates) do
candidates
|> Enum.filter(fn({_zone_name, geo_object}) ->
Topo.contains?(geo_object, %Geo.Point{ coordinates: {lng, lat}})
end)
|> Enum.map(fn({zone_name, _geo_object}) -> zone_name end)
end
end
|
lib/wheretz.ex
| 0.913305 | 0.482002 |
wheretz.ex
|
starcoder
|
defmodule Eml.Query.Helper do
@moduledoc false
alias Eml.Element
def do_transform(_node, :node, value) do
value
end
def do_transform(%Element{attrs: attrs} = node, { :attrs, key }, value) do
%Element{node|attrs: Map.put(attrs, key, value)}
end
def do_transform(%Element{} = node, key, value) do
Map.put(node, key, value)
end
def do_transform(node, key, _value) do
raise Eml.QueryError, message: "can only set key `#{inspect key}` on an element node, got: #{inspect node}"
end
def do_add(%Element{content: content} = node, expr, op) do
content = if op == :insert do
List.wrap(expr) ++ List.wrap(content)
else
List.wrap(content) ++ List.wrap(expr)
end
%Element{node|content: content}
end
def do_add(node, _expr, op) do
raise Eml.QueryError,
message: "can only #{op} with an element node, got: #{inspect node}"
end
def do_collect(op, acc, key, expr) do
case op do
:put -> Map.put(acc, key, expr)
:insert -> Map.update(acc, key, List.wrap(expr), &(List.wrap(expr) ++ List.wrap(&1)))
:append -> Map.update(acc, key, List.wrap(expr), &(List.wrap(&1) ++ List.wrap(expr)))
end
end
end
defmodule Eml.Query do
@moduledoc """
Provides a DSL for retrieving and manipulating eml.
Queries can be used on its own, but they are best used together with
`Eml.transform/2`, `Eml.collect/3` and the `Enumerable` protocol. Using them
often results in simpler and easier to read code. One of the main conveniences
of queries is that you have easy access to all fields of an element. For
example, all queries support a `where` expression. Inside a `where` expression
you can automatically use the variables `node`, `tag`, `attrs`,
`attrs.{field}`, `content` and `type`. Lets illustrate this with an example of
`node_match?/2`, the simplest query Eml provides:
iex> use Eml
iex> import Eml.Query
iex> node = div [class: "test"], "Hello world"
#div<%{class: "test"} "Hello world">
iex> node_match? node, where: attrs.class == "test"
true
iex> node_match? node, where: tag in [:div, :span]
true
iex> node_match? node, where: tag == :span or is_binary(node)
false
Queries can be divided in two groups: queries that help collecting data from
eml nodes and queries that help transform eml nodes.
## Transform queries
* `put`: puts new data into a node
* `update`: updates data in a node
* `drop`: removes a node
* `insert`: insert new content into a node
* `append`: appends new content to a node
### Transfrom examples
iex> use Eml
iex> import Eml.Query
iex> node = div(42)
#div<42>
iex> put node, "Hello World", in: content, where: content == 42
#div<"Hello World">
iex> insert node, 21, where: tag == :div
#div<[21, 42]>
iex> node = html do
...> head do
...> meta charset: "UTF-8"
...> end
...> body do
...> div class: "person" do
...> div [class: "person-name"], "mike"
...> div [class: "person-age"], 23
...> end
...> div class: "person" do
...> div [class: "person-name"], "john"
...> div [class: "person-age"], 42
...> end
...> end
...> end
iex> Eml.transform(node, fn n ->
...> n
...> |> drop(where: tag == :head)
...> |> update(content, with: &(&1 + 1), where: attrs.class == "person-age")
...> |> update(content, with: &String.capitalize/1, where: attrs.class == "person-name")
...> |> insert(h1("Persons"), where: tag == :body)
...> |> append(div([class: "person-status"], "friend"), where: attrs.class == "person")
...> end)
#html<[#body<[#h1<"Persons">, #div<%{class: "person"}
[#div<%{class: "person-name"} "Mike">, #div<%{class: "person-age"} 24>,
#div<%{class: "person-status"} "friend">]>, #div<%{class: "person"}
[#div<%{class: "person-name"} "John">, #div<%{class: "person-age"} 43>,
#div<%{class: "person-status"} "friend">]>]>]>
## Collect queries
* `put`: get data from a node and put it in a map
* `insert` get data from a node and insert it in a map
* `append` get data from a node and append it to a map
### Collect examples
iex> use Eml
iex> import Eml.Query
iex> node = html do
...> head do
...> meta charset: "UTF-8"
...> end
...> body do
...> div class: "person" do
...> div [class: "person-name"], "mike"
...> div [class: "person-age"], 23
...> end
...> div class: "person" do
...> div [class: "person-name"], "john"
...> div [class: "person-age"], 42
...> end
...> end
...> end
iex> Eml.collect(node, fn n, acc ->
...> acc
...> |> append(n, content, in: :names, where: attrs.class == "person-name")
...> |> append(n, content, in: :ages, where: attrs.class == "person-age")
...> end)
%{ages: [23, 42], names: ["mike", "john"]}
iex> collect_person = fn person_node ->
...> Eml.collect(person_node, fn n, acc ->
...> acc
...> |> put(n, content, in: :name, where: attrs.class == "person-name")
...> |> put(n, content, in: :age, where: attrs.class == "person-age")
...> end)
...> end
iex> Eml.collect(node, fn n, acc ->
...> append(acc, n, content, in: :persons, with: collect_person, where: tag == :div and attrs.class == "person")
...> end)
%{persons: [%{age: 23, name: "mike"}, %{age: 42, name: "john"}]}
## Chaining queries with `pipe`
`Eml.Query` also provide the `pipe/3` macro that makes chains of queries more
readable. The first collect example could be rewritten with the `pipe` macro
like this:
iex> Eml.collect(node, fn n, acc ->
...> pipe acc, inject: n do
...> append content, in: :names, where: attrs.class == "person-name"
...> append content, in: :ages, where: attrs.class == "person-age"
...> end
...> end)
%{ages: [23, 42], names: ["mike", "john"]}
"""
@doc """
Puts new data into a node
iex> node = div(42)
#div<42>
iex> put node, "Hello World", in: content, where: content == 42
#div<"Hello World">
iex> put node, "article", in: attrs.class, where: content == 42
#div<%{class: "article"} 42>
"""
defmacro put(node, expr, opts) do
build_transform(node, prepare_where(opts), fetch!(opts, :in), expr)
end
@doc """
Updates data in a node
iex> node = div do
...> span 21
...> span 101
...> end
#div<[#span<21>, #span<101>]>
iex> Eml.transform node, fn n ->
...> update n, content, with: &(&1 * 2), where: tag == :span
...> end
#div<[#span<42>, #span<202>]>
"""
defmacro update(node, var, opts) do
validate_var(var)
expr = Macro.prewalk(var, &handle_attrs/1)
expr = quote do: unquote(fetch!(opts, :with)).(unquote(expr))
build_transform(node, prepare_where(opts), var, expr)
end
@doc """
Removes a node in a tree
iex> node = div do
...> span [class: "remove-me"], 21
...> span 101
...> end
#div<[#span<%{class: "remove-me"} 21>, #span<101>]>
iex> Eml.transform node, fn n ->
...> drop n, where: attrs.class == "remove-me"
...> end
#div<[#span<101>]>
"""
defmacro drop(node, opts) do
quote do
unquote(inject_vars(node))
if unquote(prepare_where(opts)), do: nil, else: var!(node)
end
end
@doc """
Inserts content into an element node
iex> node = div do
...> span 42
...> end
#div<[#span<42>]>
iex> Eml.transform(node, fn n ->
...> insert n, 21, where: is_integer(content)
...> end
#div<[#span<[21, 42]>]>
"""
defmacro insert(node, expr, opts) do
build_add(node, expr, opts, :insert)
end
@doc """
Appends content into an element node
iex> node = div do
...> span 42
...> end
#div<[#span<42>]>
iex> Eml.transform(node, fn n ->
...> append n, 21, where: is_integer(content)
...> end
#div<[#span<[42, 21]>]>
"""
defmacro append(node, expr, opts) do
build_add(node, expr, opts, :append)
end
@doc """
Collects data from a node and puts it in a map
Optionally accepts a `:with` function that allows processing matched
data before it's being stored in the map.
iex> node = ul do
...> li "Hello World"
...> li 42
...> end
#ul<[#li<"Hello World">, #li<42>]>
iex> Eml.collect(node, fn n, acc ->
...> pipe acc, inject: n do
...> put content, in: :number, where: is_integer(content)
...> put content, in: :text, with: &String.upcase/1, where: is_binary(content)
...> end
...> end)
%{number: 42, text: "HELLO WORLD"}
"""
defmacro put(acc, node, var, opts) do
build_collect(acc, node, var, opts, :put)
end
@doc """
Collects data from a node and inserts at a given key in a map
See `Eml.Query.put/4` for more info.
iex> node = ul do
...> li "Hello World"
...> li 42
...> end
#ul<[#li<"Hello World">, #li<42>]>
iex> Eml.collect(node, fn n, acc ->
...> pipe acc, inject: n do
...> insert content, in: :list, where: is_integer(content)
...> insert content, in: :list, where: is_binary(content)
...> end
...> end)
%{list: [42, "Hello World"]}
"""
defmacro insert(acc, node, var, opts) do
build_collect(acc, node, var, opts, :insert)
end
@doc """
Collects data from a node and appends at a given key in a map
See `Eml.Query.put/4` for more info.
iex> node = ul do
...> li "Hello World"
...> li 42
...> end
#ul<[#li<"Hello World">, #li<42>]>
iex> Eml.collect(node, fn n, acc ->
...> pipe acc, inject: n do
...> append content, in: :list, where: is_integer(content)
...> append content, in: :list, where: is_binary(content)
...> end
...> end)
%{list: ["Hello World", 42]}
"""
defmacro append(acc, node, var, opts) do
build_collect(acc, node, var, opts, :append)
end
@doc """
Allows convenient chaing of queries
See `Eml.Query.put/4` for an example.
"""
defmacro pipe(x, opts \\ [], do: block) do
{ :__block__, _, calls } = block
calls = if arg = Keyword.get(opts, :inject) do
insert_arg(calls, arg)
else
calls
end
pipeline = build_pipeline(x, calls)
quote do
unquote(pipeline)
end
end
@doc """
Returns true if the node matches the `where` expression
iex> node = div [class: "match-me"], 101
#div<%{class: "match-me"} 101>
iex> match_node? node, where: attrs.class == "match-me"
true
"""
defmacro match_node?(node, opts) do
quote do
unquote(inject_vars(node))
unquote(prepare_where(opts))
end
end
defp build_transform(node, where, var, expr) do
key = get_key(var)
quote do
unquote(inject_vars(node))
if unquote(where) do
Eml.Query.Helper.do_transform(var!(node), unquote(key), unquote(expr))
else
var!(node)
end
end
end
defp build_add(node, expr, opts, op) do
quote do
unquote(inject_vars(node))
if unquote(prepare_where(opts)) do
Eml.Query.Helper.do_add(var!(node), unquote(expr), unquote(op))
else
var!(node)
end
end
end
defp build_collect(acc, node, var, opts, op) do
validate_var(var)
key = fetch!(opts, :in)
expr = Macro.prewalk(var, &handle_attrs/1)
expr = if fun = Keyword.get(opts, :with) do
quote do: unquote(fun).(unquote(expr))
else
expr
end
quote do
acc = unquote(acc)
unquote(inject_vars(node))
if unquote(prepare_where(opts)) do
Eml.Query.Helper.do_collect(unquote(op), acc, unquote(key), unquote(expr))
else
acc
end
end
end
defp inject_vars(node) do
quote do
var!(node) = unquote(node)
{ var!(tag), var!(attrs), var!(content), var!(type) } =
case var!(node) do
%Eml.Element{tag: tag, attrs: attrs, content: content, type: type} ->
{ tag, attrs, content, type }
_ ->
{ nil, %{}, nil, nil }
end
_ = var!(node); _ = var!(tag); _ = var!(attrs)
_ = var!(content); _ = var!(type)
end
end
defp get_key({ key, _, _ }) when key in ~w(node tag attrs content type)a do
key
end
defp get_key({ { :., _, [{ :attrs, _, _ }, key] }, _, _ }) do
{ :attrs, key }
end
defp get_key(expr) do
raise Eml.QueryError,
message: "only `node`, `tag`, `attrs`, `attrs.{field}, `content` and `type` are valid, got: #{Macro.to_string(expr)}"
end
defp validate_var(expr) do
get_key(expr)
:ok
end
defp fetch!(keywords, key) do
case Keyword.get(keywords, key, :__undefined) do
:__undefined ->
raise Eml.QueryError, message: "Missing `#{inspect key}` option"
value ->
value
end
end
defp prepare_where(opts) do
Macro.prewalk(fetch!(opts, :where), &handle_attrs/1)
end
defp build_pipeline(expr, calls) do
Enum.reduce(calls, expr, fn call, acc ->
Macro.pipe(acc, call, 0)
end)
end
defp handle_attrs({ { :., _, [{ :attrs, _, _ }, key] }, meta, _ }) do
line = Keyword.get(meta, :line, 0)
quote line: line do
Map.get(var!(attrs), unquote(key))
end
end
defp handle_attrs(expr) do
expr
end
defp insert_arg(calls, arg) do
Enum.map(calls, fn
{ name, meta, args } when is_atom(name) and (is_list(args) or is_atom(args)) ->
args = if is_atom(args), do: [], else: args
{ name, meta, [arg | args] }
_ ->
raise Eml.QueryError, message: "invalid pipeline"
end)
end
end
|
lib/eml/query.ex
| 0.747892 | 0.478346 |
query.ex
|
starcoder
|
defmodule ExRabbitMQ.RPC.Server do
@moduledoc """
*A behavior module for implementing a RabbitMQ RPC server with a `GenServer`.*
It uses the `ExRabbitMQ.Consumer`, which in-turn uses the `AMQP` library to configure and consume messages.
Additionally this module offers a way to receive requests and send back responses easily.
A typical implementation of this behavior is to call the `c:setup_server/3` on `GenServer.init/1` and
implement the `c:handle_request/3` for processing requests and responding back. When the application needs to
respond back, the functions `c:respond/2` or `c:respond/3` can be called to achieve this.
Make sure that before starting a `ExRabbitMQ.RPC.Server` to already run in your supervision tree the
`ExRabbitMQ.Connection.Supervisor`.
**Example**
```elixir
defmodule MyServer do
use GenServer
use ExRabbitMQ.RPC.Server
def start_link(args) do
GenServer.start_link(__MODULE__, args, [])
end
def init(_) do
{:ok, state} = setup_server(:connection, :queue, %{})
{:ok, state}
end
def handle_request(payload, _metadata, state) do
response = do_process_request(payload)
{:respond, response, state}
end
# On consume success, AMQP will send this message to our process.
def handle_info({:basic_consume_ok, _}, state) do
{:noreply, state}
end
end
```
"""
@doc """
Opens a RabbitMQ connection & channel and configures the queue for receiving requests.
This function calls the function `ExRabbitMQ.Consumer.xrmq_init/3` for creating a new RabbitMQ connection &
channel and configure the exchange & queue for consuming incoming requests.
This function is usually called on `GenServer.init/1` callback.
### Parameters
The parameter `connection_config` specifies the configuration of the RabbitMQ connection. If set to an atom,
the configuration will be loaded from the application's config.exs under the app key `:exrabbitmq`,
eg. if the value is set to `:default_connection`, then the config.exs should have configuration like the following:
```elixir
config :exrabbitmq, :default_connection,
username: "guest",
password: "<PASSWORD>",
host: "localhost",
port: 5672
```
The parameter `connection_config` can also be set to the struct `ExRabbitMQ.Config.Connection` which allows
to programatically configure the connection without config.exs.
The parameter `queue_config` specifies the configuration of the RabbitMQ queue to consume. If set to an atom,
the configuration will be loaded from the application's config.exs under the app key :exrabbitmq,
eg. if the value is set to `:default_queue`, then the config.exs should have configuration like the following:
```elixir
config :exrabbitmq, :default_queue,
queue: "test_queue",
queue_opts: [durable: true],
consume_opts: [no_ack: true]
```
The parameter `connection_config` can also be set to the struct `ExRabbitMQ.Consumer.QueueConfig` which allows
to programatically configure the queue without config.exs.
Please note that the configuration above will only declare the queue and start consuming it. For further
configuration such as exchange declare, queue bind and QOS setup, you need to override the `ExRabbitMQ` functions
`ExRabbitMQ.Consumer.xrmq_channel_setup/2` and `ExRabbitMQ.Consumer.xrmq_queue_setup/3`.
The parameter `state` is the state of the `GenServer` process.
The return value can be `{:ok, state}` when the consumer has been successfully registered or on error the tuple
`{:error, reason, state}`.
*For more information about the usage, also check the documentation of the function
`ExRabbitMQ.Consumer.xrmq_init/3`.*
"""
@callback setup_server(connection, session, term) ::
{:ok, new_state} | {:error, term, new_state}
when new_state: term,
connection: atom | %ExRabbitMQ.Config.Connection{},
session: atom | %ExRabbitMQ.Config.Session{}
@doc """
Responds to a request that was received through the `c:handle_request/3` callback.
This function will publish a message back to the origin app of the request through RabbitMQ. It uses the metadata
from the request message, the `reply_to` and `correlation_id` headers to route the response back. Additionally,
the function **must** be called from the `ExRabbitMQ.RPC.Server` process, as it needs the process's dictionary
which contain the connection & channel information.
### Parameters
The parameter `payload` is the payload of the response to send back to the origin of the request,
The parameter `metadata` if the metadata of the request message from which will use the the `reply_to` and
`correlation_id` headers.
The parameter `state` is the state of the `GenServer` process.
The return value can be:
* `:ok` - when the response has been send successfully,
* `{:error, reason}` - then the response has failed to be send with the returned `reason`.
"""
@callback respond(binary, %{reply_to: String.t(), correlation_id: String.t()}) ::
:ok | {:error, term}
@doc """
Responds to a request that was received through the `c:handle_request/3` callback.
Same as `respond/2` but with different parameters. The `metadata` parameter has been replaced with the
`routing_key` and `correlation_id`.
### Parameters
The parameter `routing_key` is the queue name to publish the message. This parameter is required and should never
be nil or empty string.
The parameter `correlation_id` is the correlation_id of the request message that we responding to.
*For more information about the usage, also check the documentation of the function `respond/2`.*
"""
@callback respond(binary, String.t(), String.t()) :: :ok | {:error, term}
@doc """
Invoked when a message has been received from RabbitMQ and should be processed and reply with a response
by your implementation of the `ExRabbitMQ.RPC.Server`.
### Parameters
The parameter `payload` `payload` contains the message content.
The parameter `metadata` contains all the metadata set when the message was published or any additional info
set by the broker.
The parameter `state` is the state of the `GenServer` process.
The return values of this callback can be:
* `{:respond, response, new_state}` - Will respond (publish) back to the origin of the request with a message with
the `response` payload and will acknowledge the message on broker.
* `{:ack, new_state}` - Will not respond back but will acknowledge the message on broker.
* `{:reject, new_state}` - Will not respond back and will reject the message on broker.
* Any other value will be passed as the return value of the `GenServer.handle_info/2`. In this case, no response will
be send back or acknowledge or reject the message, and needs to be handled by the implementation. If the response
needs to be done at later time, use the `respond/2` or `respond/3` for doing that.
"""
@callback handle_request(binary, map, term) ::
{:respond, binary, new_state}
| {:ack, new_state}
| {:reject, new_state}
| {:noreply, new_state}
| {:noreply, new_state, timeout | :hibernate}
| {:stop, term, new_state}
when new_state: term
defmacro __using__(_) do
quote location: :keep do
@behaviour ExRabbitMQ.RPC.Server
use ExRabbitMQ.Consumer
alias AMQP.Basic
alias ExRabbitMQ.State
@doc false
def setup_server(connection_config, session_config, state) do
{:ok, state, ExRabbitMQ.continue_tuple_try_init(connection_config, session_config, true, nil)}
end
@doc false
def respond(payload, metadata) do
respond(payload, metadata[:reply_to], metadata[:correlation_id])
end
@doc false
# When a receive message has no property `reply_to` then the AMQP library sets the value to `:undefined`
# The `nil` or empty string are valid only when the developer calls explicitely the `response/3`
def respond(_payload, reply_to, _correlation_id)
when is_nil(reply_to) or reply_to == "" or reply_to == :undefined do
{:error, :no_reply_to}
end
@doc false
def respond(payload, reply_to, correlation_id) do
opts = [
correlation_id: correlation_id || :undefined,
timestamp: DateTime.to_unix(DateTime.utc_now(), :millisecond)
]
with {:ok, channel} <- get_channel(),
# TODO: check if we can use xrmq_basic_publish here to use accounting
# TODO: perhaps we could use a pool of producers for this functionality
:ok <- Basic.publish(channel, "", reply_to, payload, opts) do
:ok
else
{:error, reason} -> {:error, reason}
error -> {:error, error}
end
end
@doc false
# Receives the request message and calls the `c:handle_request/3` for further processing.
def xrmq_basic_deliver(payload, %{delivery_tag: delivery_tag} = metadata, state) do
case handle_request(payload, metadata, state) do
{:respond, response, state} ->
respond(response, metadata)
xrmq_basic_ack(delivery_tag, state)
{:noreply, state}
{:ack, state} ->
xrmq_basic_ack(delivery_tag, state)
{:noreply, state}
{:reject, state} ->
xrmq_basic_reject(delivery_tag, state)
{:noreply, state}
other ->
other
end
end
def xrmq_on_hibernation_threshold_reached({:noreply, state}) do
{:noreply, state, :hibernate}
end
def xrmq_on_hibernation_threshold_reached(callback_result), do: callback_result
# Gets the channel information for the process dictionary.
defp get_channel do
case State.get_channel_info() do
{channel, _} when channel != nil -> {:ok, channel}
_ -> {:error, :no_channel}
end
end
end
end
end
|
lib/ex_rabbitmq/rpc/server.ex
| 0.896026 | 0.824144 |
server.ex
|
starcoder
|
defmodule Weaver do
@moduledoc """
Root module and main API of Weaver.
Entry point for weaving queries based on `Absinthe.Pipeline`.
Use `run/3` for initial execution, returning a `Weaver.Step.Result`.
Subsequent steps (the result's `dispatched` and `next` steps) can be executed via `resolve/3`.
"""
defmodule Ref do
@moduledoc """
References a node in the graph using a globally unique `id`.
Used as placeholder in any graph tuples, such as for storing
and retrieval in `Weaver.Graph`.
"""
@enforce_keys [:id]
defstruct @enforce_keys
@type t() :: %__MODULE__{
id: String.t()
}
def new(id) when is_binary(id), do: %__MODULE__{id: id}
def from(obj), do: new(Weaver.Resolvers.id_for(obj))
end
defmodule Marker do
@moduledoc """
References a position in a timeline where a chunk of previously
retrieved data starts or ends, used as boundaries for retrieval
of new records in the timeline.
Can be stored as meta data together with the actual graph
data in `Weaver.Graph`.
"""
@enforce_keys [:type, :ref, :val]
defstruct @enforce_keys
@type t() :: %__MODULE__{
ref: any(),
val: any(),
type: :chunk_start | :chunk_end
}
def chunk_start(id, val) do
%__MODULE__{type: :chunk_start, ref: %Ref{id: id}, val: val}
end
def chunk_end(id, val) do
%__MODULE__{type: :chunk_end, ref: %Ref{id: id}, val: val}
end
end
alias Absinthe.Pipeline
alias Weaver.Absinthe.Middleware.Continue
@result_phase Weaver.Absinthe.Phase.Document.Result
@resolution_phase Absinthe.Phase.Document.Execution.Resolution
def prepare(document, schema, options \\ []) do
context =
Keyword.get(options, :context, %{})
|> Map.put_new(:cache, Keyword.get(options, :cache, nil))
|> Map.put_new(:refresh, Keyword.get(options, :refresh, true))
|> Map.put_new(:backfill, Keyword.get(options, :backfill, true))
options = Keyword.put(options, :context, context)
pipeline =
schema
|> pipeline(options)
|> Pipeline.without(@resolution_phase)
case Absinthe.Pipeline.run(document, pipeline) do
{:ok, %{result: {:validation_failed, errors}}, _phases} ->
{:error, {:validation_failed, errors}}
{:ok, blueprint, _phases} ->
{:ok, blueprint}
{:error, msg, _phases} ->
{:error, msg}
end
end
def pipeline(schema, options) do
options = Keyword.put_new(options, :result_phase, @result_phase)
Pipeline.for_document(schema, options)
|> Pipeline.replace(Absinthe.Phase.Document.Result, @result_phase)
end
def weave(blueprint, options \\ []) do
pipeline =
pipeline(blueprint.schema, options)
|> Pipeline.from(@resolution_phase)
case Absinthe.Pipeline.run(blueprint, pipeline) do
{:ok, %{result: result}, _phases} ->
result =
case Weaver.Step.Result.next(result) do
nil ->
result
next_blueprint ->
continuation = next_blueprint.execution.acc[Continue]
Weaver.Step.Result.set_next(
result,
update_in(
blueprint.execution.acc,
&Map.put(&1, Continue, continuation)
)
)
end
{:ok, result}
{:error, msg, _phases} ->
{:error, msg}
end
end
end
|
lib/weaver.ex
| 0.898801 | 0.62651 |
weaver.ex
|
starcoder
|
defmodule Vex.Validators.Confirmation do
@moduledoc """
Ensure a value, if provided, is equivalent to a second value.
Generally used to check, eg, a password and password
confirmation.
Note: This validator is treated differently by Vex, in that
two values are passed to it.
## Options
* `:message`: Optional. A custom error message. May be in EEx format
and use the fields described in "Custom Error Messages," below.
## Examples
iex> Vex.Validators.Confirmation.validate(["foo", "bar"], true)
{:error, "must match its confirmation"}
iex> Vex.Validators.Confirmation.validate(["foo", "foo"], true)
:ok
iex> Vex.Validators.Confirmation.validate(["foo", "bar"], message: "<%= confirmation %> isn't the same as <%= value %>!")
{:error, "bar isn't the same as foo!"}
iex> Vex.Validators.Confirmation.validate([nil, "bar"], true)
:ok
iex> Vex.Validators.Confirmation.validate(["foo", nil], true)
{:error, "must match its confirmation"}
iex> Vex.Validators.Confirmation.validate(["foo", nil], message: "must match!")
{:error, "must match!"}
iex> Vex.Validators.Confirmation.validate(["", "unneeded"], [allow_blank: true])
:ok
## Custom Error Messages
Custom error messages (in EEx format), provided as :message, can use the following values:
iex> Vex.Validators.Confirmation.__validator__(:message_fields)
[value: "The value to confirm", confirmation: "Bad confirmation value"]
An example:
iex> Vex.Validators.Confirmation.validate(["foo", nil], message: "<%= inspect confirmation %> doesn't match <%= inspect value %>")
{:error, ~S(nil doesn't match "foo")}
"""
use Vex.Validator
@message_fields [value: "The value to confirm", confirmation: "Bad confirmation value"]
def validate(values, true), do: validate(values, [])
def validate([nil | _], _options), do: :ok
def validate([value, confirmation] = values, options) when is_list(options) do
unless_skipping(value, options) do
if values |> Enum.uniq() |> length == 1 do
:ok
else
{:error,
message(options, "must match its confirmation", value: value, confirmation: confirmation)}
end
end
end
end
|
lib/vex/validators/confirmation.ex
| 0.837935 | 0.489564 |
confirmation.ex
|
starcoder
|
defmodule SMWCBot.MessageServer do
@moduledoc """
A GenServer for Sending messages at a specified rate.
## Options
- `:rate` (integer) - The rate at which to send the messages. (one message
per `rate`). Optional. Defaults to `1500` ms.
### Twitch command and message rate limits:
If command and message rate limits are exceeded, an application cannot send chat
messages or commands for 30 minutes.
| Limit | Applies to
|-------------------------------|---------------------------------------------
| 20 per 30 seconds | Users sending commands or messages to
| | channels in which they are not the broadcaster
| | and do not have Moderator status.
| 100 per 30 seconds | Users sending commands or messages to channels
| | in which they are the broadcaster or have
| | Moderator status.
| 7500 per 30 seconds | Verified bots. The channel limits above also
| site-wide | apply. In other words, one of the two limits
| | above will also be applied depending on
| | whether the verified bot is the broadcaster
| | or has Moderator status.
https://dev.twitch.tv/docs/irc/guide#rate-limits
"""
use GenServer
require Logger
@default_rate_ms 1500
@doc """
Start the message server.
"""
@spec start_link(keyword()) :: GenServer.on_start()
def start_link(opts) do
GenServer.start_link(__MODULE__, opts, name: __MODULE__)
end
@doc """
Add a message to the outbound message queue.
"""
@spec add_message(String.t(), String.t()) :: :ok
def add_message(chat, message) do
GenServer.cast(__MODULE__, {:add, {chat, message}})
end
## Callbacks
@impl true
def init(opts) do
state = %{
rate: Keyword.get(opts, :rate, @default_rate_ms),
timer_ref: nil,
queue: :queue.new()
}
Logger.info("[MessageServer] STARTING with a message rate of #{state.rate}ms...")
{:ok, state}
end
@impl true
# If there is no timer_ref, then that means the queue was empty and paused, so
# we will add it to the queue and start it again.
def handle_cast({:add, chat_message}, %{timer_ref: nil} = state) do
send_and_schedule_next(%{state | queue: :queue.in(chat_message, state.queue)})
end
# The timer_ref was not empty so that means the queue is running, so we will
# just add the message to queue.
def handle_cast({:add, chat_message}, state) do
{:noreply, %{state | queue: :queue.in(chat_message, state.queue)}}
end
@impl true
def handle_info(:send, state) do
send_and_schedule_next(state)
end
## Internal API
# Pops a message off the queue and sends it.
defp send_and_schedule_next(state) do
case :queue.out(state.queue) do
{:empty, _} ->
Logger.debug("[MessageServer] no more messages to send: PAUSED")
{:noreply, %{state | timer_ref: nil}}
{{:value, {chat, message}}, rest} ->
TMI.message(chat, message)
Logger.debug("[MessageServer] SENT #{chat}: #{message}")
timer_ref = Process.send_after(self(), :send, state.rate)
{:noreply, %{state | queue: rest, timer_ref: timer_ref}}
end
end
end
|
lib/smwc_bot/message_server.ex
| 0.851984 | 0.530419 |
message_server.ex
|
starcoder
|
defmodule Crutches.String do
alias Crutches.Option
import String,
only: [
replace: 3,
slice: 2,
trim: 1
]
@moduledoc ~s"""
Convenience functions for strings.
This module provides several convenience functions operating on strings.
Simply call any function (with any options if applicable) to make use of it.
"""
# Access
@doc ~S"""
Gives a substring of `string` from the given `position`.
If `position` is positive, counts from the start of the string.
If `position` is negative, count from the end of the string.
## Examples
iex> String.from("hello", 0)
"hello"
iex> String.from("hello", 3)
"lo"
iex> String.from("hello", -2)
"lo"
iex> String.from("hello", -7)
""
You can mix it with +to+ method and do fun things like:
iex> "hello"
iex> |> String.from(0)
iex> |> String.to(-1)
"hello"
iex> "hello"
iex> |> String.from(1)
iex> |> String.to(-2)
"ell"
iex> "a"
iex> |> String.from(1)
iex> |> String.to(1500)
""
iex> "elixir"
iex> |> String.from(-10)
iex> |> String.to(-7)
""
"""
@spec from(String.t(), integer) :: String.t()
def from(string, position) when position >= 0 do
slice(string, position..(String.length(string) - 1))
end
def from(string, position) when position < 0 do
new_position = String.length(string) + position
case new_position < 0 do
true -> ""
false -> slice(string, new_position..(String.length(string) - 1))
end
end
@doc ~S"""
Returns a substring from the beginning of the string to the given position.
If the position is negative, it is counted from the end of the string.
## Examples
iex> String.to("hello", 0)
"h"
iex> String.to("hello", 3)
"hell"
iex> String.to("hello", -2)
"hell"
You can mix it with +from+ method and do fun things like:
iex> "hello"
iex> |> String.from(0)
iex> |> String.to(-1)
"hello"
iex> "hello"
iex> |> String.from(1)
iex> |> String.to(-2)
"ell"
"""
@spec to(String.t(), integer) :: String.t()
def to(string, length) when length >= 0 do
slice(string, 0..length)
end
def to(string, length) when length < 0 do
slice(string, 0..(String.length(string) + length))
end
# Filters
@doc ~S"""
Returns the string, first removing all whitespace on both ends of
the string, and then changing remaining consecutive whitespace
groups into one space each.
## Examples
iex> str = "A multi line
iex> string"
iex> String.squish(str)
"A multi line string"
iex> str = " foo bar \n \t boo"
iex> String.squish(str)
"foo bar boo"
"""
@spec squish(String.t()) :: String.t()
def squish(string) do
string |> replace(~r/[[:space:]]+/, " ") |> trim
end
@doc ~S"""
Remove all occurrences of `pattern` from `string`.
Can also take a list of `patterns`.
## Examples
iex> String.remove("foo bar test", " test")
"foo bar"
iex> String.remove("foo bar test", ~r/foo /)
"bar test"
iex> String.remove("foo bar test", [~r/foo /, " test"])
"bar"
"""
@spec remove(String.t(), String.t() | Regex.t() | list(any)) :: String.t()
def remove(string, patterns) when is_list(patterns) do
patterns |> Enum.reduce(string, &remove(&2, &1))
end
def remove(string, pattern) do
replace(string, pattern, "")
end
@doc ~S"""
Capitalizes every word in a string. Similar to ActiveSupport's #titleize.
iex> String.titlecase("the truth is rarely pure and never simple.")
"The Truth Is Rarely Pure And Never Simple."
iex> String.titlecase("THE TRUTH IS RARELY PURE AND NEVER SIMPLE.")
"The Truth Is Rarely Pure And Never Simple."
iex> String.titlecase("the truth is rarely pure and NEVER simple.")
"The Truth Is Rarely Pure And Never Simple."
"""
@spec titlecase(String.t()) :: String.t()
def titlecase(string) when is_binary(string) do
string
|> String.split(" ")
|> Enum.map(&String.capitalize/1)
|> Enum.join(" ")
end
@doc ~S"""
Truncates a given `text` after a given `length` if `text` is longer than `length`:
Truncates a given text after a given `len`gth if text is longer than `len`th.
The last characters will be replaced with the `:omission` (defaults to “...”) for a total length not exceeding `len`.
Pass a `:separator` to truncate text at a natural break (the first occurence of that separator before the provided length).
## Examples
iex> String.truncate("Once upon a time in a world far far away", 27)
"Once upon a time in a wo..."
iex> String.truncate("Once upon a time in a world far far away", 27, separator: " ")
"Once upon a time in a..."
iex> String.truncate("Once upon a time in a world far far away", 27, separator: ~r/\s/)
"Once upon a time in a..."
iex> String.truncate("Once upon a time in a world far far away", 35, separator: "far ")
"Once upon a time in a world far..."
iex> String.truncate("And they found that many people were sleeping better.", 25, omission: "... (continued)")
"And they f... (continued)"
iex> String.truncate("Supercalifragilisticexpialidocious", 24, separator: ~r/\s/)
"Supercalifragilistice..."
"""
@truncate [
valid: ~w(separator omission)a,
defaults: [
separator: nil,
omission: "..."
]
]
def truncate(string, len, opts \\ [])
def truncate(nil, _, _), do: nil
def truncate(string, len, opts) when is_binary(string) and is_integer(len) do
opts = Option.combine!(opts, @truncate)
if String.length(string) > len do
length_with_room = len - String.length(opts[:omission])
do_truncate(string, length_with_room, opts[:separator], opts[:omission])
else
string
end
end
defp do_truncate(string, length, sep, omission) when is_nil(sep) do
String.slice(string, 0, length) <> omission
end
defp do_truncate(string, length, sep, omission) when is_binary(sep) do
sep_size = String.length(sep)
chunk_indexes =
string
|> String.codepoints()
|> Enum.take(length)
|> Enum.with_index()
|> Enum.chunk_every(sep_size)
|> Enum.reverse()
|> Enum.find(fn chars ->
str = chars |> Enum.map(&elem(&1, 0)) |> Enum.join("")
str == sep
end)
{_, index} = if chunk_indexes, do: List.last(chunk_indexes), else: {nil, length}
do_truncate(string, index, nil, omission)
end
defp do_truncate(string, length, sep, omission) do
case Regex.scan(sep, string, return: :index) do
[_ | _] = captures ->
[{index, _}] = captures |> Enum.reverse() |> Enum.find(fn [{i, _}] -> i <= length end)
do_truncate(string, index, nil, omission)
[] ->
do_truncate(string, length, nil, omission)
end
end
end
|
lib/crutches/string.ex
| 0.868465 | 0.438124 |
string.ex
|
starcoder
|
defmodule SqlValue do
@moduledoc """
Implementations of SQL operators and functions (where they differ from Elixir).
SQL is pretty weird, around `NULL` at least; we have to implement the weirdness
somewhere.
"""
@doc """
True if `v` is a null value.
Because the CSV files don't include any information about the column types,
we lamely treat empty strings as nulls.
"""
def is_null?(v) do
v == :nil || v == ""
end
@doc """
Return true if SQL considers the value `v` to be a true value.
## Examples
iex> SqlValue.is_truthy?(true)
true
iex> SqlValue.is_truthy?(0)
false
iex> SqlValue.is_truthy?(2)
true
iex> SqlValue.is_truthy?(nil)
nil
"""
def is_truthy?(v) do
case v do
true -> true
nil -> nil
v -> is_integer(v) && v != 0
end
end
@doc """
Return true if `left` and `right` are considered equal.
As the SQL standard requires, if either `left` or `right` is null, the answer
is `nil` rather than `false` or `true`.
## Examples
iex> SqlValue.equals?(3, 3)
true
iex> SqlValue.equals?(3, 5)
false
iex> SqlValue.equals?(3, "3")
false
iex> SqlValue.equals?(nil, "hello")
nil
iex> SqlValue.equals?(nil, nil)
nil
"""
def equals?(left, right) do
if is_null?(left) || is_null?(right) do
nil
else
left == right
end
end
def logical_not(v) do
case is_truthy?(v) do
true -> false
false -> true
nil -> nil
end
end
def logical_and(a, b) do
case {is_truthy?(a), is_truthy?(b)} do
{nil, _} -> nil
{_, nil} -> nil
{true, true} -> true
_ -> false
end
end
def logical_or(a, b) do
case {is_truthy?(a), is_truthy?(b)} do
{nil, _} -> nil
{_, nil} -> nil
{false, false} -> false
_ -> true
end
end
def from_string(_, ""), do: :nil
def from_string(:int, string) do
{n, ""} = Integer.parse(string)
n
end
def from_string(:num, string), do: Decimal.new(string)
def from_string(:str, string), do: string
def from_string(:bool, "true"), do: true
def from_string(:bool, "false"), do: false
def from_string(:bool, "1"), do: true
def from_string(:bool, "0"), do: false
def add(nil, _), do: nil
def add(_, nil), do: nil
def add(a, b) do
cond do
Decimal.decimal?(b) -> Decimal.add(a, b)
true -> a + b
end
end
def sum(values, type) do
start = case type do
:int -> 0
:num -> Decimal.new("0")
end
Enum.reduce(values, start, &add/2)
end
def round(nil), do: nil
def round(num) do
Decimal.round(num, 0)
end
def round(nil, _), do: nil
def round(_, nil), do: nil
def round(num, places) do
Decimal.round(num, places)
end
end
|
jorendorff+elixir/lib/SqlValue.ex
| 0.901463 | 0.586819 |
SqlValue.ex
|
starcoder
|
defmodule ShEx.ShExC.Decoder do
@moduledoc false
import ShEx.Utils
alias RDF.{IRI, BlankNode, Literal, XSD}
alias ShEx.NodeConstraint.{StringFacets, NumericFacets}
import RDF.Serialization.ParseHelper, only: [error_description: 1]
defmodule State do
@moduledoc false
defstruct base_iri: nil, namespaces: %{}, bnode_counter: 0
def add_namespace(%State{namespaces: namespaces} = state, ns, iri) do
%State{state | namespaces: Map.put(namespaces, ns, iri)}
end
def ns(%State{namespaces: namespaces}, prefix) do
namespaces[prefix]
end
end
def decode(content, opts \\ []) do
with {:ok, tokens, _} <- tokenize(content),
{:ok, ast} <- parse(tokens) do
base = Keyword.get(opts, :base)
build_schema(ast, base && RDF.iri(base))
else
{:error, {error_line, :shexc_lexer, error_descriptor}, _error_line_again} ->
{:error,
"ShExC scanner error on line #{error_line}: #{error_description(error_descriptor)}"}
{:error, {error_line, :shexc_parser, error_descriptor}} ->
{:error,
"ShExC parser error on line #{error_line}: #{error_description(error_descriptor)}"}
end
end
defp tokenize(content), do: content |> to_charlist |> :shexc_lexer.string()
defp parse([]), do: {:ok, []}
defp parse(tokens), do: tokens |> :shexc_parser.parse()
defp build_schema({:shex_doc, directives_ast, start_acts_ast, statements_ast}, base) do
state = %State{base_iri: base}
all_statements = directives_ast ++ statements_ast
with {:ok, statements, imports} <-
extract_imports(all_statements, state),
{:ok, statements, start} <-
extract_start(statements, state),
{:ok, statements, state} <-
extract_prefixes(statements, state),
{:ok, start_acts} <-
if_present(start_acts_ast, &build_semantic_actions/2, state),
{:ok, shapes, _state} <-
Enum.reduce_while(statements, {:ok, [], state}, fn statement, {:ok, shapes, state} ->
case build_shape(statement, state) do
{:ok, nil, new_state} -> {:cont, {:ok, shapes, new_state}}
{:ok, shape, new_state} -> {:cont, {:ok, [shape | shapes], new_state}}
{:error, _} = error -> {:halt, error}
end
end) do
ShEx.Schema.new(
unless(Enum.empty?(shapes), do: Enum.reverse(shapes)),
start,
unless(Enum.empty?(imports), do: imports),
start_acts
)
end
end
defp extract_prefixes(statements_ast, state) do
{statements, _, state} =
Enum.reduce(statements_ast, {[], :consume_directives, state}, &handle_base_and_prefixes/2)
{:ok, statements, state}
end
defp handle_base_and_prefixes(
{:prefix, {:prefix_ns, _, ns}, iri} = directive,
{statements, value, state}
) do
{
if value == :consume_directives do
statements
else
statements ++ [directive]
end,
value,
if IRI.absolute?(iri) do
State.add_namespace(state, ns, iri)
else
State.add_namespace(state, ns, iri |> IRI.absolute(state.base_iri) |> to_string())
end
}
end
defp handle_base_and_prefixes(
{:base, iri} = directive,
{statements, value, %State{base_iri: base_iri} = state}
) do
{
if value == :consume_directives do
statements
else
statements ++ [directive]
end,
value,
cond do
IRI.absolute?(iri) ->
%State{state | base_iri: RDF.iri(iri)}
base_iri != nil ->
%State{state | base_iri: IRI.absolute(iri, base_iri)}
true ->
raise "Could not resolve relative IRI '#{iri}', no base iri provided"
end
}
end
defp handle_base_and_prefixes(statement, {statements, value, state}) do
{statements ++ [statement], value, state}
end
defp extract_imports(statements_ast, %State{} = state) do
{statements, imports, _} =
Enum.reduce(statements_ast, {[], [], state}, fn
{:import, iri}, {statements, imports, state} ->
{statements,
[
if IRI.absolute?(iri) do
iri
else
iri |> IRI.absolute(state.base_iri) |> to_string()
end
| imports
], state}
statement, acc ->
handle_base_and_prefixes(statement, acc)
end)
{:ok, statements, Enum.reverse(imports)}
end
defp extract_start(statements_ast, %State{} = state) do
with {statements, start, _} when statements != :error <-
Enum.reduce_while(statements_ast, {[], nil, state}, fn
{:start, inline_shape_expression}, {statements, nil, state} ->
case build_shape_expression(inline_shape_expression, state) do
{:ok, shape} -> {:cont, {statements, shape, state}}
error -> {:halt, error}
end
{:start, _inline_shape_expression}, {_statements, _start, _state} ->
{:halt, {:error, "multiple start shapes defined"}}
statement, acc ->
{:cont, handle_base_and_prefixes(statement, acc)}
end) do
{:ok, statements, start}
end
end
defp build_shape({:shape_expr_decl, label_ast, :external}, state) do
with {:ok, shape_expr_label} <- build_node(label_ast, state) do
{:ok, %ShEx.ShapeExternal{id: shape_expr_label}, state}
end
end
defp build_shape({:shape_expr_decl, label_ast, expression_ast}, state) do
with {:ok, shape_expr} <- build_shape_expression(expression_ast, state),
{:ok, shape_expr_label} <- build_node(label_ast, state) do
{:ok, Map.put(shape_expr, :id, shape_expr_label), state}
end
end
defp build_shape_expression(
{:shape, extra_property_set_ast, triple_expression_ast, annotations_ast, sem_acts_ast},
state
) do
with {:ok, extra, closed} <-
get_extra_properties(extra_property_set_ast, state),
{:ok, triple_expression} <-
if(triple_expression_ast,
do: build_triple_expression(triple_expression_ast, state),
else: {:ok, nil}
),
{:ok, sem_acts} <-
if_present(sem_acts_ast, &build_semantic_actions/2, state),
{:ok, annotations} <-
if(annotations_ast,
do: map(annotations_ast, &build_annotation/2, state),
else: {:ok, nil}
) do
{:ok,
%ShEx.Shape{
expression: triple_expression,
closed: closed,
extra: unless(Enum.empty?(extra), do: extra),
sem_acts: sem_acts,
annotations: annotations
}}
end
end
defp build_shape_expression({:shape_or, shape_exprs_ast}, state) do
with {:ok, shape_expressions} <-
map(shape_exprs_ast, &build_shape_expression/2, state) do
{:ok, %ShEx.ShapeOr{shape_exprs: shape_expressions}}
end
end
defp build_shape_expression({:shape_and, shape_exprs_ast}, state) do
with {:ok, shape_expressions} <-
map(shape_exprs_ast, &build_shape_expression/2, state) do
{:ok, %ShEx.ShapeAnd{shape_exprs: shape_expressions}}
end
end
defp build_shape_expression({:shape_not, shape_expr_ast}, state) do
with {:ok, shape_expression} <- build_shape_expression(shape_expr_ast, state) do
{:ok, %ShEx.ShapeNot{shape_expr: shape_expression}}
end
end
defp build_shape_expression(:empty_shape, _state), do: {:ok, %ShEx.Shape{}}
defp build_shape_expression({:literal_node_constraint, _, _, _, _} = node_constraint_ast, state) do
build_node_constraint(node_constraint_ast, state)
end
defp build_shape_expression({:non_literal_node_constraint, _, _} = node_constraint_ast, state) do
build_node_constraint(node_constraint_ast, state)
end
defp build_shape_expression({:shape_ref, {:at_prefix_ln, line, {prefix, name}}}, state) do
build_node({:prefix_ln, line, {prefix, name}}, state)
end
defp build_shape_expression({:shape_ref, {:at_prefix_ns, line, prefix}}, state) do
build_node({:prefix_ns, line, prefix}, state)
end
defp build_shape_expression({:shape_ref, shape_ref_ast}, state) do
build_node(shape_ref_ast, state)
end
defp get_extra_properties(nil, _state), do: {:ok, [], nil}
defp get_extra_properties(extra_property_set_ast, state) do
Enum.reduce_while(extra_property_set_ast, {:ok, [], nil}, fn
{:extra, predicates}, {:ok, extra, closed} ->
case map(predicates, &build_node/2, state) do
{:ok, new_extra} ->
{:cont, {:ok, extra ++ new_extra, closed}}
{:error, error} ->
{:halt, {:error, error}}
end
:closed, {:ok, extra, _} ->
{:cont, {:ok, extra, true}}
end)
end
defp build_triple_expression(
{:bracketed_triple_expr, triple_expression_ast, cardinality_ast, annotations_ast,
sem_acts_ast},
state
) do
with {:ok, triple_expression} <-
build_triple_expression(triple_expression_ast, state),
{:ok, min, max} <-
get_cardinality(cardinality_ast, state),
{:ok, sem_acts} <-
if_present(sem_acts_ast, &build_semantic_actions/2, state),
{:ok, annotations} <-
if(annotations_ast,
do: map(annotations_ast, &build_annotation/2, state),
else: {:ok, nil}
) do
{:ok,
triple_expression
|> Map.put(:min, min)
|> Map.put(:max, max)
|> Map.update(:sem_acts, sem_acts, fn
nil -> sem_acts
old -> old ++ sem_acts
end)
|> Map.put(:annotations, annotations)}
end
end
defp build_triple_expression({:each_of, shape_exprs_ast}, state) do
with {:ok, expressions} <-
map(shape_exprs_ast, &build_triple_expression/2, state) do
{:ok, %ShEx.EachOf{expressions: expressions}}
end
end
defp build_triple_expression({:one_of, shape_exprs_ast}, state) do
with {:ok, expressions} <-
map(shape_exprs_ast, &build_triple_expression/2, state) do
{:ok, %ShEx.OneOf{expressions: expressions}}
end
end
defp build_triple_expression(
{:triple_constraint, sense_flags, predicate_ast, inline_shape_expression_ast,
cardinality_ast, annotations_ast, sem_acts_ast},
state
) do
with {:ok, predicate_iri} <-
build_node(predicate_ast, state),
{:ok, shape_expression} <-
if(inline_shape_expression_ast == :empty_shape,
do: {:ok, nil},
else: build_shape_expression(inline_shape_expression_ast, state)
),
{:ok, min, max} <-
get_cardinality(cardinality_ast, state),
{:ok, sem_acts} <-
if_present(sem_acts_ast, &build_semantic_actions/2, state),
{:ok, annotations} <-
if(annotations_ast,
do: map(annotations_ast, &build_annotation/2, state),
else: {:ok, nil}
) do
{:ok,
%ShEx.TripleConstraint{
value_expr: shape_expression,
predicate: predicate_iri,
inverse: if(sense_flags, do: sense_flags == :inverse),
min: min,
max: max,
sem_acts: sem_acts,
annotations: annotations
}}
end
end
defp build_triple_expression({:include, triple_expr_label_ast}, state) do
build_node(triple_expr_label_ast, state)
end
defp build_triple_expression(
{:named_triple_expression, triple_expr_label_ast, triple_expr_ast},
state
) do
with {:ok, triple_expression_label} <-
build_node(triple_expr_label_ast, state),
{:ok, triple_expression} <-
build_triple_expression(triple_expr_ast, state) do
{:ok, Map.put(triple_expression, :id, triple_expression_label)}
end
end
defp build_node_constraint(
{:literal_node_constraint, kind, datatype_ast, value_set_ast, xs_facets_ast},
state
) do
with {:ok, datatype} <-
if_present(datatype_ast, &build_node/2, state),
{:ok, xs_facets} <-
xs_facets(xs_facets_ast, Map.put(state, :current_xs_facet_datatype, datatype)),
string_facets <-
StringFacets.new(xs_facets),
{:ok, numeric_facets} <-
xs_facets |> NumericFacets.new() |> validate_numeric_datatype(datatype),
{:ok, values} <-
if_present(value_set_ast, &value_set/2, state) do
{:ok,
%ShEx.NodeConstraint{
node_kind: if(kind, do: to_string(kind)),
datatype: datatype,
string_facets: string_facets,
numeric_facets: numeric_facets,
values: ShEx.NodeConstraint.Values.new(values)
}}
end
end
defp build_node_constraint({:non_literal_node_constraint, kind, string_facets_ast}, state) do
with {:ok, string_facets} <- xs_facets(string_facets_ast, state) do
{:ok,
%ShEx.NodeConstraint{
node_kind: if(kind, do: to_string(kind)),
string_facets: StringFacets.new(string_facets)
}}
end
end
defp build_annotation({:annotation, predicate_ast, object_ast}, state) do
with {:ok, predicate} <- build_node(predicate_ast, state),
{:ok, object} <- build_node(object_ast, state) do
{:ok,
%ShEx.Annotation{
predicate: predicate,
object: object
}}
end
end
defp build_semantic_actions({type, code_decls_ast}, state)
when type in [:code_decls, :start_actions] do
code_decls_ast
|> map(&build_semantic_action/2, state)
end
defp build_semantic_action({:code_decl, name_ast, code_token}, state) do
with {:ok, name} <- build_node(name_ast, state),
{:ok, code} <- get_code(code_token) do
{:ok,
%ShEx.SemAct{
name: name,
code: unescape_code(code)
}}
end
end
defp get_code(nil), do: {:ok, nil}
defp get_code({:code, _line, code}), do: {:ok, code}
defp get_cardinality(nil, _), do: {:ok, nil, nil}
defp get_cardinality(:"?", _), do: {:ok, 0, 1}
defp get_cardinality(:+, _), do: {:ok, 1, -1}
defp get_cardinality(:*, _), do: {:ok, 0, -1}
defp get_cardinality({:repeat_range, _line, {min, max}}, _), do: {:ok, min, max}
defp get_cardinality({:repeat_range, _line, exact}, _), do: {:ok, exact, exact}
defp xs_facets(xs_facets_ast, state) do
xs_facets_ast
|> List.wrap()
|> Enum.reduce_while({:ok, %{}}, fn xs_facet_ast, {:ok, xs_facets} ->
case xs_facet(xs_facet_ast, state) do
{:ok, xs_facet} ->
conflicts = Map.take(xs_facets, Map.keys(xs_facet))
if conflicts == %{} do
{:cont, {:ok, Map.merge(xs_facets, xs_facet)}}
else
{:halt,
{:error,
"multiple occurrences of the same xsFacet: #{conflicts |> Map.keys() |> Enum.join(", ")}}"}}
end
{:error, _} = error ->
{:halt, error}
end
end)
end
defp xs_facet({:string_facet, :regexp, {regexp, {:regexp_flags, _, regexp_flags}}}, state) do
with {:ok, string_facet} <- xs_facet({:string_facet, :regexp, {regexp, nil}}, state) do
{:ok, Map.put(string_facet, :flags, regexp_flags)}
end
end
defp xs_facet({:string_facet, :regexp, {{:regexp, _line, regexp}, nil}}, _state) do
with {:ok, regexp} <- valid_regexp_escaping(regexp) do
{:ok, %{pattern: unescape_regex(regexp)}}
end
end
defp xs_facet({:string_facet, length_type, {:integer, _line, integer}}, _state) do
{:ok, %{length_type => Literal.value(integer)}}
end
defp xs_facet({:numeric_length_facet, numeric_length_type, {:integer, _line, integer}}, _state) do
{:ok, %{numeric_length_type => Literal.value(integer)}}
end
defp xs_facet({:numeric_range_facet, numeric_range_type, numeric}, _state) do
{:ok, %{numeric_range_type => Literal.value(numeric)}}
end
defp validate_numeric_datatype(nil, _), do: {:ok, nil}
defp validate_numeric_datatype(numeric_facets, nil), do: {:ok, numeric_facets}
defp validate_numeric_datatype(numeric_facets, datatype_iri) do
datatype = XSD.Datatype.get(datatype_iri)
if datatype && XSD.Numeric.datatype?(datatype) do
{:ok, numeric_facets}
else
{:error,
"numeric facet constraints applied to non-numeric datatype: #{to_string(datatype_iri)}}"}
end
end
defp value_set({:value_set, value_set_values_ast}, state) do
with {:ok, values} <-
value_set_values_ast
|> map(&value_set_value/2, state)
|> empty_to_nil() do
{:ok, values}
end
end
defp value_set_value({:iri_range, iri_ast, nil, nil}, state) do
with {:ok, iri} <- build_node(iri_ast, state) do
{:ok, iri}
end
end
defp value_set_value({:iri_range, iri_ast, :stem, nil}, state) do
with {:ok, iri} <- build_node(iri_ast, state) do
{:ok, %{type: "IriStem", stem: iri}}
end
end
defp value_set_value({:iri_range, iri_ast, :stem, exclusions_ast}, state) do
with {:ok, iri} <- build_node(iri_ast, state),
{:ok, exclusion_values} <- map(exclusions_ast, &exclusion_value/2, state) do
{:ok, %{type: "IriStemRange", stem: iri, exclusions: exclusion_values}}
end
end
defp value_set_value({:literal_range, literal_ast, nil, nil}, %{in_exclusion: true} = state) do
with {:ok, literal} <- build_node(literal_ast, state) do
{:ok, Literal.lexical(literal)}
end
end
defp value_set_value({:literal_range, literal_ast, nil, nil}, state) do
with {:ok, literal} <- build_node(literal_ast, state) do
{:ok, literal}
end
end
defp value_set_value({:literal_range, literal_ast, :stem, nil}, state) do
with {:ok, literal} <- build_node(literal_ast, state) do
{:ok, %{type: "LiteralStem", stem: Literal.lexical(literal)}}
end
end
defp value_set_value({:literal_range, literal_ast, :stem, exclusions}, state) do
with {:ok, literal} <- build_node(literal_ast, state),
{:ok, exclusion_values} <- map(exclusions, &exclusion_value/2, state) do
{:ok,
%{type: "LiteralStemRange", stem: Literal.lexical(literal), exclusions: exclusion_values}}
end
end
defp value_set_value({:language_range, langtag_token, nil, nil}, %{in_exclusion: true}) do
with {:ok, language_tag} <- language_tag(langtag_token) do
{:ok, language_tag}
end
end
defp value_set_value({:language_range, langtag_token, nil, nil}, _state) do
with {:ok, language_tag} <- language_tag(langtag_token) do
{:ok, %{type: "Language", languageTag: language_tag}}
end
end
defp value_set_value({:language_range, langtag_token, :stem, nil}, _state) do
with {:ok, language_tag} <- language_tag(langtag_token) do
{:ok, %{type: "LanguageStem", stem: language_tag}}
end
end
defp value_set_value({:language_range, langtag_token, :stem, exclusions_ast}, state) do
with {:ok, language_tag} <- language_tag(langtag_token),
{:ok, exclusion_values} <- map(exclusions_ast, &exclusion_value/2, state) do
{:ok, %{type: "LanguageStemRange", stem: language_tag, exclusions: exclusion_values}}
end
end
defp value_set_value({:exclusions, [{exclusion_type, _, _} | _] = exclusions_ast}, state) do
with {:ok, exclusions} <- map(exclusions_ast, &exclusion_value/2, state) do
{:ok,
%{
type: exclusion_value_type(exclusion_type),
stem: ShEx.NodeConstraint.Values.wildcard(),
exclusions: exclusions
}}
end
end
defp exclusion_value({exclusion_type_ast, value_ast, stem_ast}, state) do
value_set_value(
{exclusion_value_ast_type(exclusion_type_ast), value_ast, stem_ast, nil},
Map.put(state, :in_exclusion, true)
)
end
defp exclusion_value_ast_type(:iri_exclusion), do: :iri_range
defp exclusion_value_ast_type(:literal_exclusion), do: :literal_range
defp exclusion_value_ast_type(:language_exclusion), do: :language_range
defp exclusion_value_type(:iri_exclusion), do: "IriStemRange"
defp exclusion_value_type(:literal_exclusion), do: "LiteralStemRange"
defp exclusion_value_type(:language_exclusion), do: "LanguageStemRange"
defp language_tag({:langtag, _line, lang_tag}), do: {:ok, lang_tag}
defp language_tag({:@, _line}), do: {:ok, ""}
defp build_node(%IRI{} = iri, _state), do: {:ok, iri}
defp build_node(%BlankNode{} = bnode, _state), do: {:ok, bnode}
defp build_node(%Literal{} = literal, _state), do: {:ok, literal}
defp build_node(:rdf_type, _state), do: {:ok, RDF.type()}
defp build_node({:prefix_ln, line, {prefix, name}}, state) do
if ns = State.ns(state, prefix) do
{:ok, RDF.iri(ns <> name)}
else
{:error, "unknown prefix #{inspect(prefix)} in line #{inspect(line)}"}
end
end
defp build_node({:prefix_ns, line, prefix}, state) do
if ns = State.ns(state, prefix) do
{:ok, RDF.iri(ns)}
else
{:error, "unknown prefix #{inspect(prefix)} in line #{inspect(line)}"}
end
end
defp build_node({{:string_literal_quote, _line, value}, {:datatype, datatype}}, state) do
with {:ok, datatype} <- build_node(datatype, state) do
{:ok, RDF.literal(value, datatype: datatype)}
end
end
defp build_node({:relative_iri, relative_iri}, %State{base_iri: nil}) do
{:error, "unresolvable relative IRI '#{relative_iri}', no base iri defined"}
end
defp build_node({:relative_iri, relative_iri}, %State{base_iri: base_iri}) do
{:ok, IRI.absolute(relative_iri, base_iri)}
end
defp valid_regexp_escaping(regexp) do
{:ok, regexp}
end
defp unescape_code(nil), do: nil
defp unescape_code(string), do: Macro.unescape_string(string)
defp unescape_regex(nil), do: nil
defp unescape_regex(string),
do: string |> unescape_8digit_unicode_seq() |> Macro.unescape_string(®ex_unescape_map(&1))
defp regex_unescape_map(:unicode), do: true
defp regex_unescape_map(?/), do: ?\/
defp regex_unescape_map(_), do: false
defp unescape_8digit_unicode_seq(string) do
String.replace(
string,
~r/(?<!\\)\\U([0-9]|[A-F]|[a-f]){2}(([0-9]|[A-F]|[a-f]){6})/,
"\\u{\\2}"
)
end
end
|
lib/shex/shexc/decoder.ex
| 0.627495 | 0.500671 |
decoder.ex
|
starcoder
|
defmodule Ratatouille.Renderer.Element.Panel do
@moduledoc false
@behaviour Ratatouille.Renderer
alias ExTermbox.Position
alias Ratatouille.Renderer.{Border, Box, Canvas, Element, Text}
@padding 2
@title_offset_x 2
@impl true
def render(
%Canvas{render_box: box} = canvas,
%Element{attributes: %{height: :fill} = attrs} = element,
render_fn
) do
new_attrs = %{attrs | height: Box.height(box)}
render(canvas, %Element{element | attributes: new_attrs}, render_fn)
end
def render(
%Canvas{render_box: box} = canvas,
%Element{attributes: attrs, children: children},
render_fn
) do
fill_empty? = !is_nil(attrs[:height])
constrained_canvas =
canvas
|> constrain_canvas(attrs[:height])
rendered_canvas =
constrained_canvas
|> Canvas.padded(@padding)
|> render_fn.(children)
consume_y =
rendered_canvas.render_box.top_left.y - box.top_left.y + @padding
constrained_canvas
|> wrapper_canvas(rendered_canvas, fill_empty?)
|> render_features(attrs)
|> Canvas.consume_rows(consume_y)
end
defp render_features(canvas, attrs) do
canvas
|> Border.render()
|> render_title(attrs[:title])
end
defp render_title(canvas, nil), do: canvas
defp render_title(%Canvas{render_box: box} = canvas, title) do
Text.render(canvas, title_position(box), title)
end
defp title_position(box),
do: Position.translate_x(box.top_left, @title_offset_x)
defp wrapper_canvas(original_canvas, rendered_canvas, fill?) do
%Canvas{
rendered_canvas
| render_box:
wrapper_box(
original_canvas.render_box,
rendered_canvas.render_box,
fill?
)
}
end
defp wrapper_box(original_box, _rendered_box, true), do: original_box
defp wrapper_box(original_box, rendered_box, false),
do: %Box{
original_box
| bottom_right: %Position{
x: original_box.bottom_right.x,
y: rendered_box.top_left.y
}
}
defp constrain_canvas(%Canvas{render_box: box} = canvas, height),
do: %Canvas{canvas | render_box: constrain_box(box, height)}
defp constrain_box(box, nil), do: box
defp constrain_box(%Box{top_left: top_left} = box, height) do
Box.from_dimensions(Box.width(box), height, top_left)
end
end
|
lib/ratatouille/renderer/element/panel.ex
| 0.856392 | 0.42051 |
panel.ex
|
starcoder
|
defmodule Advent.Y2021.D09 do
@moduledoc """
https://adventofcode.com/2021/day/9
"""
@typep point :: {non_neg_integer(), non_neg_integer()}
@typep grid :: %{point() => non_neg_integer()}
@doc """
Find all of the low points on your heightmap. What is the sum of the risk
levels of all low points on your heightmap?
"""
@spec part_one(Enumerable.t()) :: non_neg_integer()
def part_one(input) do
grid = parse_input(input)
grid
|> find_low_points()
|> Enum.map(&risk_level(grid, &1))
|> Enum.sum()
end
@doc """
What do you get if you multiply together the sizes of the three largest
basins?
"""
@spec part_two(Enumerable.t()) :: non_neg_integer()
def part_two(input) do
grid = parse_input(input)
grid
|> find_low_points()
|> Enum.map(&find_basin(grid, &1))
|> Enum.map(&MapSet.size/1)
|> Enum.sort(:desc)
|> Enum.take(3)
|> Enum.product()
end
@spec parse_input(Enumerable.t()) :: grid()
defp parse_input(input) do
input
|> Stream.map(fn line ->
line
|> String.graphemes()
|> Enum.map(&String.to_integer/1)
|> Enum.with_index()
end)
|> Stream.with_index()
|> Enum.reduce(Map.new(), fn {heights, row}, grid ->
Enum.reduce(heights, grid, fn {height, col}, grid ->
Map.put(grid, {col, row}, height)
end)
end)
end
@spec find_low_points(grid()) :: [point()]
defp find_low_points(grid) do
Enum.filter(grid, fn {point, height} ->
adj_heights = Enum.map(get_adjacent_points(grid, point), &Map.get(grid, &1, :infinity))
Enum.all?(adj_heights, &(&1 > height))
end)
|> Enum.map(fn {point, _height} -> point end)
end
@spec get_adjacent_points(grid(), point()) :: [point()]
defp get_adjacent_points(grid, {col, row}) do
[{col - 1, row}, {col + 1, row}, {col, row - 1}, {col, row + 1}]
|> Enum.filter(&Map.has_key?(grid, &1))
end
@spec risk_level(grid(), point()) :: non_neg_integer()
defp risk_level(grid, point) do
grid[point] + 1
end
@spec find_basin(grid(), point()) :: MapSet.t()
defp find_basin(grid, low_point) do
do_find_basin(grid, [low_point], MapSet.new())
end
@spec do_find_basin(grid(), [point()], MapSet.t()) :: MapSet.t()
defp do_find_basin(_grid, [], seen), do: seen
defp do_find_basin(grid, [head | todo], seen) do
adj =
get_adjacent_points(grid, head)
|> Enum.reject(&MapSet.member?(seen, &1))
|> Enum.filter(fn ap ->
grid[ap] > grid[head] && grid[ap] != 9
end)
do_find_basin(grid, todo ++ adj, MapSet.put(seen, head))
end
end
|
lib/advent/y2021/d09.ex
| 0.767559 | 0.589066 |
d09.ex
|
starcoder
|
defmodule Omise.Recipient do
@moduledoc ~S"""
Provides Recipient API interfaces.
<https://www.omise.co/recipients-api>
"""
use Omise.HTTPClient, endpoint: "recipients"
defstruct object: "recipient",
id: nil,
livemode: nil,
location: nil,
verified: nil,
active: nil,
name: nil,
email: nil,
description: nil,
type: nil,
tax_id: nil,
bank_account: %Omise.BankAccount{},
failure_code: nil,
created: nil,
deleted: false
@type t :: %__MODULE__{
object: String.t(),
id: String.t(),
livemode: boolean,
location: String.t(),
verified: boolean,
active: boolean,
name: String.t(),
email: String.t(),
description: String.t(),
type: String.t(),
tax_id: String.t(),
bank_account: Omise.BankAccount.t(),
failure_code: String.t(),
created: String.t(),
deleted: boolean
}
@doc ~S"""
List all recipients.
Returns `{:ok, recipients}` if the request is successful, `{:error, error}` otherwise.
## Query Parameters:
* `offset` - (optional, default: 0) The offset of the first record returned.
* `limit` - (optional, default: 20, maximum: 100) The maximum amount of records returned.
* `from` - (optional, default: 1970-01-01T00:00:00Z, format: ISO 8601) The UTC date and time limiting the beginning of returned records.
* `to` - (optional, default: current UTC Datetime, format: ISO 8601) The UTC date and time limiting the end of returned records.
## Examples
Omise.Recipient.list
Omise.Recipient.list(limit: 5)
"""
@spec list(Keyword.t(), Keyword.t()) :: {:ok, Omise.List.t()} | {:error, Omise.Error.t()}
def list(params \\ [], opts \\ []) do
opts = Keyword.merge(opts, as: %Omise.List{data: [%__MODULE__{}]})
get(@endpoint, params, opts)
end
@doc ~S"""
Retrieve a recipient.
Returns `{:ok, recipient}` if the request is successful, `{:error, error}` otherwise.
## Examples
Omise.Recipient.retrieve("recp_test_4z6p7e0m4k40txecj5o")
"""
@spec retrieve(String.t(), Keyword.t()) :: {:ok, t} | {:error, Omise.Error.t()}
def retrieve(id, opts \\ []) do
opts = Keyword.merge(opts, as: %__MODULE__{})
get("#{@endpoint}/#{id}", [], opts)
end
@doc ~S"""
Create a recipient.
Returns `{:ok, recipient}` if the request is successful, `{:error, error}` otherwise.
## Request Parameters:
* `name` - The recipient's name.
* `email` - (optional) The recipient's email.
* `description` - (optional) The recipient's description.
* `type` - Either individual or corporation.
* `tax_id` - (optional) The recipient's tax id.
* `bank_account` - A valid bank account.
## Examples
params = [
name: "Nanna",
email: "<EMAIL>",
description: "Though the truth may vary, this ship will carry our bodies safe to shore",
type: "individual",
bank_account: [
brand: "bbl",
number: "1234567890",
name: "Nanna"
]
]
Omise.Recipient.create(params)
"""
@spec create(Keyword.t(), Keyword.t()) :: {:ok, t} | {:error, Omise.Error.t()}
def create(params, opts \\ []) do
opts = Keyword.merge(opts, as: %__MODULE__{})
post(@endpoint, params, opts)
end
@doc ~S"""
Update a recipient.
Returns `{:ok, recipient}` if the request is successful, `{:error, error}` otherwise.
## Request Parameters:
* `name` - The recipient's name.
* `email` - (optional) The recipient's email.
* `description` - (optional) The recipient's description.
* `type` - Either individual or corporation.
* `tax_id` - (optional) The recipient's tax id.
* `bank_account` - A valid bank account.
## Examples
params = [
name: "<NAME>",
email: "<EMAIL>",
bank_account: [
brand: "kbank",
name: "<NAME>"
]
]
Omise.Recipient.update("recp_test_4z6p7e0m4k40txecj5oparams", params)
"""
@spec update(String.t(), Keyword.t(), Keyword.t()) :: {:ok, t} | {:error, Omise.Error.t()}
def update(id, params, opts \\ []) do
opts = Keyword.merge(opts, as: %__MODULE__{})
put("#{@endpoint}/#{id}", params, opts)
end
@doc ~S"""
Destroy a recipient.
Returns `{:ok, recipient}` if the request is successful, `{:error, error}` otherwise.
## Examples
Omise.Recipient.destroy("recp_test_4z6p7e0m4k40txecj5o")
"""
@spec destroy(String.t(), Keyword.t()) :: {:ok, t} | {:error, Omise.Error.t()}
def destroy(id, opts \\ []) do
opts = Keyword.merge(opts, as: %__MODULE__{})
delete("#{@endpoint}/#{id}", opts)
end
@doc ~S"""
Search all the recipients.
Returns `{:ok, recipients}` if the request is successful, `{:error, error}` otherwise.
## Query Parameters:
<https://www.omise.co/search-query-and-filters>
## Examples
Omise.Recipient.search(filters: [kind: "individual"])
Omise.Recipient.search(query: "recp_235k46kl6ljl")
"""
@spec search(Keyword.t(), Keyword.t()) :: {:ok, Omise.Search.t()} | {:error, Omise.Error.t()}
def search(params \\ [], opts \\ []) do
Omise.Search.execute("recipient", params, opts)
end
@doc ~S"""
List all transfer schedules for a given recipient.
Returns `{:ok, schedules}` if the request is successful, `{:error, error}` otherwise.
## Query Parameters:
* `offset` - (optional, default: 0) The offset of the first record returned.
* `limit` - (optional, default: 20, maximum: 100) The maximum amount of records returned.
* `from` - (optional, default: 1970-01-01T00:00:00Z, format: ISO 8601) The UTC date and time limiting the beginning of returned records.
* `to` - (optional, default: current UTC Datetime, format: ISO 8601) The UTC date and time limiting the end of returned records.
## Examples
Omise.Recipient.list_schedules("recp_test_556jkf7u174ptxuytac")
"""
@spec list_schedules(String.t(), Keyword.t(), Keyword.t()) :: {:ok, Omise.List.t()} | {:error, Omise.Error.t()}
def list_schedules(id, params \\ [], opts \\ []) do
opts = Keyword.merge(opts, as: %Omise.List{data: [%Omise.Schedule{}]})
get("#{@endpoint}/#{id}/schedules", params, opts)
end
end
|
lib/omise/recipient.ex
| 0.913416 | 0.529993 |
recipient.ex
|
starcoder
|
defmodule Stripe.Util do
def datetime_from_timestamp(ts) when is_binary ts do
ts = case Integer.parse ts do
:error -> 0
{i, _r} -> i
end
datetime_from_timestamp ts
end
def datetime_from_timestamp(ts) when is_number ts do
{{year, month, day}, {hour, minutes, seconds}} = :calendar.gregorian_seconds_to_datetime ts
{{year + 1970, month, day}, {hour, minutes, seconds}}
end
def datetime_from_timestamp(nil) do
datetime_from_timestamp 0
end
def string_map_to_atoms([string_key_map]) do
string_map_to_atoms string_key_map
end
def string_map_to_atoms(string_key_map) do
for {key, val} <- string_key_map, into: %{}, do: {String.to_atom(key), val}
end
def handle_stripe_response(res) do
cond do
res["error"] -> {:error, res}
res["data"] -> {:ok, Enum.map(res["data"], &Stripe.Util.string_map_to_atoms &1)}
true -> {:ok, Stripe.Util.string_map_to_atoms res}
end
end
# returns the full response in {:ok, response}
# this is useful to access top-level properties
def handle_stripe_full_response(res) do
cond do
res["error"] -> {:error, res}
true -> {:ok, Stripe.Util.string_map_to_atoms res}
end
end
def list_raw( endpoint, limit \\ 10, starting_after \\ "") do
list_raw endpoint, Stripe.config_or_env_key, limit, starting_after
end
def list_raw( endpoint, key, limit, starting_after) do
q = "#{endpoint}?limit=#{limit}"
q =
if String.length(starting_after) > 0 do
q <> "&starting_after=#{starting_after}"
else
q
end
Stripe.make_request_with_key(:get, q, key )
|> Stripe.Util.handle_stripe_full_response
end
def list( endpoint, key, starting_after, limit) do
list_raw endpoint, key, limit, starting_after
end
def list( endpoint, starting_after \\ "", limit \\ 10) do
list endpoint, Stripe.config_or_env_key, starting_after, limit
end
# most stripe listing endpoints allow the total count to be included without any results
def count(endpoint) do
count endpoint, Stripe.config_or_env_key
end
def count(endpoint, key) do
case Stripe.make_request_with_key(:get, "#{endpoint}?include[]=total_count&limit=0", key)
|> Stripe.Util.handle_stripe_full_response do
{:ok, res} ->
{:ok, res[:total_count]}
{:error, err} -> raise err
end
end
end
|
lib/stripe/util.ex
| 0.656438 | 0.460168 |
util.ex
|
starcoder
|
defmodule ColonelKurtz.BlockTypeContent do
@moduledoc """
`BlockTypeContent` is used to model the inner `content` field for a given block
type. Each block type has a unique schema represented by an Ecto.Schema that
defines an `embedded_schema` for the expected fields (corresponding with the
JS implementation for this block type).
Modules that use this macro may optionally define a `validate/2` that receives
the Content struct and a changeset with the fields in their `embedded_schema`
already cast and ready to be validated.
"""
alias ColonelKurtz.BlockType
alias ColonelKurtz.Utils
@type t :: %{
:__struct__ => atom,
optional(any) => any
}
@doc """
Macro for mixing in the BlockTypeContent behavior.
"""
defmacro __using__(_opts) do
quote do
use Ecto.Schema
import Ecto.Changeset
import ColonelKurtz.BlockTypeContent
alias ColonelKurtz.BlockTypeContent
alias ColonelKurtz.BlockTypes
@typep changeset :: Ecto.Changeset.t()
@typep block_content :: BlockTypeContent.t()
@before_compile ColonelKurtz.BlockTypeContent
@primary_key false
@derive [Jason.Encoder]
@spec changeset(block_content, map) :: changeset
def changeset(content, params) do
embeds = __schema__(:embeds)
fields = __schema__(:fields) -- embeds
changeset =
struct!(__MODULE__)
|> cast(params_map(params), fields)
changeset_with_embeds =
Enum.reduce(embeds, changeset, fn embed_name, c ->
cast_embed(c, embed_name)
end)
validate(content, changeset_with_embeds)
end
@spec from_map(map) :: block_content
def from_map(attrs) do
struct_attrs =
for name <- __schema__(:fields),
into: Keyword.new(),
do: {name, Map.get(attrs, Atom.to_string(name))}
struct!(__MODULE__, struct_attrs)
end
@spec validate(block_content, changeset) :: changeset
def validate(_content, changeset), do: changeset
defoverridable validate: 2
end
end
def __before_compile__(%{module: module}) do
block_module_contents =
quote do
use BlockType
end
module
|> get_block_module_name()
|> maybe_create(block_module_contents)
end
@spec get_block_module_name(module) :: module
defp get_block_module_name(content_module_name) do
content_module_name
|> Module.split()
|> Enum.drop(-1)
|> Module.concat()
end
@spec maybe_create(atom, Macro.t()) :: nil | {:module, module, binary, term}
defp maybe_create(module, module_contents) do
unless Utils.module_defined?(module) do
Module.create(module, module_contents, Macro.Env.location(__ENV__))
end
end
@spec params_map(map | struct) :: map
def params_map(params) when is_struct(params),
do: Map.from_struct(params)
def params_map(params) when is_map(params),
do: params
end
|
lib/colonel_kurtz/block_type_content.ex
| 0.823506 | 0.441553 |
block_type_content.ex
|
starcoder
|
defmodule Membrane.RawAudio do
@moduledoc """
This module contains a definition and related functions for struct `t:#{inspect(__MODULE__)}.t/0`,
describing a format of raw audio stream with interleaved channels.
"""
alias __MODULE__.SampleFormat
alias Membrane.Time
@compile {:inline,
[
sample_size: 1,
frame_size: 1,
sample_type_float?: 1,
sample_type_fixed?: 1,
big_endian?: 1,
little_endian?: 1,
signed?: 1,
unsigned?: 1,
sample_to_value: 2,
value_to_sample: 2,
value_to_sample_check_overflow: 2,
sample_min: 1,
sample_max: 1,
silence: 1,
frames_to_bytes: 2,
bytes_to_frames: 3,
frames_to_time: 3,
time_to_frames: 3,
bytes_to_time: 3,
time_to_bytes: 3
]}
# Amount of channels inside a frame.
@type channels_t :: pos_integer
# Sample rate of the audio.
@type sample_rate_t :: pos_integer
@type t :: %Membrane.RawAudio{
channels: channels_t,
sample_rate: sample_rate_t,
sample_format: SampleFormat.t()
}
@enforce_keys [:channels, :sample_rate, :sample_format]
defstruct @enforce_keys
@doc """
Returns how many bytes are needed to store a single sample.
Inlined by the compiler
"""
@spec sample_size(t) :: integer
def sample_size(%__MODULE__{sample_format: format}) do
{_type, size, _endianness} = SampleFormat.to_tuple(format)
size |> div(8)
end
@doc """
Returns how many bytes are needed to store a single frame.
Inlined by the compiler
"""
@spec frame_size(t) :: integer
def frame_size(%__MODULE__{channels: channels} = format) do
sample_size(format) * channels
end
@doc """
Determines if the sample values are represented by a floating point number.
Inlined by the compiler.
"""
@spec sample_type_float?(t) :: boolean
def sample_type_float?(%__MODULE__{sample_format: format}) do
case SampleFormat.to_tuple(format) do
{:f, _size, _endianness} -> true
_otherwise -> false
end
end
@doc """
Determines if the sample values are represented by an integer.
Inlined by the compiler.
"""
@spec sample_type_fixed?(t) :: boolean
def sample_type_fixed?(%__MODULE__{sample_format: format}) do
case SampleFormat.to_tuple(format) do
{:s, _size, _endianness} -> true
{:u, _size, _endianness} -> true
_otherwise -> false
end
end
@doc """
Determines if the sample values are represented by a number in little endian byte ordering.
Inlined by the compiler.
"""
@spec little_endian?(t) :: boolean
def little_endian?(%__MODULE__{sample_format: format}) do
case SampleFormat.to_tuple(format) do
{_type, _size, :le} -> true
{_type, _size, :any} -> true
_otherwise -> false
end
end
@doc """
Determines if the sample values are represented by a number in big endian byte ordering.
Inlined by the compiler.
"""
@spec big_endian?(t) :: boolean
def big_endian?(%__MODULE__{sample_format: format}) do
case SampleFormat.to_tuple(format) do
{_type, _size, :be} -> true
{_type, _size, :any} -> true
_otherwise -> false
end
end
@doc """
Determines if the sample values are represented by a signed number.
Inlined by the compiler.
"""
@spec signed?(t) :: boolean
def signed?(%__MODULE__{sample_format: format}) do
case SampleFormat.to_tuple(format) do
{:s, _size, _endianness} -> true
{:f, _size, _endianness} -> true
_otherwise -> false
end
end
@doc """
Determines if the sample values are represented by an unsigned number.
Inlined by the compiler.
"""
@spec unsigned?(t) :: boolean
def unsigned?(%__MODULE__{sample_format: format}) do
case SampleFormat.to_tuple(format) do
{:u, _size, _endianness} -> true
_otherwise -> false
end
end
@doc """
Converts one raw sample into its numeric value, interpreting it for given sample format.
Inlined by the compiler.
"""
@spec sample_to_value(bitstring, t) :: number
def sample_to_value(sample, %__MODULE__{sample_format: format}) do
case SampleFormat.to_tuple(format) do
{:s, size, endianness} when endianness in [:le, :any] ->
<<value::integer-size(size)-little-signed>> = sample
value
{:u, size, endianness} when endianness in [:le, :any] ->
<<value::integer-size(size)-little-unsigned>> = sample
value
{:s, size, :be} ->
<<value::integer-size(size)-big-signed>> = sample
value
{:u, size, :be} ->
<<value::integer-size(size)-big-unsigned>> = sample
value
{:f, size, :le} ->
<<value::float-size(size)-little>> = sample
value
{:f, size, :be} ->
<<value::float-size(size)-big>> = sample
value
end
end
@doc """
Converts value into one raw sample, encoding it with the given sample format.
Inlined by the compiler.
"""
@spec value_to_sample(number, t) :: binary
def value_to_sample(value, %__MODULE__{sample_format: format}) do
case SampleFormat.to_tuple(format) do
{:s, size, endianness} when endianness in [:le, :any] ->
<<value::integer-size(size)-little-signed>>
{:u, size, endianness} when endianness in [:le, :any] ->
<<value::integer-size(size)-little-unsigned>>
{:s, size, :be} ->
<<value::integer-size(size)-big-signed>>
{:u, size, :be} ->
<<value::integer-size(size)-big-unsigned>>
{:f, size, :le} ->
<<value::float-size(size)-little>>
{:f, size, :be} ->
<<value::float-size(size)-big>>
end
end
@doc """
Same as value_to_sample/2, but also checks for overflow.
Returns {:error, :overflow} if overflow happens.
Inlined by the compiler.
"""
@spec value_to_sample_check_overflow(number, t) :: {:ok, binary} | {:error, :overflow}
def value_to_sample_check_overflow(value, format) do
if sample_min(format) <= value and sample_max(format) >= value do
{:ok, value_to_sample(value, format)}
else
{:error, :overflow}
end
end
@doc """
Returns minimum sample value for given sample format.
Inlined by the compiler.
"""
@spec sample_min(t) :: number
def sample_min(%__MODULE__{sample_format: format}) do
import Bitwise
case SampleFormat.to_tuple(format) do
{:u, _size, _endianness} -> 0
{:s, size, _endianness} -> -(1 <<< (size - 1))
{:f, _size, _endianness} -> -1.0
end
end
@doc """
Returns maximum sample value for given sample format.
Inlined by the compiler.
"""
@spec sample_max(t) :: number
def sample_max(%__MODULE__{sample_format: format}) do
import Bitwise
case SampleFormat.to_tuple(format) do
{:s, size, _endianness} -> (1 <<< (size - 1)) - 1
{:u, size, _endianness} -> (1 <<< size) - 1
{:f, _size, _endianness} -> 1.0
end
end
@doc """
Returns one 'silent' sample, that is value of zero in given format' sample format.
Inlined by the compiler.
"""
@spec silence(t) :: binary
def silence(%__MODULE__{sample_format: :s8}), do: <<0>>
def silence(%__MODULE__{sample_format: :u8}), do: <<128>>
def silence(%__MODULE__{sample_format: :s16le}), do: <<0, 0>>
def silence(%__MODULE__{sample_format: :u16le}), do: <<0, 128>>
def silence(%__MODULE__{sample_format: :s16be}), do: <<0, 0>>
def silence(%__MODULE__{sample_format: :u16be}), do: <<128, 0>>
def silence(%__MODULE__{sample_format: :s24le}), do: <<0, 0, 0>>
def silence(%__MODULE__{sample_format: :u24le}), do: <<0, 0, 128>>
def silence(%__MODULE__{sample_format: :s24be}), do: <<0, 0, 0>>
def silence(%__MODULE__{sample_format: :u24be}), do: <<128, 0, 0>>
def silence(%__MODULE__{sample_format: :s32le}), do: <<0, 0, 0, 0>>
def silence(%__MODULE__{sample_format: :u32le}), do: <<0, 0, 0, 128>>
def silence(%__MODULE__{sample_format: :s32be}), do: <<0, 0, 0, 0>>
def silence(%__MODULE__{sample_format: :u32be}), do: <<128, 0, 0, 0>>
def silence(%__MODULE__{sample_format: :f32le}), do: <<0, 0, 0, 0>>
def silence(%__MODULE__{sample_format: :f32be}), do: <<0, 0, 0, 0>>
def silence(%__MODULE__{sample_format: :f64le}), do: <<0, 0, 0, 0, 0, 0, 0, 0>>
def silence(%__MODULE__{sample_format: :f64be}), do: <<0, 0, 0, 0, 0, 0, 0, 0>>
@doc """
Returns a binary which corresponds to the silence during the given interval
of time in given format' sample format
## Examples:
The following code generates the silence for the given format
iex> alias Membrane.RawAudio
iex> format = %RawAudio{sample_rate: 48_000, sample_format: :s16le, channels: 2}
iex> silence = RawAudio.silence(format, 100 |> Membrane.Time.microseconds())
<<0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0>>
"""
@spec silence(t, Time.non_neg_t(), (float -> integer)) :: binary
def silence(%__MODULE__{} = format, time, round_f \\ &(&1 |> :math.ceil() |> trunc))
when time >= 0 do
length = time_to_frames(time, format, round_f)
silence(format) |> String.duplicate(format.channels * length)
end
@doc """
Converts frames to bytes in given format.
Inlined by the compiler.
"""
@spec frames_to_bytes(non_neg_integer, t) :: non_neg_integer
def frames_to_bytes(frames, %__MODULE__{} = format) when frames >= 0 do
frames * frame_size(format)
end
@doc """
Converts bytes to frames in given format.
Inlined by the compiler.
"""
@spec bytes_to_frames(non_neg_integer, t, (float -> integer)) :: non_neg_integer
def bytes_to_frames(bytes, %__MODULE__{} = format, round_f \\ &trunc/1) when bytes >= 0 do
(bytes / frame_size(format)) |> round_f.()
end
@doc """
Converts time in Membrane.Time units to frames in given format.
Inlined by the compiler.
"""
@spec time_to_frames(Time.non_neg_t(), t, (float -> integer)) :: non_neg_integer
def time_to_frames(time, %__MODULE__{} = format, round_f \\ &(&1 |> :math.ceil() |> trunc))
when time >= 0 do
(time * format.sample_rate / Time.second()) |> round_f.()
end
@doc """
Converts frames to time in Membrane.Time units in given format.
Inlined by the compiler.
"""
@spec frames_to_time(non_neg_integer, t, (float -> integer)) :: Time.non_neg_t()
def frames_to_time(frames, %__MODULE__{} = format, round_f \\ &trunc/1)
when frames >= 0 do
(frames * Time.second() / format.sample_rate) |> round_f.()
end
@doc """
Converts time in Membrane.Time units to bytes in given format.
Inlined by the compiler.
"""
@spec time_to_bytes(Time.non_neg_t(), t, (float -> integer)) :: non_neg_integer
def time_to_bytes(time, %__MODULE__{} = format, round_f \\ &(&1 |> :math.ceil() |> trunc))
when time >= 0 do
time_to_frames(time, format, round_f) |> frames_to_bytes(format)
end
@doc """
Converts bytes to time in Membrane.Time units in given format.
Inlined by the compiler.
"""
@spec bytes_to_time(non_neg_integer, t, (float -> integer)) :: Time.non_neg_t()
def bytes_to_time(bytes, %__MODULE__{} = format, round_f \\ &trunc/1)
when bytes >= 0 do
frames_to_time(bytes |> bytes_to_frames(format), format, round_f)
end
end
|
lib/membrane_raw_audio.ex
| 0.909942 | 0.687525 |
membrane_raw_audio.ex
|
starcoder
|
defmodule Vivaldi.Peer.PingClient do
@moduledoc """
Periodically Pings peers in a random order, and measures RTT on response.
When 8(configurable) responses are received from another peer `x_j`, the median RTT and latest coordinate of `x_j` is chosen, and sent to the Coordinate process
so that it can update our coordinate, `x_i`
This is a stateless process, i.e. individual pings and peer states are not maintained.
For example, if `x_j` crashes after 4 pings and doesn't respond, we just move on to the next peer.
"""
use GenServer
use Timex
require Logger
alias Vivaldi.Peer.{Coordinate, Connections, PingServer}
# Public API
def start_link(config) do
node_id = config[:node_id]
GenServer.start_link(__MODULE__, config, name: get_name(node_id))
end
def get_name(node_id) do
:"#{node_id}-ping-client"
end
def begin_pings(node_id) do
GenServer.call(get_name(node_id), :begin_pings)
end
# Implementation
def handle_call(:begin_pings, _, config) do
node_id = config[:node_id]
name = get_periodic_pinger_name(node_id)
case Process.whereis(name) do
nil ->
spawn_periodic_pinger(config)
_ ->
Logger.info "#{node_id} - ignoring :begin_pings. Already started..."
end
{:reply, :ok, config}
end
def handle_info({:EXIT, _pid, reason}, config) do
node_id = config[:node_id]
Logger.warn "#{node_id} - periodic_pinger exited. Reason: #{inspect reason}"
spawn_periodic_pinger(config)
{:noreply, config}
end
def get_periodic_pinger_name(node_id) do
:"#{node_id}-periodic_pinger"
end
defp spawn_periodic_pinger(config) do
node_id = config[:node_id]
Process.flag :trap_exit, true
pid = spawn_link(fn -> begin_periodic_pinger(config) end)
name = get_periodic_pinger_name(node_id)
Process.register pid, name
pid
end
@doc """
Pings peer_ids in random order serially.
Should we introduce concurrent pinging?
"""
def begin_periodic_pinger(config) do
node_id = config[:node_id]
config[:peer_ids]
|> Enum.shuffle()
|> Enum.map(fn peer_id ->
case ping_multi(config, peer_id) do
{:ok, {rtt, other_coordinate}} ->
Coordinate.update_coordinate(node_id, peer_id, other_coordinate, rtt)
{:error, reason} ->
Logger.error "#{node_id} - ping_multi to #{peer_id} failed. #{inspect reason}"
end
:timer.sleep(config[:ping_gap_interval])
end)
begin_periodic_pinger(config)
end
def ping_multi(config, peer_id) do
Logger.info "Pinging #{inspect peer_id}..."
{node_id, times} = {config[:node_id], config[:ping_repeat]}
start_ping_id = generate_start_ping_id()
case Connections.get_peer_ping_server(node_id, peer_id) do
{:ok, server_pid} ->
Stream.map(1..times, fn i ->
ping_once(config, peer_id, server_pid, start_ping_id + i)
end)
|> Stream.filter(fn {status, _} ->
status == :pong
end)
|> Stream.map(fn {_, response} -> response end)
|> Enum.into([])
|> get_median_rtt_and_last_coordinate()
{:error, reason} ->
{:error, reason}
end
end
def ping_once(config, peer_id, peer_server_pid, ping_id) do
{node_id, session_id, timeout} = {config[:node_id], config[:session_id], config[:ping_timeout]}
start = Duration.now()
response = PingServer.ping(node_id, session_id, peer_id, peer_server_pid, ping_id, timeout)
finish = Duration.now()
case response do
{:pong, payload} ->
rtt = calculate_rtt(start, finish)
other_coordinate = payload[:coordinate]
{:pong, {rtt, other_coordinate}}
{:pang, message} ->
Logger.error message
{:pang, message}
{:error, message}
{:error, reason} ->
Logger.warn "#{node_id} - ping to #{peer_id} failed. Reason: #{inspect reason}"
{:error, reason}
_ ->
message = "#{node_id} - unknown response from #{peer_id} to ping: #{ping_id}"
Logger.error message
{:error, message}
end
end
def get_median_rtt_and_last_coordinate([]) do
{:error, "No valid responses received"}
end
def get_median_rtt_and_last_coordinate(responses) do
{:ok, {get_median_rtt(responses), get_last_coordinate(responses)}}
end
def get_median_rtt(responses) do
rtts = Enum.map(responses, fn {rtt, _} -> rtt end)
sorted_rtts = Enum.sort(rtts)
count = Enum.count(sorted_rtts)
case rem(count, 2) do
1 ->
median_index = round(count/2) - 1
Enum.at(sorted_rtts, median_index)
0 ->
middle = round(count/2)
{median_index_1, median_index_2} = {middle, middle - 1}
rtt_1 = Enum.at(sorted_rtts, median_index_1)
rtt_2 = Enum.at(sorted_rtts, median_index_2)
(rtt_1 + rtt_2) / 2
end
end
def get_last_coordinate(responses) do
{_rtt, coordinate} = List.last(responses)
coordinate
end
@doc """
Generate a random id. We'll just use a 3 digit integer for now, for debugging.
If id's clash, we'll probably use something like an uuid
"""
def generate_start_ping_id do
:rand.uniform() * 1000 |> round()
end
def calculate_rtt(start, finish) do
microseconds = Duration.diff(finish, start, :microseconds)
microseconds * 1.0e-6
end
end
|
vivaldi/lib/peer/ping_client.ex
| 0.782746 | 0.448306 |
ping_client.ex
|
starcoder
|
defmodule Ockam.Stream.Index.Shard do
@moduledoc """
Stream index management shard.
This module performs storage operations and keeping state per client_id/stream_name pair
"""
use Ockam.Worker
require Logger
def get_index(shard, partition) do
GenServer.call(shard, {:get_index, partition})
end
def save_index(shard, partition, index) do
GenServer.cast(shard, {:save_index, partition, index})
end
@impl true
def setup(options, state) do
{:ok, {client_id, stream_name}} = Keyword.fetch(options, :shard_id)
{:ok, {storage_mod, storage_options}} = Keyword.fetch(options, :storage)
case storage_mod.init(storage_options) do
{:ok, storage_state} ->
{:ok,
Map.merge(
state,
%{
storage: {storage_mod, storage_state},
client_id: client_id,
stream_name: stream_name
}
)}
{:error, error} ->
Logger.error("Stream index setup error: #{inspect(error)}")
{:error, error}
end
end
@impl true
def handle_message(_msg, state) do
{:ok, state}
end
@impl true
def handle_cast({:save_index, partition, index}, state) do
%{client_id: client_id, stream_name: stream_name} = state
case save_index(client_id, stream_name, partition, index, state) do
{:ok, state} ->
{:noreply, update_ts(state)}
{{:error, error}, state} ->
Logger.error(
"Unable to save index: #{inspect({client_id, stream_name, partition, index})}. Reason: #{
inspect(error)
}"
)
{:stop, :normal, state}
end
end
@impl true
def handle_call({:get_index, partition}, _from, state) do
%{client_id: client_id, stream_name: stream_name} = state
case get_index(client_id, stream_name, partition, state) do
{{:ok, index}, state} ->
{:reply, {:ok, index}, update_ts(state)}
{{:error, error}, state} ->
Logger.error(
"Unable to get index for: #{inspect({client_id, stream_name, partition})}. Reason: #{
inspect(error)
}"
)
{:reply, {:error, error}, update_ts(state)}
end
end
def update_ts(state) do
Map.put(state, :last_message_ts, System.os_time(:millisecond))
end
def save_index(client_id, stream_name, partition, index, state) do
with_storage(state, fn storage_mod, storage_state ->
storage_mod.save_index(client_id, stream_name, partition, index, storage_state)
end)
end
def get_index(client_id, stream_name, partition, state) do
with_storage(state, fn storage_mod, storage_state ->
storage_mod.get_index(client_id, stream_name, partition, storage_state)
end)
end
def with_storage(state, fun) do
{storage_mod, storage_state} = Map.get(state, :storage)
{result, new_storage_state} = fun.(storage_mod, storage_state)
{result, Map.put(state, :storage, {storage_mod, new_storage_state})}
end
end
|
implementations/elixir/ockam/ockam/lib/ockam/stream/index/shard.ex
| 0.754418 | 0.405331 |
shard.ex
|
starcoder
|
defmodule MixUnused.Filter do
@moduledoc false
import Kernel, except: [match?: 2]
alias MixUnused.Exports
@type module_pattern() :: module() | Regex.t() | :_
@type function_pattern() :: atom() | Regex.t() | :_
@type arity_pattern() :: arity() | Range.t(arity(), arity()) | :_
@type pattern() ::
{module_pattern(), function_pattern(), arity_pattern()}
| {module_pattern(), function_pattern()}
| module_pattern()
@doc """
Reject values in `exports` that match any pattern in `patterns`.
## Examples
```
iex> functions = %{
...> {Foo, :bar, 1} => %{},
...> {Foo, :baz, 1} => %{},
...> {Bar, :foo, 1} => %{}
...> }
iex> patterns = [{Foo, :_, 1}]
iex> #{inspect(__MODULE__)}.reject_matching(functions, patterns)
[{{Bar, :foo, 1}, %{}}]
```
The pattern can be just atom which will be then treated as `{mod, :_, :_}`:
```
iex> functions = %{
...> {Foo, :bar, 1} => %{},
...> {Foo, :baz, 1} => %{},
...> {Bar, :foo, 1} => %{}
...> }
iex> patterns = [Foo]
iex> #{inspect(__MODULE__)}.reject_matching(functions, patterns)
[{{Bar, :foo, 1}, %{}}]
```
As well it can be 2-ary tuple. Then it will accepr any arity:
```
iex> functions = %{
...> {Foo, :bar, 1} => %{},
...> {Foo, :bar, 2} => %{},
...> {Foo, :baz, 1} => %{}
...> }
iex> patterns = [{Foo, :bar}]
iex> #{inspect(__MODULE__)}.reject_matching(functions, patterns)
[{{Foo, :baz, 1}, %{}}]
```
As a pattern for module and function name the reqular expression can be
passed:
```
iex> functions = %{
...> {Foo, :bar, 1} => %{},
...> {Foo, :baz, 1} => %{}
...> }
iex> patterns = [{Foo, ~r/^ba[rz]$/}]
iex> #{inspect(__MODULE__)}.reject_matching(functions, patterns)
[]
```
Allow pattern matching module as well:
```
iex> functions = %{
...> {Foo, :bar, 1} => %{},
...> {Foo.Bar, :baz, 1} => %{}
...> }
iex> patterns = [{~r/Foo\..*$/, ~r/^ba[rz]$/}]
iex> #{inspect(__MODULE__)}.reject_matching(functions, patterns)
[{{Foo, :bar, 1}, %{}}]
```
For arity you can pass range:
```
iex> functions = %{
...> {Foo, :bar, 1} => %{},
...> {Foo, :bar, 2} => %{},
...> {Foo, :bar, 3} => %{}
...> }
iex> patterns = [{Foo, :bar, 2..3}]
iex> #{inspect(__MODULE__)}.reject_matching(functions, patterns)
[{{Foo, :bar, 1}, %{}}]
```
"""
@spec reject_matching(exports :: Exports.t(), patterns :: [pattern()]) ::
Exports.t()
def reject_matching(exports, patterns) do
filters =
Enum.map(patterns, fn
{_m, _f, _a} = entry -> entry
{m, f} -> {m, f, :_}
{m} -> {m, :_, :_}
m -> {m, :_, :_}
end)
Enum.reject(exports, fn {func, _} ->
Enum.any?(filters, &mfa_match?(&1, func))
end)
end
@spec mfa_match?(mfa(), pattern()) :: boolean()
defp mfa_match?({pmod, pname, parity}, {fmod, fname, farity}) do
match?(pmod, fmod) and match?(pname, fname) and arity_match?(parity, farity)
end
defp match?(value, value), do: true
defp match?(:_, _value), do: true
defp match?(%Regex{} = re, value) when is_atom(value),
do: inspect(value) =~ re or Atom.to_string(value) =~ re
defp match?(_, _), do: false
defp arity_match?(:_, _value), do: true
defp arity_match?(value, value), do: true
defp arity_match?(_.._ = range, value), do: value in range
defp arity_match?(_, _), do: false
end
|
lib/mix_unused/filter.ex
| 0.851305 | 0.86771 |
filter.ex
|
starcoder
|
defexception IO.StreamError, reason: nil do
def message(exception) do
formatted = iolist_to_binary(:file.format_error(reason exception))
"error during streaming: #{formatted}"
end
end
defmodule IO do
@moduledoc """
Module responsible for doing IO. Many functions in this
module expects an IO device and an io data encoded in UTF-8.
Use the bin* functions if the data is binary, useful when
working with raw bytes or when no unicode conversion should
be performed.
An IO device must be a pid or an atom representing a process.
For convenience, Elixir provides `:stdio` and `:stderr` as
shortcuts to Erlang's `:standard_io` and `:standard_error`.
An io data can be:
* A list of integers representing a string. Any unicode
character must be represented with one entry in the list,
this entry being an integer with the codepoint value;
* A binary in which unicode characters are represented
with many bytes (Elixir's default representation);
* A list of binaries or a list of char lists (as described above);
"""
import :erlang, only: [group_leader: 0]
defmacrop is_iolist(data) do
quote do
is_list(unquote(data)) or is_binary(unquote(data))
end
end
@doc """
Reads `count` characters from the IO device or until
the end of the line if `:line` is given. It returns:
* `data` - The input characters.
* `:eof` - End of file was encountered.
* `{:error, reason}` - Other (rare) error condition,
for instance `{:error, :estale}` if reading from an
NFS file system.
"""
def read(device // group_leader, chars_or_line)
def read(device, :line) do
:io.get_line(map_dev(device), '')
end
def read(device, count) when count >= 0 do
:io.get_chars(map_dev(device), '', count)
end
@doc """
Reads `count` bytes from the IO device or until
the end of the line if `:line` is given. It returns:
* `data` - The input characters.
* `:eof` - End of file was encountered.
* `{:error, reason}` - Other (rare) error condition,
for instance `{:error, :estale}` if reading from an
NFS file system.
"""
def binread(device // group_leader, chars_or_line)
def binread(device, :line) do
case :file.read_line(map_dev(device)) do
{ :ok, data } -> data
other -> other
end
end
def binread(device, count) when count >= 0 do
case :file.read(map_dev(device), count) do
{ :ok, data } -> data
other -> other
end
end
@doc """
Writes the given argument to the given device.
By default the device is the standard output.
The argument is expected to be a chardata (i.e.
a char list or an unicode binary).
It returns `:ok` if it succeeds.
## Examples
IO.write "sample"
#=> "sample"
IO.write :stderr, "error"
#=> "error"
"""
def write(device // group_leader(), item) when is_iolist(item) do
:io.put_chars map_dev(device), item
end
@doc """
Writes the given argument to the given device
as a binary, no unicode conversion happens.
Check `write/2` for more information.
"""
def binwrite(device // group_leader(), item) when is_iolist(item) do
:file.write map_dev(device), item
end
@doc """
Writes the argument to the device, similar to `write/2`,
but adds a newline at the end. The argument is expected
to be a chardata.
"""
def puts(device // group_leader(), item) when is_iolist(item) do
erl_dev = map_dev(device)
:io.put_chars erl_dev, [item, ?\n]
end
@doc """
Inspects and writes the given argument to the device
followed by a newline. A set of options can be given.
It sets by default pretty printing to true and the
width to be the width of the device, with a minimum
of 80 characters.
## Examples
IO.inspect Process.list
"""
def inspect(item, opts // []) do
inspect group_leader(), item, opts
end
@doc """
Inspects the item with options using the given device.
"""
def inspect(device, item, opts) when is_list(opts) do
opts = Keyword.put_new(opts, :pretty, true)
unless Keyword.get(opts, :width) do
opts = case :io.columns(device) do
{ :ok, width } -> Keyword.put(opts, :width, width)
{ :error, _ } -> opts
end
end
puts device, Kernel.inspect(item, opts)
item
end
@doc """
Gets a number of bytes from the io device. If the
io device is a unicode device, `count` implies
the number of unicode codepoints to be retrieved.
Otherwise, `count` is the number of raw bytes to be retrieved.
It returns:
* `data` - The input characters.
* `:eof` - End of file was encountered.
* `{:error, reason}` - Other (rare) error condition,
for instance `{:error, :estale}` if reading from an
NFS file system.
"""
def getn(prompt, count // 1)
def getn(prompt, count) when is_integer(count) do
getn(group_leader, prompt, count)
end
def getn(device, prompt) do
getn(device, prompt, 1)
end
@doc """
Gets a number of bytes from the io device. If the
io device is a unicode device, `count` implies
the number of unicode codepoints to be retrieved.
Otherwise, `count` is the number of raw bytes to be retrieved.
"""
def getn(device, prompt, count) do
:io.get_chars(map_dev(device), prompt, count)
end
@doc """
Reads a line from the IO device. It returns:
* `data` - The characters in the line terminated
by a LF (or end of file).
* `:eof` - End of file was encountered.
* `{:error, reason}` - Other (rare) error condition,
for instance `{:error, :estale}` if reading from an
NFS file system.
"""
def gets(device // group_leader(), prompt) do
:io.get_line(map_dev(device), prompt)
end
@doc """
Converts the io device into a Stream. The device is
iterated line by line if :line is given or by a given
number of codepoints.
This reads the io as utf-8. Check out
`IO.binstream/2` to handle the IO as a raw binary.
## Examples
Here is an example on how we mimic an echo server
from the command line:
Enum.each IO.stream(:stdio, :line), &IO.write(&1)
"""
def stream(device, line_or_bytes) do
fn(acc, f) -> stream(map_dev(device), line_or_bytes, acc, f) end
end
@doc """
Converts the io device into a Stream. The device is
iterated line by line.
This reads the io as a raw binary.
"""
def binstream(device, line_or_bytes) do
fn(acc, f) -> binstream(map_dev(device), line_or_bytes, acc, f) end
end
@doc false
def stream(device, what, acc, fun) do
case read(device, what) do
:eof ->
acc
{ :error, reason } ->
raise IO.StreamError, reason: reason
data ->
stream(device, what, fun.(data, acc), fun)
end
end
@doc false
def binstream(device, what, acc, fun) do
case binread(device, what) do
:eof ->
acc
{ :error, reason } ->
raise IO.StreamError, reason: reason
data ->
binstream(device, what, fun.(data, acc), fun)
end
end
# Map the Elixir names for standard io and error to Erlang names
defp map_dev(:stdio), do: :standard_io
defp map_dev(:stderr), do: :standard_error
defp map_dev(other), do: other
end
|
lib/elixir/lib/io.ex
| 0.87584 | 0.677444 |
io.ex
|
starcoder
|
defmodule Logi.Layout do
@moduledoc """
Log Message Layout Behaviour.
This module defines the standard interface to format log messages issued by the functions in `Logi` module.
(e.g., `Logi.info/3`, `Logi.warning/3`, etc)
A layout instance may be installed into a channel along with an associated sink.
## Examples
```elixir
iex> format_fun = fn (_, format, data) -> :lists.flatten(:io_lib.format("EXAMPLE: " <> format <> "\\n", data)) end
iex> layout = Logi.BuiltIn.Layout.Fun.new format_fun
iex> {:ok, _} = Logi.Channel.install_sink(Logi.BuiltIn.Sink.IoDevice.new(:foo, [layout: layout]), :info)
iex> Logi.info "hello world"
#OUTPUT# EXAMPLE: hello world
```
"""
@doc "Message formatting function."
@callback format(Logi.Context.context, :io.format, data, extra_data) :: formatted_data
@typedoc "An instance of `Logi.Layout` behaviour implementation module."
@opaque layout :: :logi_layout.layout
@typedoc "A module that implements the `Logi.Layout` behaviour."
@type callback_module :: module
@typedoc """
The value of the fourth arguemnt of the `c:format/4` callback function.
If the `layout()` does not have an explicit `extra_data()`, `nil` will be passed instead.
"""
@type extra_data :: any
@typedoc """
A data which is subject to format.
This type is an alias of the type of second arguemnt of the `:io_lib.format/2`.
"""
@type data :: [any]
@typedoc "Formatted Data."
@type formatted_data :: any
@doc "Creates a new layout instance."
@spec new(callback_module, extra_data) :: layout
def new(module, extra_data \\ nil) do
:logi_layout.new module, extra_data
end
@doc "Returns `true` if `x` is a `t:layout/0`, `false` otherwise."
@spec layout?(any) :: boolean
def layout?(x) do
:logi_layout.is_layout x
end
@doc "Gets the module of `layout`."
@spec get_module(layout) :: callback_module
def get_module(layout) do
:logi_layout.get_module layout
end
@doc "Gets the extra data of `layout`."
@spec get_extra_data(layout) :: extra_data
def get_extra_data(layout) do
:logi_layout.get_extra_data layout
end
@doc "Returns an `formatted_data()` which represents `data` formatted by `layout` in accordance with `format` and `context`."
@spec format(Logi.Context.context, :io.format, data, layout) :: formatted_data
def format(context, format, data, layout) do
:logi_layout.format context, format, data, layout
end
end
|
lib/logi/layout.ex
| 0.894397 | 0.76934 |
layout.ex
|
starcoder
|
defmodule Refraction.Neuron do
alias Refraction.Neuron
alias Refraction.Neuron.{Activation, Connection}
@type t :: %__MODULE__{
pid: pid(),
input: integer,
output: integer | float,
incoming: [integer],
outgoing: [integer | float],
bias?: boolean,
delta: float
}
defstruct pid: nil,
input: 0,
output: 0,
incoming: [],
outgoing: [],
bias?: false,
delta: 0
@spec start_link(map()) :: {:ok, pid()}
def start_link(attributes \\ %{}) do
{:ok, pid} = Agent.start_link(fn -> %Neuron{} end)
update(pid, Map.merge(attributes, %{pid: pid}))
{:ok, pid}
end
@spec get(pid()) :: Neuron.t()
def get(pid), do: Agent.get(pid, fn neuron -> neuron end)
@spec learning_rate() :: float
def learning_rate, do: 0.618
@spec update(pid(), map()) :: :ok
def update(pid, new_attributes) do
Agent.update(pid, fn current_attributes ->
Map.merge(current_attributes, new_attributes)
end)
end
@spec connect(pid(), pid()) :: :ok
def connect(source_neuron_pid, target_neuron_pid) do
{:ok, connection_pid} =
Connection.connection_for(source_neuron_pid, target_neuron_pid)
update(source_neuron_pid, %{
outgoing: get(source_neuron_pid).outgoing ++ [connection_pid]
})
update(target_neuron_pid, %{
incoming: get(target_neuron_pid).incoming ++ [connection_pid]
})
end
@spec activate(pid(), atom, integer | nil) :: :ok
def activate(neuron_pid, activation, value \\ nil) do
neuron = get(neuron_pid)
attributes =
if neuron.bias? do
%{output: 1}
else
input = value || Enum.reduce(neuron.incoming, 0, calculate_input())
%{input: input, output: Activation.calculate_output(activation, input)}
end
update(neuron_pid, attributes)
end
defp calculate_input do
fn connection_pid, sum ->
connection = Connection.get(connection_pid)
sum + get(connection.source_pid).output * connection.weight
end
end
end
|
lib/refraction/neuron.ex
| 0.825027 | 0.424173 |
neuron.ex
|
starcoder
|
defmodule RGBMatrix.Animation.HueWave do
@moduledoc """
Creates a wave of shifting hue that moves across the matrix.
"""
use RGBMatrix.Animation
alias Chameleon.HSV
alias KeyboardLayout.LED
import RGBMatrix.Utils, only: [mod: 2]
field(:speed, :integer,
default: 4,
min: 0,
max: 32,
doc: [
name: "Speed",
description: """
Controls the speed at which the wave moves across the matrix.
"""
]
)
field(:width, :integer,
default: 20,
min: 10,
max: 100,
step: 10,
doc: [
name: "Width",
description: """
The rate of change of the wave, higher values means it's more spread out.
"""
]
)
field(:direction, :option,
default: :right,
options: ~w(right left up down)a,
doc: [
name: "Direction",
description: """
The direction the wave travels across the matrix.
"""
]
)
defmodule State do
@moduledoc false
defstruct [:tick, :leds, :steps]
end
@delay_ms 17
@impl true
def new(leds, config) do
steps = 360 / config.width
%State{tick: 0, leds: leds, steps: steps}
end
@impl true
def render(state, config) do
%{tick: tick, leds: leds, steps: _steps} = state
%{speed: speed, direction: direction} = config
steps = 360 / config.width
time = div(tick * speed, 5)
colors = render_colors(leds, steps, time, direction)
{@delay_ms, colors, %{state | tick: tick + 1}}
end
defp render_colors(leds, steps, time, :right) do
for %LED{id: id, x: x} <- leds do
hue = mod(trunc(x * steps) - time, 360)
{id, HSV.new(hue, 100, 100)}
end
end
defp render_colors(leds, steps, time, :left) do
for %LED{id: id, x: x} <- leds do
hue = mod(trunc(x * steps) + time, 360)
{id, HSV.new(hue, 100, 100)}
end
end
defp render_colors(leds, steps, time, :up) do
for %LED{id: id, y: y} <- leds do
hue = mod(trunc(y * steps) + time, 360)
{id, HSV.new(hue, 100, 100)}
end
end
defp render_colors(leds, steps, time, :down) do
for %LED{id: id, y: y} <- leds do
hue = mod(trunc(y * steps) - time, 360)
{id, HSV.new(hue, 100, 100)}
end
end
end
|
lib/rgb_matrix/animation/hue_wave.ex
| 0.922961 | 0.597667 |
hue_wave.ex
|
starcoder
|
defmodule Strsim do
@moduledoc """
Documentation for `Strsim`.
"""
@doc """
Like optimal string alignment, but substrings can be edited an unlimited number of times, and the triangle inequality holds.
iex> Strsim.damerau_levenshtein("ab", "bca")
{:ok, 2}
"""
defdelegate damerau_levenshtein(a, b), to: Strsim.Nif
@doc """
Like optimal string alignment, but substrings can be edited an unlimited number of times, and the triangle inequality holds.
iex> Strsim.damerau_levenshtein!("ab", "bca")
2
"""
def damerau_levenshtein!(a, b) do
case damerau_levenshtein(a, b) do
{:ok, value} -> value
{:error, error} -> raise error
end
end
@doc """
Calculates the number of positions in the two sequences where the elements differ. Returns an error if the sequences have different lengths.
iex> Strsim.generic_hamming([1, 2], [1, 3])
{:ok, 1}
iex> Strsim.generic_hamming([1, 2], [1, 3, 4])
{:error, :different_length_args}
"""
defdelegate generic_hamming(a, b), to: Strsim.Nif
@doc """
Calculates the number of positions in the two sequences where the elements differ. Returns an error if the sequences have different lengths.
iex> Strsim.generic_hamming!([1, 2], [1, 3])
1
iex> Strsim.generic_hamming!([1, 2], [1, 3, 4])
** (Strsim.DifferentLengthArgsError) arguments are different length
"""
def generic_hamming!(a, b) do
case generic_hamming(a, b) do
{:ok, value} -> value
{:error, :different_length_args} -> raise(Strsim.DifferentLengthArgsError)
end
end
@doc """
Calculates the Jaro similarity between two sequences. The returned value is between 0.0 and 1.0 (higher value means more similar).
iex> Strsim.generic_jaro([1, 2], [1, 3, 4])
{:ok, 0.611111111111111}
"""
defdelegate generic_jaro(a, b), to: Strsim.Nif
@doc """
Calculates the Jaro similarity between two sequences. The returned value is between 0.0 and 1.0 (higher value means more similar).
iex> Strsim.generic_jaro!([1, 2], [1, 3, 4])
0.611111111111111
"""
def generic_jaro!(a, b) do
case generic_jaro(a, b) do
{:ok, value} -> value
{:error, error} -> raise error
end
end
@doc """
Like Jaro but gives a boost to sequences that have a common prefix.
iex> Strsim.generic_jaro_winkler([1, 2], [1, 3, 4])
{:ok, 0.6499999999999999}
"""
defdelegate generic_jaro_winkler(a, b), to: Strsim.Nif
@doc """
Like Jaro but gives a boost to sequences that have a common prefix.
iex> Strsim.generic_jaro_winkler!([1, 2], [1, 3, 4])
0.6499999999999999
"""
def generic_jaro_winkler!(a, b) do
case generic_jaro_winkler(a, b) do
{:ok, value} -> value
{:error, error} -> raise error
end
end
@doc """
Calculates the minimum number of insertions, deletions, and substitutions required to change one sequence into the other.
iex> Strsim.generic_levenshtein([1, 2, 3], [1, 2, 3, 4, 5, 6])
{:ok, 3}
"""
defdelegate generic_levenshtein(a, b), to: Strsim.Nif
@doc """
Calculates the minimum number of insertions, deletions, and substitutions required to change one sequence into the other.
iex> Strsim.generic_levenshtein!([1, 2, 3], [1, 2, 3, 4, 5, 6])
3
"""
def generic_levenshtein!(a, b) do
case generic_levenshtein(a, b) do
{:ok, value} -> value
{:error, error} -> raise error
end
end
@doc """
Calculates the number of positions in the two strings where the characters differ. Returns an error if the strings have different lengths.
iex> Strsim.hamming("hamming", "hammers")
{:ok, 3}
iex> Strsim.hamming("hamming", "ham")
{:error, :different_length_args}
"""
defdelegate hamming(a, b), to: Strsim.Nif
@doc """
Calculates the number of positions in the two strings where the characters differ. Returns an error if the strings have different lengths.
iex> Strsim.hamming!("hamming", "hammers")
3
iex> Strsim.hamming!("hamming", "ham")
** (Strsim.DifferentLengthArgsError) arguments are different length
"""
def hamming!(a, b) do
case hamming(a, b) do
{:ok, value} -> value
{:error, :different_length_args} -> raise(Strsim.DifferentLengthArgsError)
end
end
@doc """
Calculates the Jaro similarity between two strings. The returned value is between 0.0 and 1.0 (higher value means more similar).
iex> Strsim.jaro("<NAME>", "<NAME>")
{:ok, 0.39188596491228067}
"""
defdelegate jaro(a, b), to: Strsim.Nif
@doc """
Calculates the Jaro similarity between two strings. The returned value is between 0.0 and 1.0 (higher value means more similar).
iex> Strsim.jaro!("<NAME>", "<NAME>")
0.39188596491228067
"""
def jaro!(a, b) do
case jaro(a, b) do
{:ok, value} -> value
{:error, error} -> raise error
end
end
@doc """
Like Jaro but gives a boost to strings that have a common prefix.
iex> Strsim.jaro_winkler("cheeseburger", "cheese fries")
{:ok, 0.9111111111111111}
"""
defdelegate jaro_winkler(a, b), to: Strsim.Nif
@doc """
Like Jaro but gives a boost to strings that have a common prefix.
iex> Strsim.jaro_winkler!("cheeseburger", "cheese fries")
0.9111111111111111
"""
def jaro_winkler!(a, b) do
case jaro_winkler(a, b) do
{:ok, value} -> value
{:error, error} -> raise error
end
end
@doc """
Calculates the minimum number of insertions, deletions, and substitutions required to change one string into the other.
iex> Strsim.levenshtein("kitten", "sitting")
{:ok, 3}
"""
defdelegate levenshtein(a, b), to: Strsim.Nif
@doc """
Calculates the minimum number of insertions, deletions, and substitutions required to change one string into the other.
iex> Strsim.levenshtein!("kitten", "sitting")
3
"""
def levenshtein!(a, b) do
case levenshtein(a, b) do
{:ok, value} -> value
{:error, error} -> raise error
end
end
@doc """
Calculates a normalized score of the Damerau–Levenshtein algorithm between 0.0 and 1.0 (inclusive), where 1.0 means the strings are the same.
iex> Strsim.normalized_damerau_levenshtein("levenshtein", "löwenbräu")
{:ok, 0.2727272727272727}
"""
defdelegate normalized_damerau_levenshtein(a, b), to: Strsim.Nif
@doc """
Calculates a normalized score of the Damerau–Levenshtein algorithm between 0.0 and 1.0 (inclusive), where 1.0 means the strings are the same.
iex> Strsim.normalized_damerau_levenshtein!("levenshtein", "löwenbräu")
0.2727272727272727
"""
def normalized_damerau_levenshtein!(a, b) do
case normalized_damerau_levenshtein(a, b) do
{:ok, value} -> value
{:error, error} -> raise error
end
end
@doc """
Calculates a normalized score of the Levenshtein algorithm between 0.0 and 1.0 (inclusive), where 1.0 means the strings are the same.
iex> Strsim.normalized_levenshtein("kitten", "sitting")
{:ok, 0.5714285714285714}
"""
defdelegate normalized_levenshtein(a, b), to: Strsim.Nif
@doc """
Calculates a normalized score of the Levenshtein algorithm between 0.0 and 1.0 (inclusive), where 1.0 means the strings are the same.
iex> Strsim.normalized_levenshtein!("kitten", "sitting")
0.5714285714285714
"""
def normalized_levenshtein!(a, b) do
case normalized_levenshtein(a, b) do
{:ok, value} -> value
{:error, error} -> raise error
end
end
@doc """
Like Levenshtein but allows for adjacent transpositions. Each substring can only be edited once.
iex> Strsim.osa_distance("ab", "bca")
{:ok, 3}
"""
defdelegate osa_distance(a, b), to: Strsim.Nif
@doc """
Like Levenshtein but allows for adjacent transpositions. Each substring can only be edited once.
iex> Strsim.osa_distance!("ab", "bca")
3
"""
def osa_distance!(a, b) do
case osa_distance(a, b) do
{:ok, value} -> value
{:error, error} -> raise error
end
end
@doc """
Calculates a Sørensen-Dice similarity distance using bigrams.
iex> Strsim.sorensen_dice("ferris", "feris")
{:ok, 0.8888888888888888}
"""
defdelegate sorensen_dice(a, b), to: Strsim.Nif
@doc """
Calculates a Sørensen-Dice similarity distance using bigrams.
iex> Strsim.sorensen_dice!("ferris", "feris")
0.8888888888888888
"""
def sorensen_dice!(a, b) do
case sorensen_dice(a, b) do
{:ok, value} -> value
{:error, error} -> raise error
end
end
end
defmodule Strsim.DifferentLengthArgsError do
defexception message: "arguments are different length"
end
|
lib/strsim.ex
| 0.911441 | 0.625724 |
strsim.ex
|
starcoder
|
defmodule Atomex.Feed do
@moduledoc """
Represent an Atom feed. Embed many `Atomex.Entry`
"""
@type t :: list()
import XmlBuilder
alias Atomex.Types.{Person, Link, Text, Category}
@doc """
Create a new feed
"""
@spec new(binary(), DateTime.t(), binary(), binary()) :: Atomex.Feed.t()
def new(id, last_update_datetime, title, title_type \\ "text") do
[
{:id, nil, id},
Text.new(:title, title, title_type),
{:updated, nil, DateTime.to_iso8601(last_update_datetime)}
]
end
@doc """
Must be called before build_document, once the feed is fully prepared
"""
def build(feed, attributes \\ %{}) do
attributes = Map.merge(%{xmlns: "http://www.w3.org/2005/Atom"}, attributes)
element(:feed, attributes, feed)
end
@doc """
Add a custom field to the feed
## Parameters
- feed: The feed to which you want to add a field
- tag: String or atom with the name of the tag
- attributes: A map of attributes
- content: String, or list of xml_elements as created
by `XmlBuilder.element/3`
"""
def add_field(feed, tag, attributes, content) do
[element(tag, attributes, content) | feed]
end
@doc """
Add a custom field to the feed
## Parameters
- feed: The feed to which you want to add a field
- xml_element: An xml element as returned by `XmlBuilder.element/3`
"""
def add_field(feed, xml_element) do
[xml_element | feed]
end
@doc """
Add an author to the feed. See `Atomex.Types.Person` for accepted attributes
"""
@spec author(Atomex.Feed.t(), binary(), list()) :: Atomex.Feed.t()
def author(feed, name, attributes \\ []),
do: add_field(feed, Person.new(:author, name, attributes))
@doc """
Add a link to the feed. See `Atomex.Types.Link` for accepted attributes
"""
@spec link(Atomex.Feed.t(), binary(), list()) :: Atomex.Feed.t()
def link(feed, href, attributes \\ []),
do: add_field(feed, Link.new(href, attributes))
@doc """
Add given entries to the feed
"""
@spec entries(Atomex.Feed.t(), list(Atomex.Entry.t())) :: Atomex.Feed.t()
def entries(feed, entries),
do: feed ++ entries
# ---- Optional fields ----
@doc """
Names one contributor to the feed.
A feed may have multiple contributor elements.
See `Atomex.Types.Person` for accepted attributes
"""
def contributor(feed, name, attributes \\ []),
do: add_field(feed, Person.new(:contributor, name, attributes))
@doc """
Conveys information about rights, e.g. copyrights, held in and over the feed.
See `Atomex.Types.Text` for accepted types
"""
def rights(feed, content, type \\ "text"),
do: add_field(feed, Text.new(:rights, content, type))
@doc """
Specifies a category that the feed belongs to.
A feed may have multiple category elements.
See `Atomex.Types.Category` for accepted attributes
"""
def category(feed, term, attributes \\ []),
do: add_field(feed, Category.new(term, attributes))
@doc """
Identify feed generator. Default to Atomex with current version.
## Parameters
- attributes:
* uri: Generator's URI
* version: Generator's version
"""
def generator(feed),
do: add_field(feed, :generator, %{version: Atomex.version()}, "Atomex")
def generator(feed, name, attributes \\ []),
do: add_field(feed, :generator, attributes, name)
@doc """
Identifies a small image which provides iconic visual identification for
the feed. Icons should be square.
"""
def icon(feed, uri), do: add_field(feed, :icon, nil, uri)
@doc """
Identifies a larger image which provides visual identification for the feed.
Images should be twice as wide as they are tall.
"""
def logo(feed, uri), do: add_field(feed, :logo, nil, uri)
@doc """
Contains a human-readable description or subtitle for the feed.
See `Atomex.Types.Text` for accepted types
"""
def subtitle(entry, content, type \\ "text"),
do: add_field(entry, Text.new(:subtitle, content, type))
end
|
lib/atomex/feed.ex
| 0.899048 | 0.401277 |
feed.ex
|
starcoder
|
defmodule Mailapi.SmtpHandler do
@behaviour :gen_smtp_server_session
require Logger
alias Mailapi.Database
defmodule State do
defstruct options: []
end
@type error_message :: {:error, String.t, State.t}
# SMTP error codes
@smtp_too_busy 421
@smtp_requested_action_okay 250
@smtp_mail_action_abort 552
@smtp_unrecognized_command 500
@doc """
Every time a mail arrives, a process is started is kicked started to handle it.
The init/4 function accepts the following args
* hostname - the SMTP server's hostname
* session_count - number of mails currently being handled
* client_ip_address - IP address of the client
* options - the `callbackoptions` passed to `:gen_smtp_server.start/2`
Return
* `{:ok, banner, state}` - to send `banner` to client and initializes session with `state`
* `{:stop, reason, message}` - to exit session with `reason` and send `message` to client
"""
@spec init(binary, non_neg_integer, tuple, list) :: {:ok, String.t, State.t} | {:stop, any, String.t}
def init(hostname, _session_count, _client_ip_address, options) do
banner = [hostname, " ESMTP mailapi server"]
state = %State{options: options}
{:ok, banner, state}
end
@doc """
Handshake with the client
* Return `{:ok, max_message_size, state}` if we handle the hostname
```
# max_message_size should be an integer
# For 10kb max size, the return value would look like this
{:ok, 1024 * 10, state}
```
* Return `{:error, error_message, state}` if we don't handle mail for the hostname
```
# error_message must be prefixed with standard SMTP error code
# looks like this
554 invalid hostname
554 Dear human from Sector-8614 we don't handle mail for this domain name
```
"""
@spec handle_HELO(binary, State.t) :: {:ok, pos_integer, State.t} | {:ok, State.t} | error_message
def handle_HELO(hostname, state) do
:io.format("#{@smtp_requested_action_okay} HELO from #{hostname}~n")
{:ok, 655360, state} # we'll say 640kb of max size
end
@spec handle_EHLO(binary, list, State.t) :: {:ok, list, State.t} | error_message
def handle_EHLO(_hostname, extensions, state) do
{:ok, extensions, state}
end
@doc "Accept or reject mail to incoming addresses here"
@spec handle_MAIL(binary, State.t) :: {:ok, State.t} | error_message
def handle_MAIL(_sender, state) do
{:ok, state}
end
@doc "Accept receipt of mail to an email address or reject it"
@spec handle_RCPT(binary(), State.t) :: {:ok, State.t} | {:error, String.t, State.t}
def handle_RCPT(_to, state) do
{:ok, state}
end
@doc """
Verify incoming address.
This I heard was a security issue since people were able to check which accounts existed on the system. We'll just say yes to all incoming addresses.
"""
@spec handle_VRFY(binary, State.t) :: {:ok, String.t, State.t} | {:error, String.t, State.t}
def handle_VRFY(user, state) do
{:ok, "#{user}@#{:smtp_util.guess_FQDN()}", state}
end
@doc "Handle mail data. This includes subject, body, etc"
@spec handle_DATA(binary, [binary,...], binary, State.t) :: {:ok, String.t, State.t} | {:error, String.t, State.t}
def handle_DATA(_from, _to, "", state) do
{:error, "#{@smtp_mail_action_abort} Message too small", state}
end
def create_unique_id do
ref_list = :erlang.now()
|> :erlang.term_to_binary()
|> :erlang.md5()
|> :erlang.bitstring_to_list()
:lists.flatten Enum.map(ref_list, fn(n)-> :io_lib.format("~2.16.0b", [n]) end)
end
def handle_DATA(from, to, data, state) do
unique_id = create_unique_id()
email = %{
from: from,
to: to,
data: data,
unique_id: unique_id
}
Logger.debug("#{inspect email}")
for sender <- to do
Database.add(sender, email)
end
{:ok, unique_id, state}
end
@doc "Reset internal state"
@spec handle_RSET(State.t) :: State.t
def handle_RSET(state) do
state
end
@doc "No other SMTP verbs are recognized"
@spec handle_other(binary, binary, State.t) :: {String.t, State.t}
def handle_other(verb, _args, state) do
{["#{@smtp_unrecognized_command} Error: command not recognized : '", verb, "'"], state}
end
@spec terminate(any, State.t) :: {:ok, any, State.t}
def terminate(reason, state) do
{:ok, reason, state}
end
end
|
lib/mailapi/smtp_handler.ex
| 0.539226 | 0.623635 |
smtp_handler.ex
|
starcoder
|
defmodule Towwwer.Tools.WPScan do
@moduledoc """
Contains functions used to interact with the separately installed
WPScan tool.
"""
@doc """
Run WPScan against the given `url` with default settings.
TODO: Check if System.cmd actually runs properly.
"""
@spec run(map(), String.t()) :: {:ok, any()} | {:error, String.t()}
def run(site, url) when is_map(site) and is_binary(url) do
construct_wpscan_command(site, url)
end
def run(_site, _url), do: {:error, "URL not a binary or Site not a map"}
# Helper to construct the WPScan command
@spec construct_wpscan_command(map(), String.t()) :: tuple()
defp construct_wpscan_command(site, url) do
# See which params to pass to WPScan
params =
cond do
# Both WP Content and WP Plugins directories are set
both_directory_params_set?(site) ->
base_params() ++ url_params(url) ++ wp_content_params(site) ++ wp_plugins_params(site)
# WP Content directory is set
site.wp_content_dir != nil && site.wp_content_dir != "" ->
base_params() ++ url_params(url) ++ wp_content_params(site)
# WP Plugins directory is set
site.wp_plugins_dir != nil && site.wp_plugins_dir != "" ->
base_params() ++ url_params(url) ++ wp_plugins_params(site)
# No directories are set
true ->
base_params() ++ url_params(url)
end
# Run command with correct params
{cmd, _} = System.cmd("wpscan", params, parallelism: true)
{:ok, cmd}
end
# Check if both directory params are set
defp both_directory_params_set?(site) do
site.wp_content_dir != nil && site.wp_content_dir != "" && site.wp_plugins_dir != nil &&
site.wp_plugins_dir != ""
end
# Returns a list of common base parameters used by all wpscan commands
defp base_params do
["--no-banner", "--force", "--no-update", "--format", "json"]
end
# Returns a list of url parameters
defp url_params(url) do
["--url", url]
end
# Returns a list of wp_content parameters
defp wp_content_params(site) do
["--wp-content-dir", site.wp_content_dir]
end
# Returns a list of wp_plugins parameters
defp wp_plugins_params(site) do
["--wp-plugins-dir", site.wp_plugins_dir]
end
end
|
lib/towwwer/tools/wpscan.ex
| 0.600188 | 0.4165 |
wpscan.ex
|
starcoder
|
require Logger
defmodule Notifications.Data.Migrator do
@moduledoc """
This applies any migrations provided by Data.Migrations.all that have not been applied
in order, with transactional context. While the changes are not written to be idempotent,
the transaction around each migration ensures that we can't be left in a partially-applied
state for a given migration.
This module tracks which migrations have been applied via the migrations table,
which is itself created as the first migration.
When a migration is applied successfully, the migrations table record for that migration
is inserted as part of the same transaction used for the migration.
Error handling is 100% "let it crash" - since this is not user facing and the
types of failures we might encounter (db not available, someoone has a table locked, etc) are
transient by nature, we're relying on restarts by the service supervisor (hab, not erlang) after
the notifications service crashes.
Error logging will capture failure reasons as 'badmatch' errors
"""
alias Notifications.Data.Migrator.{DB, Migrations}
def run() do
{:ok, conn} = DB.connect()
current = DB.current_migration_level(conn)
target = length(Migrations.all)
case next_migration(current, target) do
{:error, :notifications_service_upgrade_required} = error ->
Logger.error("Notifications service is out of sync. Data is migrated to #{current} but expected max of #{target}) ")
DB.disconnect(conn)
error
next ->
Logger.info("Current migration level is #{current}, next is #{next}, targeting #{target}")
migrate(conn, next)
DB.disconnect(conn)
:ok
end
end
def migrate(_conn, {:error, _reason} = error), do: error
def migrate(_conn, :done), do: :ok
def migrate(conn, migration_number) do
migrations = Migrations.all()
target = length(migrations)
{detail, _} = List.pop_at(migrations, migration_number - 1)
Logger.info("Starting migration #{migration_number}: #{detail.description}")
# If there is only one query then do not run it in a transaction
# This was added because an postgres ALTER TYPE can not be ran in a transaction.
case length(detail.queries) do
1 ->
[query] = detail.queries
DB.exec_migration_sql(conn, query)
DB.add_migration_record(conn, migration_number, detail.description)
_ ->
DB.begin_tx(conn)
for query <- detail.queries, do: [DB.exec_migration_sql(conn, query)]
DB.add_migration_record(conn, migration_number, detail.description)
DB.commit_tx(conn)
end
Logger.info("Finished migration #{migration_number}")
migrate(conn, next_migration(migration_number, target))
end
def next_migration(last_applied, target) when last_applied > target, do: {:error, :notifications_service_upgrade_required}
def next_migration(last_applied, target) when last_applied == target, do: :done
def next_migration(last_applied, _target), do: last_applied + 1
end
defmodule Notifications.Data.Migrator.DB do
@moduledoc "Database interactions required by DataMigrator."
def connect() do
cfg = Notifications.Config.sqerl_settings()
options = [database: Keyword.get(cfg, :db_name), port: Keyword.get(cfg, :db_port)] ++ Keyword.get(cfg, :db_options)
:epgsql.connect(Keyword.get(cfg, :db_host), Keyword.get(cfg, :db_user),
Keyword.get(cfg, :db_pass), options)
end
def disconnect(conn) do
:epgsql.close(conn)
end
def current_migration_level(conn) do
case :epgsql.squery(conn, "SELECT max(num) as level from migrations") do
# relation does not exist
{:error, {:error, :error, "42P01", _, _}} ->
0
# exists, but has no migrations
{:ok, _, [{:null}]} ->
# The table exists but has no records - should not happen
0
{:ok, _, [{level}]} ->
{real_level, _} = Integer.parse(level)
real_level
end
end
def add_migration_record(conn, level, description) do
sql = "INSERT INTO migrations(num, descr, at) VALUES ($1, $2, CURRENT_TIMESTAMP)"
{:ok, _} = :epgsql.equery(conn, sql, [level, description])
:ok
end
def begin_tx(conn) do
{:ok, [], []} = :epgsql.squery(conn, "BEGIN ISOLATION LEVEL SERIALIZABLE")
:ok
end
def commit_tx(conn) do
{:ok, [], []} = :epgsql.squery(conn, "COMMIT")
:ok
end
def exec_migration_sql(conn, query) do
{:ok, _, _} = :epgsql.equery(conn, query, [])
:ok
end
end
|
components/notifications-service/server/lib/data/migrator.ex
| 0.785473 | 0.416856 |
migrator.ex
|
starcoder
|
defmodule Adap.Joiner do
@doc """
Make a stream wich reduces input elements joining them according to specified key pattern.
The principle is to keep a fixed length queue of elements waiting to
receive joined elements.
This is for stream of elements where order is unknown, but elements to join
are supposed to be close.
- each element of `enum` must be like `{:sometype,elem}`
- you want to merge elements of type `from_type` into element of type `to_type`
- `opts[:fk_from]` must contain an anonymous function taking an element
"""
def join(enum, from_type, to_type, opts \\ []) do
opts = set_default_opts(opts,from_type,to_type)
enum |> Stream.concat([:last]) |> Stream.transform({Map.new(), :queue.new(), 0}, fn
:last, {tolink, queue, _} ->
{elems, tolink} = Enum.reduce(:queue.to_list(queue), {[], tolink}, fn e, {elems, tolink} ->
{e, tolink} = merge(e, tolink, opts)
{[{to_type, e} | elems], tolink}
end)
IO.puts "end join, #{Enum.count(tolink)} elements failed to join and are ignored"
{elems, nil}
{type, obj_from}, {tolink, queue, count} when type == from_type ->
if (fk = opts.fk_from.(obj_from)) do
tolink = Map.update(tolink, fk, [obj_from], &([obj_from | &1]))
{if(opts.keep, do: [{from_type, obj_from}], else: []), {tolink, queue,count}}
else
{[{from_type, obj_from}],{tolink, queue, count}}
end
{type, obj_to}, {tolink, queue, count} when type == to_type ->
{queue, count} = {:queue.in(obj_to, queue), count + 1}
if count > opts.queue_len do
{{{:value, obj_to_merge}, queue}, count} = {:queue.out(queue), count - 1}
{obj, tolink} = merge(obj_to_merge, tolink, opts)
{[{to_type, obj}],{tolink, queue, count}}
else
{[], {tolink, queue, count}}
end
{type, obj}, acc -> {[{type, obj}], acc}
end)
end
defp set_default_opts(opts, from_type, to_type) do
from_types = :"#{from_type}s"
%{fk_from: opts[:fk_from] || &(&1[to_type]),
fk_to: opts[:fk_to] || &(&1.id),
keep: opts[:keep] || false,
reducer: opts[:reducer] || fn from_obj, to_obj ->
Map.update(to_obj, from_types, [from_obj], &( [from_obj|&1]))
end,
queue_len: opts[:queue_len] || 10}
end
defp merge(obj, tolink, opts) do
{objs_tolink, tolink} = Map.pop(tolink, opts.fk_to.(obj), [])
{Enum.reduce(objs_tolink, obj, opts.reducer), tolink}
end
end
|
lib/joiner.ex
| 0.685529 | 0.544438 |
joiner.ex
|
starcoder
|
defmodule Day10 do
def part1(input, chip_list \\ [17, 61]) do
solve(input, chip_list)
|> Map.fetch!(:result)
|> elem(1)
end
def part2(input) do
solve(input, nil)
|> result_part2
end
defp solve(input, chip_list) do
instructions = Parser.parse(input)
state = init_state(instructions)
|> Map.put(:chip_list, chip_list)
fully_chipped = Map.to_list(state)
|> Enum.filter(fn pair ->
case pair do
{{:bot, _}, [_low, _high]} -> true
_ -> false
end
end)
|> Enum.map(&elem(&1, 0))
distribute_chips(state, fully_chipped)
end
defp result_part2(state) do
%{{:output, 0} => [output0],
{:output, 1} => [output1],
{:output, 2} => [output2]} = state
output0 * output1 * output2
end
defp init_state(instructions) do
Enum.reduce(instructions, %{}, fn instruction, state ->
case instruction do
{:value, bot, value} ->
chips = Map.get(state, bot, [])
chips = Enum.sort([value | chips])
Map.put(state, bot, chips)
{:give, from, low_dest, high_dest} ->
Map.put(state, {:give, from}, {low_dest, high_dest})
end
end)
end
defp distribute_chips(state, []), do: state
defp distribute_chips(state, [{:bot, _} = bot | bots]) do
state = give_chips(state, bot)
distribute_chips(state, bots)
end
defp distribute_chips(state, [{:output, _} | bots]) do
distribute_chips(state, bots)
end
defp give_chips(state, from) do
{low_dest, high_dest} = Map.get(state, {:give, from})
low_high = Map.fetch!(state, from)
case low_high do
[low, high] ->
chip_list = Map.fetch!(state, :chip_list)
state = if (low_high === chip_list) do
Map.put(state, :result, from)
else
state
end
Map.put(state, from, [])
|> give_to(low_dest, low)
|> give_to(high_dest, high)
|> distribute_chips([low_dest, high_dest])
_ ->
state
end
end
defp give_to(state, destination, value) do
chips = Map.get(state, destination, [])
chips = Enum.sort([value | chips])
Map.put(state, destination, chips)
end
end
defmodule Parser do
import NimbleParsec
defp pack_value([value,bot]) do
{:value, bot, value}
end
defp pack_give([from, bot_high, bot_low]) do
{:give, from, bot_high, bot_low}
end
bot = ignore(string("bot "))
|> integer(min: 1)
|> unwrap_and_tag(:bot)
output = ignore(string("output "))
|> integer(min: 1)
|> unwrap_and_tag(:output)
destination = choice([bot, output])
give = bot
|> ignore(string(" gives low to "))
|> concat(destination)
|> ignore(string(" and high to "))
|> concat(destination)
|> reduce({:pack_give, []})
value = ignore(string("value "))
|> integer(min: 1)
|> ignore(string(" goes to "))
|> concat(bot)
|> reduce({:pack_value, []})
defparsec :command, choice([value, give]) |> eos
def parse(input) do
Enum.map(input, fn line ->
{:ok, [result], "", _, _, _} = command(line)
result
end)
end
end
|
day10/lib/day10.ex
| 0.537527 | 0.558809 |
day10.ex
|
starcoder
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.