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 Mix.Releases.Archiver.Archive do @moduledoc false defstruct [:name, :working_dir, :manifest] @type path :: String.t() @type t :: %__MODULE__{ name: String.t(), working_dir: path, manifest: %{path => path} } @doc """ Creates a new Archive with the given name and working directory. The working directory is the location where added files will be considered to be relative to. When adding entries to the archive, we strip the working directory from the source path via `Path.relative_to/2` to form the path in the resulting tarball. """ @spec new(name :: String.t(), path) :: t def new(name, working_dir) when is_binary(name) when is_binary(working_dir) do %__MODULE__{name: name, working_dir: working_dir, manifest: %{}} end @doc """ Adds a new entry to the archive """ @spec add(t, path) :: t def add(%__MODULE__{working_dir: work_dir, manifest: manifest} = archive, source_path) do entry_path = Path.relative_to(source_path, work_dir) manifest = Map.put(manifest, entry_path, source_path) %{archive | :manifest => manifest} end @doc """ Adds a new entry to the archive with the given entry path """ @spec add(t, path, path) :: t def add(%__MODULE__{manifest: manifest} = archive, source_path, entry_path) do %{archive | :manifest => Map.put(manifest, entry_path, source_path)} end @doc """ Extracts the archive at the given path, into the provided target directory, and returns an Archive struct populated with the manifest of the extracted tarball """ @spec extract(path, path) :: {:ok, t} | {:error, {:archiver, {:erl_tar, term}}} def extract(archive_path, output_dir) do with archive_path_cl = String.to_charlist(archive_path), output_dir_cl = String.to_charlist(output_dir), {:ok, manifest} <- :erl_tar.table(archive_path_cl, [:compressed]), manifest = Enum.map(manifest, &List.to_string/1), :ok <- :erl_tar.extract(archive_path_cl, [{:cwd, output_dir_cl}, :compressed]) do name = archive_path |> Path.basename(".tar.gz") archive = new(name, output_dir) archive = manifest |> Enum.reduce(archive, fn entry, acc -> add(acc, Path.join(output_dir, entry), entry) end) {:ok, archive} else {:error, err} -> {:error, {:archiver, {:erl_tar, err}}} end end @doc """ Writes a compressed tar to the given output directory, using the archive name as the filename. Returns the path of the written tarball wrapped in an ok tuple if successful """ @spec save(t, path) :: {:ok, path} | {:error, {:file.filename(), reason :: term}} def save(%__MODULE__{name: name} = archive, output_dir) when is_binary(output_dir) do do_save(archive, Path.join([output_dir, name <> ".tar.gz"])) end defp do_save(%__MODULE__{manifest: manifest}, out_path) do out_path_cl = String.to_charlist(out_path) case :erl_tar.create(out_path_cl, to_erl_tar_manifest(manifest), [:dereference, :compressed]) do :ok -> {:ok, out_path} {:error, _} = err -> err end end defp to_erl_tar_manifest(manifest) when is_map(manifest) do to_erl_tar_manifest(Map.to_list(manifest), []) end defp to_erl_tar_manifest([], acc), do: acc defp to_erl_tar_manifest([{entry, source} | manifest], acc) do to_erl_tar_manifest(manifest, [{String.to_charlist(entry), String.to_charlist(source)} | acc]) end end
lib/mix/lib/releases/archiver/archive.ex
0.758466
0.419321
archive.ex
starcoder
defmodule Absinthe.Phase.Document.Validation.ArgumentsOfCorrectType do @moduledoc false # Validates document to ensure that all arguments are of the correct type. alias Absinthe.{Blueprint, Phase, Phase.Document.Validation.Utils, Schema, Type} use Absinthe.Phase @doc """ Run this validation. """ @spec run(Blueprint.t(), Keyword.t()) :: Phase.result_t() def run(input, _options \\ []) do result = Blueprint.prewalk(input, &handle_node(&1, input.schema)) {:ok, result} end # Check arguments, objects, fields, and lists @spec handle_node(Blueprint.node_t(), Schema.t()) :: Blueprint.node_t() # handled by Phase.Document.Validation.KnownArgumentNames defp handle_node(%Blueprint.Input.Argument{schema_node: nil} = node, _schema) do {:halt, node} end # handled by Phase.Document.Validation.ProvidedNonNullArguments defp handle_node(%Blueprint.Input.Argument{input_value: %{normalized: nil}} = node, _schema) do {:halt, node} end defp handle_node(%Blueprint.Input.Argument{flags: %{invalid: _}} = node, schema) do descendant_errors = collect_child_errors(node.input_value, schema) message = error_message( node.name, Blueprint.Input.inspect(node.input_value), descendant_errors ) error = error(node, message) node = node |> put_error(error) {:halt, node} end defp handle_node(node, _) do node end defp collect_child_errors(%Blueprint.Input.List{} = node, schema) do node.items |> Enum.map(& &1.normalized) |> Enum.with_index() |> Enum.flat_map(fn {%{schema_node: nil} = child, _} -> collect_child_errors(child, schema) {%{flags: %{invalid: _}} = child, idx} -> child_type_name = child.schema_node |> Type.value_type(schema) |> Type.name(schema) child_inspected_value = Blueprint.Input.inspect(child) [ value_error_message(idx, child_type_name, child_inspected_value) | collect_child_errors(child, schema) ] {child, _} -> collect_child_errors(child, schema) end) end defp collect_child_errors(%Blueprint.Input.Object{} = node, schema) do node.fields |> Enum.flat_map(fn %{flags: %{invalid: _}, schema_node: nil} = child -> field_suggestions = case Type.unwrap(node.schema_node) do %Type.Scalar{} -> [] %Type.Enum{} -> [] nil -> [] _ -> suggested_field_names(node.schema_node, child.name) end [unknown_field_error_message(child.name, field_suggestions)] %{flags: %{invalid: _}} = child -> child_type_name = Type.value_type(child.schema_node, schema) |> Type.name(schema) child_errors = case child.schema_node do %Type.Scalar{} -> [] %Type.Enum{} -> [] _ -> collect_child_errors(child.input_value, schema) end child_inspected_value = Blueprint.Input.inspect(child.input_value) [ value_error_message(child.name, child_type_name, child_inspected_value) | child_errors ] child -> collect_child_errors(child.input_value.normalized, schema) end) end defp collect_child_errors(%Blueprint.Input.Value{normalized: norm}, schema) do collect_child_errors(norm, schema) end defp collect_child_errors(_node, _) do [] end defp suggested_field_names(schema_node, name) do schema_node.fields |> Map.values() |> Enum.map(& &1.name) |> Absinthe.Utils.Suggestion.sort_list(name) end # Generate the error for the node @spec error(Blueprint.node_t(), String.t()) :: Phase.Error.t() defp error(node, message) do %Phase.Error{ phase: __MODULE__, message: message, locations: [node.source_location] } end def error_message(arg_name, inspected_value, verbose_errors \\ []) def error_message(arg_name, inspected_value, []) do ~s(Argument "#{arg_name}" has invalid value #{inspected_value}.) end def error_message(arg_name, inspected_value, verbose_errors) do error_message(arg_name, inspected_value) <> "\n" <> Enum.join(verbose_errors, "\n") end def value_error_message(id, expected_type_name, inspected_value) when is_integer(id) do ~s(In element ##{id + 1}: ) <> expected_type_error_message(expected_type_name, inspected_value) end def value_error_message(id, expected_type_name, inspected_value) do ~s(In field "#{id}": ) <> expected_type_error_message(expected_type_name, inspected_value) end def unknown_field_error_message(field_name, suggestions \\ []) def unknown_field_error_message(field_name, []) do ~s(In field "#{field_name}": Unknown field.) end def unknown_field_error_message(field_name, suggestions) do ~s(In field "#{field_name}": Unknown field.) <> Utils.MessageSuggestions.suggest_message(suggestions) end defp expected_type_error_message(expected_type_name, inspected_value) do ~s(Expected type "#{expected_type_name}", found #{inspected_value}.) end end
lib/absinthe/phase/document/validation/arguments_of_correct_type.ex
0.835685
0.423875
arguments_of_correct_type.ex
starcoder
defmodule Scidata.FashionMNIST do @moduledoc """ Module for downloading the [FashionMNIST dataset](https://github.com/zalandoresearch/fashion-mnist#readme). """ require Scidata.Utils alias Scidata.Utils @base_url "http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/" @train_image_file "train-images-idx3-ubyte.gz" @train_label_file "train-labels-idx1-ubyte.gz" @test_image_file "t10k-images-idx3-ubyte.gz" @test_label_file "t10k-labels-idx1-ubyte.gz" @doc """ Downloads the FashionMNIST training dataset or fetches it locally. Returns a tuple of format: {{images_binary, images_type, images_shape}, {labels_binary, labels_type, labels_shape}} If you want to one-hot encode the labels, you can: labels_binary |> Nx.from_binary(labels_type) |> Nx.new_axis(-1) |> Nx.equal(Nx.tensor(Enum.to_list(0..9))) ## Examples iex> Scidata.FashionMNIST.download() {{<<105, 109, 97, 103, 101, 115, 45, 105, 100, 120, 51, 45, 117, 98, 121, 116, 101, 0, 236, 253, 7, 88, 84, 201, 215, 232, 11, 23, 152, 38, 57, 51, 166, 81, 71, 157, 209, 49, 135, 49, 141, 99, 206, 142, 57, 141, 89, 68, ...>>, {:u, 8}, {3739854681, 226418, 1634299437}}, {<<0, 3, 116, 114, 97, 105, 110, 45, 108, 97, 98, 101, 108, 115, 45, 105, 100, 120, 49, 45, 117, 98, 121, 116, 101, 0, 53, 221, 9, 130, 36, 73, 110, 100, 81, 219, 220, 150, 91, 214, 249, 251, 20, 141, 247, 53, 114, ...>>, {:u, 8}, {3739854681}}} """ def download() do {download_images(@train_image_file), download_labels(@train_label_file)} end @doc """ Downloads the FashionMNIST test dataset or fetches it locally. Accepts the same options as `download/1`. """ def download_test() do {download_images(@test_image_file), download_labels(@test_label_file)} end defp download_images(image_file) do data = Utils.get!(@base_url <> image_file).body <<_::32, n_images::32, n_rows::32, n_cols::32, images::binary>> = data {images, {:u, 8}, {n_images, 1, n_rows, n_cols}} end defp download_labels(label_file) do data = Utils.get!(@base_url <> label_file).body <<_::32, n_labels::32, labels::binary>> = data {labels, {:u, 8}, {n_labels}} end end
lib/scidata/fashionmnist.ex
0.639061
0.630856
fashionmnist.ex
starcoder
defmodule Model.Service do @moduledoc """ Service represents a set of dates on which trips run. """ use Recordable, id: nil, start_date: ~D[1970-01-01], end_date: ~D[9999-12-31], valid_days: [], description: nil, schedule_name: nil, schedule_type: nil, schedule_typicality: 0, rating_start_date: nil, rating_end_date: nil, rating_description: nil, added_dates: [], added_dates_notes: [], removed_dates: [], removed_dates_notes: [] @type id :: String.t() @type t :: %__MODULE__{ id: id, start_date: Date.t(), end_date: Date.t(), valid_days: [Timex.Types.weekday()], description: String.t(), schedule_name: String.t(), schedule_type: String.t(), schedule_typicality: 0..5, rating_start_date: Date.t() | nil, rating_end_date: Date.t() | nil, rating_description: String.t() | nil, added_dates: [Date.t()], added_dates_notes: [String.t()], removed_dates: [Date.t()], removed_dates_notes: [String.t()] } @doc """ Returns the earliest date which is valid for this service. """ def start_date(%__MODULE__{} = service) do # we don't need to take removed dates into account because they're # already not valid. [service.start_date | service.added_dates] |> Enum.min_by(&Date.to_erl/1) end @doc """ Returns the latest date which is valid for this service. """ def end_date(%__MODULE__{} = service) do # we don't need to take removed dates into account because they're # already not valid. [service.end_date | service.added_dates] |> Enum.max_by(&Date.to_erl/1) end @doc """ Returns true if this service is valid on or after the given date. iex> service = %Service{ ...> start_date: ~D[2018-03-01], ...> end_date: ~D[2018-03-30], ...> valid_days: [1, 2, 3, 4], ...> added_dates: [~D[2018-04-01]], ...> removed_dates: [~D[2018-03-15]] ...> } iex> valid_after?(service, ~D[2018-02-01]) true iex> valid_after?(service, ~D[2018-03-01]) true iex> valid_after?(service, ~D[2018-04-01]) true iex> valid_after?(service, ~D[2018-04-02]) false """ @spec valid_after?(t, Date.t()) :: boolean def valid_after?(%__MODULE__{end_date: end_date, added_dates: added_dates}, %Date{} = date) do Date.compare(end_date, date) != :lt or Enum.any?(added_dates, &(Date.compare(&1, date) != :lt)) end @doc """ Returns true if this service is valid on the given date. iex> service = %Service{ ...> start_date: ~D[2018-03-01], ...> end_date: ~D[2018-03-30], ...> valid_days: [1, 2, 3, 4], ...> added_dates: [~D[2018-04-01]], ...> removed_dates: [~D[2018-03-15]] ...> } iex> valid_for_date?(service, ~D[2018-03-01]) true iex> valid_for_date?(service, ~D[2018-03-29]) true iex> valid_for_date?(service, ~D[2018-04-01]) true iex> valid_for_date?(service, ~D[2018-02-28]) false iex> valid_for_date?(service, ~D[2018-03-15]) false iex> valid_for_date?(service, ~D[2018-04-02]) false """ @spec valid_for_date?(t, Date.t()) :: boolean def valid_for_date?( %__MODULE__{ start_date: start_date, end_date: end_date, valid_days: valid_days, added_dates: added_dates, removed_dates: removed_dates }, %Date{} = date ) do not dates_include?(date, removed_dates) && (dates_include?(date, added_dates) || (between_or_equal?(date, start_date, end_date) && valid_weekday?(date, valid_days))) end @spec valid_weekday?(Date.t(), [Timex.Types.weekday()]) :: boolean defp valid_weekday?(date, valid_days) do weekday = Timex.weekday(date) valid_days |> Enum.any?(&(&1 == weekday)) end @spec dates_include?(Date.t(), [Date.t()]) :: boolean defp dates_include?(date, date_enum) do date in date_enum end defp between_or_equal?(date, _, date), do: true defp between_or_equal?(date, date, _), do: true defp between_or_equal?(date, start_date, end_date) do Date.compare(date, start_date) != :lt and Date.compare(date, end_date) != :gt end end
apps/model/lib/model/service.ex
0.872619
0.439868
service.ex
starcoder
defmodule Kino.VegaLite do @moduledoc """ A widget wrapping [VegaLite](https://hexdocs.pm/vega_lite) graphic. This widget allow for rendering regular VegaLite graphic and then streaming new data points to update the graphic. ## Examples widget = Vl.new(width: 400, height: 400) |> Vl.mark(:line) |> Vl.encode_field(:x, "x", type: :quantitative) |> Vl.encode_field(:y, "y", type: :quantitative) |> Kino.VegaLite.new() |> tap(&Kino.render/1) for i <- 1..300 do point = %{x: i / 10, y: :math.sin(i / 10)} Kino.VegaLite.push(widget, point) Process.sleep(25) end """ @doc false use GenServer, restart: :temporary defstruct [:pid] @type t :: %__MODULE__{pid: pid()} @typedoc false @type state :: %{ parent_monitor_ref: reference(), vl: VegaLite.t(), window: non_neg_integer(), datasets: %{binary() => list()}, pids: list(pid()) } @doc """ Starts a widget process with the given VegaLite definition. """ @spec new(VegaLite.t()) :: t() def new(vl) when is_struct(vl, VegaLite) do parent = self() opts = [vl: vl, parent: parent] {:ok, pid} = DynamicSupervisor.start_child(Kino.WidgetSupervisor, {__MODULE__, opts}) %__MODULE__{pid: pid} end # TODO: remove in v0.3.0 @deprecated "Use Kino.VegaLite.new/1 instead" def start(vl), do: new(vl) @doc false def start_link(opts) do GenServer.start_link(__MODULE__, opts) end @doc """ Appends a single data point to the graphic dataset. ## Options * `:window` - the maximum number of data points to keep. This option is useful when you are appending new data points to the plot over a long period of time. * `dataset` - name of the targetted dataset from the VegaLite specification. Defaults to the default anonymous dataset. """ @spec push(t(), map(), keyword()) :: :ok def push(widget, data_point, opts \\ []) do dataset = opts[:dataset] window = opts[:window] data_point = Map.new(data_point) GenServer.cast(widget.pid, {:push, dataset, [data_point], window}) end @doc """ Appends a number of data points to the graphic dataset. See `push/3` for more details. """ @spec push_many(t(), list(map()), keyword()) :: :ok def push_many(widget, data_points, opts \\ []) when is_list(data_points) do dataset = opts[:dataset] window = opts[:window] data_points = Enum.map(data_points, &Map.new/1) GenServer.cast(widget.pid, {:push, dataset, data_points, window}) end @doc """ Removes all data points from the graphic dataset. ## Options * `dataset` - name of the targetted dataset from the VegaLite specification. Defaults to the default anonymous dataset. """ @spec clear(t(), keyword()) :: :ok def clear(widget, opts \\ []) do dataset = opts[:dataset] GenServer.cast(widget.pid, {:clear, dataset}) end @doc """ Registers a callback to run periodically in the widget process. The callback is run every `interval_ms` milliseconds and receives the accumulated value. The callback should return either of: * `{:cont, acc}` - the continue with the new accumulated value * `:halt` - to no longer schedule callback evaluation The callback is run for the first time immediately upon registration. """ @spec periodically(t(), pos_integer(), term(), (term() -> {:cont, term()} | :halt)) :: :ok def periodically(widget, interval_ms, acc, fun) do GenServer.cast(widget.pid, {:periodically, interval_ms, acc, fun}) end @impl true def init(opts) do vl = Keyword.fetch!(opts, :vl) parent = Keyword.fetch!(opts, :parent) parent_monitor_ref = Process.monitor(parent) {:ok, %{parent_monitor_ref: parent_monitor_ref, vl: vl, datasets: %{}, pids: []}} end @impl true def handle_cast({:push, dataset, data, window}, state) do for pid <- state.pids do send(pid, {:push, %{data: data, dataset: dataset, window: window}}) end state = update_in(state.datasets[dataset], fn current_data -> current_data = current_data || [] if window do Enum.take(current_data ++ data, -window) else current_data ++ data end end) {:noreply, state} end def handle_cast({:clear, dataset}, state) do for pid <- state.pids do send(pid, {:push, %{data: [], dataset: dataset, window: 0}}) end {_, state} = pop_in(state.datasets[dataset]) {:noreply, state} end def handle_cast({:periodically, interval_ms, acc, fun}, state) do periodically_iter(interval_ms, acc, fun) {:noreply, state} end @compile {:no_warn_undefined, {VegaLite, :to_spec, 1}} @impl true def handle_info({:connect, pid}, state) do Process.monitor(pid) send(pid, {:connect_reply, %{spec: VegaLite.to_spec(state.vl)}}) for {dataset, data} <- state.datasets do send(pid, {:push, %{data: data, dataset: dataset, window: nil}}) end {:noreply, %{state | pids: [pid | state.pids]}} end def handle_info({:periodically_iter, interval_ms, acc, fun}, state) do periodically_iter(interval_ms, acc, fun) {:noreply, state} end def handle_info({:DOWN, ref, :process, _object, _reason}, %{parent_monitor_ref: ref} = state) do {:stop, :shutdown, state} end def handle_info({:DOWN, _ref, :process, pid, _reason}, state) do {:noreply, %{state | pids: List.delete(state.pids, pid)}} end defp periodically_iter(interval_ms, acc, fun) do case fun.(acc) do {:cont, acc} -> Process.send_after(self(), {:periodically_iter, interval_ms, acc, fun}, interval_ms) :halt -> :ok end end end
lib/kino/vega_lite.ex
0.759493
0.613135
vega_lite.ex
starcoder
defmodule Commanded.Registration.LocalRegistry do @moduledoc """ Local process registration, restricted to a single node, using Elixir's [Registry](https://hexdocs.pm/elixir/Registry.html). """ @behaviour Commanded.Registration @doc """ Return an optional supervisor spec for the registry """ @spec child_spec() :: [:supervisor.child_spec()] @impl Commanded.Registration def child_spec do [ {Registry, keys: :unique, name: __MODULE__} ] end @doc """ Starts a supervisor. """ @spec supervisor_child_spec(module :: atom, arg :: any()) :: :supervisor.child_spec() @impl Commanded.Registration def supervisor_child_spec(module, arg) do default = %{ id: module, start: {module, :start_link, [arg]}, type: :supervisor } Supervisor.child_spec(default, []) end @doc """ Starts a uniquely named child process of a supervisor using the given module and args. Registers the pid with the given name. """ @spec start_child( name :: term(), supervisor :: module(), child_spec :: Commanded.Registration.start_child_arg() ) :: {:ok, pid} | {:error, term} @impl Commanded.Registration def start_child(name, supervisor, child_spec) do via_name = {:via, Registry, {__MODULE__, name}} child_spec = case child_spec do module when is_atom(module) -> {module, name: via_name} {module, args} when is_atom(module) and is_list(args) -> {module, Keyword.put(args, :name, via_name)} end case DynamicSupervisor.start_child(supervisor, child_spec) do {:error, {:already_started, pid}} -> {:ok, pid} reply -> reply end end @doc """ Starts a uniquely named `GenServer` process for the given module and args. Registers the pid with the given name. """ @spec start_link(name :: term(), module :: module(), args :: any()) :: {:ok, pid} | {:error, term} @impl Commanded.Registration def start_link(name, module, args) do via_name = {:via, Registry, {__MODULE__, name}} case GenServer.start_link(module, args, name: via_name) do {:error, {:already_started, pid}} -> {:ok, pid} reply -> reply end end @doc """ Get the pid of a registered name. Returns `:undefined` if the name is unregistered. """ @spec whereis_name(name :: term) :: pid | :undefined @impl Commanded.Registration def whereis_name(name), do: Registry.whereis_name({__MODULE__, name}) @doc """ Return a `:via` tuple to route a message to a process by its registered name """ @spec via_tuple(name :: term()) :: {:via, module(), name :: term()} @impl Commanded.Registration def via_tuple(name), do: {:via, Registry, {__MODULE__, name}} @doc false def handle_call(_request, _from, _state) do raise "attempted to call GenServer #{inspect(proc())} but no handle_call/3 clause was provided" end @doc false def handle_cast(_request, _state) do raise "attempted to cast GenServer #{inspect(proc())} but no handle_cast/2 clause was provided" end @doc false def handle_info(_msg, state) do {:noreply, state} end defp proc do case Process.info(self(), :registered_name) do {_, []} -> self() {_, name} -> name end end end
lib/commanded/registration/local_registry.ex
0.873795
0.418489
local_registry.ex
starcoder
defmodule Sqlitex.Server.StatementCache do @moduledoc """ Implements a least-recently used (LRU) cache for prepared SQLite statements. Caches a fixed number of prepared statements and purges the statements which were least-recently used when that limit is exceeded. """ defstruct db: false, size: 0, limit: 1, cached_stmts: %{}, lru: [] @doc """ Creates a new prepared statement cache. """ def new({:connection, _, _} = db, limit) when is_integer(limit) and limit > 0 do %__MODULE__{db: db, limit: limit} end @doc """ Given a statement cache and an SQL statement (string), returns a tuple containing the updated statement cache and a prepared SQL statement. If possible, reuses an existing prepared statement; if not, prepares the statement and adds it to the cache, possibly removing the least-recently used prepared statement if the designated cache size limit would be exceeded. Will return `{:error, reason}` if SQLite is unable to prepare the statement. """ def prepare(%__MODULE__{cached_stmts: cached_stmts} = cache, sql) when is_binary(sql) and byte_size(sql) > 0 do case Map.fetch(cached_stmts, sql) do {:ok, stmt} -> {update_cache_for_read(cache, sql), stmt} :error -> prepare_new_statement(cache, sql) end end defp prepare_new_statement(%__MODULE__{db: db} = cache, sql) do case Sqlitex.Statement.prepare(db, sql) do {:ok, prepared} -> cache = cache |> store_new_stmt(sql, prepared) |> purge_cache_if_full |> update_cache_for_read(sql) {cache, prepared} error -> error end end defp store_new_stmt(%__MODULE__{size: size, cached_stmts: cached_stmts} = cache, sql, prepared) do %{cache | size: size + 1, cached_stmts: Map.put(cached_stmts, sql, prepared)} end defp purge_cache_if_full(%__MODULE__{size: size, limit: limit, cached_stmts: cached_stmts, lru: [purge_victim | lru]} = cache) when size > limit do %{cache | size: size - 1, cached_stmts: Map.drop(cached_stmts, [purge_victim]), lru: lru} end defp purge_cache_if_full(cache), do: cache defp update_cache_for_read(%__MODULE__{lru: lru} = cache, sql) do lru = lru |> Enum.reject(&(&1 == sql)) |> Kernel.++([sql]) %{cache | lru: lru} end end
deps/sqlitex/lib/sqlitex/server/statement_cache.ex
0.770594
0.468487
statement_cache.ex
starcoder
defmodule PhoenixGuardian.ConnCase do @moduledoc """ This module defines the test case to be used by tests that require setting up a connection. Such tests rely on `Phoenix.ConnTest` and also imports other functionality to make it easier to build and query models. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with connections use Phoenix.ConnTest alias PhoenixGuardian.Repo import Ecto.Schema import Ecto.Query, only: [from: 2] import PhoenixGuardian.Router.Helpers # The default endpoint for testing @endpoint PhoenixGuardian.Endpoint # We need a way to get into the connection to login a user # We need to use the bypass_through to fire the plugs in the router # and get the session fetched. def guardian_login(%PhoenixGuardian.User{} = user), do: guardian_login(conn(), user, :token, []) def guardian_login(%PhoenixGuardian.User{} = user, token), do: guardian_login(conn(), user, token, []) def guardian_login(%PhoenixGuardian.User{} = user, token, opts), do: guardian_login(conn(), user, token, opts) def guardian_login(%Plug.Conn{} = conn, user), do: guardian_login(conn, user, :token, []) def guardian_login(%Plug.Conn{} = conn, user, token), do: guardian_login(conn, user, token, []) def guardian_login(%Plug.Conn{} = conn, user, token, opts) do conn |> bypass_through(PhoenixGuardian.Router, [:browser]) |> get("/") |> Guardian.Plug.sign_in(user, token, opts) |> send_resp(200, "Flush the session yo") |> recycle() end end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(PhoenixGuardian.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(PhoenixGuardian.Repo, {:shared, self()}) end {:ok, conn: Phoenix.ConnTest.conn()} end end
test/support/conn_case.ex
0.724286
0.428712
conn_case.ex
starcoder
defmodule DataBase.Schemas.Account do @moduledoc """ The main abstraction to a bank account per say. Provides a set of functions to interact with it, since its creation to queries about its data. Express information over the `accounts` database table. """ import Ecto.Query use Ecto.Schema alias DataBase.Schemas.AccountTransfer, as: Transfer alias DataBase.Schemas.AccountMovement, as: Movement alias DataBase.Repos.AmethystRepo, as: Repo alias Decimal, as: D @typedoc """ A `DataBase.Schemas.Account` struct. """ @type t :: %__MODULE__{} @typedoc """ A standard Ecto response to `DataBase.Schemas.Account` data insertion. """ @type response_t :: {:ok, t()} | {:error, any()} @typedoc """ A map containing a `:final_balance` key with a `t:Decimal.t/0` value. Or `nil`. It's the representation for querying this specific field in the database. """ @type final_balance_t :: %{final_balance: D.t()} | nil schema "accounts" do field :name, :string field :api_token, :string has_many :movements, Movement has_many :outgoing_transfers, Transfer, foreign_key: :sender_account_id has_many :incoming_transfers, Transfer, foreign_key: :recipient_account_id timestamps() end @doc """ Given `t:t/0`, generates a API token to it. """ @spec set_token(t) :: t() def set_token(%__MODULE__{} = account) do Map.merge(account, %{api_token: generate_api_token()}) end @doc """ Tries to insert a `t:t/0` struct into database. """ @spec create(t) :: response_t() def create(%__MODULE__{} = account), do: Repo.insert(account) @doc """ Checks if a given `t:t/0` has a given `t:Decimal.t/0` as amount available in its balance. """ @spec has_funds?(t, D.t) :: boolean() def has_funds?(%__MODULE__{} = account, %D{} = amount) do Enum.member?([:eq, :gt], D.cmp(balance(account), amount)) end @doc """ Returns the given `t:t/0` balance. """ @spec balance(t | final_balance_t) :: D.t() def balance(%__MODULE__{} = account) do account.id |> balance_query() |> Repo.one() |> balance() end def balance(nil), do: D.new(0) def balance(%{} = result), do: result.final_balance @doc """ Registers a outbound `t:DataBase.Schemas.AccountMovement.t/0` for a given `t:t/0` and `t:Decimal.t/0` as amount. """ @spec debit(t, D.t) :: Movement.response_t() def debit(%__MODULE__{} = account, %D{} = amount) do account.id |> Movement.build(amount, -1) |> Movement.move() end @doc """ Registers a inbound `t:DataBase.Schemas.AccountMovement.t/0` for a given `t:t/0` and `t:Decimal.t/0` as amount. """ @spec credit(t, D.t) :: Movement.response_t() def credit(%__MODULE__{} = account, %D{} = amount) do account.id |> Movement.build(amount, 1) |> Movement.move() end @doc """ A sum of all inbound `t:DataBase.Schemas.AccountMovement.t/0` `:amount` for a given `t:t/0` on a specific date. """ @spec inbounds_on(pos_integer, Date.t) :: D.t() def inbounds_on(id, %Date{} = date) when is_integer(id) do id |> inbounds_on_query(date) |> Repo.one() || D.new(0) end @doc """ A sum of all outbound `t:DataBase.Schemas.AccountMovement.t/0` `:amount` for a given `t:t/0` on a specific date. """ @spec outbounds_on(pos_integer, Date.t) :: D.t() def outbounds_on(id, %Date{} = date) when is_integer(id) do id |> outbounds_on_query(date) |> Repo.one() || D.new(0) end @doc """ Given the `:id` of `t:t/0` and a `t:Date.t/0`, it determines the `:initial_balance` of the first `t:DataBase.Schemas.AccountMovement.t/0` on this date. """ @spec early_balance(pos_integer, Date.t) :: Movement.initial_balance_t def early_balance(id, %Date{} = date) when is_integer(id) do id |> early_balance_query(date) |> Repo.one() end @doc """ It's a `t:Date.Range.t/0` representing the activity time span of a given `t:t/0`. """ @spec activity_range(t) :: nil | Date.Range.t() def activity_range(%__MODULE__{} = account) do account |> opening_date() |> range_today() end @spec generate_api_token() :: binary() defp generate_api_token do 32..64 |> Enum.random() |> SecureRandom.base64() end @spec range_today(nil | Date.t) :: nil | Date.Range.t() defp range_today(nil), do: nil defp range_today(%Date{} = date) do Date.range(date, Date.utc_today) end @spec opening_date(t) :: Date.t() | nil defp opening_date(%__MODULE__{} = account) do account.id |> opening_date_query() |> Repo.one() end @spec inbounds_on_query(pos_integer, Date.t) :: Ecto.Query.t() defp inbounds_on_query(id, %Date{} = date) when is_integer(id) do from m in Movement, where: m.account_id == ^id, where: m.move_on == ^date, where: m.direction == 1, select: sum(m.amount) end @spec outbounds_on_query(pos_integer, Date.t) :: Ecto.Query.t() defp outbounds_on_query(id, %Date{} = date) when is_integer(id) do from m in Movement, where: m.account_id == ^id, where: m.move_on == ^date, where: m.direction == -1, select: sum(m.amount) end @spec early_balance_query(pos_integer, Date.t) :: Ecto.Query.t() defp early_balance_query(id, %Date{} = date) when is_integer(id) do from m in Movement, where: m.account_id == ^id, where: m.move_on == ^date, order_by: [asc: m.move_at], limit: 1, select: [:initial_balance] end @spec balance_query(pos_integer) :: Ecto.Query.t() defp balance_query(id) when is_integer(id) do from m in Movement, where: m.account_id == ^id, order_by: [desc: m.move_at], limit: 1, select: [:final_balance] end @spec opening_date_query(pos_integer) :: Ecto.Query.t() defp opening_date_query(id) when is_integer(id) do from m in Movement, where: m.account_id == ^id, order_by: [asc: m.move_at], select: m.move_on, limit: 1 end end
apps/database/lib/database/schemas/account.ex
0.911431
0.61832
account.ex
starcoder
defmodule Guachiman.Plug.MetaPipeline do @moduledoc """ Defines a plug pipeline that applies `Guardian.Plug.Pipeline` and use `:guachiman` as its `otp_app`. """ defmacro __using__(options \\ []) do otp_app = Keyword.get(options, :otp_app, :guachiman) quote do use Guardian.Plug.Pipeline, otp_app: unquote(otp_app) end end end defmodule Guachiman.Plug.Pipeline do @moduledoc """ Defines a plug pipeline that applies `Guardian.Plug.Pipeline` and uses `:guachiman` as `otp_app`, `Guachiman.Guardian` as Guardian's module and `Guachiman.AuthErrorHandler` as error handler for `Guardian`. The easiest way to use `Guachiman.Plug.Pipeline` is create a module to define the custom pipeline. ```elixir defmodule MyCustomAuth0Pipeline do use Guachiman.Plug.Pipeline plug(Guardian.Plug.VerifyHeader, realm: "Bearer") plug(Guachiman.Plug.EnsureAuthenticated) ... end ``` Then, when you want to use the module, do the following: ```elixir plug MyCustomAuth0Pipeline, audience: "my_aut0_api_audience" ``` Similarly, you can also use `Guachiman.Plug.Pipeline` inline to set the audience as follows: ### Inline pipelines If you want to define your pipeline inline, you can do so by using `Guachiman.Plug.Pipeline` as a plug itself. ```elixir plug(Guachiman.Plug.Pipeline, audience: "my_aut0_api_audience") plug(Guardian.Plug.VerifyHeader, realm: "Bearer") plug(Guachiman.Plug.EnsureAuthenticated) ``` """ defmacro __using__(options \\ []) do alias Guachiman.Plug.Pipeline otp_app = Keyword.get(options, :otp_app, :guachiman) module = Keyword.get(options, :module, Guachiman.Guardian) error_handler = Keyword.get(options, :error_handler, Guachiman.AuthErrorHandler) quote do use Plug.Builder import Pipeline plug( Guardian.Plug.Pipeline, otp_app: unquote(otp_app), module: unquote(module), error_handler: unquote(error_handler) ) def init(opts) do Pipeline.init(opts) end def call(conn, opts) do conn |> Pipeline.call(opts) |> super(opts) end end end ### PUBLIC API @spec init(Keyword.t()) :: Keyword.t() def init(opts) do audience = get_audience(opts) opts |> Keyword.put(:audience, audience) end @spec call(Plug.Conn.t(), Keyword.t()) :: Plug.Conn.t() def call(conn, opts) do conn |> put_audience(opts) end @spec fetch_audience(Plug.Conn.t()) :: binary() @doc """ Fetches the audience assigned to the pipeline. Raises an error when the audience hasn't been set. """ def fetch_audience(conn) do audience = current_audience(conn) if audience do audience else raise("`audience` not set in Guachiman Pipeline") end end ### HELPERS @spec put_audience(Plug.Conn.t(), Keyword.t()) :: Plug.Conn.t() def put_audience(conn, opts) do conn |> Plug.Conn.put_private(:guachiman_audience, Keyword.get(opts, :audience)) end @spec current_audience(Plug.Conn.t()) :: Plug.Conn.t() defp current_audience(conn), do: conn.private[:guachiman_audience] defp get_audience(opts) do # get `audience` from plug options or use configuration instead opts |> Keyword.get(:audience, Application.get_env(:guachiman, :audience)) end end defmodule Guachiman.Plug.Auth0Pipeline do @moduledoc """ A pipeline that verifies the AUTH0's JWT token, ensure token's `aud` claim is correct and load a resource using Guachiman.Guardian module. See `Guachiman.Resource`. """ use Guachiman.Plug.Pipeline plug(Guardian.Plug.VerifyHeader, realm: "Bearer") plug(Guachiman.Plug.EnsureAuthenticated) plug(Guardian.Plug.LoadResource) end defmodule Guachiman.Plug.Auth0AppsPipeline do @moduledoc """ A pipeline to verify an AUTH0's JWT token and ensure token's aud claims is the specified once. """ use Guachiman.Plug.Pipeline plug(Guardian.Plug.VerifyHeader, realm: "Bearer") plug(Guachiman.Plug.EnsureAuthenticated) end
lib/guachiman/plug/pipeline.ex
0.838911
0.888275
pipeline.ex
starcoder
defmodule Grizzly.ZWave.Commands.FirmwareMDReport do @moduledoc """ The Firmware Meta Data Report Command is used to advertise the status of the current firmware in the device. Params: * `:manufacturer_id` - A unique ID identifying the manufacturer of the device * `:firmware_id` - A manufacturer SHOULD assign a unique Firmware ID to each existing product variant. * `:checksum` - The checksum of the firmware image. * `:upgradable?` - Whether the Z-Wave chip is firmware upgradable * `:max_fragment_size` - The maximum number of Data bytes that a device is able to receive at a time * `:other_firmware_ids` - Ids of firmware targets other than the Z-Wave chip. Empty list if the device's only firmware target is the Z-Wave chip * `:hardware_version` - A value which is unique to this particular version of the product * `:activation_supported?` - Whether the node supports subsequent activation after Firmware Update transfer * `:active_during_transfer?` - Whether the supporting node’s Command Classes functionality will continue to function normally during Firmware Update transfer. """ @behaviour Grizzly.ZWave.Command alias Grizzly.ZWave.Command alias Grizzly.ZWave.CommandClasses.FirmwareUpdateMD @type param :: {:manufacturer_id, non_neg_integer} | {:firmware_id, non_neg_integer} | {:checksum, non_neg_integer} | {:upgradable?, boolean} | {:max_fragment_size, non_neg_integer} | {:other_firmware_ids, [non_neg_integer]} | {:hardware_version, byte} | {:activation_supported?, boolean} | {:active_during_transfer?, boolean} @impl true @spec new([param()]) :: {:ok, Command.t()} def new(params) do command = %Command{ name: :firmware_md_report, command_byte: 0x02, command_class: FirmwareUpdateMD, params: params, impl: __MODULE__ } {:ok, command} end @impl true # version 1 def decode_params( <<manufacturer_id::size(2)-integer-unsigned-unit(8), firmware_id::size(2)-integer-unsigned-unit(8), checksum::size(2)-integer-unsigned-unit(8)>> ) do {:ok, [ manufacturer_id: manufacturer_id, firmware_id: firmware_id, checksum: checksum ]} end # version 3 def decode_params( <<manufacturer_id::size(2)-integer-unsigned-unit(8), firmware_id::size(2)-integer-unsigned-unit(8), checksum::size(2)-integer-unsigned-unit(8), firmware_upgradable, firmware_targets, max_fragment_size::size(2)-integer-unsigned-unit(8), firmware_target_ids::size(firmware_targets)-binary-unit(16)>> ) do other_firmware_ids = for <<id::16 <- firmware_target_ids>>, do: id {:ok, [ manufacturer_id: manufacturer_id, firmware_id: firmware_id, checksum: checksum, firmware_upgradable?: firmware_upgradable == 0xFF, max_fragment_size: max_fragment_size, other_firmware_ids: other_firmware_ids ]} end # version 5 def decode_params( <<manufacturer_id::size(2)-integer-unsigned-unit(8), firmware_id::size(2)-integer-unsigned-unit(8), checksum::size(2)-integer-unsigned-unit(8), firmware_upgradable, firmware_targets, max_fragment_size::size(2)-integer-unsigned-unit(8), firmware_target_ids::size(firmware_targets)-binary-unit(16), hardware_version>> ) do other_firmware_ids = for <<id::16 <- firmware_target_ids>>, do: id {:ok, [ manufacturer_id: manufacturer_id, firmware_id: firmware_id, checksum: checksum, firmware_upgradable?: firmware_upgradable == 0xFF, max_fragment_size: max_fragment_size, other_firmware_ids: other_firmware_ids, hardware_version: hardware_version ]} end # versions 6-7 def decode_params( <<manufacturer_id::size(2)-integer-unsigned-unit(8), firmware_id::size(2)-integer-unsigned-unit(8), checksum::size(2)-integer-unsigned-unit(8), firmware_upgradable, firmware_targets, max_fragment_size::size(2)-integer-unsigned-unit(8), firmware_target_ids::size(firmware_targets)-binary-unit(16), hardware_version, _reserved::size(6), activation::size(1), cc::size(1)>> ) do other_firmware_ids = for <<id::16 <- firmware_target_ids>>, do: id {:ok, [ manufacturer_id: manufacturer_id, firmware_id: firmware_id, checksum: checksum, firmware_upgradable?: firmware_upgradable == 0xFF, max_fragment_size: max_fragment_size, other_firmware_ids: other_firmware_ids, hardware_version: hardware_version, active_during_transfer?: cc == 0x01, activation_supported?: activation == 0x01 ]} end @impl true @spec encode_params(Command.t()) :: binary() def encode_params(command) do params = command.params |> Enum.into(%{}) case params do # v6-7 %{ manufacturer_id: manufacturer_id, firmware_id: firmware_id, checksum: checksum, firmware_upgradable?: firmware_upgradable?, max_fragment_size: max_fragment_size, other_firmware_ids: other_firmware_ids, hardware_version: hardware_version, activation_supported?: activation_supported?, active_during_transfer?: active_during_transfer? } -> firmware_targets = Enum.count(other_firmware_ids) firmware_target_ids = for id <- other_firmware_ids, do: <<id::16>>, into: <<>> firmware_upgradable = if firmware_upgradable?, do: 0xFF, else: 0x00 activation_supported = if activation_supported?, do: 0x01, else: 0x00 cc = if active_during_transfer?, do: 0x01, else: 0x00 <<manufacturer_id::size(2)-integer-unsigned-unit(8), firmware_id::size(2)-integer-unsigned-unit(8), checksum::size(2)-integer-unsigned-unit(8), firmware_upgradable, firmware_targets, max_fragment_size::size(2)-integer-unsigned-unit(8), firmware_target_ids::size(firmware_targets)-binary-unit(16), hardware_version, 0x00::size(6), activation_supported::size(1), cc::size(1)>> # v5 %{ manufacturer_id: manufacturer_id, firmware_id: firmware_id, checksum: checksum, firmware_upgradable?: firmware_upgradable?, max_fragment_size: max_fragment_size, other_firmware_ids: other_firmware_ids, hardware_version: hardware_version } -> firmware_targets = Enum.count(other_firmware_ids) firmware_target_ids = for id <- other_firmware_ids, do: <<id::16>>, into: <<>> firmware_upgradable = if firmware_upgradable?, do: 0xFF, else: 0x00 <<manufacturer_id::size(2)-integer-unsigned-unit(8), firmware_id::size(2)-integer-unsigned-unit(8), checksum::size(2)-integer-unsigned-unit(8), firmware_upgradable, firmware_targets, max_fragment_size::size(2)-integer-unsigned-unit(8), firmware_target_ids::size(firmware_targets)-binary-unit(16), hardware_version>> # v3 %{ manufacturer_id: manufacturer_id, firmware_id: firmware_id, checksum: checksum, firmware_upgradable?: firmware_upgradable?, max_fragment_size: max_fragment_size, other_firmware_ids: other_firmware_ids } -> firmware_targets = Enum.count(other_firmware_ids) firmware_target_ids = for id <- other_firmware_ids, do: <<id::16>>, into: <<>> firmware_upgradable = if firmware_upgradable?, do: 0xFF, else: 0x00 <<manufacturer_id::size(2)-integer-unsigned-unit(8), firmware_id::size(2)-integer-unsigned-unit(8), checksum::size(2)-integer-unsigned-unit(8), firmware_upgradable, firmware_targets, max_fragment_size::size(2)-integer-unsigned-unit(8), firmware_target_ids::size(firmware_targets)-binary-unit(16)>> # v1 %{ manufacturer_id: manufacturer_id, firmware_id: firmware_id, checksum: checksum } -> <<manufacturer_id::size(2)-integer-unsigned-unit(8), firmware_id::size(2)-integer-unsigned-unit(8), checksum::size(2)-integer-unsigned-unit(8)>> end end end
lib/grizzly/zwave/commands/firmware_md_report.ex
0.845273
0.409339
firmware_md_report.ex
starcoder
defmodule Sanbase.Anomaly.SqlQuery do @table "anomalies_v2" @metadata_table "anomalies_model_metadata" @moduledoc ~s""" Define the SQL queries to access to the anomalies in Clickhouse The anomalies are stored in the '#{@table}' clickhouse table """ use Ecto.Schema import Sanbase.DateTimeUtils, only: [str_to_sec: 1] import Sanbase.Metric.SqlQuery.Helper, only: [aggregation: 3] alias Sanbase.Anomaly.FileHandler @table_map FileHandler.table_map() @metric_map FileHandler.metric_map() @model_name_map FileHandler.model_name_map() schema @table do field(:datetime, :utc_datetime, source: :dt) field(:value, :float) field(:asset_id, :integer) field(:metric_id, :integer) field(:model_id, :integer) field(:computed_at, :utc_datetime) end def timeseries_data_query(anomaly, slug, from, to, interval, aggregation) do query = """ SELECT toUnixTimestamp(intDiv(toUInt32(toDateTime(dt)), ?1) * ?1) AS t, toFloat32(#{aggregation(aggregation, "value", "dt")}) FROM( SELECT dt, argMax(value, computed_at) AS value FROM #{Map.get(@table_map, anomaly)} PREWHERE dt >= toDateTime(?2) AND dt < toDateTime(?3) AND model_id GLOBAL IN ( SELECT model_id FROM #{@metadata_table} PREWHERE name = ?4 AND metric_id = ( SELECT argMax(metric_id, computed_at) AS metric_id FROM metric_metadata PREWHERE name = ?5 ) AND asset_id = ( SELECT argMax(asset_id, computed_at) FROM asset_metadata PREWHERE name = ?6 ) ) GROUP BY dt ) GROUP BY t ORDER BY t """ args = [ str_to_sec(interval), from, to, Map.get(@model_name_map, anomaly), Map.get(@metric_map, anomaly), slug ] {query, args} end def aggregated_timeseries_data_query(anomaly, asset_ids, from, to, aggregation) do query = """ SELECT toUInt32(asset_id), toFloat32(#{aggregation(aggregation, "value", "dt")}) FROM( SELECT dt, asset_id, argMax(value, computed_at) AS value FROM #{Map.get(@table_map, anomaly)} PREWHERE dt >= toDateTime(?1) AND dt < toDateTime(?2) AND model_id GLOBAL IN ( SELECT model_id FROM #{@metadata_table} PREWHERE asset_id IN (?3) AND name = ?4 AND metric_id = ( SELECT argMax(metric_id, computed_at) AS metric_id FROM metric_metadata PREWHERE name = ?5 ) ) GROUP BY dt, asset_id ) GROUP BY asset_id """ args = [ from, to, asset_ids, Map.get(@model_name_map, anomaly), Map.get(@metric_map, anomaly) ] {query, args} end def available_slugs_query(anomaly) do query = """ SELECT DISTINCT(name) FROM asset_metadata PREWHERE asset_id GLOBAL IN ( SELECT DISTINCT(asset_id) FROM #{@metadata_table} PREWHERE name = ?1 AND metric_id = ( SELECT argMax(metric_id, computed_at) FROM metric_metadata PREWHERE name = ?2 a ) """ args = [ Map.get(@model_name_map, anomaly), Map.get(@metric_map, anomaly) ] {query, args} end def available_anomalies_query() do query = """ SELECT name, toUInt32(asset_id), toUInt32(metric_id) FROM #{@metadata_table} GROUP BY name, asset_id, metric_id """ args = [] {query, args} end def first_datetime_query(anomaly, nil) do query = """ SELECT toUnixTimestamp(toDateTime(min(dt))) FROM #{Map.get(@table_map, anomaly)} PREWHERE model_id GLOBAL IN ( SELECT model_id FROM #{@metadata_table} PREWHERE name = ?1 AND metric_id = ( SELECT argMax(metric_id, computed_at) FROM metric_metadata PREWHERE name = ?2 ) ) """ args = [ Map.get(@model_name_map, anomaly), Map.get(@metric_map, anomaly) ] {query, args} end def first_datetime_query(anomaly, slug) do query = """ SELECT toUnixTimestamp(toDateTime(min(dt))) FROM #{Map.get(@table_map, anomaly)} PREWHERE model_id GLOBAL IN ( SELECT model_id FROM #{@metadata_table} PREWHERE name = ?1 AND metric_id = ( SELECT argMax(metric_id, computed_at) FROM metric_metadata PREWHERE name = ?2 ) AND asset_id = ( SELECT argMax(asset_id, computed_at) FROM asset_metadata PREWHERE name = ?3 ) ) """ args = [ Map.get(@model_name_map, anomaly), Map.get(@metric_map, anomaly), slug ] {query, args} end end
lib/sanbase/anomaly/anomaly_sql_query.ex
0.793786
0.418935
anomaly_sql_query.ex
starcoder
defmodule Day11 do @moduledoc """ Documentation for Day11. """ def part1 do Day11.read_seats("input.txt") |> Day11.stabilize() |> Day11.occupied_seats() |> IO.puts() end def part2 do Day11.read_seats("input.txt") |> Day11.stabilize(&Day11.step2/1) |> Day11.occupied_seats() |> IO.puts() end def read_seats(filename) do File.stream!(filename) |> Stream.map(&String.trim/1) |> Stream.map(&String.graphemes/1) |> Stream.with_index() |> Stream.map(fn {seats, row} -> seats |> Enum.with_index() |> Enum.map(fn {seat, col} -> {{row, col}, seat} end) end) |> Stream.flat_map(fn row -> row end) |> Map.new() end def neighborhood({row, col} = loc) do for r <- [row - 1, row, row + 1], c <- [col - 1, col, col + 1] do {r, c} end |> Enum.filter(fn x -> x != loc end) end def debug(seats, size \\ 10) do for row <- 0..(size - 1), col <- 0..(size - 1) do IO.write(seats[{row, col}]) if col == 9, do: IO.puts("") end seats end def directions do for x <- -1..1, y <- -1..1 do {x, y} end |> Enum.filter(fn {0, 0} -> false _ -> true end) end def look(seats, {lx, ly}, {dx, dy} = dir) do next_loc = {lx + dx, ly + dy} case seats[next_loc] do "." -> look(seats, next_loc, dir) seat -> seat end end def neighborhood2(seats, loc) do directions() |> Enum.map(fn dir -> look(seats, loc, dir) end) end def step2(seats) do seats |> Enum.map(fn {loc, seat} -> case {seat, neighborhood2(seats, loc) |> Enum.filter(fn s -> s == "#" end) |> Enum.count()} do {".", _} -> {loc, "."} {"L", 0} -> {loc, "#"} {"#", adjacents} when adjacents >= 5 -> {loc, "L"} _ -> {loc, seat} end end) |> Map.new() end def step(seats) do seats |> Enum.map(fn {loc, seat} -> case {seat, neighborhood(loc) |> Enum.map(fn n_loc -> Map.get(seats, n_loc) end) |> Enum.filter(fn s -> s == "#" end) |> Enum.count()} do {".", _} -> {loc, "."} {"L", 0} -> {loc, "#"} {"#", adjacents} when adjacents >= 4 -> {loc, "L"} _ -> {loc, seat} end end) |> Map.new() end def occupied_seats(seats) do seats |> Map.values() |> Enum.count(fn s -> s == "#" end) end def stabilize(seats, step_fn \\ &Day11.step/1) do Stream.resource( fn -> seats end, fn last_seats -> next_seats = last_seats |> step_fn.() if next_seats == last_seats do {:halt, next_seats} else {[next_seats], next_seats} end end, fn final_seats -> final_seats end ) |> Enum.to_list() # |> Enum.map(fn seats -> # IO.puts("----------") # seats |> debug() # end) |> List.last() end end
day11/lib/day11.ex
0.552057
0.481941
day11.ex
starcoder
import TypeClass defclass Witchcraft.Apply do @moduledoc """ An extension of `Witchcraft.Functor`, `Apply` provides a way to _apply_ arguments to functions when both are wrapped in the same kind of container. This can be seen as running function application "in a context". For a nice, illustrated introduction, see [Functors, Applicatives, And Monads In Pictures](http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html). ## Graphically If function application looks like this data |> function == result and a functor looks like this %Container<data> ~> function == %Container<result> then an apply looks like %Container<data> ~>> %Container<function> == %Container<result> which is similar to function application inside containers, plus the ability to attach special effects to applications. data --------------- function ---------------> result %Container<data> --- %Container<function> ---> %Container<result> This lets us do functorial things like * continue applying values to a curried function resulting from a `Witchcraft.Functor.lift/2` * apply multiple functions to multiple arguments (with lists) * propogate some state (like [`Nothing`](https://hexdocs.pm/algae/Algae.Maybe.Nothing.html#content) in [`Algae.Maybe`](https://hexdocs.pm/algae/Algae.Maybe.html#content)) but now with a much larger number of arguments, reuse partially applied functions, and run effects with the function container as well as the data container. ## Examples iex> ap([fn x -> x + 1 end, fn y -> y * 10 end], [1, 2, 3]) [2, 3, 4, 10, 20, 30] iex> [100, 200] ...> |> Witchcraft.Functor.lift(fn(x, y, z) -> x * y / z end) ...> |> provide([5, 2]) ...> |> provide([100, 50]) [5.0, 10.0, 2.0, 4.0, 10.0, 20.0, 4.0, 8.0] # ↓ ↓ # 100 * 5 / 100 200 * 5 / 50 iex> import Witchcraft.Functor ...> ...> [100, 200] ...> ~> fn(x, y, z) -> ...> x * y / z ...> end <<~ [5, 2] ...> <<~ [100, 50] [5.0, 10.0, 2.0, 4.0, 10.0, 20.0, 4.0, 8.0] # ↓ ↓ # 100 * 5 / 100 200 * 5 / 50 %Algae.Maybe.Just{just: 42} ~> fn(x, y, z) -> x * y / z end <<~ %Algae.Maybe.Nothing{} <<~ %Algae.Maybe.Just{just: 99} #=> %Algae.Maybe.Nothing{} ## `convey` vs `ap` `convey` and `ap` essentially associate in opposite directions. For example, large data is _usually_ more efficient with `ap`, and large numbers of functions are _usually_ more efficient with `convey`. It's also more consistent consistency. In Elixir, we like to think of a "subject" being piped through a series of transformations. This places the function argument as the second argument. In `Witchcraft.Functor`, this was of little consequence. However, in `Apply`, we're essentially running superpowered function application. `ap` is short for `apply`, as to not conflict with `Kernel.apply/2`, and is meant to respect a similar API, with the function as the first argument. This also reads nicely when piped, as it becomes `[funs] |> ap([args1]) |> ap([args2])`, which is similar in structure to `fun.(arg2).(arg1)`. With potentially multiple functions being applied over potentially many arguments, we need to worry about ordering. `convey` not only flips the order of arguments, but also who is in control of ordering. `convey` typically runs each function over all arguments (`first_fun ⬸ all_args`), and `ap` runs all functions for each element (`first_arg ⬸ all_funs`). This may change the order of results, and is a feature, not a bug. iex> [1, 2, 3] ...> |> convey([&(&1 + 1), &(&1 * 10)]) [ 2, 10, # [(1 + 1), (1 * 10)] 3, 20, # [(2 + 1), (2 * 10)] 4, 30 # [(3 + 1), (3 * 10)] ] iex> [&(&1 + 1), &(&1 * 10)] ...> |> ap([1, 2, 3]) [ 2, 3, 4, # [(1 + 1), (2 + 1), (3 + 1)] 10, 20, 30 # [(1 * 10), (2 * 10), (3 * 10)] ] ## Type Class An instance of `Witchcraft.Apply` must also implement `Witchcraft.Functor`, and define `Witchcraft.Apply.convey/2`. Functor [map/2] ↓ Apply [convey/2] """ alias __MODULE__ alias Witchcraft.Functor extend Witchcraft.Functor use Witchcraft.Internal, deps: [Witchcraft.Functor] use Witchcraft.Functor use Quark @type t :: any() @type fun :: any() where do @doc """ Pipe arguments to functions, when both are wrapped in the same type of data structure. ## Examples iex> [1, 2, 3] ...> |> convey([fn x -> x + 1 end, fn y -> y * 10 end]) [2, 10, 3, 20, 4, 30] """ @spec convey(Apply.t(), Apply.fun()) :: Apply.t() def convey(wrapped_args, wrapped_funs) end properties do def composition(data) do alias Witchcraft.Functor use Quark as = data |> generate() |> Functor.map(&inspect/1) fs = data |> generate() |> Functor.replace(fn x -> x <> x end) gs = data |> generate() |> Functor.replace(fn y -> y <> "foo" end) left = Apply.convey(Apply.convey(as, gs), fs) right = fs |> Functor.lift(&compose/2) |> (fn x -> Apply.convey(gs, x) end).() |> (fn y -> Apply.convey(as, y) end).() equal?(left, right) end end @doc """ Alias for `convey/2`. Why "hose"? * Pipes (`|>`) are application with arguments flipped * `ap/2` is like function application "in a context" * The opposite of `ap` is a contextual pipe * `hose`s are a kind of flexible pipe Q.E.D. ![](http://s2.quickmeme.com/img/fd/fd0baf5ada879021c32129fc7dea679bd7666e708df8ca8ca536da601ea3d29e.jpg) ## Examples iex> [1, 2, 3] ...> |> hose([fn x -> x + 1 end, fn y -> y * 10 end]) [2, 10, 3, 20, 4, 30] """ @spec hose(Apply.t(), Apply.fun()) :: Apply.t() def hose(wrapped_args, wrapped_funs), do: convey(wrapped_args, wrapped_funs) @doc """ Reverse arguments and sequencing of `convey/2`. Conceptually this makes operations happen in a different order than `convey/2`, with the left-side arguments (functions) being run on all right-side arguments, in that order. We're altering the _sequencing_ of function applications. ## Examples iex> ap([fn x -> x + 1 end, fn y -> y * 10 end], [1, 2, 3]) [2, 3, 4, 10, 20, 30] # For comparison iex> convey([1, 2, 3], [fn x -> x + 1 end, fn y -> y * 10 end]) [2, 10, 3, 20, 4, 30] iex> [100, 200] ...> |> Witchcraft.Functor.lift(fn(x, y, z) -> x * y / z end) ...> |> ap([5, 2]) ...> |> ap([100, 50]) [5.0, 10.0, 2.0, 4.0, 10.0, 20.0, 4.0, 8.0] # ↓ ↓ # 100 * 5 / 100 200 * 5 / 50 """ @spec ap(Apply.fun(), Apply.t()) :: Apply.t() def ap(wrapped_funs, wrapped) do lift(wrapped, wrapped_funs, fn arg, fun -> fun.(arg) end) end @doc """ Async version of `convey/2` ## Examples iex> [1, 2, 3] ...> |> async_convey([fn x -> x + 1 end, fn y -> y * 10 end]) [2, 10, 3, 20, 4, 30] 0..10_000 |> Enum.to_list() |> async_convey([ fn x -> Process.sleep(500) x + 1 end, fn y -> Process.sleep(500) y * 10 end ]) #=> [1, 0, 2, 10, 3, 30, ...] in around a second """ @spec async_convey(Apply.t(), Apply.fun()) :: Apply.t() def async_convey(wrapped_args, wrapped_funs) do wrapped_args |> convey( lift(wrapped_funs, fn fun, arg -> Task.async(fn -> fun.(arg) end) end) ) |> map(&Task.await/1) end @doc """ Async version of `ap/2` ## Examples iex> [fn x -> x + 1 end, fn y -> y * 10 end] ...> |> async_ap([1, 2, 3]) [2, 3, 4, 10, 20, 30] [ fn x -> Process.sleep(500) x + 1 end, fn y -> Process.sleep(500) y * 10 end ] |> async_ap(Enum.to_list(0..10_000)) #=> [1, 2, 3, 4, ...] in around a second """ @spec async_ap(Apply.fun(), Apply.t()) :: Apply.t() def async_ap(wrapped_funs, wrapped_args) do wrapped_funs |> lift(fn fun, arg -> Task.async(fn -> fun.(arg) end) end) |> ap(wrapped_args) |> map(&Task.await/1) end @doc """ Operator alias for `ap/2` Moves against the pipe direction, but in the order of normal function application ## Examples iex> [fn x -> x + 1 end, fn y -> y * 10 end] <<~ [1, 2, 3] [2, 3, 4, 10, 20, 30] iex> import Witchcraft.Functor ...> ...> [100, 200] ...> ~> fn(x, y, z) -> x * y / z ...> end <<~ [5, 2] ...> <<~ [100, 50] ...> ~> fn x -> x + 1 end [6.0, 11.0, 3.0, 5.0, 11.0, 21.0, 5.0, 9.0] iex> import Witchcraft.Functor, only: [<~: 2] ...> fn(a, b, c, d) -> a * b - c + d end <~ [1, 2] <<~ [3, 4] <<~ [5, 6] <<~ [7, 8] [5, 6, 4, 5, 6, 7, 5, 6, 8, 9, 7, 8, 10, 11, 9, 10] """ defalias wrapped_funs <<~ wrapped, as: :provide @doc """ Operator alias for `reverse_ap/2`, moving in the pipe direction ## Examples iex> [1, 2, 3] ~>> [fn x -> x + 1 end, fn y -> y * 10 end] [2, 10, 3, 20, 4, 30] iex> import Witchcraft.Functor ...> ...> [100, 50] ...> ~>> ([5, 2] # Note the bracket ...> ~>> ([100, 200] # on both `Apply` lines ...> ~> fn(x, y, z) -> x * y / z end)) [5.0, 10.0, 2.0, 4.0, 10.0, 20.0, 4.0, 8.0] """ defalias wrapped ~>> wrapped_funs, as: :supply @doc """ Same as `convey/2`, but with all functions curried. ## Examples iex> [1, 2, 3] ...> |> supply([fn x -> x + 1 end, fn y -> y * 10 end]) [2, 10, 3, 20, 4, 30] """ @spec supply(Apply.t(), Apply.fun()) :: Apply.t() def supply(args, funs), do: convey(args, Functor.map(funs, &curry/1)) @doc """ Same as `ap/2`, but with all functions curried. ## Examples iex> [&+/2, &*/2] ...> |> provide([1, 2, 3]) ...> |> ap([4, 5, 6]) [5, 6, 7, 6, 7, 8, 7, 8, 9, 4, 5, 6, 8, 10, 12, 12, 15, 18] """ @spec provide(Apply.fun(), Apply.t()) :: Apply.t() def provide(funs, args), do: funs |> Functor.map(&curry/1) |> ap(args) @doc """ Sequence actions, replacing the first/previous values with the last argument This is essentially a sequence of actions forgetting the first argument ## Examples iex> [1, 2, 3] ...> |> Witchcraft.Apply.then([4, 5, 6]) ...> |> Witchcraft.Apply.then([7, 8, 9]) [ 7, 8, 9, 7, 8, 9, 7, 8, 9, 7, 8, 9, 7, 8, 9, 7, 8, 9, 7, 8, 9, 7, 8, 9, 7, 8, 9 ] iex> {1, 2, 3} |> Witchcraft.Apply.then({4, 5, 6}) |> Witchcraft.Apply.then({7, 8, 9}) {12, 15, 9} """ @spec then(Apply.t(), Apply.t()) :: Apply.t() def then(wrapped_a, wrapped_b), do: over(&Quark.constant(&2, &1), wrapped_a, wrapped_b) @doc """ Sequence actions, replacing the last argument with the first argument's values This is essentially a sequence of actions forgetting the second argument ## Examples iex> [1, 2, 3] ...> |> following([3, 4, 5]) ...> |> following([5, 6, 7]) [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3 ] iex> {1, 2, 3} |> following({4, 5, 6}) |> following({7, 8, 9}) {12, 15, 3} """ @spec following(Apply.t(), Apply.t()) :: Apply.t() def following(wrapped_a, wrapped_b), do: lift(wrapped_b, wrapped_a, &Quark.constant(&2, &1)) @doc """ Extends `Functor.lift/2` to apply arguments to a binary function ## Examples iex> lift([1, 2], [3, 4], &+/2) [4, 5, 5, 6] iex> [1, 2] ...> |> lift([3, 4], &*/2) [3, 6, 4, 8] """ @spec lift(Apply.t(), Apply.t(), fun()) :: Apply.t() def lift(a, b, fun) do a |> lift(fun) |> (fn f -> convey(b, f) end).() end @doc """ Extends `lift` to apply arguments to a ternary function ## Examples iex> lift([1, 2], [3, 4], [5, 6], fn(a, b, c) -> a * b - c end) [-2, -3, 1, 0, -1, -2, 3, 2] """ @spec lift(Apply.t(), Apply.t(), Apply.t(), fun()) :: Apply.t() def lift(a, b, c, fun), do: a |> lift(b, fun) |> ap(c) @doc """ Extends `lift` to apply arguments to a quaternary function ## Examples iex> lift([1, 2], [3, 4], [5, 6], [7, 8], fn(a, b, c, d) -> a * b - c + d end) [5, 6, 4, 5, 8, 9, 7, 8, 6, 7, 5, 6, 10, 11, 9, 10] """ @spec lift(Apply.t(), Apply.t(), Apply.t(), Apply.t(), fun()) :: Apply.t() def lift(a, b, c, d, fun), do: a |> lift(b, c, fun) |> ap(d) @doc """ Extends `Functor.async_lift/2` to apply arguments to a binary function ## Examples iex> async_lift([1, 2], [3, 4], &+/2) [4, 5, 5, 6] iex> [1, 2] ...> |> async_lift([3, 4], &*/2) [3, 6, 4, 8] """ @spec async_lift(Apply.t(), Apply.t(), fun()) :: Apply.t() def async_lift(a, b, fun) do a |> async_lift(fun) |> (fn f -> async_convey(b, f) end).() end @doc """ Extends `async_lift` to apply arguments to a ternary function ## Examples iex> async_lift([1, 2], [3, 4], [5, 6], fn(a, b, c) -> a * b - c end) [-2, -3, 1, 0, -1, -2, 3, 2] """ @spec async_lift(Apply.t(), Apply.t(), Apply.t(), fun()) :: Apply.t() def async_lift(a, b, c, fun), do: a |> async_lift(b, fun) |> async_ap(c) @doc """ Extends `async_lift` to apply arguments to a quaternary function ## Examples iex> async_lift([1, 2], [3, 4], [5, 6], [7, 8], fn(a, b, c, d) -> a * b - c + d end) [5, 6, 4, 5, 8, 9, 7, 8, 6, 7, 5, 6, 10, 11, 9, 10] """ @spec async_lift(Apply.t(), Apply.t(), Apply.t(), Apply.t(), fun()) :: Apply.t() def async_lift(a, b, c, d, fun), do: a |> async_lift(b, c, fun) |> async_ap(d) @doc """ Extends `over` to apply arguments to a binary function ## Examples iex> over(&+/2, [1, 2], [3, 4]) [4, 5, 5, 6] iex> (&*/2) ...> |> over([1, 2], [3, 4]) [3, 4, 6, 8] """ @spec over(fun(), Apply.t(), Apply.t()) :: Apply.t() def over(fun, a, b), do: a |> lift(fun) |> ap(b) @doc """ Extends `over` to apply arguments to a ternary function ## Examples iex> fn(a, b, c) -> a * b - c end iex> |> over([1, 2], [3, 4], [5, 6]) [-2, -3, -1, -2, 1, 0, 3, 2] """ @spec over(fun(), Apply.t(), Apply.t(), Apply.t()) :: Apply.t() def over(fun, a, b, c), do: fun |> over(a, b) |> ap(c) @doc """ Extends `over` to apply arguments to a ternary function ## Examples iex> fn(a, b, c) -> a * b - c end ...> |> over([1, 2], [3, 4], [5, 6]) [-2, -3, -1, -2, 1, 0, 3, 2] """ @spec over(fun(), Apply.t(), Apply.t(), Apply.t(), Apply.t()) :: Apply.t() def over(fun, a, b, c, d), do: fun |> over(a, b, c) |> ap(d) @doc """ Extends `async_over` to apply arguments to a binary function ## Examples iex> async_over(&+/2, [1, 2], [3, 4]) [4, 5, 5, 6] iex> (&*/2) ...> |> async_over([1, 2], [3, 4]) [3, 4, 6, 8] """ @spec async_over(fun(), Apply.t(), Apply.t()) :: Apply.t() def async_over(fun, a, b), do: a |> lift(fun) |> async_ap(b) @doc """ Extends `async_over` to apply arguments to a ternary function ## Examples iex> fn(a, b, c) -> a * b - c end iex> |> async_over([1, 2], [3, 4], [5, 6]) [-2, -3, -1, -2, 1, 0, 3, 2] """ @spec async_over(fun(), Apply.t(), Apply.t(), Apply.t()) :: Apply.t() def async_over(fun, a, b, c), do: fun |> async_over(a, b) |> async_ap(c) @doc """ Extends `async_over` to apply arguments to a ternary function ## Examples iex> fn(a, b, c) -> a * b - c end ...> |> async_over([1, 2], [3, 4], [5, 6]) [-2, -3, -1, -2, 1, 0, 3, 2] """ @spec async_over(fun(), Apply.t(), Apply.t(), Apply.t(), Apply.t()) :: Apply.t() def async_over(fun, a, b, c, d), do: fun |> async_over(a, b, c) |> async_ap(d) end definst Witchcraft.Apply, for: Function do use Quark def convey(g, f), do: fn x -> curry(f).(x).(curry(g).(x)) end end definst Witchcraft.Apply, for: List do def convey(val_list, fun_list) when is_list(fun_list) do Enum.flat_map(val_list, fn val -> Enum.map(fun_list, fn fun -> fun.(val) end) end) end end # Contents must be semigroups definst Witchcraft.Apply, for: Tuple do import TypeClass.Property.Generator, only: [generate: 1] use Witchcraft.Semigroup custom_generator(_) do {generate(""), generate(1), generate(0), generate(""), generate(""), generate("")} end def convey({v, w}, {a, fun}), do: {v <> a, fun.(w)} def convey({v, w, x}, {a, b, fun}), do: {v <> a, w <> b, fun.(x)} def convey({v, w, x, y}, {a, b, c, fun}), do: {v <> a, w <> b, x <> c, fun.(y)} def convey({v, w, x, y, z}, {a, b, c, d, fun}) do { a <> v, b <> w, c <> x, d <> y, fun.(z) } end def convey(tuple_a, tuple_b) when tuple_size(tuple_a) == tuple_size(tuple_b) do last_index = tuple_size(tuple_a) - 1 tuple_a |> Tuple.to_list() |> Enum.zip(Tuple.to_list(tuple_b)) |> Enum.with_index() |> Enum.map(fn {{arg, fun}, ^last_index} -> fun.(arg) {{left, right}, _} -> left <> right end) |> List.to_tuple() end end
lib/witchcraft/apply.ex
0.865324
0.769514
apply.ex
starcoder
defmodule Farmbot.Farmware do @moduledoc """ Farmware is Farmbot's plugin system. Developing a farmware is simple. You will need 3 things: * A `manifest.json` hosted on the internet somewhere. * A zip package of your farmware. # Prerequisites While it is _technically_ possible to use any language to develop a Farmware, We currently only actively support Python (with a small set of dependencies.) If you want another language/framework, you have a couple options. * Ask the Farmbot developers to enable a package. * Package the language/framework yourself. (very advanced) ## Should *I* develop a Farmware? Farmware is not always the correct solution. If you plan on developing a plugin, you should ask yourself a few questions. * Does my plugin need to be running 24/7 to work? * Does my plugin need a realtime interface? * Does my plugin need keyboard input? If you answered Yes to any of those questions, you should consider, using an external plugin. See [a Python example](https://github.com/FarmBot-Labs/FarmBot-Python-Examples) # Farmware Manifest The `manifest.json` file should contain a number of required fields. * `package` - the name of your package. Should be CamelCase by convention. * `version` - The version of your package. [Semver](http://semver.org/) is required here. * `min_os_version_major` - A version requirement for Farmbot OS. * `url` - A url that points to this file. * `zip` - A url to the zip package to be downloaded and installed. * `executable` - the binary file that will be executed. * `args` - An array of strings that will be passed to the `executable`. * `config` - A set of default values to be passed to the Farmware. see [Configuration](#Configuration) for more details There are also a number of metadata fields that are not required, but are highly suggested. * `author` - The author of this package. * `description` - A brief description of the package. * `language` - The language that this plugin was developed in. # The zip package The zip package is simply a zip file that contains all your assets. This will usually contain a executable of some sort, and anything required to enable the execution of your package. # Repositories If you have more than one Farmware, and you would like to install all of them at one time, it might be worth it to put them in a `repository`. You will need to host a special `manifest.json` file that simply contains a list of objects. the objects should contain the following keys: * `manifest` - This should be a url that points to the package manifest. * `name` - the name of the package to install. # Developing a Farmware Farmwares should be simple script-like programs. They block other access to the bot for their lifetime, so they should also be short lived. ## Communication Since Farmbot can not have two way communication with a Farmware, If you Farmware needs to communicate with Farmbot, you will need to use one of: * HTTP - [Docs](Farmbot.BotState.Transport.HTTP.html) * Easy to work with. * Allows call/response type functionality. * Requires polling for state updates. * No access to logs. * Raw Websockets - [Docs](Farmbot.BotState.Transport.HTTP.SocketHandler.html) * More difficult to work with. * Not exactly call/response. * No polling for state updates. * Logs come in real time. # Configuration Since Farmbot and the Farmware can not talk directly, all configuration data is sent via Unix Environment Variables. *NOTE: All values denoted by a `$` mean they are a environment variable, the actual variable name will not contain the `$`.* There are two of default configuration's that can not be changed. * `$API_TOKEN` - An encoded binary that can be used to communicate with Farmbot and it's configured cloud server. * `$FARMWARE_URL` - The url to connect your HTTP client too to access Farmbot's REST API. *NOTE* This is *_NOT_* the same API as the cloud REST API. * `$IMAGES_DIR` - A local directory that will be scanned. Photos left in this directory will be uploaded and visable from the web app. Additional configuration can be supplied via the manifest. This is handy for configurating default values for a Farmware. the `config` field on the manifest should be an array of objects with these keys: * `name` - The name of the config. * `label` - The label that will show up on the web app. * `value` - The default value. When your Farmware executes you will have these keys available, but they will be namespaced to your Farmware `package` name in snake case. For Example, if you have a farmware called "HelloFarmware", and it has a config: `{"name": "first_config", "label": "a config field", "value": 100}`, when your Farmware executes, it will have a key by the name of `$hello_farmware_first_config` that will have the value `100`. Config values can however be overwritten by the Farmbot App. # More info See [Here](https://developer.farm.bot/docs/farmware) for more info. """ defmodule Meta do @moduledoc "Metadata about a Farmware." defstruct [:author, :language, :description] end defstruct [ :name, :version, :min_os_version_major, :url, :zip, :executable, :args, :config, :farmware_tools_version, :meta ] defdelegate execute(fw, env), to: Farmbot.Farmware.Runtime @doc "Lookup a farmware by it's name." def lookup(name) do dir = Farmbot.Farmware.Installer.install_root_path() with {:ok, all_installed} <- File.ls(dir), true <- name in all_installed do mani_path = Path.join( Farmbot.Farmware.Installer.install_path(name), "manifest.json" ) File.read!(mani_path) |> Poison.decode!() |> new() else false -> {:error, :not_installed} {:error, _} = err -> err end end @doc "Creates a new Farmware Struct" def new(map) do with {:ok, name} <- extract_name(map), {:ok, version} <- extract_version(map), {:ok, os_req} <- extract_os_requirement(map), {:ok, url} <- extract_url(map), {:ok, zip} <- extract_zip(map), {:ok, exe} <- extract_exe(map), {:ok, args} <- extract_args(map), {:ok, config} <- extract_config(map), {:ok, farmware_tools_version} <- extrace_farmware_tools_version(map), {:ok, meta} <- extract_meta(map) do res = struct( __MODULE__, name: name, version: version, min_os_version_major: os_req, url: url, zip: zip, executable: exe, args: args, config: config, farmware_tools_version: farmware_tools_version, meta: meta ) {:ok, res} else err -> err end end defp extract_name(%{"package" => name}) when is_binary(name), do: {:ok, name} defp extract_name(_), do: {:error, "bad or missing farmware name"} defp extract_version(%{"version" => version}) do case Version.parse(version) do {:ok, _} = res -> res :error -> {:error, "Could not parse version."} end end defp extract_version(_), do: {:error, "bad or missing farmware version"} defp extract_os_requirement(%{"min_os_version_major" => num}) when is_number(num) do {:ok, num} end defp extract_os_requirement(_), do: {:error, "bad or missing os requirement"} defp extract_zip(%{"zip" => zip}) when is_binary(zip), do: {:ok, zip} defp extract_zip(_), do: {:error, "bad or missing farmware zip url"} defp extract_url(%{"url" => url}) when is_binary(url), do: {:ok, url} defp extract_url(_), do: {:error, "bad or missing farmware url"} defp extract_exe(%{"executable" => exe}) when is_binary(exe) do case System.find_executable(exe) do nil -> {:error, "#{exe} is not installed"} path -> {:ok, path} end end defp extract_exe(_), do: {:error, "bad or missing farmware executable"} defp extract_args(%{"args" => args}) when is_list(args) do if Enum.all?(args, &is_binary(&1)) do {:ok, args} else {:error, "invalid args"} end end defp extract_args(_), do: {:error, "bad or missing farmware args"} defp extract_config(map) do {:ok, Map.get(map, "config", [])} end defp extrace_farmware_tools_version(%{"farmware_tools_version" => version}) do {:ok, version} end defp extrace_farmware_tools_version(_) do {:ok, "v0.1.0"} end defp extract_meta(map) do desc = Map.get(map, "description", "no description provided.") lan = Map.get(map, "language", "no language provided.") auth = Map.get(map, "author", "no author provided") {:ok, struct(Meta, description: desc, language: lan, author: auth)} end end
lib/farmbot/farmware/farmware.ex
0.863536
0.590071
farmware.ex
starcoder
defmodule ExIsbndb.Book do @moduledoc """ The `ExIsbndb.Book` module contains all the available endpoints for Books. All functions need to receive a map with params, but only those needed for the endpoint will be taken. """ alias ExIsbndb.Client @valid_column_values ["", "title", "author", "date_published"] @doc """ Returns an instance of Book Params required: * isbn (string) - string representing the isbn to search Params available: * with_prices (integer): 1 being true or 0 being false ## Examples iex> ExIsbndb.Book.get(%{isbn: "1234567789", with_prices: 0) {:ok, %Finch.Response{body: "...", headers: [...], status: 200}} """ @spec get(map()) :: {:ok, Finch.Response.t()} | {:error, Exception.t()} def get(%{isbn: isbn} = params) when is_binary(isbn) do params = %{with_prices: Map.get(params, :with_prices, 0)} Client.request(:get, "book/#{URI.encode(isbn)}", params) end @doc """ Returns all the Books that match the given query. Params required: * query (string) - string used to search Params available: * page (integer) - page number of the Books to be searched * page_size (integer) - number of Books to be searched per page * column(string) - Search limited to this column with values: ['', title, author, date_published] Any other parameters will be ignored. ## Examples iex> ExIsbndb.Book.search(%{query: "Stormlight", page: 1, page_size: 5, column: ""}) {:ok, %Finch.Response{body: "...", headers: [...], status: 200}} """ @spec search(map()) :: {:ok, Finch.Response.t()} | {:error, Exception.t()} def search(%{query: query} = params) when is_binary(query) do params = %{ page: params[:page], pageSize: params[:page_size], column: validate_column(params[:column]) } Client.request(:get, "books/#{URI.encode(query)}", params) end @doc """ This returns a list of books that match the query. Only with the Premium and Pro plans and can only send up to 1,000 ISBN numbers per request. ## Examples iex> ExIsbndb.Book.get_by_isbns(["123456789", "987654321"]) {:ok, %Finch.Response{body: "...", headers: [...], status: 200}} """ @spec search(list()) :: {:ok, Finch.Response.t()} | {:error, Exception.t()} def get_by_isbns(isbns) when is_list(isbns) do Client.request(:post, "books", %{isbns: isbns}) end ### PRIV defp validate_column(col) when col in @valid_column_values, do: col defp validate_column(_), do: "" end
lib/book.ex
0.894424
0.643182
book.ex
starcoder
defmodule Pbkdf2.Base do @moduledoc """ Base module for the Pbkdf2 password hashing library. """ use Bitwise alias Pbkdf2.{Base64, Tools} @max_length bsl(1, 32) - 1 @deprecated "Use Pbkdf2.gen_salt/1 (with `format: :django`) instead" def django_salt(len) do Tools.get_random_string(len) end @doc """ Hash a password using Pbkdf2. ## Options There are four options (rounds can be used to override the value in the config): * `:rounds` - the number of rounds * the amount of computation, given in number of iterations * the default is 160_000 * this can also be set in the config file * `:format` - the output format of the hash * the default is `:modular` - modular crypt format * the other available formats are: * `:django` - the format used in django applications * `:hex` - the hash is encoded in hexadecimal * `:digest` - the sha algorithm that pbkdf2 will use * the default is sha512 * `:length` - the length, in bytes, of the hash * the default is 64 for sha512 and 32 for sha256 """ @spec hash_password(binary, binary, keyword) :: binary def hash_password(password, salt, opts \\ []) do Tools.check_salt_length(byte_size(salt)) {rounds, output_fmt, {digest, length}} = get_opts(opts) if length > @max_length do raise ArgumentError, "length must be equal to or less than #{@max_length}" end password |> create_hash(salt, digest, rounds, length) |> format(salt, digest, rounds, output_fmt) end @doc """ Verify a password by comparing it with the stored Pbkdf2 hash. """ @spec verify_pass(binary, binary, binary, atom, binary, atom) :: boolean def verify_pass(password, hash, salt, digest, rounds, output_fmt) do {salt, length} = case output_fmt do :modular -> {Base64.decode(salt), byte_size(Base64.decode(hash))} :django -> {salt, byte_size(Base.decode64!(hash))} :hex -> {salt, byte_size(Base.decode16!(hash, case: :lower))} end password |> create_hash(salt, digest, String.to_integer(rounds), length) |> encode(output_fmt) |> Tools.secure_check(hash) end defp get_opts(opts) do { Keyword.get(opts, :rounds, Application.get_env(:pbkdf2_elixir, :rounds, 160_000)), Keyword.get(opts, :format, :modular), case opts[:digest] do :sha -> {:sha, opts[:length] || 16} :sha256 -> {:sha256, opts[:length] || 32} _ -> {:sha512, opts[:length] || 64} end } end defp create_hash(password, salt, digest, rounds, length) do digest |> hmac_fun(password) |> do_create_hash(salt, rounds, length, 1, [], 0) end defp do_create_hash(_fun, _salt, _rounds, dklen, _block_index, acc, length) when length >= dklen do key = acc |> Enum.reverse() |> IO.iodata_to_binary() <<bin::binary-size(dklen), _::binary>> = key bin end defp do_create_hash(fun, salt, rounds, dklen, block_index, acc, length) do initial = fun.(<<salt::binary, block_index::integer-size(32)>>) block = iterate(fun, rounds - 1, initial, initial) do_create_hash( fun, salt, rounds, dklen, block_index + 1, [block | acc], byte_size(block) + length ) end defp iterate(_fun, 0, _prev, acc), do: acc defp iterate(fun, round, prev, acc) do next = fun.(prev) iterate(fun, round - 1, next, :crypto.exor(next, acc)) end defp format(hash, salt, digest, rounds, :modular) do "$pbkdf2-#{digest}$#{rounds}$#{Base64.encode(salt)}$#{Base64.encode(hash)}" end defp format(hash, salt, digest, rounds, :django) do "pbkdf2_#{digest}$#{rounds}$#{salt}$#{Base.encode64(hash)}" end defp format(hash, _salt, _digest, _rounds, :hex), do: Base.encode16(hash, case: :lower) defp encode(hash, :modular), do: Base64.encode(hash) defp encode(hash, :django), do: Base.encode64(hash) defp encode(hash, :hex), do: Base.encode16(hash, case: :lower) if System.otp_release() >= "22" do defp hmac_fun(digest, key), do: &:crypto.mac(:hmac, digest, key, &1) else defp hmac_fun(digest, key), do: &:crypto.hmac(digest, key, &1) end end
lib/pbkdf2/base.ex
0.87185
0.472623
base.ex
starcoder
defmodule AWS.QuickSight do @moduledoc """ Amazon QuickSight API Reference Amazon QuickSight is a fully managed, serverless business intelligence service for the AWS Cloud that makes it easy to extend data and insights to every user in your organization. This API reference contains documentation for a programming interface that you can use to manage Amazon QuickSight. """ @doc """ Cancels an ongoing ingestion of data into SPICE. """ def cancel_ingestion(client, aws_account_id, data_set_id, ingestion_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/data-sets/#{URI.encode(data_set_id)}/ingestions/#{URI.encode(ingestion_id)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, nil) end @doc """ Creates Amazon QuickSight customizations the current AWS Region. Currently, you can add a custom default theme by using the `CreateAccountCustomization` or `UpdateAccountCustomization` API operation. To further customize QuickSight by removing QuickSight sample assets and videos for all new users, see [Customizing QuickSight](https://docs.aws.amazon.com/quicksight/latest/user/customizing-quicksight.html) in the *Amazon QuickSight User Guide.* You can create customizations for your AWS account or, if you specify a namespace, for a QuickSight namespace instead. Customizations that apply to a namespace always override customizations that apply to an AWS account. To find out which customizations apply, use the `DescribeAccountCustomization` API operation. Before you use the `CreateAccountCustomization` API operation to add a theme as the namespace default, make sure that you first share the theme with the namespace. If you don't share it with the namespace, the theme isn't visible to your users even if you make it the default theme. To check if the theme is shared, view the current permissions by using the ` `DescribeThemePermissions` ` API operation. To share the theme, grant permissions by using the ` `UpdateThemePermissions` ` API operation. """ def create_account_customization(client, aws_account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/customizations" headers = [] {query_, input} = [ {"Namespace", "namespace"}, ] |> AWS.Request.build_params(input) request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Creates an analysis in Amazon QuickSight. """ def create_analysis(client, analysis_id, aws_account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/analyses/#{URI.encode(analysis_id)}" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Creates a dashboard from a template. To first create a template, see the ` `CreateTemplate` ` API operation. A dashboard is an entity in QuickSight that identifies QuickSight reports, created from analyses. You can share QuickSight dashboards. With the right permissions, you can create scheduled email reports from them. If you have the correct permissions, you can create a dashboard from a template that exists in a different AWS account. """ def create_dashboard(client, aws_account_id, dashboard_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/dashboards/#{URI.encode(dashboard_id)}" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Creates a dataset. """ def create_data_set(client, aws_account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/data-sets" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Creates a data source. """ def create_data_source(client, aws_account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/data-sources" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Creates an Amazon QuickSight group. The permissions resource is `arn:aws:quicksight:us-east-1:*<relevant-aws-account-id>*:group/default/*<group-name>* `. The response is a group object. """ def create_group(client, aws_account_id, namespace, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces/#{URI.encode(namespace)}/groups" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Adds an Amazon QuickSight user to an Amazon QuickSight group. """ def create_group_membership(client, aws_account_id, group_name, member_name, namespace, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces/#{URI.encode(namespace)}/groups/#{URI.encode(group_name)}/members/#{URI.encode(member_name)}" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, nil) end @doc """ Creates an assignment with one specified IAM policy, identified by its Amazon Resource Name (ARN). This policy will be assigned to specified groups or users of Amazon QuickSight. The users and groups need to be in the same namespace. """ def create_i_a_m_policy_assignment(client, aws_account_id, namespace, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces/#{URI.encode(namespace)}/iam-policy-assignments/" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Creates and starts a new SPICE ingestion on a dataset Any ingestions operating on tagged datasets inherit the same tags automatically for use in access control. For an example, see [How do I create an IAM policy to control access to Amazon EC2 resources using tags?](https://aws.amazon.com/premiumsupport/knowledge-center/iam-ec2-resource-tags/) in the AWS Knowledge Center. Tags are visible on the tagged dataset, but not on the ingestion resource. """ def create_ingestion(client, aws_account_id, data_set_id, ingestion_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/data-sets/#{URI.encode(data_set_id)}/ingestions/#{URI.encode(ingestion_id)}" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, nil) end @doc """ (Enterprise edition only) Creates a new namespace for you to use with Amazon QuickSight. A namespace allows you to isolate the QuickSight users and groups that are registered for that namespace. Users that access the namespace can share assets only with other users or groups in the same namespace. They can't see users and groups in other namespaces. You can create a namespace after your AWS account is subscribed to QuickSight. The namespace must be unique within the AWS account. By default, there is a limit of 100 namespaces per AWS account. To increase your limit, create a ticket with AWS Support. """ def create_namespace(client, aws_account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Creates a template from an existing QuickSight analysis or template. You can use the resulting template to create a dashboard. A *template* is an entity in QuickSight that encapsulates the metadata required to create an analysis and that you can use to create s dashboard. A template adds a layer of abstraction by using placeholders to replace the dataset associated with the analysis. You can use templates to create dashboards by replacing dataset placeholders with datasets that follow the same schema that was used to create the source analysis and template. """ def create_template(client, aws_account_id, template_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/templates/#{URI.encode(template_id)}" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Creates a template alias for a template. """ def create_template_alias(client, alias_name, aws_account_id, template_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/templates/#{URI.encode(template_id)}/aliases/#{URI.encode(alias_name)}" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Creates a theme. A *theme* is set of configuration options for color and layout. Themes apply to analyses and dashboards. For more information, see [Using Themes in Amazon QuickSight](https://docs.aws.amazon.com/quicksight/latest/user/themes-in-quicksight.html) in the *Amazon QuickSight User Guide*. """ def create_theme(client, aws_account_id, theme_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/themes/#{URI.encode(theme_id)}" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Creates a theme alias for a theme. """ def create_theme_alias(client, alias_name, aws_account_id, theme_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/themes/#{URI.encode(theme_id)}/aliases/#{URI.encode(alias_name)}" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Deletes all Amazon QuickSight customizations in this AWS Region for the specified AWS account and QuickSight namespace. """ def delete_account_customization(client, aws_account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/customizations" headers = [] {query_, input} = [ {"Namespace", "namespace"}, ] |> AWS.Request.build_params(input) request(client, :delete, path_, query_, headers, input, options, nil) end @doc """ Deletes an analysis from Amazon QuickSight. You can optionally include a recovery window during which you can restore the analysis. If you don't specify a recovery window value, the operation defaults to 30 days. QuickSight attaches a `DeletionTime` stamp to the response that specifies the end of the recovery window. At the end of the recovery window, QuickSight deletes the analysis permanently. At any time before recovery window ends, you can use the `RestoreAnalysis` API operation to remove the `DeletionTime` stamp and cancel the deletion of the analysis. The analysis remains visible in the API until it's deleted, so you can describe it but you can't make a template from it. An analysis that's scheduled for deletion isn't accessible in the QuickSight console. To access it in the console, restore it. Deleting an analysis doesn't delete the dashboards that you publish from it. """ def delete_analysis(client, analysis_id, aws_account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/analyses/#{URI.encode(analysis_id)}" headers = [] {query_, input} = [ {"ForceDeleteWithoutRecovery", "force-delete-without-recovery"}, {"RecoveryWindowInDays", "recovery-window-in-days"}, ] |> AWS.Request.build_params(input) request(client, :delete, path_, query_, headers, input, options, nil) end @doc """ Deletes a dashboard. """ def delete_dashboard(client, aws_account_id, dashboard_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/dashboards/#{URI.encode(dashboard_id)}" headers = [] {query_, input} = [ {"VersionNumber", "version-number"}, ] |> AWS.Request.build_params(input) request(client, :delete, path_, query_, headers, input, options, nil) end @doc """ Deletes a dataset. """ def delete_data_set(client, aws_account_id, data_set_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/data-sets/#{URI.encode(data_set_id)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, nil) end @doc """ Deletes the data source permanently. This operation breaks all the datasets that reference the deleted data source. """ def delete_data_source(client, aws_account_id, data_source_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/data-sources/#{URI.encode(data_source_id)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, nil) end @doc """ Removes a user group from Amazon QuickSight. """ def delete_group(client, aws_account_id, group_name, namespace, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces/#{URI.encode(namespace)}/groups/#{URI.encode(group_name)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, nil) end @doc """ Removes a user from a group so that the user is no longer a member of the group. """ def delete_group_membership(client, aws_account_id, group_name, member_name, namespace, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces/#{URI.encode(namespace)}/groups/#{URI.encode(group_name)}/members/#{URI.encode(member_name)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, nil) end @doc """ Deletes an existing IAM policy assignment. """ def delete_i_a_m_policy_assignment(client, assignment_name, aws_account_id, namespace, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespace/#{URI.encode(namespace)}/iam-policy-assignments/#{URI.encode(assignment_name)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, nil) end @doc """ Deletes a namespace and the users and groups that are associated with the namespace. This is an asynchronous process. Assets including dashboards, analyses, datasets and data sources are not deleted. To delete these assets, you use the API operations for the relevant asset. """ def delete_namespace(client, aws_account_id, namespace, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces/#{URI.encode(namespace)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, nil) end @doc """ Deletes a template. """ def delete_template(client, aws_account_id, template_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/templates/#{URI.encode(template_id)}" headers = [] {query_, input} = [ {"VersionNumber", "version-number"}, ] |> AWS.Request.build_params(input) request(client, :delete, path_, query_, headers, input, options, nil) end @doc """ Deletes the item that the specified template alias points to. If you provide a specific alias, you delete the version of the template that the alias points to. """ def delete_template_alias(client, alias_name, aws_account_id, template_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/templates/#{URI.encode(template_id)}/aliases/#{URI.encode(alias_name)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, nil) end @doc """ Deletes a theme. """ def delete_theme(client, aws_account_id, theme_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/themes/#{URI.encode(theme_id)}" headers = [] {query_, input} = [ {"VersionNumber", "version-number"}, ] |> AWS.Request.build_params(input) request(client, :delete, path_, query_, headers, input, options, nil) end @doc """ Deletes the version of the theme that the specified theme alias points to. If you provide a specific alias, you delete the version of the theme that the alias points to. """ def delete_theme_alias(client, alias_name, aws_account_id, theme_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/themes/#{URI.encode(theme_id)}/aliases/#{URI.encode(alias_name)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, nil) end @doc """ Deletes the Amazon QuickSight user that is associated with the identity of the AWS Identity and Access Management (IAM) user or role that's making the call. The IAM user isn't deleted as a result of this call. """ def delete_user(client, aws_account_id, namespace, user_name, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces/#{URI.encode(namespace)}/users/#{URI.encode(user_name)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, nil) end @doc """ Deletes a user identified by its principal ID. """ def delete_user_by_principal_id(client, aws_account_id, namespace, principal_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces/#{URI.encode(namespace)}/user-principals/#{URI.encode(principal_id)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, nil) end @doc """ Describes the customizations associated with the provided AWS account and Amazon QuickSight namespace in an AWS Region. The QuickSight console evaluates which customizations to apply by running this API operation with the `Resolved` flag included. To determine what customizations display when you run this command, it can help to visualize the relationship of the entities involved. * `AWS Account` - The AWS account exists at the top of the hierarchy. It has the potential to use all of the AWS Regions and AWS Services. When you subscribe to QuickSight, you choose one AWS Region to use as your home Region. That's where your free SPICE capacity is located. You can use QuickSight in any supported AWS Region. * `AWS Region` - In each AWS Region where you sign in to QuickSight at least once, QuickSight acts as a separate instance of the same service. If you have a user directory, it resides in us-east-1, which is the US East (N. Virginia). Generally speaking, these users have access to QuickSight in any AWS Region, unless they are constrained to a namespace. To run the command in a different AWS Region, you change your Region settings. If you're using the AWS CLI, you can use one of the following options: * Use [command line options](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-options.html). * Use [named profiles](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html). * Run `aws configure` to change your default AWS Region. Use Enter to key the same settings for your keys. For more information, see [Configuring the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html). * `Namespace` - A QuickSight namespace is a partition that contains users and assets (data sources, datasets, dashboards, and so on). To access assets that are in a specific namespace, users and groups must also be part of the same namespace. People who share a namespace are completely isolated from users and assets in other namespaces, even if they are in the same AWS account and AWS Region. * `Applied customizations` - Within an AWS Region, a set of QuickSight customizations can apply to an AWS account or to a namespace. Settings that you apply to a namespace override settings that you apply to an AWS account. All settings are isolated to a single AWS Region. To apply them in other AWS Regions, run the `CreateAccountCustomization` command in each AWS Region where you want to apply the same customizations. """ def describe_account_customization(client, aws_account_id, namespace \\ nil, resolved \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/customizations" headers = [] query_ = [] query_ = if !is_nil(resolved) do [{"resolved", resolved} | query_] else query_ end query_ = if !is_nil(namespace) do [{"namespace", namespace} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Describes the settings that were used when your QuickSight subscription was first created in this AWS account. """ def describe_account_settings(client, aws_account_id, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/settings" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Provides a summary of the metadata for an analysis. """ def describe_analysis(client, analysis_id, aws_account_id, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/analyses/#{URI.encode(analysis_id)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Provides the read and write permissions for an analysis. """ def describe_analysis_permissions(client, analysis_id, aws_account_id, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/analyses/#{URI.encode(analysis_id)}/permissions" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Provides a summary for a dashboard. """ def describe_dashboard(client, aws_account_id, dashboard_id, alias_name \\ nil, version_number \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/dashboards/#{URI.encode(dashboard_id)}" headers = [] query_ = [] query_ = if !is_nil(version_number) do [{"version-number", version_number} | query_] else query_ end query_ = if !is_nil(alias_name) do [{"alias-name", alias_name} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Describes read and write permissions for a dashboard. """ def describe_dashboard_permissions(client, aws_account_id, dashboard_id, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/dashboards/#{URI.encode(dashboard_id)}/permissions" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Describes a dataset. """ def describe_data_set(client, aws_account_id, data_set_id, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/data-sets/#{URI.encode(data_set_id)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Describes the permissions on a dataset. The permissions resource is `arn:aws:quicksight:region:aws-account-id:dataset/data-set-id`. """ def describe_data_set_permissions(client, aws_account_id, data_set_id, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/data-sets/#{URI.encode(data_set_id)}/permissions" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Describes a data source. """ def describe_data_source(client, aws_account_id, data_source_id, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/data-sources/#{URI.encode(data_source_id)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Describes the resource permissions for a data source. """ def describe_data_source_permissions(client, aws_account_id, data_source_id, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/data-sources/#{URI.encode(data_source_id)}/permissions" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Returns an Amazon QuickSight group's description and Amazon Resource Name (ARN). """ def describe_group(client, aws_account_id, group_name, namespace, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces/#{URI.encode(namespace)}/groups/#{URI.encode(group_name)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Describes an existing IAM policy assignment, as specified by the assignment name. """ def describe_i_a_m_policy_assignment(client, assignment_name, aws_account_id, namespace, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces/#{URI.encode(namespace)}/iam-policy-assignments/#{URI.encode(assignment_name)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Describes a SPICE ingestion. """ def describe_ingestion(client, aws_account_id, data_set_id, ingestion_id, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/data-sets/#{URI.encode(data_set_id)}/ingestions/#{URI.encode(ingestion_id)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Describes the current namespace. """ def describe_namespace(client, aws_account_id, namespace, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces/#{URI.encode(namespace)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Describes a template's metadata. """ def describe_template(client, aws_account_id, template_id, alias_name \\ nil, version_number \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/templates/#{URI.encode(template_id)}" headers = [] query_ = [] query_ = if !is_nil(version_number) do [{"version-number", version_number} | query_] else query_ end query_ = if !is_nil(alias_name) do [{"alias-name", alias_name} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Describes the template alias for a template. """ def describe_template_alias(client, alias_name, aws_account_id, template_id, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/templates/#{URI.encode(template_id)}/aliases/#{URI.encode(alias_name)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Describes read and write permissions on a template. """ def describe_template_permissions(client, aws_account_id, template_id, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/templates/#{URI.encode(template_id)}/permissions" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Describes a theme. """ def describe_theme(client, aws_account_id, theme_id, alias_name \\ nil, version_number \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/themes/#{URI.encode(theme_id)}" headers = [] query_ = [] query_ = if !is_nil(version_number) do [{"version-number", version_number} | query_] else query_ end query_ = if !is_nil(alias_name) do [{"alias-name", alias_name} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Describes the alias for a theme. """ def describe_theme_alias(client, alias_name, aws_account_id, theme_id, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/themes/#{URI.encode(theme_id)}/aliases/#{URI.encode(alias_name)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Describes the read and write permissions for a theme. """ def describe_theme_permissions(client, aws_account_id, theme_id, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/themes/#{URI.encode(theme_id)}/permissions" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Returns information about a user, given the user name. """ def describe_user(client, aws_account_id, namespace, user_name, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces/#{URI.encode(namespace)}/users/#{URI.encode(user_name)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Generates a session URL and authorization code that you can use to embed an Amazon QuickSight read-only dashboard in your web server code. Before you use this command, make sure that you have configured the dashboards and permissions. Currently, you can use `GetDashboardEmbedURL` only from the server, not from the user's browser. The following rules apply to the combination of URL and authorization code: * They must be used together. * They can be used one time only. * They are valid for 5 minutes after you run this command. * The resulting user session is valid for 10 hours. For more information, see [Embedding Amazon QuickSight](https://docs.aws.amazon.com/quicksight/latest/user/embedding-dashboards.html) in the *Amazon QuickSight User Guide* . """ def get_dashboard_embed_url(client, aws_account_id, dashboard_id, identity_type, reset_disabled \\ nil, session_lifetime_in_minutes \\ nil, undo_redo_disabled \\ nil, user_arn \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/dashboards/#{URI.encode(dashboard_id)}/embed-url" headers = [] query_ = [] query_ = if !is_nil(user_arn) do [{"user-arn", user_arn} | query_] else query_ end query_ = if !is_nil(undo_redo_disabled) do [{"undo-redo-disabled", undo_redo_disabled} | query_] else query_ end query_ = if !is_nil(session_lifetime_in_minutes) do [{"session-lifetime", session_lifetime_in_minutes} | query_] else query_ end query_ = if !is_nil(reset_disabled) do [{"reset-disabled", reset_disabled} | query_] else query_ end query_ = if !is_nil(identity_type) do [{"creds-type", identity_type} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Generates a session URL and authorization code that you can use to embed the Amazon QuickSight console in your web server code. Use `GetSessionEmbedUrl` where you want to provide an authoring portal that allows users to create data sources, datasets, analyses, and dashboards. The users who access an embedded QuickSight console need belong to the author or admin security cohort. If you want to restrict permissions to some of these features, add a custom permissions profile to the user with the ` `UpdateUser` ` API operation. Use ` `RegisterUser` ` API operation to add a new user with a custom permission profile attached. For more information, see the following sections in the *Amazon QuickSight User Guide*: * [Embedding the Amazon QuickSight Console](https://docs.aws.amazon.com/quicksight/latest/user/embedding-the-quicksight-console.html) * [Customizing Access to the Amazon QuickSight Console](https://docs.aws.amazon.com/quicksight/latest/user/customizing-permissions-to-the-quicksight-console.html) """ def get_session_embed_url(client, aws_account_id, entry_point \\ nil, session_lifetime_in_minutes \\ nil, user_arn \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/session-embed-url" headers = [] query_ = [] query_ = if !is_nil(user_arn) do [{"user-arn", user_arn} | query_] else query_ end query_ = if !is_nil(session_lifetime_in_minutes) do [{"session-lifetime", session_lifetime_in_minutes} | query_] else query_ end query_ = if !is_nil(entry_point) do [{"entry-point", entry_point} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists Amazon QuickSight analyses that exist in the specified AWS account. """ def list_analyses(client, aws_account_id, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/analyses" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"next-token", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"max-results", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists all the versions of the dashboards in the QuickSight subscription. """ def list_dashboard_versions(client, aws_account_id, dashboard_id, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/dashboards/#{URI.encode(dashboard_id)}/versions" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"next-token", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"max-results", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists dashboards in an AWS account. """ def list_dashboards(client, aws_account_id, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/dashboards" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"next-token", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"max-results", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists all of the datasets belonging to the current AWS account in an AWS Region. The permissions resource is `arn:aws:quicksight:region:aws-account-id:dataset/*`. """ def list_data_sets(client, aws_account_id, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/data-sets" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"next-token", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"max-results", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists data sources in current AWS Region that belong to this AWS account. """ def list_data_sources(client, aws_account_id, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/data-sources" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"next-token", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"max-results", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists member users in a group. """ def list_group_memberships(client, aws_account_id, group_name, namespace, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces/#{URI.encode(namespace)}/groups/#{URI.encode(group_name)}/members" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"next-token", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"max-results", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists all user groups in Amazon QuickSight. """ def list_groups(client, aws_account_id, namespace, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces/#{URI.encode(namespace)}/groups" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"next-token", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"max-results", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists IAM policy assignments in the current Amazon QuickSight account. """ def list_i_a_m_policy_assignments(client, aws_account_id, namespace, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces/#{URI.encode(namespace)}/iam-policy-assignments" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"next-token", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"max-results", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists all the IAM policy assignments, including the Amazon Resource Names (ARNs) for the IAM policies assigned to the specified user and group or groups that the user belongs to. """ def list_i_a_m_policy_assignments_for_user(client, aws_account_id, namespace, user_name, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces/#{URI.encode(namespace)}/users/#{URI.encode(user_name)}/iam-policy-assignments" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"next-token", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"max-results", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists the history of SPICE ingestions for a dataset. """ def list_ingestions(client, aws_account_id, data_set_id, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/data-sets/#{URI.encode(data_set_id)}/ingestions" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"next-token", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"max-results", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists the namespaces for the specified AWS account. """ def list_namespaces(client, aws_account_id, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"next-token", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"max-results", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists the tags assigned to a resource. """ def list_tags_for_resource(client, resource_arn, options \\ []) do path_ = "/resources/#{URI.encode(resource_arn)}/tags" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists all the aliases of a template. """ def list_template_aliases(client, aws_account_id, template_id, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/templates/#{URI.encode(template_id)}/aliases" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"next-token", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"max-result", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists all the versions of the templates in the current Amazon QuickSight account. """ def list_template_versions(client, aws_account_id, template_id, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/templates/#{URI.encode(template_id)}/versions" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"next-token", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"max-results", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists all the templates in the current Amazon QuickSight account. """ def list_templates(client, aws_account_id, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/templates" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"next-token", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"max-result", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists all the aliases of a theme. """ def list_theme_aliases(client, aws_account_id, theme_id, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/themes/#{URI.encode(theme_id)}/aliases" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"next-token", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"max-result", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists all the versions of the themes in the current AWS account. """ def list_theme_versions(client, aws_account_id, theme_id, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/themes/#{URI.encode(theme_id)}/versions" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"next-token", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"max-results", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists all the themes in the current AWS account. """ def list_themes(client, aws_account_id, max_results \\ nil, next_token \\ nil, type \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/themes" headers = [] query_ = [] query_ = if !is_nil(type) do [{"type", type} | query_] else query_ end query_ = if !is_nil(next_token) do [{"next-token", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"max-results", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists the Amazon QuickSight groups that an Amazon QuickSight user is a member of. """ def list_user_groups(client, aws_account_id, namespace, user_name, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces/#{URI.encode(namespace)}/users/#{URI.encode(user_name)}/groups" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"next-token", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"max-results", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Returns a list of all of the Amazon QuickSight users belonging to this account. """ def list_users(client, aws_account_id, namespace, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces/#{URI.encode(namespace)}/users" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"next-token", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"max-results", max_results} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Creates an Amazon QuickSight user, whose identity is associated with the AWS Identity and Access Management (IAM) identity or role specified in the request. """ def register_user(client, aws_account_id, namespace, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces/#{URI.encode(namespace)}/users" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Restores an analysis. """ def restore_analysis(client, analysis_id, aws_account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/restore/analyses/#{URI.encode(analysis_id)}" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Searches for analyses that belong to the user specified in the filter. """ def search_analyses(client, aws_account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/search/analyses" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Searches for dashboards that belong to a user. """ def search_dashboards(client, aws_account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/search/dashboards" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Assigns one or more tags (key-value pairs) to the specified QuickSight resource. Tags can help you organize and categorize your resources. You can also use them to scope user permissions, by granting a user permission to access or change only resources with certain tag values. You can use the `TagResource` operation with a resource that already has tags. If you specify a new tag key for the resource, this tag is appended to the list of tags associated with the resource. If you specify a tag key that is already associated with the resource, the new tag value that you specify replaces the previous value for that tag. You can associate as many as 50 tags with a resource. QuickSight supports tagging on data set, data source, dashboard, and template. Tagging for QuickSight works in a similar way to tagging for other AWS services, except for the following: * You can't use tags to track AWS costs for QuickSight. This restriction is because QuickSight costs are based on users and SPICE capacity, which aren't taggable resources. * QuickSight doesn't currently support the Tag Editor for AWS Resource Groups. """ def tag_resource(client, resource_arn, input, options \\ []) do path_ = "/resources/#{URI.encode(resource_arn)}/tags" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Removes a tag or tags from a resource. """ def untag_resource(client, resource_arn, input, options \\ []) do path_ = "/resources/#{URI.encode(resource_arn)}/tags" headers = [] {query_, input} = [ {"TagKeys", "keys"}, ] |> AWS.Request.build_params(input) request(client, :delete, path_, query_, headers, input, options, nil) end @doc """ Updates Amazon QuickSight customizations the current AWS Region. Currently, the only customization you can use is a theme. You can use customizations for your AWS account or, if you specify a namespace, for a QuickSight namespace instead. Customizations that apply to a namespace override customizations that apply to an AWS account. To find out which customizations apply, use the `DescribeAccountCustomization` API operation. """ def update_account_customization(client, aws_account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/customizations" headers = [] {query_, input} = [ {"Namespace", "namespace"}, ] |> AWS.Request.build_params(input) request(client, :put, path_, query_, headers, input, options, nil) end @doc """ Updates the Amazon QuickSight settings in your AWS account. """ def update_account_settings(client, aws_account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/settings" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, nil) end @doc """ Updates an analysis in Amazon QuickSight """ def update_analysis(client, analysis_id, aws_account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/analyses/#{URI.encode(analysis_id)}" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, nil) end @doc """ Updates the read and write permissions for an analysis. """ def update_analysis_permissions(client, analysis_id, aws_account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/analyses/#{URI.encode(analysis_id)}/permissions" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, nil) end @doc """ Updates a dashboard in an AWS account. """ def update_dashboard(client, aws_account_id, dashboard_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/dashboards/#{URI.encode(dashboard_id)}" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, nil) end @doc """ Updates read and write permissions on a dashboard. """ def update_dashboard_permissions(client, aws_account_id, dashboard_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/dashboards/#{URI.encode(dashboard_id)}/permissions" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, nil) end @doc """ Updates the published version of a dashboard. """ def update_dashboard_published_version(client, aws_account_id, dashboard_id, version_number, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/dashboards/#{URI.encode(dashboard_id)}/versions/#{URI.encode(version_number)}" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, nil) end @doc """ Updates a dataset. """ def update_data_set(client, aws_account_id, data_set_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/data-sets/#{URI.encode(data_set_id)}" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, nil) end @doc """ Updates the permissions on a dataset. The permissions resource is `arn:aws:quicksight:region:aws-account-id:dataset/data-set-id`. """ def update_data_set_permissions(client, aws_account_id, data_set_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/data-sets/#{URI.encode(data_set_id)}/permissions" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Updates a data source. """ def update_data_source(client, aws_account_id, data_source_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/data-sources/#{URI.encode(data_source_id)}" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, nil) end @doc """ Updates the permissions to a data source. """ def update_data_source_permissions(client, aws_account_id, data_source_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/data-sources/#{URI.encode(data_source_id)}/permissions" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Changes a group description. """ def update_group(client, aws_account_id, group_name, namespace, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces/#{URI.encode(namespace)}/groups/#{URI.encode(group_name)}" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, nil) end @doc """ Updates an existing IAM policy assignment. This operation updates only the optional parameter or parameters that are specified in the request. """ def update_i_a_m_policy_assignment(client, assignment_name, aws_account_id, namespace, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces/#{URI.encode(namespace)}/iam-policy-assignments/#{URI.encode(assignment_name)}" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, nil) end @doc """ Updates a template from an existing Amazon QuickSight analysis or another template. """ def update_template(client, aws_account_id, template_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/templates/#{URI.encode(template_id)}" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, nil) end @doc """ Updates the template alias of a template. """ def update_template_alias(client, alias_name, aws_account_id, template_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/templates/#{URI.encode(template_id)}/aliases/#{URI.encode(alias_name)}" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, nil) end @doc """ Updates the resource permissions for a template. """ def update_template_permissions(client, aws_account_id, template_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/templates/#{URI.encode(template_id)}/permissions" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, nil) end @doc """ Updates a theme. """ def update_theme(client, aws_account_id, theme_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/themes/#{URI.encode(theme_id)}" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, nil) end @doc """ Updates an alias of a theme. """ def update_theme_alias(client, alias_name, aws_account_id, theme_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/themes/#{URI.encode(theme_id)}/aliases/#{URI.encode(alias_name)}" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, nil) end @doc """ Updates the resource permissions for a theme. Permissions apply to the action to grant or revoke permissions on, for example `"quicksight:DescribeTheme"`. Theme permissions apply in groupings. Valid groupings include the following for the three levels of permissions, which are user, owner, or no permissions: * User * `"quicksight:DescribeTheme"` * `"quicksight:DescribeThemeAlias"` * `"quicksight:ListThemeAliases"` * `"quicksight:ListThemeVersions"` * Owner * `"quicksight:DescribeTheme"` * `"quicksight:DescribeThemeAlias"` * `"quicksight:ListThemeAliases"` * `"quicksight:ListThemeVersions"` * `"quicksight:DeleteTheme"` * `"quicksight:UpdateTheme"` * `"quicksight:CreateThemeAlias"` * `"quicksight:DeleteThemeAlias"` * `"quicksight:UpdateThemeAlias"` * `"quicksight:UpdateThemePermissions"` * `"quicksight:DescribeThemePermissions"` * To specify no permissions, omit the permissions list. """ def update_theme_permissions(client, aws_account_id, theme_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/themes/#{URI.encode(theme_id)}/permissions" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, nil) end @doc """ Updates an Amazon QuickSight user. """ def update_user(client, aws_account_id, namespace, user_name, input, options \\ []) do path_ = "/accounts/#{URI.encode(aws_account_id)}/namespaces/#{URI.encode(namespace)}/users/#{URI.encode(user_name)}" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, nil) end @spec request(AWS.Client.t(), binary(), binary(), list(), list(), map(), list(), pos_integer()) :: {:ok, map() | nil, map()} | {:error, term()} defp request(client, method, path, query, headers, input, options, success_status_code) do client = %{client | service: "quicksight"} host = build_host("quicksight", client) url = host |> build_url(path, client) |> add_query(query, client) additional_headers = [{"Host", host}, {"Content-Type", "application/x-amz-json-1.1"}] headers = AWS.Request.add_headers(additional_headers, headers) payload = encode!(client, input) headers = AWS.Request.sign_v4(client, method, url, headers, payload) perform_request(client, method, url, payload, headers, options, success_status_code) end defp perform_request(client, method, url, payload, headers, options, success_status_code) do case AWS.Client.request(client, method, url, payload, headers, options) do {:ok, %{status_code: status_code, body: body} = response} when is_nil(success_status_code) and status_code in [200, 202, 204] when status_code == success_status_code -> body = if(body != "", do: decode!(client, body)) {:ok, body, response} {:ok, response} -> {:error, {:unexpected_response, response}} error = {:error, _reason} -> error end end defp build_host(_endpoint_prefix, %{region: "local", endpoint: endpoint}) do endpoint end defp build_host(_endpoint_prefix, %{region: "local"}) do "localhost" end defp build_host(endpoint_prefix, %{region: region, endpoint: endpoint}) do "#{endpoint_prefix}.#{region}.#{endpoint}" end defp build_url(host, path, %{:proto => proto, :port => port}) do "#{proto}://#{host}:#{port}#{path}" end defp add_query(url, [], _client) do url end defp add_query(url, query, client) do querystring = encode!(client, query, :query) "#{url}?#{querystring}" end defp encode!(client, payload, format \\ :json) do AWS.Client.encode!(client, payload, format) end defp decode!(client, payload) do AWS.Client.decode!(client, payload, :json) end end
lib/aws/generated/quick_sight.ex
0.835416
0.455562
quick_sight.ex
starcoder
defmodule Ada.Email.Quickchart do @moduledoc """ Minimal DSL and functions to create image charts via <https://quickchart.io>. Doesn't support all api options (yet). """ @default_width 516 @default_height 300 @base_url "https://quickchart.io/chart" defstruct type: "bar", width: @default_width, height: @default_height, data: %{labels: [], datasets: []} @type chart_type :: String.t() @type label :: String.t() @type dimension :: pos_integer() @type data :: [number()] @type dataset :: %{label: label(), data: data()} @type t :: %__MODULE__{ type: chart_type(), width: dimension(), height: dimension(), data: %{labels: [label()], datasets: [dataset()]} } @doc """ Given a chart type, return a new chart. Defaults to bar iex> Ada.Email.Quickchart.new() %Ada.Email.Quickchart{ data: %{datasets: [], labels: []}, height: 300, type: "bar", width: 516 } iex> Ada.Email.Quickchart.new("line") %Ada.Email.Quickchart{ data: %{datasets: [], labels: []}, height: 300, type: "line", width: 516 } """ @spec new(chart_type()) :: t() def new(type \\ "bar"), do: %__MODULE__{type: type} @doc """ Given a chart, set its dimensions. iex> Ada.Email.Quickchart.new() ...> |> Ada.Email.Quickchart.set_dimensions(200, 200) %Ada.Email.Quickchart{ data: %{datasets: [], labels: []}, height: 200, type: "bar", width: 200 } """ @spec set_dimensions(t(), dimension(), dimension()) :: t() def set_dimensions(chart, width, height) do %{chart | width: width, height: height} end @doc """ Given a chart, add general labels. iex> Ada.Email.Quickchart.new() ...> |> Ada.Email.Quickchart.add_labels(["May", "June"]) %Ada.Email.Quickchart{ data: %{datasets: [], labels: ["May", "June"]}, height: 300, type: "bar", width: 516 } """ @spec add_labels(t(), [label()]) :: t() def add_labels(chart, labels) do %{chart | data: Map.put(chart.data, :labels, labels)} end @doc """ Given a chart, add a new dataset, identified by its label and data. iex> Ada.Email.Quickchart.new() ...> |> Ada.Email.Quickchart.add_dataset("Sales", [1,2,3]) %Ada.Email.Quickchart{ data: %{datasets: [%{label: "Sales", data: [1,2,3]}], labels: []}, height: 300, type: "bar", width: 516 } """ @spec add_dataset(t(), label(), data()) :: t() def add_dataset(chart, label, data) do dataset = %{label: label, data: data} %{chart | data: Map.update!(chart.data, :datasets, fn current -> current ++ [dataset] end)} end @doc """ Given a chart, returns its corresponding quickchart url. iex> Ada.Email.Quickchart.new() ...> |> Ada.Email.Quickchart.add_labels(["April", "May", "June"]) ...> |> Ada.Email.Quickchart.add_dataset("Sales", [1,2,3]) ...> |> Ada.Email.Quickchart.to_url() "https://quickchart.io/chart?c=%7B%27data%27%3A%7B%27datasets%27%3A%5B%7B%27data%27%3A%5B1%2C2%2C3%5D%2C%27label%27%3A%27Sales%27%7D%5D%2C%27labels%27%3A%5B%27April%27%2C%27May%27%2C%27June%27%5D%7D%2C%27type%27%3A%27bar%27%7D&height=300&width=516" """ @spec to_url(t()) :: String.t() def to_url(chart) do payload = Map.take(chart, [:type, :data]) qs = %{ width: chart.width, height: chart.height, c: payload |> Jason.encode!() |> String.replace(~s("), "'") } @base_url <> "?" <> URI.encode_query(qs) end end
lib/ada/email/quickchart.ex
0.805976
0.62395
quickchart.ex
starcoder
defmodule Turtle do @moduledoc """ Turtle graphics is a popular and fun way to learn programming. It was part of the original Logo programming language developed by <NAME> and <NAME> in 1966. To give you an idea, imagine a robotic turtle starting at `{0, 0}` in the x-y plane. And after giving a command like `Turtle.forward(%Turtle{}, 15)`, it moves 15 pixels in the direction it is facing, drawing a line as it moves. Give it the command `Turtle.right(turtle, 15)`, and it rotates in-place 15 degrees clockwise. By combining together these and similar commands, complex shapes and pictures can easily be drawn. """ @type t :: %__MODULE__{ x: number(), y: number(), angle: integer(), pen_down?: boolean(), pen_color: atom() | tuple(), pen_size: pos_integer(), visible: boolean() } defstruct x: 0, y: 0, angle: 0, pen_down?: true, pen_color: :black, pen_size: 1, visible: true alias __MODULE__.{Motion, Pen} @doc delegate_to: {Motion, :forward, 2} defdelegate forward(turtle, distance), to: Motion @doc delegate_to: {Motion, :forward, 2} defdelegate fd(turtle, distance), to: Motion, as: :forward @doc delegate_to: {Motion, :backward, 2} defdelegate back(turtle, distance), to: Motion, as: :backward @doc delegate_to: {Motion, :backward, 2} defdelegate bk(turtle, distance), to: Motion, as: :backward @doc delegate_to: {Motion, :backward, 2} defdelegate backward(turtle, distance), to: Motion @doc delegate_to: {Motion, :right, 2} defdelegate right(turtle, angle), to: Motion @doc delegate_to: {Motion, :right, 2} defdelegate rt(turtle, angle), to: Motion, as: :right @doc delegate_to: {Motion, :left, 2} defdelegate left(turtle, angle), to: Motion @doc delegate_to: {Motion, :left, 2} defdelegate lt(turtle, angle), to: Motion, as: :left @doc delegate_to: {Motion, :go_to, 3} defdelegate go_to(turtle, x, y), to: Motion @doc delegate_to: {Motion, :go_to, 2} defdelegate go_to(turtle, vector), to: Motion @doc delegate_to: {Motion, :go_to, 3} defdelegate setpos(turtle, x, y), to: Motion, as: :go_to @doc delegate_to: {Motion, :go_to, 2} defdelegate setposition(turtle, x, y), to: Motion, as: :go_to @doc delegate_to: {Motion, :set_x, 2} defdelegate set_x(turtle, x), to: Motion @doc delegate_to: {Motion, :set_y, 2} defdelegate set_y(turtle, y), to: Motion @doc delegate_to: {Motion, :set_heading, 2} defdelegate set_heading(turtle, to_angle), to: Motion @doc delegate_to: {Motion, :set_heading, 2} defdelegate seth(turtle, to_angle), to: Motion, as: :set_heading @doc delegate_to: {Motion, :home, 1} defdelegate home(turtle), to: Motion @doc delegate_to: {Motion, :home, 1} defdelegate reset(turtle), to: Motion, as: :home @doc delegate_to: {Motion, :position, 1} defdelegate position(turtle), to: Motion @doc delegate_to: {Motion, :heading, 1} defdelegate heading(turtle), to: Motion @doc delegate_to: {Motion, :x_cor, 1} defdelegate x_cor(turtle), to: Motion @doc delegate_to: {Motion, :y_cor, 1} defdelegate y_cor(turtle), to: Motion @doc delegate_to: {Motion, :towards, 2} defdelegate towards(turtle, vector), to: Motion @doc delegate_to: {Motion, :towards, 3} defdelegate towards(turtle, x, y), to: Motion @doc delegate_to: {Motion, :distance, 2} defdelegate distance(turle, vector), to: Motion @doc delegate_to: {Motion, :distance, 3} defdelegate distance(turtle, x, y), to: Motion @doc delegate_to: {Pen, :pen_up, 1} defdelegate pen_up(turtle), to: Pen @doc delegate_to: {Pen, :pen_down, 1} defdelegate pen_down(turtle), to: Pen @doc delegate_to: {Pen, :pen_down?, 1} defdelegate pen_down?(turtle), to: Pen @doc delegate_to: {Pen, :pen_up?, 1} defdelegate pen_up?(turtle), to: Pen @doc delegate_to: {Pen, :pen_size, 1} defdelegate pen_size(turtle), to: Pen @doc delegate_to: {Pen, :pen_size, 2} defdelegate pen_size(turtle, thickness), to: Pen @doc delegate_to: {Pen, :pen_color, 1} defdelegate pen_color(turtle), to: Pen @doc delegate_to: {Pen, :pen_color, 2} defdelegate pen_color(turtle, color), to: Pen @doc """ Creates a new Turtle. """ def new(opts \\ []) do struct(__MODULE__, opts) end @doc """ Makes the turtle invisible. """ def hide(%Turtle{} = turtle) do %{turtle | visible: false} end @doc """ Makes the turtle visible. """ def show(%Turtle{} = turtle) do %{turtle | visible: true} end @doc """ Returns `true` is turtle is visible, otherwise `false` """ def visible?(%Turtle{visible: visible}) do visible end end
turtle/lib/turtle.ex
0.868241
0.803135
turtle.ex
starcoder
defmodule EctoSearcher do @moduledoc """ EctoSearcher is an attempt to bring dynamicly built queries (hello [Ransack](https://github.com/activerecord-hackery/ransack)) to the world of [Ecto](https://github.com/elixir-ecto/ecto). ## Installation Add `ecto_searcher` to your mix.ex deps: ```elixir def deps do [ {:ecto_searcher, "~> 0.2.1"} ] end ``` ## Notice This package is build for sql queries and is tested with PostgreSQL. Every other usage may not work. ## Usage (short) - `EctoSearcher.Searcher` — use this to search - `EctoSearcher.Sorter` — use this to sort - `EctoSearcher.Mapping` — use this to implement custom searches - `EctoSearcher.Mapping.Default` — use this if you don't want to implement custom mapping ## Usage Obviously, EctoSearcher works on top of ecto schemas and ecto repos. It consumes ecto query and adds conditions built from input. Searching with `EctoSearcher.Searcher.search/5` and sorting `EctoSearcher.Sorter.sort/5` could be used separately or together. ### Searching To search use `EctoSearcher.Searcher.search/4` or `EctoSearcher.Searcher.search/5`: Basic usage: ```elixir defmodule TotallyNotAPhoenixController do def not_some_controller_method() do base_query = Ecto.Query.from(MyMegaModel) search = %{"name_eq" => "<NAME>", "description_cont" => "My president"} query = EctoSearcher.Searcher.search(base_query, MyMegaModel, search) MySuperApp.Repo.all(query) end end ``` ### Sorting To sort use `EctoSearcher.Sorter.sort/3` or `EctoSearcher.Sorter.sort/5`: ```elixir defmodule TotallyNotAPhoenixController do def not_some_controller_method() do base_query = Ecto.Query.from(MyMegaModel) sort = %{"field" => "name", "order" => "desc"} query = EctoSearcher.Sorter.sort(base_query, MyMegaModel, sort) MySuperApp.Repo.all(query) end end ``` ### Custom fields and matchers In case you need to implement custom field queries or custom matchers you can implement custom Mapping (using `EctoSearcher.Mapping` behaviour): ```elixir defmodule MySuperApp.CustomMapping do use EctoSearcher.Mapping def matchers do custom_matchers = %{ "not_eq" => fn field, value -> Query.dynamic([q], ^field != ^value) end } ## No magic, just plain data manipulation Map.merge( custom_matchers, EctoSearcher.Mapping.Default.matchers() ) end def fields do %{ datetime_field_as_date: %{ query: Query.dynamic([q], fragment("?::date", q.custom_field)), type: :date } } end end ``` And use it in `EctoSearcher.Searcher.search/5` or `EctoSearcher.Sorter.sort/5`: ```elixir defmodule TotallyNotAPhoenixContext do import Ecto.Query require Ecto.Query def not_some_context_method() do search = %{ "name_eq" => "<NAME>", "datetime_as_date_gteq" => "2016-11-08", "datetime_as_date_lteq" => "2019-09-11", "description_not_eq" => "Not my president" } sort = %{ "field" => "datetime_as_date_gteq", "order" => "desc" } base_query = from(q in MyMegaModel, where: [q.id < 1984]) query = base_query |> EctoSearcher.Searcher.search(MyMegaModel, search, MySuperApp.CustomMapping) |> EctoSearcher.Searcher.search(base_query, MyMegaModel, sort, MySuperApp.CustomMapping) |> MySuperApp.Repo.all() end end ``` `EctoSearcher.Searcher.search/5` and `EctoSearcher.Sorter.sort/5` looks up fields in mapping first, then looks up fields in schema. """ end
lib/ecto_searcher.ex
0.80969
0.804751
ecto_searcher.ex
starcoder
defmodule Prexent.Parser do @moduledoc """ This module is the parser from markdown to HTML """ require Logger @typedoc """ A single slide """ @type slide() :: [ Map.t( type :: :html | :code | :header | :footer | :comment | :custom_css | :slide_background | :slide_classes | :global_background | :error, content :: String.t() ) ] @typedoc """ The result of the parse. This type will return a list of slides() """ @type parse_result() :: [slide()] @doc """ Parses slides of the markdown to a list of HTML. If exists any parse error, the item in the list will be the error message. It recognizes some commands: * `!include <file>` - with a markdown file to include in any place * `!code <file>` - will parse a code script """ @spec to_parsed_list(String.t()) :: parse_result() def to_parsed_list(path_to_file) do try do read_file!(path_to_file) |> parse_content() rescue e in File.Error -> [e.message()] end end defp parse_content(content) do regex = ~r/(^---$)|(^!([\S*]+) ([\S*]+).*$)/m Regex.split(regex, content, include_captures: true, trim: true) |> Enum.map(&process_chunk(&1)) |> List.flatten() |> split_on("---") end defp split_on(list, on) do list |> Enum.reverse() |> do_split_on(on, [[]]) |> Enum.reject(fn list -> list == [] end) end defp do_split_on([], _, acc), do: acc defp do_split_on([h | t], h, acc), do: do_split_on(t, h, [[] | acc]) defp do_split_on([h | t], on, [h2 | t2]), do: do_split_on(t, on, [[h | h2] | t2]) defp process_chunk("---"), do: "---" defp process_chunk("!code " <> arguments), do: process_code(String.split(arguments, " ")) defp process_chunk("!include " <> argument) do path_to_file = path_to_file(argument) try do read_file!(path_to_file) |> parse_content() rescue _ -> process_error("Included file not found: #{path_to_file}") end end defp process_chunk("!" <> rest) do case String.split(rest, " ") do ["header" | args] -> %{type: :header, content: Enum.join(args, " ")} ["footer" | args] -> %{type: :footer, content: Enum.join(args, " ")} ["comment" | args] -> %{type: :comment, content: Enum.join(args, " ")} ["custom_css" | args] -> %{type: :custom_css, content: Enum.at(args, 0)} ["global_background" | args] -> %{type: :global_background, content: Enum.at(args, 0)} ["slide_background" | args] -> %{type: :slide_background, content: Enum.at(args, 0)} ["slide_classes" | args] -> %{type: :slide_classes, content: args} _ -> %{type: :error, content: "wrong command !#{rest}"} end end defp process_chunk(chunk) do case Earmark.as_html(chunk) do {:ok, html_doc, _} -> %{ type: :html, content: html_doc } {:error, _html_doc, error_messages} -> process_error(error_messages) end end defp process_code([fname]), do: process_code([fname, "elixir", "elixir"]) defp process_code([fname, lang, runner]) do path_to_file = path_to_file(fname) try do file_content = read_file!(path_to_file) %{ type: :code, content: file_content, filename: path_to_file, runner: runner, lang: lang } rescue _ -> process_error("Code file not found: #{path_to_file}") end end defp process_code(parameters) do process_error("invalid code parameters #{Enum.join(parameters, ' ')}") end defp process_error(content), do: %{ type: :error, content: content } defp path_to_file(input) do input |> String.trim() |> String.split(" ") |> Enum.at(0) end defp read_file!(path_to_file) do abspath = Path.absname(path_to_file) File.read!(abspath) end end
lib/prexent/parser.ex
0.682574
0.436862
parser.ex
starcoder
defmodule AWS.ElasticBeanstalk do @moduledoc """ AWS Elastic Beanstalk AWS Elastic Beanstalk makes it easy for you to create, deploy, and manage scalable, fault-tolerant applications running on the Amazon Web Services cloud. For more information about this product, go to the [AWS Elastic Beanstalk](http://aws.amazon.com/elasticbeanstalk/) details page. The location of the latest AWS Elastic Beanstalk WSDL is [https://elasticbeanstalk.s3.amazonaws.com/doc/2010-12-01/AWSElasticBeanstalk.wsdl](https://elasticbeanstalk.s3.amazonaws.com/doc/2010-12-01/AWSElasticBeanstalk.wsdl). To install the Software Development Kits (SDKs), Integrated Development Environment (IDE) Toolkits, and command line tools that enable you to access the API, go to [Tools for Amazon Web Services](http://aws.amazon.com/tools/). ## Endpoints For a list of region-specific endpoints that AWS Elastic Beanstalk supports, go to [Regions and Endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#elasticbeanstalk_region) in the *Amazon Web Services Glossary*. """ @doc """ Cancels in-progress environment configuration update or application version deployment. """ def abort_environment_update(client, input, options \\ []) do request(client, "AbortEnvironmentUpdate", input, options) end @doc """ Applies a scheduled managed action immediately. A managed action can be applied only if its status is `Scheduled`. Get the status and action ID of a managed action with `DescribeEnvironmentManagedActions`. """ def apply_environment_managed_action(client, input, options \\ []) do request(client, "ApplyEnvironmentManagedAction", input, options) end @doc """ Add or change the operations role used by an environment. After this call is made, Elastic Beanstalk uses the associated operations role for permissions to downstream services during subsequent calls acting on this environment. For more information, see [Operations roles](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/iam-operationsrole.html) in the *AWS Elastic Beanstalk Developer Guide*. """ def associate_environment_operations_role(client, input, options \\ []) do request(client, "AssociateEnvironmentOperationsRole", input, options) end @doc """ Checks if the specified CNAME is available. """ def check_d_n_s_availability(client, input, options \\ []) do request(client, "CheckDNSAvailability", input, options) end @doc """ Create or update a group of environments that each run a separate component of a single application. Takes a list of version labels that specify application source bundles for each of the environments to create or update. The name of each environment and other required information must be included in the source bundles in an environment manifest named `env.yaml`. See [Compose Environments](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-mgmt-compose.html) for details. """ def compose_environments(client, input, options \\ []) do request(client, "ComposeEnvironments", input, options) end @doc """ Creates an application that has one configuration template named `default` and no application versions. """ def create_application(client, input, options \\ []) do request(client, "CreateApplication", input, options) end @doc """ Creates an application version for the specified application. You can create an application version from a source bundle in Amazon S3, a commit in AWS CodeCommit, or the output of an AWS CodeBuild build as follows: Specify a commit in an AWS CodeCommit repository with `SourceBuildInformation`. Specify a build in an AWS CodeBuild with `SourceBuildInformation` and `BuildConfiguration`. Specify a source bundle in S3 with `SourceBundle` Omit both `SourceBuildInformation` and `SourceBundle` to use the default sample application. After you create an application version with a specified Amazon S3 bucket and key location, you can't change that Amazon S3 location. If you change the Amazon S3 location, you receive an exception when you attempt to launch an environment from the application version. """ def create_application_version(client, input, options \\ []) do request(client, "CreateApplicationVersion", input, options) end @doc """ Creates an AWS Elastic Beanstalk configuration template, associated with a specific Elastic Beanstalk application. You define application configuration settings in a configuration template. You can then use the configuration template to deploy different versions of the application with the same configuration settings. Templates aren't associated with any environment. The `EnvironmentName` response element is always `null`. Related Topics * `DescribeConfigurationOptions` * `DescribeConfigurationSettings` * `ListAvailableSolutionStacks` """ def create_configuration_template(client, input, options \\ []) do request(client, "CreateConfigurationTemplate", input, options) end @doc """ Launches an AWS Elastic Beanstalk environment for the specified application using the specified configuration. """ def create_environment(client, input, options \\ []) do request(client, "CreateEnvironment", input, options) end @doc """ Create a new version of your custom platform. """ def create_platform_version(client, input, options \\ []) do request(client, "CreatePlatformVersion", input, options) end @doc """ Creates a bucket in Amazon S3 to store application versions, logs, and other files used by Elastic Beanstalk environments. The Elastic Beanstalk console and EB CLI call this API the first time you create an environment in a region. If the storage location already exists, `CreateStorageLocation` still returns the bucket name but does not create a new bucket. """ def create_storage_location(client, input, options \\ []) do request(client, "CreateStorageLocation", input, options) end @doc """ Deletes the specified application along with all associated versions and configurations. The application versions will not be deleted from your Amazon S3 bucket. You cannot delete an application that has a running environment. """ def delete_application(client, input, options \\ []) do request(client, "DeleteApplication", input, options) end @doc """ Deletes the specified version from the specified application. You cannot delete an application version that is associated with a running environment. """ def delete_application_version(client, input, options \\ []) do request(client, "DeleteApplicationVersion", input, options) end @doc """ Deletes the specified configuration template. When you launch an environment using a configuration template, the environment gets a copy of the template. You can delete or modify the environment's copy of the template without affecting the running environment. """ def delete_configuration_template(client, input, options \\ []) do request(client, "DeleteConfigurationTemplate", input, options) end @doc """ Deletes the draft configuration associated with the running environment. Updating a running environment with any configuration changes creates a draft configuration set. You can get the draft configuration using `DescribeConfigurationSettings` while the update is in progress or if the update fails. The `DeploymentStatus` for the draft configuration indicates whether the deployment is in process or has failed. The draft configuration remains in existence until it is deleted with this action. """ def delete_environment_configuration(client, input, options \\ []) do request(client, "DeleteEnvironmentConfiguration", input, options) end @doc """ Deletes the specified version of a custom platform. """ def delete_platform_version(client, input, options \\ []) do request(client, "DeletePlatformVersion", input, options) end @doc """ Returns attributes related to AWS Elastic Beanstalk that are associated with the calling AWS account. The result currently has one set of attributes—resource quotas. """ def describe_account_attributes(client, input, options \\ []) do request(client, "DescribeAccountAttributes", input, options) end @doc """ Retrieve a list of application versions. """ def describe_application_versions(client, input, options \\ []) do request(client, "DescribeApplicationVersions", input, options) end @doc """ Returns the descriptions of existing applications. """ def describe_applications(client, input, options \\ []) do request(client, "DescribeApplications", input, options) end @doc """ Describes the configuration options that are used in a particular configuration template or environment, or that a specified solution stack defines. The description includes the values the options, their default values, and an indication of the required action on a running environment if an option value is changed. """ def describe_configuration_options(client, input, options \\ []) do request(client, "DescribeConfigurationOptions", input, options) end @doc """ Returns a description of the settings for the specified configuration set, that is, either a configuration template or the configuration set associated with a running environment. When describing the settings for the configuration set associated with a running environment, it is possible to receive two sets of setting descriptions. One is the deployed configuration set, and the other is a draft configuration of an environment that is either in the process of deployment or that failed to deploy. Related Topics * `DeleteEnvironmentConfiguration` """ def describe_configuration_settings(client, input, options \\ []) do request(client, "DescribeConfigurationSettings", input, options) end @doc """ Returns information about the overall health of the specified environment. The **DescribeEnvironmentHealth** operation is only available with AWS Elastic Beanstalk Enhanced Health. """ def describe_environment_health(client, input, options \\ []) do request(client, "DescribeEnvironmentHealth", input, options) end @doc """ Lists an environment's completed and failed managed actions. """ def describe_environment_managed_action_history(client, input, options \\ []) do request(client, "DescribeEnvironmentManagedActionHistory", input, options) end @doc """ Lists an environment's upcoming and in-progress managed actions. """ def describe_environment_managed_actions(client, input, options \\ []) do request(client, "DescribeEnvironmentManagedActions", input, options) end @doc """ Returns AWS resources for this environment. """ def describe_environment_resources(client, input, options \\ []) do request(client, "DescribeEnvironmentResources", input, options) end @doc """ Returns descriptions for existing environments. """ def describe_environments(client, input, options \\ []) do request(client, "DescribeEnvironments", input, options) end @doc """ Returns list of event descriptions matching criteria up to the last 6 weeks. This action returns the most recent 1,000 events from the specified `NextToken`. """ def describe_events(client, input, options \\ []) do request(client, "DescribeEvents", input, options) end @doc """ Retrieves detailed information about the health of instances in your AWS Elastic Beanstalk. This operation requires [enhanced health reporting](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/health-enhanced.html). """ def describe_instances_health(client, input, options \\ []) do request(client, "DescribeInstancesHealth", input, options) end @doc """ Describes a platform version. Provides full details. Compare to `ListPlatformVersions`, which provides summary information about a list of platform versions. For definitions of platform version and other platform-related terms, see [AWS Elastic Beanstalk Platforms Glossary](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/platforms-glossary.html). """ def describe_platform_version(client, input, options \\ []) do request(client, "DescribePlatformVersion", input, options) end @doc """ Disassociate the operations role from an environment. After this call is made, Elastic Beanstalk uses the caller's permissions for permissions to downstream services during subsequent calls acting on this environment. For more information, see [Operations roles](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/iam-operationsrole.html) in the *AWS Elastic Beanstalk Developer Guide*. """ def disassociate_environment_operations_role(client, input, options \\ []) do request(client, "DisassociateEnvironmentOperationsRole", input, options) end @doc """ Returns a list of the available solution stack names, with the public version first and then in reverse chronological order. """ def list_available_solution_stacks(client, input, options \\ []) do request(client, "ListAvailableSolutionStacks", input, options) end @doc """ Lists the platform branches available for your account in an AWS Region. Provides summary information about each platform branch. For definitions of platform branch and other platform-related terms, see [AWS Elastic Beanstalk Platforms Glossary](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/platforms-glossary.html). """ def list_platform_branches(client, input, options \\ []) do request(client, "ListPlatformBranches", input, options) end @doc """ Lists the platform versions available for your account in an AWS Region. Provides summary information about each platform version. Compare to `DescribePlatformVersion`, which provides full details about a single platform version. For definitions of platform version and other platform-related terms, see [AWS Elastic Beanstalk Platforms Glossary](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/platforms-glossary.html). """ def list_platform_versions(client, input, options \\ []) do request(client, "ListPlatformVersions", input, options) end @doc """ Return the tags applied to an AWS Elastic Beanstalk resource. The response contains a list of tag key-value pairs. Elastic Beanstalk supports tagging of all of its resources. For details about resource tagging, see [Tagging Application Resources](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/applications-tagging-resources.html). """ def list_tags_for_resource(client, input, options \\ []) do request(client, "ListTagsForResource", input, options) end @doc """ Deletes and recreates all of the AWS resources (for example: the Auto Scaling group, load balancer, etc.) for a specified environment and forces a restart. """ def rebuild_environment(client, input, options \\ []) do request(client, "RebuildEnvironment", input, options) end @doc """ Initiates a request to compile the specified type of information of the deployed environment. Setting the `InfoType` to `tail` compiles the last lines from the application server log files of every Amazon EC2 instance in your environment. Setting the `InfoType` to `bundle` compresses the application server log files for every Amazon EC2 instance into a `.zip` file. Legacy and .NET containers do not support bundle logs. Use `RetrieveEnvironmentInfo` to obtain the set of logs. Related Topics * `RetrieveEnvironmentInfo` """ def request_environment_info(client, input, options \\ []) do request(client, "RequestEnvironmentInfo", input, options) end @doc """ Causes the environment to restart the application container server running on each Amazon EC2 instance. """ def restart_app_server(client, input, options \\ []) do request(client, "RestartAppServer", input, options) end @doc """ Retrieves the compiled information from a `RequestEnvironmentInfo` request. Related Topics * `RequestEnvironmentInfo` """ def retrieve_environment_info(client, input, options \\ []) do request(client, "RetrieveEnvironmentInfo", input, options) end @doc """ Swaps the CNAMEs of two environments. """ def swap_environment_c_n_a_m_es(client, input, options \\ []) do request(client, "SwapEnvironmentCNAMEs", input, options) end @doc """ Terminates the specified environment. """ def terminate_environment(client, input, options \\ []) do request(client, "TerminateEnvironment", input, options) end @doc """ Updates the specified application to have the specified properties. If a property (for example, `description`) is not provided, the value remains unchanged. To clear these properties, specify an empty string. """ def update_application(client, input, options \\ []) do request(client, "UpdateApplication", input, options) end @doc """ Modifies lifecycle settings for an application. """ def update_application_resource_lifecycle(client, input, options \\ []) do request(client, "UpdateApplicationResourceLifecycle", input, options) end @doc """ Updates the specified application version to have the specified properties. If a property (for example, `description`) is not provided, the value remains unchanged. To clear properties, specify an empty string. """ def update_application_version(client, input, options \\ []) do request(client, "UpdateApplicationVersion", input, options) end @doc """ Updates the specified configuration template to have the specified properties or configuration option values. If a property (for example, `ApplicationName`) is not provided, its value remains unchanged. To clear such properties, specify an empty string. Related Topics * `DescribeConfigurationOptions` """ def update_configuration_template(client, input, options \\ []) do request(client, "UpdateConfigurationTemplate", input, options) end @doc """ Updates the environment description, deploys a new application version, updates the configuration settings to an entirely new configuration template, or updates select configuration option values in the running environment. Attempting to update both the release and configuration is not allowed and AWS Elastic Beanstalk returns an `InvalidParameterCombination` error. When updating the configuration settings to a new template or individual settings, a draft configuration is created and `DescribeConfigurationSettings` for this environment returns two setting descriptions with different `DeploymentStatus` values. """ def update_environment(client, input, options \\ []) do request(client, "UpdateEnvironment", input, options) end @doc """ Update the list of tags applied to an AWS Elastic Beanstalk resource. Two lists can be passed: `TagsToAdd` for tags to add or update, and `TagsToRemove`. Elastic Beanstalk supports tagging of all of its resources. For details about resource tagging, see [Tagging Application Resources](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/applications-tagging-resources.html). If you create a custom IAM user policy to control permission to this operation, specify one of the following two virtual actions (or both) instead of the API operation name: ## Definitions ### elasticbeanstalk:AddTags Controls permission to call `UpdateTagsForResource` and pass a list of tags to add in the `TagsToAdd` parameter. ### elasticbeanstalk:RemoveTags Controls permission to call `UpdateTagsForResource` and pass a list of tag keys to remove in the `TagsToRemove` parameter. For details about creating a custom user policy, see [Creating a Custom User Policy](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/AWSHowTo.iam.managed-policies.html#AWSHowTo.iam.policies). """ def update_tags_for_resource(client, input, options \\ []) do request(client, "UpdateTagsForResource", input, options) end @doc """ Takes a set of configuration settings and either a configuration template or environment, and determines whether those values are valid. This action returns a list of messages indicating any errors or warnings associated with the selection of option values. """ def validate_configuration_settings(client, input, options \\ []) do request(client, "ValidateConfigurationSettings", 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: "elasticbeanstalk"} host = build_host("elasticbeanstalk", client) url = build_url(host, client) headers = [ {"Host", host}, {"Content-Type", "application/x-www-form-urlencoded"} ] input = Map.merge(input, %{"Action" => action, "Version" => "2010-12-01"}) 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/elastic_beanstalk.ex
0.852721
0.561155
elastic_beanstalk.ex
starcoder
defmodule OT.Server.ETSAdapter do @moduledoc """ This is an adapter for OT.Server that stores data and operations in ETS tables. It is not meant for production use, as all of its data is publicly available for testing purposes. """ @behaviour OT.Server.Adapter use GenServer @ops_table :ot_ops @data_table :ot_data defmodule RollbackError do defexception [:message] def exception(error) do %__MODULE__{message: inspect(error)} end end @doc false def start_link(_) do GenServer.start_link(__MODULE__, [], name: __MODULE__) end @impl GenServer def init(_) do :ets.new(@data_table, [:named_table, :set, :public]) :ets.new(@ops_table, [:named_table, :ordered_set, :public]) {:ok, []} end @impl OT.Server.Adapter def transact(_, func) do GenServer.call(__MODULE__, {:transact, func}) end @impl OT.Server.Adapter def rollback(err) do raise RollbackError, err end @impl OT.Server.Adapter def get_conflicting_operations(%{id: id}, op_vsn) do # Compiled from: # :ets.fun2ms(fn {{^id, vsn}, op} when vsn >= op_vsn -> # {op, vsn} # end) match_spec = [{ {{:"$1", :"$2"}, :"$3"}, [{:>=, :"$2", {:const, op_vsn}}, {:"=:=", {:const, id}, :"$1"}], [{{:"$3", :"$2"}}] }] :ets.select(@ops_table, match_spec) end @impl OT.Server.Adapter def get_datum(id) do @data_table |> :ets.lookup(id) |> case do [{^id, datum}] -> {:ok, datum} _ -> {:error, :not_found} end end @impl OT.Server.Adapter def handle_submit_error({:error, :version_mismatch}, _, _) do :retry end def handle_submit_error(err, _, _) do err end @impl OT.Server.Adapter def insert_operation(%{id: id}, {op, vsn}, _meta) do if :ets.insert_new(@ops_table, {{id, vsn}, op}) do {:ok, {op, vsn}} else {:error, :version_mismatch} end end @impl OT.Server.Adapter def update_datum(datum, content) do datum = datum |> Map.put(:content, content) |> Map.put(:version, datum[:version] + 1) if :ets.insert(@data_table, {datum[:id], datum}) do {:ok, datum} else {:error, :update_failed} end end @impl GenServer def handle_call({:transact, func}, _, state) do {:reply, {:ok, func.()}, state} end end
lib/ot/server/ets_adapter.ex
0.658088
0.44903
ets_adapter.ex
starcoder
defmodule Mix.Tasks.Edeliver do use Mix.Task @shortdoc "Build and deploy releases" @moduledoc """ Build and deploy Elixir applications and perform hot-code upgrades # Usage: * mix edeliver <build-command|deploy-command|node-command|local-command> command-info [Options] * mix edeliver --help|--version * mix edeliver help <command> ## Build Commands: * mix edeliver build release [--revision=<git-revision>|--tag=<git-tag>] [--branch=<git-branch>] [Options] * mix edeliver build appups|upgrade --from=<git-tag-or-revision>|--with=<release-version-from-store> [--to=<git-tag-or-revision>] [--branch=<git-branch>] [Options] ## Deploy Commands: * mix edeliver deploy release|upgrade [[to] staging|production] [--version=<release-version>] [Options] * mix edeliver upgrade [staging|production] [--to=<git-tag-or-revision>] [--branch=<git-branch>] [Options] * mix edeliver update [staging|production] [--to=<git-tag-or-revision>] [--branch=<git-branch>] [Options] ## Node Commands: * mix edeliver start|stop|restart|ping|version [staging|production] [Options] * mix edeliver migrate [staging|production] [up|down] [--version=<migration-version>] * mix edeliver [show] migrations [on] [staging|production] ## Local Commands: * mix edeliver check release|config [--version=<release-version>] * mix edeliver show releases|appups * mix edeliver show relup <xyz.upgrade.tar.gz> * mix edeliver edit relup|appups [--version=<release-version>] * mix edeliver upload|download [release|upgrade <release-version>]|<src-file-name> [<dest-file-name>] * mix edeliver increase [major|minor] versions [--from=<git-tag-or-revision>] [--to=<git-tag-or-revision>] * mix edeliver unpack|pack release|upgrade [--version=<release-version>] ## Command line Options * `--quiet` - do not output verbose messages * `--only` - only fetch dependencies for given environment * `-C`, `--compact` Displays every task as it's run, silences all output. (default mode) * `-V`, `--verbose` Same as above, does not silence output. * `-P`, `--plain` Displays every task as it's run, silences all output. No colouring. (CI) * `-D`, `--debug` Runs in shell debug mode, displays everything. * `-S`, `--skip-existing` Skip copying release archives if they exist already on the deploy hosts. * `-F`, `--force` Do not ask, just do, overwrite, delete or destroy everything * `--clean-deploy` Delete the release, lib and erts-* directories before deploying the release * `--start-deploy` Starts the deployed release. If release is running, it is restarted! * `--host=[u@]vwx.yz` Run command only on that host, even if different hosts are configured * `--skip-git-clean` Don't build from a clean state for faster builds. By default all built files are removed before the next build using `git clean`. This can be adjusted by the $GIT_CLEAN_PATHS env. * `--skip-mix-clean` Skip the 'mix clean step' for faster builds. Makes only sense in addition to the --skip-git-clean * `--skip-relup-mod` Skip modification of relup file. Custom relup instructions are not added * `--relup-mod=<module-name>` The name of the module to modify the relup * `--auto-version=revision|commit-count|branch|date` Automatically append metadata to release version. * `--increment-version=major|minor|patch` Increment the version for the current build. * `--set-version=<release-version>` Set the release version for the current build. * `--mix-env=<env>` Build with custom mix env $MIX_ENV. Default is 'prod' """ @spec run(OptionParser.argv) :: :ok def run(args) do edeliver = Path.join [Mix.Project.config[:deps_path], "edeliver", "bin", "edeliver"] if (res = run_edeliver(Enum.join([edeliver | args] ++ ["--runs-as-mix-task"], " "))) > 0, do: System.halt(res) end defp run_edeliver(command) do port = Port.open({:spawn, shell_command(command)}, [:stream, :binary, :exit_status, :use_stdio, :stderr_to_stdout]) stdin_pid = Process.spawn(__MODULE__, :forward_stdin, [port], [:link]) print_stdout(port, stdin_pid) end @doc """ Forwards stdin to the edeliver script which was spawned as port. """ @spec forward_stdin(port::port) :: :ok def forward_stdin(port) do case IO.gets(:stdio, "") do :eof -> :ok {:error, reason} -> throw reason data -> Port.command(port, data) end end # Prints the output received from the port running the edeliver command to stdout. # If the edeliver command terminates, it returns the exit code of the edeliver script. @spec print_stdout(port::port, stdin_pid::pid) :: exit_status::non_neg_integer defp print_stdout(port, stdin_pid) do receive do {^port, {:data, data}} -> IO.write(data) print_stdout(port, stdin_pid) {^port, {:exit_status, status}} -> Process.unlink(stdin_pid) Process.exit(stdin_pid, :kill) status end end # Finding shell command logic from :os.cmd in OTP # https://github.com/erlang/otp/blob/8deb96fb1d017307e22d2ab88968b9ef9f1b71d0/lib/kernel/src/os.erl#L184 defp shell_command(command) do case :os.type do {:unix, _} -> command = command |> String.replace("\"", "\\\"") |> :binary.bin_to_list 'sh -c "' ++ command ++ '"' {:win32, osname} -> command = :binary.bin_to_list(command) case {System.get_env("COMSPEC"), osname} do {nil, :windows} -> 'command.com /c ' ++ command {nil, _} -> 'cmd /c ' ++ command {cmd, _} -> '#{cmd} /c ' ++ command end end end end
lib/mix/tasks/edeliver.ex
0.753648
0.519034
edeliver.ex
starcoder
defmodule Yggdrasil.Ethereum.Application do @moduledoc """ [![Build Status](https://travis-ci.org/etherharvest/yggdrasil_ethereum.svg?branch=master)](https://travis-ci.org/etherharvest/yggdrasil_ethereum) [![Hex pm](http://img.shields.io/hexpm/v/yggdrasil_ethereum.svg?style=flat)](https://hex.pm/packages/yggdrasil_ethereum) [![hex.pm downloads](https://img.shields.io/hexpm/dt/yggdrasil_ethereum.svg?style=flat)](https://hex.pm/packages/yggdrasil_ethereum) This project is an Ethereum adapter for `Yggdrasil` publisher/subscriber. ## Small example The following example uses Ethereum adapter to distribute messages: We need to configure [EthEvent](https://github.com/etherharvest/eth_event) which is the library use to request the events from contracts: ```elixir config :eth_event, node_url: "https://mainnet.infura.io/v3", # Can be a custom URL node_key: "" # Infura key or empty for custom URL ``` And then we declare the event using `EthEvent` library. In this example, we will declare a `Transfer(address,address,uint256)` _event_. These events are declared in ERC20 tokens and they are _emitted_ when a successfull token transfers has occurred between wallets. In Solidity, we would have: ```solidity contract SomeToken is ERC20 { event Trasfer( address indexed from, address indexed to, uint256 value ); (...) } ``` Using `EthEvent` library, we can create an equivalent of the previous event in Elixir as follows: ```elixir iex(1)> defmodule Transfer do iex(1)> use EthEvent.Schema iex(1)> iex(1)> event "Transfer" do iex(1)> address :from, indexed: true iex(1)> address :to, indexed: true iex(1)> uint256 :value iex(1)> end iex(1)> end ``` We can now subscribe to any contract that has that type of event. For this example, we are going to subscribe to the `Transfer` events from OmiseGo contract. First we declare the channel: ```elixir iex(2)> contract = "0xd26114cd6EE289AccF82350c8d8487fedB8A0C07" # OmiseGo iex(3)> channel = %Yggdrasil.Channel{ iex(3)> name: {Transfer, [address: contract]}, iex(3)> adapter: :ethereum iex(3)> } ``` And then we subscribe to it: ```elixir iex(4)> Yggdrasil.subscribe(channel) iex(5)> flush() {:Y_CONNECTED, %Yggdrasil.Channel{(...)}} ``` If we wait enough, we should receive a message as follows: ```elixir iex(6)> flush() {:Y_EVENT, %Yggdrasil.Channel{(...)}, %Transfer{(...)}} ``` Where the struct `%Transfer{}` contains the information of a token transfer between two wallet addresses. When we want to stop receiving messages, then we can unsubscribe from the channel as follows: ```elixir iex(7)> Yggdrasil.unsubscribe(channel) iex(8)> flush() {:Y_DISCONNECTED, %Yggdrasil.Channel{(...)}} ``` ## Ethereum adapter The Ethereum adapter has the following rules: * The `adapter` name is identified by the atom `:ethereum`. * The channel `name` must be a tuple with the module name of the event and the `Keyword` list of options e.g: `:address`, `:from`, `:to`, etc (depends on the event). * The `transformer` should be always `:default`. * Any `backend` can be used (by default is `:default`). The following is an example of a valid channel for the subscribers: ```elixir %Yggdrasil.Channel{ name: {Balance, [address: "0x3f5CE5FBFe3E9af3971dD833D26bA9b5C936f0bE"]}, adapter: :ethereum } ``` It will subscribe to the balance of that address. ## Ethereum configuration This adapter uses long-polling to get the information from the Ethereum node and the frequency of the requests can be configured with the `:timeout` parameter. The following shows a configuration with and without namespace: ```elixir # Without namespace config :yggdrasil, ethereum: [timeout: 5_000] # With namespace config :yggdrasil, EthereumOne, ethereum: [timeout: 15_000] ``` Additionally, we can configure `EthEvent` options: * `node_url` - The Ethereum node URL. * `node_key` - It'll be appended to the URL at the end. ```elixir config :eth_event, node_url: "https://mainnet.infura.io/v3", # Can be a custom URL node_key: "some_key" # Empty for custom URL ``` All the options can be provided as OS environment variables. The available variables are: * `YGGDRASIL_ETHEREUM_TIMEOUT` or `<NAMESPACE>_YGGDRASIL_ETHEREUM_TIMEOUT`. * `ETH_EVENT_NODE_URL`. * `ETH_EVENT_NODE_KEY`. where `<NAMESPACE>` is the snakecase of the namespace chosen e.g. for the namespace `EthereumTwo`, you would use `ETHEREUM_TWO` as namespace in the OS environment variable. ## Installation Using this Ethereum adapter with `Yggdrasil` is a matter of adding the available hex package to your `mix.exs` file e.g: ```elixir def deps do [{:yggdrasil_ethereum, "~> 0.1"}] end ``` """ use Application @impl true def start(_type, _args) do children = [ Supervisor.child_spec({Yggdrasil.Adapter.Ethereum, []}, []) ] opts = [strategy: :one_for_one, name: Yggdrasil.Ethereum.Supervisor] Supervisor.start_link(children, opts) end end
lib/yggdrasil/ethereum/application.ex
0.897814
0.948251
application.ex
starcoder
defmodule Static.Folder do @moduledoc """ As you generate html documents from a folder structure, a `Static.Folder` structure describes a main entry point. A `Static.Folder` can consist of - a `Static.Site` or - a `Static.Folder` """ alias __MODULE__ alias Static.Site alias Static.Parameter alias Static.NestedSet @derive Jason.Encoder @type t :: %Folder{ sites: [Site.t() | Folder.t()], parameter: Parameter.t(), lnum: pos_integer(), rnum: pos_integer() } defstruct sites: [], parameter: nil, lnum: nil, rnum: nil @doc """ Creates a `Static.Folder` struct for given application `Static.Parameter` and a list of `Static.Site`. """ @spec create(parameter :: Parameter.t(), sites :: [Site.t() | Folder.t()]) :: Folder.t() def create(parameter, sites), do: %Folder{ parameter: parameter, sites: sites } @spec populate_breadcrumb(Static.Folder.t()) :: Static.Folder.t() def populate_breadcrumb(root_folder) do populate_breadcrumb(root_folder, root_folder |> NestedSet.flattened_tree()) end defp populate_breadcrumb(%Folder{sites: sites} = folder, nested_set) do found_sites = sites |> Enum.filter(fn x -> Kernel.is_struct(x, Site) end) populated_sites = found_sites |> Enum.map(fn %Site{url: active_url} = site -> %Site{ site | breadcrumb: NestedSet.breadcrumb(nested_set, site), siblings: sites |> Enum.map(fn possible_active_site -> if is_struct(possible_active_site, Folder) do %Folder{sites: [first_site | _rest]} = possible_active_site first_site else %Site{url: possible_active_url} = possible_active_site if possible_active_url == active_url do %Site{possible_active_site | is_active: true} else possible_active_site end end end) |> Enum.filter(fn %Site{title: title} -> not is_nil(title) end) } end) found_folders = sites |> Enum.filter(fn x -> Kernel.is_struct(x, Folder) end) |> Enum.map(fn found_folder -> populate_breadcrumb(found_folder, nested_set) end) %Folder{folder | sites: populated_sites ++ found_folders} end end
lib/folder.ex
0.789477
0.482368
folder.ex
starcoder
defmodule Entrance.Mix.Phoenix.Inflector do @moduledoc false @doc """ Inflects path, scope, alias and more from the given name. ## Examples ``` [alias: "User", human: "User", base: "Phoenix", web_module: "PhoenixWeb", module: "Phoenix.User", scoped: "User", singular: "user", path: "user"] [alias: "User", human: "User", base: "Phoenix", web_module: "PhoenixWeb", module: "Phoenix.Admin.User", scoped: "Admin.User", singular: "user", path: "admin/user"] [alias: "SuperUser", human: "Super user", base: "Phoenix", web_module: "PhoenixWeb", module: "Phoenix.Admin.SuperUser", scoped: "Admin.SuperUser", singular: "super_user", path: "admin/super_user"] ``` """ def call(singular) do base = get_base() web_module = base |> web_module() |> inspect() web_path = base |> web_path() scoped = camelize(singular) path = underscore(scoped) singular = String.split(path, "/") |> List.last() module = Module.concat(base, scoped) |> inspect test_module = "#{module}Test" alias = String.split(module, ".") |> List.last() human = humanize(singular) [ alias: alias, human: human, base: base, web_module: web_module, web_path: web_path, test_module: test_module, module: module, scoped: scoped, singular: singular, path: path ] end defp web_path(base) do "#{Macro.underscore(base)}_web" end defp web_module(base) do if base |> to_string() |> String.ends_with?("Web") do Module.concat([base]) else Module.concat(["#{base}Web"]) end end defp get_base do app_base(otp_app()) end defp app_base(app) do case Application.get_env(app, :namespace, app) do ^app -> app |> to_string() |> camelize() mod -> mod |> inspect() end end defp otp_app do Mix.Project.config() |> Keyword.fetch!(:app) end defp camelize(value), do: Macro.camelize(value) # defp camelize("", :lower), do: "" # defp camelize(<<?_, t::binary>>, :lower) do # camelize(t, :lower) # end # defp camelize(<<h, _t::binary>> = value, :lower) do # <<_first, rest::binary>> = camelize(value) # <<to_lower_char(h)>> <> rest # end defp underscore(value), do: Macro.underscore(value) defp humanize(atom) when is_atom(atom), do: humanize(Atom.to_string(atom)) defp humanize(bin) when is_binary(bin) do bin = if String.ends_with?(bin, "_id") do binary_part(bin, 0, byte_size(bin) - 3) else bin end bin |> String.replace("_", " ") |> String.capitalize() end # defp to_lower_char(char) when char in ?A..?Z, do: char + 32 # defp to_lower_char(char), do: char end
lib/mix/phoenix/inflector.ex
0.693369
0.546738
inflector.ex
starcoder
defmodule Infer do @moduledoc """ A dependency free library to infer file and MIME type by checking the [magic number](https://en.wikipedia.org/wiki/Magic_number_(programming)) signature. An elixir adaption of the [`infer`](https://github.com/bojand/infer) rust library. """ defmodule Type do defstruct [:matcher_type, :mime_type, :extension, :matcher] @type matcher_type() :: :app | :archive | :audio | :book | :image | :font | :text @type mime_type() :: binary() @type extension() :: binary() @type matcher_fun() :: fun((binary() -> boolean())) @type t() :: %{matcher_type: matcher_type(), mime_type: mime_type(), extension: extension(), matcher: matcher_fun()} end # Load matchers on compilation @matchers Infer.Matchers.list() @doc """ Takes the binary file contents as argument and returns the `t:Infer.Type.t/0` if the file matches one of the supported types. Returns `nil` otherwise. ## Examples iex> binary = File.read!("test/images/sample.png") iex> Infer.get(binary) %Infer.Type{extension: "png", matcher: &Infer.Image.png?/1, matcher_type: :image, mime_type: "image/png"} """ @spec get(binary()) :: Infer.Type.t() | nil def get(binary), do: Enum.find(@matchers, & &1.matcher.(binary)) @doc """ Same as `Infer.get/1`, but takes the file path as argument. ## Examples iex> Infer.get_from_path("test/images/sample.png") %Infer.Type{extension: "png", matcher: &Infer.Image.png?/1, matcher_type: :image, mime_type: "image/png"} """ @spec get_from_path(binary()) :: Infer.Type.t() | nil def get_from_path(path) do binary = File.read!(path) Enum.find(@matchers, & &1.matcher.(binary)) end @doc """ Takes the binary content and the file extension as arguments. Returns whether the file content is of the given extension. ## Examples iex> binary = File.read!("test/images/sample.png") iex> Infer.is?(binary, "png") true """ @spec is?(binary(), Infer.Type.extension()) :: boolean() def is?(binary, extension), do: Enum.any?(@matchers, &(&1.extension == extension && &1.matcher.(binary))) @doc """ Takes the binary content and the file extension as arguments. Returns whether the file content is of the given mime type. ## Examples iex> binary = File.read!("test/images/sample.png") iex> Infer.mime?(binary, "image/png") true """ @spec mime?(binary(), Infer.Type.mime_type()) :: boolean() def mime?(binary, mime_type), do: Enum.any?(@matchers, &(&1.mime_type == mime_type && &1.matcher.(binary))) @doc """ Returns whether the given extension is supported. ## Examples iex> Infer.supported?("png") true """ @spec supported?(Infer.Type.extension()) :: boolean() def supported?(extension), do: Enum.any?(@matchers, &(&1.extension == extension)) @doc """ Returns whether the given mime type is supported. ## Examples iex> Infer.mime_supported?("image/png") true """ @spec mime_supported?(Infer.Type.mime_type()) :: boolean() def mime_supported?(mime_type), do: Enum.any?(@matchers, &(&1.mime_type == mime_type)) @doc """ Takes the binary file contents as argument and returns whether the file is an application or not. ## Examples iex> binary = File.read!("test/app/sample.wasm") iex> Infer.app?(binary) true iex> binary = File.read!("test/images/sample.png") iex> Infer.app?(binary) false """ @spec app?(binary()) :: boolean() def app?(binary), do: Enum.any?(@matchers, &(&1.matcher_type == :app && &1.matcher.(binary))) @doc """ Takes the binary file contents as argument and returns whether the file is an archive or not. ## Examples iex> binary = File.read!("test/archives/sample.zip") iex> Infer.archive?(binary) true iex> binary = File.read!("test/images/sample.png") iex> Infer.archive?(binary) false """ @spec archive?(binary()) :: boolean() def archive?(binary), do: Enum.any?(@matchers, &(&1.matcher_type == :archive && &1.matcher.(binary))) @doc """ Takes the binary file contents as argument and returns whether the file is an archive or not. ## Examples iex> binary = File.read!("test/audio/sample.mp3") iex> Infer.audio?(binary) true iex> binary = File.read!("test/images/sample.png") iex> Infer.audio?(binary) false """ @spec audio?(binary()) :: boolean() def audio?(binary), do: Enum.any?(@matchers, &(&1.matcher_type == :audio && &1.matcher.(binary))) @doc """ Takes the binary file contents as argument and returns whether the file is an book (epub or mobi) or not. ## Examples iex> binary = File.read!("test/books/sample.epub") iex> Infer.book?(binary) true iex> binary = File.read!("test/images/sample.png") iex> Infer.book?(binary) false """ @spec book?(binary()) :: boolean() def book?(binary), do: Enum.any?(@matchers, &(&1.matcher_type == :book && &1.matcher.(binary))) @doc """ Takes the binary file contents as argument and returns whether the file is a document (microsoft office, open office) ## Examples iex> binary = File.read!("test/docs/sample.xlsx") iex> Infer.document?(binary) true iex> binary = File.read!("test/docs/sample.pptx") iex> Infer.document?(binary) true iex> binary = File.read!("test/docs/sample.odp") iex> Infer.document?(binary) true iex> binary = File.read!("test/images/sample.png") iex> Infer.document?(binary) false """ @spec document?(binary()) :: boolean() def document?(binary), do: Enum.any?(@matchers, &(&1.matcher_type == :doc && &1.matcher.(binary))) @doc """ Takes the binary file contents as argument and returns whether the file is a font or not. ## Examples iex> binary = File.read!("test/fonts/sample.ttf") iex> Infer.font?(binary) true iex> binary = File.read!("test/app/sample.wasm") iex> Infer.font?(binary) false """ @spec font?(binary()) :: boolean() def font?(binary), do: Enum.any?(@matchers, &(&1.matcher_type == :font && &1.matcher.(binary))) @doc """ Takes the binary file contents as argument and returns whether the file is an image or not. ## Examples iex> binary = File.read!("test/images/sample.png") iex> Infer.image?(binary) true iex> binary = File.read!("test/app/sample.wasm") iex> Infer.image?(binary) false """ @spec image?(binary()) :: boolean() def image?(binary), do: Enum.any?(@matchers, &(&1.matcher_type == :image && &1.matcher.(binary))) @doc """ Takes the binary file contents as argument and returns whether the file is a video or not. ## Examples iex> binary = File.read!("test/videos/sample.mp4") iex> Infer.video?(binary) true iex> binary = File.read!("test/app/sample.wasm") iex> Infer.video?(binary) false """ @spec video?(binary()) :: boolean() def video?(binary), do: Enum.any?(@matchers, &(&1.matcher_type == :video && &1.matcher.(binary))) end
lib/infer.ex
0.916321
0.660857
infer.ex
starcoder
defmodule WinInfo do require Logger @moduledoc """ A process wide table containing the window information """ def new_table() do try do :ets.new(table_name(), [:set, :protected, :named_table]) rescue _ -> Logger.warn("Attempt to create #{inspect(table_name())} failed: Table exists. ") end end def put_table(value) do :ets.insert_new(table_name(), value) end @doc """ Given am atom, get the info for the object. """ def get_by_name(name) do # display_table() res = :ets.lookup(table_name(), name) {name, id, obj} = case length(res) do 0 -> {nil, nil, nil} _ -> List.first(res) end {name, id, obj} end @doc """ Given a numeric ID, get the info for the object. """ def get_by_id(id) do res = :ets.match_object(table_name(), {:_, id, :_}) {name, id, obj} = case length(res) do 0 -> {nil, nil, nil} _ -> List.first(res) end {name, id, obj} end def get_object_name(id) do {name, _id, _obj} = get_by_id(id) name end def get_events() do res = :ets.lookup(table_name(), :__events__) events = case length(res) do 0 -> %{} _ -> {_, events} = List.first(res) events end events end def put_event(event_type, info) do res = :ets.lookup(table_name(), :__events__) events = case length(res) do 0 -> %{} _ -> {_, events} = List.first(res) events end events = Map.put(events, event_type, info) :ets.insert(table_name(), {:__events__, events}) end def display_table() do table = String.to_atom("#{inspect(self())}") all = :ets.match(table_name(), :"$1") Logger.info("Table: #{inspect(table)}") display_rows(all) end def display_rows([]) do :ok end def display_rows([[h] | t]) do Logger.info(" #{inspect(h)}") display_rows(t) end def table_name() do String.to_atom("#{inspect(self())}") end @doc """ FIFO implemented using ETS storage. """ def stack_push(value) do stack = get_stack() new_stack = case stack do [] -> [value] _ -> [value | stack] end # Logger.info("insert = #{inspect(new_stack)}") :ets.insert(table_name(), {:__stack__, new_stack}) end def stack_tos() do stack = get_stack() # Logger.info("get tos = #{inspect(stack)}") tos = case stack do nil -> nil [tos | _rest] -> tos [] -> # Logger.info("get tos []") nil end tos end def stack_pop() do stack = get_stack() {tos, rest} = case stack do nil -> {nil, []} [] -> {nil, []} [tos | rest] -> {tos, rest} end :ets.insert(table_name(), {:__stack__, rest}) tos end defp get_stack() do res = :ets.lookup(table_name(), :__stack__) # res = case res do [] -> [] _ -> res[:__stack__] end end end
lib/ElixirWx/wxWinInfo.ex
0.635901
0.439687
wxWinInfo.ex
starcoder
defmodule UeberauthToken.Config do @moduledoc """ Helper functions for ueberauth_token configuration. Cachex may be used for the storage of tokens temporarily by setting the option `:use_cache` to `true`. Cached tokens increase speed of token payload lookup but with the tradeoff that token invalidation may be delayed. This can optionally be mitigated somewhat by also using the background token worker inconjunction with the cached token. ## Example configuration config :ueberauth_token, UeberauthToken.Config, providers: {:system, :list, "TEST_TOKEN_PROVIDER", [UeberauthToken.TestProvider]} config :ueberauth_token, UeberauthToken.TestProvider, use_cache: {:system, :boolean, "TEST_USE_CACHE", false}, cache_name: {:system, :atom, "TEST_CACHE_NAME", :ueberauth_token}, background_checks: {:system, :boolean, "TEST_BACKGROUND_CHECKS", false}, background_frequency: {:system, :integer, "TEST_BACKGROUND_FREQUENCY", 120}, background_worker_log_level: {:system, :integer, "TEST_BACKGROUND_WORKER_LOG_LEVEL", :warn} ## Configuration options * `:use_cache` - boolean Whether or not the cache should be used at all. If set to true, the Cachex worker will be started in the supervision tree and the token will be cached. * `:background_checks` - boolean Whether or not to perform background checks on the tokens in the cache. If set to true, the `UeberauthToken.Worker` is started in the supervision tree. If unset, defaults to `false` * `:background_frequency` - seconds as an integer The frequency with which each token in the cache will be checked. The checks are not applied all at once, but staggered out across the `background_frequency` value in 30 evenly graduated phasese to avoid a burst of requests for the token verification. Defaults to `300` (5 minutes). * `:background_worker_log_level` - `:debug`, `:info`, `:warn` or `:error` The log level at which the background worker will log unexpected timeout and terminate events. Defaults to `:warn` * `:cache_name` - an atom The ets table name for the cache * `:provider` - a module a required provider module which implements the callbacks defined in `UeberauthToken.Strategy`. See `UeberauthToken.Strategy` """ alias Confex.Resolver @background_checking_by_default? false @use_cache_by_default? false @default_background_frequency 300 @background_worker_log_level :warn @default_cache_name :ueberauth_token @doc """ Get the list of configured providers. """ @spec providers() :: Keyword.t() def providers do case Application.get_env(:ueberauth_token, __MODULE__)[:providers] do {:system, :list, _, _} = config -> Resolver.resolve!(config) config -> config end end @doc """ Get the configuration for a given provider. """ @spec provider_config(provider :: module()) :: Keyword.t() def provider_config(provider) when is_atom(provider) do Application.get_env(:ueberauth_token, provider) end @doc """ Whether the cache is to be started and used or not. Defaults to `true` if not set """ @spec use_cache?(provider :: module()) :: boolean() def use_cache?(provider) when is_atom(provider) do Keyword.get(provider_config(provider), :use_cache, @use_cache_by_default?) end @doc """ Whether the background checks on the token will be performed or not. Defaults to `false` """ @spec background_checks?(provider :: module()) :: boolean() def background_checks?(provider) when is_atom(provider) do Keyword.get(provider_config(provider), :background_checks, @background_checking_by_default?) end @doc """ Get the name for the cache. Defaults to underscored provider name concatenated with `ueberauth_token`. """ @spec cache_name(provider :: module()) :: atom() def cache_name(provider) do Keyword.get(provider_config(provider), :cache_name) || @default_cache_name |> Atom.to_string() |> Kernel.<>("_") |> Kernel.<>(String.replace(Macro.underscore(provider), "/", "_")) |> String.to_atom() end @doc """ The average frequency with which background checks should be performed. Defaults to 300 seconds. """ @spec background_frequency(provider :: module()) :: boolean() def background_frequency(provider) when is_atom(provider) do Keyword.get(provider_config(provider), :background_frequency, @default_background_frequency) end @doc """ The log level at which the background worker will log unexpected timeout and terminate events. Defaults to `:warn` """ @spec background_worker_log_level(provider :: module()) :: boolean() def background_worker_log_level(provider) when is_atom(provider) do Keyword.get( provider_config(provider), :background_worker_log_level, @background_worker_log_level ) end @doc """ Validates a provider as one which has been specified in the configuration. Raises and error if the provider is not configured. """ @spec validate_provider!(provider :: module()) :: :ok | no_return def validate_provider!(provider) do case validate_provider(provider) do {:ok, :valid} -> :ok {:error, :invalid} -> raise("Unknown provider #{provider}, a provider must be configured") end end @doc """ Validates a provider as one which has been specified in the configuration """ @spec validate_provider(provider :: module()) :: {:ok, :valid} | {:error, :invalid} def validate_provider(provider) do if provider in providers() do {:ok, :valid} else {:error, :invalid} end end end
lib/ueberauth_token/config.ex
0.909857
0.517754
config.ex
starcoder
defmodule Pathex.Lenses.Star do @moduledoc """ Private module for `star()` lens """ # Helpers defmacrop extend_if_ok(func, value, acc) do quote do case unquote(func).(unquote(value)) do {:ok, result} -> [result | unquote(acc)] :error -> unquote(acc) end end end defmacrop wrap_ok(code) do quote(do: {:ok, unquote(code)}) end # Lens @spec star() :: Pathex.t() def star do fn :view, {%{} = map, func} -> map |> Enum.reduce([], fn {_key, value}, acc -> extend_if_ok(func, value, acc) end) |> wrap_ok() :view, {t, func} when is_tuple(t) and tuple_size(t) > 0 -> t |> Tuple.to_list() |> Enum.reduce([], fn value, acc -> extend_if_ok(func, value, acc) end) |> :lists.reverse() |> wrap_ok() :view, {[{a, _} | _] = kwd, func} when is_atom(a) -> Enum.reduce(kwd, [], fn {_key, value}, acc -> extend_if_ok(func, value, acc) end) |> :lists.reverse() |> wrap_ok() :view, {l, func} when is_list(l) -> Enum.reduce(l, [], fn value, acc -> extend_if_ok(func, value, acc) end) |> :lists.reverse() |> wrap_ok() :update, {%{} = map, func} -> map |> Map.new(fn {key, value} -> case func.(value) do {:ok, new_value} -> {key, new_value} :error -> {key, value} end end) |> wrap_ok() :update, {t, func} when is_tuple(t) and tuple_size(t) > 0 -> t |> Tuple.to_list() |> Enum.map(fn value -> case func.(value) do {:ok, new_value} -> new_value :error -> value end end) |> List.to_tuple() |> wrap_ok() :update, {[{a, _} | _] = kwd, func} when is_atom(a) -> kwd |> Enum.map(fn {key, value} -> case func.(value) do {:ok, new_value} -> {key, new_value} :error -> {key, value} end end) |> wrap_ok() :update, {l, func} when is_list(l) -> Enum.map(l, fn value -> case func.(value) do {:ok, new_value} -> new_value :error -> value end end) |> wrap_ok() :force_update, {%{} = map, func, default} -> map |> Map.new(fn {key, value} -> case func.(value) do {:ok, v} -> {key, v} :error -> {key, default} end end) |> wrap_ok() :force_update, {t, func, default} when is_tuple(t) and tuple_size(t) > 0 -> t |> Tuple.to_list() |> Enum.map(fn value -> case func.(value) do {:ok, v} -> v :error -> default end end) |> List.to_tuple() |> wrap_ok() :force_update, {[{a, _} | _] = kwd, func, default} when is_atom(a) -> kwd |> Enum.map(fn {key, value} -> case func.(value) do {:ok, v} -> {key, v} :error -> {key, default} end end) |> wrap_ok() :force_update, {l, func, default} when is_list(l) -> l |> Enum.map(fn value -> case func.(value) do {:ok, v} -> v :error -> default end end) |> wrap_ok() op, _ when op in ~w[view update force_update]a -> :error end end end
lib/pathex/lenses/star.ex
0.826397
0.465995
star.ex
starcoder
defmodule Storage do @moduledoc """ This module wraps a lot of the internal storage calls. The goal here is to provide an API abstraction layer so we can swap out how the storage of these systems work in general """ require Logger # ---------------------------------------------------------------------------- # Types # ---------------------------------------------------------------------------- @type gameT :: %{ game_id: String.t(), name: String.t(), owner: String.t(), pay_id: String.t(), image: String.t(), description: String.t(), active: boolean, meta: map, inserted_at: NativeDateTime.t(), updated_at: NativeDateTime.t() } @type guildT :: %{ guild_id: Stringt.t(), name: Stringt.t(), owner: Stringt.t(), pay_id: Stringt.t(), image: Stringt.t(), description: Stringt.t(), members: map(), games: map, active: boolean, meta: map, inserted_at: NativeDateTime.t(), updated_at: NativeDateTime.t() } @type page :: %{ next: boolean, prev: boolean, last_page: integer, next_page: integer, page: integer, first_idx: integer, last_idx: integer, count: integer, list: [gameT | guildT] } # ---------------------------------------------------------------------------- # Public API # ---------------------------------------------------------------------------- @doc """ Get all names for a given setup of IDs """ @spec userNames([String.t()]) :: {:ok, %{String.t() => String.t()}} | {:error, any} def userNames(ids), do: Storage.Auth.User.queryNames(ids) # ---------------------------------------------------------------------------- # Game API # ---------------------------------------------------------------------------- @doc """ Creates a new game in the storage system. As part of the map returned the newly create game_id also attached to the map """ @spec gameCreate(String.t(), String.t(), String.t(), String.t(), String.t(), String.t(), map) :: {:ok, gameT()} | {:error, any} def gameCreate(name, owner, payId, image, fee, description, meta \\ %{}) do info = Storage.Game.new(name, owner, payId, image, fee, description, meta) case Storage.Game.write(info) do {:ok, data} -> {:ok, gameParse(data)} err -> err end end @doc """ Pull out all the active games in the system """ @spec games() :: {:ok, [gameT()]} def games() do {:ok, Enum.map(Storage.Game.queryAll(), fn e -> gameParse(e) end)} end @doc """ Query a specific game """ @spec game(String.t()) :: gameT() | nil def game(gameId) do Storage.Game.query(gameId) |> gameParse() end @doc """ Delete a specific game from the db. Note this does not delete other records that store this game id. This is JUST a storage wipe and not a logic wipe of the game data """ @spec gameDelete(String.t()) :: :ok def gameDelete(gameId), do: Storage.Game.delete(gameId) @doc """ read out a game page in the standard pagenated format """ @spec gamePage(non_neg_integer(), non_neg_integer()) :: {:ok, page()} | {:error, any} def gamePage(page, count) do case Storage.Game.queryPage(page, count) do {:ok, page} -> list = Enum.map(Map.get(page, :list, []), fn i -> gameParse(i) end) {:ok, Map.put(page, :list, list)} err -> err end end @doc """ Get all names for a given setup of IDs """ @spec gameNames([String.t()]) :: {:ok, %{String.t() => String.t()}} | {:error, any} def gameNames(ids), do: Storage.Game.queryNames(ids) @doc """ Get all names """ @spec gameNames() :: {:ok, %{String.t() => String.t()}} | {:error, any} def gameNames(), do: Storage.Game.queryNames() @doc """ Hard set the name of the game """ @spec gameSetName(String.t(), String.t()) :: {:ok, gameT()} | {:error, any} def gameSetName(gameId, name) do case Storage.Game.setName(gameId, name) do {:ok, data} -> {:ok, gameParse(data)} err -> err end end @doc """ Hard set the owner of the game """ @spec gameSetOwner(String.t(), String.t()) :: {:ok, gameT()} | {:error, any} def gameSetOwner(gameId, owner) do case Storage.Game.setOwner(gameId, owner) do {:ok, data} -> {:ok, gameParse(data)} err -> err end end @doc """ Activate the game """ @spec gameSetActive(String.t()) :: {:ok, gameT()} | {:error, any} def gameSetActive(gameId) do case Storage.Game.setActiveValue(gameId, true) do {:ok, data} -> {:ok, gameParse(data)} err -> err end end @doc """ Deactivate the game """ @spec gameSetDeactive(String.t()) :: {:ok, gameT()} | {:error, any} def gameSetDeactive(gameId) do case Storage.Game.setActiveValue(gameId, false) do {:ok, data} -> {:ok, gameParse(data)} err -> err end end @doc """ Set the game image URL """ @spec gameSetImage(String.t(), String.t()) :: {:ok, gameT()} | {:error, any} def gameSetImage(gameId, url) do case Storage.Game.setImage(gameId, url) do {:ok, data} -> {:ok, gameParse(data)} err -> err end end @doc """ Set the game fee """ @spec gameSetFee(String.t(), String.t() | float()) :: {:ok, gameT()} | {:error, any} def gameSetFee(gameId, fee) when is_float(fee) do gameSetFee(gameId, Float.to_string(fee)) end def gameSetFee(gameId, fee) do case Storage.Game.setFee(gameId, fee) do {:ok, data} -> {:ok, gameParse(data)} err -> err end end @doc """ Set the game description """ @spec gameSetDescription(String.t(), String.t()) :: {:ok, gameT()} | {:error, any} def gameSetDescription(gameId, description) do case Storage.Game.setDescription(gameId, description) do {:ok, data} -> {:ok, gameParse(data)} err -> err end end @doc """ Set the game Meta field """ @spec gameSetMeta(String.t(), map) :: {:ok, gameT()} | {:error, any} def gameSetMeta(gameId, meta) do case Storage.Game.setMeta(gameId, meta) do {:ok, data} -> {:ok, gameParse(data)} err -> err end end # ---------------------------------------------------------------------------- # Guild API # ---------------------------------------------------------------------------- @doc """ Creates a new game in the storage system. As part of the map returned the newly create guild_id also attached to the map """ @spec guildCreate(String.t(), String.t(), String.t(), String.t(), String.t(), map) :: {:ok, gameT()} | {:error, any} def guildCreate(name, owner, payId, image, description, meta \\ %{}) do info = Storage.Guild.new(name, owner, payId, image, description, meta) case Storage.Guild.write(info) do {:ok, data} -> {:ok, guildParse(data)} err -> err end end @doc """ Pull out all the active guilds in the system """ @spec guilds() :: {:ok, [guildT()]} def guilds() do {:ok, Enum.map(Storage.Guild.queryAll(), fn e -> guildParse(e) end)} end @doc """ Query a specific game """ @spec guild(String.t()) :: gameT() | nil def guild(guildId) do Storage.Guild.query(guildId) |> guildParse() end @doc """ Delete a specific guild from the db. Note this does not delete other records that store this guild id. This is JUST a storage wipe and not a logic wipe of the guild data """ @spec guildDelete(String.t()) :: :ok def guildDelete(gameId), do: Storage.Guild.delete(gameId) @doc """ Get all names for a given setup of IDs """ @spec guildNames([String.t()]) :: {:ok, [String.t()]} | {:error, any} def guildNames(ids), do: Storage.Guild.queryNames(ids) @doc """ Get all names for the guilds with their IDs """ @spec guildNames() :: {:ok, [String.t()]} | {:error, any} def guildNames(), do: Storage.Guild.queryNames() @doc """ read out a guild page in the standard pagenated format """ @spec guildPage(non_neg_integer(), non_neg_integer()) :: {:ok, page()} | {:error, any} def guildPage(page, count) do case Storage.Guild.queryPage(page, count) do {:ok, page} -> list = Enum.map(Map.get(page, :list, []), fn i -> guildParse(i) end) {:ok, Map.put(page, :list, list)} err -> err end end @doc """ Hard set the members of the Guild. Members format is like so: ``` %{ "userId" => integer_ownership_value } ``` """ @spec guildSetMembers(String.t(), map) :: {:ok, guildT()} | {:error, any} def guildSetMembers(guildId, members) do case Storage.Guild.setMembers(guildId, members) do {:ok, data} -> {:ok, guildParse(data)} err -> err end end @doc """ Hard set the name of the Guild """ @spec guildSetName(String.t(), String.t()) :: {:ok, guildT()} | {:error, any} def guildSetName(guildId, name) do case Storage.Guild.setName(guildId, name) do {:ok, data} -> {:ok, guildParse(data)} err -> err end end @doc """ Hard set the owner of the guild """ @spec guildSetOwner(String.t(), String.t()) :: {:ok, guildT()} | {:error, any} def guildSetOwner(guildId, owner) do case Storage.Guild.setOwner(guildId, owner) do {:ok, data} -> {:ok, guildParse(data)} err -> err end end @doc """ Hard set the games of the guild """ @spec guildSetGames(String.t(), map) :: {:ok, guildT()} | {:error, any} def guildSetGames(guildId, games) do case Storage.Guild.setGames(guildId, games) do {:ok, data} -> {:ok, guildParse(data)} err -> err end end @doc """ Activate the guild """ @spec guildSetActive(String.t()) :: {:ok, guildT()} | {:error, any} def guildSetActive(guildId) do case Storage.Guild.setActiveValue(guildId, true) do {:ok, data} -> {:ok, guildParse(data)} err -> err end end @doc """ Deactivate the guild """ @spec guildSetDeactive(String.t()) :: {:ok, guildT()} | {:error, any} def guildSetDeactive(gameId) do case Storage.Guild.setActiveValue(gameId, false) do {:ok, data} -> {:ok, guildParse(data)} err -> err end end @doc """ Set the guild image URL """ @spec guildSetImage(String.t(), String.t()) :: {:ok, guildT()} | {:error, any} def guildSetImage(gameId, url) do case Storage.Guild.setImage(gameId, url) do {:ok, data} -> {:ok, guildParse(data)} err -> err end end @doc """ Set the guild description """ @spec guildSetDescription(String.t(), String.t()) :: {:ok, guildT()} | {:error, any} def guildSetDescription(guildId, description) do case Storage.Guild.setDescription(guildId, description) do {:ok, data} -> {:ok, guildParse(data)} err -> err end end @doc """ Set the guild meta """ @spec guildSetMeta(String.t(), map) :: {:ok, guildT()} | {:error, any} def guildSetMeta(guildId, meta) do case Storage.Guild.setMeta(guildId, meta) do {:ok, data} -> {:ok, guildParse(data)} err -> err end end # ---------------------------------------------------------------------------- # Private APIs # ---------------------------------------------------------------------------- # Convert the internal struct into a generic map defp gameParse(data), do: Utils.structToMap(data) defp guildParse(data), do: Utils.structToMap(data) # defp guildParse(data), do: Utils.structToMap(data) # defp orderParse(data), do: Utils.structToMap(data) # defp ethParse(data), do: Utils.structToMap(data) # defp xrpParse(data), do: Utils.structToMap(data) # defp userParse(data), do: Utils.structToMap(data) end
src/apps/storage/lib/storage.ex
0.784979
0.490114
storage.ex
starcoder
defmodule Tesseract.Tree.R.Util do alias Tesseract.Geometry.AABB3 alias Tesseract.Geometry.Point3D alias Tesseract.Math.Vec3 def point2entry({label, point}, padding \\ 0) do {Point3D.mbb(point, padding), label} end def points2entries(points, padding \\ 0) when is_list(points) do points |> Enum.map(&(point2entry(&1, padding))) end def entry_mbb({mbb, _}), do: mbb def entry_value({_, value}), do: value def entry_is_leaf?({_, {:leaf, _}}), do: true def entry_is_leaf?(_), do: false def entries_mbb(entries) when is_list(entries) do entries |> Enum.map(&entry_mbb/1) |> AABB3.union() |> AABB3.fix() end def wrap_mbb({_, entries} = node) when is_list(entries) do {entries_mbb(entries), node} end def wrap_depth(entries, depth) when is_list(entries) do depth |> List.duplicate(length(entries)) |> Enum.zip(entries) end def wrap_depth(entry, depth) do {depth, entry} end def depth(tree) do tree_depth(tree, 0) end defp tree_depth({:leaf, _}, d) do d end defp tree_depth({:internal, entries}, d) do entries |> Enum.map(fn {_, node} -> tree_depth(node, d + 1) end) |> Enum.max end def count_entries({:leaf, entries}), do: length(entries) def count_entries({_, entries}) when is_list(entries) do entries |> Enum.map(&elem(&1, 1)) |> Enum.map(&count_entries/1) |> Enum.sum() end def count_entries(_), do: 1 def box_volume_increase(box_a, box_b) do combined = AABB3.union(box_a, box_b) AABB3.volume(combined) - AABB3.volume(box_a) end def box_intersection_volume(box, other_boxes) when is_list(other_boxes) do other_boxes |> Enum.map(&AABB3.intersection_volume(box, &1)) |> Enum.sum end # Computes min/max coordinates along given axis def mbb_axis_minmax({mbb_point_a, mbb_point_b}, axis) do mbb_point_a_axis_value = elem(mbb_point_a, axis) mbb_point_b_axis_value = elem(mbb_point_b, axis) { min(mbb_point_a_axis_value, mbb_point_b_axis_value), max(mbb_point_a_axis_value, mbb_point_b_axis_value) } end # Computes a "margin" for AABB3. That is, a sum of length of all its edges. def mbb_margin({{x1, y1, z1} = a, {x2, y2, z2}}) do 4 * Vec3.length(Vec3.subtract({x2, y1, z1}, a)) + 4 * Vec3.length(Vec3.subtract({x1, y1, z2}, a)) + 4 * Vec3.length(Vec3.subtract({x1, y2, z1}, a)) end end
lib/tree/r/util.ex
0.717705
0.590189
util.ex
starcoder
defmodule Tw.V1_1.Media do @moduledoc """ Media data structure and related functions. https://developer.twitter.com/en/docs/twitter-api/v1/data-dictionary/object-model/entities """ alias Tw.V1_1.Client alias Tw.V1_1.Schema alias Tw.V1_1.Sizes alias Tw.V1_1.Tweet alias Tw.V1_1.User @type id :: pos_integer() @enforce_keys [ :additional_media_info, :video_info, :display_url, :expanded_url, :id, :id_str, :indices, :media_url, :media_url_https, :sizes, :source_status_id, :source_status_id_str, :type, :url ] defstruct([ :additional_media_info, :video_info, :display_url, :expanded_url, :id, :id_str, :indices, :media_url, :media_url_https, :sizes, :source_status_id, :source_status_id_str, :type, :url ]) @typedoc """ > | field | description | > | - | - | > | `display_url` | URL of the media to display to clients. Example: `\"pic.twitter.com/rJC5Pxsu\" `. | > | `expanded_url` | An expanded version of display_url. Links to the media display page. Example: `\"http://twitter.com/yunorno/status/114080493036773378/photo/1\" `. | > | `id` | ID of the media expressed as a 64-bit integer. Example: `114080493040967680 `. | > | `id_str` | ID of the media expressed as a string. Example: `\"114080493040967680\" `. | > | `indices` | An array of integers indicating the offsets within the Tweet text where the URL begins and ends. The first integer represents the location of the first character of the URL in the Tweet text. The second integer represents the location of the first non-URL character occurring after the URL (or the end of the string if the URL is the last part of the Tweet text). Example: `[15,35] `. | > | `media_url` | An http:// URL pointing directly to the uploaded media file. Example: `\"http://pbs.twimg.com/media/DOhM30VVwAEpIHq.jpg\" For media in direct messages, media_url is the same https URL as media_url_https and must be accessed by signing a request with the user’s access token using OAuth 1.0A.It is not possible to access images via an authenticated twitter.com session. Please visit this page to learn how to account for these recent change. You cannot directly embed these images in a web page.See Photo Media URL formatting for how to format a photo's URL, such as media_url_https, based on the available sizes.`. | > | `media_url_https` | An https:// URL pointing directly to the uploaded media file, for embedding on https pages. Example: `\"https://p.twimg.com/AZVLmp-CIAAbkyy.jpg\" For media in direct messages, media_url_https must be accessed by signing a request with the user’s access token using OAuth 1.0A.It is not possible to access images via an authenticated twitter.com session. Please visit this page to learn how to account for these recent change. You cannot directly embed these images in a web page.See Photo Media URL formatting for how to format a photo's URL, such as media_url_https, based on the available sizes.`. | > | `sizes` | An object showing available sizes for the media file. | > | `source_status_id` | Nullable. For Tweets containing media that was originally associated with a different tweet, this ID points to the original Tweet. Example: `205282515685081088 `. | > | `source_status_id_str` | Nullable. For Tweets containing media that was originally associated with a different tweet, this string-based ID points to the original Tweet. Example: `\"205282515685081088\" `. | > | `type` | Type of uploaded media. Possible types include photo, video, and animated_gif. Example: `\"photo\" `. | > | `url` | Wrapped URL for the media link. This corresponds with the URL embedded directly into the raw Tweet text, and the values for the indices parameter. Example: `\"http://t.co/rJC5Pxsu\" `. | > """ @type t :: %__MODULE__{ additional_media_info: %{ optional(:title) => binary(), optional(:description) => binary(), optional(:embeddable) => boolean(), optional(:monetizable) => boolean(), optional(:source_user) => User.t() } | nil, video_info: %{ optional(:duration_millis) => non_neg_integer(), aspect_ratio: list(pos_integer()), variants: list(%{bitrate: non_neg_integer(), content_type: binary(), url: binary()}) } | nil, display_url: binary(), expanded_url: binary(), id: id(), id_str: binary(), indices: list(non_neg_integer()), media_url: binary(), media_url_https: binary(), sizes: Sizes.t(), source_status_id: Tweet.id() | nil, source_status_id_str: binary() | nil, type: :photo | :video | :animated_gif, url: binary() } @spec decode!(map) :: t @doc """ Decode JSON-decoded map into `t:t/0` """ def decode!(json) do json = json |> Map.update!(:type, &String.to_atom/1) |> Map.update( :additional_media_info, nil, Schema.nilable(fn info -> info |> Map.update(:source_user, nil, Schema.nilable(&User.decode!/1)) end) ) |> Map.update!(:sizes, &Sizes.decode!/1) struct(__MODULE__, json) end @type upload_params :: %{ required(:path) => Path.t(), optional(:media_category) => binary(), optional(:additional_owners) => list(pos_integer()) } | %{ required(:device) => IO.device(), required(:media_type) => binary(), required(:total_bytes) => pos_integer(), optional(:media_category) => binary(), optional(:additional_owners) => list(pos_integer()) } | %{ required(:data) => iodata(), required(:media_type) => binary(), optional(:media_category) => binary(), optional(:additional_owners) => list(pos_integer()) } @type upload_ok_result :: %{ media_id: id(), media_id_string: binary(), expires_after_secs: pos_integer() } @type upload_error_result :: %{ media_id: id(), media_id_string: binary(), processing_info: %{ state: binary(), error: %{ code: integer(), name: binary(), message: binary() } } } @chunk_size 1024 * 1024 @doc """ Upload an image or video to Twitter by senqunce of requests to `POST media/upload` and `GET media/upload`. If you want to use more low-level API, use `upload_command/3` instead. ## Examples iex> {:ok, res} = Tw.V1_1.Media.upload(client, %{path: "/tmp/abc.png"}) iex> Tw.V1_1.Tweet.create(client, %{status: "Tweets with a image", media_ids: [res.media_id]}) {:ok, %Tw.V1_1.Tweet{}} iex> {:ok, res} = Tw.V1_1.Media.upload(client, %{data: png_binary, media_type: "image/png"}) iex> Tw.V1_1.Tweet.create(client, %{status: "Tweets with a image", media_ids: [res.media_id]}) {:ok, %Tw.V1_1.Tweet{}} See [the Twitter API documentation](https://developer.twitter.com/en/docs/twitter-api/v1/media/upload-media/overview) for details. """ @spec upload(Client.t(), upload_params()) :: {:ok, upload_ok_result()} | {:error, :file.posix() | Client.error() | upload_error_result()} def upload(client, params) def upload(client, %{path: path} = params) do with {:ok, stat} <- File.stat(path), {:ok, media_type} <- infer_media_type(path), {:ok, device} <- File.open(path, [:binary, :read]) do try do params = params |> Map.delete(:path) |> Map.merge(%{device: device, media_type: media_type, total_bytes: stat.size}) upload(client, params) after File.close(device) end end end def upload(client, %{device: device, media_type: media_type, total_bytes: _total_bytes} = params) do params = params |> Map.delete(:device) |> Map.put_new_lazy(:media_category, fn -> category_from_type(media_type) end) upload_sequence(client, IO.binstream(device, @chunk_size), params) end def upload(client, %{data: data, media_type: media_type} = params) do params = params |> Map.delete(:data) |> Map.put_new_lazy(:total_bytes, fn -> IO.iodata_length(data) end) |> Map.put_new_lazy(:media_category, fn -> category_from_type(media_type) end) upload_sequence(client, data |> IO.iodata_to_binary() |> chunks(), params) end defp upload_sequence(client, chunks, params) do with {:ok, init_result} <- initialize_upload(client, params), :ok <- upload_chunks(client, init_result.media_id, chunks), {:ok, finalize_result} <- finalize_upload(client, init_result.media_id) do wait_for_processing(client, finalize_result) end end defp chunks(<<chunk::binary-size(@chunk_size), rest::binary>>), do: [chunk | chunks(rest)] defp chunks(rest), do: [rest] defp initialize_upload(client, params) do upload_command(client, :post, params |> Map.put(:command, :INIT)) end defp upload_chunks(client, media_id, chunks) do chunks |> Stream.with_index() |> Task.async_stream(fn {bin, i} -> upload_append(client, %{media_id: media_id, media: bin, segment_index: i}) end) |> Enum.filter(&match?({:error, _}, &1)) |> case do [] -> :ok [error | _] -> error end end defp upload_append(client, params) do upload_command(client, :post, params |> Map.put(:command, :APPEND)) end defp finalize_upload(client, media_id) do upload_command(client, :post, %{command: :FINALIZE, media_id: media_id}) end defp wait_for_processing(client, finalize_result) defp wait_for_processing(_client, %{processing_info: %{state: "failed"}} = res) do {:error, res} end defp wait_for_processing(_client, %{processing_info: %{state: "succeeded"}} = res) do {:ok, res} end defp wait_for_processing(client, %{processing_info: %{state: state} = processing_info} = res) when state in ["pending", "in_progress"] do Process.sleep(:timer.seconds(processing_info.check_after_secs)) case upload_command(client, :get, %{command: :STATUS, media_id: res.media_id}) do {:ok, res} -> wait_for_processing(client, res) error -> error end end defp wait_for_processing(_client, res), do: {:ok, res} @type upload_init_command_params :: %{ required(:command) => :INIT, required(:total_bytes) => non_neg_integer(), required(:media_type) => binary(), optional(:media_category) => binary(), optional(:additional_owners) => list(User.id()) } @type upload_append_command_params :: %{ required(:command) => :APPEND, required(:media_id) => pos_integer(), required(:media) => binary(), required(:segment_index) => binary(), optional(:additional_owners) => list(User.id()) } | %{ required(:command) => :APPEND, required(:media_id) => pos_integer(), required(:media_data) => binary(), required(:segment_index) => binary(), optional(:additional_owners) => list(User.id()) } @type upload_finalize_command_params :: %{ required(:command) => :FINALIZE, required(:media_id) => pos_integer() } @type upload_status_command_params :: %{ required(:command) => :STATUS, required(:media_id) => pos_integer() } @type upload_command_params :: upload_init_command_params() | upload_append_command_params() | upload_finalize_command_params() | upload_status_command_params() @spec upload_command(Client.t(), :get | :post, upload_command_params()) :: {:ok, %{atom => term}} | {:error, term} def upload_command(client, method, params) do Client.request(client, method, "/media/upload.json", params) end # https://developer.twitter.com/en/docs/twitter-api/v1/media/upload-media/uploading-media/media-best-practices defp infer_media_type(path) do case Path.extname(path) do ".mp4" -> {:ok, "video/mp4"} ".mov" -> {:ok, "video/quicktime"} ".png" -> {:ok, "image/png"} ".webp" -> {:ok, "image/webp"} ".gif" -> {:ok, "image/gif"} ext when ext in [".jpg", ".jpeg", ".jfif", ".pjpeg", "pjp"] -> {:ok, "image/jpeg"} ".srt" -> {:ok, "application/x-subrip"} name -> {:error, "Could not infer media type from the extension `#{name}`"} end end defp category_from_type("image/gif"), do: "tweet_gif" defp category_from_type("image/" <> _), do: "tweet_image" defp category_from_type("video/" <> _), do: "tweet_video" defp category_from_type("application/x-subrip"), do: "subtitles" @type create_metadata_params :: %{ media_id: id(), alt_text: %{ text: binary() } } @doc """ Add metadata to an uploaded medium by `POST media/metadata/create` > This endpoint can be used to provide additional information about the uploaded media_id. This feature is currently only supported for images and GIFs. See [the Twitter API documentation](https://developer.twitter.com/en/docs/twitter-api/v1/media/upload-media/api-reference/post-media-metadata-create) for details. ## Examples iex> {:ok, res} = Tw.V1_1.Media.upload(client, %{path: "/tmp/abc.png"}) iex> Tw.V1_1.Media.create_metadata(client, %{media_id: res.media_id, alt_text: %{text: "dancing cat"}}) {:ok, ""} """ @spec create_metadata(Client.t(), create_metadata_params()) :: {:ok, binary()} | {:error, Client.error()} def create_metadata(client, params) do params = params |> Map.update!(:media_id, &to_string/1) Client.request(client, :post, "/media/metadata/create.json", params) end @type bind_subtitles_params :: %{ media_id: id(), subtitles: [%{media_id: binary() | pos_integer(), language_code: binary(), display_name: binary()}] } @doc """ Bind subtitles to an uploaded video by requesting `POST media/subtitles/create`. > You can associate subtitles to video before or after Tweeting. See [the Twitter API documentation](https://developer.twitter.com/en/docs/twitter-api/v1/media/upload-media/api-reference/post-media-subtitles-create) for details. ## Examples iex> {:ok, video} = Tw.V1_1.Media.upload(client, %{path: "/tmp/abc.mp4"}) iex> {:ok, en_sub} = Tw.V1_1.Media.upload(client, %{path: "/tmp/en.srt"}) iex> subtitles = [%{media_id: en_sub.media_id, language_code: "EN", display_name: "English"}] iex> {:ok, en_sub} = Tw.V1_1.Media.bind_subtitles(client, %{media_id: video.media_id, subtitles: subtitles}) {:ok, nil} """ @spec bind_subtitles(Client.t(), bind_subtitles_params) :: {:ok, nil} | {:error, Client.error()} def bind_subtitles(client, %{media_id: media_id, subtitles: subtitles}) do params = %{ media_id: media_id |> to_string(), media_category: "TweetVideo", subtitle_info: %{ subtitles: subtitles |> Enum.map(fn sub -> sub |> Map.update!(:media_id, &to_string/1) end) } } Client.request(client, :post, "/media/subtitles/create.json", params) end @type unbind_subtitles_params :: %{ media_id: id(), subtitles: [%{language_code: binary()}] } @doc """ Unbind subtitles to an uploaded video by requesting `POST media/subtitles/delete`. > You can dissociate subtitles from a video before or after Tweeting. See [the Twitter API documentation](https://developer.twitter.com/en/docs/twitter-api/v1/media/upload-media/api-reference/post-media-subtitles-delete) for details. ## Examples iex> {:ok, en_sub} = Tw.V1_1.Media.unbind_subtitles(client, %{media_id: video.media_id, subtitles: [%{language_code: "EN"}]}) {:ok, nil} """ @spec unbind_subtitles(Client.t(), unbind_subtitles_params()) :: {:ok, nil} | {:error, Client.error()} def unbind_subtitles(client, %{media_id: media_id, subtitles: subtitles}) do params = %{ media_id: media_id |> to_string(), media_category: "TweetVideo", subtitle_info: %{ subtitles: subtitles } } Client.request(client, :post, "/media/subtitles/delete.json", params) end end
lib/tw/v1_1/media.ex
0.884651
0.549761
media.ex
starcoder
defmodule Block do @derive [Poison.Encoder] defstruct [:index, :timestamp, :transactions, :hash, :previous_hash, :difficulty, :nonce] @difficulty 5 def generate(previous_block, from, to, value) do new = %Block{ index: previous_block.index + 1, timestamp: DateTime.utc_now() |> DateTime.to_unix(), transactions: [ %Transaction{ id: :crypto.hash(:sha256, DateTime.utc_now() |> DateTime.to_unix() |> Integer.to_string()) |> Base.encode16(), output: %Row{address: from, value: value}, input: %Row{address: to, value: value} } ], previous_hash: previous_block.hash, difficulty: @difficulty } cond do !Wallet.valid_address?(from) -> raise ArgumentError, message: "Address (#{from}): Invalid!" !Wallet.valid_address?(to) -> raise ArgumentError, message: "Address (#{from}): Invalid!" !Transaction.can_withdraw?(from, value) -> raise ArgumentError, message: "Address(#{from}): Do not have enough balance!" true -> Map.merge(new, generate_hash(new)) end end def valid?(block) do calculate_hash(block) == block.hash end def valid?(new_block, previous_block) do cond do previous_block.index + 1 != new_block.index -> false previous_block.hash != new_block.previous_hash -> false calculate_hash(new_block) != new_block.hash -> false true -> true end end def to_string(block) do Enum.join([ block.index |> Integer.to_string(), block.timestamp, block.nonce |> Integer.to_string() ]) end def calculate_hash(block) do :crypto.hash(:sha256, block |> Block.to_string()) |> Base.encode16() end defp generate_hash(block, nonce \\ 1) do hash = calculate_hash(Map.merge(block, %{nonce: nonce})) IO.write("\r#{hash}") case valid_hash?(hash) do true -> %{hash: hash, nonce: nonce} false -> generate_hash(block, nonce + 1) end end defp valid_hash?(hash) do prefix = String.duplicate("0", @difficulty) String.starts_with?(hash, prefix) end end
lib/block/block.ex
0.720958
0.475362
block.ex
starcoder
defmodule AshGraphql.Resource.Query do @moduledoc "Represents a configured query on a resource" defstruct [ :name, :action, :type, :identity, :allow_nil?, :modify_resolution, as_mutation?: false ] @get_schema [ name: [ type: :atom, doc: "The name to use for the query.", default: :get ], action: [ type: :atom, doc: "The action to use for the query.", required: true ], identity: [ type: :atom, doc: "The identity to use for looking up the record. Pass `false` to not use an identity.", required: false ], allow_nil?: [ type: :boolean, default: true, doc: "Whether or not the action can return nil." ], modify_resolution: [ type: :mfa, doc: """ An MFA that will be called with the resolution, the query, and the result of the action as the first three arguments (followed by the arguments in the mfa). Must return a new absinthe resolution. This can be used to implement things like setting cookies based on resource actions. A method of using resolution context for that is documented here: https://hexdocs.pm/absinthe_plug/Absinthe.Plug.html#module-before-send *Important* if you are modifying the context, then you should also set `as_mutation?` to true and represent this in your graphql as a mutation. See `as_mutation?` for more. """ ], as_mutation?: [ type: :boolean, default: false, doc: """ Places the query in the `mutations` key instead. The use cases for this are likely very minimal. If you have a query that needs to modify the graphql context using `modify_resolution`, then you should likely set this as well. A simple example might be a `log_in`, which could be a read action on the user that accepts an email/password, and should then set some context in the graphql inside of `modify_resolution`. Once in the context, you can see the guide referenced in `modify_resolution` for more on setting the session or a cookie with an auth token. """ ] ] @read_one_schema [ name: [ type: :atom, doc: "The name to use for the query.", default: :read_one ], action: [ type: :atom, doc: "The action to use for the query.", required: true ], allow_nil?: [ type: :boolean, default: true, doc: "Whether or not the action can return nil." ] ] @list_schema [ name: [ type: :atom, doc: "The name to use for the query.", default: :list ], action: [ type: :atom, doc: "The action to use for the query.", required: true ] ] def get_schema, do: @get_schema def read_one_schema, do: @read_one_schema def list_schema, do: @list_schema end
lib/resource/query.ex
0.840177
0.552419
query.ex
starcoder
defmodule Arangoex.Database do @moduledoc """ This module contains functions used to manage databases. """ @doc """ Create a new database. The `conn` parameter is an ArangoDB connection PID. The `database` parameter is a map describing the database to be created. ## Endpoint POST /_api/database ## Options See the "Shared Options" in the `Arangoex` module documentation for additional options. ## Examples {:ok, conn} = Arangoex.start_link() {:ok, resp} = Arangoex.Database.create(conn, %{name: "foo"}) """ def create(conn, %{} = database, opts \\ []) do Arangoex.request(conn, :post, "/_api/database", %{}, %{}, database, opts) end @doc """ Return information about the current database. The `conn` parameter is an ArangoDB connection PID. ## Endpoint GET /_api/database/current ## Options See the "Shared Options" in the `Arangoex` module documentation for additional options. ## Examples {:ok, conn} = Arangoex.start_link() {:ok, resp} = Arangoex.Database.current(conn) """ def current(conn, opts \\ []) do Arangoex.request(conn, :get, "/_api/database/current", %{}, %{}, nil, opts) end @doc """ Return a list of databases on the system. The `conn` parameter is an ArangoDB connection PID. ## Endpoint GET /_api/database ## Options See the "Shared Options" in the `Arangoex` module documentation for additional options. ## Examples {:ok, conn} = Arangoex.start_link() {:ok, resp} = Arangoex.Database.list(conn) """ def list(conn, opts \\ []) do Arangoex.request(conn, :get, "/_api/database", %{}, %{}, nil, opts) end @doc """ Return a list of databases on the system for the current user. The `conn` parameter is an ArangoDB connection PID. ## Endpoint GET /_api/database/user ## Options See the "Shared Options" in the `Arangoex` module documentation for additional options. ## Examples {:ok, conn} = Arangoex.start_link() {:ok, resp} = Arangoex.Database.list_for_current_user(conn) """ def list_for_current_user(conn, opts \\ []) do Arangoex.request(conn, :get, "/_api/database/user", %{}, %{}, nil, opts) end @doc """ Remove the given database from the system. The `conn` parameter is an ArangoDB connection PID. The `database_name` parameter is the database to be removed. ## Endpoint DELETE /_api/database/{database_name} ## Options See the "Shared Options" in the `Arangoex` module documentation for additional options. ## Examples {:ok, conn} = Arangoex.start_link() {:ok, resp} = Arangoex.Database.remove(conn, "foo") """ def remove(conn, database_name, opts \\ []) do Arangoex.request(conn, :delete, "/_api/database/#{database_name}", %{}, %{}, nil, opts) end end
lib/arangoex/database.ex
0.858793
0.475788
database.ex
starcoder
defmodule Indicado.SMA do @moduledoc """ This is the SMA module used for calculating Simple Moving Average. """ @doc """ Calculates SMA for the list. Returns `{:ok, sma_list}` or `{:error, reason}` ## Examples iex> Indicado.SMA.eval([1, 3, 5, 7], 2) {:ok, [2.0, 4.0, 6.0]} iex> Indicado.SMA.eval([1, 3], 3) {:error, :not_enough_data} iex> Indicado.SMA.eval([1, 3, 4], 0) {:error, :bad_period} """ @spec eval(nonempty_list(list), pos_integer) :: {:ok, nonempty_list(float)} | {:error, atom} def eval(list, period), do: calc(list, period) @doc """ Calculates SMA for the list. Raises exceptions when arguments does not satisfy needed conditions to calculate SMA. Raises `NotEnoughDataError` if the given list is not longh enough for calculating SMA. Raises `BadPeriodError` if period is an unacceptable number. ## Examples iex> Indicado.SMA.eval!([1, 3, 5, 7], 2) [2.0, 4.0, 6.0] iex> Indicado.SMA.eval!([1, 3], 3) ** (NotEnoughDataError) not enough data iex> Indicado.SMA.eval!([1, 3, 4], 0) ** (BadPeriodError) bad period """ @spec eval!(nonempty_list(list), pos_integer) :: nonempty_list(float) | no_return def eval!(list, period) do case calc(list, period) do {:ok, result} -> result {:error, :not_enough_data} -> raise NotEnoughDataError {:error, :bad_period} -> raise BadPeriodError end end defp calc(list, period, results \\ []) defp calc([], _period, []), do: {:error, :not_enough_data} defp calc(_list, period, _results) when period < 1, do: {:error, :bad_period} defp calc([], _period, results), do: {:ok, Enum.reverse(results)} defp calc([_head | tail] = list, period, results) when length(list) < period do calc(tail, period, results) end defp calc([_head | tail] = list, period, results) do avg = list |> Enum.take(period) |> Enum.sum() |> Kernel./(period) calc(tail, period, [avg | results]) end end
lib/indicado/sma.ex
0.89253
0.532
sma.ex
starcoder
defmodule BMP280.Calibration do @moduledoc false defstruct [ :has_humidity?, :dig_T1, :dig_T2, :dig_T3, :dig_P1, :dig_P2, :dig_P3, :dig_P4, :dig_P5, :dig_P6, :dig_P7, :dig_P8, :dig_P9, :dig_H1, :dig_H2, :dig_H3, :dig_H4, :dig_H5, :dig_H6 ] @type uint16() :: 0..65535 @type int16() :: -32768..32767 @type uint8() :: 0..255 @type int8() :: -128..127 @type int12() :: -2048..2047 @type t() :: %__MODULE__{ has_humidity?: boolean(), dig_T1: uint16(), dig_T2: int16(), dig_T3: int16(), dig_P1: uint16(), dig_P2: int16(), dig_P3: int16(), dig_P4: int16(), dig_P5: int16(), dig_P6: int16(), dig_P7: int16(), dig_P8: int16(), dig_P9: int16(), dig_H1: uint8(), dig_H2: int16(), dig_H3: uint8(), dig_H4: int12(), dig_H5: int12(), dig_H6: int8() } @spec from_binary(<<_::192>> | <<_::248>>) :: BMP280.Calibration.t() def from_binary( <<dig_T1::little-16, dig_T2::little-signed-16, dig_T3::little-signed-16, dig_P1::little-16, dig_P2::little-signed-16, dig_P3::little-signed-16, dig_P4::little-signed-16, dig_P5::little-signed-16, dig_P6::little-signed-16, dig_P7::little-signed-16, dig_P8::little-signed-16, dig_P9::little-signed-16>> ) do %__MODULE__{ has_humidity?: false, dig_T1: dig_T1, dig_T2: dig_T2, dig_T3: dig_T3, dig_P1: dig_P1, dig_P2: dig_P2, dig_P3: dig_P3, dig_P4: dig_P4, dig_P5: dig_P5, dig_P6: dig_P6, dig_P7: dig_P7, dig_P8: dig_P8, dig_P9: dig_P9 } end def from_binary( <<dig_T1::little-16, dig_T2::little-signed-16, dig_T3::little-signed-16, dig_P1::little-16, dig_P2::little-signed-16, dig_P3::little-signed-16, dig_P4::little-signed-16, dig_P5::little-signed-16, dig_P6::little-signed-16, dig_P7::little-signed-16, dig_P8::little-signed-16, dig_P9::little-signed-16, _, dig_H1, dig_H2::little-signed-16, dig_H3, dig_H4h, dig_H4l::4, dig_H5l::4, dig_H5h, dig_H6::signed>> ) do %__MODULE__{ has_humidity?: true, dig_T1: dig_T1, dig_T2: dig_T2, dig_T3: dig_T3, dig_P1: dig_P1, dig_P2: dig_P2, dig_P3: dig_P3, dig_P4: dig_P4, dig_P5: dig_P5, dig_P6: dig_P6, dig_P7: dig_P7, dig_P8: dig_P8, dig_P9: dig_P9, dig_H1: dig_H1, dig_H2: dig_H2, dig_H3: dig_H3, dig_H4: dig_H4h * 16 + dig_H4l, dig_H5: dig_H5h * 16 + dig_H5l, dig_H6: dig_H6 } end end
lib/bmp280/calibration.ex
0.632276
0.575349
calibration.ex
starcoder
defmodule Daguex.Processor.PutImage do use Daguex.Processor alias Daguex.Image import Daguex.Processor.StorageHelper def init(opts) do %{storage: init_storage(required_option(:storage)), name: required_option(:name)} end def process(context, %{storage: storage, name: name}) do image = context.image variants = Image.variants_with_origal(image) |> filter_variants(image, name) with {:ok, context, variant_and_images} <- load_local_images(context, variants) do async(context, %{storage: storage, name: name, variants: variant_and_images}, &async_process/2, &post_process/2) end end def async_process(context, %{storage: {storage, opts}, name: name, variants: variants}) do bucket = Keyword.get(context.opts, :bucket) Enum.reduce_while(variants, {:ok, []}, fn {format, %{"key" => key}, image_file}, {:ok, acc} -> case storage.put(image_file.uri |> to_string, key, bucket, opts) do {:ok, identifier} -> {:cont, {:ok, [%{storage_name: name, format: format, key: identifier} | acc]}} {:ok, identifier, extra} -> {:cont, {:ok, [%{storage_name: name, format: format, key: identifier, extra: extra}|acc]}} error -> {:halt, error} end end) end def post_process(context, data) do Enum.reduce(data, {:ok, context}, fn %{storage_name: name, format: format, key: key}, {:ok, context} -> image = context.image |> update_key(name, format, key) {:ok, %{context | image: image}} %{storage_name: name, format: format, key: key, extra: extra}, {:ok, context} -> image = context.image |> update_key(name, format, key) |> update_extra(name, format, extra) {:ok, %{context | image: image}} end) end defp load_local_images(context, variants) do Enum.reduce_while(variants, {:ok, context, []}, fn {format, variant}, {:ok, context, acc} -> with {:ok, context, image_file} <- load_local_image(context, format) do {:cont, {:ok, context, [{format, variant, image_file}|acc]}} else e -> {:halt, e} end end) end defp init_storage({storage, opts}), do: {storage, opts} defp init_storage(storage), do: {storage, []} defp filter_variants(variants, image, name) do Enum.reject(variants, &saved?(image, name, elem(&1, 0))) end end
lib/daguex/processor/put_image.ex
0.61173
0.417895
put_image.ex
starcoder
defmodule Abacus do @moduledoc """ A math-expression parser, evaluator and formatter for Elixir. ## Features ### Supported operators - `+`, `-`, `/`, `*` - Exponentials with `^` - Factorial (`n!`) - Bitwise operators * `<<` `>>` bitshift * `&` bitwise and * `|` bitwise or * `|^` bitwise xor * `~` bitwise not (unary) - Boolean operators * `&&`, `||`, `not` * `==`, `!=`, `>`, `>=`, `<`, `<=` * Ternary `condition ? if_true : if_false` ### Supported functions - `sin(x)`, `cos(x)`, `tan(x)` - `round(n, precision = 0)`, `ceil(n, precision = 0)`, `floor(n, precision = 0)` ### Reserved words - `true` - `false` - `null` ### Access to variables in scope - `a` with scope `%{"a" => 10}` would evaluate to `10` - `a.b` with scope `%{"a" => %{"b" => 42}}` would evaluate to `42` - `list[2]` with scope `%{"list" => [1, 2, 3]}` would evaluate to `3` ### Data types - Boolean: `true`, `false` - None: `null` - Integer: `0`, `40`, `-184` - Float: `0.2`, `12.`, `.12` - String: `"Hello World"`, `"He said: \"Let's write a math parser\""` If a variable is not in the scope, `eval/2` will result in `{:error, error}`. """ @doc """ Evaluates the given expression with no scope. If `expr` is a string, it will be parsed first. """ @spec eval(expr::tuple | charlist | String.t) :: {:ok, result::number} | {:error, error::map} @spec eval(expr::tuple | charlist | String.t, scope::map) :: {:ok, result::number} | {:error, error::map} @spec eval!(expr::tuple | charlist | String.t) :: result::number @spec eval!(expr::tuple | charlist | String.t, scope::map) :: result::number def eval(source, scope \\ [], vars \\ %{}) def eval(source, scope, _vars) when is_binary(source) or is_bitstring(source) do with {:ok, ast, vars} <- compile(source) do eval(ast, scope, vars) end end def eval(expr, scope, vars) do scope = Abacus.Runtime.Scope.prepare_scope(scope, vars) try do case Code.eval_quoted(expr, scope) do {result, _} -> {:ok, result} end rescue e -> {:error, e} catch e -> {:error, e} end end @doc """ Evaluates the given expression. Raises errors when parsing or evaluating goes wrong. """ def eval!(expr) do eval!(expr, %{}) end @doc """ Evaluates the given expression with the given scope. If `expr` is a string, it will be parsed first. """ def eval!(expr, scope) do case Abacus.eval(expr, scope) do {:ok, result} -> result {:error, error} -> raise error end end def compile(source) when is_binary(source) do source |> String.to_charlist() |> compile() end def compile(source) when is_list(source) do with _ = Process.put(:variables, %{}), {:ok, tokens, _} <- :math_term.string(source), {:ok, ast} <- :new_parser.parse(tokens) do vars = Process.get(:variables) ast = Abacus.Compile.post_compile(ast, vars) Process.delete(:variables) {:ok, ast, vars} end end @spec format(expr :: tuple | String.t | charlist) :: {:ok, String.t} | {:error, error::map} @doc """ Pretty-prints the given expression. If `expr` is a string, it will be parsed first. """ def format(expr) when is_binary(expr) or is_bitstring(expr) do case compile(expr) do {:ok, expr, _vars} -> format(expr) {:error, _} = error -> error end end def format(expr) do try do {:ok, Abacus.Format.format(expr)} rescue error -> {:error, error} end end end
lib/abacus.ex
0.723212
0.724627
abacus.ex
starcoder
defmodule RDF.Serialization.ParseHelper do @moduledoc false alias RDF.IRI @rdf_type RDF.Utils.Bootstrapping.rdf_iri("type") def rdf_type, do: @rdf_type def to_iri_string({:iriref, _line, value}), do: value |> iri_unescape def to_iri({:iriref, line, value}) do with iri = RDF.iri(iri_unescape(value)) do if IRI.valid?(iri) do {:ok, iri} else {:error, line, "#{value} is not a valid IRI"} end end end def to_absolute_or_relative_iri({:iriref, _line, value}) do with iri = RDF.iri(iri_unescape(value)) do if IRI.absolute?(iri) do iri else {:relative_iri, value} end end end def to_bnode({:blank_node_label, _line, value}), do: RDF.bnode(value) def to_bnode({:anon, _line}), do: RDF.bnode() def to_literal({:string_literal_quote, _line, value}), do: value |> string_unescape |> RDF.literal() def to_literal({:integer, _line, value}), do: RDF.literal(value) def to_literal({:decimal, _line, value}), do: RDF.literal(value) def to_literal({:double, _line, value}), do: RDF.literal(value) def to_literal({:boolean, _line, value}), do: RDF.literal(value) def to_literal({:string_literal_quote, _line, value}, {:language, language}), do: value |> string_unescape |> RDF.literal(language: language) def to_literal({:string_literal_quote, _line, value}, {:datatype, %IRI{} = type}), do: value |> string_unescape |> RDF.literal(datatype: type) def to_literal(string_literal_quote_ast, type), do: {string_literal_quote_ast, type} def integer(value), do: RDF.XSD.Integer.new(List.to_string(value)) def decimal(value), do: RDF.XSD.Decimal.new(List.to_string(value)) def double(value), do: RDF.XSD.Double.new(List.to_string(value)) def boolean('true'), do: true def boolean('false'), do: false def to_langtag({:langtag, _line, value}), do: value def to_langtag({:"@prefix", 1}), do: "prefix" def to_langtag({:"@base", 1}), do: "base" def bnode_str('_:' ++ value), do: List.to_string(value) def langtag_str('@' ++ value), do: List.to_string(value) def quoted_content_str(value), do: value |> List.to_string() |> String.slice(1..-2) def long_quoted_content_str(value), do: value |> List.to_string() |> String.slice(3..-4) def prefix_ns(value), do: value |> List.to_string() |> String.slice(0..-2) def prefix_ln(value), do: value |> List.to_string() |> String.split(":", parts: 2) |> List.to_tuple() def string_unescape(string), do: string |> unescape_8digit_unicode_seq |> Macro.unescape_string(&string_unescape_map(&1)) def iri_unescape(string), do: string |> unescape_8digit_unicode_seq |> Macro.unescape_string(&iri_unescape_map(&1)) defp string_unescape_map(?b), do: ?\b defp string_unescape_map(?f), do: ?\f defp string_unescape_map(?n), do: ?\n defp string_unescape_map(?r), do: ?\r defp string_unescape_map(?t), do: ?\t defp string_unescape_map(?u), do: true defp string_unescape_map(:unicode), do: true defp string_unescape_map(e), do: e defp iri_unescape_map(?u), do: true defp iri_unescape_map(:unicode), do: true defp iri_unescape_map(e), do: e def 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 def error_description(error_descriptor) when is_list(error_descriptor) do error_descriptor |> Stream.map(&to_string/1) |> Enum.join("") end def error_description(error_descriptor), do: inspect(error_descriptor) end
lib/rdf/serialization/parse_helper.ex
0.609524
0.491883
parse_helper.ex
starcoder
defmodule Surgex.Guide.CodeStyle do @moduledoc """ Basic code style and formatting guidelines. """ @doc """ Indentation must be done with 2 spaces. ## Reasoning This is [kind of a delicate subject](https://youtu.be/SsoOG6ZeyUI), but seemingly both Elixir and Ruby communities usually go for spaces, so it's best to stay aligned. When it comes to linting, the use of specific number of spaces works well with the line length rule, while tabs can be expanded to arbitrary number of soft spaces in editor, possibly ruining all the hard work put into staying in line with the column limit. As to the number of spaces, 2 seems to be optimal to allow unconstrained module, function and block indentation without sacrificing too many columns. ## Examples Preferred: defmodule User do def blocked?(user) do !user.confirmed || user.blocked end end Too deep indentation (and usual outcome of using tabs): defmodule User do def blocked?(user) do !user.confirmed || user.blocked end end Missing single space: defmodule User do def blocked?(user) do !user.confirmed || user.blocked end end """ def indentation, do: nil @doc """ Lines must not be longer than 100 characters. ## Reasoning The old-school 70 or 80 column limits seem way limiting for Elixir which is highly based on indenting blocks. Considering modern screen resolutions, 100 columns should work well for anyone with something more modern than CGA video card. Also, 100 column limit plays well with GitHub, CodeClimate, HexDocs and others. ## Examples Preferred: defmodule MyProject.Accounts.User do def build(%{ "first_name" => first_name, "last_name" => last_name, "email" => email, "phone_number" => phone_number }) do %__MODULE__{ first_name: first_name, last_name: last_name, email: email, phone_number: phone_number } end end Missing line breaks before limit: defmodule MyProject.Accounts.User do def build(%{"first_name" => first_name, "last_name" => last_name, "email" => email, "phone_number" => phone_number}) do %__MODULE__{first_name: first_name, last_name: last_name, email: email, phone_number: phone_number} end end """ def line_length, do: nil @doc """ Lines must not end with trailing white-space. ## Reasoning Leaving white-space at the end of lines is a bad programming habit that leads to crazy diffs in version control once developers that do it get mixed with those that don't. Most editors can be tuned to automatically trim trailing white-space on save. ## Examples Preferred: func() Hidden white-space (simulated by adding comment at the end of line): func() # line end """ def trailing_whitespace, do: nil @doc """ Files must end with single line break. ## Reasoning Many editors and version control systems consider files without final line break invalid. In git, such last line gets highlighted with an alarming red. Like with trailing white-space, it's a bad habit to leave such artifacts and ruin diffs for developers who save files correctly. Reversely, leaving too many line breaks is just sloppy. Most editors can be tuned to automatically add single trailing line break on save. ## Examples Preferred: func()⮐ Missing line break: func() Too many line breaks: func()⮐ ⮐ """ def trailing_newline, do: nil @doc """ Single space must be put around operators. ## Reasoning It's a matter of keeping variable names readable and distinct in operator-intensive situations. There should be no technical problem with such formatting even in long lines, since those can be easily broken into multiple, properly indented lines. ## Examples Preferred: (a + b) / c Hard to read: (a+b)/c """ def operator_spacing, do: nil @doc """ Single space must be put after commas. ## Reasoning It's a convention that passes through many languages - it looks good and so there's no reason to make an exception for Elixir on this one. ## Examples Preferred: fn(arg, %{first: first, second: second}), do: nil Three creative ways to achieve pure ugliness by omitting comma between arguments, map keys or before inline `do`: fn(arg,%{first: first,second: second}),do: nil """ def comma_spacing, do: nil @doc """ There must be no space put before `}`, `]` or `)` and after `{`, `[` or `(` brackets. ## Reasoning It's often tempting to add inner padding for tuples, maps, lists or function arguments to give those constructs more space to breathe, but these structures are distinct enough to be readable without it. They may actually be more readable without the padding, because this rule plays well with other spacing rules (like comma spacing or operator spacing), making expressions that combine brackets and operators have a distinct, nicely parse-able "rhythm". Also, when allowed to pad brackets, developers tend to add such padding inconsistently - even between opening and ending in single line. This gets even worse once a different developer modifies such code and has a different approach towards bracket spacing. Lastly, it keeps pattern matchings more compact and readable, which invites developers to utilize this wonderful Elixir feature to the fullest. ## Examples Preferred: def func(%{first: second}, [head | tail]), do: nil Everything padded and unreadable (no "rhythm"): def func( %{ first: second }, [ head | tail ] ), do: nil Inconsistencies: def func( %{first: second}, [head | tail]), do: nil """ def bracket_spacing, do: nil @doc """ There must be no space put after the `!` operator. ## Reasoning Like with brackets, it may be tempting to pad negation to make it more visible, but in general unary operators tend to be easier to parse when they live close to their argument. Why? Because they usually have precedence over binary operators and padding them away from their argument makes this precedence less apparent. ## Examples Preferred: !blocked && allowed Operator precedence mixed up: ! blocked && allowed """ def negation_spacing, do: nil @doc """ `;` must not be used to separate statements and expressions. ## Reasoning This is the most classical case when it comes to preference of vertical over horizontal alignment. Let's just keep `;` operator for `iex` sessions and focus on code readability over doing code minification manually - neither EVM nor GitHub will explode over that additional line break. > Actually, ", " costs one more byte than an Unix line break but if that would be our biggest > concern then I suppose we wouldn't prefer spaces over tabs for indentation... ## Examples Preferred: func() other_func() `iex` session saved to file by mistake: func(); other_func() """ def semicolon_usage, do: nil @doc """ Indentation blocks must never start or end with blank lines. ## Reasoning There's no point in adding additional vertical spacing since we already have horizontal padding increase/decrease on block start/end. ## Examples Preferred: def parent do nil end Wasted line: def parent do nil end """ def block_inner_spacing, do: nil @doc """ Indentation blocks should be padded from surrounding code with single blank line. ## Reasoning There are probably as many approaches to inserting blank lines between regular code as there are developers, but the common aim usually is to break the heaviest parts into separate "blocks". This rule tries to highlight one most obvious candidate for such "block" which is... an actual block. Since blocks are indented on the inside, there's no point in padding them there, but the outer parts of the block (the line where `do` appears and the line where `end` appears) often include a key to a reasoning about the whole block and are often the most important parts of the whole parent scope, so it may be beneficial to make that part distinct. In case of Elixir it's even more important, since block openings often include non-trivial destructuring, pattern matching, wrapping things in tuples etc. ## Examples Preferred (there's blank line before the `Enum.map` block since there's code (`array = [1, 2, 3]`) in parent block, but there's no blank line after that block since there's no more code after it): def parent do array = [1, 2, 3] Enum.map(array, fn number -> number + 1 end) end Obfuscated block: def parent do array = [1, 2, 3] big_numbers = Enum.map(array, fn number -> number + 1 end) big_numbers ++ [5, 6, 7] end """ def block_outer_spacing, do: nil @doc """ Vertical blocks should be preferred over horizontal blocks. ## Reasoning There's often more than one way to achieve the same and the difference is in fitting things horizontally through indentation vs vertically through function composition. This rule is about preference of the latter over the former in order to avoid crazy indentation, have more smaller functions, which makes for a code easier to understand and extend. ## Examples Too much crazy indentation to fit everything in one function: defp map_array(array) do array |> Enum.uniq |> Enum.map(fn array_item -> if is_binary(array_item) do array_item <> " (changed)" else array_item + 1 end end) end Preferred refactor of the above: defp map_array(array) do array |> Enum.uniq |> Enum.map(&map_array_item/1) end defp map_array_item(array_item) when is_binary(array_item), do: array_item <> " (changed)" defp map_array_item(array_item), do: array_item + 1 """ def block_alignment, do: nil @doc """ Inline blocks should be preferred for simple code that fits one line. ## Reasoning In case of simple and small functions, conditions etc, the inline variant of block allows to keep code more compact and fit biggest piece of the story on the screen without losing readability. ## Examples Preferred: def add_two(number), do: number + 2 Wasted vertical space: def add_two(number) do number + 2 end Too long (or too complex) to be inlined: def add_two_and_multiply_by_the_meaning_of_life_and_more(number), do: (number + 2) * 42 * get_more_for_this_truly_crazy_computation(number) """ def inline_block_usage, do: nil @doc """ Multi-line calculations should be indented by one level for assignment. ## Reasoning Horizontal alignment is something especially tempting in Elixir programming as there are many operators and structures that look cool when it gets applied. In particular, pipe chains only look good when the pipe "comes out" from the initial value. In order to achieve that in assignment, vertical alignment is often overused. The issue is with future-proofness of such alignment. For instance, it may easily get ruined without developer's attention in typical find-and-replace sessions that touch the name on the left side of `=` sign. Hence this rule, which is about inserting a new line after the `=` and indenting the right side calculation by one level. ## Examples Preferred: user = User |> build_query() |> apply_scoping() |> Repo.one() Cool yet not so future-proof: user = User |> build_query() |> apply_scoping() |> Repo.one() Find-and-replace session result on the above: authorized_user = User |> build_query() |> apply_scoping() |> Repo.one() """ def assignment_indentation, do: nil @doc """ Keywords in Ecto queries should be indented by one level (and one more for `on` after `join`). ## Reasoning Horizontal alignment is something especially tempting in Elixir programming as there are many operators and structures that look cool when it gets applied. In particular, Ecto queries are often written (and they do look good) when aligned to `:` after `from` macro keywords. In order to achieve that, vertical alignment is often overused. The issue is with future-proofness of such alignment. For instance, it'll get ruined when longer keyword will have to be added, such as `preload` or `select` in queries with only `join` or `where`. It's totally possible to adhere to the 2 space indentation rule and yet to write a good looking and readable Ecto query. In order to make things more readable, additional 2 spaces can be added for contextual indentation of sub-keywords, like `on` after `join`. ## Examples Preferred: from users in User, join: credit_cards in assoc(users, :credit_card), on: is_nil(credit_cards.deleted_at), where: is_nil(users.deleted_at), select: users.id, preload: [:credit_card], Cool yet not so future-proof: from users in User, join: credit_cards in assoc(users, :credit_card), on: is_nil(credit_cards.deleted_at), where: is_nil(users.deleted_at) """ def ecto_query_indentation, do: nil @doc """ Pipe chains must be used only for multiple function calls. ## Reasoning The whole point of pipe chain is that... well, it must be a *chain*. As such, single function call does not qualify. Reversely, nesting multiple calls instead of piping them seriously limits the readability of the code. ## Examples Preferred for 2 and more function calls: arg |> func() |> other_func() Preferred for 1 function call: yet_another_func(a, b) Not preferred: other_func(func(arg)) a |> yet_another_func(b) """ def pipe_chain_usage, do: nil @doc """ Pipe chains must be started with a plain value. ## Reasoning The whole point of pipe chain is to push some value through the chain, end to end. In order to do that consistently, it's best to keep away from starting chains with function calls. This also makes it easier to see if pipe operator should be used at all - since chain with 2 pipes may get reduced to just 1 pipe when inproperly started with function call, it may falsely look like a case when pipe should not be used at all. ## Examples Preferred: arg |> func() |> other_func() Chain that lost its reason to live: func(arg) |> other_func() """ def pipe_chain_start, do: nil @doc """ Large numbers must be padded with underscores. ## Reasoning They're just more readable that way. It's one of those cases when a minimal effort can lead to eternal gratitude from other committers. ## Examples Preferred: x = 50_000_000 "How many zeros is that" puzzle (hint: not as many as in previous example): x = 5000000 """ def number_padding, do: nil @doc """ Functions should be called with parentheses. ## Reasoning There's a convention in Elixir universe to make function calls distinct from macro calls by consistently covering them with parentheses. Function calls often take part in multiple operations in a single line or inside pipes and as such, it's just safer to mark the precedence via parentheses. ## Examples Preferred: first() && second(arg) Unreadable and with compiler warning coming up: first && second arg """ def function_call_parentheses, do: nil @doc """ Macros should be called without parentheses. ## Reasoning There's a convention in Elixir universe to make function calls distinct from macro calls by consistently covering them with parentheses. Compared to functions, macros are often used as a DSL, with one macro invocation per line. As such, they can be safely written (and just look better) without parentheses. ## Examples Preferred: if bool, do: nil from t in table, select: t.id Macro call that looks like a function call: from(t in table, select: t.id) """ def macro_call_parentheses, do: nil @doc """ Single blank line must be inserted after `@moduledoc`. ## Reasoning `@moduledoc` is a module-wide introduction to the module. It makes sense to give it padding and separate it from what's coming next. The reverse looks especially bad when followed by a function that has no `@doc` clause yet. ## Examples Preferred: defmodule SuperMod do @moduledoc \""" This module is seriously amazing. \""" def call, do: nil end `@moduledoc` that pretends to be a `@doc`: defmodule SuperMod do @moduledoc \""" This module is seriously amazing. \""" def call, do: nil end """ def moduledoc_spacing, do: nil @doc """ There must be no blank lines between `@doc` and the function definition. ## Reasoning Compared to moduledoc spacing, the `@doc` clause belongs to the function definition directly beneath it, so the lack of blank line between the two is there to make this linkage obvious. If the blank line is there, there's a growing risk of `@doc` clause becoming completely separated from its owner in the heat of future battles. ## Examples Preferred: @doc \""" This is by far the most complex function in the universe. \""" def func, do: nil Weak linkage: @doc \""" This is by far the most complex function in the universe. \""" def func, do: nil Broken linkage: @doc \""" This is by far the most complex function in the universe. \""" def non_complex_func, do: something_less_complex_than_returning_nil() def func, do: nil """ def doc_spacing, do: nil @doc """ Aliases should be preferred over using full module name. ## Reasoning Aliasing modules makes code more compact and easier to read. They're even more beneficial as the number of uses of aliased module grows. That's of course assuming they don't override other used modules or ones that may be used in the future (such as stdlib's `IO` or similar). ## Examples Preferred: def create(params) alias Toolbox.Creator params |> Creator.build() |> Creator.call() |> Toolbox.IO.write() end Not so DRY: def create(params) params |> Toolbox.Creator.build() |> Toolbox.Creator.call() |> Toolbox.IO.write() end Overriding standard library: def create(params) alias Toolbox.IO params |> Toolbox.Creator.build() |> Toolbox.Creator.call() |> IO.write() end """ def alias_usage, do: nil @doc """ Reuse directives against same module should be grouped with `{}` syntax and sorted A-Z. ## Reasoning The fresh new grouping feature for `alias`, `import`, `require` and `use` allows to make multiple reuses from single module shorter, more declarative and easier to comprehend. It's just a challenge to use this feature consistently, hence this rule. Keeping sub-module names in separate lines (even when they could fit a single line) is an additional investment for the future - to have clean diffs when more modules will get added. It's also easier to keep them in alphabetical order when they're in separate lines from day one. ## Examples Preferred: alias Toolbox.{ Creator, Deletor, Other, } alias SomeOther.Mod Short but not so future-proof: alias Toolbox.{Creator, Deletor, Other} Classical but inconsistent and not so future-proof: alias Toolbox.Creator alias Toolbox.Deletor alias SomeOther.Mod alias Toolbox.Other """ def reuse_directive_grouping, do: nil @doc """ Per-function usage of reuse directives should be preferred over module-wide usage. ## Reasoning If a need for `alias`, `import` or `require` spans only across single function in a module (or across a small subset of functions in otherwise large module), it should be preferred to declare it locally on top of that function instead of globally for whole module. Keeping these declarations local makes them even more descriptive as to what scope is really affected. They're also more visible, being closer to the place they're used at. The chance for conflicts is also reduced when they're local. ## Examples Preferred (`alias` on `Users.User` is used in both `create` and `delete` functions so it's made global, but `import` on `Ecto.Query` is only used in `delete` function so it's declared only there): defmodule Users do alias Users.User def create(params) %User{} |> User.changeset(params) |> Repo.insert() end def delete(user_id) do import Ecto.Query Repo.delete_all(from users in User, where: users.id == ^user_id) end end Not so DRY (still, this could be OK if there would be more functions in `Users` module that wouldn't use the `User` sub-module): defmodule Users do def create(params) alias Users.User %User{} |> User.changeset(params) |> Repo.insert() end def delete(user_id) do import Ecto.Query alias Users.User Repo.delete_all(from users in User, where: users.id == ^user_id) end end Everything a bit too public: defmodule Users do import Ecto.Query alias Users.User def create(params) %User{} |> User.changeset(params) |> Repo.insert() end def delete(user_id) do Repo.delete_all(from users in User, where: users.id == ^user_id) end end """ def reuse_directive_scope, do: nil @doc """ Reuse directives should be placed on top of modules or functions. ## Reasoning Calls to `alias`, `import`, `require` or `use` should be placed on top of module or function, or directly below `@moduledoc` in case of modules with documentation. Just like with the order rule, this is to make finding these directives faster when reading the code. For that reason, it's more beneficial to have such important key for interpreting code in obvious place than attempting to have them right above the point where they're needed (which usually ends up messed up anyway when code gets changed over time). ## Examples Preferred: defmodule Users do alias Users.User def name(user) do user["name"] || user.name end def delete(user_id) do import Ecto.Query user_id = String.to_integer(user_id) Repo.delete_all(from users in User, where: users.id == ^user_id) end end Cool yet not so future-proof "lazy" placement: defmodule Users do def name(user) do user["name"] || user.name end alias Users.User def delete(user_id) do user_id = String.to_integer(user_id) import Ecto.Query Repo.delete_all(from users in User, where: users.id == ^user_id) end end """ def reuse_directive_placement, do: nil @doc """ Calls to reuse directives should be placed in `use`, `require`, `import`,`alias` order. ## Reasoning First of all, having any directive ordering convention definitely beats not having one, since they are a key to parsing code and so it adds up to better code reading experience when you know exactly where to look for an alias or import. This specific order is an attempt to introduce more significant directives before more trivial ones. It so happens that in case of reuse directives, the reverse alphabetical order does exactly that, starting with `use` (which can do virtually anything with a target module) and ending with `alias` (which is only a cosmetic change and doesn't affect the module's behavior). ## Examples Preferred: use Helpers.Thing import Helpers.Other alias Helpers.Tool Out of order: alias Helpers.Tool import Helpers.Other use Helpers.Thing """ def reuse_directive_order, do: nil @doc """ Calls to reuse directives should not be separated with blank lines. ## Reasoning It may be tempting to separate all aliases from imports with blank line or to separate multi-line grouped aliases from other aliases, but as long as they're properly placed and ordered, they're readable enough without such extra efforts. Also, as their number grows, it's more beneficial to keep them vertically compact than needlessly padded. ## Examples Preferred: use Helpers.Thing import Helpers.Other alias Helpers.Subhelpers.{ First, Second } alias Helpers.Tool Too much padding (with actual code starting N screens below): use Helpers.Thing import Helpers.Other alias Helpers.Subhelpers.{ First, Second } alias Helpers.Tool """ def reuse_directive_spacing, do: nil @doc """ RESTful actions should be placed in `I S N C E U D` order in controllers and their tests. ## Reasoning It's important to establish a consistent order to make it easier to find actions and their tests, considering that both controller and (especially) controller test files tend to be big at times. This particular order (`index`, `show`, `new`, `create`, `edit`, `update`, `delete`) comes from the long-standing convention established by both Phoenix and, earlier, Ruby on Rails generators, so it should be familiar, predictable and non-surprising to existing developers. ## Examples Preferred: defmodule MyProject.Web.UserController do use MyProject.Web, :controller def index(_conn, _params), do: raise("Not implemented") def show(_conn, _params), do: raise("Not implemented") def new(_conn, _params), do: raise("Not implemented") def create(_conn, _params), do: raise("Not implemented") def edit(_conn, _params), do: raise("Not implemented") def update(_conn, _params), do: raise("Not implemented") def delete(_conn, _params), do: raise("Not implemented") end Different (CRUD-like) order against the convention: defmodule MyProject.Web.UserController do use MyProject.Web, :controller def index(_conn, _params), do: raise("Not implemented") def new(_conn, _params), do: raise("Not implemented") def create(_conn, _params), do: raise("Not implemented") def show(_conn, _params), do: raise("Not implemented") def edit(_conn, _params), do: raise("Not implemented") def update(_conn, _params), do: raise("Not implemented") def delete(_conn, _params), do: raise("Not implemented") end > The issue with CRUD order is that `index` action falls between fitting and being kind of "above" the *Read* section and `new`/`edit` actions fall between *Read* and *Create*/*Update* sections, respectively. """ def restful_action_order, do: nil @doc """ Documentation in `@doc` and `@moduledoc` should start with an one-line summary sentence. ## Reasoning This first line is treated specially by ExDoc in that it's taken as a module/function summary for API summary listings. The period at its end is removed so that it looks good both as a summary (without the period) and as part of a whole documentation (with a period). The single-line limit (with up to 100 characters as per line limit rule) is there to avoid mixing up short and very long summaries on a single listing. It's also important to fit as precise description as possible in this single line, without unnecessarily repeating what's already expressed in the module or function name itself. ## Examples Preferred: defmodule MyProject.Accounts do @moduledoc \""" User account authorization and management system. \""" end Too vague: defmodule MyProject.Accounts do @moduledoc \""" Accounts system. \""" end Missing trailing period: defmodule MyProject.Accounts do @moduledoc \""" Accounts system \""" end Missing trailing blank line: defmodule MyProject.Accounts do @moduledoc \""" User account authorization and management system. All functions take the `MyProject.Accounts.Input` structure as input argument. \""" end """ def doc_summary_format, do: nil @doc """ Documentation in `@doc` and `@moduledoc` should be written in ExDoc-friendly Markdown. Here's what is considered an ExDoc-friendly Markdown: - Paragraphs written with full sentences, separated by a blank line - Headings starting from 2nd level heading (`## Biggest heading`) - Bullet lists starting with a dash and subsequent lines indented by 2 spaces - Bullet/ordered list items separated by a blank line - Elixir code indented by 4 spaces to mark the code block ## Reasoning This syntax is encouraged in popular Elixir libraries, it's confirmed to generate nicely readable output and it's just as readable in the code which embeds it as well. ## Examples Preferred: defmodule MyProject.Accounts do @moduledoc \""" User account authorization and management system. This module does truly amazing stuff. It's purpose is to take anything you pass its way and make an user out of that. It can also tell you if specific user can do specific things without messing the system too much. Here's what you can expect from this module: - Nicely written lists with a lot of precious information that get indented properly in every subsequent line - And that are well padded as well And here's an Elixir code example: defmodule MyProject.Accounts.User do @defstruct [:name, :email] end It's all beautiful, isn't it? \""" end Messed up line breaks, messed up list item indentation and non ExDoc-ish code block: defmodule MyProject.Accounts do @moduledoc \""" User account authorization and management system. This module does truly amazing stuff. It's purpose is to take anything you pass its way and make an user out of that. It can also tell you if specific user can do specific things without messing the system too much. Here's what you can expect from this module: - Nicely written lists with a lot of precious information that get indented properly in every subsequent line - And that are well padded as well And here's an Elixir code example: ``` defmodule MyProject.Accounts.User do @defstruct [:name, :email] end ``` It's not so beautiful, is it? \""" end """ def doc_content_format, do: nil @doc """ Config calls should be placed in alphabetical order, with modules over atoms. ## Reasoning Provides obvious and predictable placement of specific config calls. ## Examples Preferred: config :another_package, key: value config :my_project, MyProject.A, key: "value" config :my_project, MyProject.B, key: "value" config :my_project, :a, key: "value" config :my_project, :b, key: "value" config :package, key: "value" Modules wrongly mixed with atoms and internal props wrongly before external ones: config :my_project, MyProject.A, key: "value" config :my_project, :a, key: "value" config :my_project, MyProject.B, key: "value" config :my_project, :b, key: "value" config :another_package, key: value config :package, key: "value" """ def config_order, do: nil @doc ~S""" Exceptions should define semantic struct fields and a custom `message/1` function. ## Reasoning It's possible to define an exception with custom arguments and message by overriding the `exception/1` function and defining a standard `defexception [:message]` struct, but that yields to non-semantic exceptions that don't express their arguments in their structure. It also makes it harder (or at least inconsistent) to define multi-argument exceptions, which is simply a consequence of not having a struct defined for an actual struct. Therefore, it's better to define exceptions with a custom set of struct fields instead of a `message` field and to define a `message/1` function that takes those fields and creates an error message out of them. ## Examples Preferred: defmodule MyError do defexception [:a, :b] def message(%__MODULE__{a: a, b: b}) do "a: #{a}, b: #{b}" end end raise MyError, a: 1, b: 2 Non-semantic error struct with unnamed fields in multi-argument call: defmodule MyError do defexception [:message] def exception({a, b}) do %__MODULE__{message: "a: #{a}, b: #{b}"} end end raise MyError, {1, 2} """ def exception_structure, do: nil @doc """ Hardcoded word (both string and atom) lists should be written using the `~w` sigil. ## Reasoning They're simply more compact and easier to read this way. They're also easier to extend. For long lists, line breaks can be applied without problems. ## Examples Preferred: ~w(one two three) ~w(one two three)a Harder to read: ["one", "two", "three"] [:one, :two, :three] """ def list_format, do: nil @doc """ Exception modules (and only them) should be named with the `Error` suffix. ## Reasoning Exceptions are a distinct kind of application entities, so it's good to emphasize that in their naming. Two most popular suffixes are `Exception` and `Error`. The latter was choosen for brevity. ## Examples Preferred: defmodule InvalidCredentialsError do defexception [:one, :other] end Invalid suffix: defmodule InvalidCredentialsException do defexception [:one, :other] end Usage of `Error` suffix for non-exception modules: defmodule Actions.HandleRegistrationError do # ... end """ def exception_naming, do: nil @doc """ Basic happy case in a test file or scope should be placed on top of other cases. ## Reasoning When using tests to understand how specific unit of code works, it's very handy to have the basic happy case placed on top of other cases. ## Examples Preferred: defmodule MyProject.Web.MyControllerTest do describe "index/2" do test "works for valid params" do # ... end test "fails for invalid params" do # ... end end end Out of order: defmodule MyProject.Web.MyControllerTest do describe "index/2" do test "fails for invalid params" do # ... end test "works for valid params" do # ... end end end """ def test_happy_case_placement, do: nil @doc """ Pipe chains must be aligned into multiple lines. > Check out `Surgex.Guide.CodeStyle.assignment_indentation/0` to see how to assign the output from properly formatted multi-line chains. ## Reasoning This comes from general preference of vertical spacing over horizontal spacing, expressed across this guide by rules such as `Surgex.Guide.CodeStyle.block_alignment/0`. This ensures that the code is readable and not too condensed. Also, it's easier to modify or extend multi-line chains, because they don't require re-aligning the whole thing. By the way, single-line chains look kinda like a code copied from `iex` in a hurry, which is only fine when the building was on fire during the coding session. ## Examples Preferred: user |> reset_password() |> send_password_reset_email() Too condensed: user |> reset_password() |> send_password_reset_email() """ def pipe_chain_alignment, do: nil @doc """ Modules referenced in typespecs should be aliased. ## Reasoning When writing typespecs, it is often necessary to reference a module in some nested naming scheme. One could reference it with the absolute name, e.g. `Application.Accounting.Invoice.t`, but this makes typespecs rather lengthy. Using aliased modules makes typespecs easier to read and, as an added benefit, it allows for an in-front declaration of module dependencies. This way we can easily spot breaches in module isolation. ## Examples Preferred: alias VideoApp.Recommendations.{Rating, Recommendation, User} @spec calculate_recommendations(User.t, [Rating.t]) :: [Recommendation.t] def calculate_recommendations(user, ratings) do # ... end Way too long: @spec calculate_recommendations( VideoApp.Recommendations.User.t, [VideoApp.Recommendations.Rating.t] ) :: [VideoApp.Recommendations.Recommendation.t] def calculate_recommendations(user, ratings) do # ... end """ def typespec_alias_usage, do: nil end
lib/surgex/guide/code_style.ex
0.840292
0.615435
code_style.ex
starcoder
defmodule MazesWeb.HexagonalMazeView do use MazesWeb, :view import MazesWeb.MazeHelper alias Mazes.Maze def hex_radius(maze) do max_width = max_svg_width() - 2 * svg_padding() max_height = max_svg_width() - 2 * svg_padding() r1 = trunc(max_width / (0.5 + maze.width * 1.5)) h = trunc(max_height / maze.width) r2 = h / (2 * :math.sin(:math.pi() / 3)) Enum.min([r1, r2]) end def hex_height(maze) do 2 * hex_radius(maze) * :math.sin(alpha()) end def alpha() do :math.pi() / 3 end def svg_width(maze) do 2 * svg_padding() + hex_radius(maze) * (0.5 + maze.width * 1.5) end def svg_height(maze) do 2 * svg_padding() + hex_height(maze) * maze.width end def hex_center(maze, {x, y}) do r = hex_radius(maze) h = hex_height(maze) cx = r + 1.5 * r * (x - 1) + svg_padding() cy = if Integer.mod(x, 2) == 1 do h / 2 * (1 + (y - 1) * 2) + svg_padding() else h / 2 * (2 + (y - 1) * 2) + svg_padding() end {cx, cy - Integer.mod(Integer.floor_div(maze.width - 1, 2), 2) * 0.5 * h} end def hex(maze, vertex, settings, colors) do r = hex_radius(maze) hex_center = hex_center(maze, vertex) hex_points = Enum.map(0..5, fn n -> move_coordinate_by_radius_and_angle(hex_center, r, alpha() / 2 + n * alpha()) end) {path_start_x, path_start_y} = List.last(hex_points) path_lines = Enum.map(hex_points, fn {x, y} -> "L #{format_number(x)} #{format_number(y)}" end) |> Enum.join(" ") d = "M #{format_number(path_start_x)} #{format_number(path_start_y)} #{path_lines}" content_tag(:path, "", d: d, style: "fill: #{ vertex_color( maze, vertex, colors, settings.show_colors, settings.hue, settings.saturation ) }", stroke: vertex_color( maze, vertex, colors, settings.show_colors, settings.hue, settings.saturation ) ) end def wall(maze, vertex, n) do r = hex_radius(maze) hex_center = hex_center(maze, vertex) {path_start_x, path_start_y} = move_coordinate_by_radius_and_angle(hex_center, r, alpha() / 2 + n * alpha()) {path_end_x, path_end_y} = move_coordinate_by_radius_and_angle(hex_center, r, alpha() / 2 + (n + 1) * alpha()) # sort points so that visually overlapping lines always have the same direction # and will be de-duplicated in the template by calling Enum.uniq() on the rendered lines [{path_start_x, path_start_y}, {path_end_x, path_end_y}] = Enum.sort( [ {path_start_x, path_start_y}, {path_end_x, path_end_y} ], fn {x, y}, {a, b} -> if x == a do y > b else x > a end end ) d = "M #{format_number(path_start_x)} #{format_number(path_start_y)} L #{ format_number(path_end_x) } #{format_number(path_end_y)}" content_tag(:path, "", d: d, fill: "transparent", style: line_style(maze) ) end end
lib/mazes_web/views/hexagonal_maze_view.ex
0.632276
0.41938
hexagonal_maze_view.ex
starcoder
defmodule Annex.Perceptron do @moduledoc """ A simple perceptron Learner capable of making good predictions given a linearly separable dataset and labels. """ use Annex.Learner alias Annex.{ Data.List1D, Dataset, Perceptron, Utils } import Annex.Utils, only: [is_pos_integer: 1] @type activation :: (number() -> float()) @type data_type :: List1D @type t :: %Perceptron{ weights: list(float), learning_rate: float(), activation: activation(), bias: float() } defstruct [:weights, :learning_rate, :activation, :bias] @spec new(pos_integer, activation(), Keyword.t()) :: Perceptron.t() def new(inputs, activation, opts \\ []) when is_pos_integer(inputs) and is_function(activation, 1) do %Perceptron{ weights: get_or_create_weights(inputs, opts), bias: Keyword.get(opts, :bias, 1.0), learning_rate: Keyword.get(opts, :learning_rate, 0.05), activation: activation } end defp get_or_create_weights(inputs, opts) do case Keyword.get(opts, :weights) do weights when length(weights) == inputs -> weights _ -> List1D.new_random(inputs) end end @spec predict(t(), List1D.t()) :: float() def predict(%Perceptron{activation: activation, weights: weights, bias: bias}, inputs) do inputs |> List1D.dot(weights) |> Kernel.+(bias) |> activation.() end @spec train(t(), Dataset.t(), Keyword.t()) :: struct() def train(%Perceptron{} = p, dataset, opts \\ []) do runs = Keyword.fetch!(opts, :runs) fn -> Enum.random(dataset) end |> Stream.repeatedly() |> Stream.with_index() |> Enum.reduce_while(p, fn {data_row, index}, p_acc -> if index >= runs do {:halt, p_acc} else {:cont, train_once(p_acc, data_row)} end end) end defp train_once(%Perceptron{} = p, {inputs, label}) do %Perceptron{ weights: weights, bias: bias, learning_rate: lr } = p prediction = predict(p, inputs) error = label - prediction slope_delta = error * lr updated_weights = inputs |> Utils.zip(weights) |> Enum.map(fn {i, w} -> w + slope_delta * i end) %Perceptron{p | weights: updated_weights, bias: bias + slope_delta} end end
lib/annex/perceptron.ex
0.884008
0.693849
perceptron.ex
starcoder
defmodule Andi.InputSchemas.InputConverter do @moduledoc """ Used to convert between SmartCity.Datasets, form data (defined by Andi.InputSchemas.DatasetInput), and Ecto.Changesets. """ alias SmartCity.Dataset alias Andi.InputSchemas.DatasetInput @type dataset :: map() | Dataset.t() @spec changeset_from_dataset(dataset) :: Ecto.Changeset.t() def changeset_from_dataset(dataset) do %{id: id, business: business, technical: technical} = AtomicMap.convert(dataset, safe: false, underscore: false) from_business = get_business(business) |> fix_modified_date() from_technical = get_technical(technical) %{id: id} |> Map.merge(from_business) |> Map.merge(from_technical) |> DatasetInput.full_validation_changeset() end @spec changeset_from_dataset(Dataset.t(), map()) :: Ecto.Changeset.t() def changeset_from_dataset(%SmartCity.Dataset{} = original_dataset, changes) do form_data_with_atom_keys = AtomicMap.convert(changes, safe: false, underscore: false) original_dataset_flattened = original_dataset |> changeset_from_dataset() |> Ecto.Changeset.apply_changes() all_changes = Map.merge(original_dataset_flattened, form_data_with_atom_keys) all_changes |> adjust_form_input() |> DatasetInput.full_validation_changeset() end @spec form_changeset(map()) :: Ecto.Changeset.t() def form_changeset(params \\ %{}) do params |> adjust_form_input() |> DatasetInput.light_validation_changeset() end defp adjust_form_input(params) do params |> AtomicMap.convert(safe: false, underscore: false) |> Map.update(:keywords, nil, &keywords_to_list/1) |> fix_modified_date() end @spec restruct(map(), Dataset.t()) :: Dataset.t() def restruct(changes, dataset) do formatted_changes = changes |> Map.update(:issuedDate, nil, &date_to_iso8601_datetime/1) |> Map.update(:modifiedDate, nil, &date_to_iso8601_datetime/1) business = Map.merge(dataset.business, get_business(formatted_changes)) |> Map.from_struct() technical = Map.merge(dataset.technical, get_technical(formatted_changes)) |> Map.from_struct() %{} |> Map.put(:id, dataset.id) |> Map.put(:business, business) |> Map.put(:technical, technical) |> SmartCity.Dataset.new() |> (fn {:ok, dataset} -> dataset end).() end defp get_business(map) when is_map(map) do Map.take(map, DatasetInput.business_keys()) end defp get_technical(map) when is_map(map) do Map.take(map, DatasetInput.technical_keys()) end defp keywords_to_list(nil), do: [] defp keywords_to_list(""), do: [] defp keywords_to_list(keywords) when is_binary(keywords) do keywords |> String.split(", ") |> Enum.map(&String.trim/1) end defp keywords_to_list(keywords) when is_list(keywords), do: keywords defp date_to_iso8601_datetime(date) do time_const = "00:00:00Z" "#{Date.to_iso8601(date)} #{time_const}" end defp fix_modified_date(map) do map |> Map.get_and_update(:modifiedDate, fn "" -> {"", nil} current_value -> {current_value, current_value} end) |> elem(1) end end
apps/andi/lib/andi/input_schemas/input_converter.ex
0.727201
0.40869
input_converter.ex
starcoder
defmodule LearnKit.Math do @moduledoc """ Math module """ @type row :: [number] @type matrix :: [row] @doc """ Sum of 2 numbers ## Examples iex> LearnKit.Math.summ(1, 2) 3 """ @spec summ(number, number) :: number def summ(a, b), do: a + b @doc """ Division for 2 elements ## Examples iex> LearnKit.Math.division(10, 2) 5.0 """ @spec division(number, number) :: number def division(x, y) when y != 0, do: x / y @doc """ Calculate the mean from a list of numbers ## Examples iex> LearnKit.Math.mean([]) nil iex> LearnKit.Math.mean([1, 2, 3]) 2.0 """ @spec mean(list) :: number def mean(list) when is_list(list), do: do_mean(list, 0, 0) defp do_mean([], 0, 0), do: nil defp do_mean([], sum, number), do: sum / number defp do_mean([head | tail], sum, number) do do_mean(tail, sum + head, number + 1) end @doc """ Calculate variance from a list of numbers ## Examples iex> LearnKit.Math.variance([]) nil iex> LearnKit.Math.variance([1, 2, 3, 4]) 1.25 """ @spec variance(list) :: number def variance([]), do: nil def variance(list) when is_list(list) do list_mean = mean(list) variance(list, list_mean) end @doc """ Calculate variance from a list of numbers, with calculated mean ## Examples iex> LearnKit.Math.variance([1, 2, 3, 4], 2.5) 1.25 """ @spec variance(list, number) :: number def variance(list, list_mean) when is_list(list) do list |> Enum.map(fn x -> :math.pow(list_mean - x, 2) end) |> mean() end @doc """ Calculate standard deviation from a list of numbers ## Examples iex> LearnKit.Math.standard_deviation([]) nil iex> LearnKit.Math.standard_deviation([1, 2]) 0.5 """ @spec standard_deviation(list) :: number def standard_deviation([]), do: nil def standard_deviation(list) when is_list(list) do list |> variance() |> :math.sqrt() end @doc """ Calculate standard deviation from a list of numbers, with calculated variance ## Examples iex> LearnKit.Math.standard_deviation_from_variance(1.25) 1.118033988749895 """ @spec standard_deviation_from_variance(number) :: number def standard_deviation_from_variance(list_variance) do :math.sqrt(list_variance) end @doc """ Transposing a matrix ## Examples iex> LearnKit.Math.transpose([[1, 2], [3, 4], [5, 6]]) [[1, 3, 5], [2, 4, 6]] """ @spec transpose(matrix) :: matrix def transpose(m), do: do_transpose(m) defp do_transpose([head | _]) when head == [], do: [] defp do_transpose(rows) do firsts = Enum.map(rows, fn x -> hd(x) end) others = Enum.map(rows, fn x -> tl(x) end) [firsts | do_transpose(others)] end @doc """ Scalar multiplication ## Examples iex> LearnKit.Math.scalar_multiply(10, [5, 6]) [50, 60] """ @spec scalar_multiply(integer, list) :: list def scalar_multiply(multiplicator, list) when is_list(list) do Enum.map(list, fn x -> x * multiplicator end) end @doc """ Vector subtraction ## Examples iex> LearnKit.Math.vector_subtraction([40, 50, 60], [35, 5, 40]) [5, 45, 20] """ @spec vector_subtraction(list, list) :: list def vector_subtraction(x, y) when length(x) == length(y) do Enum.zip(x, y) |> Enum.map(fn {xi, yi} -> xi - yi end) end @doc """ Calculate the covariance of two lists ## Examples iex> LearnKit.Math.covariance([1, 2, 3], [14, 17, 25]) 5.5 """ @spec covariance(list, list) :: number def covariance(x, y) when length(x) == length(y) do mean_x = mean(x) mean_y = mean(y) size = length(x) Enum.zip(x, y) |> Enum.reduce(0, fn {xi, yi}, acc -> acc + (xi - mean_x) * (yi - mean_y) end) |> division(size - 1) end @doc """ Correlation of two lists ## Examples iex> LearnKit.Math.correlation([1, 2, 3], [14, 17, 25]) 0.9672471299049061 """ @spec correlation(list, list) :: number def correlation(x, y) when length(x) == length(y) do mean_x = mean(x) mean_y = mean(y) divider = Enum.zip(x, y) |> Enum.reduce(0, fn {xi, yi}, acc -> acc + (xi - mean_x) * (yi - mean_y) end) denom_x = Enum.reduce(x, 0, fn xi, acc -> acc + :math.pow(xi - mean_x, 2) end) denom_y = Enum.reduce(y, 0, fn yi, acc -> acc + :math.pow(yi - mean_y, 2) end) divider / :math.sqrt(denom_x * denom_y) end end
lib/learn_kit/math.ex
0.933119
0.764188
math.ex
starcoder
defmodule Bolt.Cogs.Warn do @moduledoc false @behaviour Nosedrum.Command alias Bolt.Converters alias Bolt.ErrorFormatters alias Bolt.Helpers alias Bolt.Humanizer alias Bolt.ModLog alias Bolt.Repo alias Bolt.Schema.Infraction alias Nosedrum.Predicates alias Nostrum.Api alias Nostrum.Struct.User @impl true def usage, do: ["warn <user:member> <reason:str...>"] @impl true def description, do: """ Warn the given user for the specified reason. The warning is stored in the infraction database, and can be retrieved later. Requires the `MANAGE_MESSAGES` permission. **Examples**: ```rs warn @Dude#0001 spamming duck images at #dog-pics ``` """ @impl true def predicates, do: [&Predicates.guild_only/1, Predicates.has_permission(:manage_messages)] @impl true def command(msg, [user | reason_list]) do response = with reason when reason != "" <- Enum.join(reason_list, " "), {:ok, member} <- Converters.to_member(msg.guild_id, user), infraction <- %{ type: "warning", guild_id: msg.guild_id, user_id: member.user.id, actor_id: msg.author.id, reason: reason }, changeset <- Infraction.changeset(%Infraction{}, infraction), {:ok, _created_infraction} <- Repo.insert(changeset) do ModLog.emit( msg.guild_id, "INFRACTION_CREATE", "#{Humanizer.human_user(msg.author)} has warned" <> " #{Humanizer.human_user(member.user)} with reason `#{reason}`" ) "👌 warned #{User.full_name(member.user)} (`#{Helpers.clean_content(reason)}`)" else "" -> "🚫 must provide a reason to warn the user for" error -> ErrorFormatters.fmt(msg, error) end {:ok, _msg} = Api.create_message(msg.channel_id, response) end def command(msg, _anything) do response = "ℹ️ usage: `warn <user:member> <reason:str...>`" {:ok, _msg} = Api.create_message(msg.channel_id, response) end end
lib/bolt/cogs/warn.ex
0.803135
0.474449
warn.ex
starcoder
defmodule Cryptopunk.Crypto.Bitcoin do @moduledoc """ Bitcoin address generation logic. All addresses use compressed public keys. """ alias Cryptopunk.Crypto.Bitcoin.Bech32Address alias Cryptopunk.Crypto.Bitcoin.LegacyAddress alias Cryptopunk.Crypto.Bitcoin.P2shP2wpkhAddress alias Cryptopunk.Key @doc """ Generate a legacy (P2PKH) address. It accepts three parameters: - public or private key. if a private key is provided, it will be converted to public key. - network (`:mainnet` or `:testnet`) - optional keyword params. Currently, the only allowed parameter is `:uncompressed` key. Passing `[uncompressed: true]` will generate the address from the uncompressed public key which is not advised. but it may be required for compatibility reasons Examples: iex> private_key = %Cryptopunk.Key{key: <<16, 42, 130, 92, 247, 244, 62, 96, 24, 129, 187, 141, 124, 42, 176, 116, 234, 171, 184, 107, 3, 229, 255, 72, 30, 116, 79, 243, 36, 142, 184, 24>>, type: :private} iex> Cryptopunk.Crypto.Bitcoin.legacy_address(private_key, :mainnet) "1JfhAmwWjbGJ3RW2hjoRdmpKaKXgCjSwEL" iex> public_key = %Cryptopunk.Key{key: <<4, 57, 163, 96, 19, 48, 21, 151, 218, 239, 65, 251, 229, 147, 160, 44, 197, 19, 208, 181, 85, 39, 236, 45, 241, 5, 14, 46, 143, 244, 156, 133, 194, 60, 190, 125, 237, 14, 124, 230, 165, 148, 137, 107, 143, 98, 136, 143, 219, 197, 200, 130, 19, 5, 226, 234, 66, 191, 1, 227, 115, 0, 17, 98, 129>>, type: :public} iex> Cryptopunk.Crypto.Bitcoin.legacy_address(public_key, :testnet) "mkHGce7dctSxHgaWSSbmmrRWsZfzz7MxMk" iex> private_key = %Cryptopunk.Key{key: <<16, 42, 130, 92, 247, 244, 62, 96, 24, 129, 187, 141, 124, 42, 176, 116, 234, 171, 184, 107, 3, 229, 255, 72, 30, 116, 79, 243, 36, 142, 184, 24>>, type: :private} iex> Cryptopunk.Crypto.Bitcoin.legacy_address(private_key, :mainnet, uncompressed: true) "1AqWUNX6mdaiPay55BqZcAMqNSEJgcgj1D" """ @spec legacy_address(Key.t(), atom() | binary(), Keyword.t()) :: String.t() def legacy_address(private_or_public_key, net_or_version_byte, opts \\ []) do address(private_or_public_key, net_or_version_byte, :legacy, opts) end @doc """ Generate a 'Pay to Witness Public Key Hash nested in BIP16 Pay to Script Hash' (P2WPKH-P2SH) address It accepts two parameters: - public or private key. if a private key is provided, it will be converted to public key. - network (`:mainnet` or `:testnet`) Examples: iex> private_key = %Cryptopunk.Key{key: <<16, 42, 130, 92, 247, 244, 62, 96, 24, 129, 187, 141, 124, 42, 176, 116, 234, 171, 184, 107, 3, 229, 255, 72, 30, 116, 79, 243, 36, 142, 184, 24>>, type: :private} iex> Cryptopunk.Crypto.Bitcoin.p2sh_p2wpkh_address(private_key, :mainnet) "397Y4wveZFbdEo8rTzXSPHWYuamfKs2GWd" iex> public_key = %Cryptopunk.Key{key: <<4, 57, 163, 96, 19, 48, 21, 151, 218, 239, 65, 251, 229, 147, 160, 44, 197, 19, 208, 181, 85, 39, 236, 45, 241, 5, 14, 46, 143, 244, 156, 133, 194, 60, 190, 125, 237, 14, 124, 230, 165, 148, 137, 107, 143, 98, 136, 143, 219, 197, 200, 130, 19, 5, 226, 234, 66, 191, 1, 227, 115, 0, 17, 98, 129>>, type: :public} iex> Cryptopunk.Crypto.Bitcoin.p2sh_p2wpkh_address(public_key, :testnet) "2NFNttcoWjE7WUcByBqpPKkcjg8wzgnU5HE" """ @spec p2sh_p2wpkh_address(Key.t(), atom() | binary()) :: String.t() def p2sh_p2wpkh_address(private_or_public_key, net_or_version_byte) do address(private_or_public_key, net_or_version_byte, :p2sh_p2wpkh) end @doc """ Generate a bech32 segwit address It accepts three parameters: - public or private key. if a private key is provided, it will be converted to public key. - network (`:mainnet`, `:testnet` or `:regtest`) - optional parameters. Currently the only allowed parameter is a witness version (`:version`). Examples: iex> private_key = %Cryptopunk.Key{key: <<16, 42, 130, 92, 247, 244, 62, 96, 24, 129, 187, 141, 124, 42, 176, 116, 234, 171, 184, 107, 3, 229, 255, 72, 30, 116, 79, 243, 36, 142, 184, 24>>, type: :private} iex> Cryptopunk.Crypto.Bitcoin.bech32_address(private_key, :mainnet) "bc1qc89hn5kmwxl804yfqmd97st3trarqr24y2hpqh" iex> private_key = %Cryptopunk.Key{key: <<16, 42, 130, 92, 247, 244, 62, 96, 24, 129, 187, 141, 124, 42, 176, 116, 234, 171, 184, 107, 3, 229, 255, 72, 30, 116, 79, 243, 36, 142, 184, 24>>, type: :private} iex> Cryptopunk.Crypto.Bitcoin.bech32_address(private_key, :mainnet, version: 1) "<KEY>" iex> public_key = %Cryptopunk.Key{key: <<4, 57, 163, 96, 19, 48, 21, 151, 218, 239, 65, 251, 229, 147, 160, 44, 197, 19, 208, 181, 85, 39, 236, 45, 241, 5, 14, 46, 143, 244, 156, 133, 194, 60, 190, 125, 237, 14, 124, 230, 165, 148, 137, 107, 143, 98, 136, 143, 219, 197, 200, 130, 19, 5, 226, 234, 66, 191, 1, 227, 115, 0, 17, 98, 129>>, type: :public} iex> Cryptopunk.Crypto.Bitcoin.bech32_address(public_key, :testnet) "tb1qx3ppj0smkuy3d6g525sh9n2w9k7fm7q3vh5ssm" """ @spec bech32_address(Key.t(), atom() | String.t(), Keyword.t()) :: String.t() def bech32_address(private_or_public_key, net_or_hrp, opts \\ []) do address(private_or_public_key, net_or_hrp, :bech32, opts) end defp address(private_key, net_or_version_byte, type, opts \\ []) defp address(%Key{type: :private} = private_key, net_or_version_byte, type, opts) do private_key |> Key.public_from_private() |> generate_address(net_or_version_byte, type, opts) end defp address(%Key{type: :public} = public_key, net_or_version_byte, type, opts) do generate_address(public_key, net_or_version_byte, type, opts) end defp generate_address(public_key, net_or_version_byte, :legacy, opts) do LegacyAddress.address(public_key, net_or_version_byte, opts) end defp generate_address(public_key, net_or_version_byte, :p2sh_p2wpkh, _opts) do P2shP2wpkhAddress.address(public_key, net_or_version_byte) end defp generate_address(public_key, net_or_hrp, :bech32, opts) do Bech32Address.address(public_key, net_or_hrp, opts) end end
lib/cryptopunk/crypto/bitcoin.ex
0.856362
0.40251
bitcoin.ex
starcoder
defmodule Spaceentropy do alias Faker alias Comeonin.Bcrypt @random_faker [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 ] @moduledoc """ Spaceentropy generates random passwords with the glorious power of faker data, comeonin, and bcrypt. """ @doc """ gen_faker ## Examples iex> Spaceentropy.gen_faker {:ok, "superstructure 20 with Squid, Venison, Capers, Pineapple, and Buffalo Mozzarella BRAVO Regional BrandingDirector"} """ def gen_faker do wizard = @random_faker |> Enum.shuffle |> List.first feet = @random_faker |> Enum.shuffle |> List.last stink = @random_faker |> Enum.shuffle |> List.first sorry = @random_faker |> Enum.shuffle |> List.last r1 = case wizard do 1 -> Faker.Beer.En.style() 2 -> Faker.Food.spice() 3 -> Faker.Name.title() 4 -> Faker.Pizza.pizza() 5 -> Faker.Superhero.power() 6 -> Faker.Cat.name() 7 -> Faker.Color.name() 8 -> Faker.Company.buzzword_suffix() 9 -> Faker.Lorem.word() 0 -> Faker.Nato.letter_code_word() end r2 = case feet do 1 -> Faker.Beer.En.style() 2 -> Faker.Food.spice() 3 -> Faker.Name.title() 4 -> Faker.Pizza.pizza() 5 -> Faker.Superhero.power() 6 -> Faker.Cat.name() 7 -> Faker.Color.name() 8 -> Faker.Company.buzzword_suffix() 9 -> Faker.Lorem.word() 0 -> Faker.Nato.letter_code_word() end r3 = case stink do 1 -> Faker.Beer.En.style() 2 -> Faker.Food.spice() 3 -> Faker.Name.title() 4 -> Faker.Pizza.pizza() 5 -> Faker.Superhero.power() 6 -> Faker.Cat.name() 7 -> Faker.Color.name() 8 -> Faker.Company.buzzword_suffix() 9 -> Faker.Lorem.word() 0 -> Faker.Nato.letter_code_word() end r4 = case sorry do 1 -> Faker.Beer.En.style() 2 -> Faker.Food.spice() 3 -> Faker.Name.title() 4 -> Faker.Pizza.pizza() 5 -> Faker.Superhero.power() 6 -> Faker.Cat.name() 7 -> Faker.Color.name() 8 -> Faker.Company.buzzword_suffix() 9 -> Faker.Lorem.word() 0 -> Faker.Nato.letter_code_word() end {:ok, "#{r1} #{r2} #{r3} #{r4}"} end @doc """ gen_crypt ## Examples iex> Spaceentropy.gen_crypt {:ok, "$2b$12$DX7RHvRQLnhRzAeFxkreHeRtvPYmizUnIooSBxIvp2Te0JFDcy3I."} """ def gen_crypt do a = Faker.Color.name() b = Faker.Company.buzzword_suffix() c = Faker.Lorem.word() d = Faker.Pokemon.name() e = "#{a} #{b} #{c} #{d} #{b} #{b}" password = Bcrypt.hashpwsalt(e) {:ok, password} end end
lib/spaceentropy.ex
0.648132
0.474327
spaceentropy.ex
starcoder
defmodule Mongo.InsertOneResult do @moduledoc """ The successful result struct of `Mongo.insert_one/4`. Its fields are: * `:inserted_id` - The id of the inserted document """ @type t :: %__MODULE__{ acknowledged: boolean, inserted_id: nil | BSON.ObjectId.t() } defstruct acknowledged: true, inserted_id: nil end defmodule Mongo.InsertManyResult do @moduledoc """ The successful result struct of `Mongo.insert_many/4`. Its fields are: * `:inserted_ids` - The ids of the inserted documents indexed by their order """ @type t :: %__MODULE__{ acknowledged: boolean, inserted_ids: %{non_neg_integer => BSON.ObjectId.t()} } defstruct acknowledged: true, inserted_ids: nil end defmodule Mongo.DeleteResult do @moduledoc """ The successful result struct of `Mongo.delete_one/4` and `Mongo.delete_many/4`. Its fields are: * `:deleted_count` - Number of deleted documents """ @type t :: %__MODULE__{ acknowledged: boolean, deleted_count: non_neg_integer } defstruct acknowledged: true, deleted_count: 0 end defmodule Mongo.UpdateResult do @moduledoc """ The successful result struct of `Mongo.update_one/5`, `Mongo.update_many/5` and `Mongo.replace_one/5`. Its fields are: * `:matched_count` - Number of matched documents * `:modified_count` - Number of modified documents * `:upserted_ids` - If the operation was an upsert, the ids of the upserted documents """ @type t :: %__MODULE__{ acknowledged: boolean, matched_count: non_neg_integer, modified_count: non_neg_integer, # TODO this isn't always a BSON.ObjectId upserted_ids: nil | list(BSON.ObjectId.t()) } defstruct acknowledged: true, matched_count: 0, modified_count: 0, upserted_ids: nil end defmodule Mongo.FindAndModifyResult do @moduledoc """ The successful result struct of `Mongo.find_one_and_*` functions, which under the hood use Mongo's `findAndModify` API. See <https://docs.mongodb.com/manual/reference/command/findAndModify/> for more information. """ @type t :: %__MODULE__{ value: BSON.document(), matched_count: non_neg_integer(), upserted_id: String.t(), updated_existing: boolean() } defstruct [ :value, :matched_count, :upserted_id, :updated_existing ] end defmodule Mongo.CreateIndexesResult do @moduledoc """ The successful result struct of `Mongo.create_indexes/4`. Its fields are: * `:commit_quorum` - Quorum voting behaviour. See https://docs.mongodb.com/manual/reference/command/createIndexes/#std-label-createIndexes-cmd-commitQuorum * `:created_collection_automatically` - `true` when the collection was implicitly created as part of the index creation command, `false` otherwise * `:num_indexes_after` - Number of indexes after the index creation command took place * `:num_indexes_before` - Number of indexes before the index creation command took place """ @type t :: %__MODULE__{ commit_quorum: non_neg_integer() | binary(), created_collection_automatically: boolean(), num_indexes_after: non_neg_integer(), num_indexes_before: non_neg_integer() } defstruct [ :commit_quorum, :created_collection_automatically, :num_indexes_after, :num_indexes_before ] end defmodule Mongo.DropIndexResult do @moduledoc """ The successful result struct of `Mongo.drop_index/4`. Its fields are: * `:num_indexes_was` - Number of indexes before the index was dropped. """ @type t :: %__MODULE__{ num_indexes_was: non_neg_integer() } defstruct [:num_indexes_was] end
lib/mongo/results.ex
0.744285
0.541348
results.ex
starcoder
defmodule Rubbergloves.Struct do @moduledoc""" A series of macros to define how to convert from a raw %{} map to a well defined struct. Supports nested struct mapping, and global conventions. Using *Rubbergloves.Struct* give you access to the `defmapping` module that defines how to convert the input into your stuct. Once in a defmapping block, two macros are avaliable for you: - *keys/1* Takes a function that retrieves the key of the struct and returns the key in the map to collect the data from. i.e. to map input in the form `%{ "someKeyName" => "value"}` to a struct like `defstruct [:some_key_name]` - *overrides/2* Takes the struct key and a keyword list of override options. Override options can include: :key - A string/atom value of the key in the input map - Or a function in the format struct_key -> expected_key :value - A hard coded value to use despite whats in the input map. - Or more useful a function in the format input_value -> transformed_value - For nested structs, use the one/many macros to apply nested mapping rules ### Given Input ``` params = %{ "username" => "test", "password" => "password" "meta" => %{ "type" => "UserPass" } } ``` ### With Definitions ``` defmodule MyApp.Requests.LoginRequestMeta do defstruct [:type ] defmapping do keys &CamelCaseKeyResolver.resolve/1 end end defmodule MyApp.Requests.LoginRequest do use Rubbergloves.Struct alias MyApp.Requests.LoginRequestMeta defstruct [:username, :password, :hashed_password, :meta] defmapping do keys &CamelCaseKeyResolver.resolve/1 override :hashed_password, key: "password", value: &hash_password_input/1 override :meta, value: one(LoginRequestMeta) end @impl validate def validate(request) do # Validate however you like end # Custom methods to map your input to struct values def hash_password_input(_val) do "SOMEHASHED_PASSWORD_EXAMPLE" end end ``` """ alias Rubbergloves.Mapper defmacro __using__(_) do quote do require Rubbergloves.Struct import Rubbergloves.Struct alias Rubbergloves.Mapper.CamelCaseKeyResolver alias Rubbergloves.Mapper @before_compile { unquote(__MODULE__), :__before_compile__ } @mappings %Mapper.Options{} @callback validate(%__MODULE__{}) :: :ok | {:error, any()} def many(struct, nil), do: &many(struct, &1, struct.mappings) def many(struct, opts), do: &many(struct, &1, opts) defp many(struct, value, opts) when is_list(value), do: value |> Enum.map(&one(struct, &1, opts)) defp many(_, _, _), do: [] def one(struct, nil), do: &one(struct, &1, struct.mappings) def one(struct, opts), do: &one(struct, &1, opts) defp one(struct, val, opts), do: Mapper.map(struct, val, opts) end end defmacro __before_compile__(_) do quote do def mappings(), do: @mappings def validate(%__MODULE__{}), do: :ok def validate(any), do: :invalid_type end end defmacro defmapping(block) do quote do unquote(block) end end defmacro keys(val) do func_name = "keys_func" |> String.to_atom use_value_default = is_atom(val) quote do if(!unquote(use_value_default)) do localize_function(unquote(func_name), unquote(val)) end @mappings Map.put(@mappings, :keys, if(unquote(use_value_default), do: unquote(val), else: &__MODULE__.unquote(func_name)/2) ) end end defmacro override(struct_key, override) do key = Keyword.get(override, :key, :default) value = Keyword.get(override, :value, :default) key_func_name = "#{struct_key}_key" |> String.to_atom value_func_name = "#{struct_key}_value" |> String.to_atom # Note: Akward that we must do this here, but we cannot evaluate the value of key/value in quote incase its a missing local function use_key_default = key == :default use_value_default = value == :default quote do localize_function(unquote(key_func_name), unquote(key)) localize_function(unquote(value_func_name), unquote(value)) overrides = Map.put(Map.get(@mappings, :overrides), unquote(struct_key), %Mapper.Override{ key: if(unquote(use_key_default), do: :default, else: &__MODULE__.unquote(key_func_name)/2), value: if(unquote(use_value_default), do: :default, else: &__MODULE__.unquote(value_func_name)/1) }) @mappings Map.put(@mappings, :overrides, overrides) end end defmacro localize_function(name, defenition) do if(is_tuple(defenition)) do quote do def unquote(name)(a), do: unquote(defenition).(a) def unquote(name)(a,b), do: unquote(defenition).(a,b) end else quote do def unquote(name)(input), do: unquote(defenition) end end end end
lib/mapper/struct.ex
0.809991
0.915507
struct.ex
starcoder
defmodule RojakAPI.V1.NewsController do use RojakAPI.Web, :controller alias RojakAPI.Data.News @apidoc """ @api {get} /news Get list of news @apiGroup News @apiName NewsList @apiDescription Get a list of news, optionally with <code>media</code>, <code>mentions</code>, and <code>sentiments</code>. Filterable by media and mentioned candidates. @apiParam {String} [embed[]] Fields to embed on the response. Available fields: <code>media</code>, <code>mentions</code>, <code>sentiments</code> </br></br> Example: <pre>?embed[]=field1&embed[]=field2</pre> @apiParam {Integer} [offset=0] Skip over a number of elements by specifying an offset value for the query. </br></br> Example: <pre>?offset=20</pre> @apiParam {Integer} [limit=10] Limit the number of elements on the response. </br></br> Example: <pre>?limit=20</pre> @apiParam {Integer} [media_id[]] Filter articles based on <code>id</code> of media. </br></br> Example: <pre>?media_id[]=1&media_id[]=2</pre> @apiParam {Integer} [candidate_id[]] Filter articles based on <code>id</code> of mentioned candidates. </br></br> Example: <pre>?candidate_id[]=1&candidate_id[]=2</pre> @apiSuccessExample {json} Success HTTP/1.1 200 OK [ { "id": 1, "media_id": 3, "title": "Kunjungan Presiden Jokowi ke Depok", "url": "https://rojaktv.com/jokowi-jalan-jalan-ke-depok", "author_name": "Anto", "inserted_at": 1341533193, "updated_at": 1341533193, // embedded fields "media": { // media data }, "mentions": [ { // candidate data } ], "sentiments": [ { pairing: { // pairing data }, type: 'positive', confidentScore: 0.12345 } ] }, { "id": 2, "media_id": 3, "title": "Budi Berpasangan dengan Ani", "url": "https://rojaktv.com/budi-berpasangan-ani", "author_name": "Anto", "inserted_at": 1341533201, "updated_at": 1341533201, // embedded fields "media": { // media data }, "mentions": [ { // candidate data } ], "sentiments": [ { pairing: { // pairing data }, type: 'positive', confidentScore: 0.12345 } ] } ] """ defparams news_index_params(%{ limit: [field: :integer, default: 10], offset: [field: :integer, default: 0], embed: [:string], media_id: [:integer], candidate_id: [:integer] }) do def changeset(ch, params) do cast(ch, params, [:limit, :offset, :embed, :media_id, :candidate_id]) |> validate_subset(:embed, ["media", "mentions", "sentiments"]) end end def index(conn, params) do validated_params = ParamsValidator.validate params, &news_index_params/1 news = News.fetch(validated_params) render(conn, "index.json", news: news) end @apidoc """ @api {get} /news/:newsId Get a single news @apiGroup News @apiName NewsSingle @apiDescription Get a news article based on {newsId}, optionally with <code>media</code>, <code>mentions</code>, and <code>sentiments</code>. @apiParam {String} newsId @apiParam {String} [embed[]] Fields to embed on the response. Available fields: <code>media</code>, <code>mentions</code>, <code>sentiments</code> </br></br> Example: <pre>?embed[]=field1&embed[]=field2</pre> @apiSuccessExample {json} Success HTTP/1.1 200 OK { "id": 1, "mediaId": 3, "title": "Kunjungan Presiden Jokowi ke Depok", "url": "https://rojaktv.com/jokowi-jalan-jalan-ke-depok", "author_name": "Anto", "inserted_at": 1341533193, "updated_at": 1341533193, // embedded fields "media": { // media data }, "mentions": [ { // candidate data } ], "sentiments": [ { pairing: { // pairing data }, type: 'positive', confidentScore: 0.12345 } ] } @apiErrorExample {json} Item Not Found HTTP/1.1 404 Not Found { "message" : "item not found" } """ defparams news_show_params(%{ id!: :integer, embed: [:string], }) do def changeset(ch, params) do cast(ch, params, [:id, :embed]) |> validate_subset(:embed, ["media", "mentions", "sentiments"]) end end def show(conn, params) do validated_params = ParamsValidator.validate params, &news_show_params/1 news = News.fetch_one(validated_params) render(conn, "show.json", news: news) end end
rojak-api/web/v1/news/news_controller.ex
0.770681
0.436082
news_controller.ex
starcoder
defmodule OddJob.Async.Proxy do @moduledoc """ The `OddJob.Async.Proxy` links the job caller to the worker as the job is being performed. The process that calls `async_perform/2` or `async_perform_many/3` must link and monitor the worker performing the job so it can receive the results and be notified of failure by exiting or receiving an `:EXIT` message if the process is trapping exits. However, at the time the function is called it is unknown which worker will receive the job and when. The proxy is a process that is created to provide a link between the caller and the worker. When an async funcion is called, the caller links and monitors the proxy, and the proxy `pid` and monitor `reference` are stored in the `OddJob.Job` struct. When the worker receives the job it calls the proxy to be linked and monitored. Job results as well as `:EXIT` and `:DOWN` messages are passed from the worker to the caller via the proxy. """ @moduledoc since: "0.1.0" @doc false use GenServer, restart: :temporary defstruct [:worker_ref, :job] @type t :: %__MODULE__{ worker_ref: reference, job: job } @type job :: OddJob.Job.t() @type proxy :: pid # <---- Client API ----> @doc false @spec start_link([]) :: :ignore | {:error, any} | {:ok, pid} def start_link([]), do: GenServer.start_link(__MODULE__, []) @doc false @spec link_and_monitor_caller(proxy) :: {:ok, reference} def link_and_monitor_caller(proxy), do: GenServer.call(proxy, :link_and_monitor_caller) @doc false @spec report_completed_job(proxy, job) :: :ok def report_completed_job(proxy, job), do: GenServer.call(proxy, {:job_complete, job}) # <---- Callbacks ----> @impl GenServer @spec init(any) :: {:ok, any} def init(_init_arg) do {:ok, %__MODULE__{}} end @impl GenServer def handle_call(:link_and_monitor_caller, {from, _}, state) do Process.link(from) ref = Process.monitor(from) {:reply, {:ok, ref}, %{state | worker_ref: ref}} end def handle_call({:job_complete, job}, {from, _}, %{worker_ref: ref} = state) do Process.unlink(from) Process.demonitor(ref, [:flush]) Process.send(job.owner, {job.ref, job.results}, []) {:stop, :normal, :ok, state} end @impl GenServer def handle_info({:DOWN, _, _, _, reason}, state) do {:stop, reason, state} end end
lib/odd_job/async/proxy.ex
0.828731
0.564939
proxy.ex
starcoder
defmodule Cuda.Compiler.Context do @moduledoc """ Compilation context """ alias Cuda.Graph.GraphProto @type t :: %__MODULE__{ env: Cuda.Env.t, assigns: map, root: Cuda.Graph.t | Cuda.Node.t, path: [Cuda.Graph.id] } defstruct [:env, :root, assigns: %{}, path: []] def new(opts) do struct(__MODULE__, Enum.into(opts, [])) end def assign(%__MODULE__{assigns: assigns} = ctx, values) do %{ctx | assigns: Map.merge(assigns, Enum.into(values, %{}))} end def assign(%__MODULE__{assigns: assigns} = ctx, key, value) do %{ctx | assigns: Map.put(assigns, key, value)} end defp expanded_path(path) do path |> Enum.flat_map(fn id when is_tuple(id) -> id |> Tuple.to_list |> Enum.reverse id -> [id] end) end defp find_in_expanded(_, _, []), do: nil defp find_in_expanded(assigns, path, [_ | rest] = ctx_path) do expanded = ctx_path |> Enum.reverse |> Enum.intersperse(:expanded) expanded = [:expanded | expanded] ++ path with nil <- get_in(assigns, expanded) do find_in_expanded(assigns, path, rest) end end def find_assign(ctx, path, ctx_path \\ nil, callback \\ fn _ -> true end) def find_assign(ctx, path, nil, callback) do find_assign(ctx, path, ctx.path, callback) end def find_assign(%{root: nil}, _, _, _), do: nil def find_assign(ctx, path, [], callback) do value = with nil <- get_in(ctx.root.assigns, [:expanded | path]) do get_in(ctx.root.assigns, path) end if not is_nil(value) and callback.(value), do: value, else: nil end def find_assign(ctx, path, [_ | rest] = ctx_path, callback) do with nil <- find_in_expanded(ctx.root.assigns, path, expanded_path(ctx_path)) do with %{} = child <- node(ctx, ctx_path) do with nil <- find_in_expanded(child.assigns, path, expanded_path(rest)), nil <- get_in(child.assigns, path) do find_assign(ctx, path, rest, callback) else value -> if callback.(value) do value else find_assign(ctx, path, rest, callback) end end else _ -> find_assign(ctx, path, rest, callback) end end end def find_assign(_, _, _, _), do: nil def for_node(%__MODULE__{root: nil} = ctx, child) do %{ctx | root: child, path: []} end def for_node(%__MODULE__{path: path} = ctx, %{id: id}) do {_, with_id} = Enum.split_while(path, & &1 != id) path = if with_id == [], do: [id | path], else: with_id %{ctx | path: path} end def node(ctx, node \\ nil) def node(%__MODULE__{root: root, path: []}, nil), do: root def node(%__MODULE__{path: path} = ctx, nil), do: node(ctx, path) def node(%__MODULE__{root: nil}, _), do: nil def node(%__MODULE__{root: root}, []) do root end def node(%__MODULE__{root: root}, path) do GraphProto.node(root, Enum.reverse(path)) end def node(_, _) do nil end def replace_current(%__MODULE__{path: []} = ctx, node) do %{ctx | root: node} end def replace_current(%__MODULE__{root: root, path: [_ | rest] = id} = ctx, node) do %{ctx | path: [node.id | rest], root: GraphProto.replace(root, id |> Enum.reverse, node)} end end
lib/cuda/compiler/context.ex
0.641535
0.400105
context.ex
starcoder
defmodule Ui.Pins do @moduledoc """ This is an abstraction layer for the underlying GPIO pin interface. Holds the GPIO pin pids internally to allow easier manipulation. """ use GenServer @type pin_number :: non_neg_integer() defmodule GPIOPin do @moduledoc """ Information about a GPIO pin. """ @type t :: %GPIOPin{} defstruct [:mode, :state, :pid] end @doc """ Starts the Ui.Pins server. Only one is allowed per VM. the """ @spec start_link([pin_number]) :: GenServer.start def start_link(pins) do GenServer.start_link(__MODULE__, pins, name: __MODULE__) end def init(pins) do state = Enum.reduce(pins, %{}, fn pin_number, accum -> {:ok, pid} = Gpio.start_link(pin_number, :output) Gpio.write(pid, 0) pin = %GPIOPin{pid: pid, state: 0, mode: :output} Map.put(accum, pin_number, pin) end) {:ok, state} end @doc """ Get pin object of the underlying Gpio process for a pin to use lower-level operations. """ @spec pin(pin_number()) :: GPIOPin.t def pin(number) when is_integer(number) do GenServer.call(__MODULE__, {:pin, number}) end @doc "Returns the state of the pin" @spec read(pin_number()) :: 1 | 0 def read(number) when is_integer(number) do GenServer.call(__MODULE__, {:read, number}) end @doc "Sets pin to 1" @spec on(pin_number()) :: :on def on(number) when is_integer(number) do GenServer.call(__MODULE__, {:on, number}) end @doc "Sets pin to 0" @spec off(pin_number()) :: :off def off(number) when is_integer(number) do GenServer.call(__MODULE__, {:off, number}) end @doc """ turn pin on for `time` ms, then off for `length` ms. Repeat `times` times. Note that this is synchronous, so it sets the appropriate timeout in the GenServer call, but if any other GenServer is waiting, it might time out. """ @spec blink(pin_number(), pos_integer(), pos_integer()) :: :off def blink(number, times \\ 10, time \\ 250) when is_integer(number) do # Each on/off blink takes `time * 2` ms, and we do it `times` times, and add 500ms padding timeout = times * time * 2 + 500 GenServer.call(__MODULE__, {:blink, number, times, time}, timeout) end def handle_call({:pin, number}, _from, state) do pin = Map.get state, number {:reply, pin, state} end def handle_call({:read, number}, _from, state) do pin = Map.get state, number value = Gpio.read(pin.pid) {:reply, value, state} end def handle_call({:on, number}, _from, state) do pin = Map.get state, number Gpio.write(pin, 1) {:reply, :on, state} end def handle_call({:off, number}, _from, state) do pin = Map.get state, number Gpio.write(pin, 0) {:reply, :off, state} end def handle_call({:blink, number, times, time}, _from, state) do pin = Map.get state, number Enum.each(1..times, fn _ -> Gpio.write(pin, 1) :timer.sleep time Gpio.write(pin, 0) :timer.sleep time end) {:reply, :off, state} end end
apps/ui/lib/ui/pins.ex
0.834069
0.535706
pins.ex
starcoder
defmodule ExOauth2Provider.Plug.EnsureScopes do @moduledoc """ Use this plug to ensure that there are the correct scopes on the token found on the connection. ### Example alias ExOauth2Provider.Plug.EnsureScopes # With custom handler plug EnsureScopes, scopes: ~w(read write), handler: SomeMod, # item:read AND item:write scopes AND :profile scope plug EnsureScopes, scopes: ~(item:read item:write profile) # iteam:read AND item: write scope OR :profile for the default set plug EnsureScopes, one_of: [~(item:read item:write), ~(profile)] # item :read AND :write for the token located in the :secret location plug EnsureScopes, key: :secret, scopes: ~(read :write) If the handler option is not passed, `ExOauth2Provider.Plug.ErrorHandler` will provide the default behavior. """ require Logger import Plug.Conn @doc false def init(opts) do opts = Enum.into(opts, %{}) key = Map.get(opts, :key, :default) handler = build_handler_tuple(opts) %{ handler: handler, key: key, scopes_sets: scopes_sets(opts) } end @doc false defp scopes_sets(%{one_of: one_of}), do: one_of defp scopes_sets(%{scopes: single_set}), do: [single_set] defp scopes_sets(_), do: nil @doc false def call(conn, opts) do conn |> ExOauth2Provider.Plug.current_access_token(Map.get(opts, :key)) |> check_scopes(conn, opts) |> handle_error end defp check_scopes(nil, conn, opts), do: {:error, conn, opts} defp check_scopes(token, conn, opts) do scopes_set = Map.get(opts, :scopes_sets) case matches_any_scopes_set?(token, scopes_set) do true -> {:ok, conn, opts} false -> {:error, conn, opts} end end defp matches_any_scopes_set?(_, []), do: true defp matches_any_scopes_set?(access_token, scopes_sets) do Enum.any?(scopes_sets, &matches_scopes?(access_token, &1)) end defp matches_scopes?(access_token, required_scopes) do access_token |> ExOauth2Provider.Scopes.from_access_token |> ExOauth2Provider.Scopes.all?(required_scopes) end defp handle_error({:ok, conn, _}), do: conn defp handle_error({:error, %Plug.Conn{params: params} = conn, opts}) do conn = conn |> assign(:ex_oauth2_provider_failure, :unauthorized) |> halt params = Map.merge(params, %{reason: :unauthorized}) {mod, meth} = Map.get(opts, :handler) apply(mod, meth, [conn, params]) end defp build_handler_tuple(%{handler: mod}), do: {mod, :unauthorized} defp build_handler_tuple(_), do: {ExOauth2Provider.Plug.ErrorHandler, :unauthorized} end
lib/ex_oauth2_provider/plug/ensure_scopes.ex
0.713631
0.40695
ensure_scopes.ex
starcoder
defmodule Filtrex.Condition.Date do use Filtrex.Condition use Timex @string_date_comparators ["equals", "does not equal", "after", "on or after", "before", "on or before"] @start_end_comparators ["between", "not between"] @comparators @string_date_comparators ++ @start_end_comparators @type t :: Filtrex.Condition.Date.t @moduledoc """ `Filtrex.Condition.Date` is a specific condition type for handling date filters with various comparisons. Configuration Options: | Key | Type | Description | |--------|---------|----------------------------------------------------------------| | format | string | the date format\* to use for parsing the incoming date string \| | | | (defaults to YYYY-MM-DD) | \\\* See https://hexdocs.pm/timex/Timex.Format.DateTime.Formatters.Default.html There are three different value formats allowed based on the type of comparator: | Key | Type | Format / Allowed Values | |------------|---------|-------------------------------------------| | inverse | boolean | See `Filtrex.Condition.Text` | | column | string | any allowed keys from passed `config` | | comparator | string | after, on or after, before, on or before,\| | | | equals, does not equal | | value | string | "YYYY-MM-DD" | | type | string | "date" | | Key | Type | Format / Allowed Values | |------------|---------|-------------------------------------------| | inverse | boolean | See `Filtrex.Condition.Text` | | column | string | any allowed keys from passed `config` | | comparator | string | between, not between | | value | map | %{start: "YYYY-MM-DD", end: "YYYY-MM-DD"} | | type | string | "date" | """ def type, do: :date def comparators, do: @comparators def parse(config, %{column: column, comparator: comparator, value: value, inverse: inverse}) do with {:ok, parsed_comparator} <- validate_comparator(comparator), {:ok, parsed_value} <- validate_value(config, parsed_comparator, value) do {:ok, %Condition.Date{type: :date, inverse: inverse, column: column, comparator: parsed_comparator, value: parsed_value}} end end defp validate_comparator(comparator) when comparator in @comparators, do: {:ok, comparator} defp validate_comparator(comparator), do: {:error, parse_error(comparator, :comparator, :date)} defp validate_value(config, comparator, value) do cond do comparator in @string_date_comparators -> Filtrex.Validator.Date.parse_string_date(config, value) comparator in @start_end_comparators -> Filtrex.Validator.Date.parse_start_end(config, value) end end defimpl Filtrex.Encoder do @format Filtrex.Validator.Date.format encoder "after", "before", "column > ?", &default/1 encoder "before", "after", "column < ?", &default/1 encoder "on or after", "on or before", "column >= ?", &default/1 encoder "on or before", "on or after", "column <= ?", &default/1 encoder "between", "not between", "(column >= ?) AND (column <= ?)", fn (%{start: start, end: end_value}) -> [default_value(start), default_value(end_value)] end encoder "not between", "between", "(column > ?) AND (column < ?)", fn (%{start: start, end: end_value}) -> [default_value(end_value), default_value(start)] end encoder "equals", "does not equal", "column = ?", &default/1 encoder "does not equal", "equals", "column != ?", &default/1 defp default(timex_date) do {:ok, date} = Timex.format(timex_date, @format) [date] end defp default_value(timex_date), do: default(timex_date) |> List.first end end
lib/filtrex/conditions/date.ex
0.866599
0.534612
date.ex
starcoder
defmodule Membrane.MP4.Muxer.ISOM do @moduledoc """ Puts payloaded streams into an MPEG-4 container. Due to the structure of MPEG-4 containers, the muxer has to be used along with `Membrane.File.Sink` or any other sink that can handle `Membrane.File.SeekEvent`. The event is used to fill in `mdat` box size after processing all incoming buffers and, if `fast_start` is set to `true`, to insert `moov` box at the beginning of the file. """ use Membrane.Filter alias Membrane.{Buffer, File, MP4, RemoteStream, Time} alias Membrane.MP4.{Container, FileTypeBox, MediaDataBox, MovieBox, Track} @ftyp FileTypeBox.assemble("isom", ["isom", "iso2", "avc1", "mp41"]) @ftyp_size @ftyp |> Container.serialize!() |> byte_size() @mdat_header_size 8 def_input_pad :input, demand_unit: :buffers, caps: Membrane.MP4.Payload, availability: :on_request def_output_pad :output, caps: {RemoteStream, type: :bytestream, content_format: MP4} def_options fast_start: [ spec: boolean(), default: false, description: """ Generates a container more suitable for streaming by allowing media players to start playback as soon as they start to receive its media data. When set to `true`, the container metadata (`moov` atom) will be placed before media data (`mdat` atom). The equivalent of FFmpeg's `-movflags faststart` option. """ ], chunk_duration: [ spec: Time.t(), default: Time.seconds(1), description: """ Expected duration of each chunk in the resulting MP4 container. Once the total duration of samples received on one of the input pads exceeds that threshold, a chunk containing these samples is flushed. Interleaving chunks belonging to different tracks may have positive impact on performance of media players. """ ] @impl true def handle_init(options) do state = options |> Map.from_struct() |> Map.merge(%{ mdat_size: 0, next_track_id: 1, pad_order: [], pad_to_track: %{} }) {:ok, state} end @impl true def handle_pad_added(Pad.ref(:input, pad_ref), _ctx, state) do {track_id, state} = Map.get_and_update!(state, :next_track_id, &{&1, &1 + 1}) state = state |> Map.update!(:pad_order, &[pad_ref | &1]) |> put_in([:pad_to_track, pad_ref], track_id) {:ok, state} end @impl true def handle_caps(Pad.ref(:input, pad_ref) = pad, %Membrane.MP4.Payload{} = caps, ctx, state) do cond do # Handle receiving very first caps on the given pad is_nil(ctx.pads[pad].caps) -> update_in(state, [:pad_to_track, pad_ref], fn track_id -> caps |> Map.take([:width, :height, :content, :timescale]) |> Map.put(:id, track_id) |> Track.new() end) # Handle receiving all but first caps on the given pad when # inband_parameters? are allowed or caps are duplicated - ignore Map.get(ctx.pads[pad].caps.content, :inband_parameters?, false) || ctx.pads[pad].caps == caps -> state # otherwise we can assume that output will be corrupted true -> raise("ISOM Muxer doesn't support variable parameters") end |> then(&{:ok, &1}) end @impl true def handle_prepared_to_playing(_ctx, state) do # dummy mdat header will be overwritten in `finalize_mp4/1`, when media data size is known header = [@ftyp, MediaDataBox.assemble(<<>>)] |> Enum.map_join(&Container.serialize!/1) actions = [ caps: {:output, %RemoteStream{content_format: MP4}}, buffer: {:output, %Buffer{payload: header}} ] {{:ok, actions}, state} end @impl true def handle_demand(:output, _size, :buffers, _ctx, state) do next_ref = hd(state.pad_order) {{:ok, demand: {Pad.ref(:input, next_ref), 1}}, state} end @impl true def handle_process(Pad.ref(:input, pad_ref), buffer, _ctx, state) do {maybe_buffer, state} = state |> update_in([:pad_to_track, pad_ref], &Track.store_sample(&1, buffer)) |> maybe_flush_chunk(pad_ref) {{:ok, maybe_buffer ++ [redemand: :output]}, state} end @impl true def handle_end_of_stream(Pad.ref(:input, pad_ref), _ctx, state) do {buffer, state} = do_flush_chunk(state, pad_ref) state = Map.update!(state, :pad_order, &List.delete(&1, pad_ref)) if state.pad_order != [] do {{:ok, buffer ++ [redemand: :output]}, state} else actions = finalize_mp4(state) {{:ok, buffer ++ actions ++ [end_of_stream: :output]}, state} end end defp maybe_flush_chunk(state, pad_ref) do use Ratio, comparison: true track = get_in(state, [:pad_to_track, pad_ref]) if Track.current_chunk_duration(track) >= state.chunk_duration do do_flush_chunk(state, pad_ref) else {[], state} end end defp do_flush_chunk(state, pad_ref) do {chunk, track} = state |> get_in([:pad_to_track, pad_ref]) |> Track.flush_chunk(chunk_offset(state)) state = state |> Map.put(:mdat_size, state.mdat_size + byte_size(chunk)) |> put_in([:pad_to_track, pad_ref], track) |> Map.update!(:pad_order, &shift_left/1) {[buffer: {:output, %Buffer{payload: chunk}}], state} end defp finalize_mp4(state) do movie_box = state.pad_to_track |> Map.values() |> Enum.sort_by(& &1.id) |> MovieBox.assemble() after_ftyp = {:bof, @ftyp_size} mdat_total_size = @mdat_header_size + state.mdat_size update_mdat_actions = [ event: {:output, %File.SeekEvent{position: after_ftyp}}, buffer: {:output, %Buffer{payload: <<mdat_total_size::32>>}} ] if state.fast_start do moov = movie_box |> prepare_for_fast_start() |> Container.serialize!() update_mdat_actions ++ [ event: {:output, %File.SeekEvent{position: after_ftyp, insert?: true}}, buffer: {:output, %Buffer{payload: moov}} ] else moov = Container.serialize!(movie_box) [buffer: {:output, %Buffer{payload: moov}}] ++ update_mdat_actions end end defp prepare_for_fast_start(movie_box) do movie_box_size = movie_box |> Container.serialize!() |> byte_size() movie_box_children = get_in(movie_box, [:moov, :children]) # updates all `trak` boxes by adding `movie_box_size` to the offset of each chunk in their sample tables track_boxes_with_offset = movie_box_children |> Keyword.get_values(:trak) |> Enum.map(fn trak -> Container.update_box( trak.children, [:mdia, :minf, :stbl, :stco], [:fields, :entry_list], &Enum.map(&1, fn %{chunk_offset: offset} -> %{chunk_offset: offset + movie_box_size} end) ) end) |> Enum.map(&{:trak, %{children: &1, fields: %{}}}) # replaces all `trak` boxes with the ones with updated chunk offsets movie_box_children |> Keyword.delete(:trak) |> Keyword.merge(track_boxes_with_offset) |> then(&[moov: %{children: &1, fields: %{}}]) end defp chunk_offset(%{mdat_size: mdat_size}), do: @ftyp_size + @mdat_header_size + mdat_size defp shift_left([]), do: [] defp shift_left([first | rest]), do: rest ++ [first] end
lib/membrane_mp4/muxer/isom.ex
0.873923
0.555556
isom.ex
starcoder
defmodule Bcrypt do @moduledoc """ Elixir wrapper for the Bcrypt password hashing function. Most applications will just need to use the `add_hash/2` and `check_pass/3` convenience functions in this module. For a lower-level API, see Bcrypt.Base. ## Configuration The following parameter can be set in the config file: * `log_rounds` - the computational cost as number of log rounds * the default is 12 (2^12 rounds) If you are hashing passwords in your tests, it can be useful to add the following to the `config/test.exs` file: config :bcrypt_elixir, log_rounds: 4 NB. do not use this value in production. ## Bcrypt Bcrypt is a key derivation function for passwords designed by <NAME> and <NAME>. Bcrypt is an adaptive function, which means that it can be configured to remain slow and resistant to brute-force attacks even as computational power increases. ## Bcrypt versions This bcrypt implementation is based on the latest OpenBSD version, which fixed a small issue that affected some passwords longer than 72 characters. By default, it produces hashes with the prefix `$2b$`, and it can check hashes with either the `$2b$` prefix or the older `$2a$` prefix. It is also possible to generate hashes with the `$2a$` prefix by running the following command: Bcrypt.Base.hash_password("<PASSWORD>", Bcrypt.gen_salt(12, true)) This option should only be used if you need to generate hashes that are then checked by older libraries. The `$2y$` prefix is not supported. For advice on how to use hashes with the `$2y$` prefix, see [this issue](https://github.com/riverrun/comeonin/issues/103). Hash the password with a salt which is randomly generated. """ use Comeonin alias Bcrypt.Base @doc """ Generate a salt for use with the `Bcrypt.Base.hash_password` function. The log_rounds parameter determines the computational complexity of the generation of the password hash. Its default is 12, the minimum is 4, and the maximum is 31. The `legacy` option is for generating salts with the old `$2a$` prefix. Only use this option if you need to generate hashes that are then checked by older libraries. """ def gen_salt(log_rounds \\ 12, legacy \\ false) do Base.gensalt_nif(:crypto.strong_rand_bytes(16), log_rounds, (legacy and 97) || 98) end @doc """ Hashes a password with a randomly generated salt. ## Option * `log_rounds` - the computational cost as number of log rounds * the default is 12 (2^12 rounds) * this can be used to override the value set in the config ## Examples The following examples show how to hash a password with a randomly-generated salt and then verify a password: iex> hash = Bcrypt.hash_pwd_salt("password") ...> Bcrypt.verify_pass("password", hash) true iex> hash = Bcrypt.hash_pwd_salt("password") ...> Bcrypt.verify_pass("incorrect", hash) false """ @impl true def hash_pwd_salt(password, opts \\ []) do Base.hash_password( password, gen_salt( Keyword.get(opts, :log_rounds, Application.get_env(:bcrypt_elixir, :log_rounds, 12)), Keyword.get(opts, :legacy, false) ) ) end @doc """ Verifies a password by hashing the password and comparing the hashed value with a stored hash. See the documentation for `hash_pwd_salt/2` for examples of using this function. """ @impl true def verify_pass(password, stored_hash) do Base.checkpass_nif(:binary.bin_to_list(password), :binary.bin_to_list(stored_hash)) |> handle_verify end defp handle_verify(0), do: true defp handle_verify(_), do: false end
deps/bcrypt_elixir/lib/bcrypt.ex
0.852813
0.649037
bcrypt.ex
starcoder
defmodule Bonbon.API.Schema.Cuisine do use Absinthe.Schema use Translecto.Query import_types Bonbon.API.Schema.Cuisine.Region @moduledoc false @desc "An cuisine used in food" object :cuisine do field :id, :id, description: "The id of the cuisine" field :name, :string, description: "The name of the cuisine" field :region, :region, description: "The region of the cuisine" end @desc "A cuisine used in food" input_object :cuisine_input do field :id, :id, description: "The id of the cuisine" field :name, :string, description: "The name of the cuisine" field :region, :region_input, description: "The region of the cuisine" end def format(result), do: Map.merge(result, %{ region: Bonbon.API.Schema.Cuisine.Region.format(result.region) }) def get(%{ id: id, locale: locale }, _) do query = from cuisine in Bonbon.Model.Cuisine, where: cuisine.id == ^id, locales: ^Bonbon.Model.Locale.to_locale_id_list!(locale), translate: name in cuisine.name, join: region in Bonbon.Model.Cuisine.Region, where: region.id == cuisine.region_id, translate: continent in region.continent, translate: subregion in region.subregion, translate: country in region.country, translate: province in region.province, select: %{ id: cuisine.id, name: name.term, region: %{ id: region.id, continent: continent.term, subregion: subregion.term, country: country.term, province: province.term } } case Bonbon.Repo.one(query) do nil -> { :error, "Could not find cuisine" } result -> { :ok, format(result) } end end defp query_all(args = %{ find: find }) do find = find <> "%" where(query_all(Map.delete(args, :find)), [i, cn, r, c, s, n, p], ilike(cn.term, ^find) or ilike(c.term, ^find) or ilike(s.term, ^find) or ilike(n.term, ^find) or ilike(p.term, ^find) ) end defp query_all(args = %{ name: name }) do name = name <> "%" where(query_all(Map.delete(args, :name)), [i, n], ilike(n.term, ^name)) end defp query_all(args = %{ region: region }) do Enum.reduce(region, query_all(Map.delete(args, :region)), fn { :id, id }, query -> where(query, [i, cn, r, c, s, n, p], r.id == ^id) { :continent, continent }, query -> where(query, [i, cn, r, c, s, n, p], ilike(c.term, ^(continent <> "%"))) { :subregion, subregion }, query -> where(query, [i, cn, r, c, s, n, p], ilike(s.term, ^(subregion <> "%"))) { :country, country }, query -> where(query, [i, cn, r, c, s, n, p], ilike(n.term, ^(country <> "%"))) { :province, province }, query -> where(query, [i, cn, r, c, s, n, p], ilike(p.term, ^(province <> "%"))) end) end defp query_all(%{ locale: locale, limit: limit, offset: offset }) do from cuisine in Bonbon.Model.Cuisine, locales: ^Bonbon.Model.Locale.to_locale_id_list!(locale), translate: name in cuisine.name, join: region in Bonbon.Model.Cuisine.Region, on: region.id == cuisine.region_id, translate: continent in region.continent, translate: subregion in region.subregion, translate: country in region.country, translate: province in region.province, limit: ^limit, offset: ^offset, #todo: paginate select: %{ id: cuisine.id, name: name.term, region: %{ id: region.id, continent: continent.term, subregion: subregion.term, country: country.term, province: province.term } } end def all(args, _) do case Bonbon.Repo.all(query_all(args)) do nil -> { :error, "Could not retrieve any cuisines" } result -> { :ok, Enum.map(result, &format/1) } end end end
web/api/schema/cuisine.ex
0.539226
0.421463
cuisine.ex
starcoder
defmodule Jason.EncodeError do defexception [:message] @type t :: %__MODULE__{message: String.t} def new({:duplicate_key, key}) do %__MODULE__{message: "duplicate key: #{key}"} end def new({:invalid_byte, byte, original}) do %__MODULE__{message: "invalid byte #{inspect byte, base: :hex} in #{inspect original}"} end end defmodule Jason.Encode do @moduledoc """ Utilities for encoding elixir values to JSON. """ import Bitwise alias Jason.{Codegen, EncodeError, Encoder, Fragment} @typep escape :: (String.t, String.t, integer -> iodata) @typep encode_map :: (map, escape, encode_map -> iodata) @opaque opts :: {escape, encode_map} # @compile :native @doc false @spec encode(any, map) :: {:ok, iodata} | {:error, EncodeError.t | Exception.t} def encode(value, opts) do escape = escape_function(opts) encode_map = encode_map_function(opts) try do {:ok, value(value, escape, encode_map)} catch :throw, %EncodeError{} = e -> {:error, e} :error, %Protocol.UndefinedError{protocol: Jason.Encoder} = e -> {:error, e} end end defp encode_map_function(%{maps: maps}) do case maps do :naive -> &map_naive/3 :strict -> &map_strict/3 end end defp escape_function(%{escape: escape}) do case escape do :json -> &escape_json/3 :html_safe -> &escape_html/3 :unicode_safe -> &escape_unicode/3 :javascript_safe -> &escape_javascript/3 # Keep for compatibility with Poison :javascript -> &escape_javascript/3 :unicode -> &escape_unicode/3 end end @doc """ Equivalent to calling the `Jason.Encoder.encode/2` protocol function. Slightly more efficient for built-in types because of the internal dispatching. """ @spec value(term, opts) :: iodata def value(value, {escape, encode_map}) do value(value, escape, encode_map) end @doc false # We use this directly in the helpers and deriving for extra speed def value(value, escape, _encode_map) when is_atom(value) do encode_atom(value, escape) end def value(value, escape, _encode_map) when is_binary(value) do encode_string(value, escape) end def value(value, _escape, _encode_map) when is_integer(value) do integer(value) end def value(value, _escape, _encode_map) when is_float(value) do float(value) end def value(value, escape, encode_map) when is_list(value) do list(value, escape, encode_map) end def value(%{__struct__: module} = value, escape, encode_map) do struct(value, escape, encode_map, module) end def value(value, escape, encode_map) when is_map(value) do case Map.to_list(value) do [] -> "{}" keyword -> encode_map.(keyword, escape, encode_map) end end def value(value, escape, encode_map) do Encoder.encode(value, {escape, encode_map}) end @compile {:inline, integer: 1, float: 1} @spec atom(atom, opts) :: iodata def atom(atom, {escape, _encode_map}) do encode_atom(atom, escape) end defp encode_atom(nil, _escape), do: "null" defp encode_atom(true, _escape), do: "true" defp encode_atom(false, _escape), do: "false" defp encode_atom(atom, escape), do: encode_string(Atom.to_string(atom), escape) @spec integer(integer) :: iodata def integer(integer) do Integer.to_string(integer) end @spec float(float) :: iodata def float(float) do :io_lib_format.fwrite_g(float) end @spec list(list, opts) :: iodata def list(list, {escape, encode_map}) do list(list, escape, encode_map) end defp list([], _escape, _encode_map) do "[]" end defp list([head | tail], escape, encode_map) do [?[, value(head, escape, encode_map) | list_loop(tail, escape, encode_map)] end defp list_loop([], _escape, _encode_map) do ']' end defp list_loop([head | tail], escape, encode_map) do [?,, value(head, escape, encode_map) | list_loop(tail, escape, encode_map)] end @spec keyword(keyword, opts) :: iodata def keyword(list, _) when list == [], do: "{}" def keyword(list, {escape, encode_map}) when is_list(list) do encode_map.(list, escape, encode_map) end @spec map(map, opts) :: iodata def map(value, {escape, encode_map}) do case Map.to_list(value) do [] -> "{}" keyword -> encode_map.(keyword, escape, encode_map) end end defp map_naive([{key, value} | tail], escape, encode_map) do ["{\"", key(key, escape), "\":", value(value, escape, encode_map) | map_naive_loop(tail, escape, encode_map)] end defp map_naive_loop([], _escape, _encode_map) do '}' end defp map_naive_loop([{key, value} | tail], escape, encode_map) do [",\"", key(key, escape), "\":", value(value, escape, encode_map) | map_naive_loop(tail, escape, encode_map)] end defp map_strict([{key, value} | tail], escape, encode_map) do key = IO.iodata_to_binary(key(key, escape)) visited = %{key => []} ["{\"", key, "\":", value(value, escape, encode_map) | map_strict_loop(tail, escape, encode_map, visited)] end defp map_strict_loop([], _encode_map, _escape, _visited) do '}' end defp map_strict_loop([{key, value} | tail], escape, encode_map, visited) do key = IO.iodata_to_binary(key(key, escape)) case visited do %{^key => _} -> error({:duplicate_key, key}) _ -> visited = Map.put(visited, key, []) [",\"", key, "\":", value(value, escape, encode_map) | map_strict_loop(tail, escape, encode_map, visited)] end end @spec struct(struct, opts) :: iodata def struct(%module{} = value, {escape, encode_map}) do struct(value, escape, encode_map, module) end # TODO: benchmark the effect of inlining the to_iso8601 functions for module <- [Date, Time, NaiveDateTime, DateTime] do defp struct(value, _escape, _encode_map, unquote(module)) do [?\", unquote(module).to_iso8601(value), ?\"] end end defp struct(value, _escape, _encode_map, Decimal) do # silence the xref warning decimal = Decimal [?\", decimal.to_string(value, :normal), ?\"] end defp struct(value, escape, encode_map, Fragment) do %{encode: encode} = value encode.({escape, encode_map}) end defp struct(value, escape, encode_map, _module) do Encoder.encode(value, {escape, encode_map}) end @doc false # This is used in the helpers and deriving implementation def key(string, escape) when is_binary(string) do escape.(string, string, 0) end def key(atom, escape) when is_atom(atom) do string = Atom.to_string(atom) escape.(string, string, 0) end def key(other, escape) do string = String.Chars.to_string(other) escape.(string, string, 0) end @spec string(String.t, opts) :: iodata def string(string, {escape, _encode_map}) do encode_string(string, escape) end defp encode_string(string, escape) do [?\", escape.(string, string, 0), ?\"] end slash_escapes = Enum.zip('\b\t\n\f\r\"\\', 'btnfr"\\') surogate_escapes = Enum.zip([0x2028, 0x2029], ["\\u2028", "\\u2029"]) ranges = [{0x00..0x1F, :unicode} | slash_escapes] html_ranges = [{0x00..0x1F, :unicode}, {?/, ?/} | slash_escapes] escape_jt = Codegen.jump_table(html_ranges, :error) Enum.each(escape_jt, fn {byte, :unicode} -> sequence = List.to_string(:io_lib.format("\\u~4.16.0B", [byte])) defp escape(unquote(byte)), do: unquote(sequence) {byte, char} when is_integer(char) -> defp escape(unquote(byte)), do: unquote(<<?\\, char>>) {byte, :error} -> defp escape(unquote(byte)), do: throw(:error) end) ## regular JSON escape json_jt = Codegen.jump_table(ranges, :chunk, 0x7F + 1) defp escape_json(data, original, skip) do escape_json(data, [], original, skip) end Enum.map(json_jt, fn {byte, :chunk} -> defp escape_json(<<byte, rest::bits>>, acc, original, skip) when byte === unquote(byte) do escape_json_chunk(rest, acc, original, skip, 1) end {byte, _escape} -> defp escape_json(<<byte, rest::bits>>, acc, original, skip) when byte === unquote(byte) do acc = [acc | escape(byte)] escape_json(rest, acc, original, skip + 1) end end) defp escape_json(<<char::utf8, rest::bits>>, acc, original, skip) when char <= 0x7FF do escape_json_chunk(rest, acc, original, skip, 2) end defp escape_json(<<char::utf8, rest::bits>>, acc, original, skip) when char <= 0xFFFF do escape_json_chunk(rest, acc, original, skip, 3) end defp escape_json(<<_char::utf8, rest::bits>>, acc, original, skip) do escape_json_chunk(rest, acc, original, skip, 4) end defp escape_json(<<>>, acc, _original, _skip) do acc end defp escape_json(<<byte, _rest::bits>>, _acc, original, _skip) do error({:invalid_byte, byte, original}) end Enum.map(json_jt, fn {byte, :chunk} -> defp escape_json_chunk(<<byte, rest::bits>>, acc, original, skip, len) when byte === unquote(byte) do escape_json_chunk(rest, acc, original, skip, len + 1) end {byte, _escape} -> defp escape_json_chunk(<<byte, rest::bits>>, acc, original, skip, len) when byte === unquote(byte) do part = binary_part(original, skip, len) acc = [acc, part | escape(byte)] escape_json(rest, acc, original, skip + len + 1) end end) defp escape_json_chunk(<<char::utf8, rest::bits>>, acc, original, skip, len) when char <= 0x7FF do escape_json_chunk(rest, acc, original, skip, len + 2) end defp escape_json_chunk(<<char::utf8, rest::bits>>, acc, original, skip, len) when char <= 0xFFFF do escape_json_chunk(rest, acc, original, skip, len + 3) end defp escape_json_chunk(<<_char::utf8, rest::bits>>, acc, original, skip, len) do escape_json_chunk(rest, acc, original, skip, len + 4) end defp escape_json_chunk(<<>>, acc, original, skip, len) do part = binary_part(original, skip, len) [acc | part] end defp escape_json_chunk(<<byte, _rest::bits>>, _acc, original, _skip, _len) do error({:invalid_byte, byte, original}) end ## javascript safe JSON escape defp escape_javascript(data, original, skip) do escape_javascript(data, [], original, skip) end Enum.map(json_jt, fn {byte, :chunk} -> defp escape_javascript(<<byte, rest::bits>>, acc, original, skip) when byte === unquote(byte) do escape_javascript_chunk(rest, acc, original, skip, 1) end {byte, _escape} -> defp escape_javascript(<<byte, rest::bits>>, acc, original, skip) when byte === unquote(byte) do acc = [acc | escape(byte)] escape_javascript(rest, acc, original, skip + 1) end end) defp escape_javascript(<<char::utf8, rest::bits>>, acc, original, skip) when char <= 0x7FF do escape_javascript_chunk(rest, acc, original, skip, 2) end Enum.map(surogate_escapes, fn {byte, escape} -> defp escape_javascript(<<unquote(byte)::utf8, rest::bits>>, acc, original, skip) do acc = [acc | unquote(escape)] escape_javascript(rest, acc, original, skip + 3) end end) defp escape_javascript(<<char::utf8, rest::bits>>, acc, original, skip) when char <= 0xFFFF do escape_javascript_chunk(rest, acc, original, skip, 3) end defp escape_javascript(<<_char::utf8, rest::bits>>, acc, original, skip) do escape_javascript_chunk(rest, acc, original, skip, 4) end defp escape_javascript(<<>>, acc, _original, _skip) do acc end defp escape_javascript(<<byte, _rest::bits>>, _acc, original, _skip) do error({:invalid_byte, byte, original}) end Enum.map(json_jt, fn {byte, :chunk} -> defp escape_javascript_chunk(<<byte, rest::bits>>, acc, original, skip, len) when byte === unquote(byte) do escape_javascript_chunk(rest, acc, original, skip, len + 1) end {byte, _escape} -> defp escape_javascript_chunk(<<byte, rest::bits>>, acc, original, skip, len) when byte === unquote(byte) do part = binary_part(original, skip, len) acc = [acc, part | escape(byte)] escape_javascript(rest, acc, original, skip + len + 1) end end) defp escape_javascript_chunk(<<char::utf8, rest::bits>>, acc, original, skip, len) when char <= 0x7FF do escape_javascript_chunk(rest, acc, original, skip, len + 2) end Enum.map(surogate_escapes, fn {byte, escape} -> defp escape_javascript_chunk(<<unquote(byte)::utf8, rest::bits>>, acc, original, skip, len) do part = binary_part(original, skip, len) acc = [acc, part | unquote(escape)] escape_javascript(rest, acc, original, skip + len + 3) end end) defp escape_javascript_chunk(<<char::utf8, rest::bits>>, acc, original, skip, len) when char <= 0xFFFF do escape_javascript_chunk(rest, acc, original, skip, len + 3) end defp escape_javascript_chunk(<<_char::utf8, rest::bits>>, acc, original, skip, len) do escape_javascript_chunk(rest, acc, original, skip, len + 4) end defp escape_javascript_chunk(<<>>, acc, original, skip, len) do part = binary_part(original, skip, len) [acc | part] end defp escape_javascript_chunk(<<byte, _rest::bits>>, _acc, original, _skip, _len) do error({:invalid_byte, byte, original}) end ## HTML safe JSON escape html_jt = Codegen.jump_table(html_ranges, :chunk, 0x7F + 1) defp escape_html(data, original, skip) do escape_html(data, [], original, skip) end Enum.map(html_jt, fn {byte, :chunk} -> defp escape_html(<<byte, rest::bits>>, acc, original, skip) when byte === unquote(byte) do escape_html_chunk(rest, acc, original, skip, 1) end {byte, _escape} -> defp escape_html(<<byte, rest::bits>>, acc, original, skip) when byte === unquote(byte) do acc = [acc | escape(byte)] escape_html(rest, acc, original, skip + 1) end end) defp escape_html(<<char::utf8, rest::bits>>, acc, original, skip) when char <= 0x7FF do escape_html_chunk(rest, acc, original, skip, 2) end Enum.map(surogate_escapes, fn {byte, escape} -> defp escape_html(<<unquote(byte)::utf8, rest::bits>>, acc, original, skip) do acc = [acc | unquote(escape)] escape_html(rest, acc, original, skip + 3) end end) defp escape_html(<<char::utf8, rest::bits>>, acc, original, skip) when char <= 0xFFFF do escape_html_chunk(rest, acc, original, skip, 3) end defp escape_html(<<_char::utf8, rest::bits>>, acc, original, skip) do escape_html_chunk(rest, acc, original, skip, 4) end defp escape_html(<<>>, acc, _original, _skip) do acc end defp escape_html(<<byte, _rest::bits>>, _acc, original, _skip) do error({:invalid_byte, byte, original}) end Enum.map(html_jt, fn {byte, :chunk} -> defp escape_html_chunk(<<byte, rest::bits>>, acc, original, skip, len) when byte === unquote(byte) do escape_html_chunk(rest, acc, original, skip, len + 1) end {byte, _escape} -> defp escape_html_chunk(<<byte, rest::bits>>, acc, original, skip, len) when byte === unquote(byte) do part = binary_part(original, skip, len) acc = [acc, part | escape(byte)] escape_html(rest, acc, original, skip + len + 1) end end) defp escape_html_chunk(<<char::utf8, rest::bits>>, acc, original, skip, len) when char <= 0x7FF do escape_html_chunk(rest, acc, original, skip, len + 2) end Enum.map(surogate_escapes, fn {byte, escape} -> defp escape_html_chunk(<<unquote(byte)::utf8, rest::bits>>, acc, original, skip, len) do part = binary_part(original, skip, len) acc = [acc, part | unquote(escape)] escape_html(rest, acc, original, skip + len + 3) end end) defp escape_html_chunk(<<char::utf8, rest::bits>>, acc, original, skip, len) when char <= 0xFFFF do escape_html_chunk(rest, acc, original, skip, len + 3) end defp escape_html_chunk(<<_char::utf8, rest::bits>>, acc, original, skip, len) do escape_html_chunk(rest, acc, original, skip, len + 4) end defp escape_html_chunk(<<>>, acc, original, skip, len) do part = binary_part(original, skip, len) [acc | part] end defp escape_html_chunk(<<byte, _rest::bits>>, _acc, original, _skip, _len) do error({:invalid_byte, byte, original}) end ## unicode escape defp escape_unicode(data, original, skip) do escape_unicode(data, [], original, skip) end Enum.map(json_jt, fn {byte, :chunk} -> defp escape_unicode(<<byte, rest::bits>>, acc, original, skip) when byte === unquote(byte) do escape_unicode_chunk(rest, acc, original, skip, 1) end {byte, _escape} -> defp escape_unicode(<<byte, rest::bits>>, acc, original, skip) when byte === unquote(byte) do acc = [acc | escape(byte)] escape_unicode(rest, acc, original, skip + 1) end end) defp escape_unicode(<<char::utf8, rest::bits>>, acc, original, skip) when char <= 0xFF do acc = [acc, "\\u00" | Integer.to_string(char, 16)] escape_unicode(rest, acc, original, skip + 2) end defp escape_unicode(<<char::utf8, rest::bits>>, acc, original, skip) when char <= 0x7FF do acc = [acc, "\\u0" | Integer.to_string(char, 16)] escape_unicode(rest, acc, original, skip + 2) end defp escape_unicode(<<char::utf8, rest::bits>>, acc, original, skip) when char <= 0xFFF do acc = [acc, "\\u0" | Integer.to_string(char, 16)] escape_unicode(rest, acc, original, skip + 3) end defp escape_unicode(<<char::utf8, rest::bits>>, acc, original, skip) when char <= 0xFFFF do acc = [acc, "\\u" | Integer.to_string(char, 16)] escape_unicode(rest, acc, original, skip + 3) end defp escape_unicode(<<char::utf8, rest::bits>>, acc, original, skip) do char = char - 0x10000 acc = [ acc, "\\uD", Integer.to_string(0x800 ||| (char >>> 10), 16), "\\uD" | Integer.to_string(0xC00 ||| (char &&& 0x3FF), 16) ] escape_unicode(rest, acc, original, skip + 4) end defp escape_unicode(<<>>, acc, _original, _skip) do acc end defp escape_unicode(<<byte, _rest::bits>>, _acc, original, _skip) do error({:invalid_byte, byte, original}) end Enum.map(json_jt, fn {byte, :chunk} -> defp escape_unicode_chunk(<<byte, rest::bits>>, acc, original, skip, len) when byte === unquote(byte) do escape_unicode_chunk(rest, acc, original, skip, len + 1) end {byte, _escape} -> defp escape_unicode_chunk(<<byte, rest::bits>>, acc, original, skip, len) when byte === unquote(byte) do part = binary_part(original, skip, len) acc = [acc, part | escape(byte)] escape_unicode(rest, acc, original, skip + len + 1) end end) defp escape_unicode_chunk(<<char::utf8, rest::bits>>, acc, original, skip, len) when char <= 0xFF do part = binary_part(original, skip, len) acc = [acc, part, "\\u00" | Integer.to_string(char, 16)] escape_unicode(rest, acc, original, skip + len + 2) end defp escape_unicode_chunk(<<char::utf8, rest::bits>>, acc, original, skip, len) when char <= 0x7FF do part = binary_part(original, skip, len) acc = [acc, part, "\\u0" | Integer.to_string(char, 16)] escape_unicode(rest, acc, original, skip + len + 2) end defp escape_unicode_chunk(<<char::utf8, rest::bits>>, acc, original, skip, len) when char <= 0xFFF do part = binary_part(original, skip, len) acc = [acc, part, "\\u0" | Integer.to_string(char, 16)] escape_unicode(rest, acc, original, skip + len + 3) end defp escape_unicode_chunk(<<char::utf8, rest::bits>>, acc, original, skip, len) when char <= 0xFFFF do part = binary_part(original, skip, len) acc = [acc, part, "\\u" | Integer.to_string(char, 16)] escape_unicode(rest, acc, original, skip + len + 3) end defp escape_unicode_chunk(<<char::utf8, rest::bits>>, acc, original, skip, len) do char = char - 0x10000 part = binary_part(original, skip, len) acc = [ acc, part, "\\uD", Integer.to_string(0x800 ||| (char >>> 10), 16), "\\uD" | Integer.to_string(0xC00 ||| (char &&& 0x3FF), 16) ] escape_unicode(rest, acc, original, skip + len + 4) end defp escape_unicode_chunk(<<>>, acc, original, skip, len) do part = binary_part(original, skip, len) [acc | part] end defp escape_unicode_chunk(<<byte, _rest::bits>>, _acc, original, _skip, _len) do error({:invalid_byte, byte, original}) end @compile {:inline, error: 1} defp error(error) do throw EncodeError.new(error) end end
lib/encode.ex
0.72952
0.47457
encode.ex
starcoder
defmodule Exq.Enqueuer.Server do @moduledoc """ The Enqueuer is responsible for enqueueing jobs into Redis. It can either be called directly by the client, or instantiated as a standalone process. It supports enqueuing immediate jobs, or scheduling jobs in the future. ## Initialization: * `:name` - Name of target registered process * `:namespace` - Redis namespace to store all data under. Defaults to "exq". * `:queues` - Array of currently active queues (TODO: Remove, I suspect it's not needed). * `:redis` - pid of Redis process. * `:scheduler_poll_timeout` - How often to poll Redis for scheduled / retry jobs. """ require Logger alias Exq.Support.Config alias Exq.Redis.JobQueue use GenServer defmodule State do defstruct redis: nil, namespace: nil end def start_link(opts \\ []) do GenServer.start_link(__MODULE__, opts, name: server_name(opts[:name])) end ##=========================================================== ## gen server callbacks ##=========================================================== def init(opts) do {:ok, %State{redis: opts[:redis], namespace: opts[:namespace]}} end def handle_cast({:enqueue, from, queue, worker, args, options}, state) do response = JobQueue.enqueue(state.redis, state.namespace, queue, worker, args, options) GenServer.reply(from, response) {:noreply, state} end def handle_cast({:enqueue_at, from, queue, time, worker, args, options}, state) do response = JobQueue.enqueue_at(state.redis, state.namespace, queue, time, worker, args, options) GenServer.reply(from, response) {:noreply, state} end def handle_cast({:enqueue_in, from, queue, offset, worker, args, options}, state) do response = JobQueue.enqueue_in(state.redis, state.namespace, queue, offset, worker, args, options) GenServer.reply(from, response) {:noreply, state} end def handle_call({:enqueue, queue, worker, args, options}, _from, state) do response = JobQueue.enqueue(state.redis, state.namespace, queue, worker, args, options) {:reply, response, state} end def handle_call({:enqueue_at, queue, time, worker, args, options}, _from, state) do response = JobQueue.enqueue_at(state.redis, state.namespace, queue, time, worker, args, options) {:reply, response, state} end def handle_call({:enqueue_in, queue, offset, worker, args, options}, _from, state) do response = JobQueue.enqueue_in(state.redis, state.namespace, queue, offset, worker, args, options) {:reply, response, state} end def terminate(_reason, _state) do :ok end # Internal Functions def server_name(name) do name = name || Config.get(:name) "#{name}.Enqueuer" |> String.to_atom end end
lib/exq/enqueuer/server.ex
0.625324
0.550668
server.ex
starcoder
defmodule Tensor.Vector do alias Tensor.{Vector, Tensor} import Kernel, except: [length: 1] defmodule Inspect do @doc false def inspect(vector, _opts) do "#Vector<(#{Tensor.Inspect.dimension_string(vector)})#{inspect(Vector.to_list(vector))}>" end end def new() do Tensor.new([], [0], 0) end def new(length_or_list_or_range, identity \\ 0) def new(list, identity) when is_list(list) do Tensor.new(list, [Kernel.length(list)], identity) end def new(length, identity) when is_number(length) do Tensor.new([], [length], identity) end def new(range = _.._, identity) do new(range |> Enum.to_list(), identity) end def length(vector) do hd(vector.dimensions) end def from_list(list, identity \\ 0) do Tensor.new(list, [Kernel.length(list)], identity) end def reverse(vector = %Tensor{dimensions: [l]}) do new_contents = for {i, v} <- vector.contents, into: %{} do {l - 1 - i, v} end %Tensor{vector | contents: new_contents} end def dot_product(a = %Tensor{dimensions: [l]}, b = %Tensor{dimensions: [l]}) do products = for i <- 0..(l - 1) do a[i] * b[i] end Enum.sum(products) end def dot_product(_a, _b), do: raise( Tensor.ArithmeticError, "Two Vectors have to have the same length to be able to compute the dot product" ) @doc """ Returns the current identity of vector `vector`. """ defdelegate identity(vector), to: Tensor @doc """ `true` if `a` is a Vector. """ defdelegate vector?(a), to: Tensor @doc """ Returns the element at `index` from `vector`. """ defdelegate fetch(vector, index), to: Tensor @doc """ Returns the element at `index` from `vector`. If `index` is out of bounds, returns `default`. """ defdelegate get(vector, index, default), to: Tensor defdelegate pop(vector, index, default), to: Tensor defdelegate get_and_update(vector, index, function), to: Tensor defdelegate merge_with_index(vector_a, vector_b, function), to: Tensor defdelegate merge(vector_a, vector_b, function), to: Tensor defdelegate to_list(vector), to: Tensor defdelegate lift(vector), to: Tensor defdelegate map(vector, function), to: Tensor defdelegate with_coordinates(vector), to: Tensor defdelegate sparse_map_with_coordinates(vector, function), to: Tensor defdelegate dense_map_with_coordinates(vector, function), to: Tensor defdelegate add(a, b), to: Tensor defdelegate sub(a, b), to: Tensor defdelegate mult(a, b), to: Tensor defdelegate div(a, b), to: Tensor defdelegate add_number(a, b), to: Tensor defdelegate sub_number(a, b), to: Tensor defdelegate mult_number(a, b), to: Tensor defdelegate div_number(a, b), to: Tensor @doc """ Elementwise addition of vectors `vector_a` and `vector_b`. """ defdelegate add_vector(vector_a, vector_b), to: Tensor, as: :add_tensor @doc """ Elementwise subtraction of `vector_b` from `vector_a`. """ defdelegate sub_vector(vector_a, vector_b), to: Tensor, as: :sub_tensor @doc """ Elementwise multiplication of `vector_a` with `vector_b`. """ defdelegate mult_vector(vector_a, vector_b), to: Tensor, as: :mult_tensor @doc """ Elementwise division of `vector_a` and `vector_b`. Make sure that the identity of `vector_b` isn't 0 before doing this. """ defdelegate div_vector(vector_a, vector_b), to: Tensor, as: :div_tensor end
lib/tensor/vector.ex
0.815416
0.909907
vector.ex
starcoder
defmodule HomeWeb.Models.GraphModel do @moduledoc "This model constructs data for graphs" import HomeBot.Tools alias HomeBot.DataStore use Timex def gas_usage_data(start_time, end_time, group_quantity, group_unit, title \\ "Gas usage") do result = DataStore.get_energy_usage(start_time, end_time, group_quantity, group_unit) labels = result |> Enum.map(&Map.fetch!(&1, :time)) values = result |> Enum.map(&Map.fetch!(&1, :usage_gas_meter)) %{ title: title, labels: labels, datasets: [ %{ name: "Gas", data: values } ] } end def electricity_usage_data( start_time, end_time, group_unit, group_quantity, title \\ "Electricity usage" ) do result = DataStore.get_energy_usage(start_time, end_time, group_unit, group_quantity) labels = get_labels(result) %{ title: title, labels: labels, datasets: [ %{ name: "Low tariff (kWh)", data: Enum.map(result, &Map.fetch!(&1, :usage_low_tariff)) }, %{ name: "Normal tariff (kWh)", data: Enum.map(result, &Map.fetch!(&1, :usage_normal_tariff)) } ] } end def daily_gas_and_temperature_data do gas_usage = DataStore.get_gas_usage_per_day(48) temps = DataStore.get_average_temperature_per_day(48) labels = get_labels(gas_usage) gas_values = gas_usage |> Enum.map(&Map.fetch!(&1, "usage")) temperature_values = temps |> Enum.map(&Map.fetch!(&1, "temperature")) %{ title: "Daily gas usage", labels: labels, datasets: [ %{ name: "Gas (m3)", data: gas_values }, %{ name: "Temperature (°C)", data: temperature_values } ] } end def gas_usage_per_temperature_data do daily_temperatures = DataStore.get_average_temperature_per_day(:all) daily_gas_usage = DataStore.get_gas_usage_per_day(:all) raw_data = join_on_key(daily_temperatures, daily_gas_usage, "time") |> Enum.filter(fn record -> record["temperature"] != nil end) |> Enum.group_by(fn record -> round(record["temperature"]) end) |> Enum.map(fn {temperature, records} -> [temperature, mean_for_key(records, "usage")] end) |> Enum.sort_by(fn [temperature, _gas_usage] -> temperature end) %{ title: "Gas usage per temperature", labels: Enum.map(raw_data, fn [temperature, _gas_usage] -> temperature end), datasets: [ %{ name: "Gas", data: Enum.map(raw_data, fn [_temperature, gas_usage] -> gas_usage end) } ] } end def gas_usage_per_temperature_per_year_data do daily_temperatures = DataStore.get_average_temperature_per_day(:all) daily_gas_usage = DataStore.get_gas_usage_per_day(:all) {%{"temperature" => _min_temp}, %{"temperature" => max_temp}} = daily_temperatures |> Enum.filter(fn record -> record["temperature"] != nil end) |> Enum.min_max_by(fn record -> record["temperature"] end) temp_range = 0..round(max_temp) |> Enum.to_list() raw_data = join_on_key(daily_temperatures, daily_gas_usage, "time") |> Enum.group_by(fn record -> get_year(record["time"]) end) |> Enum.map(fn {year, records} -> [year, to_gas_usage_per_temp(records, temp_range)] end) dataset_data = raw_data |> Enum.map(fn [year, records] -> %{ name: year, data: Enum.map(records, fn [_temperature, gas_usage] -> gas_usage end) } end) %{ title: "Gas usage per temperature per year", labels: temp_range, datasets: dataset_data } end def hourly_electricity_usage_data do result = DataStore.get_electricity_usage_per_hour(3) labels = result |> Enum.map(&Map.fetch!(&1, "time")) %{ title: "Hourly electricity usage", labels: labels, datasets: [ %{ name: "Electricity (kWh)", data: Enum.map(result, &Map.fetch!(&1, "usage")) } ] } end def current_electricity_usage_data do result = DataStore.get_electricity_usage(5) labels = result |> Enum.map(&Map.fetch!(&1, "time")) %{ title: "Electricity usage", labels: labels, datasets: [ %{ name: "Electricity (kW)", data: Enum.map(result, &Map.fetch!(&1, "usage")) } ] } end def get_gas_mean_and_sd_of_period(period_start, period_end, ticks_string) do data = DataStore.get_gas_usage("1h", period_start, period_end) get_mean_and_sd_of_period(data, ticks_string) end def get_electricity_mean_and_sd_of_period(period_start, period_end, ticks_string) do data = DataStore.get_electricity_usage("1h", period_start, period_end) |> Enum.map(fn record -> %{ "time" => record["time"], "usage" => record["low_tariff_usage"] + record["normal_tariff_usage"] } end) get_mean_and_sd_of_period(data, ticks_string) end defp get_mean_and_sd_of_period(data, ticks_string) do ticks = String.split(ticks_string, ",") |> Enum.map(&String.to_integer/1) values = data |> Enum.filter(fn %{"time" => time} -> Enum.member?(ticks, get_hour(time)) end) |> Enum.map(fn %{"usage" => usage} -> usage end) mean = mean(values) sd = standard_deviation(values, mean) {mean, sd} end defp to_gas_usage_per_temp(records, temp_range) do grouped_records = records |> Enum.filter(fn record -> record["temperature"] != nil end) |> Enum.group_by(fn record -> round(record["temperature"]) end) temp_range |> Enum.map(fn temperature -> [temperature, mean_for_key(Map.get(grouped_records, temperature, []), "usage")] end) |> Enum.sort_by(fn [temperature, _gas_usage] -> temperature end) end def get_hour(datetime) do {:ok, dt, _} = DateTime.from_iso8601(datetime) Timezone.convert(dt, "Europe/Amsterdam").hour end defp get_year(datetime) do {:ok, dt, _} = DateTime.from_iso8601(datetime) DateTime.to_date(dt).year end defp get_labels(records) do records |> Enum.map(&Map.fetch!(&1, :time)) # TODO: Time is in UTC, convert to Europe/Amsterdam end end
lib/home_web/models/graph_model.ex
0.782621
0.455199
graph_model.ex
starcoder
defmodule MeshxConsul.Ttl do @moduledoc """ Manages TTL health check workers used by mesh services. Consul agent can use multiple kinds of checks, e.g. script checks, HTTP and TCP checks, gRPC and [others](https://www.consul.io/docs/discovery/checks). `MeshxConsul` is using TTL (Time To Live) health checks for services started with `MeshxConsul.start/4`. Dedicated worker is used to periodically update service health check state over Consul agent HTTP interface. Service health checks are defined using `template` argument of `MeshxConsul.start/4`. Default health check specification: ```elixir [ ttl: %{ id: "ttl:{{id}}", status: "passing", ttl: 5_000 } ] ``` Health check keys: * `:id` - service id (value rendered using Mustache system), * `:status` - initial health check status, * `:ttl` - health check state update interval, milliseconds. Health check state can be one of following: `"passing"`, `"warning"` or `"critical"`. TTL checks are automatically started when running `MeshxConsul.start/4` and stopped with `MeshxConsul.stop/1`. Users usually should not directly use `start/2` and `stop/1` functions defined in this module. `set_status/2` can be used to set service status depending on external conditions. One can for example use [`:os_mon`](http://erlang.org/doc/man/os_mon_app.html) [`:cpu_sup`](http://erlang.org/doc/man/cpu_sup.html) to monitor CPU utilization and update service status accordingly. #### Example: ```elixir iex(1)> MeshxConsul.start("service1") {:ok, "service1-h11", {:tcp, {127, 0, 0, 1}, 1024}} iex(2)> MeshxConsul.Ttl.get_status("service1-h11") "passing" iex(3)> MeshxConsul.Ttl.set_status("service1-h11", "warning") :ok iex(4)> MeshxConsul.Ttl.get_status("service1-h11") "warning" ``` """ alias MeshxConsul.Ttl.{Supervisor, Worker} @doc """ Starts TTL check worker for `service_id` service using `ttl_opts`. """ @spec start(service_id :: atom() | String.t(), ttl_opts :: map()) :: DynamicSupervisor.on_start_child() | {:ok, nil} defdelegate start(service_id, ttl_opts), to: Supervisor @doc """ Stops TTL check worker for `service_id` service. """ @spec stop(service_id :: atom() | String.t()) :: :ok | {:error, :not_found} defdelegate stop(service_id), to: Supervisor @doc """ Gets TTL check worker status for `service_id` service. """ @spec get_status(service_id :: atom() | String.t()) :: String.t() def get_status(service_id), do: Worker.get_status(Supervisor.id(service_id)) @doc """ Sets TTL check worker `status` for `service_id` service. """ @spec set_status(service_id :: atom() | String.t(), status :: String.t()) :: :ok def set_status(service_id, status), do: Worker.set_status(Supervisor.id(service_id), status) end
lib/ttl/ttl.ex
0.843863
0.85984
ttl.ex
starcoder
defmodule Xema.ValidationError do @moduledoc """ Raised when a validation fails. """ @type path :: [atom | integer | String.t()] @type opts :: [] | [path: path] defexception [:message, :reason] @impl true def message(%{message: nil} = exception), do: format_error(exception.reason) def message(%{message: message}), do: message @impl true def blame(exception, stacktrace) do message = message(exception) {%{exception | message: message}, stacktrace} end @doc """ This function returns an error message for an error or error tuple. ## Example ```elixir iex> schema = Xema.new(:integer) iex> schema ...> |> Xema.Validator.validate(1.1) ...> |> Xema.ValidationError.format_error() "Expected :integer, got 1.1." ``` """ @spec format_error({:error, map} | map) :: String.t() def format_error({:error, error}), do: format_error(error) def format_error(error), do: error |> travers_errors([], &format_error/3) |> Enum.reverse() |> Enum.join("\n") @doc """ Traverse the error tree and invokes the given function. ## Example ```elixir iex> fun = fn _error, path, acc -> ...> ["Error at " <> inspect(path) | acc] ...> end iex> iex> schema = Xema.new( ...> properties: %{ ...> int: :integer, ...> names: {:list, items: :string}, ...> num: [any_of: [:integer, :float]] ...> } ...> ) iex> iex> data = %{int: "x", names: [1, "x", 5], num: :foo} iex> iex> schema ...> |> Xema.Validator.validate(data) ...> |> Xema.ValidationError.travers_errors([], fun) [ "Error at [:num]", "Error at [:names, 2]", "Error at [:names, 0]", "Error at [:names]", "Error at [:int]", "Error at []" ] """ @spec travers_errors({:error, map} | map, acc, (map, path, acc -> acc), opts) :: acc when acc: any def travers_errors(error, acc, fun, opts \\ []) def travers_errors({:error, error}, acc, fun, opts), do: travers_errors(error, acc, fun, opts) def travers_errors(error, acc, fun, []), do: travers_errors(error, acc, fun, path: []) def travers_errors(%{properties: properties} = error, acc, fun, opts), do: Enum.reduce( properties, fun.(error, opts[:path], acc), fn {key, value}, acc -> travers_errors(value, acc, fun, path: opts[:path] ++ [key]) end ) def travers_errors(%{items: items} = error, acc, fun, opts), do: Enum.reduce( items, fun.(error, opts[:path], acc), fn {key, value}, acc -> travers_errors(value, acc, fun, path: opts[:path] ++ [key]) end ) def travers_errors(error, acc, fun, opts), do: fun.(error, opts[:path], acc) defp format_error(%{minimum: minimum, exclusive_minimum: true, value: value}, path, acc) when minimum == value do # The guard is used to match values of different types (integer, float). msg = "Value #{inspect(value)} equals exclusive minimum value of #{inspect(minimum)}" [msg <> at_path(path) | acc] end defp format_error(%{minimum: minimum, exclusive_minimum: true, value: value}, path, acc) do msg = "Value #{inspect(value)} is less than minimum value of #{inspect(minimum)}" [msg <> at_path(path) | acc] end defp format_error(%{exclusive_minimum: minimum, value: minimum}, path, acc) do msg = "Value #{inspect(minimum)} equals exclusive minimum value of #{inspect(minimum)}" [msg <> at_path(path) | acc] end defp format_error(%{exclusive_minimum: minimum, value: value}, path, acc) do msg = "Value #{inspect(value)} is less than minimum value of #{inspect(minimum)}" [msg <> at_path(path) | acc] end defp format_error(%{minimum: minimum, value: value}, path, acc) do msg = "Value #{inspect(value)} is less than minimum value of #{inspect(minimum)}" [msg <> at_path(path) | acc] end defp format_error(%{maximum: maximum, exclusive_maximum: true, value: value}, path, acc) when maximum == value do # The guard is used to match values of different types (integer, float). msg = "Value #{inspect(value)} equals exclusive maximum value of #{inspect(maximum)}" [msg <> at_path(path) | acc] end defp format_error(%{maximum: maximum, exclusive_maximum: true, value: value}, path, acc) do msg = "Value #{inspect(value)} exceeds maximum value of #{inspect(maximum)}" [msg <> at_path(path) | acc] end defp format_error(%{exclusive_maximum: maximum, value: maximum}, path, acc) do msg = "Value #{inspect(maximum)} equals exclusive maximum value of #{inspect(maximum)}" [msg <> at_path(path) | acc] end defp format_error(%{exclusive_maximum: maximum, value: value}, path, acc) do msg = "Value #{inspect(value)} exceeds maximum value of #{inspect(maximum)}" [msg <> at_path(path) | acc] end defp format_error(%{maximum: maximum, value: value}, path, acc) do msg = "Value #{inspect(value)} exceeds maximum value of #{inspect(maximum)}" [msg <> at_path(path) | acc] end defp format_error(%{max_length: max, value: value}, path, acc) do msg = "Expected maximum length of #{inspect(max)}, got #{inspect(value)}" [msg <> at_path(path) | acc] end defp format_error(%{min_length: min, value: value}, path, acc) do msg = "Expected minimum length of #{inspect(min)}, got #{inspect(value)}" [msg <> at_path(path) | acc] end defp format_error(%{multiple_of: multiple_of, value: value}, path, acc) do msg = "Value #{inspect(value)} is not a multiple of #{inspect(multiple_of)}" [msg <> at_path(path) | acc] end defp format_error(%{enum: _enum, value: value}, path, acc) do msg = "Value #{inspect(value)} is not defined in enum" [msg <> at_path(path) | acc] end defp format_error(%{keys: keys, value: value}, path, acc) do msg = "Expected #{inspect(keys)} as key, got #{inspect(value)}" [msg <> at_path(path) | acc] end defp format_error(%{min_properties: min, value: value}, path, acc) do msg = "Expected at least #{inspect(min)} properties, got #{inspect(value)}" [msg <> at_path(path) | acc] end defp format_error(%{max_properties: max, value: value}, path, acc) do msg = "Expected at most #{inspect(max)} properties, got #{inspect(value)}" [msg <> at_path(path) | acc] end defp format_error(%{additional_properties: false}, path, acc) do msg = "Expected only defined properties, got key #{inspect(path)}." [msg | acc] end defp format_error(%{additional_items: false}, path, acc) do msg = "Unexpected additional item" [msg <> at_path(path) | acc] end defp format_error(%{format: format, value: value}, path, acc) do msg = "String #{inspect(value)} does not validate against format #{inspect(format)}" [msg <> at_path(path) | acc] end defp format_error(%{then: error}, path, acc) do msg = ["Schema for then does not match#{at_path(path)}"] error = error |> travers_errors([], &format_error/3, path: path) |> indent() Enum.concat([error, msg, acc]) end defp format_error(%{else: error}, path, acc) do msg = ["Schema for else does not match#{at_path(path)}"] error = error |> travers_errors([], &format_error/3, path: path) |> indent() Enum.concat([error, msg, acc]) end defp format_error(%{not: :ok, value: value}, path, acc) do msg = "Value is valid against schema from not, got #{inspect(value)}" [msg <> at_path(path) | acc] end defp format_error(%{contains: errors}, path, acc) do msg = ["No items match contains#{at_path(path)}"] errors = errors |> Enum.map(fn {index, reason} -> travers_errors(reason, [], &format_error/3, path: path ++ [index]) end) |> Enum.reverse() |> indent() Enum.concat([errors, msg, acc]) end defp format_error(%{any_of: errors}, path, acc) do msg = ["No match of any schema" <> at_path(path)] errors = errors |> Enum.flat_map(fn reason -> reason |> travers_errors([], &format_error/3, path: path) |> Enum.reverse() end) |> Enum.reverse() |> indent() Enum.concat([errors, msg, acc]) end defp format_error(%{all_of: errors}, path, acc) do msg = ["No match of all schema#{at_path(path)}"] errors = errors |> Enum.map(fn reason -> travers_errors(reason, [], &format_error/3, path: path) end) |> Enum.reverse() |> indent() Enum.concat([errors, msg, acc]) end defp format_error(%{one_of: {:error, errors}}, path, acc) do msg = ["No match of any schema#{at_path(path)}"] errors = errors |> Enum.map(fn reason -> travers_errors(reason, [], &format_error/3, path: path) end) |> Enum.reverse() |> indent() Enum.concat([errors, msg, acc]) end defp format_error(%{one_of: {:ok, success}}, path, acc) do msg = "More as one schema matches (indexes: #{inspect(success)})" [msg <> at_path(path) | acc] end defp format_error(%{required: required}, path, acc) do msg = "Required properties are missing: #{inspect(required)}" [msg <> at_path(path) | acc] end defp format_error(%{property_names: errors, value: _value}, path, acc) do msg = ["Invalid property names#{at_path(path)}"] errors = errors |> Enum.map(fn {key, reason} -> "#{inspect(key)} : #{format_error(reason, [], [])}" end) |> Enum.reverse() |> indent() Enum.concat([errors, msg, acc]) end defp format_error(%{dependencies: deps}, path, acc) do msg = deps |> Enum.reduce([], fn {key, reason}, acc when is_map(reason) -> sub_msg = reason |> format_error(path, []) |> Enum.reverse() |> indent() |> Enum.join("\n") ["Dependencies for #{inspect(key)} failed#{at_path(path)}\n#{sub_msg}" | acc] {key, reason}, acc -> [ "Dependencies for #{inspect(key)} failed#{at_path(path)}" <> " Missing required key #{inspect(reason)}." | acc ] end) |> Enum.reverse() |> Enum.join("\n") [msg | acc] end defp format_error(%{min_items: min, value: value}, path, acc) do msg = "Expected at least #{inspect(min)} items, got #{inspect(value)}" [msg <> at_path(path) | acc] end defp format_error(%{max_items: max, value: value}, path, acc) do msg = "Expected at most #{inspect(max)} items, got #{inspect(value)}" [msg <> at_path(path) | acc] end defp format_error(%{unique_items: true, value: value}, path, acc) do msg = "Expected unique items, got #{inspect(value)}" [msg <> at_path(path) | acc] end defp format_error(%{const: const, value: value}, path, acc) do msg = "Expected #{inspect(const)}, got #{inspect(value)}" [msg <> at_path(path) | acc] end defp format_error(%{pattern: pattern, value: value}, path, acc) do msg = "Pattern #{inspect(pattern)} does not match value #{inspect(value)}" [msg <> at_path(path) | acc] end defp format_error(%{module: module, value: value}, path, acc) do msg = "Expected #{inspect(module)}, got #{inspect(value)}" [msg <> at_path(path) | acc] end defp format_error(%{validator: validator, value: value}, path, acc) do msg = "Validator fails with #{inspect(validator)} for value #{inspect(value)}" [msg <> at_path(path) | acc] end defp format_error(%{type: type, value: value}, path, acc) do msg = "Expected #{inspect(type)}, got #{inspect(value)}" [msg <> at_path(path) | acc] end defp format_error(%{type: false}, path, acc) do msg = "Schema always fails validation" [msg <> at_path(path) | acc] end defp format_error(%{properties: _}, _path, acc), do: acc defp format_error(%{items: _}, _path, acc), do: acc defp format_error(_error, path, acc) do msg = "Unexpected error" [msg <> at_path(path) | acc] end defp at_path([]), do: "." defp at_path(path), do: ", at #{inspect(path)}." defp indent(list), do: Enum.map(list, fn str -> " #{str}" end) end
lib/xema/validation_error.ex
0.942374
0.755321
validation_error.ex
starcoder
defmodule Forage.Codec.Decoder do @moduledoc """ Functionality to decode a Phoenix `params` map into a form suitable for use with the query builders and pagination libraries """ alias Forage.Codec.Exceptions.InvalidAssocError alias Forage.Codec.Exceptions.InvalidFieldError alias Forage.Codec.Exceptions.InvalidSortDirectionError alias Forage.Codec.Exceptions.InvalidPaginationDataError alias Forage.ForagePlan @type schema() :: atom() @type assoc() :: {schema(), atom(), atom()} @doc """ Encodes a params map into a forage plan (`Forage.ForagerPlan`). """ def decode(params, schema) do filter = decode_filter(params, schema) sort = decode_sort(params, schema) pagination = decode_pagination(params, schema) %ForagePlan{filter: filter, sort: sort, pagination: pagination} end @doc """ Extract and decode the filter filters from the `params` map into a list of filters. ## Examples: TODO """ def decode_filter(%{"_filter" => filter_data}, schema) do decoded_fields = for {field_string, %{"op" => op, "val" => val}} <- filter_data do field_or_assoc = decode_field_or_assoc(field_string, schema) [field: field_or_assoc, operator: op, value: val] end Enum.sort(decoded_fields) end def decode_filter(_params, _schema), do: [] def decode_field_or_assoc(field_string, schema) do parts = String.split(field_string, ".") case parts do [field_name] -> field = safe_field_name_to_atom!(field_name, schema) {:simple, field} [local_name, remote_name] -> assoc = safe_field_names_to_assoc!(local_name, remote_name, schema) {:assoc, assoc} _ -> raise ArgumentError, "Invalid field name '#{field_string}'." end end @doc """ Extract and decode the sort fields from the `params` map into a keyword list. To be used with a schema. """ def decode_sort(%{"_sort" => sort}, schema) do # TODO: make this more robust decoded = for {field_name, %{"direction" => direction}} <- sort do field_atom = safe_field_name_to_atom!(field_name, schema) direction = decode_direction(direction) [field: field_atom, direction: direction] end # Sort the result so that the order is always the same Enum.sort(decoded) end def decode_sort(_params, _schema), do: [] @doc """ Extract and decode the sort fields from the `params` map into a keyword list. To be used without a schema. """ def decode_sort(%{"_sort" => sort}) do # TODO: make this more robust decoded = for {field_name, %{"direction" => direction}} <- sort do field_atom = safe_field_name_to_atom!(field_name) direction = decode_direction(direction) [field: field_atom, direction: direction] end # Sort the result so that the order is always the same Enum.sort(decoded) end def decode_sort(_params), do: [] @doc """ Extract and decode the pagination data from the `params` map into a keyword list. """ def decode_pagination(%{"_pagination" => pagination}, _schema) do decoded_after = case pagination["after"] do nil -> [] after_ -> [after: after_] end decoded_before = case pagination["before"] do nil -> [] before -> [before: before] end decoded_after ++ decoded_before end def decode_pagination(_params, _schema), do: [] @spec decode_direction(String.t() | nil) :: atom() | nil defp decode_direction("asc"), do: :asc defp decode_direction("desc"), do: :desc defp decode_direction(nil), do: nil defp decode_direction(value), do: raise(InvalidSortDirectionError, value) def pagination_data_to_integer!(value) do try do String.to_integer(value) rescue ArgumentError -> raise InvalidPaginationDataError, value end end @doc false @spec safe_field_names_to_assoc!(String.t(), String.t(), atom()) :: assoc() def safe_field_names_to_assoc!(local_name, remote_name, local_schema) do local = safe_assoc_name_to_atom!(local_name, local_schema) remote_schema = local_schema.__schema__(:association, local).related remote = safe_field_name_to_atom!(remote_name, remote_schema) {remote_schema, local, remote} end @doc false def remote_schema(local_name, local_schema) do local = safe_assoc_name_to_atom!(local_name, local_schema) remote_schema = local_schema.__schema__(:association, local).related remote_schema end @doc false def remote_schema_and_field_name_as_atom(local_name_as_string, local_schema) do local = safe_assoc_name_to_atom!(local_name_as_string, local_schema) remote_schema = local_schema.__schema__(:association, local).related {remote_schema, local} end @doc false @spec safe_assoc_name_to_atom!(String.t(), schema()) :: atom() def safe_assoc_name_to_atom!(assoc_name, schema) do # This function performs the dangerous job of turning a string into an atom. schema_associations = schema.__schema__(:associations) found = Enum.find(schema_associations, fn assoc -> assoc_name == Atom.to_string(assoc) end) case found do nil -> raise InvalidAssocError, {schema, assoc_name} _ -> found end end @doc false @spec safe_field_name_to_atom!(String.t()) :: atom() def safe_field_name_to_atom!(field_name) do String.to_existing_atom(field_name) end @doc false @spec safe_field_name_to_atom!(String.t(), schema()) :: atom() def safe_field_name_to_atom!(field_name, schema) do schema_fields = schema.__schema__(:fields) try do field_name_as_atom = String.to_existing_atom(field_name) case field_name_as_atom in schema_fields do true -> field_name_as_atom false -> raise InvalidFieldError, {schema, field_name} end rescue _e in ArgumentError -> raise InvalidFieldError, {schema, field_name} end end end
lib/forage/codec/decoder.ex
0.736969
0.445831
decoder.ex
starcoder
defmodule MrRoboto.Agent do @moduledoc """ The Agent fetches the `robots.txt` file from a given site. The agent is a very simple `GenServer` with the sole purpose of requesting the `robots.txt` file from a site. The agent responds to a single call `{:check, site}` where site is the URL of the site from which `robots.txt` should be fetched. The `:check` call returns one of three general responses: * `{:ok, body}` * `{:ok, :current}` * `{:error, error}` The Agent will only request the `robots.txt` file if it was last requested more than `MrRoboto.Agent.default_expiration` seconds ago. If the Agent receives a request for a robots file and it has been requested inside the cache window it responds with `{:ok, :current}`, otherwise it responds with `{:ok, body}` In the event of an error the Agent will return `{:error, error}` where `error` is the `HTTPoison` error. """ use GenServer @default_expiration 21600 def start_link do HTTPoison.start GenServer.start_link(__MODULE__, %{}, name: __MODULE__) end def handle_call({:check, site}, _from, state) do case update_robot(site, state) do {:ok, decision, new_history} -> {:reply, {:ok, decision}, new_history} {:error, error, state} -> {:reply, {:error, error}, state} end end def default_expiration do @default_expiration end def update_robot(site, history) do case Map.fetch(history, site) do {:ok, fetched_at} -> if (fetched_at + @default_expiration) > :erlang.system_time(:seconds) do {:ok, :current, history} else fetch_robots(site, history) end :error -> fetch_robots(site, history) end end def fetch_robots(site, history) do case HTTPoison.get(site <> "/robots.txt") do {:ok, response} -> {:ok, response.body, update_timestamp(site, history)} {:error, reason} -> {:error, reason, history} end end def update_timestamp(site, history) do Map.put(history, site, :erlang.system_time(:seconds)) end end
lib/mr_roboto/agent.ex
0.742608
0.702683
agent.ex
starcoder
defmodule Coxir.Struct.User do @moduledoc """ Defines methods used to interact with Discord users. Refer to [this](https://discordapp.com/developers/docs/resources/user#user-object) for a list of fields and a broader documentation. In addition, the following fields are also embedded. - `voice` - a channel object - `avatar_url` - an URL for the avatar """ @type user :: String.t | map use Coxir.Struct alias Coxir.Struct.{Channel} def pretty(struct) do struct |> replace(:voice_id, &Channel.get/1) |> put(:avatar_url, get_avatar(struct)) end def get(user \\ :local) def get(%{id: id}), do: get(id) def get(:local) do get_id() |> get end def get(user) do super(user) |> case do nil -> API.request(:get, "users/#{user}") |> pretty user -> user end end @doc """ Computes the local user's ID. Returns a snowflake. """ @spec get_id() :: String.t def get_id do Coxir.token() |> String.split(".") |> Kernel.hd |> Base.decode64! end @doc """ Modifies the local user. Returns an user object upon success or a map containing error information. #### Params Must be an enumerable with the fields listed below. - `username` - the user's username - `avatar` - the user's avatar Refer to [this](https://discordapp.com/developers/docs/resources/user#modify-current-user) for a broader explanation on the fields and their defaults. """ @spec edit(Enum.t) :: map def edit(params) do API.request(:patch, "users/@me", params) end @doc """ Changes the username of the local user. Returns an user object upon success or a map containing error information. """ @spec set_username(String.t) :: map def set_username(name), do: edit(username: name) @doc """ Changes the avatar of the local user. Returns an user object upon success or a map containing error information. #### Avatar Either a proper data URI scheme or the path of an image's file. Refer to [this](https://discordapp.com/developers/docs/resources/user#avatar-data) for a broader explanation. """ @spec set_avatar(String.t) :: map def set_avatar(avatar) do cond do String.starts_with?(avatar, "data:image") -> edit(avatar: avatar) true -> avatar |> File.read |> case do {:ok, content} -> content = content |> Base.encode64 scheme = "data:;base64,#{content}" edit(avatar: scheme) {:error, reason} -> reason = reason |> :file.format_error |> List.to_string %{error: reason} end end end @doc """ Fetches a list of connections for the local user. Refer to [this](https://discordapp.com/developers/docs/resources/user#get-user-connections) for more information. """ @spec get_connections() :: list | map def get_connections do API.request(:get, "users/@me/connections") end @doc """ Fetches a list of guilds for the local user. Returns a list of partial guild objects or a map containing error information. #### Query Must be a keyword list with the fields listed below. - `before` - get guilds before this guild ID - `after` - get guilds after this guild ID - `max` - max number of guilds to return Refer to [this](https://discordapp.com/developers/docs/resources/user#get-current-user-guilds) for a broader explanation on the fields and their defaults. """ @spec get_guilds(Keyword.t) :: list | map def get_guilds(query \\ []) do API.request(:get, "users/@me/guilds", "", params: query) end @doc """ Creates a DM channel with a given user. Returns a channel object upon success or a map containing error information. """ @spec create_dm(user) :: map def create_dm(%{id: id}), do: create_dm(id) def create_dm(recipient) do API.request(:post, "users/@me/channels", %{recipient_id: recipient}) |> Channel.pretty end @doc """ Creates a group DM channel. Returns a channel object upon success or a map containing error information. #### Params Must be an enumerable with the fields listed below. - `access_tokens` - access tokens of users - `nicks` - a map of user ids and their respective nicknames Refer to [this](https://discordapp.com/developers/docs/resources/user#create-group-dm) for a broader explanation on the fields and their defaults. """ @spec create_group(Enum.t) :: map def create_group(params) do API.request(:post, "users/@me/channels", params) |> Channel.pretty end @doc """ Fetches a list of DM channels for the local user. Returns a list of channel objects upon success or a map containing error information. """ @spec get_dms() :: list def get_dms do API.request(:get, "users/@me/channels") |> case do list when is_list(list) -> for channel <- list do Channel.pretty(channel) end error -> error end end @doc """ Sends a direct message to a given user. Refer to `Coxir.Struct.Channel.send_message/2` for more information. """ @spec send_message(user, String.t | Enum.t) :: map def send_message(%{id: id}, content), do: send_message(id, content) def send_message(user, content) do user |> create_dm |> case do %{id: channel} -> Channel.send_message(channel, content) other -> other end end @doc """ Computes the URL for a given user's avatar. Returns a string upon success or a map containing error information. """ @spec get_avatar(user) :: String.t | map def get_avatar(id) when is_binary(id) do get(id) |> case do %{id: _id} = user -> get_avatar(user) other -> other end end def get_avatar(%{avatar_url: value}), do: value def get_avatar(%{avatar: nil, discriminator: discriminator}) do index = discriminator |> String.to_integer |> rem(5) "https://cdn.discordapp.com/embed/avatars/#{index}.png" end def get_avatar(%{avatar: avatar, id: id}) do extension = avatar |> String.starts_with?("a_") |> case do true -> "gif" false -> "png" end "https://cdn.discordapp.com/avatars/#{id}/#{avatar}.#{extension}" end def get_avatar(_other), do: nil end
lib/coxir/struct/user.ex
0.871187
0.418103
user.ex
starcoder
defmodule CircuitsLED.GPIOServer do use GenServer alias Circuits.GPIO def start_link(pin) do GenServer.start_link(__MODULE__, pin, name: pin_to_atom(pin)) end def on(pid) do GenServer.call(pid, :on) end def off(pid) do GenServer.call(pid, :off) end def blink(pid, duration, count) do GenServer.call(pid, {:blink, duration, count}) end def toggle(pid) do GenServer.call(pid, :toggle) end @impl true def init(pin) do {:ok, gpio} = Circuits.GPIO.open(pin, :output) {:ok, %{gpio: gpio, blink_ref: nil, status: :off, count: nil, duration: 0}} end @impl true def handle_call(:on, _from, state) do GPIO.write(state.gpio, 1) state = %{state | status: :on, blink_ref: nil} {:reply, :on, state} end @impl true def handle_call(:off, _from, state) do GPIO.write(state.gpio, 0) state = %{state | status: :off, blink_ref: nil} {:reply, :off, state} end @impl true def handle_call(:toggle, _from, state = %{status: :off}) do GPIO.write(state.gpio, 1) state = %{state | status: :on, blink_ref: nil} {:reply, :on, state} end @impl true def handle_call(:toggle, _from, state = %{status: :on}) do GPIO.write(state.gpio, 0) state = %{state | status: :off, blink_ref: nil} {:reply, :off, state} end @impl true def handle_call({:blink, duration, count}, _from, state) do GPIO.write(state.gpio, 1) blink_ref = make_ref() Process.send_after(self(), {:blink_tick, blink_ref}, duration) state = %{state | status: :on, blink_ref: blink_ref, count: count - 1, duration: duration} {:reply, :ok, state} end @impl true def handle_info({:blink_tick, blink_ref}, state = %{blink_ref: blink_ref, count: 0}) do GPIO.write(state.gpio, 0) {:noreply, %{state | blink_ref: nil}} end @impl true def handle_info({:blink_tick, blink_ref}, state = %{blink_ref: blink_ref, status: :on}) do GPIO.write(state.gpio, 0) Process.send_after(self(), {:blink_tick, blink_ref}, state.duration) state = %{state | status: :off} {:noreply, state} end @impl true def handle_info({:blink_tick, blink_ref}, state = %{blink_ref: blink_ref, status: :off}) do GPIO.write(state.gpio, 1) Process.send_after(self(), {:blink_tick, blink_ref}, state.duration) state = %{state | status: :on, count: state.count - 1} {:noreply, state} end @impl true def handle_info({:blink_tick, _blink_ref}, state) do {:noreply, state} end defp pin_to_atom(pin) do pin |> Integer.to_string() |> String.to_atom() end end
lib/circuits_led/gpio_led_server.ex
0.721253
0.448789
gpio_led_server.ex
starcoder
defmodule Vex do def valid?(data) do valid?(data, Vex.Extract.settings(data)) end def valid?(data, settings) do errors(data, settings) |> length == 0 end def validate(data) do validate(data, Vex.Extract.settings(data)) end def validate(data, settings) do case errors(data, settings) do errors when length(errors) > 0 -> {:error, errors} _ -> {:ok, data} end end def errors(data) do errors(data, Vex.Extract.settings(data)) end def errors(data, settings) do Enum.filter results(data, settings), &match?({:error, _, _, _}, &1) end def results(data) do results(data, Vex.Extract.settings(data)) end def results(data, settings) do Enum.map(settings, fn ({attribute, validations}) -> validations = case is_function(validations) do true -> [by: validations] false -> validations end Enum.map(validations, fn ({name, options}) -> result(data, attribute, name, options) end) end) |> List.flatten end defp result(data, attribute, name, options) do v = validator(name) if Vex.Validator.validate?(data, options) do result = extract(data, attribute, name) |> v.validate(data, options) case result do {:error, message} -> {:error, attribute, name, message} :ok -> {:ok, attribute, name} _ -> raise "'#{name}'' validator should return :ok or {:error, message}" end else {:not_applicable, attribute, name} end end @doc """ Lookup a validator from configured sources ## Examples iex> Vex.validator(:presence) Vex.Validators.Presence iex> Vex.validator(:exclusion) Vex.Validators.Exclusion """ def validator(name) do case name |> validator(sources()) do nil -> raise Vex.InvalidValidatorError, validator: name, sources: sources() found -> found end end @doc """ Lookup a validator from given sources ## Examples iex> Vex.validator(:presence, [[presence: :presence_stub]]) :presence_stub iex> Vex.validator(:exclusion, [Vex.Validators]) Vex.Validators.Exclusion iex> Vex.validator(:presence, [Vex.Validators, [presence: :presence_stub]]) Vex.Validators.Presence iex> Vex.validator(:presence, [[presence: :presence_stub], Vex.Validators]) :presence_stub """ def validator(name, sources) do Enum.find_value sources, fn (source) -> Vex.Validator.Source.lookup(source, name) end end defp sources do case Application.get_env(:vex, :sources) do nil -> [Vex.Validators] sources -> sources end end defp extract(data, attribute, :confirmation) do [attribute, String.to_atom("#{attribute}_confirmation")] |> Enum.map(fn (attr) -> Vex.Extract.attribute(data, attr) end) end defp extract(data, attribute, _name) do Vex.Extract.attribute(data, attribute) end end
lib/vex.ex
0.73077
0.402744
vex.ex
starcoder
defmodule ExDadata.Address do @moduledoc """ Entry point for address DaData API. For more information see [docs](https://dadata.ru/api/#address-clean). """ alias __MODULE__.{GeocodeAddress, GeolocateAddress, SuggestAddress} alias ExDadata.Client alias ExDadata.HTTPAdapter.Response @suggest_address_url "https://suggestions.dadata.ru/suggestions/api/4_1/rs/suggest/address" @doc """ Search address by any part of an address from the region to the house. Also, you can search by zip-code. See [documentation](https://dadata.ru/api/suggest/address/) for more info. ## Example ExDadata.Address.suggest_address(client, %{query: "москва хабар"}) """ def suggest_address(client, data) do with {:ok, body} <- do_suggest_address(client, data) do {:ok, SuggestAddress.new!(body)} end end defp do_suggest_address(client, data) do headers = Client.to_headers(client) ++ [ {"Accept", "application/json"}, {"Content-Type", "application/json"} ] adapter = Client.http_adapter(client) case adapter.request(client, :post, @suggest_address_url, headers, data, []) do {:ok, %Response{status: 200, body: response}} -> {:ok, response} {:ok, resp} -> {:error, resp} {:error, _} = error -> error end end @geocode_address_url "https://cleaner.dadata.ru/api/v1/clean/address" @doc """ Determine coordinates for the address. See [documentation](https://dadata.ru/api/geocode/) for more information. ## Example ExDadata.Address.geocode_address(client, ["мск сухонска 11/-89"]) """ def geocode_address(client, data) do with {:ok, body} <- do_geocode_address(client, data) do {:ok, GeocodeAddress.new!(body)} end end defp do_geocode_address(client, data) do headers = Client.to_headers(client) adapter = Client.http_adapter(client) case adapter.request(client, :post, @geocode_address_url, headers, data, []) do {:ok, %Response{status: 200, body: response}} -> {:ok, response} {:ok, resp} -> {:error, resp} {:error, _} = error -> error end end @geolocate_address_url "https://suggestions.dadata.ru/suggestions/api/4_1/rs/geolocate/address" @doc """ Search addresses which are close to the coordinates. See [documentation](https://dadata.ru/api/geolocate/) for more info. ## Example ExDadata.Address.geolocate_address(client, %{lat: 55.601983, lon: 37.359486}) """ def geolocate_address(client, data) do with {:ok, body} <- do_geolocate_address(client, data) do {:ok, GeolocateAddress.new!(body)} end end defp do_geolocate_address(client, data) do headers = Client.to_headers(client) ++ [ {"Accept", "application/json"}, {"Content-Type", "application/json"} ] adapter = Client.http_adapter(client) url = compose_geolocate_url(data) case adapter.request(client, :get, url, headers, %{}, []) do {:ok, %Response{status: 200, body: response}} -> {:ok, response} {:ok, resp} -> {:error, resp} {:error, _} = error -> error end end defp compose_geolocate_url(data) do uri = %URI{ URI.parse(@geolocate_address_url) | query: URI.encode_query(data) } URI.to_string(uri) end end
lib/ex_dadata/address.ex
0.838382
0.650776
address.ex
starcoder
defmodule Mechanize.Page.Element do @moduledoc """ The HMTL element. This module provides functions to manipulate and extract information from HMTL element nodes. ## Public fields * `name` - name of the HTML tag. * `attrs` - List of the element attributes. * `text` - Inner text of the element. * `page` - page where this element was extracted. ## Private fields Fields reserved for interal use of the library and it is not recommended to access it directly. * `parser_node` - internal data used by the parser. * `parser` - parser used to parse this element. """ alias Mechanize.Page.Elementable defstruct [:name, :attrs, :parser_node, :text, :parser, :page] @type attributes :: [{String.t(), String.t()}] @typedoc """ The HTML Element struct. """ @type t :: %__MODULE__{ name: String.t(), attrs: attributes(), parser_node: Mechanize.HTMLParser.parser_node(), text: String.t(), parser: module(), page: Page.t() } @doc """ Returns the page where this element was extracted. Element may be any struct implementing `Mechanize.Page.Elementable` protocol. """ @spec get_page(any()) :: Page.t() def get_page(elementable), do: Elementable.element(elementable).page @doc """ Returns the inner text from the HTML element. Text from elements without inner text are extracted as empty strings by the parser. It means that this function will return an empty string in case of the element does not have inner text. Element may be any struct implementing `Mechanize.Page.Elementable` protocol. """ @spec text(any()) :: String.t() def text(elementable), do: Elementable.element(elementable).text @doc """ Returns the HTML tag name of the element. For instance, it will return "a" and "area" for hyperlinks, "img" for images, etc. Element may be any struct implementing `Mechanize.Page.Elementable` protocol. ## Example ``` iex> Element.name(image) "img" ``` """ @spec name(any) :: String.t() def name(elementable) do elementable |> Elementable.element() |> Map.get(:name) |> normalize_value() end @doc """ Returns a list containing all attributes from a HMTL element and its values. In case element doest have any attributes, an empty list is returned. Element may be any struct implementing `Mechanize.Page.Elementable` protocol. ## Example ``` iex> Element.attrs(element) [{"href", "/home"}, {"rel", "nofollow"}] ``` """ @spec attrs(any) :: attributes() def attrs(el), do: Elementable.element(el).attrs @doc """ Returns true if attribute is present, otherwise false. Element may be any struct implementing `Mechanize.Page.Elementable` protocol. ## Example ``` iex> Element.attr_present?(checkbox, :selected) true ``` """ @spec attr_present?(any, atom()) :: boolean() def attr_present?(element, attr_name), do: attr(element, attr_name) != nil @doc """ Returns attribute value of a given element. This functions accepts opts: * `default` - Returns a default value in case of an attribute is not present. Default: `nil`. * `normalize` - Returns the value of the attribute downcased and without dangling spaces. ## Examples ``` iex> Element.attr(element, :href) "/home" ``` """ @spec attr(any, atom) :: any def attr(element, attr_name, opts \\ []) do opts = [default: nil, normalize: false] |> Keyword.merge(opts) element |> attrs() |> List.keyfind(Atom.to_string(attr_name), 0, {nil, opts[:default]}) |> elem(1) |> maybe_normalize_value(opts[:normalize]) end defp maybe_normalize_value(value, false) do value end defp maybe_normalize_value(nil, _) do nil end defp maybe_normalize_value(value, true) do normalize_value(value) end defp normalize_value(value) do value |> String.downcase() |> String.trim() end end defimpl Mechanize.Page.Elementable, for: Mechanize.Page.Element do def element(e), do: e end
lib/mechanize/page/element.ex
0.918859
0.887644
element.ex
starcoder
defmodule Record do @moduledoc """ Module to work with, define, and import records. Records are simply tuples where the first element is an atom: iex> Record.is_record {User, "john", 27} true This module provides conveniences for working with records at compilation time, where compile-time field names are used to manipulate the tuples, providing fast operations on top of the tuples' compact structure. In Elixir, records are used mostly in two situations: 1. to work with short, internal data 2. to interface with Erlang records The macros `defrecord/3` and `defrecordp/3` can be used to create records while `extract/2` and `extract_all/1` can be used to extract records from Erlang files. ## Types Types can be defined for tuples with the `record/2` macro (only available in typespecs). This macro will expand to a tuple as seen in the example below: defmodule MyModule do require Record Record.defrecord :user, name: "john", age: 25 @type user :: record(:user, name: String.t, age: integer) # expands to: "@type user :: {:user, String.t, integer}" end """ @doc """ Extracts record information from an Erlang file. Returns a quoted expression containing the fields as a list of tuples. `name`, which is the name of the extracted record, is expected to be an atom *at compile time*. ## Options This function accepts the following options, which are exclusive to each other (i.e., only one of them can be used in the same call): * `:from` - (binary representing a path to a file) path to the Erlang file that contains the record definition to extract; with this option, this function uses the same path lookup used by the `-include` attribute used in Erlang modules. * `:from_lib` - (binary representing a path to a file) path to the Erlang file that contains the record definition to extract; with this option, this function uses the same path lookup used by the `-include_lib` attribute used in Erlang modules. These options are expected to be literals (including the binary values) at compile time. ## Examples iex> Record.extract(:file_info, from_lib: "kernel/include/file.hrl") [size: :undefined, type: :undefined, access: :undefined, atime: :undefined, mtime: :undefined, ctime: :undefined, mode: :undefined, links: :undefined, major_device: :undefined, minor_device: :undefined, inode: :undefined, uid: :undefined, gid: :undefined] """ @spec extract(name :: atom, keyword) :: keyword def extract(name, opts) when is_atom(name) and is_list(opts) do Record.Extractor.extract(name, opts) end @doc """ Extracts all records information from an Erlang file. Returns a keyword list of `{record_name, fields}` tuples where `record_name` is the name of an extracted record and `fields` is a list of `{field, value}` tuples representing the fields for that record. ## Options This function accepts the following options, which are exclusive to each other (i.e., only one of them can be used in the same call): * `:from` - (binary representing a path to a file) path to the Erlang file that contains the record definitions to extract; with this option, this function uses the same path lookup used by the `-include` attribute used in Erlang modules. * `:from_lib` - (binary representing a path to a file) path to the Erlang file that contains the record definitions to extract; with this option, this function uses the same path lookup used by the `-include_lib` attribute used in Erlang modules. These options are expected to be literals (including the binary values) at compile time. """ @spec extract_all(keyword) :: [{name :: atom, keyword}] def extract_all(opts) when is_list(opts) do Record.Extractor.extract_all(opts) end @doc """ Checks if the given `data` is a record of kind `kind`. This is implemented as a macro so it can be used in guard clauses. ## Examples iex> record = {User, "john", 27} iex> Record.is_record(record, User) true """ defmacro is_record(data, kind) do case Macro.Env.in_guard?(__CALLER__) do true -> quote do is_atom(unquote(kind)) and is_tuple(unquote(data)) and tuple_size(unquote(data)) > 0 and elem(unquote(data), 0) == unquote(kind) end false -> quote do result = unquote(data) kind = unquote(kind) is_atom(kind) and is_tuple(result) and tuple_size(result) > 0 and elem(result, 0) == kind end end end @doc """ Checks if the given `data` is a record. This is implemented as a macro so it can be used in guard clauses. ## Examples iex> record = {User, "john", 27} iex> Record.is_record(record) true iex> tuple = {} iex> Record.is_record(tuple) false """ defmacro is_record(data) do case Macro.Env.in_guard?(__CALLER__) do true -> quote do is_tuple(unquote(data)) and tuple_size(unquote(data)) > 0 and is_atom(elem(unquote(data), 0)) end false -> quote do result = unquote(data) is_tuple(result) and tuple_size(result) > 0 and is_atom(elem(result, 0)) end end end @doc """ Defines a set of macros to create, access, and pattern match on a record. The name of the generated macros will be `name` (which has to be an atom). `tag` is also an atom and is used as the "tag" for the record (i.e., the first element of the record tuple); by default (if `nil`), it's the same as `name`. `kv` is a keyword list of `name: default_value` fields for the new record. The following macros are generated: * `name/0` to create a new record with default values for all fields * `name/1` to create a new record with the given fields and values, to get the zero-based index of the given field in a record or to convert the given record to a keyword list * `name/2` to update an existing record with the given fields and values or to access a given field in a given record All these macros are public macros (as defined by `defmacro`). See the "Examples" section for examples on how to use these macros. ## Examples defmodule User do require Record Record.defrecord :user, [name: "meg", age: "25"] end In the example above, a set of macros named `user` but with different arities will be defined to manipulate the underlying record. # Import the module to make the user macros locally available import User # To create records record = user() #=> {:user, "meg", 25} record = user(age: 26) #=> {:user, "meg", 26} # To get a field from the record user(record, :name) #=> "meg" # To update the record user(record, age: 26) #=> {:user, "meg", 26} # To get the zero-based index of the field in record tuple # (index 0 is occupied by the record "tag") user(:name) #=> 1 # Convert a record to a keyword list user(record) #=> [name: "meg", age: 26] The generated macros can also be used in order to pattern match on records and to bind variables during the match: record = user() #=> {:user, "meg", 25} user(name: name) = record name #=> "meg" By default, Elixir uses the record name as the first element of the tuple (the "tag"). However, a different tag can be specified when defining a record, as in the following example, in which we use `Customer` as the second argument of `defrecord/3`: defmodule User do require Record Record.defrecord :user, Customer, name: nil end require User User.user() #=> {Customer, nil} ## Defining extracted records with anonymous functions in the values If a record defines an anonymous function in the default values, an `ArgumentError` will be raised. This can happen unintentionally when defining a record after extracting it from an Erlang library that uses anonymous functions for defaults. Record.defrecord :my_rec, Record.extract(...) #=> ** (ArgumentError) invalid value for record field fun_field, #=> cannot escape #Function<12.90072148/2 in :erl_eval.expr/5>. To work around this error, redefine the field with your own &M.f/a function, like so: defmodule MyRec do require Record Record.defrecord :my_rec, Record.extract(...) |> Keyword.merge(fun_field: &__MODULE__.foo/2) def foo(bar, baz), do: IO.inspect({bar, baz}) end """ defmacro defrecord(name, tag \\ nil, kv) do quote bind_quoted: [name: name, tag: tag, kv: kv] do tag = tag || name fields = Record.__fields__(:defrecord, kv) defmacro(unquote(name)(args \\ [])) do Record.__access__(unquote(tag), unquote(fields), args, __CALLER__) end defmacro(unquote(name)(record, args)) do Record.__access__(unquote(tag), unquote(fields), record, args, __CALLER__) end end end @doc """ Same as `defrecord/3` but generates private macros. """ defmacro defrecordp(name, tag \\ nil, kv) do quote bind_quoted: [name: name, tag: tag, kv: kv] do tag = tag || name fields = Record.__fields__(:defrecordp, kv) defmacrop(unquote(name)(args \\ [])) do Record.__access__(unquote(tag), unquote(fields), args, __CALLER__) end defmacrop(unquote(name)(record, args)) do Record.__access__(unquote(tag), unquote(fields), record, args, __CALLER__) end end end # Normalizes of record fields to have default values. @doc false def __fields__(type, fields) do :lists.map(fn {key, value} when is_atom(key) -> try do Macro.escape(value) rescue e in [ArgumentError] -> raise ArgumentError, "invalid value for record field #{key}, " <> Exception.message(e) else value -> {key, value} end key when is_atom(key) -> {key, nil} other -> raise ArgumentError, "#{type} fields must be atoms, got: #{inspect other}" end, fields) end # Callback invoked from record/0 and record/1 macros. @doc false def __access__(tag, fields, args, caller) do cond do is_atom(args) -> index(tag, fields, args) Keyword.keyword?(args) -> create(tag, fields, args, caller) true -> fields = Macro.escape(fields) case Macro.expand(args, caller) do {:{}, _, [^tag | list]} when length(list) == length(fields) -> record = List.to_tuple([tag | list]) Record.__keyword__(tag, fields, record) {^tag, arg} when length(fields) == 1 -> Record.__keyword__(tag, fields, {tag, arg}) _ -> quote do: Record.__keyword__(unquote(tag), unquote(fields), unquote(args)) end end end # Callback invoked from the record/2 macro. @doc false def __access__(tag, fields, record, args, caller) do cond do is_atom(args) -> get(tag, fields, record, args) Keyword.keyword?(args) -> update(tag, fields, record, args, caller) true -> msg = "expected arguments to be a compile time atom or a keyword list, got: #{Macro.to_string args}" raise ArgumentError, msg end end # Gets the index of field. defp index(tag, fields, field) do if index = find_index(fields, field, 0) do index - 1 # Convert to Elixir index else raise ArgumentError, "record #{inspect tag} does not have the key: #{inspect field}" end end # Creates a new record with the given default fields and keyword values. defp create(tag, fields, keyword, caller) do in_match = Macro.Env.in_match?(caller) keyword = apply_underscore(fields, keyword) {match, remaining} = Enum.map_reduce(fields, keyword, fn({field, default}, each_keyword) -> new_fields = case Keyword.fetch(each_keyword, field) do {:ok, value} -> value :error when in_match -> {:_, [], nil} :error -> Macro.escape(default) end {new_fields, Keyword.delete(each_keyword, field)} end) case remaining do [] -> {:{}, [], [tag | match]} _ -> keys = for {key, _} <- remaining, do: key raise ArgumentError, "record #{inspect tag} does not have the key: #{inspect hd(keys)}" end end # Updates a record given by var with the given keyword. defp update(tag, fields, var, keyword, caller) do if Macro.Env.in_match?(caller) do raise ArgumentError, "cannot invoke update style macro inside match" end keyword = apply_underscore(fields, keyword) Enum.reduce keyword, var, fn({key, value}, acc) -> index = find_index(fields, key, 0) if index do quote do :erlang.setelement(unquote(index), unquote(acc), unquote(value)) end else raise ArgumentError, "record #{inspect tag} does not have the key: #{inspect key}" end end end # Gets a record key from the given var. defp get(tag, fields, var, key) do index = find_index(fields, key, 0) if index do quote do :erlang.element(unquote(index), unquote(var)) end else raise ArgumentError, "record #{inspect tag} does not have the key: #{inspect key}" end end defp find_index([{k, _} | _], k, i), do: i + 2 defp find_index([{_, _} | t], k, i), do: find_index(t, k, i + 1) defp find_index([], _k, _i), do: nil # Returns a keyword list of the record @doc false def __keyword__(tag, fields, record) do if is_record(record, tag) do [_tag | values] = Tuple.to_list(record) case join_keyword(fields, values, []) do kv when is_list(kv) -> kv expected_fields -> msg = "expected argument to be a #{inspect tag} record with #{expected_fields} fields, got: #{inspect record}" raise ArgumentError, msg end else msg = "expected argument to be a literal atom, literal keyword or a #{inspect tag} record, got runtime: #{inspect record}" raise ArgumentError, msg end end # Returns a keyword list, or expected number of fields on size mismatch defp join_keyword([{field, _default} | fields], [value | values], acc), do: join_keyword(fields, values, [{field, value} | acc]) defp join_keyword([], [], acc), do: :lists.reverse(acc) defp join_keyword(rest_fields, _rest_values, acc), do: length(acc) + length(rest_fields) # expected fields defp apply_underscore(fields, keyword) do case Keyword.fetch(keyword, :_) do {:ok, default} -> fields |> Enum.map(fn {k, _} -> {k, default} end) |> Keyword.merge(keyword) |> Keyword.delete(:_) :error -> keyword end end end
lib/elixir/lib/record.ex
0.891993
0.794704
record.ex
starcoder
defmodule Jason do @moduledoc """ A blazing fast JSON parser and generator in pure Elixir. """ alias Jason.{Encode, Decoder, DecodeError, EncodeError, Formatter} @type escape :: :json | :unicode_safe | :html_safe | :javascript_safe @type maps :: :naive | :strict @type encode_opt :: {:escape, escape} | {:maps, maps} | {:pretty, true | Formatter.opts()} @type keys :: :atoms | :atoms! | :strings | :copy | (String.t() -> term) @type strings :: :reference | :copy @type decode_opt :: {:keys, keys} | {:strings, strings} @doc """ Parses a JSON value from `input` iodata. ## Options * `:keys` - controls how keys in objects are decoded. Possible values are: * `:strings` (default) - decodes keys as binary strings, * `:atoms` - keys are converted to atoms using `String.to_atom/1`, * `:atoms!` - keys are converted to atoms using `String.to_existing_atom/1`, * custom decoder - additionally a function accepting a string and returning a key is accepted. * `:strings` - controls how strings (including keys) are decoded. Possible values are: * `:reference` (default) - when possible tries to create a sub-binary into the original * `:copy` - always copies the strings. This option is especially useful when parts of the decoded data will be stored for a long time (in ets or some process) to avoid keeping the reference to the original data. ## Decoding keys to atoms The `:atoms` option uses the `String.to_atom/1` call that can create atoms at runtime. Since the atoms are not garbage collected, this can pose a DoS attack vector when used on user-controlled data. ## Examples iex> Jason.decode("{}") {:ok, %{}} iex> Jason.decode("invalid") {:error, %Jason.DecodeError{data: "invalid", position: 0, token: nil}} """ @spec decode(iodata, [decode_opt]) :: {:ok, term} | {:error, DecodeError.t()} def decode(input, opts \\ []) do input = IO.iodata_to_binary(input) Decoder.parse(input, format_decode_opts(opts)) end @doc """ Parses a JSON value from `input` iodata. Similar to `decode/2` except it will unwrap the error tuple and raise in case of errors. ## Examples iex> Jason.decode!("{}") %{} iex> Jason.decode!("invalid") ** (Jason.DecodeError) unexpected byte at position 0: 0x69 ('i') """ @spec decode!(iodata, [decode_opt]) :: term | no_return def decode!(input, opts \\ []) do case decode(input, opts) do {:ok, result} -> result {:error, error} -> raise error end end @doc """ Generates JSON corresponding to `input`. The generation is controlled by the `Jason.Encoder` protocol, please refer to the module to read more on how to define the protocol for custom data types. ## Options * `:escape` - controls how strings are encoded. Possible values are: * `:json` (default) - the regular JSON escaping as defined by RFC 7159. * `:javascript_safe` - additionally escapes the LINE SEPARATOR (U+2028) and PARAGRAPH SEPARATOR (U+2029) characters to make the produced JSON valid JavaSciprt. * `:html_safe` - similar to `:javascript`, but also escapes the `/` caracter to prevent XSS. * `:unicode_safe` - escapes all non-ascii characters. * `:maps` - controls how maps are encoded. Possible values are: * `:strict` - checks the encoded map for duplicate keys and raises if they appear. For example `%{:foo => 1, "foo" => 2}` would be rejected, since both keys would be encoded to the string `"foo"`. * `:naive` (default) - does not perform the check. * `:pretty` - controls pretty printing of the output. Possible values are: * `true` to pretty print with default configuration * a keyword of options as specified by `Jason.Formatter.pretty_print/2`. ## Examples iex> Jason.encode(%{a: 1}) {:ok, ~S|{"a":1}|} iex> Jason.encode("\\xFF") {:error, %Jason.EncodeError{message: "invalid byte 0xFF in <<255>>"}} """ @spec encode(term, [encode_opt]) :: {:ok, String.t()} | {:error, EncodeError.t() | Exception.t()} def encode(input, opts \\ []) do case do_encode(input, format_encode_opts(opts)) do {:ok, result} -> {:ok, IO.iodata_to_binary(result)} {:error, error} -> {:error, error} end end @doc """ Generates JSON corresponding to `input`. Similar to `encode/1` except it will unwrap the error tuple and raise in case of errors. ## Examples iex> Jason.encode!(%{a: 1}) ~S|{"a":1}| iex> Jason.encode!("\\xFF") ** (Jason.EncodeError) invalid byte 0xFF in <<255>> """ @spec encode!(term, [encode_opt]) :: String.t() | no_return def encode!(input, opts \\ []) do case do_encode(input, format_encode_opts(opts)) do {:ok, result} -> IO.iodata_to_binary(result) {:error, error} -> raise error end end @doc """ Generates JSON corresponding to `input` and returns iodata. This function should be preferred to `encode/2`, if the generated JSON will be handed over to one of the IO functions or sent over the socket. The Erlang runtime is able to leverage vectorised writes and avoid allocating a continuous buffer for the whole resulting string, lowering memory use and increasing performance. ## Examples iex> {:ok, iodata} = Jason.encode_to_iodata(%{a: 1}) iex> IO.iodata_to_binary(iodata) ~S|{"a":1}| iex> Jason.encode_to_iodata("\\xFF") {:error, %Jason.EncodeError{message: "invalid byte 0xFF in <<255>>"}} """ @spec encode_to_iodata(term, [encode_opt]) :: {:ok, iodata} | {:error, EncodeError.t() | Exception.t()} def encode_to_iodata(input, opts \\ []) do do_encode(input, format_encode_opts(opts)) end @doc """ Generates JSON corresponding to `input` and returns iodata. Similar to `encode_to_iodata/1` except it will unwrap the error tuple and raise in case of errors. ## Examples iex> iodata = Jason.encode_to_iodata!(%{a: 1}) iex> IO.iodata_to_binary(iodata) ~S|{"a":1}| iex> Jason.encode_to_iodata!("\\xFF") ** (Jason.EncodeError) invalid byte 0xFF in <<255>> """ @spec encode_to_iodata!(term, [encode_opt]) :: iodata | no_return def encode_to_iodata!(input, opts \\ []) do case do_encode(input, format_encode_opts(opts)) do {:ok, result} -> result {:error, error} -> raise error end end defp do_encode(input, %{pretty: true} = opts) do case Encode.encode(input, opts) do {:ok, encoded} -> {:ok, Formatter.pretty_print_to_iodata(encoded)} other -> other end end defp do_encode(input, %{pretty: pretty} = opts) do case Encode.encode(input, opts) do {:ok, encoded} -> {:ok, Formatter.pretty_print_to_iodata(encoded, pretty)} other -> other end end defp do_encode(input, opts) do Encode.encode(input, opts) end defp format_encode_opts(opts) do Enum.into(opts, %{escape: :json, maps: :naive}) end defp format_decode_opts(opts) do Enum.into(opts, %{keys: :strings, strings: :reference}) end end
minimal_server/deps/jason/lib/jason.ex
0.930466
0.761206
jason.ex
starcoder
defmodule Can do import Plug.Conn defstruct [ policy: nil, action: nil, authorized?: false ] def can(conn, policy, action, context) do action = action || get_action(conn) policy = policy || get_policy(conn) conn = conn |> put_action(action) |> put_policy(policy) authorized? = apply_policy!(policy, action, [conn, Enum.into(context, %{})]) if authorized?, do: authorize(conn), else: conn end def can(conn, action, context) when is_atom(action) and is_list(context) do can(conn, get_policy(conn), action, context) end def can(conn, action) when is_atom(action) do can(conn, get_policy(conn), action, []) end def can(conn, context) when is_list(context) do can(conn, get_policy(conn), get_action(conn), context) end def can(conn) do can(conn, get_policy(conn), get_action(conn), []) end def can!(conn, policy, action, context) when is_atom(action) and is_list(context) do conn = can(conn, policy, action, context) if authorized?(conn) do conn else raise Can.UnauthorizedError, context: Enum.into(context, %{}) end end def can!(conn, action, context) when is_atom(action) and is_list(context) do can!(conn, get_policy(conn), action, context) end def can!(conn, action) when is_atom(action) do can!(conn, get_policy(conn), action, []) end def can!(conn, context) when is_list(context) do can!(conn, get_policy(conn), get_action(conn), context) end def can!(conn) do can!(conn, get_policy(conn), get_action(conn), []) end def can?(conn, policy, action, context) when is_atom(action) and is_list(context) do if authorized?(conn) do true else conn |> can(policy, action, context) |> authorized?() end end def can?(conn, action, context) when is_atom(action) and is_list(context) do can?(conn, get_policy(conn), action, context) end def can?(conn, action) when is_atom(action) do can?(conn, get_policy(conn), action, []) end def can?(conn, context) when is_list(context) do can?(conn, get_policy(conn), get_action(conn), context) end def can?(conn) do can?(conn, get_policy(conn), get_action(conn), []) end def authorize(conn, boolean \\ true) do put_can(conn, :authorized?, boolean) end def authorized?(conn) do conn.private[:can].authorized? end def put_policy(conn, policy) do put_can(conn, :policy, policy) end def get_policy(conn, policy \\ nil) do conn.private[:can].policy || policy end def put_action(conn, action) do put_can(conn, :action, action) end def get_action(conn, action \\ nil) do conn.private[:can].action || action end defp put_can(conn, key, value) do can = conn.private |> Map.get(:can, %Can{}) |> Map.put(key, value) put_private(conn, :can, can) end defp apply_policy!(policy, function, args) do policy |> verify_policy! |> apply(function, args) end defp verify_policy!(policy) do if Code.ensure_loaded?(policy) do policy else raise Can.UndefinedPolicyError, policy: policy end end end
lib/can.ex
0.50293
0.420094
can.ex
starcoder
defmodule Logger.Backends.Gelf do @moduledoc """ GELF Logger Backend # GelfLogger [![Build Status](https://travis-ci.org/jschniper/gelf_logger.svg?branch=master)](https://travis-ci.org/jschniper/gelf_logger) A logger backend that will generate Graylog Extended Log Format messages. The current version only supports UDP messages. ## Configuration In the config.exs, add gelf_logger as a backend like this: ``` config :logger, backends: [:console, {Logger.Backends.Gelf, :gelf_logger}] ``` In addition, you'll need to pass in some configuration items to the backend itself: ``` config :logger, :gelf_logger, host: "127.0.0.1", port: 12201, format: "$message", application: "myapp", compression: :gzip, # Defaults to :gzip, also accepts :zlib or :raw metadata: [:request_id, :function, :module, :file, :line], hostname: "hostname-override", json_encoder: Poison, tags: [ list: "of", extra: "tags" ] ``` In addition, if you want to use your custom metadata formatter as a "callback", you'll need to add below configuration entry: ``` format: {Module, :function} ``` Please bear in mind that your formating function MUST return a tuple in following format: `{level, message, timestamp, metadata}` In addition to the backend configuration, you might want to check the [Logger configuration](https://hexdocs.pm/logger/Logger.html) for other options that might be important for your particular environment. In particular, modifying the `:utc_log` setting might be necessary depending on your server configuration. This backend supports `metadata: :all`. ### Note on the JSON encoder: Currently, the logger defaults to Poison but it can be switched out for any module that has an encode!/1 function. ## Usage Just use Logger as normal. ## Improvements - [x] Tests - [ ] TCP Support - [x] Options for compression (none, zlib) - [x] Send timestamp instead of relying on the Graylog server to set it - [x] Find a better way of pulling the hostname And probably many more. This is only out here because it might be useful to someone in its current state. Pull requests are always welcome. ## Notes Credit where credit is due, this would not exist without [protofy/erl_graylog_sender](https://github.com/protofy/erl_graylog_sender). """ @max_size 1_047_040 @max_packet_size 8192 @max_payload_size 8180 @epoch :calendar.datetime_to_gregorian_seconds({{1970, 1, 1}, {0, 0, 0}}) @behaviour :gen_event def init({__MODULE__, name}) do if user = Process.whereis(:user) do Process.group_leader(self(), user) {:ok, configure(name, [])} else {:error, :ignore} end end def handle_call({:configure, options}, state) do {:ok, :ok, configure(state[:name], options)} end def handle_event({_level, gl, _event}, state) when node(gl) != node() do {:ok, state} end def handle_event({level, _gl, {Logger, msg, ts, md}}, %{level: min_level} = state) do if is_nil(min_level) or Logger.compare_levels(level, min_level) != :lt do log_event(level, msg, ts, md, state) end {:ok, state} end def handle_event(:flush, state) do {:ok, state} end def handle_info({:io_reply, ref, :ok}, %{ref: ref} = state) do Process.demonitor(ref, [:flush]) {:ok, state} end def handle_info({:io_reply, _ref, {:error, error}}, _state) do raise "failure while logging gelf messages: " <> inspect(error) end def handle_info({:DOWN, ref, _, pid, reason}, %{ref: ref}) do raise "device #{inspect(pid)} exited: " <> Exception.format_exit(reason) end def handle_info(_, state) do {:ok, state} end def code_change(_old_vsn, state, _extra) do {:ok, state} end def terminate(_reason, _state) do :ok end ## Helpers defp configure(name, options) do config = Keyword.merge(Application.get_env(:logger, name, []), options) Application.put_env(:logger, name, config) {:ok, socket} = :gen_udp.open(0) {:ok, hostname} = :inet.gethostname() hostname = Keyword.get(config, :hostname, hostname) gl_host = Keyword.get(config, :host) |> to_charlist port = Keyword.get(config, :port) application = Keyword.get(config, :application) level = Keyword.get(config, :level) metadata = Keyword.get(config, :metadata, []) compression = Keyword.get(config, :compression, :gzip) encoder = Keyword.get(config, :json_encoder, Poison) tags = Keyword.get(config, :tags, []) format = try do format = Keyword.get(config, :format, "$message") case format do {module, function} -> with true <- Code.ensure_loaded?(module), true <- function_exported?(module, function, 4) do {module, function} else _ -> Logger.Formatter.compile("$message") end _ -> Logger.Formatter.compile(format) end rescue _ -> Logger.Formatter.compile("$message") end port = cond do is_binary(port) -> {val, ""} = Integer.parse(to_string(port)) val true -> port end %{ name: name, gl_host: gl_host, host: to_string(hostname), port: port, metadata: metadata, level: level, application: application, socket: socket, compression: compression, tags: tags, encoder: encoder, format: format } end defp log_event(level, msg, ts, md, state) do {level, msg, ts, md} = format(level, msg, ts, md, state[:format]) int_level = case level do :debug -> 7 :info -> 6 :warn -> 4 :error -> 3 end fields = md |> take_metadata(state[:metadata]) |> Keyword.merge(state[:tags]) |> Map.new(fn {k, v} -> if is_list(v) or String.Chars.impl_for(v) == nil do {"_#{k}", inspect(v)} else {"_#{k}", to_string(v)} end end) {{year, month, day}, {hour, min, sec, milli}} = ts epoch_seconds = :calendar.datetime_to_gregorian_seconds({{year, month, day}, {hour, min, sec}}) - @epoch {timestamp, _remainder} = "#{epoch_seconds}.#{milli}" |> Float.parse() msg_formatted = if is_tuple(state[:format]), do: msg, else: format_event(level, msg, ts, md, state) gelf = %{ short_message: String.slice(to_string(msg_formatted), 0..79), full_message: to_string(msg_formatted), version: "1.1", host: state[:host], level: int_level, timestamp: Float.round(timestamp, 3), _application: state[:application] } |> Map.merge(fields) data = encode(gelf, state[:encoder]) |> compress(state[:compression]) size = byte_size(data) cond do to_string(msg_formatted) == "" -> # Skip empty messages :ok size > @max_size -> raise ArgumentError, message: "Message too large" size > @max_packet_size -> num = div(size, @max_packet_size) num = if num * @max_packet_size < size do num + 1 else num end id = :crypto.strong_rand_bytes(8) send_chunks( state[:socket], state[:gl_host], state[:port], data, id, :binary.encode_unsigned(num), 0, size ) true -> :gen_udp.send(state[:socket], state[:gl_host], state[:port], data) end end defp format(level, message, timestamp, metadata, {module, function}) do apply(module, function, [level, message, timestamp, metadata]) end defp format(level, message, timestamp, metadata, _), do: {level, message, timestamp, metadata} defp send_chunks(socket, host, port, data, id, num, seq, size) when size > @max_payload_size do <<payload::binary-size(@max_payload_size), rest::binary>> = data :gen_udp.send(socket, host, port, make_chunk(payload, id, num, seq)) send_chunks(socket, host, port, rest, id, num, seq + 1, byte_size(rest)) end defp send_chunks(socket, host, port, data, id, num, seq, _size) do :gen_udp.send(socket, host, port, make_chunk(data, id, num, seq)) end defp make_chunk(payload, id, num, seq) do bin = :binary.encode_unsigned(seq) <<0x1E, 0x0F, id::binary-size(8), bin::binary-size(1), num::binary-size(1), payload::binary>> end defp encode(data, encoder) do :erlang.apply(encoder, :encode!, [data]) end defp compress(data, type) do case type do :gzip -> :zlib.gzip(data) :zlib -> :zlib.compress(data) _ -> data end end # Ported from Logger.Backends.Console defp format_event(level, msg, ts, md, %{format: format, metadata: keys}) do Logger.Formatter.format(format, level, msg, ts, take_metadata(md, keys)) end # Ported from Logger.Backends.Console defp take_metadata(metadata, :all) do Keyword.drop(metadata, [:crash_reason, :ancestors, :callers]) end defp take_metadata(metadata, keys) do Enum.reduce(keys, [], fn key, acc -> case Keyword.fetch(metadata, key) do {:ok, val} -> [{key, val} | acc] :error -> acc end end) end end
lib/gelf_logger.ex
0.722233
0.841272
gelf_logger.ex
starcoder
defmodule Phoenix.LiveDashboard.HomePage do @moduledoc false use Phoenix.LiveDashboard.PageBuilder import Phoenix.HTML import Phoenix.LiveDashboard.Helpers alias Phoenix.LiveDashboard.SystemInfo @memory_usage_sections [ {:atom, "Atoms", "green", nil}, {:binary, "Binary", "blue", nil}, {:code, "Code", "purple", nil}, {:ets, "ETS", "yellow", nil}, {:process, "Processes", "orange", nil}, {:other, "Other", "dark-gray", nil} ] @menu_text "Home" @hints [ total_input: "The total number of bytes received through ports/sockets.", total_output: "The total number of bytes output to ports/sockets.", total_queues: """ Each core in your machine gets a scheduler to process all instructions within the Erlang VM. Each scheduler has its own queue, which is measured by this number. If this number keeps on growing, it means the machine is overloaded. The queue sizes can also be broken into CPU and IO. """, atoms: """ If the number of atoms keeps growing even if the system load is stable, you may have an atom leak in your application. You must avoid functions such as <code>String.to_atom/1</code> which can create atoms dynamically. """, ports: """ If the number of ports keeps growing even if the system load is stable, you may have a port leak in your application. This means ports are being opened by a parent process that never exits or never closes them. """, processes: """ If the number of processes keeps growing even if the system load is stable, you may have a process leak in your application. This means processes are being spawned and they never exit. """ ] @impl true def mount(_params, session, socket) do {app_title, app_name} = session[:home_app] %{ # Read once system_info: system_info, environment: environment, # Kept forever system_limits: system_limits, # Updated periodically system_usage: system_usage } = SystemInfo.fetch_system_info(socket.assigns.page.node, session[:env_keys], app_name) socket = assign(socket, system_info: system_info, system_limits: system_limits, system_usage: system_usage, environment: environment, app_title: app_title ) {:ok, socket} end @impl true def render_page(assigns) do row( components: [ columns( components: [ [ erlang_info_row(assigns.system_info), elixir_info_row(assigns.system_info, assigns.app_title), io_info_row(assigns.system_usage), run_queues_row(assigns.system_usage), environments_row(assigns.environment) ], [ atoms_usage_row(assigns), ports_usage_row(assigns), processes_usage_row(assigns), memory_shared_usage_row(assigns) ] ] ) ] ) end @impl true def menu_link(_, _) do {:ok, @menu_text} end defp erlang_info_row(system_info) do row( components: [ columns( components: [ card( title: "System information", value: "#{system_info.banner} [#{system_info.system_architecture}]", class: ["no-title"] ) ] ) ] ) end defp elixir_info_row(system_info, app_title) do row( components: [ columns( components: [ card( inner_title: "Elixir", value: system_info[:elixir_version], class: ["bg-elixir", "text-white"] ), card( inner_title: "Phoenix", value: system_info[:phoenix_version], class: ["bg-phoenix", "text-white"] ), card( inner_title: app_title, value: system_info[:app_version], class: ["bg-dashboard", "text-white"] ) ] ) ] ) end defp io_info_row(system_usage) do row( components: [ columns( components: [ card( inner_title: "Uptime", value: format_uptime(system_usage.uptime) ), card( inner_title: "Total input", inner_hint: @hints[:total_input], value: format_bytes(system_usage.io |> elem(0)) ), card( inner_title: "Total output", inner_hint: @hints[:total_output], value: format_bytes(system_usage.io |> elem(1)) ) ] ) ] ) end defp run_queues_row(system_usage) do row( components: [ columns( components: [ card( title: "Run queues", inner_title: "Total", inner_hint: @hints[:total_queues], value: system_usage.total_run_queue ), card( inner_title: "CPU", value: system_usage.cpu_run_queue ), card( inner_title: "IO", value: system_usage.total_run_queue - system_usage.cpu_run_queue ) ] ) ] ) end defp environments_row(environments) do row( components: [ columns( components: [ fields_card( title: "Environment", fields: environments ) ] ) ] ) end defp atoms_usage_row(assigns) do usages = usage_params(:atoms, assigns) params = [ usages: usages, dom_id: "atoms", title: "System limits", csp_nonces: assigns.csp_nonces ] row( components: [ columns( components: [ usage_card(params) ] ) ] ) end defp ports_usage_row(assigns) do usages = usage_params(:ports, assigns) params = [usages: usages, dom_id: "ports", csp_nonces: assigns.csp_nonces] row( components: [ columns( components: [ usage_card(params) ] ) ] ) end defp processes_usage_row(assigns) do usages = usage_params(:processes, assigns) params = [usages: usages, dom_id: "processes", csp_nonces: assigns.csp_nonces] row( components: [ columns( components: [ usage_card(params) ] ) ] ) end defp memory_shared_usage_row(assigns) do params = memory_usage_params(assigns) row( components: [ columns( components: [ shared_usage_card(params) ] ) ] ) end defp usage_params(type, %{system_usage: system_usage, system_limits: system_limits}) do [ %{ current: system_usage[type], limit: system_limits[type], percent: percentage(system_usage[type], system_limits[type]), dom_sub_id: "total", hint: raw(@hints[type]), title: Phoenix.Naming.humanize(type) } ] end defp memory_usage_params(%{system_usage: system_usage} = assigns) do total = system_usage.memory.total memory_usage = calculate_memory_usage(system_usage.memory) usages = [calculate_memory_usage_percent(memory_usage, total)] [ title: "Memory", usages: usages, total_data: memory_usage, total_legend: "Total usage:", total_usage: format_bytes(system_usage.memory[:total]), total_formatter: &format_bytes(&1), csp_nonces: assigns.csp_nonces, dom_id: "memory" ] end defp calculate_memory_usage(memory_usage) do for {key, name, color, desc} <- @memory_usage_sections, value = memory_usage[key] do {name, value, color, desc} end end defp calculate_memory_usage_percent(memory_usage, total) do data = Enum.map(memory_usage, fn {name, value, color, desc} -> {name, percentage(value, total), color, desc} end) %{ data: data, dom_sub_id: "total" } end @impl true def handle_refresh(socket) do {:noreply, assign(socket, system_usage: SystemInfo.fetch_system_usage(socket.assigns.page.node))} end end
lib/phoenix/live_dashboard/pages/home_page.ex
0.708313
0.426142
home_page.ex
starcoder
defmodule Timber.Integrations.HTTPContextPlug do @moduledoc """ Automatically captures the HTTP method, path, and request_id in Plug-based frameworks like Phoenix and adds it to the context. By adding this data to the context, you'll be able to associate all the log statements that occur while processing that HTTP request. ## Adding the Plug `Timber.Integrations.HTTPContextPlug` can be added to your plug pipeline using the standard `Plug.Builder.plug/2` macro. The point at which you place it determines what state Timber will receive the connection in, therefore it's recommended you place it as close to the origin of the request as possible. ### Plug (Standalone or Plug.Router) If you are using Plug without a framework, your setup will vary depending on your architecture. The call to `plug Timber.Integrations.HTTPContextPlug` should be grouped with any other plugs you call prior to performing business logic. Timber expects query parameters to have already been fetched on the connection using `Plug.Conn.fetch_query_params/2`. ### Phoenix Phoenix's flexibility means there are multiple points in the plug pipeline where the `Timber.Integrations.HTTPContextPlug` can be inserted. The recommended place is in `endpoint.ex`. Make sure that you insert this plug immediately before your `Router` plug. ## Request ID Timber does its best to track the request ID for every HTTP request in order to help you filter your logs easily. If you are calling the `Plug.RequestId` plug in your pipeline, you should make sure that `Timber.Integrations.HTTPContextPlug` appears _after_ that plug so that it can pick up the correct ID. By default, Timber expects your request ID to be stored using the header name "X-Request-ID" (casing irrelevant), but that may not fit all needs. If you use a custom header name for your request ID, you can pass that name as an option to the plug: ``` plug Timber.Plug, request_id_header: "req-id" ``` """ alias Timber.Contexts.HTTPContext alias Timber.Utils.Plug, as: PlugUtils @doc """ Prepares the given options for use in a plug pipeline When the `Plug.Builder.plug/2` macro is called, it will use this function to prepare options. Any resulting options will be passed on to the plug on every call. The options accepted by this function are the same as defined by `call/2`. """ @spec init(Plug.opts) :: Plug.opts def init(opts) do opts end @doc """ Adds the Request ID to the Timber context data """ @spec call(Plug.Conn.t, Plug.opts) :: Plug.Conn.t def call(%{method: method, request_path: request_path} = conn, opts) do request_id_header = Keyword.get(opts, :request_id_header, "x-request-id") remote_addr = PlugUtils.get_client_ip(conn) request_id = case PlugUtils.get_request_id(conn, request_id_header) do [{_, request_id}] -> request_id [] -> nil end %HTTPContext{ method: method, path: request_path, request_id: request_id, remote_addr: remote_addr } |> Timber.add_context() conn end end
lib/timber/integrations/http_context_plug.ex
0.89792
0.670308
http_context_plug.ex
starcoder
defmodule Mix.Project do @moduledoc """ A module that provides conveniences for defining and working with projects. ## Examples In order to configure Mix, a developer needs to use `Mix.Project` in a module and define a function named `project` that returns a keywords list with configuration. defmodule MyApp do use Mix.Project def project do [ app: :my_app, vsn: "0.6.0" ] end end After defined, the configuration for this project can be read as `Mix.project/0`. Notice that config won't fail if a project is not defined, this allows many of mix tasks to work even without a project. In case the developer needs a project or want to access a special function in the project, he can access `Mix.Project.current/0` which fails with `Mix.NoProjectError` in case a project is not defined. """ def behaviour_info(:callbacks) do [project: 0] end @doc false defmacro __using__(_) do Mix.Project.push __CALLER__.module quote do @behavior Mix.Project end end # Push a project into the project stack. Only # the top of the stack can be accessed. @doc false def push(atom) when is_atom(atom) do Mix.Server.cast({ :push_project, atom }) end # Pops a project from the stack. @doc false def pop do Mix.Server.cast(:pop_project) end # Loads the mix.exs file in the current directory # and executes the given function. The project and # tasks stack are properly manipulated, no side-effects # should remain. @doc false def in_subproject(function) do current = Mix.Project.current tasks = Mix.Task.clear if File.regular?("mix.exs") do Code.load_file "mix.exs" end if current == Mix.Project.current do Mix.Project.push nil end try do function.() after Mix.Project.pop Mix.Task.set_tasks(tasks) end end @doc """ Retrieves the current project, raises an error if there is no project set. """ def current do case Mix.Server.call(:projects) do [h|_] when h != nil -> h _ -> raise Mix.NoProjectError end end @doc """ Returns true if a current project is defined. """ def defined? do case Mix.Server.call(:projects) do [h|_] when h != nil -> true _ -> false end end end
lib/mix/lib/mix/project.ex
0.761006
0.407216
project.ex
starcoder
defmodule Astarte.Flow.Blocks.MqttSource do @moduledoc """ An Astarte Flow source that produces data from an MQTT connection. When a message is received on a subscribed topic, `MqttSource` generates an `%Astarte.Flow.Message{}` containing these fields: * `key` contains the topic on which the message was received. * `data` contains the payload of the message. * `type` is always `:binary`. * `subtype` defaults to `application/octet-stream` but can be configured with the `subtype` option in `start_link/1`. * `metadata` contains the `Astarte.Flow.Blocks.MqttSource.broker_url` key with the broker url as value. * `timestamp` contains the timestamp (in microseconds) the message was received on. Since MQTT is a push-driven protocol, this block implements a queue to buffer incoming messages while waiting for consumer demand. """ use GenStage require Logger alias Astarte.Flow.Message defmodule State do @moduledoc false defstruct [ :mqtt_connection, :pending_demand, :queue ] end @doc """ Starts the `MqttSource`. ## Options * `broker_url` (required): the URL of the broker the source will connect to. The transport will be deduced by the URL: if `mqtts://` is used, SSL transport will be used, if `mqtt://` is used, TCP transport will be used. * `subscriptions` (required): a non-empty list of topic filters to subscribe to. * `client_id`: the client id used to connect. Defaults to a random string. * `username`: username used to authenticate to the broker. * `password`: password used to authenticate to the broker. * `ignore_ssl_errors`: if true, accept invalid certificates (e.g. self-signed) when using SSL. * `subtype`: a MIME type that will be put as `subtype` in the generated Messages. Defaults to `application/octet-stream` """ @spec start_link(opts) :: GenServer.on_start() when opts: [opt], opt: {:broker_url, String.t()} | {:subscriptions, nonempty_list(String.t())} | {:client_id, String.t()} | {:username, String.t()} | {:password, String.t()} | {:ignore_ssl_errors, boolean} def start_link(opts) do GenStage.start_link(__MODULE__, opts) end # GenStage callbacks @impl true def init(opts) do with {:ok, tortoise_opts} <- build_tortoise_opts(opts), {:ok, pid} <- Tortoise.Connection.start_link(tortoise_opts) do state = %State{ mqtt_connection: pid, pending_demand: 0, queue: :queue.new() } {:producer, state, dispatcher: GenStage.BroadcastDispatcher} else {:error, reason} -> {:stop, reason} end end @impl true def handle_demand(incoming_demand, %State{pending_demand: demand} = state) do dispatch_messages(%{state | pending_demand: demand + incoming_demand}, []) end @impl true def handle_cast({:new_message, %Message{} = message}, state) do %State{ queue: queue } = state updated_queue = :queue.in(message, queue) dispatch_messages(%{state | queue: updated_queue}, []) end defp build_tortoise_opts(opts) do alias Astarte.Flow.Blocks.MqttSource.Handler with {:url, {:ok, broker_url}} <- {:url, Keyword.fetch(opts, :broker_url)}, {:subs, {:ok, [_head | _tail] = subscriptions}} <- {:subs, Keyword.fetch(opts, :subscriptions)}, client_id = Keyword.get_lazy(opts, :client_id, &random_client_id/0), {:ok, server} <- build_server(broker_url, opts) do subscriptions_with_qos = for subscription <- subscriptions do {subscription, 2} end subtype = Keyword.get(opts, :subtype, "application/octet-stream") handler_opts = [ source_pid: self(), broker_url: broker_url, subtype: subtype ] base_opts = [ client_id: client_id, broker_url: broker_url, server: server, subscriptions: subscriptions_with_qos, handler: {Handler, handler_opts} ] additional_opts = Keyword.take(opts, [:username, :password]) |> Enum.map(fn # Adapt :username option to Tortoise spelling (:user_name) {:username, username} -> {:user_name, username} {other, value} -> {other, value} end) {:ok, Keyword.merge(base_opts, additional_opts)} else {:url, _} -> {:error, :missing_broker_url} {:subs, :error} -> {:error, :missing_subscriptions} {:subs, {:ok, []}} -> {:error, :empty_subscriptions} {:error, reason} -> {:error, reason} end end defp build_server(broker_url, opts) do case URI.parse(broker_url) do %URI{scheme: "mqtts", host: host, port: port} when is_binary(host) -> verify = if Keyword.get(opts, :ignore_ssl_errors) do :verify_none else :verify_peer end opts = [ host: host, port: port || 8883, cacertfile: :certifi.cacertfile(), verify: verify ] {:ok, {Tortoise.Transport.SSL, opts}} %URI{scheme: "mqtt", host: host, port: port} when is_binary(host) -> opts = [ host: host, port: port || 1883 ] {:ok, {Tortoise.Transport.Tcp, opts}} _ -> _ = Logger.warn("Can't parse broker url: #{inspect(broker_url)}") {:error, :invalid_broker_url} end end defp random_client_id do :crypto.strong_rand_bytes(16) |> Base.url_encode64(padding: false) end defp dispatch_messages(%State{pending_demand: 0} = state, messages) do {:noreply, Enum.reverse(messages), state} end defp dispatch_messages(%State{pending_demand: demand, queue: queue} = state, messages) do case :queue.out(queue) do {{:value, message}, updated_queue} -> updated_state = %{state | pending_demand: demand - 1, queue: updated_queue} updated_messages = [message | messages] dispatch_messages(updated_state, updated_messages) {:empty, _queue} -> {:noreply, Enum.reverse(messages), state} end end end
lib/astarte_flow/blocks/mqtt_source.ex
0.851367
0.491273
mqtt_source.ex
starcoder
defmodule Bloomex do @moduledoc """ This module implements a [Scalable Bloom Filter](http://haslab.uminho.pt/cbm/files/dbloom.pdf). ## Examples iex> bf = Bloomex.scalable(1000, 0.1, 0.1, 2) %Bloomex.ScalableBloom... iex> bf = Bloomex.add(bf, 5) %Bloomex.ScalableBloom... iex> Bloomex.member?(bf, 5) true iex> bf = Bloomex.add(bf, 100) %Bloomex.ScalableBloom... iex> Bloomex.member?(bf, 100) true iex> Bloomex.member?(bf, 105) false iex> Bloomex.member?(bf, 101) # false positive true """ @type t :: Bloomex.Bloom.t() | Bloomex.ScalableBloom.t() @type mode :: :bits | :size @type hash_func :: (term -> pos_integer) use Bitwise defmodule Bloom do @moduledoc """ A plain bloom filter. * :error_prob - error probability * :max - maximum number of elements * :mb - 2^mb = m, the size of each slice (bitvector) * :size - number of elements * :bv - list of bitvectors * :hash_func - hash function to use """ defstruct [ :error_prob, :max, :mb, :size, :bv, :hash_func ] @type t :: %Bloom{ error_prob: number, max: integer, mb: integer, size: integer, bv: [Bloomex.BitArray.t()], hash_func: Bloomex.hash_func() } end defmodule ScalableBloom do @moduledoc """ A scalable bloom filter. * :error_prob - error probability * :error_prob_ratio - error probability ratio * :growth - log 2 of growth ratio * :size - number of elements * :b - list of plain bloom filters * :hash_func - hash function to use """ defstruct [ :error_prob, :error_prob_ratio, :growth, :size, :b, :hash_func ] @type t :: %ScalableBloom{ error_prob: number, error_prob_ratio: number, growth: integer, size: integer, b: [Bloomex.Bloom.t()], hash_func: Bloomex.hash_func() } end @doc """ Returns a scalable Bloom filter based on the provided arguments: * `capacity`, the initial capacity before expanding * `error`, the error probability * `error_ratio`, the error probability ratio * `growth`, the growth ratio when full * `hash_func`, a hashing function If a hash function is not provided then `:erlang.phash2/2` will be used with the maximum range possible `(2^32)`. Restrictions: * `capacity` must be a positive integer * `error` must be a float between `0` and `1` * `error_ratio` must be a float between `0` and `1` * `growth` must be a positive integer between `1` and `3` * `hash_func` must be a function of type `term -> pos_integer` The function follows a rule of thumb due to double hashing where `capacity >= 4 / (error * (1 - error_ratio))` must hold true. """ @spec scalable(integer, number, number, 1 | 2 | 3, hash_func()) :: ScalableBloom.t() def scalable( capacity, error, error_ratio, growth, hash_func \\ fn x -> :erlang.phash2(x, 1 <<< 32) end ) when capacity > 0 and error > 0 and error < 1 and growth in [1, 2, 3] and error_ratio > 0 and error_ratio < 1 and capacity >= 4 / (error * (1 - error_ratio)) do %ScalableBloom{ error_prob: error, error_prob_ratio: error_ratio, growth: growth, size: 0, b: [plain(capacity, error * (1 - error_ratio), hash_func)], hash_func: hash_func } end @doc """ Returns a plain Bloom filter based on the provided arguments: * `capacity`, used to calculate the size of each bitvector slice * `error`, the error probability * `hash_func`, a hashing function If a hash function is not provided then `:erlang.phash2/2` will be used with the maximum range possible `(2^32)`. Restrictions: * `capacity` must be a positive integer * `error` must be a float between `0` and `1` * `hash_func` must be a function of type `term -> pos_integer` The function follows a rule of thumb due to double hashing where `capacity >= 4 / error` must hold true. """ @spec plain(integer, float, hash_func()) :: Bloom.t() def plain(capacity, error, hash_func \\ fn x -> :erlang.phash2(x, 1 <<< 32) end) when is_number(error) and capacity > 0 and is_float(error) and error > 0 and error < 1 and capacity >= 4 / error do plain(:size, capacity, error, hash_func) end @spec plain(mode(), integer, number, hash_func()) :: Bloom.t() defp plain(mode, capacity, e, hash_func) do k = 1 + trunc(log2(1 / e)) p = :math.pow(e, 1 / k) mb = case mode do :size -> 1 + trunc(-log2(1 - :math.pow(1 - p, 1 / capacity))) :bits -> capacity end m = 1 <<< mb n = trunc(:math.log(1 - p) / :math.log(1 - 1 / m)) %Bloom{ error_prob: e, max: n, mb: mb, size: 0, bv: for(_ <- 1..k, do: Bloomex.BitArray.new(1 <<< mb)), hash_func: hash_func } end @doc """ Returns the number of elements currently in the bloom filter. """ @spec size(t) :: pos_integer def size(%Bloom{size: size}), do: size def size(%ScalableBloom{size: size}), do: size @doc """ Returns the capacity of the bloom filter. A plain bloom filter will always have a fixed capacity, while a scalable one will always have a theoretically infite capacity. """ @spec capacity(Bloomex.t()) :: pos_integer | :infinity def capacity(%Bloom{max: n}), do: n def capacity(%ScalableBloom{}), do: :infinity @doc """ Returns `true` if the element `e` exists in the bloom filter, otherwise returns `false`. Keep in mind that you may get false positives, but never false negatives. """ @spec member?(Bloomex.t(), any) :: boolean def member?(%Bloom{mb: mb, hash_func: hash_func} = bloom, e) do hashes = make_hashes(mb, e, hash_func) hash_member(hashes, bloom) end def member?(%ScalableBloom{b: [%Bloom{mb: mb, hash_func: hash_func} | _]} = bloom, e) do hashes = make_hashes(mb, e, hash_func) hash_member(hashes, bloom) end @spec hash_member(pos_integer, Bloomex.t()) :: boolean defp hash_member(hashes, %Bloom{mb: mb, bv: bv}) do mask = (1 <<< mb) - 1 {i1, i0} = make_indexes(mask, hashes) all_set(mask, i1, i0, bv) end defp hash_member(hashes, %ScalableBloom{b: b}) do Enum.any?(b, &hash_member(hashes, &1)) end @spec make_hashes(pos_integer, any, hash_func()) :: pos_integer | {pos_integer, pos_integer} defp make_hashes(mb, e, hash_func) when mb <= 16 do hash_func.({e}) end defp make_hashes(mb, e, hash_func) when mb <= 32 do {hash_func.({e}), hash_func.([e])} end @spec make_indexes(pos_integer, {pos_integer, pos_integer}) :: {pos_integer, pos_integer} defp make_indexes(mask, {h0, h1}) when mask > 1 <<< 16 do masked_pair(mask, h0, h1) end defp make_indexes(mask, {h0, _}) do make_indexes(mask, h0) end @spec make_indexes(pos_integer, pos_integer) :: {pos_integer, pos_integer} defp make_indexes(mask, h0) do masked_pair(mask, h0 >>> 16, h0) end @spec masked_pair(pos_integer, pos_integer, pos_integer) :: {pos_integer, pos_integer} defp masked_pair(mask, x, y), do: {x &&& mask, y &&& mask} @spec all_set(pos_integer, pos_integer, pos_integer, [Bloomex.BitArray.t()]) :: boolean defp all_set(_, _, _, []), do: true defp all_set(mask, i1, i, [h | t]) do if Bloomex.BitArray.get(h, i) do all_set(mask, i1, i + i1 &&& mask, t) else false end end @doc """ Returns a bloom filter with the element `e` added. """ @spec add(Bloomex.t(), any) :: Bloomex.t() def add(%Bloom{mb: mb, hash_func: hash_func} = bloom, e) do hashes = make_hashes(mb, e, hash_func) hash_add(hashes, bloom) end def add(%ScalableBloom{error_prob_ratio: r, size: size, growth: g, b: [h | t] = bs} = bloom, e) do %Bloom{mb: mb, error_prob: err, max: n, size: head_size, hash_func: hash_func} = h hashes = make_hashes(mb, e, hash_func) if hash_member(hashes, bloom) do bloom else if head_size < n do %{bloom | size: size + 1, b: [hash_add(hashes, h) | t]} else b = :bits |> plain(mb + g, err * r, hash_func) |> add(e) %{bloom | size: size + 1, b: [b | bs]} end end end @spec hash_add(pos_integer, Bloom.t()) :: Bloom.t() defp hash_add(hashes, %Bloom{mb: mb, bv: bv, size: size} = b) do mask = (1 <<< mb) - 1 {i1, i0} = make_indexes(mask, hashes) if all_set(mask, i1, i0, bv) do b else %{b | size: size + 1, bv: set_bits(mask, i1, i0, bv, [])} end end @spec set_bits( pos_integer, pos_integer, pos_integer, [Bloomex.BitArray.t()], [Bloomex.BitArray.t()] ) :: [Bloomex.BitArray.t()] defp set_bits(_, _, _, [], acc), do: Enum.reverse(acc) defp set_bits(mask, i1, i, [h | t], acc) do set_bits(mask, i1, i + i1 &&& mask, t, [Bloomex.BitArray.set(h, i) | acc]) end @spec log2(float) :: float defp log2(x) do :math.log(x) / :math.log(2) end end
lib/bloomex.ex
0.930494
0.660487
bloomex.ex
starcoder
defmodule ExWeather.WeatherManager do @moduledoc """ The WeatherManager is a higher level client for getting certain weather aspects. """ require Logger alias ExWeather.WeatherClient alias ExWeather.MetaWeatherClient defmodule TemperatureResponse do @type t :: %__MODULE__{ title: String.t(), avg_max: float() } defstruct [:title, :avg_max] end @type temp_response :: {:error, any()} | {:ok, TemperatureResponse.t()} @spec temperature_for_location(any(), String.t(), integer()) :: temp_response() def temperature_for_location(client \\ MetaWeatherClient, location_id, days) do Logger.debug("Getting temperature data for location #{location_id}") case client.get_weather_for_location(location_id) do {:ok, response} -> handle_weather_response(client, response, location_id, days) {:error, error} -> Logger.error(inspect(error)) {:error, "failed to fetch tempurature data"} end end @spec handle_weather_response( any(), list(WeatherClient.WeatherResponse.t()), String.t(), integer() ) :: temp_response() defp handle_weather_response(client, weather_data, location_id, requested_days) do response_length = Enum.count(weather_data) title = Enum.at(weather_data, 0).title cond do response_length == requested_days -> avg_max = weather_data |> Enum.map(& &1.max_temp) |> Enum.to_list() |> ExWeather.average() {:ok, %TemperatureResponse{ title: title, avg_max: avg_max }} response_length > requested_days -> Logger.debug( "Requested #{requested_days} days, but received #{response_length} from the API." ) avg_max = weather_data |> Enum.take(requested_days) |> Enum.map(& &1.max_temp) |> Enum.to_list() |> ExWeather.average() {:ok, %TemperatureResponse{ title: title, avg_max: avg_max }} 0 < response_length and response_length < requested_days -> days_short = requested_days - response_length Logger.debug("Short by: #{days_short} days. Requesting additional data...") latest_datum = Enum.max_by(weather_data, & &1.applicable_date, Date) dates_to_fetch = ExWeather.dates_until_days(latest_datum.applicable_date, days_short) remaining_data = async_get_by_dates(client, location_id, dates_to_fetch) final_batch = weather_data ++ remaining_data avg_max = final_batch |> Enum.map(& &1.max_temp) |> Enum.to_list() |> ExWeather.average() {:ok, %TemperatureResponse{ title: title, avg_max: avg_max }} end end defp async_get_by_dates(client, location_id, dates) do Logger.debug( "Async fetching weather for location: #{location_id} on dates: #{inspect(dates)}" ) dates |> Task.async_stream(&get_location_data_for_date(client, location_id, &1), ordered: true) |> Stream.filter(&match?({:ok, _}, &1)) |> Stream.map(fn {:ok, res} -> res end) |> Enum.into([], fn {:ok, res} -> res end) end defp get_location_data_for_date(client, location_id, date) do case client.get_weather_for_location_on_date(location_id, date) do {:ok, weather_response} -> {:ok, weather_response} {:error, _} -> err_msg = "failed to fetch for location: #{location_id} on #{Date.to_iso8601(date)}" Logger.error(err_msg) {:error, err_msg} end end end
lib/ex_weather/weather_manager.ex
0.810366
0.425784
weather_manager.ex
starcoder
defmodule Membrane.RTP.Serializer do @moduledoc """ Given following RTP payloads and their minimal metadata, creates their proper header information, incrementing timestamps and sequence numbers for each packet. Header information then is put inside buffer's metadata under `:rtp` key. Accepts the following metadata under `:rtp` key: `:marker`, `:csrcs`, `:extension`. See `Membrane.RTP.Header` for their meaning and specifications. """ use Membrane.Filter alias Membrane.{Buffer, RTP, RemoteStream} @max_seq_num 65_535 @max_timestamp 0xFFFFFFFF def_input_pad :input, caps: RTP, demand_unit: :buffers def_output_pad :output, caps: {RemoteStream, type: :packetized, content_format: RTP} def_options ssrc: [spec: RTP.ssrc_t()], payload_type: [spec: RTP.payload_type_t()], clock_rate: [spec: RTP.clock_rate_t()], alignment: [ default: 1, spec: pos_integer(), description: """ Number of bytes that each packet should be aligned to. Alignment is achieved by adding RTP padding. """ ] defmodule State do @moduledoc false use Bunch.Access defstruct sequence_number: 0, init_timestamp: 0 @type t :: %__MODULE__{ sequence_number: non_neg_integer(), init_timestamp: non_neg_integer() } end @impl true def handle_init(options) do state = %State{ sequence_number: Enum.random(0..@max_seq_num), init_timestamp: Enum.random(0..@max_timestamp) } {:ok, Map.merge(Map.from_struct(options), state)} end @impl true def handle_caps(:input, _caps, _ctx, state) do caps = %RemoteStream{type: :packetized, content_format: RTP} {{:ok, caps: {:output, caps}}, state} end @impl true def handle_demand(:output, size, :buffers, _ctx, state) do {{:ok, demand: {:input, size}}, state} end @impl true def handle_process(:input, %Buffer{payload: payload, metadata: metadata}, _ctx, state) do {rtp_metadata, metadata} = Map.pop(metadata, :rtp, %{}) rtp_offset = rtp_metadata |> buffer_timestamp(metadata) |> Ratio.mult(state.clock_rate) |> Membrane.Time.to_seconds() rtp_timestamp = rem(state.init_timestamp + rtp_offset, @max_timestamp + 1) state = Map.update!(state, :sequence_number, &rem(&1 + 1, @max_seq_num + 1)) header = %{ ssrc: state.ssrc, marker: Map.get(rtp_metadata, :marker, false), payload_type: state.payload_type, timestamp: rtp_timestamp, sequence_number: state.sequence_number, csrcs: Map.get(rtp_metadata, :csrcs, []), extension: Map.get(rtp_metadata, :extension) } buffer = %Membrane.Buffer{ metadata: Map.put(metadata, :rtp, header), payload: payload } {{:ok, buffer: {:output, buffer}}, state} end defp buffer_timestamp(%{timestamp: timestamp}, _metadata), do: timestamp defp buffer_timestamp(_rtp_metadata, %{timestamp: timestamp}), do: timestamp end
lib/membrane/rtp/serializer.ex
0.892848
0.500366
serializer.ex
starcoder
defmodule Benchmarks.GoogleMessage3.Message35546.Message35547 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field35569, 5, required: true, type: :int32 field :field35570, 6, required: true, type: :int32 end defmodule Benchmarks.GoogleMessage3.Message35546.Message35548 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field35571, 11, required: true, type: :int64 field :field35572, 12, required: true, type: :int64 end defmodule Benchmarks.GoogleMessage3.Message35546 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field35556, 1, optional: true, type: :int64 field :field35557, 2, optional: true, type: :int32 field :field35558, 3, optional: true, type: :bool field :field35559, 13, optional: true, type: :int64 field :message35547, 4, optional: true, type: :group field :message35548, 10, optional: true, type: :group field :field35562, 14, optional: true, type: :bool field :field35563, 15, optional: true, type: :bool field :field35564, 16, optional: true, type: :int32 field :field35565, 17, optional: true, type: :bool field :field35566, 18, optional: true, type: :bool field :field35567, 100, optional: true, type: :string end defmodule Benchmarks.GoogleMessage3.Message2356.Message2357 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field2399, 9, optional: true, type: :int64 field :field2400, 10, optional: true, type: :int32 field :field2401, 11, optional: true, type: :int32 field :field2402, 12, optional: true, type: :int32 field :field2403, 13, optional: true, type: :int32 field :field2404, 116, optional: true, type: :int32 field :field2405, 106, optional: true, type: :int32 field :field2406, 14, required: true, type: :bytes field :field2407, 45, optional: true, type: :int32 field :field2408, 112, optional: true, type: :int32 field :field2409, 122, optional: true, type: :bool field :field2410, 124, optional: true, type: :bytes end defmodule Benchmarks.GoogleMessage3.Message2356.Message2358 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 end defmodule Benchmarks.GoogleMessage3.Message2356.Message2359 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field2413, 41, optional: true, type: :string field :field2414, 42, optional: true, type: :string field :field2415, 43, optional: true, type: :string field :field2416, 44, optional: true, type: :string field :field2417, 46, optional: true, type: :int32 field :field2418, 47, optional: true, type: :string field :field2419, 110, optional: true, type: :float field :field2420, 111, optional: true, type: :float end defmodule Benchmarks.GoogleMessage3.Message2356 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field2368, 121, optional: true, type: Benchmarks.GoogleMessage3.Message1374 field :field2369, 1, optional: true, type: :uint64 field :field2370, 2, optional: true, type: :int32 field :field2371, 17, optional: true, type: :int32 field :field2372, 3, required: true, type: :string field :field2373, 7, optional: true, type: :int32 field :field2374, 8, optional: true, type: :bytes field :field2375, 4, optional: true, type: :string field :field2376, 101, optional: true, type: :string field :field2377, 102, optional: true, type: :int32 field :field2378, 103, optional: true, type: :int32 field :field2379, 104, optional: true, type: :int32 field :field2380, 113, optional: true, type: :int32 field :field2381, 114, optional: true, type: :int32 field :field2382, 115, optional: true, type: :int32 field :field2383, 117, optional: true, type: :int32 field :field2384, 118, optional: true, type: :int32 field :field2385, 119, optional: true, type: :int32 field :field2386, 105, optional: true, type: :int32 field :field2387, 5, optional: true, type: :bytes field :message2357, 6, optional: true, type: :group field :field2389, 120, optional: true, type: :string field :message2358, 107, optional: true, type: :group field :message2359, 40, repeated: true, type: :group field :field2392, 50, optional: true, type: :int32 field :field2393, 60, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field2394, 70, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field2395, 80, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field2396, 90, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field2397, 100, optional: true, type: :string field :field2398, 123, optional: true, type: :string end defmodule Benchmarks.GoogleMessage3.Message7029.Message7030 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field7226, 14, optional: true, type: :string field :field7227, 15, optional: true, type: :string field :field7228, 16, optional: true, type: :int64 end defmodule Benchmarks.GoogleMessage3.Message7029.Message7031 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field7229, 22, optional: true, type: :string field :field7230, 23, optional: true, type: :int32 field :field7231, 24, optional: true, type: :int32 field :field7232, 30, optional: true, type: :int32 field :field7233, 31, optional: true, type: :int32 field :field7234, 35, optional: true, type: :int32 end defmodule Benchmarks.GoogleMessage3.Message7029 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field7183, 1, required: true, type: :int32 field :field7184, 2, optional: true, type: :int32 field :field7185, 3, optional: true, type: :int32 field :field7186, 4, optional: true, type: :int32 field :field7187, 5, optional: true, type: :int32 field :field7188, 6, optional: true, type: :int32 field :field7189, 17, optional: true, type: :int32 field :field7190, 18, optional: true, type: :int32 field :field7191, 49, optional: true, type: :int32 field :field7192, 28, optional: true, type: :int32 field :field7193, 33, optional: true, type: :int32 field :field7194, 25, optional: true, type: :int32 field :field7195, 26, optional: true, type: :int32 field :field7196, 40, optional: true, type: :int32 field :field7197, 41, optional: true, type: :int32 field :field7198, 42, optional: true, type: :int32 field :field7199, 43, optional: true, type: :int32 field :field7200, 19, optional: true, type: :int32 field :field7201, 7, optional: true, type: :int32 field :field7202, 8, optional: true, type: :int32 field :field7203, 9, optional: true, type: :int32 field :field7204, 10, optional: true, type: :int32 field :field7205, 11, optional: true, type: :int32 field :field7206, 12, optional: true, type: :int32 field :message7030, 13, repeated: true, type: :group field :message7031, 21, repeated: true, type: :group field :field7209, 20, optional: true, type: :int32 field :field7210, 27, optional: true, type: :float field :field7211, 29, optional: true, type: :int32 field :field7212, 32, optional: true, type: :int32 field :field7213, 48, optional: true, type: :string field :field7214, 34, optional: true, type: :bool field :field7215, 36, optional: true, type: :int32 field :field7216, 37, optional: true, type: :float field :field7217, 38, optional: true, type: :bool field :field7218, 39, optional: true, type: :bool field :field7219, 44, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field7220, 45, optional: true, type: :int32 field :field7221, 46, optional: true, type: :int32 field :field7222, 47, optional: true, type: :int32 field :field7223, 50, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field7224, 51, optional: true, type: :int32 end defmodule Benchmarks.GoogleMessage3.Message35538 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field35539, 1, required: true, type: :int64 end defmodule Benchmarks.GoogleMessage3.Message18921.Message18922 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field18959, 6, optional: true, type: :uint64 field :field18960, 13, optional: true, type: :string field :field18961, 21, optional: true, type: :bool field :field18962, 33, optional: true, type: :bool field :field18963, 7, optional: true, type: :int32 field :field18964, 8, optional: true, type: :int32 field :field18965, 9, optional: true, type: :string field :field18966, 10, optional: true, type: Benchmarks.GoogleMessage3.Message18856 field :field18967, 34, optional: true, type: :uint64 field :field18968, 11, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field18969, 35, optional: true, type: :uint64 field :field18970, 12, optional: true, type: :float field :field18971, 14, repeated: true, type: :string field :field18972, 15, optional: true, type: :bool field :field18973, 16, optional: true, type: :bool field :field18974, 22, optional: true, type: :float field :field18975, 18, optional: true, type: :int32 field :field18976, 19, optional: true, type: :int32 field :field18977, 20, optional: true, type: :int32 field :field18978, 25, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field18979, 26, optional: true, type: Benchmarks.GoogleMessage3.UnusedEnum, enum: true field :field18980, 27, repeated: true, type: :string field :field18981, 28, optional: true, type: :float end defmodule Benchmarks.GoogleMessage3.Message18921 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field18946, 1, optional: true, type: :string field :field18947, 2, optional: true, type: :fixed64 field :field18948, 3, optional: true, type: :int32 field :field18949, 4, optional: true, type: :double field :field18950, 17, optional: true, type: :bool field :field18951, 23, optional: true, type: :bool field :field18952, 24, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :message18922, 5, repeated: true, type: :group field :field18954, 29, repeated: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field18955, 30, repeated: true, type: Benchmarks.GoogleMessage3.Message18943 field :field18956, 31, repeated: true, type: Benchmarks.GoogleMessage3.Message18944 field :field18957, 32, repeated: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage end defmodule Benchmarks.GoogleMessage3.Message35540 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field35541, 1, optional: true, type: :bool end defmodule Benchmarks.GoogleMessage3.Message3886.Message3887 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field3932, 2, required: true, type: :string field :field3933, 9, optional: true, type: :string field :field3934, 3, optional: true, type: Benchmarks.GoogleMessage3.Message3850 field :field3935, 8, optional: true, type: :bytes end defmodule Benchmarks.GoogleMessage3.Message3886 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :message3887, 1, repeated: true, type: :group end defmodule Benchmarks.GoogleMessage3.Message6743 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field6759, 1, optional: true, type: Benchmarks.GoogleMessage3.Message6721 field :field6760, 2, optional: true, type: Benchmarks.GoogleMessage3.Message6723 field :field6761, 8, optional: true, type: Benchmarks.GoogleMessage3.Message6723 field :field6762, 3, optional: true, type: Benchmarks.GoogleMessage3.Message6725 field :field6763, 4, optional: true, type: Benchmarks.GoogleMessage3.Message6726 field :field6764, 5, optional: true, type: Benchmarks.GoogleMessage3.Message6733 field :field6765, 6, optional: true, type: Benchmarks.GoogleMessage3.Message6734 field :field6766, 7, optional: true, type: Benchmarks.GoogleMessage3.Message6742 end defmodule Benchmarks.GoogleMessage3.Message6773 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field6794, 1, optional: true, type: Benchmarks.GoogleMessage3.Enum6769, enum: true field :field6795, 9, optional: true, type: :int32 field :field6796, 10, optional: true, type: Benchmarks.GoogleMessage3.UnusedEnum, enum: true field :field6797, 11, optional: true, type: :int32 field :field6798, 2, optional: true, type: :int32 field :field6799, 3, optional: true, type: Benchmarks.GoogleMessage3.Enum6774, enum: true field :field6800, 5, optional: true, type: :double field :field6801, 7, optional: true, type: :double field :field6802, 8, optional: true, type: :double field :field6803, 6, optional: true, type: Benchmarks.GoogleMessage3.Enum6782, enum: true end defmodule Benchmarks.GoogleMessage3.Message8224 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field8255, 1, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field8256, 2, optional: true, type: Benchmarks.GoogleMessage3.Message8184 field :field8257, 3, optional: true, type: Benchmarks.GoogleMessage3.Message7966 field :field8258, 4, optional: true, type: :string field :field8259, 5, optional: true, type: :string field :field8260, 6, optional: true, type: :bool field :field8261, 7, optional: true, type: :int64 field :field8262, 8, optional: true, type: :string field :field8263, 9, optional: true, type: :int64 field :field8264, 10, optional: true, type: :double field :field8265, 11, optional: true, type: :int64 field :field8266, 12, repeated: true, type: :string field :field8267, 13, optional: true, type: :int64 field :field8268, 14, optional: true, type: :int32 field :field8269, 15, optional: true, type: :int32 field :field8270, 16, optional: true, type: :int64 field :field8271, 17, optional: true, type: :double field :field8272, 18, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field8273, 19, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field8274, 20, repeated: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field8275, 21, optional: true, type: :bool field :field8276, 22, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field8277, 23, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field8278, 24, repeated: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field8279, 25, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field8280, 26, optional: true, type: :bool field :field8281, 27, repeated: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage end defmodule Benchmarks.GoogleMessage3.Message8392 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field8395, 1, optional: true, type: :string field :field8396, 2, optional: true, type: :string field :field8397, 3, optional: true, type: Benchmarks.GoogleMessage3.Message7966 field :field8398, 4, optional: true, type: :string field :field8399, 5, optional: true, type: :string field :field8400, 6, optional: true, type: :string field :field8401, 7, optional: true, type: :string field :field8402, 8, optional: true, type: :string field :field8403, 9, optional: true, type: :string end defmodule Benchmarks.GoogleMessage3.Message8130 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field8156, 1, optional: true, type: :string field :field8157, 2, optional: true, type: :string field :field8158, 4, optional: true, type: :string field :field8159, 6, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field8160, 7, repeated: true, type: :string field :field8161, 8, optional: true, type: :int64 field :field8162, 9, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field8163, 10, optional: true, type: :string field :field8164, 11, optional: true, type: :string field :field8165, 12, optional: true, type: :string field :field8166, 13, optional: true, type: :string field :field8167, 14, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field8168, 15, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field8169, 16, optional: true, type: :string field :field8170, 17, optional: true, type: Benchmarks.GoogleMessage3.UnusedEnum, enum: true field :field8171, 18, optional: true, type: Benchmarks.GoogleMessage3.UnusedEnum, enum: true field :field8172, 19, optional: true, type: :bool field :field8173, 20, optional: true, type: :bool field :field8174, 21, optional: true, type: :double field :field8175, 22, optional: true, type: :int32 field :field8176, 23, optional: true, type: :int32 field :field8177, 24, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field8178, 25, repeated: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field8179, 26, repeated: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage end defmodule Benchmarks.GoogleMessage3.Message8478 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field8489, 7, optional: true, type: :string field :field8490, 1, optional: true, type: Benchmarks.GoogleMessage3.Message7966 field :field8491, 2, optional: true, type: Benchmarks.GoogleMessage3.Message8476 field :field8492, 3, optional: true, type: :int64 field :field8493, 4, optional: true, type: Benchmarks.GoogleMessage3.Message8476 field :field8494, 5, repeated: true, type: Benchmarks.GoogleMessage3.Message8477 field :field8495, 6, optional: true, type: Benchmarks.GoogleMessage3.Message8454 field :field8496, 8, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage end defmodule Benchmarks.GoogleMessage3.Message8479 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field8497, 1, optional: true, type: Benchmarks.GoogleMessage3.Message8475 field :field8498, 2, optional: true, type: Benchmarks.GoogleMessage3.Message7966 field :field8499, 3, optional: true, type: Benchmarks.GoogleMessage3.Message8476 field :field8500, 4, optional: true, type: Benchmarks.GoogleMessage3.Message8476 field :field8501, 6, optional: true, type: :string field :field8502, 7, optional: true, type: :string field :field8503, 8, optional: true, type: Benchmarks.GoogleMessage3.Message7966 field :field8504, 5, optional: true, type: Benchmarks.GoogleMessage3.Message8455 field :field8505, 9, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage end defmodule Benchmarks.GoogleMessage3.Message10319 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field10340, 1, optional: true, type: Benchmarks.GoogleMessage3.Enum10325, enum: true field :field10341, 4, optional: true, type: :int32 field :field10342, 5, optional: true, type: :int32 field :field10343, 3, optional: true, type: :bytes field :field10344, 2, optional: true, type: :string field :field10345, 6, optional: true, type: :string field :field10346, 7, optional: true, type: :string end defmodule Benchmarks.GoogleMessage3.Message4016 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field4017, 1, required: true, type: :int32 field :field4018, 2, required: true, type: :int32 field :field4019, 3, required: true, type: :int32 field :field4020, 4, required: true, type: :int32 end defmodule Benchmarks.GoogleMessage3.Message12669 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field12681, 1, optional: true, type: Benchmarks.GoogleMessage3.Message12559 field :field12682, 2, optional: true, type: :float field :field12683, 3, optional: true, type: :bool field :field12684, 4, optional: true, type: Benchmarks.GoogleMessage3.Enum12670, enum: true end defmodule Benchmarks.GoogleMessage3.Message12819 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field12834, 1, optional: true, type: :double field :field12835, 2, optional: true, type: :double field :field12836, 3, optional: true, type: :double field :field12837, 4, optional: true, type: :double field :field12838, 5, optional: true, type: :double field :field12839, 6, optional: true, type: :double end defmodule Benchmarks.GoogleMessage3.Message12820 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field12840, 1, optional: true, type: :int32 field :field12841, 2, optional: true, type: :int32 field :field12842, 3, optional: true, type: :int32 field :field12843, 8, optional: true, type: :int32 field :field12844, 4, optional: true, type: :int32 field :field12845, 5, optional: true, type: :int32 field :field12846, 6, optional: true, type: :int32 field :field12847, 7, optional: true, type: :int32 end defmodule Benchmarks.GoogleMessage3.Message12821 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field12848, 1, optional: true, type: :int32 field :field12849, 2, optional: true, type: :int32 field :field12850, 3, optional: true, type: :int32 field :field12851, 4, optional: true, type: :int32 field :field12852, 5, optional: true, type: :int32 end defmodule Benchmarks.GoogleMessage3.Message12818 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field12829, 1, optional: true, type: :uint64 field :field12830, 2, optional: true, type: :int32 field :field12831, 3, optional: true, type: :int32 field :field12832, 5, optional: true, type: :int32 field :field12833, 4, repeated: true, type: Benchmarks.GoogleMessage3.Message12817 end defmodule Benchmarks.GoogleMessage3.Message16479 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field16484, 1, optional: true, type: Benchmarks.GoogleMessage3.Message16480 field :field16485, 5, optional: true, type: :int32 field :field16486, 2, optional: true, type: :float field :field16487, 4, optional: true, type: :uint32 field :field16488, 3, optional: true, type: :bool field :field16489, 6, optional: true, type: :uint32 end defmodule Benchmarks.GoogleMessage3.Message16722 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field16752, 1, optional: true, type: :string field :field16753, 2, optional: true, type: :string field :field16754, 3, optional: true, type: :string field :field16755, 5, optional: true, type: :int32 field :field16756, 4, optional: true, type: :string end defmodule Benchmarks.GoogleMessage3.Message16724 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field16761, 1, optional: true, type: :int64 field :field16762, 2, optional: true, type: :float field :field16763, 3, optional: true, type: :int64 field :field16764, 4, optional: true, type: :int64 field :field16765, 5, optional: true, type: :bool field :field16766, 6, repeated: true, type: :string field :field16767, 7, repeated: true, type: :string field :field16768, 8, optional: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field16769, 9, optional: true, type: :bool field :field16770, 10, optional: true, type: :uint32 field :field16771, 11, optional: true, type: Benchmarks.GoogleMessage3.Enum16728, enum: true field :field16772, 12, repeated: true, type: :int32 field :field16773, 13, optional: true, type: :bool end defmodule Benchmarks.GoogleMessage3.Message17728 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 end defmodule Benchmarks.GoogleMessage3.Message24356 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field24559, 1, optional: true, type: :string field :field24560, 2, optional: true, type: :string field :field24561, 14, optional: true, type: :int32 field :field24562, 3, optional: true, type: :string field :field24563, 4, optional: true, type: :string field :field24564, 5, optional: true, type: :string field :field24565, 13, optional: true, type: Benchmarks.GoogleMessage3.UnusedEnum, enum: true field :field24566, 6, optional: true, type: :string field :field24567, 12, optional: true, type: Benchmarks.GoogleMessage3.Enum24361, enum: true field :field24568, 7, optional: true, type: :string field :field24569, 8, optional: true, type: :string field :field24570, 9, optional: true, type: :string field :field24571, 10, repeated: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field24572, 11, repeated: true, type: :string field :field24573, 15, repeated: true, type: :string end defmodule Benchmarks.GoogleMessage3.Message24376 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field24589, 1, optional: true, type: :string field :field24590, 2, optional: true, type: :string field :field24591, 3, optional: true, type: :string field :field24592, 4, required: true, type: Benchmarks.GoogleMessage3.Message24377 field :field24593, 5, optional: true, type: Benchmarks.GoogleMessage3.Message24317 field :field24594, 6, optional: true, type: :string field :field24595, 7, optional: true, type: Benchmarks.GoogleMessage3.Message24378 field :field24596, 8, repeated: true, type: :string field :field24597, 14, repeated: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field24598, 9, repeated: true, type: :string field :field24599, 10, repeated: true, type: :string field :field24600, 11, repeated: true, type: :string field :field24601, 12, optional: true, type: :string field :field24602, 13, repeated: true, type: :string end defmodule Benchmarks.GoogleMessage3.Message24366 do @moduledoc false use Protobuf, protoc_gen_elixir_version: "0.10.1-dev", syntax: :proto2 field :field24574, 1, optional: true, type: :string field :field24575, 2, optional: true, type: :string field :field24576, 3, optional: true, type: :string field :field24577, 10, optional: true, type: :int32 field :field24578, 13, optional: true, type: :string field :field24579, 4, optional: true, type: :string field :field24580, 5, optional: true, type: :string field :field24581, 9, optional: true, type: Benchmarks.GoogleMessage3.UnusedEnum, enum: true field :field24582, 14, optional: true, type: :string field :field24583, 15, optional: true, type: Benchmarks.GoogleMessage3.UnusedEnum, enum: true field :field24584, 6, optional: true, type: :string field :field24585, 12, optional: true, type: :string field :field24586, 7, repeated: true, type: Benchmarks.GoogleMessage3.UnusedEmptyMessage field :field24587, 8, repeated: true, type: :string field :field24588, 11, repeated: true, type: :string end
bench/lib/datasets/google_message3/benchmark_message3_3.pb.ex
0.571767
0.40204
benchmark_message3_3.pb.ex
starcoder
defmodule AWS.Client do @moduledoc """ Provides credentials and connection details for making requests to AWS services. You can configure `access_key_id` and `secret_access_key` which are the credentials needed by [IAM](https://aws.amazon.com/iam), and also the `region` for your services. The list of regions can be found in the [AWS service endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html) documentation. You can also use "local" to make requests to your localhost. ## Custom HTTP client The option `http_client` accepts a tuple with a module and a list of options. The module must implement the callback `c:AWS.HTTPClient.request/5`. ## Custom JSON or XML parsers You can configure a custom JSON parser by using the option `json_module`. This option accepts a tuple with a module and options. The given module must implement the callbacks from `AWS.JSON`. Similarly, there is a `xml_module` option that configures the XML parser. The XML module must implement the callbacks from `AWS.XML`. ## Additional options * `:session_token` - an option to set the `X-Amz-Security-Token` when performing the requests. * `:port` - is the port to use when making requests. Defaults to `443`. * `:proto` - is the protocol to use. It can be "http" or "https". Defaults to `"https"`. * `:endpoint` - the AWS endpoint. Defaults to `"amazonaws.com"`. You can configure this using `put_endpoint/2` for AWS compatible APIs. The `service` option is overwritten by each service with its signing name from metadata. """ defstruct access_key_id: nil, secret_access_key: nil, session_token: nil, region: nil, service: nil, endpoint: nil, proto: "https", port: 443, http_client: {AWS.HTTPClient, []}, json_module: {AWS.JSON, []}, xml_module: {AWS.XML, []} @typedoc """ The endpoint configuration. Check `put_endpoint/2` for more details. """ @type endpoint_config :: binary() | {:keep_prefixes, binary()} | (map() -> binary()) @type t :: %__MODULE__{ access_key_id: binary() | nil, secret_access_key: binary() | nil, session_token: binary() | nil, region: binary() | nil, service: binary() | nil, endpoint: endpoint_config(), proto: binary(), port: non_neg_integer(), http_client: {module(), keyword()}, json_module: {module(), keyword()}, xml_module: {module(), keyword()} } @aws_default_endpoint "amazonaws.com" @aws_access_key_id "AWS_ACCESS_KEY_ID" @aws_secret_access_key "AWS_SECRET_ACCESS_KEY" @aws_session_token "AWS_SESSION_TOKEN" @aws_default_region "AWS_DEFAULT_REGION" @doc """ The default endpoint. Check `put_endpoint/2` for more details on how to configure a custom endpoint. """ def default_endpoint, do: @aws_default_endpoint def create() do case System.get_env(@aws_default_region) do nil -> raise RuntimeError, "missing default region" region -> create(region) end end def create(region) do case {System.get_env(@aws_access_key_id), System.get_env(@aws_secret_access_key), System.get_env(@aws_session_token)} do {nil, _, _} -> raise RuntimeError, "missing access key id" {_, nil, _} -> raise RuntimeError, "missing secret access key" {access_key_id, secret_access_key, nil} -> create(access_key_id, secret_access_key, region) {access_key_id, secret_access_key, token} -> create(access_key_id, secret_access_key, token, region) end end def create(access_key_id, secret_access_key, region) do %AWS.Client{ access_key_id: access_key_id, secret_access_key: secret_access_key, region: region } end def create(access_key_id, secret_access_key, token, region) do %AWS.Client{ access_key_id: access_key_id, secret_access_key: secret_access_key, session_token: token, region: region } end @doc """ Configures the endpoint to a custom one. This is useful to set a custom endpoint when working with AWS compatible APIs. The following configuration is valid: * `"example.com"`: this will be used as it is, without considering regions or endpoint prefixes or account id. * `{:keep_prefixes, "example.com"}`: it will keep the same rules from AWS to build the prefixes. For example, if region is "us-east-1" and the service prefix is "s3", then the final endpoint will be `"s3.us-east-1.example.com"` * `fn options -> "example.com" end`: a function that will be invoked with options for that request. `options` is a map with the following shape: ``` %{ endpoint: endpoint_config(), region: binary() | nil, service: binary(), global?: boolean(), endpoint_prefix: binary(), account_id: binary() | nil } ``` ## Examples iex> put_endpoint(%Client{}, "example.com") %Client{endpoint: "example.com} iex> put_endpoint(%Client{}, {:keep_prefixes, "example.com"}) %Client{endpoint: {:keep_prefixes, "example.com}} iex> put_endpoint(%Client{}, fn opts -> Enum.join(["baz", opts.region, "foo.com"], ".") end) %Client{endpoint: #Function<>} """ def put_endpoint(%__MODULE__{} = client, endpoint_config) when is_binary(endpoint_config) or is_function(endpoint_config, 1) do %{client | endpoint: endpoint_config} end def put_endpoint(%__MODULE__{} = client, {:keep_prefixes, endpoint} = endpoint_config) when is_binary(endpoint) do %{client | endpoint: endpoint_config} end def request(client, method, url, body, headers, _opts \\ []) do {mod, options} = Map.fetch!(client, :http_client) apply(mod, :request, [method, url, body, headers, options]) end def encode!(_client, payload, :query), do: AWS.Util.encode_query(payload) def encode!(client, payload, format) do {mod, opts} = Map.fetch!(client, String.to_existing_atom("#{format}_module")) apply(mod, :encode_to_iodata!, [payload, opts]) end def decode!(client, payload, format) do {mod, opts} = Map.fetch!(client, String.to_existing_atom("#{format}_module")) apply(mod, :decode!, [payload, opts]) end end
lib/aws/client.ex
0.861596
0.485234
client.ex
starcoder
defmodule Grapevine.Telnet.Options do @moduledoc """ Parse telnet IAC options coming from the game """ alias Grapevine.Telnet.GMCP alias Grapevine.Telnet.MSSP @se 240 @nop 241 @ga 249 @sb 250 @will 251 @wont 252 @iac_do 253 @dont 254 @iac 255 @term_type 24 @line_mode 34 @charset 42 @mssp 70 @gmcp 201 @charset_request 1 @term_type_send 1 def mssp_data?(options) do Enum.any?(options, fn option -> match?({:mssp, _}, option) end) end def text_mssp?(string) do string =~ "MSSP-REPLY-START" end def get_mssp_data(options) do Enum.find(options, fn option -> match?({:mssp, _}, option) end) end @doc """ Parse binary data from a MUD into any telnet options found and known """ def parse(binary) do {options, leftover} = options(binary, <<>>, [], binary) options = options |> Enum.reject(&(&1 == <<>>)) |> Enum.map(&transform/1) string = options |> Enum.filter(&is_string?/1) |> Enum.map(&(elem(&1, 1))) |> Enum.join() options = options |> Enum.reject(&is_unknown_option?/1) |> Enum.reject(&is_string?/1) {options, string, strip_to_iac(leftover)} end defp is_unknown_option?(option), do: option == :unknown defp is_string?({:string, _}), do: true defp is_string?(_), do: false defp strip_to_iac(<<>>), do: <<>> defp strip_to_iac(<<@iac, data::binary>>), do: <<@iac>> <> data defp strip_to_iac(<<_byte::size(8), data::binary>>) do strip_to_iac(data) end @doc """ Parse options out of a binary stream """ def options(<<>>, current, stack, leftover) do {stack ++ [current], leftover} end def options(<<@iac, @sb, data::binary>>, current, stack, leftover) do case parse_sub_negotiation(<<@iac, @sb>> <> data) do :error -> options(data, current <> <<@iac, @sb>>, stack, leftover) {sub, data} -> options(data, <<>>, stack ++ [current, sub], data) end end def options(<<@iac, @will, byte::size(8), data::binary>>, current, stack, _leftover) do options(data, <<>>, stack ++ [current, <<@iac, @will, byte>>], data) end def options(<<@iac, @wont, byte::size(8), data::binary>>, current, stack, _leftover) do options(data, <<>>, stack ++ [current, <<@iac, @wont, byte>>], data) end def options(<<@iac, @iac_do, byte::size(8), data::binary>>, current, stack, _leftover) do options(data, <<>>, stack ++ [current, <<@iac, @iac_do, byte>>], data) end def options(<<@iac, @dont, byte::size(8), data::binary>>, current, stack, _leftover) do options(data, <<>>, stack ++ [current, <<@iac, @dont, byte>>], data) end def options(<<@iac, @ga, data::binary>>, current, stack, _leftover) do options(data, <<>>, stack ++ [current, <<@iac, @ga>>], data) end def options(<<@iac, @nop, data::binary>>, current, stack, _leftover) do options(data, <<>>, stack ++ [current, <<@iac, @nop>>], data) end def options(<<@iac, data::binary>>, current, stack, leftover) do options(data, <<@iac>>, stack ++ [current], leftover) end def options(<<byte::size(8), data::binary>>, current, stack, leftover) do options(data, current <> <<byte>>, stack, leftover) end @doc """ Parse sub negotiation options out of a stream """ def parse_sub_negotiation(data, stack \\ <<>>) def parse_sub_negotiation(<<>>, _stack), do: :error def parse_sub_negotiation(<<byte::size(8), @iac, @se, data::binary>>, stack) do {stack <> <<byte, @iac, @se>>, data} end def parse_sub_negotiation(<<byte::size(8), data::binary>>, stack) do parse_sub_negotiation(data, stack <> <<byte>>) end @doc """ Transform IAC binary data to actionable terms iex> Options.transform(<<255, 253, 42>>) {:do, :charset} iex> Options.transform(<<255, 253, 24>>) {:do, :term_type} iex> Options.transform(<<255, 253, 34>>) {:do, :line_mode} iex> Options.transform(<<255, 251, 42>>) {:will, :charset} iex> Options.transform(<<255, 251, 70>>) {:will, :mssp} iex> Options.transform(<<255, 252, 70>>) {:wont, :mssp} iex> Options.transform(<<255, 251, 201>>) {:will, :gmcp} Returns a generic DO/WILL if the specific term is not known. For responding with the opposite command to reject. iex> Options.transform(<<255, 251, 1>>) {:will, 1} iex> Options.transform(<<255, 252, 1>>) {:wont, 1} iex> Options.transform(<<255, 253, 1>>) {:do, 1} iex> Options.transform(<<255, 254, 1>>) {:dont, 1} Everything else is parsed as `:unknown` iex> Options.transform(<<255>>) :unknown """ def transform(<<@iac, @iac_do, @term_type>>), do: {:do, :term_type} def transform(<<@iac, @iac_do, @line_mode>>), do: {:do, :line_mode} def transform(<<@iac, @iac_do, @charset>>), do: {:do, :charset} def transform(<<@iac, @iac_do, @gmcp>>), do: {:do, :gmcp} def transform(<<@iac, @iac_do, byte>>), do: {:do, byte} def transform(<<@iac, @dont, byte>>), do: {:dont, byte} def transform(<<@iac, @will, @mssp>>), do: {:will, :mssp} def transform(<<@iac, @will, @gmcp>>), do: {:will, :gmcp} def transform(<<@iac, @will, @charset>>), do: {:will, :charset} def transform(<<@iac, @will, byte>>), do: {:will, byte} def transform(<<@iac, @wont, @mssp>>), do: {:wont, :mssp} def transform(<<@iac, @wont, byte>>), do: {:wont, byte} def transform(<<@iac, @sb, @mssp, data::binary>>) do case MSSP.parse(<<@iac, @sb, @mssp, data::binary>>) do :error -> :unknown {:ok, data} -> {:mssp, data} end end def transform(<<@iac, @sb, @term_type, @term_type_send, @iac, @se>>) do {:send, :term_type} end def transform(<<@iac, @sb, @charset, @charset_request, sep::size(8), data::binary>>) do data = parse_charset(data) {:charset, :request, <<sep>>, data} end def transform(<<@iac, @sb, @gmcp, data::binary>>) do case GMCP.parse(data) do {:ok, module, data} -> {:gmcp, module, data} :error -> :unknown end end def transform(<<@iac, @sb, _data::binary>>) do :unknown end def transform(<<@iac, @ga>>), do: {:ga} def transform(<<@iac, @nop>>), do: {:nop} def transform(<<@iac, _byte::size(8)>>), do: :unknown def transform(<<@iac>>), do: :unknown def transform(binary), do: {:string, binary} @doc """ Strip the final IAC SE from the charset """ def parse_charset(<<@iac, @se>>) do <<>> end def parse_charset(<<byte::size(8), data::binary>>) do <<byte>> <> parse_charset(data) end end
lib/grapevine/telnet/options.ex
0.679072
0.419113
options.ex
starcoder
defmodule Grizzly.ZWave.SmartStart.MetaExtension.SmartStartInclusionSetting do @moduledoc """ This extension is used to advertise the SmartStart inclusion setting of the provisioning list entry """ @typedoc """ The setting for SmartStart inclusion. This tells the controller if it must listen and/or include a node in the network when receiving SmartStart inclusion requests. - `:pending` - the node will be added to the network when it issues SmartStart inclusion requests. - `:passive` - this node is unlikely to issues a SmartStart inclusion request and SmartStart inclusion requests will be ignored from this node by the Z/IP Gateway. All nodes in the list with this setting must be updated to `:pending` when Provisioning List Iteration Get command is issued. - `:ignored` - All SmartStart inclusion request are ignored from this node until updated via Z/IP Client (Grizzly) or a controlling node. """ @behaviour Grizzly.ZWave.SmartStart.MetaExtension @type setting :: :pending | :passive | :ignored @type t :: %__MODULE__{ setting: setting() } @enforce_keys [:setting] defstruct setting: nil @spec new(setting()) :: {:ok, t()} | {:error, :invalid_setting} def new(setting) do case validate_setting(setting) do :ok -> {:ok, %__MODULE__{setting: setting}} error -> error end end @doc """ Make a `SmartStartInclusionSetting.t()` from a binary If the setting is invalid this function will return `{:error, :invalid_setting}` """ @impl true @spec to_binary(t()) :: {:ok, binary} def to_binary(%__MODULE__{setting: setting}) do setting_byte = setting_to_byte(setting) {:ok, <<0x34::size(7), 0x01::size(1), 0x01, setting_byte>>} end @doc """ Make a binary from a `SmartStartInclusionSetting.t()` If the setting is invalid this function will return `{:error, :invalid_setting}` If the binary does not have the critical bit set then this function will return `{:error, :critical_bit_not_set}` """ @impl true @spec from_binary(binary()) :: {:ok, t()} | {:error, :invalid_setting | :critical_bit_not_set | :invalid_binary} def from_binary(<<0x34::size(7), 0x01::size(1), 0x01, setting_byte>>) do case setting_from_byte(setting_byte) do {:ok, setting} -> {:ok, %__MODULE__{setting: setting}} error -> error end end def from_binary(<<0x34, 0x00::size(1), _rest::binary>>) do {:error, :critical_bit_not_set} end def from_binary(_), do: {:error, :invalid_binary} defp validate_setting(setting) when setting in [:pending, :passive, :ignored], do: :ok defp validate_setting(_), do: {:error, :invalid_setting} defp setting_to_byte(:pending), do: 0x00 defp setting_to_byte(:passive), do: 0x02 defp setting_to_byte(:ignored), do: 0x03 defp setting_from_byte(0x00), do: {:ok, :pending} defp setting_from_byte(0x02), do: {:ok, :passive} defp setting_from_byte(0x03), do: {:ok, :ignored} defp setting_from_byte(_), do: {:error, :invalid_setting} end
lib/grizzly/zwave/smart_start/meta_extension/smart_start_inclusion_setting.ex
0.888493
0.429489
smart_start_inclusion_setting.ex
starcoder
defmodule JSONC.Tokenizer do @whitespace ["\v", "\f", "\r", "\n", "\s", "\t", "\b"] @invalid_for_generics [ "{", "}", "[", "]", ",", ":", "\\", "/", "\"", "`", "'", "~", "*", "(", ")", "<", ">", "!", "?", "@", "#", "$", "%", "^", "&", "=", ";", "|" ] def peek(state) do case next(state) do {token, _} -> token end end def next(_content, _state \\ {:start, ""}) def next({"", cursor: cursor, token: _token}, {:start, ""}) do {:done, {"", cursor: cursor, token: nil}} end def next({"", cursor: {line, column} = cursor, token: _token}, {:generic, generic}) do {{handle_generic(generic), line, column}, {"", cursor: cursor, token: nil}} end def next({"", cursor: {line, column}, token: _token}, {:string, _subtype, _storage}) do {{:error, "unexpected end of input"}, {"", cursor: {line, column}, token: nil}} end def next( {<<current::utf8, rest::binary>>, cursor: {line, column}, token: token}, {:start, _} = state ) do case <<current::utf8>> do "/" when rest == "" -> {{:error, "unexpected end of input"}, {rest, cursor: {line, column}, token: nil}} "/" -> <<peeked::utf8, peeked_rest::binary>> = rest case <<peeked::utf8>> do "/" -> next( {peeked_rest, cursor: {line, column + 2}, token: {line, column}}, {:comment, :single, ""} ) "*" -> next( {peeked_rest, cursor: {line, column + 2}, token: {line, column}}, {:comment, :multi, ""} ) _ -> {{:error, "unexpected character `#{<<peeked::utf8>>}` at line #{line} column #{column}"}, {rest, cursor: {line, column}, token: nil}} end "{" -> {{{:delimiter, {:brace, :open}}, line, column}, {rest, cursor: {line, column + 1}, token: nil}} "}" -> {{{:delimiter, {:brace, :close}}, line, column}, {rest, cursor: {line, column + 1}, token: nil}} "[" -> {{{:delimiter, {:bracket, :open}}, line, column}, {rest, cursor: {line, column + 1}, token: nil}} "]" -> {{{:delimiter, {:bracket, :close}}, line, column}, {rest, cursor: {line, column + 1}, token: nil}} "," -> {{{:delimiter, :comma}, line, column}, {rest, cursor: {line, column + 1}, token: nil}} ":" -> {{{:delimiter, :colon}, line, column}, {rest, cursor: {line, column + 1}, token: nil}} "\"" -> next({rest, cursor: {line, column + 1}, token: {line, column}}, {:string, :single, ""}) "`" -> next({rest, cursor: {line, column + 1}, token: {line, column}}, {:string, :multi, ""}) "\n" -> next({rest, cursor: {line + 1, 1}, token: token}, state) ch when ch in @whitespace -> next({rest, cursor: {line, column + 1}, token: token}, state) ch when ch in @invalid_for_generics -> {{:error, "unexpected character `#{<<current::utf8>>}` at line #{line} column #{column}"}, {rest, cursor: {line, column + 1}, token: nil}} _ -> next( {"#{<<current::utf8>>}#{rest}", cursor: {line, column}, token: {line, column}}, {:generic, ""} ) end end def next( {<<current::utf8, rest::binary>>, cursor: {line, column}, token: token}, {:generic, storage} ) do case rest do "" -> {{handle_generic("#{storage}#{<<current::utf8>>}"), token |> elem(0), token |> elem(1)}, {rest, cursor: {line, column + 1}, token: nil}} _ -> <<peeked::utf8, _peeked_rest::binary>> = rest cond do <<current::utf8>> == "\n" -> {{handle_generic(storage), token |> elem(0), token |> elem(1)}, {rest, cursor: {line + 1, 1}, token: nil}} <<current::utf8>> in @whitespace -> {{handle_generic(storage), token |> elem(0), token |> elem(1)}, {rest, cursor: {line, column + 1}, token: nil}} <<peeked::utf8>> in [",", "}", "]", ":"] -> { { handle_generic("#{storage}#{<<current::utf8>>}"), token |> elem(0), token |> elem(1) }, {rest, cursor: {line, column + 1}, token: nil} } <<peeked::utf8>> in @invalid_for_generics -> {{:error, "unexpected character `#{<<peeked::utf8>>}` at line #{line} column #{column}"}, {rest, cursor: {line, column + 1}, token: nil}} true -> next( {rest, cursor: {line, column + 1}, token: token}, {:generic, "#{storage}#{<<current::utf8>>}"} ) end end end def next( {<<current::utf8, rest::binary>>, cursor: {line, column}, token: token}, {:string, subtype, storage} ) do case <<current::utf8>> do "\"" when subtype == :single -> {{{:string, {:single, storage}}, token |> elem(0), token |> elem(1)}, {rest, cursor: {line, column + 1}, token: nil}} "`" when subtype == :multi -> {{{:string, {:multi, storage}}, token |> elem(0), token |> elem(1)}, {rest, cursor: {line, column + 1}, token: nil}} "\\" when rest == "" -> {{:error, "unexpected end of input"}, {rest, cursor: {line, column}, token: nil}} "\\" -> <<peeked::utf8, peeked_rest::binary>> = rest case <<peeked::utf8>> do "n" -> next( {peeked_rest, cursor: {line, column + 2}, token: token}, {:string, subtype, "#{storage}\n"} ) "b" -> next( {peeked_rest, cursor: {line, column + 2}, token: token}, {:string, subtype, "#{storage}\b"} ) "f" -> next( {peeked_rest, cursor: {line, column + 2}, token: token}, {:string, subtype, "#{storage}\f"} ) "t" -> next( {peeked_rest, cursor: {line, column + 2}, token: token}, {:string, subtype, "#{storage}\t"} ) "r" -> next( {peeked_rest, cursor: {line, column + 2}, token: token}, {:string, subtype, "#{storage}\r"} ) "\\" -> next( {peeked_rest, cursor: {line, column + 2}, token: token}, {:string, subtype, "#{storage}\\"} ) "u" -> next( {rest, cursor: {line, column + 2}, token: token}, {:hex, subtype, storage} ) "\"" when subtype == :single -> next( {peeked_rest, cursor: {line, column + 2}, token: token}, {:string, subtype, "#{storage}\""} ) "\"" when subtype == :multi -> next( {peeked_rest, cursor: {line, column + 2}, token: token}, {:string, subtype, "#{storage}\\\""} ) _ -> {{:error, "unexpected character `#{<<peeked::utf8>>}` at line #{line} column #{column}"}, {rest, cursor: {line, column}, token: nil}} end "\n" when subtype == :single -> {{:error, "unexpected end of line at line #{line} column #{column}"}, {rest, cursor: {line + 1, 1}, token: nil}} "\n" when subtype == :multi -> next( {rest, cursor: {line + 1, 1}, token: token}, {:string, :multi, "#{storage}#{<<current::utf8>>}"} ) "\s" -> next( {rest, cursor: {line, column + 1}, token: token}, {:string, subtype, "#{storage}#{<<current::utf8>>}"} ) ch when subtype == :single and ch in @whitespace -> {{:error, "unescaped whitespace character #{current} at line #{line} column #{column}"}, {rest, cursor: {line, column}, token: nil}} _ -> next( {rest, cursor: {line, column + 1}, token: token}, {:string, subtype, "#{storage}#{<<current::utf8>>}"} ) end end def next( {<<_current::utf8, rest::binary>>, cursor: {line, column}, token: token}, {:hex, string_type, storage} ) do case rest do "" -> {{:error, "unexpected end of input"}, {rest, cursor: {line, column}, token: nil}} _ -> <<first::utf8, second::utf8, third::utf8, fourth::utf8, rest::binary>> = rest try do String.to_integer( "#{<<first::utf8>>}#{<<second::utf8>>}#{<<third::utf8>>}#{<<fourth::utf8>>}", 16 ) rescue ArgumentError -> {{:error, "invalid hex sequence #{<<first::utf8>>}#{<<second::utf8>>}#{<<third::utf8>>}#{<<fourth::utf8>>}"}, {rest, cursor: {line, column + 6}, token: nil}} else code -> next( {rest, cursor: {line, column + 6}, token: token}, {:string, string_type, "#{storage}#{<<code::utf8>>}"} ) end end end def next( {<<current::utf8, rest::binary>>, cursor: {line, column}, token: token}, {:comment, subtype, storage} ) do case rest do "" when subtype == :single -> {{{:comment, {:single, "#{storage}#{<<current::utf8>>}"}}, token |> elem(0), token |> elem(1)}, {"", cursor: {line, column + 1}, token: nil}} "" when subtype == :multi -> {{{:comment, {:multi, "#{storage}#{<<current::utf8>>}"}}, token |> elem(0), token |> elem(1)}, {"", cursor: {line, column + 1}, token: nil}} _ -> <<peeked::utf8, peeked_rest::binary>> = rest case <<current::utf8>> do "\n" when subtype == :single -> {{{:comment, {:single, storage}}, token |> elem(0), token |> elem(1)}, {rest, cursor: {line + 1, 1}, token: nil}} "\n" when subtype == :multi -> next( {rest, cursor: {line + 1, 1}, token: token}, {:comment, :multi, "#{storage}#{<<current::utf8>>}"} ) _ when <<current::utf8, peeked::utf8>> == "*/" and subtype == :multi -> {{{:comment, {:multi, storage}}, token |> elem(0), token |> elem(1)}, {peeked_rest, cursor: {line, column + 2}, token: nil}} _ -> next( {rest, cursor: {line, column + 1}, token: token}, {:comment, subtype, "#{storage}#{<<current::utf8>>}"} ) end end end defp handle_generic("true") do {:boolean, true} end defp handle_generic("false") do {:boolean, false} end defp handle_generic("null") do nil end defp handle_generic(generic) when is_binary(generic) do try do String.to_float(generic) rescue ArgumentError -> try do String.to_integer(generic) rescue ArgumentError -> case String.split(generic, "e") do [base, exponent] -> try do {String.to_integer(base), String.to_integer(exponent)} rescue ArgumentError -> {:string, {:free, generic}} else {base, exponent} -> try do String.to_float("#{base / 1}e#{exponent}") rescue ArgumentError -> {:string, {:free, generic}} else float -> {:number, {:float, float}} end end [generic] -> {:string, {:free, generic}} end else integer -> {:number, {:integer, integer}} end else float -> {:number, {:float, float}} end end end
lib/tokenizer.ex
0.590071
0.549036
tokenizer.ex
starcoder
defmodule UTM do import :math @a 6_378_137.0 @f 1 / 298.2572236 @drad pi() / 180 @k_0 0.9996 @b @a * (1 - @f) @e sqrt(1 - pow(@b / @a, 2)) @esq pow(@e, 2) @e0sq @esq / (1 - @esq) @e_1 (1 - sqrt(1 - @esq)) / (1 + sqrt(1 - @esq)) @doc """ Converts from WGS84 to UTM ## Examples: iex> UTM.from_wgs84(59.805241567229885, 11.40618711509996) %{east: 634980.0000762338, north: 6632172.011406599} iex> UTM.from_wgs84(63.50614385818526, 9.200909996819014) %{east: 5.1e5, north: 7042000.012790729} iex> UTM.from_wgs84(-31.953512, 115.857048) %{east: 391_984.4643429378, north: 6_464_146.921846279} """ @mc_1 1 - @esq * (1 / 4 + @esq * (3 / 64 + 5 / 256 * @esq)) @mc_2 @esq * (3 / 8 + @esq * (3 / 32 + 45 / 1024 * @esq)) @mc_3 pow(@esq, 2) * (15 / 256 + @esq * 45 / 1204) @mc_4 pow(@esq, 3) * 35 / 3072 def from_wgs84(lat, lon) do phi = lat * @drad zcm = 3 + 6 * (utmz(lon) - 1) - 180 n = @a / sqrt(1 - pow(@e * sin(phi), 2)) t = pow(tan(phi), 2) c = @e0sq * pow(cos(phi), 2) a = (lon - zcm) * @drad * cos(phi) x = @k_0 * n * a * (1 + pow(a, 2) * ((1 - t + c) / 6 + pow(a, 2) * (5 - 18 * t + pow(t, 2) + 72 * c - 58 * @e0sq) / 120)) + 500_000 m = phi * @mc_1 m = m - sin(2 * phi) * @mc_2 m = m + sin(4 * phi) * @mc_3 m = m - sin(6 * phi) * @mc_4 m = m * @a y = @k_0 * (m + n * tan(phi) * (pow(a, 2) * (1 / 2 + pow(a, 2) * ((5 - t + 9 * c + 4 * pow(c, 2)) / 24 + pow(a, 2) * (61 - 58 * t + pow(t, 2) + 600 * c - 330 * @e0sq) / 720)))) if y < 0 do %{east: x, north: y + 10_000_000} else %{east: x, north: y} end end @doc """ Converts from UTM to WGS84 ## Examples: iex> UTM.to_wgs84(634980.0, 6632172.0, 32, :north) %{lat: 59.805241567229885, lon: 11.40618711509996} iex> UTM.to_wgs84(510000, 7042000, 32, :north) %{lat: 63.50614385818526, lon: 9.200909996819014} iex> UTM.to_wgs84(391_984.4643429378, 6_464_146.921846279, 50, :south) %{lat: -31.95351191012423, lon: 115.8570480011093} """ def to_wgs84(e, n, zone, hemisphere) do n = case hemisphere do :south -> n - 10_000_000 :north -> n end m = n / @k_0 mu = m / (@a * @mc_1) phi_1 = mu + @e_1 * (3 / 2 - 27 / 32 * pow(@e_1, 2)) * sin(2 * mu) phi_1 = phi_1 + pow(@e_1, 2) * (21 / 16 - 55 / 32 * pow(@e_1, 2)) * sin(4 * mu) phi_1 = phi_1 + pow(@e_1, 3) * (sin(6 * mu) * 151 / 96 + @e_1 * sin(8 * mu) * 1097 / 512) c_1 = @e0sq * pow(cos(phi_1), 2) t_1 = pow(tan(phi_1), 2) n_1 = @a / sqrt(1 - pow(@e * sin(phi_1), 2)) r_1 = n_1 * (1 - @esq) / (1 - pow(@e * sin(phi_1), 2)) d = (e - 500_000) / (n_1 * @k_0) phi = pow(d, 2) * (1 / 2 - pow(d, 2) * (5 + 3 * t_1 + 10 * c_1 - 4 * pow(c_1, 2) - 9 * @e0sq) / 24) phi = phi + pow(d, 6) * (61 + 90 * t_1 + 298 * c_1 + 45 * pow(t_1, 2) - 252 * @e0sq - 3 * pow(c_1, 2)) / 720 phi = phi_1 - n_1 * tan(phi_1) / r_1 * phi lon = d * (1 + pow(d, 2) * ((-1 - 2 * t_1 - c_1) / 6 + pow(d, 2) * (5 - 2 * c_1 + 28 * t_1 - 3 * pow(c_1, 2) + 8 * @e0sq + 24 * pow(t_1, 2)) / 120)) / cos(phi_1) zcm = 3 + 6 * (zone - 1) - 180 %{lat: phi / @drad, lon: zcm + lon / @drad} end defp utmz(lon), do: 1 + Float.floor((lon + 180) / 6) end
lib/utm.ex
0.646014
0.461138
utm.ex
starcoder
defmodule Faker.Dog.PtBr do import Faker, only: [sampler: 2] @moduledoc """ Functions for Dog names, breeds and characteristics in Portuguese """ @doc """ Returns a dog name. ## Examples iex> Faker.Dog.PtBr.name() "Simba" iex> Faker.Dog.PtBr.name() "Max" iex> Faker.Dog.PtBr.name() "Malu" iex> Faker.Dog.PtBr.name() "Mike" """ @spec name() :: String.t() sampler(:name, [ "Amora", "Belinha", "Bela", "Bidu", "Billy", "Bob", "Boris", "Bruce", "Buddy", "Cacau", "Chanel", "Chico", "Cindy", "Fiona", "Fred", "Frederico", "Frida", "Iracema", "Jack", "Jade", "Kiara", "Lara", "Lili", "Lilica", "Lola", "Lua", "Luke", "Luna", "Malu", "Marley", "Max", "Maya", "Meg", "Mike", "Nick", "Nina", "Ozzy", "Pandora", "Pingo", "Princesa", "Scooby", "Simba", "Sofia", "Theo", "Thor", "Tobias", "Toddy", "Zeca", "Zeus" ]) @doc """ Returns a dog breed. ## Examples iex> Faker.Dog.PtBr.breed() "Boxer" iex> Faker.Dog.PtBr.breed() "Schnauzer" iex> Faker.Dog.PtBr.breed() "Lhasa apso" iex> Faker.Dog.PtBr.breed() "Fila brasileiro" """ @spec breed() :: String.t() sampler(:breed, [ "Akita", "B<NAME>", "Beagle", "<NAME>", "Boiadeiro australiano", "Border collie", "Boston terrier", "Boxer", "Buldogue francês", "Buldogue inglês", "Bull terrier", "Cane corso", "Cavalier king char<NAME>", "Chihuahua", "Chow chow", "Cocker spaniel inglês", "Dachshund", "Dálmata", "Doberman", "Dogo argentino", "Dogue alemão", "Fila brasileiro", "Golden retriever", "<NAME>", "<NAME>", "Labrador retriever", "Lhasa apso", "Lulu da pomerânia", "Maltês", "Mastiff inglês", "<NAME>", "<NAME>", "Pastor australiano", "Pastor de Shetland", "Pequinês", "Pinscher", "Pit bull", "Poodle", "Pug", "Rottweiler", "Schnauzer", "Shar-pei", "Shiba", "Sh<NAME>", "Staffordshire bull terrier", "Weimaraner", "Yorkshire" ]) @doc """ Returns a characteristic of a dog. ## Examples iex> Faker.Dog.PtBr.characteristic() "Atlético, protetor e amável" iex> Faker.Dog.PtBr.characteristic() "Independente, reservado e inteligente" iex> Faker.Dog.PtBr.characteristic() "Amigável, trabalhador e extrovertido" iex> Faker.Dog.PtBr.characteristic() "Calmo, leal e orgulhoso" """ @spec characteristic() :: String.t() sampler(:characteristic, [ "Alegre, carinhoso e cheio de vida", "Alegre, companheiro e aventureiro", "Amigável, inteligente e vivaz", "Amigável, trabalhador e extrovertido", "Amoroso, temperamental e companheiro", "Animado, inteligente e cheio de personalidade", "Atlético, protetor e amável", "Brincalhão, energético e esperto", "Calmo, leal e orgulhoso", "Carinhoso, brincalhão e encantador", "Carinhoso, leal e brincalhão", "Charmoso, animado e atrevido", "Companheiro, alegre e afetuoso", "Corajoso, animado e inteligente", "Destemido, carinhoso e cheio de energia", "Esperto, confiante e independente", "Gentil, brincalhão e afetuoso", "Independente, reservado e inteligente", "Inteligente, brincalhão e leal", "Leal, amigo e brincalhão", "Orgulhoso, ativo e inteligente", "Paciente, teimoso e charmoso", "Protetor, leal e inteligente", "Travesso, brincalhão e leal" ]) end
lib/faker/dog/pt_br.ex
0.66061
0.422624
pt_br.ex
starcoder
defmodule Phoenix.LiveView.Diff do @moduledoc false alias Phoenix.LiveView.{Rendered, Comprehension} # entry point # {thing_to_be_serialized, fingerprint_tree} = traverse(result, nil) # nexttime # {thing_to_be_serialized, fingerprint_tree} = traverse(result, fingerprint_tree) def render(%Rendered{} = rendered, fingerprint_tree \\ nil) do traverse(rendered, fingerprint_tree) end defp traverse(%Rendered{fingerprint: fingerprint, dynamic: dynamic}, {fingerprint, children}) do {_counter, diff, children} = traverse_dynamic(dynamic, children) {diff, {fingerprint, children}} end defp traverse(%Rendered{fingerprint: fingerprint, static: static, dynamic: dynamic}, _) do {_counter, diff, children} = traverse_dynamic(dynamic, %{}) {Map.put(diff, :static, static), {fingerprint, children}} end defp traverse(nil, fingerprint_tree) do {nil, fingerprint_tree} end defp traverse(%Comprehension{dynamics: dynamics}, :comprehension) do {%{dynamics: dynamics_to_iodata(dynamics)}, :comprehension} end defp traverse(%Comprehension{static: static, dynamics: dynamics}, nil) do {%{dynamics: dynamics_to_iodata(dynamics), static: static}, :comprehension} end defp traverse(iodata, _) do {IO.iodata_to_binary(iodata), nil} end defp traverse_dynamic(dynamic, children) do Enum.reduce(dynamic, {0, %{}, children}, fn entry, {counter, diff, children} -> {serialized, child_fingerprint} = traverse(entry, Map.get(children, counter)) diff = if serialized do Map.put(diff, counter, serialized) else diff end children = if child_fingerprint do Map.put(children, counter, child_fingerprint) else Map.delete(children, counter) end {counter + 1, diff, children} end) end defp dynamics_to_iodata(dynamics) do Enum.map(dynamics, fn list -> Enum.map(list, fn iodata -> IO.iodata_to_binary(iodata) end) end) end end
lib/phoenix_live_view/diff.ex
0.721645
0.547404
diff.ex
starcoder
defmodule Absinthe.Language do @moduledoc false alias Absinthe.Language alias __MODULE__ @type t :: Language.Argument.t() | Language.BooleanValue.t() | Language.Directive.t() | Language.Document.t() | Language.EnumTypeDefinition.t() | Language.EnumValue.t() | Language.Field.t() | Language.FieldDefinition.t() | Language.FloatValue.t() | Language.Fragment.t() | Language.FragmentSpread.t() | Language.InlineFragment.t() | Language.InputObjectTypeDefinition.t() | Language.InputValueDefinition.t() | Language.IntValue.t() | Language.InterfaceTypeDefinition.t() | Language.ListType.t() | Language.ListValue.t() | Language.NamedType.t() | Language.NonNullType.t() | Language.ObjectField.t() | Language.ObjectTypeDefinition.t() | Language.ObjectValue.t() | Language.OperationDefinition.t() | Language.ScalarTypeDefinition.t() | Language.SelectionSet.t() | Language.Source.t() | Language.StringValue.t() | Language.TypeExtensionDefinition.t() | Language.UnionTypeDefinition.t() | Language.Variable.t() | Language.VariableDefinition.t() # Value nodes @type value_t :: Language.Variable.t() | Language.IntValue.t() | Language.FloatValue.t() | Language.StringValue.t() | Language.BooleanValue.t() | Language.EnumValue.t() | Language.ListValue.t() | Language.ObjectValue.t() # Type reference nodes @type type_reference_t :: Language.NamedType.t() | Language.ListType.t() | Language.NonNullType.t() # Type definition nodes @type type_definition_t :: Language.ObjectTypeDefinition.t() | Language.InterfaceTypeDefinition.t() | Language.UnionTypeDefinition.t() | Language.ScalarTypeDefinition.t() | Language.EnumTypeDefinition.t() | Language.InputObjectTypeDefinition.t() | Language.TypeExtensionDefinition.t() @type loc_t :: %{start_line: nil | integer, end_line: nil | integer} @type input_t :: Language.BooleanValue | Language.EnumValue | Language.FloatValue | Language.IntValue | Language.ListValue | Language.ObjectValue | Language.StringValue | Language.Variable # Unwrap an AST type from a NonNullType @doc false @spec unwrap(Language.NonNullType.t() | t) :: t def unwrap(%Language.NonNullType{type: t}), do: t def unwrap(type), do: type end
lib/absinthe/language.ex
0.781831
0.470919
language.ex
starcoder
defmodule BPE.Account do @moduledoc """ `PLM.Account` is a process that handles user investments. """ require ERP require BPE require Record Record.defrecord(:close_account, []) Record.defrecord(:tx, []) def def() do BPE.process( name: :n2o.user(), flows: [ BPE.sequenceFlow(source: :Created, target: :Init), BPE.sequenceFlow(source: :Init, target: :Upload), BPE.sequenceFlow(source: :Upload, target: :Payment), BPE.sequenceFlow(source: :Payment, target: [:Signatory, :Process]), BPE.sequenceFlow(source: :Process, target: [:Process, :Final]), BPE.sequenceFlow(source: :Signatory, target: [:Process, :Final]) ], tasks: [ BPE.userTask(name: :Created, module: BPE.Account), BPE.userTask(name: :Init, module: BPE.Account), BPE.userTask(name: :Upload, module: BPE.Account), BPE.userTask(name: :Signatory, module: BPE.Account), BPE.serviceTask(name: :Payment, module: BPE.Account), BPE.serviceTask(name: :Process, module: BPE.Account), BPE.endEvent(name: :Final, module: BPE.Account) ], beginEvent: :Init, endEvent: :Final, events: [BPE.messageEvent(name: :PaymentReceived)] ) end def action({:request, :Created}, proc) do IO.inspect("First Step") {:reply, proc} end def action({:request, :Init}, proc) do IO.inspect("Second Step") {:reply, proc} end def action({:request, :Payment}, proc) do payment = :bpe.doc({:payment_notification}, proc) case payment do [] -> {:reply, :Process, BPE.process(proc, docs: [tx()])} _ -> {:reply, :Signatory, Proc} end end def action({:request, :Signatory}, proc) do {:reply, :Process, proc} end def action({:request, :Process}, proc) do case :bpe.doc(close_account(), proc) do close_account() -> {:reply, :Final, proc} _ -> {:reply, proc} end end def action({:request, :Upload}, proc), do: {:reply, proc} def action({:request, :Final}, proc), do: {:reply, proc} end
lib/actors/account.ex
0.623492
0.579698
account.ex
starcoder
defmodule Poison.ParseError do @type t :: %__MODULE__{pos: integer, value: String.t()} alias Code.Identifier defexception pos: 0, value: nil, rest: nil def message(%{value: "", pos: pos}) do "Unexpected end of input at position #{pos}" end def message(%{value: <<token::utf8>>, pos: pos}) do "Unexpected token at position #{pos}: #{escape(token)}" end def message(%{value: value, pos: pos}) when is_binary(value) do start = pos - String.length(value) "Cannot parse value at position #{start}: #{inspect(value)}" end def message(%{value: value}) do "Unsupported value: #{inspect(value)}" end defp escape(token) do {value, _} = Identifier.escape(<<token::utf8>>, ?\\) value end end defmodule Poison.Parser do @moduledoc """ An RFC 7159 and ECMA 404 conforming JSON parser. See: https://tools.ietf.org/html/rfc7159 See: http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf """ @compile :inline @compile {:inline_size, 256} if Application.get_env(:poison, :native) do @compile [:native, {:hipe, [:o3]}] end use Bitwise alias Poison.ParseError @type t :: nil | true | false | list | float | integer | String.t() | map defmacrop stacktrace do if Version.compare(System.version(), "1.7.0") != :lt do quote do: __STACKTRACE__ else quote do: System.stacktrace() end end def parse!(iodata, options) do string = IO.iodata_to_binary(iodata) keys = Map.get(options, :keys) {rest, pos} = skip_whitespace(skip_bom(string), 0) {value, pos, rest} = value(rest, pos, keys) case skip_whitespace(rest, pos) do {"", _pos} -> value {other, pos} -> syntax_error(other, pos) end rescue ArgumentError -> reraise %ParseError{value: iodata}, stacktrace() end defp value("\"" <> rest, pos, _keys) do string_continue(rest, pos + 1, []) end defp value("{" <> rest, pos, keys) do {rest, pos} = skip_whitespace(rest, pos + 1) object_pairs(rest, pos, keys, []) end defp value("[" <> rest, pos, keys) do {rest, pos} = skip_whitespace(rest, pos + 1) array_values(rest, pos, keys, []) end defp value("null" <> rest, pos, _keys), do: {nil, pos + 4, rest} defp value("true" <> rest, pos, _keys), do: {true, pos + 4, rest} defp value("false" <> rest, pos, _keys), do: {false, pos + 5, rest} defp value(<<char, _::binary>> = string, pos, _keys) when char in '-0123456789' do number_start(string, pos) end defp value(other, pos, _keys), do: syntax_error(other, pos) ## Objects defp object_pairs("\"" <> rest, pos, keys, acc) do {name, pos, rest} = string_continue(rest, pos + 1, []) {value, start, pos, rest} = case skip_whitespace(rest, pos) do {":" <> rest, start} -> {rest, pos} = skip_whitespace(rest, start + 1) {value, pos, rest} = value(rest, pos, keys) {value, start, pos, rest} {other, pos} -> syntax_error(other, pos) end acc = [{object_name(name, start, keys), value} | acc] case skip_whitespace(rest, pos) do {"," <> rest, pos} -> {rest, pos} = skip_whitespace(rest, pos + 1) object_pairs(rest, pos, keys, acc) {"}" <> rest, pos} -> {:maps.from_list(acc), pos + 1, rest} {other, pos} -> syntax_error(other, pos) end end defp object_pairs("}" <> rest, pos, _, []) do {:maps.new(), pos + 1, rest} end defp object_pairs(other, pos, _, _), do: syntax_error(other, pos) defp object_name(name, pos, :atoms!) do String.to_existing_atom(name) rescue ArgumentError -> reraise %ParseError{value: name, pos: pos}, stacktrace() end defp object_name(name, _pos, :atoms), do: String.to_atom(name) defp object_name(name, _pos, _keys), do: name ## Arrays defp array_values("]" <> rest, pos, _, []) do {[], pos + 1, rest} end defp array_values(string, pos, keys, acc) do {value, pos, rest} = value(string, pos, keys) acc = [value | acc] case skip_whitespace(rest, pos) do {"," <> rest, pos} -> {rest, pos} = skip_whitespace(rest, pos + 1) array_values(rest, pos, keys, acc) {"]" <> rest, pos} -> {:lists.reverse(acc), pos + 1, rest} {other, pos} -> syntax_error(other, pos) end end ## Numbers defp number_start("-" <> rest, pos) do case rest do "0" <> rest -> number_frac(rest, pos + 2, ["-0"]) rest -> number_int(rest, pos + 1, [?-]) end end defp number_start("0" <> rest, pos) do number_frac(rest, pos + 1, [?0]) end defp number_start(string, pos) do number_int(string, pos, []) end defp number_int(<<char, _::binary>> = string, pos, acc) when char in '123456789' do {digits, pos, rest} = number_digits(string, pos) number_frac(rest, pos, [acc, digits]) end defp number_int(other, pos, _), do: syntax_error(other, pos) defp number_frac("." <> rest, pos, acc) do {digits, pos, rest} = number_digits(rest, pos + 1) number_exp(rest, true, pos, [acc, ?., digits]) end defp number_frac(string, pos, acc) do number_exp(string, false, pos, acc) end defp number_exp(<<e>> <> rest, frac, pos, acc) when e in 'eE' do e = if frac, do: ?e, else: ".0e" case rest do "-" <> rest -> number_exp_continue(rest, frac, pos + 2, [acc, e, ?-]) "+" <> rest -> number_exp_continue(rest, frac, pos + 2, [acc, e]) rest -> number_exp_continue(rest, frac, pos + 1, [acc, e]) end end defp number_exp(string, frac, pos, acc) do {number_complete(acc, frac, pos), pos, string} end defp number_exp_continue(rest, frac, pos, acc) do {digits, pos, rest} = number_digits(rest, pos) pos = if frac, do: pos, else: pos + 2 {number_complete([acc, digits], true, pos), pos, rest} end defp number_complete(iolist, false, _pos) do iolist |> IO.iodata_to_binary() |> String.to_integer() end defp number_complete(iolist, true, pos) do iolist |> IO.iodata_to_binary() |> String.to_float() rescue ArgumentError -> value = iolist |> IO.iodata_to_binary() reraise %ParseError{pos: pos, value: value}, stacktrace() end defp number_digits(<<char>> <> rest = string, pos) when char in '0123456789' do count = number_digits_count(rest, 1) <<digits::binary-size(count), rest::binary>> = string {digits, pos + count, rest} end defp number_digits(other, pos), do: syntax_error(other, pos) defp number_digits_count(<<char>> <> rest, acc) when char in '0123456789' do number_digits_count(rest, acc + 1) end defp number_digits_count(_, acc), do: acc ## Strings defp string_continue("\"" <> rest, pos, acc) do {IO.iodata_to_binary(acc), pos + 1, rest} end defp string_continue("\\" <> rest, pos, acc) do string_escape(rest, pos, acc) end defp string_continue("", pos, _), do: syntax_error(nil, pos) defp string_continue(string, pos, acc) do {count, pos} = string_chunk_size(string, pos, 0) <<chunk::binary-size(count), rest::binary>> = string string_continue(rest, pos, [acc, chunk]) end for {seq, char} <- Enum.zip('"\\ntr/fb', '"\\\n\t\r/\f\b') do defp string_escape(<<unquote(seq)>> <> rest, pos, acc) do string_continue(rest, pos + 1, [acc, unquote(char)]) end end defguardp is_surrogate(a1, a2, b1, b2) when a1 in 'dD' and a2 in 'dD' and b1 in '89abAB' and (b2 in ?c..?f or b2 in ?C..?F) # http://www.ietf.org/rfc/rfc2781.txt # http://perldoc.perl.org/Encode/Unicode.html#Surrogate-Pairs # http://mathiasbynens.be/notes/javascript-encoding#surrogate-pairs defp string_escape( <<?u, a1, b1, c1, d1, "\\u", a2, b2, c2, d2>> <> rest, pos, acc ) when is_surrogate(a1, a2, b1, b2) do hi = List.to_integer([a1, b1, c1, d1], 16) lo = List.to_integer([a2, b2, c2, d2], 16) codepoint = 0x10000 + ((hi &&& 0x03FF) <<< 10) + (lo &&& 0x03FF) string_continue(rest, pos + 11, [acc, <<codepoint::utf8>>]) rescue ArgumentError -> value = <<"\\u", a1, b1, c1, d1, "\\u", a2, b2, c2, d2>> reraise %ParseError{pos: pos + 12, value: value}, stacktrace() end defp string_escape(<<?u, seq::binary-size(4)>> <> rest, pos, acc) do code = String.to_integer(seq, 16) string_continue(rest, pos + 5, [acc, <<code::utf8>>]) rescue ArgumentError -> value = "\\u" <> seq reraise %ParseError{pos: pos + 6, value: value}, stacktrace() end defp string_escape(other, pos, _), do: syntax_error(other, pos) defp string_chunk_size("\"" <> _, pos, acc), do: {acc, pos} defp string_chunk_size("\\" <> _, pos, acc), do: {acc, pos} # Control Characters (http://seriot.ch/parsing_json.php#25) defp string_chunk_size(<<char>> <> _rest, pos, _acc) when char <= 0x1F do syntax_error(<<char>>, pos) end defp string_chunk_size(<<char>> <> rest, pos, acc) when char < 0x80 do string_chunk_size(rest, pos + 1, acc + 1) end defp string_chunk_size(<<codepoint::utf8>> <> rest, pos, acc) do string_chunk_size(rest, pos + 1, acc + string_codepoint_size(codepoint)) end defp string_chunk_size(other, pos, _acc), do: syntax_error(other, pos) defp string_codepoint_size(codepoint) when codepoint < 0x800, do: 2 defp string_codepoint_size(codepoint) when codepoint < 0x10000, do: 3 defp string_codepoint_size(_), do: 4 ## Whitespace defp skip_whitespace(<<char>> <> rest, pos) when char in '\s\n\t\r' do skip_whitespace(rest, pos + 1) end defp skip_whitespace(string, pos), do: {string, pos} # https://tools.ietf.org/html/rfc7159#section-8.1 # https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8 defp skip_bom(<<0xEF, 0xBB, 0xBF>> <> rest) do rest end defp skip_bom(string) do string end ## Errors defp syntax_error(<<token::utf8>> <> _, pos) do raise %ParseError{pos: pos, value: <<token::utf8>>} end defp syntax_error(_, pos) do raise %ParseError{pos: pos, value: ""} end end
lib/poison/parser.ex
0.607197
0.595551
parser.ex
starcoder
defmodule ExBreak do @moduledoc """ Provides circuit breaker functionality around function calls """ alias ExBreak.Breaker @type opt :: {:timeout_sec, pos_integer} | {:threshold, pos_integer} | {:match_exception, (any -> boolean)} | {:match_return, (any -> boolean)} | {:on_trip, (Breaker.t() -> any)} @type opts :: [opt] @default_opts [timeout_sec: 60 * 15, threshold: 10] @doc """ Call a function using a circuit breaker. The first option is the function to call, followed by an optional list of arguments. If the function succeeds, and does not return an error tuple (in the form `{:error, any}`), the value returned by the function will be returned. If the function fails (meaning it returns an `{:error, any}` tuple), a counter is incremented in a circuit breaker for that function. If the counter meets or exceeds the configured circuit breaker threshold, the breaker for that function is marked as tripped. If the function fails and the circuit breaker for that function has been marked as tripped (and has not expired), then `{:error, :circuit_breaker_tripped}` will be returned. A list of options can be provided as the final argument to `call`: - `timeout_sec` (default `900`) The number of seconds after which a tripped breaker times out and is re-opened - `threshold` (default `10`) The number of times an error is permitted before further calls will be ignored and will return an `{:error, :circuilt_closed}` - `match_exception` (default `fn _ -> true end`) A function called when an exception is raised during the function call. If it returns true, the breaker trip count is incremented. - `match_return` (defaults to return `true` when matching `{:error, _}`) A function called on the return value of the function. If it returns `true`, the breaker trip count is incremented. - `on_trip` (defaults to `nil`) A function called with the tripped breaker as an argument when the breaker was tripped ## Example This simple example increments the breaker when the return value is `{:error, _}`: iex> ExBreak.call(fn ret -> ret end, [:ok]) :ok iex> fun = fn -> {:error, :fail} end iex> ExBreak.call(fun, [], threshold: 2) {:error, :fail} iex> ExBreak.call(fun, [], threshold: 2) {:error, :fail} iex> ExBreak.call(fun, [], threshold: 2) {:error, :circuit_breaker_tripped} In this example, we only increment when the return value is exactly `{:error, :bad}`: iex> fun = fn ret -> ret end iex> opts = [threshold: 2, match_return: fn ...> {:error, :bad} -> true ...> _ -> false ...> end] iex> ExBreak.call(fun, [{:error, :not_bad}], opts) {:error, :not_bad} iex> ExBreak.call(fun, [{:error, :not_bad}], opts) {:error, :not_bad} iex> ExBreak.call(fun, [{:error, :not_bad}], opts) {:error, :not_bad} iex> ExBreak.call(fun, [{:error, :bad}], opts) {:error, :bad} iex> ExBreak.call(fun, [{:error, :bad}], opts) {:error, :bad} iex> ExBreak.call(fun, [{:error, :bad}], opts) {:error, :circuit_breaker_tripped} """ @spec call(function, [any], opts) :: any def call(fun, args \\ [], opts \\ []) do opts = Keyword.merge(@default_opts, opts) lookup(fun, fn pid -> if Breaker.is_tripped(pid, opts[:timeout_sec]) do {:error, :circuit_breaker_tripped} else Breaker.reset_tripped(pid) call_func(fun, args, opts) end end) end # Rewinds a breaker's tripped_at time for testing. @doc false @spec rewind_trip(function, integer) :: :ok def rewind_trip(fun, rewind_sec) do lookup(fun, fn pid -> Agent.update(pid, fn breaker -> tripped_at = DateTime.add(breaker.tripped_at, -rewind_sec, :second) Map.put(breaker, :tripped_at, tripped_at) end) end) end defp lookup(fun, callback) do case ExBreak.Registry.get_breaker(fun) do {:ok, pid} -> callback.(pid) error -> error end end defp call_func(fun, args, opts) do match_exception = Keyword.get(opts, :match_exception, fn _ -> true end) match_return = Keyword.get(opts, :match_return, fn ret -> match?({:error, _}, ret) end) try do apply(fun, args) rescue exception -> if match_exception.(exception) do increment_breaker(fun, opts) end reraise exception, __STACKTRACE__ else return -> if match_return.(return) do increment_breaker(fun, opts) return else reset_breaker(fun) return end end end defp increment_breaker(fun, opts) do lookup(fun, &Breaker.increment(&1, opts[:threshold], opts[:on_trip])) end defp reset_breaker(fun) do lookup(fun, &Breaker.reset_tripped/1) end end
lib/ex_break.ex
0.856332
0.604428
ex_break.ex
starcoder
defmodule SlackLoggerBackend do @moduledoc """ A logger backend for posting errors to Slack. You can find the hex package [here](https://hex.pm/packages/slack_logger_backend), and the docs [here](http://hexdocs.pm/slack_logger_backend). ## Usage First, add the client to your `mix.exs` dependencies: ```elixir def deps do [{:slack_logger_backend, "~> 0.2.0"}] end ``` Then run `$ mix do deps.get, compile` to download and compile your dependencies. Finally, add `SlackLoggerBackend.Logger` to your list of logging backends in your app's config: ```elixir config :logger, backends: [:console, {SlackLoggerBackend.Logger, :error}] ``` You'll need to create a custom incoming webhook URL for your Slack team. You can either configure the webhook in your config: ```elixir config :slack_logger_backend, :slack, [url: "http://example.com"] ``` You can also put the webhook URL in the `SLACK_LOGGER_WEBHOOK_URL` environment variable. If you have both the environment variable will take priority. If you want to prevent the same message from being spammed in the slack channel you can set a debounce, which will send the message with a count of the number of occurances of the message within the debounce period: ``` config :slack_logger_backend, debounce_seconds: 300 ``` An optional field labeled "Deployment" is availiable in the Slack messages. This is useful if you have multiple deployments send messages to the same Slack thread. This value can be set in config (see below) or using the environment variable `SLACK_LOGGER_DEPLOYMENT_NAME`. The environment variable will take priority. ``` config :slack_logger_backend, deployment_name: "example deployment", ``` """ use Application alias SlackLoggerBackend.{Pool, Formatter, Producer, Consumer} @doc false def start(_type, _args) do children = [ Producer, {Formatter, [10, 5]}, {Consumer, [10, 5]}, {Pool, [10]} ] opts = [strategy: :one_for_one, name: SlackLoggerBackend.Supervisor] Supervisor.start_link(children, opts) end @doc false def stop(_args) do # noop end end
lib/slack_logger_backend.ex
0.821903
0.828592
slack_logger_backend.ex
starcoder
defmodule ElixirLokaliseApi.Processor do @moduledoc """ Performs processing of user-supplied data and data returned by the API. """ @pagination_headers %{ "x-pagination-total-count" => :total_count, "x-pagination-page-count" => :page_count, "x-pagination-limit" => :per_page_limit, "x-pagination-page" => :current_page } @doc """ Encodes user-supplied data sent to the API. """ def encode(nil), do: "" def encode(data), do: Jason.encode!(data) @doc """ Parses data returned by the API. It can return a model, a collection, and a raw response. All returned values are represented as tuples with two elements (`:ok` and the actual data): {:ok, data} = ElixirLokaliseApi.Projects.find(project_id) If an error is raised by the API, the returned tuple contains an `:error` atom, the error details, and the HTTP status code: {:error, error, status} = ElixirLokaliseApi.Projects.find(nil) """ def parse(response, module, type) do data_key = module.data_key singular_data_key = module.singular_data_key json = response.body |> Jason.decode!(keys: :atoms) status = response.status_code case json do raw_data when type == :raw and status < 400 -> {:ok, raw_data} data when type == :foreign_model and status < 400 -> {:ok, create_struct(:foreign_model, module, data)} %{^data_key => items_data} when (is_list(items_data) or is_map(items_data)) and status < 400 -> {:ok, create_struct(:collection, module, items_data, response.headers, json)} %{^singular_data_key => item_data} when (is_list(item_data) or is_map(item_data)) and status < 400 -> {:ok, create_struct(:model, module, item_data)} item_data when status < 400 -> {:ok, create_struct(:model, module, item_data)} raw_data -> {:error, raw_data, status} end end defp create_struct(:foreign_model, module, raw_data) do foreign_model = module.foreign_model case module.foreign_data_key do nil -> foreign_model |> struct(raw_data) key -> foreign_model |> struct(raw_data[key]) end end defp create_struct(:model, module, item_data), do: struct(module.model, item_data) defp create_struct(:collection, module, items_data, resp_headers, raw_json) do struct_data = struct_for_items(module, items_data) |> add_data_by_key(module.parent_key, raw_json) |> add_data_by_key(:branch, raw_json) |> add_data_by_key(:user_id, raw_json) |> add_data_by_key(:errors, raw_json) |> pagination_for(resp_headers) module.collection |> struct(struct_data) end defp struct_for_items(module, raw_data) do Enum.reduce(Enum.reverse(raw_data), %{items: []}, fn item, acc -> struct_item = struct(module.model, item) %{acc | items: [struct_item | acc.items]} end) end defp pagination_for(struct_data, resp_headers) do Enum.reduce(@pagination_headers, struct_data, fn {raw_header, formatted_header}, acc -> case get_header(resp_headers, raw_header) do [] -> acc [list | _] -> {header_value, _} = list |> elem(1) |> Integer.parse() acc |> Map.put(formatted_header, header_value) end end) end defp get_header(headers, key) do headers |> Enum.filter(fn {k, _} -> String.downcase(k) == to_string(key) end) end defp add_data_by_key(struct_data, key, raw_json) do case raw_json[key] do nil -> struct_data value -> struct_data |> Map.put(key, value) end end end
lib/elixir_lokalise_api/processor.ex
0.721743
0.487734
processor.ex
starcoder