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 :queue do # Types @type queue :: queue(_) # Functions @spec cons(item, q1 :: queue(item)) :: q2 :: queue(item) def cons(x, q), do: in_r(x, q) @spec daeh(q :: queue(item)) :: item def daeh(q), do: get_r(q) @spec drop(q1 :: queue(item)) :: q2 :: queue(item) def drop({[], []} = q), do: :erlang.error(:empty, [q]) def drop({[_], []}), do: {[], []} def drop({[y | r], []}) do [_ | f] = :lists.reverse(r, []) {[y], f} end def drop({r, [_]}) when is_list(r), do: r2f(r) def drop({r, [_ | f]}) when is_list(r), do: {r, f} def drop(q), do: :erlang.error(:badarg, [q]) @spec drop_r(q1 :: queue(item)) :: q2 :: queue(item) def drop_r({[], []} = q), do: :erlang.error(:empty, [q]) def drop_r({[], [_]}), do: {[], []} def drop_r({[], [y | f]}) do [_ | r] = :lists.reverse(f, []) {r, [y]} end def drop_r({[_], f}) when is_list(f), do: f2r(f) def drop_r({[_ | r], f}) when is_list(f), do: {r, f} def drop_r(q), do: :erlang.error(:badarg, [q]) @spec filter(fun, q1 :: queue(item)) :: q2 :: queue(item) when fun: (item -> (boolean() | [item])) def filter(fun, {r0, f0}) when is_function(fun, 1) and is_list(r0) and is_list(f0) do f = filter_f(fun, f0) r = filter_r(fun, r0) cond do r === [] -> f2r(f) f === [] -> r2f(r) true -> {r, f} end end def filter(fun, q), do: :erlang.error(:badarg, [fun, q]) @spec from_list(l :: [item]) :: queue(item) def from_list(l) when is_list(l), do: f2r(l) def from_list(l), do: :erlang.error(:badarg, [l]) @spec get(q :: queue(item)) :: item def get({[], []} = q), do: :erlang.error(:empty, [q]) def get({r, f}) when is_list(r) and is_list(f), do: get(r, f) def get(q), do: :erlang.error(:badarg, [q]) @spec get_r(q :: queue(item)) :: item def get_r({[], []} = q), do: :erlang.error(:empty, [q]) def get_r({[h | _], f}) when is_list(f), do: h def get_r({[], [h]}), do: h def get_r({[], [_ | f]}), do: :lists.last(f) def get_r(q), do: :erlang.error(:badarg, [q]) @spec head(q :: queue(item)) :: item def head({[], []} = q), do: :erlang.error(:empty, [q]) def head({r, f}) when is_list(r) and is_list(f), do: get(r, f) def head(q), do: :erlang.error(:badarg, [q]) @spec unquote(:in)(item, q1 :: queue(item)) :: q2 :: queue(item) def unquote(:in)(x, {[_] = erlangVariableIn, []}), do: {[x], erlangVariableIn} def unquote(:in)(x, {erlangVariableIn, out}) when is_list(erlangVariableIn) and is_list(out), do: {[x | erlangVariableIn], out} def unquote(:in)(x, q), do: :erlang.error(:badarg, [x, q]) @spec in_r(item, q1 :: queue(item)) :: q2 :: queue(item) def in_r(x, {[], [_] = f}), do: {f, [x]} def in_r(x, {r, f}) when is_list(r) and is_list(f), do: {r, [x | f]} def in_r(x, q), do: :erlang.error(:badarg, [x, q]) @spec init(q1 :: queue(item)) :: q2 :: queue(item) def init(q), do: drop_r(q) @spec is_empty(q :: queue()) :: boolean() def is_empty({[], []}), do: true def is_empty({erlangVariableIn, out}) when is_list(erlangVariableIn) and is_list(out), do: false def is_empty(q), do: :erlang.error(:badarg, [q]) @spec is_queue(term :: term()) :: boolean() def is_queue({r, f}) when is_list(r) and is_list(f), do: true def is_queue(_), do: false @spec join(q1 :: queue(item), q2 :: queue(item)) :: q3 :: queue(item) def join({r, f} = q, {[], []}) when is_list(r) and is_list(f), do: q def join({[], []}, {r, f} = q) when is_list(r) and is_list(f), do: q def join({r1, f1}, {r2, f2}) when is_list(r1) and is_list(f1) and is_list(r2) and is_list(f2), do: {r2, f1 ++ :lists.reverse(r1, f2)} def join(q1, q2), do: :erlang.error(:badarg, [q1, q2]) @spec lait(q1 :: queue(item)) :: q2 :: queue(item) def lait(q), do: drop_r(q) @spec last(q :: queue(item)) :: item def last(q), do: get_r(q) @spec len(q :: queue()) :: non_neg_integer() def len({r, f}) when is_list(r) and is_list(f), do: length(r) + length(f) def len(q), do: :erlang.error(:badarg, [q]) @spec liat(q1 :: queue(item)) :: q2 :: queue(item) def liat(q), do: drop_r(q) @spec member(item, q :: queue(item)) :: boolean() def member(x, {r, f}) when is_list(r) and is_list(f), do: :lists.member(x, r) or :lists.member(x, f) def member(x, q), do: :erlang.error(:badarg, [x, q]) def module_info() do # body not decompiled end def module_info(p0) do # body not decompiled end @spec new() :: queue() def new(), do: {[], []} @spec out(q1 :: queue(item)) :: ({{:value, item}, q2 :: queue(item)} | {:empty, q1 :: queue(item)}) def out({[], []} = q), do: {:empty, q} def out({[v], []}), do: {{:value, v}, {[], []}} def out({[y | erlangVariableIn], []}) do [v | out] = :lists.reverse(erlangVariableIn, []) {{:value, v}, {[y], out}} end def out({erlangVariableIn, [v]}) when is_list(erlangVariableIn), do: {{:value, v}, r2f(erlangVariableIn)} def out({erlangVariableIn, [v | out]}) when is_list(erlangVariableIn), do: {{:value, v}, {erlangVariableIn, out}} def out(q), do: :erlang.error(:badarg, [q]) @spec out_r(q1 :: queue(item)) :: ({{:value, item}, q2 :: queue(item)} | {:empty, q1 :: queue(item)}) def out_r({[], []} = q), do: {:empty, q} def out_r({[], [v]}), do: {{:value, v}, {[], []}} def out_r({[], [y | out]}) do [v | erlangVariableIn] = :lists.reverse(out, []) {{:value, v}, {erlangVariableIn, [y]}} end def out_r({[v], out}) when is_list(out), do: {{:value, v}, f2r(out)} def out_r({[v | erlangVariableIn], out}) when is_list(out), do: {{:value, v}, {erlangVariableIn, out}} def out_r(q), do: :erlang.error(:badarg, [q]) @spec peek(q :: queue(item)) :: (:empty | {:value, item}) def peek({[], []}), do: :empty def peek({r, [h | _]}) when is_list(r), do: {:value, h} def peek({[h], []}), do: {:value, h} def peek({[_ | r], []}), do: {:value, :lists.last(r)} def peek(q), do: :erlang.error(:badarg, [q]) @spec peek_r(q :: queue(item)) :: (:empty | {:value, item}) def peek_r({[], []}), do: :empty def peek_r({[h | _], f}) when is_list(f), do: {:value, h} def peek_r({[], [h]}), do: {:value, h} def peek_r({[], [_ | r]}), do: {:value, :lists.last(r)} def peek_r(q), do: :erlang.error(:badarg, [q]) @spec reverse(q1 :: queue(item)) :: q2 :: queue(item) def reverse({r, f}) when is_list(r) and is_list(f), do: {f, r} def reverse(q), do: :erlang.error(:badarg, [q]) @spec snoc(q1 :: queue(item), item) :: q2 :: queue(item) def snoc(q, x), do: apply(__MODULE__, :in, [x, q]) @spec split(n :: non_neg_integer(), q1 :: queue(item)) :: {q2 :: queue(item), q3 :: queue(item)} def split(0, {r, f} = q) when is_list(r) and is_list(f), do: {{[], []}, q} def split(n, {r, f} = q) when is_integer(n) and n >= 1 and is_list(r) and is_list(f) do lf = :erlang.length(f) cond do n < lf -> [x | f1] = f split_f1_to_r2(n - 1, r, f1, [], [x]) n > lf -> lr = length(r) m = lr - n - lf cond do m < 0 -> :erlang.error(:badarg, [n, q]) m > 0 -> [x | r1] = r split_r1_to_f2(m - 1, r1, f, [x], []) true -> {q, {[], []}} end true -> {f2r(f), r2f(r)} end end def split(n, q), do: :erlang.error(:badarg, [n, q]) @spec tail(q1 :: queue(item)) :: q2 :: queue(item) def tail(q), do: drop(q) @spec to_list(q :: queue(item)) :: [item] def to_list({erlangVariableIn, out}) when is_list(erlangVariableIn) and is_list(out), do: out ++ :lists.reverse(erlangVariableIn, []) def to_list(q), do: :erlang.error(:badarg, [q]) # Private Functions def filter_f(_, []), do: [] def filter_f(fun, [x | f]) do case fun.(x) do true -> [x | filter_f(fun, f)] false -> filter_f(fun, f) l when is_list(l) -> l ++ filter_f(fun, f) end end def filter_r(_, []), do: [] def filter_r(fun, [x | r0]) do r = filter_r(fun, r0) case fun.(x) do true -> [x | r] false -> r l when is_list(l) -> :lists.reverse(l, r) end end @spec get([], []) :: term() def get(r, [h | _]) when is_list(r), do: h def get([h], []), do: h def get([_ | r], []), do: :lists.last(r) def split_f1_to_r2(0, r1, f1, r2, f2), do: {{r2, f2}, {r1, f1}} def split_f1_to_r2(n, r1, [x | f1], r2, f2), do: split_f1_to_r2(n - 1, r1, f1, [x | r2], f2) def split_r1_to_f2(0, r1, f1, r2, f2), do: {{r1, f1}, {r2, f2}} def split_r1_to_f2(n, [x | r1], f1, r2, f2), do: split_r1_to_f2(n - 1, r1, f1, r2, [x | f2]) end
testData/org/elixir_lang/beam/decompiler/queue.ex
0.808559
0.481088
queue.ex
starcoder
defmodule Clickhousex.Codec.Values do alias Clickhousex.Query def encode(%Query{param_count: 0, type: :insert}, _, []) do # An insert query's arguments go into the post body and the query part goes into the query string. # If we don't have any arguments, we don't have to encode anything, but we don't want to return # anything here because we'll duplicate the query into both the query string and post body "" end def encode(%Query{param_count: 0, statement: statement}, _, []) do statement end def encode(%Query{param_count: 0}, _, _) do raise ArgumentError, "Extra params! Query doesn't contain '?'" end def encode(%Query{param_count: param_count} = query, query_text, params) do query_parts = String.split(query_text, "?") weave(query, query_parts, params, param_count) end defp weave(query, [part | parts], [param | params], param_count) do [part, encode_param(query, param) | weave(query, parts, params, param_count - 1)] end defp weave(_query, [_] = parts, [], 1), do: parts defp weave(_query, [_], [], _) do raise ArgumentError, "The number of parameters does not correspond to the number of question marks!" end defp encode_param(query, param) when is_list(param) do values = Enum.map_join(param, ",", &encode_param(query, &1)) case query do # We pass lists to in clauses, and they shouldn't have brackets around them. %{type: :select} -> values _ -> "[#{values}]" end end defp encode_param(_query, param) when is_integer(param) do Integer.to_string(param) end defp encode_param(_query, true), do: "1" defp encode_param(_query, false), do: "0" defp encode_param(_query, param) when is_float(param) do to_string(param) end defp encode_param(_query, nil), do: "NULL" defp encode_param(%{codec: Clickhousex.Codec.RowBinary}, %DateTime{} = dt) do DateTime.to_unix(dt) end defp encode_param(_query, %DateTime{} = datetime) do iso_date = DateTime.truncate(datetime, :second) "'#{Date.to_string iso_date} #{Time.to_string iso_date}'" end defp encode_param(_query, %NaiveDateTime{} = naive_datetime) do naive = DateTime.truncate(naive_datetime, :second) "'#{Date.to_string naive} #{Time.to_string naive}'" end defp encode_param(_query, %Date{} = date), do: "'#{date}'" defp encode_param(_query, param) do "'#{escape param}'" end defp escape(s) do s |> String.replace("_", "\_") |> String.replace("'", "\'") |> String.replace("%", "\%") |> String.replace(~s("), ~s(\\")) |> String.replace("\\", "\\\\") end end
lib/clickhousex/codec/values.ex
0.618896
0.514888
values.ex
starcoder
defmodule LFSR do @moduledoc """ Implements a binary Galois Linear Feedback Shift Register with arbitrary size `n`. A LFSR is a shift register whose input bit is a linear function of its previous state. The bit positions that affect the next state are called the taps. A LFSR with well chosen taps will produce a maximum cycle, meaning that a register with size `n` will produce a sequence of length 2<sup>n</sup>-1 without repetitions. The LFSR can be initialized by providing a starting state and the desired size of the register. In this case, a table of default taps that generate the maximum cycle is used. Alternatively, the LFSR can be initialized with the starting state and a list of taps. Note however that not all combinations of taps will produce the maximum cycle. """ import Bitwise defstruct [:state, :mask] @doc """ Initializes and returns a new LFSR. The LFSR is represented using a Struct. The first argument is the starting state and must be a number greater than 0 and less than 2<sup>n</sup>, where `n` is the size of the register. The second argument is either the size in bits of the register or a list of taps. ## Examples iex> LFSR.new(1, 8) %LFSR{mask: 184, state: 1} iex> LFSR.new(1, [8, 6, 5, 4]) %LFSR{mask: 184, state: 1} """ def new(state, size) when is_integer(state) and is_integer(size) do new(state, taps(size)) end def new(state, [size | _] = taps) when is_integer(state) and is_integer(size) do limit = 1 <<< size if state <= 0 or state >= limit do raise ArgumentError, message: "initial state must be between 1 and #{limit - 1}" end struct(__MODULE__, state: state, mask: mask(size, taps)) end @doc """ Takes the LFSR and returns the LFSR in the next state. ## Examples iex> LFSR.new(1, 8) %LFSR{mask: 184, state: 1} iex> LFSR.new(1, 8) |> LFSR.next %LFSR{mask: 184, state: 184} """ def next(%__MODULE__{state: state, mask: mask} = lfsr) do lsb = state &&& 1 state = state >>> 1 state = if lsb == 1, do: state ^^^ mask, else: state %{lfsr | state: state} end @doc """ Convenience function to fetch the state of a LFSR. ## Examples iex> LFSR.new(1, 8) |> LFSR.state 1 """ def state(%__MODULE__{state: state}), do: state defp mask(size, taps) do <<mask::size(size)>> = Enum.reduce(taps, <<0::size(size)>>, &(set_bit(&2, size - &1))) mask end defp set_bit(bits, pos) do <<left::size(pos), _::1, right::bitstring>> = bits <<left::size(pos), 1::1, right::bitstring>> end # http://www.eej.ulst.ac.uk/~ian/modules/EEE515/files/old_files/lfsr/lfsr_table.pdf defp taps(2), do: [2, 1] defp taps(3), do: [3, 2] defp taps(4), do: [4, 3] defp taps(5), do: [5, 4, 3, 2] defp taps(6), do: [6, 5, 3, 2] defp taps(7), do: [7, 6, 5, 4] defp taps(8), do: [8, 6, 5, 4] defp taps(9), do: [9, 8, 6, 5] defp taps(10), do: [10, 9, 7, 6] defp taps(11), do: [11, 10, 9, 7] defp taps(12), do: [12, 11, 8, 6] defp taps(13), do: [13, 12, 10, 9] defp taps(14), do: [14, 13, 11, 9] defp taps(15), do: [15, 14, 13, 11] defp taps(16), do: [16, 14, 13, 11] defp taps(17), do: [17, 16, 15, 14] defp taps(18), do: [18, 17, 16, 13] defp taps(19), do: [19, 18, 17, 14] defp taps(20), do: [20, 19, 16, 14] defp taps(21), do: [21, 20, 19, 16] defp taps(22), do: [22, 19, 18, 17] defp taps(23), do: [23, 22, 20, 18] defp taps(24), do: [24, 23, 21, 20] defp taps(25), do: [25, 24, 23, 22] defp taps(26), do: [26, 25, 24, 20] defp taps(27), do: [27, 26, 25, 22] defp taps(28), do: [28, 27, 24, 22] defp taps(29), do: [29, 28, 27, 25] defp taps(30), do: [30, 29, 26, 24] defp taps(31), do: [31, 30, 29, 28] defp taps(32), do: [32, 30, 26, 25] defp taps(33), do: [33, 32, 29, 27] defp taps(34), do: [34, 31, 30, 26] defp taps(35), do: [35, 34, 28, 27] defp taps(36), do: [36, 35, 29, 28] defp taps(37), do: [37, 36, 33, 31] defp taps(38), do: [38, 37, 33, 32] defp taps(39), do: [39, 38, 35, 32] defp taps(40), do: [40, 37, 36, 35] defp taps(41), do: [41, 40, 39, 38] defp taps(42), do: [42, 40, 37, 35] defp taps(43), do: [43, 42, 38, 37] defp taps(44), do: [44, 42, 39, 38] defp taps(45), do: [45, 44, 42, 41] defp taps(46), do: [46, 40, 39, 38] defp taps(47), do: [47, 46, 43, 42] defp taps(48), do: [48, 44, 41, 39] defp taps(49), do: [49, 45, 44, 43] defp taps(50), do: [50, 48, 47, 46] defp taps(51), do: [51, 50, 48, 45] defp taps(52), do: [52, 51, 49, 46] defp taps(53), do: [53, 52, 51, 47] defp taps(54), do: [54, 51, 48, 46] defp taps(55), do: [55, 54, 53, 49] defp taps(56), do: [56, 54, 52, 49] defp taps(57), do: [57, 55, 54, 52] defp taps(58), do: [58, 57, 53, 52] defp taps(59), do: [59, 57, 55, 52] defp taps(60), do: [60, 58, 56, 55] defp taps(61), do: [61, 60, 59, 56] defp taps(62), do: [62, 59, 57, 56] defp taps(63), do: [63, 62, 59, 58] defp taps(64), do: [64, 63, 61, 60] defp taps(65), do: [65, 64, 62, 61] defp taps(66), do: [66, 60, 58, 57] defp taps(67), do: [67, 66, 65, 62] defp taps(68), do: [68, 67, 63, 61] defp taps(69), do: [69, 67, 64, 63] defp taps(70), do: [70, 69, 67, 65] defp taps(71), do: [71, 70, 68, 66] defp taps(72), do: [72, 69, 63, 62] defp taps(73), do: [73, 71, 70, 69] defp taps(74), do: [74, 71, 70, 67] defp taps(75), do: [75, 74, 72, 69] defp taps(76), do: [76, 74, 72, 71] defp taps(77), do: [77, 75, 72, 71] defp taps(78), do: [78, 77, 76, 71] defp taps(79), do: [79, 77, 76, 75] defp taps(80), do: [80, 78, 76, 71] defp taps(81), do: [81, 79, 78, 75] defp taps(82), do: [82, 78, 76, 73] defp taps(83), do: [83, 81, 79, 76] defp taps(84), do: [84, 83, 77, 75] defp taps(85), do: [85, 84, 83, 77] defp taps(86), do: [86, 84, 81, 80] defp taps(87), do: [87, 86, 82, 80] defp taps(88), do: [88, 80, 79, 77] defp taps(89), do: [89, 86, 84, 83] defp taps(90), do: [90, 88, 87, 85] defp taps(91), do: [91, 90, 86, 83] defp taps(92), do: [92, 90, 87, 86] defp taps(93), do: [93, 91, 90, 87] defp taps(94), do: [94, 93, 89, 88] defp taps(95), do: [95, 94, 90, 88] defp taps(96), do: [96, 90, 87, 86] defp taps(97), do: [97, 95, 93, 91] defp taps(98), do: [98, 97, 91, 90] defp taps(99), do: [99, 95, 94, 92] defp taps(100), do: [100, 98, 93, 92] defp taps(101), do: [101, 100, 95, 94] defp taps(102), do: [102, 99, 97, 96] defp taps(103), do: [103, 102, 99, 94] defp taps(104), do: [104, 103, 94, 93] defp taps(105), do: [105, 104, 99, 98] defp taps(106), do: [106, 105, 101, 100] defp taps(107), do: [107, 105, 99, 98] defp taps(108), do: [108, 103, 97, 96] defp taps(109), do: [109, 107, 105, 104] defp taps(110), do: [110, 109, 106, 104] defp taps(111), do: [111, 109, 107, 104] defp taps(112), do: [112, 108, 106, 101] defp taps(113), do: [113, 111, 110, 108] defp taps(114), do: [114, 113, 112, 103] defp taps(115), do: [115, 110, 108, 107] defp taps(116), do: [116, 114, 111, 110] defp taps(117), do: [117, 116, 115, 112] defp taps(118), do: [118, 116, 113, 112] defp taps(119), do: [119, 116, 111, 110] defp taps(120), do: [120, 118, 114, 111] defp taps(121), do: [121, 120, 116, 113] defp taps(122), do: [122, 121, 120, 116] defp taps(123), do: [123, 122, 119, 115] defp taps(124), do: [124, 119, 118, 117] defp taps(125), do: [125, 120, 119, 118] defp taps(126), do: [126, 124, 122, 119] defp taps(127), do: [127, 126, 124, 120] defp taps(128), do: [128, 127, 126, 121] defp taps(129), do: [129, 128, 125, 124] defp taps(130), do: [130, 129, 128, 125] defp taps(131), do: [131, 129, 128, 123] defp taps(132), do: [132, 130, 127, 123] defp taps(133), do: [133, 131, 125, 124] defp taps(134), do: [134, 133, 129, 127] defp taps(135), do: [135, 132, 131, 129] defp taps(136), do: [136, 134, 133, 128] defp taps(137), do: [137, 136, 133, 126] defp taps(138), do: [138, 137, 131, 130] defp taps(139), do: [139, 136, 134, 131] defp taps(140), do: [140, 139, 136, 132] defp taps(141), do: [141, 140, 135, 128] defp taps(142), do: [142, 141, 139, 132] defp taps(143), do: [143, 141, 140, 138] defp taps(144), do: [144, 142, 140, 137] defp taps(145), do: [145, 144, 140, 139] defp taps(146), do: [146, 144, 143, 141] defp taps(147), do: [147, 145, 143, 136] defp taps(148), do: [148, 145, 143, 141] defp taps(149), do: [149, 142, 140, 139] defp taps(150), do: [150, 148, 147, 142] defp taps(151), do: [151, 150, 149, 148] defp taps(152), do: [152, 150, 149, 146] defp taps(153), do: [153, 149, 148, 145] defp taps(154), do: [154, 153, 149, 145] defp taps(155), do: [155, 151, 150, 148] defp taps(156), do: [156, 153, 151, 147] defp taps(157), do: [157, 155, 152, 151] defp taps(158), do: [158, 153, 152, 150] defp taps(159), do: [159, 156, 153, 148] defp taps(160), do: [160, 158, 157, 155] defp taps(161), do: [161, 159, 158, 155] defp taps(162), do: [162, 158, 155, 154] defp taps(163), do: [163, 160, 157, 156] defp taps(164), do: [164, 159, 158, 152] defp taps(165), do: [165, 162, 157, 156] defp taps(166), do: [166, 164, 163, 156] defp taps(167), do: [167, 165, 163, 161] defp taps(168), do: [168, 162, 159, 152] defp taps(169), do: [169, 164, 163, 161] defp taps(170), do: [170, 169, 166, 161] defp taps(171), do: [171, 169, 166, 165] defp taps(172), do: [172, 169, 165, 161] defp taps(173), do: [173, 171, 168, 165] defp taps(174), do: [174, 169, 166, 165] defp taps(175), do: [175, 173, 171, 169] defp taps(176), do: [176, 167, 165, 164] defp taps(177), do: [177, 175, 174, 172] defp taps(178), do: [178, 176, 171, 170] defp taps(179), do: [179, 178, 177, 175] defp taps(180), do: [180, 173, 170, 168] defp taps(181), do: [181, 180, 175, 174] defp taps(182), do: [182, 181, 176, 174] defp taps(183), do: [183, 179, 176, 175] defp taps(184), do: [184, 177, 176, 175] defp taps(185), do: [185, 184, 182, 177] defp taps(186), do: [186, 180, 178, 177] defp taps(187), do: [187, 182, 181, 180] defp taps(188), do: [188, 186, 183, 182] defp taps(189), do: [189, 187, 184, 183] defp taps(190), do: [190, 188, 184, 177] defp taps(191), do: [191, 187, 185, 184] defp taps(192), do: [192, 190, 178, 177] defp taps(193), do: [193, 189, 186, 184] defp taps(194), do: [194, 192, 191, 190] defp taps(195), do: [195, 193, 192, 187] defp taps(196), do: [196, 194, 187, 185] defp taps(197), do: [197, 195, 193, 188] defp taps(198), do: [198, 193, 190, 183] defp taps(199), do: [199, 198, 195, 190] defp taps(200), do: [200, 198, 197, 195] defp taps(201), do: [201, 199, 198, 195] defp taps(202), do: [202, 198, 196, 195] defp taps(203), do: [203, 202, 196, 195] defp taps(204), do: [204, 201, 200, 194] defp taps(205), do: [205, 203, 200, 196] defp taps(206), do: [206, 201, 197, 196] defp taps(207), do: [207, 206, 201, 198] defp taps(208), do: [208, 207, 205, 199] defp taps(209), do: [209, 207, 206, 204] defp taps(210), do: [210, 207, 206, 198] defp taps(211), do: [211, 203, 201, 200] defp taps(212), do: [212, 209, 208, 205] defp taps(213), do: [213, 211, 208, 207] defp taps(214), do: [214, 213, 211, 209] defp taps(215), do: [215, 212, 210, 209] defp taps(216), do: [216, 215, 213, 209] defp taps(217), do: [217, 213, 212, 211] defp taps(218), do: [218, 217, 211, 210] defp taps(219), do: [219, 218, 215, 211] defp taps(220), do: [220, 211, 210, 208] defp taps(221), do: [221, 219, 215, 213] defp taps(222), do: [222, 220, 217, 214] defp taps(223), do: [223, 221, 219, 218] defp taps(224), do: [224, 222, 217, 212] defp taps(225), do: [225, 224, 220, 215] defp taps(226), do: [226, 223, 219, 216] defp taps(227), do: [227, 223, 218, 217] defp taps(228), do: [228, 226, 217, 216] defp taps(229), do: [229, 228, 225, 219] defp taps(230), do: [230, 224, 223, 222] defp taps(231), do: [231, 229, 227, 224] defp taps(232), do: [232, 228, 223, 221] defp taps(233), do: [233, 232, 229, 224] defp taps(234), do: [234, 232, 225, 223] defp taps(235), do: [235, 234, 229, 226] defp taps(236), do: [236, 229, 228, 226] defp taps(237), do: [237, 236, 233, 230] defp taps(238), do: [238, 237, 236, 233] defp taps(239), do: [239, 238, 232, 227] defp taps(240), do: [240, 237, 235, 232] defp taps(241), do: [241, 237, 233, 232] defp taps(242), do: [242, 241, 236, 231] defp taps(243), do: [243, 242, 238, 235] defp taps(244), do: [244, 243, 240, 235] defp taps(245), do: [245, 244, 241, 239] defp taps(246), do: [246, 245, 244, 235] defp taps(247), do: [247, 245, 243, 238] defp taps(248), do: [248, 238, 234, 233] defp taps(249), do: [249, 248, 245, 242] defp taps(250), do: [250, 247, 245, 240] defp taps(251), do: [251, 249, 247, 244] defp taps(252), do: [252, 251, 247, 241] defp taps(253), do: [253, 252, 247, 246] defp taps(254), do: [254, 253, 252, 247] defp taps(255), do: [255, 253, 252, 250] defp taps(256), do: [256, 254, 251, 246] defp taps(257), do: [257, 255, 251, 250] defp taps(258), do: [258, 254, 252, 249] defp taps(259), do: [259, 257, 253, 249] defp taps(260), do: [260, 253, 252, 250] defp taps(261), do: [261, 257, 255, 254] defp taps(262), do: [262, 258, 254, 253] defp taps(263), do: [263, 261, 258, 252] defp taps(264), do: [264, 263, 255, 254] defp taps(265), do: [265, 263, 262, 260] defp taps(266), do: [266, 265, 260, 259] defp taps(267), do: [267, 264, 261, 259] defp taps(268), do: [268, 267, 264, 258] defp taps(269), do: [269, 268, 263, 262] defp taps(270), do: [270, 267, 263, 260] defp taps(271), do: [271, 265, 264, 260] defp taps(272), do: [272, 270, 266, 263] defp taps(273), do: [273, 272, 271, 266] defp taps(274), do: [274, 272, 267, 265] defp taps(275), do: [275, 266, 265, 264] defp taps(276), do: [276, 275, 273, 270] defp taps(277), do: [277, 274, 271, 265] defp taps(278), do: [278, 277, 274, 273] defp taps(279), do: [279, 278, 275, 274] defp taps(280), do: [280, 278, 275, 271] defp taps(281), do: [281, 280, 277, 272] defp taps(282), do: [282, 278, 277, 272] defp taps(283), do: [283, 278, 276, 271] defp taps(284), do: [284, 279, 278, 276] defp taps(285), do: [285, 280, 278, 275] defp taps(286), do: [286, 285, 276, 271] defp taps(287), do: [287, 285, 282, 281] defp taps(288), do: [288, 287, 278, 277] defp taps(289), do: [289, 286, 285, 277] defp taps(290), do: [290, 288, 287, 285] defp taps(291), do: [291, 286, 280, 279] defp taps(292), do: [292, 291, 289, 285] defp taps(293), do: [293, 292, 287, 282] defp taps(294), do: [294, 292, 291, 285] defp taps(295), do: [295, 293, 291, 290] defp taps(296), do: [296, 292, 287, 285] defp taps(297), do: [297, 296, 293, 292] defp taps(298), do: [298, 294, 290, 287] defp taps(299), do: [299, 295, 293, 288] defp taps(300), do: [300, 290, 288, 287] defp taps(301), do: [301, 299, 296, 292] defp taps(302), do: [302, 297, 293, 290] defp taps(303), do: [303, 297, 291, 290] defp taps(304), do: [304, 303, 302, 293] defp taps(305), do: [305, 303, 299, 298] defp taps(306), do: [306, 305, 303, 299] defp taps(307), do: [307, 305, 303, 299] defp taps(308), do: [308, 306, 299, 293] defp taps(309), do: [309, 307, 302, 299] defp taps(310), do: [310, 309, 305, 302] defp taps(311), do: [311, 308, 306, 304] defp taps(312), do: [312, 307, 302, 301] defp taps(313), do: [313, 312, 310, 306] defp taps(314), do: [314, 311, 305, 300] defp taps(315), do: [315, 314, 306, 305] defp taps(316), do: [316, 309, 305, 304] defp taps(317), do: [317, 315, 313, 310] defp taps(318), do: [318, 313, 312, 310] defp taps(319), do: [319, 318, 317, 308] defp taps(320), do: [320, 319, 317, 316] defp taps(321), do: [321, 319, 316, 314] defp taps(322), do: [322, 321, 320, 305] defp taps(323), do: [323, 322, 320, 313] defp taps(324), do: [324, 321, 320, 318] defp taps(325), do: [325, 323, 320, 315] defp taps(326), do: [326, 325, 323, 316] defp taps(327), do: [327, 325, 322, 319] defp taps(328), do: [328, 323, 321, 319] defp taps(329), do: [329, 326, 323, 321] defp taps(330), do: [330, 328, 323, 322] defp taps(331), do: [331, 329, 325, 321] defp taps(332), do: [332, 325, 321, 320] defp taps(333), do: [333, 331, 329, 325] defp taps(334), do: [334, 333, 330, 327] defp taps(335), do: [335, 333, 328, 325] defp taps(336), do: [336, 335, 332, 329] defp taps(337), do: [337, 336, 331, 327] defp taps(338), do: [338, 336, 335, 332] defp taps(339), do: [339, 332, 329, 323] defp taps(340), do: [340, 337, 336, 329] defp taps(341), do: [341, 336, 330, 327] defp taps(342), do: [342, 341, 340, 331] defp taps(343), do: [343, 338, 335, 333] defp taps(344), do: [344, 338, 334, 333] defp taps(345), do: [345, 343, 341, 337] defp taps(346), do: [346, 344, 339, 335] defp taps(347), do: [347, 344, 337, 336] defp taps(348), do: [348, 344, 341, 340] defp taps(349), do: [349, 347, 344, 343] defp taps(350), do: [350, 340, 337, 336] defp taps(351), do: [351, 348, 345, 343] defp taps(352), do: [352, 346, 341, 339] defp taps(353), do: [353, 349, 346, 344] defp taps(354), do: [354, 349, 341, 340] defp taps(355), do: [355, 354, 350, 349] defp taps(356), do: [356, 349, 347, 346] defp taps(357), do: [357, 355, 347, 346] defp taps(358), do: [358, 351, 350, 344] defp taps(359), do: [359, 358, 352, 350] defp taps(360), do: [360, 359, 335, 334] defp taps(361), do: [361, 360, 357, 354] defp taps(362), do: [362, 360, 351, 344] defp taps(363), do: [363, 362, 356, 355] defp taps(364), do: [364, 363, 359, 352] defp taps(365), do: [365, 360, 359, 356] defp taps(366), do: [366, 362, 359, 352] defp taps(367), do: [367, 365, 363, 358] defp taps(368), do: [368, 361, 359, 351] defp taps(369), do: [369, 367, 359, 358] defp taps(370), do: [370, 368, 367, 365] defp taps(371), do: [371, 369, 368, 363] defp taps(372), do: [372, 369, 365, 357] defp taps(373), do: [373, 371, 366, 365] defp taps(374), do: [374, 369, 368, 366] defp taps(375), do: [375, 374, 368, 367] defp taps(376), do: [376, 371, 369, 368] defp taps(377), do: [377, 376, 374, 369] defp taps(378), do: [378, 374, 365, 363] defp taps(379), do: [379, 375, 370, 369] defp taps(380), do: [380, 377, 374, 366] defp taps(381), do: [381, 380, 379, 376] defp taps(382), do: [382, 379, 375, 364] defp taps(383), do: [383, 382, 378, 374] defp taps(384), do: [384, 378, 369, 368] defp taps(385), do: [385, 383, 381, 379] defp taps(386), do: [386, 381, 380, 376] defp taps(387), do: [387, 385, 379, 378] defp taps(388), do: [388, 387, 385, 374] defp taps(389), do: [389, 384, 380, 379] defp taps(390), do: [390, 388, 380, 377] defp taps(391), do: [391, 390, 389, 385] defp taps(392), do: [392, 386, 382, 379] defp taps(393), do: [393, 392, 391, 386] defp taps(394), do: [394, 392, 387, 386] defp taps(395), do: [395, 390, 389, 384] defp taps(396), do: [396, 392, 390, 389] defp taps(397), do: [397, 392, 387, 385] defp taps(398), do: [398, 393, 392, 384] defp taps(399), do: [399, 397, 390, 388] defp taps(400), do: [400, 398, 397, 395] defp taps(401), do: [401, 399, 392, 389] defp taps(402), do: [402, 399, 398, 393] defp taps(403), do: [403, 398, 395, 394] defp taps(404), do: [404, 400, 398, 397] defp taps(405), do: [405, 398, 397, 388] defp taps(406), do: [406, 402, 397, 393] defp taps(407), do: [407, 402, 400, 398] defp taps(408), do: [408, 407, 403, 401] defp taps(409), do: [409, 406, 404, 402] defp taps(410), do: [410, 407, 406, 400] defp taps(411), do: [411, 408, 401, 399] defp taps(412), do: [412, 409, 404, 401] defp taps(413), do: [413, 407, 406, 403] defp taps(414), do: [414, 405, 401, 398] defp taps(415), do: [415, 413, 411, 406] defp taps(416), do: [416, 414, 411, 407] defp taps(417), do: [417, 416, 414, 407] defp taps(418), do: [418, 417, 415, 403] defp taps(419), do: [419, 415, 414, 404] defp taps(420), do: [420, 412, 410, 407] defp taps(421), do: [421, 419, 417, 416] defp taps(422), do: [422, 421, 416, 412] defp taps(423), do: [423, 420, 418, 414] defp taps(424), do: [424, 422, 417, 415] defp taps(425), do: [425, 422, 421, 418] defp taps(426), do: [426, 415, 414, 412] defp taps(427), do: [427, 422, 421, 416] defp taps(428), do: [428, 426, 425, 417] defp taps(429), do: [429, 422, 421, 419] defp taps(430), do: [430, 419, 417, 415] defp taps(431), do: [431, 430, 428, 426] defp taps(432), do: [432, 429, 428, 419] defp taps(433), do: [433, 430, 428, 422] defp taps(434), do: [434, 429, 423, 422] defp taps(435), do: [435, 430, 426, 423] defp taps(436), do: [436, 432, 431, 430] defp taps(437), do: [437, 436, 435, 431] defp taps(438), do: [438, 436, 432, 421] defp taps(439), do: [439, 437, 436, 431] defp taps(440), do: [440, 439, 437, 436] defp taps(441), do: [441, 440, 433, 430] defp taps(442), do: [442, 440, 437, 435] defp taps(443), do: [443, 442, 437, 433] defp taps(444), do: [444, 435, 432, 431] defp taps(445), do: [445, 441, 439, 438] defp taps(446), do: [446, 442, 439, 431] defp taps(447), do: [447, 446, 441, 438] defp taps(448), do: [448, 444, 442, 437] defp taps(449), do: [449, 446, 440, 438] defp taps(450), do: [450, 443, 438, 434] defp taps(451), do: [451, 450, 441, 435] defp taps(452), do: [452, 448, 447, 446] defp taps(453), do: [453, 449, 447, 438] defp taps(454), do: [454, 449, 445, 444] defp taps(455), do: [455, 453, 449, 444] defp taps(456), do: [456, 454, 445, 433] defp taps(457), do: [457, 454, 449, 446] defp taps(458), do: [458, 453, 448, 445] defp taps(459), do: [459, 457, 454, 447] defp taps(460), do: [460, 459, 455, 451] defp taps(461), do: [461, 460, 455, 454] defp taps(462), do: [462, 457, 451, 450] defp taps(463), do: [463, 456, 455, 452] defp taps(464), do: [464, 460, 455, 441] defp taps(465), do: [465, 463, 462, 457] defp taps(466), do: [466, 460, 455, 452] defp taps(467), do: [467, 466, 461, 456] defp taps(468), do: [468, 464, 459, 453] defp taps(469), do: [469, 467, 464, 460] defp taps(470), do: [470, 468, 462, 461] defp taps(471), do: [471, 469, 468, 465] defp taps(472), do: [472, 470, 469, 461] defp taps(473), do: [473, 470, 467, 465] defp taps(474), do: [474, 465, 463, 456] defp taps(475), do: [475, 471, 467, 466] defp taps(476), do: [476, 475, 468, 466] defp taps(477), do: [477, 470, 462, 461] defp taps(478), do: [478, 477, 474, 472] defp taps(479), do: [479, 475, 472, 470] defp taps(480), do: [480, 473, 467, 464] defp taps(481), do: [481, 480, 472, 471] defp taps(482), do: [482, 477, 476, 473] defp taps(483), do: [483, 479, 477, 474] defp taps(484), do: [484, 483, 482, 470] defp taps(485), do: [485, 479, 469, 468] defp taps(486), do: [486, 481, 478, 472] defp taps(487), do: [487, 485, 483, 478] defp taps(488), do: [488, 487, 485, 484] defp taps(489), do: [489, 484, 483, 480] defp taps(490), do: [490, 485, 483, 481] defp taps(491), do: [491, 488, 485, 480] defp taps(492), do: [492, 491, 485, 484] defp taps(493), do: [493, 490, 488, 483] defp taps(494), do: [494, 493, 489, 481] defp taps(495), do: [495, 494, 486, 480] defp taps(496), do: [496, 494, 491, 480] defp taps(497), do: [497, 493, 488, 486] defp taps(498), do: [498, 495, 489, 487] defp taps(499), do: [499, 494, 493, 488] defp taps(500), do: [500, 499, 494, 490] defp taps(501), do: [501, 499, 497, 496] defp taps(502), do: [502, 498, 497, 494] defp taps(503), do: [503, 502, 501, 500] defp taps(504), do: [504, 502, 490, 483] defp taps(505), do: [505, 500, 497, 493] defp taps(506), do: [506, 501, 494, 491] defp taps(507), do: [507, 504, 501, 494] defp taps(508), do: [508, 505, 500, 495] defp taps(509), do: [509, 506, 502, 501] defp taps(510), do: [510, 501, 500, 498] defp taps(511), do: [511, 509, 503, 501] defp taps(512), do: [512, 510, 507, 504] defp taps(513), do: [513, 505, 503, 500] defp taps(514), do: [514, 511, 509, 507] defp taps(515), do: [515, 511, 508, 501] defp taps(516), do: [516, 514, 511, 509] defp taps(517), do: [517, 515, 507, 505] defp taps(518), do: [518, 516, 515, 507] defp taps(519), do: [519, 517, 511, 507] defp taps(520), do: [520, 509, 507, 503] defp taps(521), do: [521, 519, 514, 512] defp taps(522), do: [522, 518, 509, 507] defp taps(523), do: [523, 521, 517, 510] defp taps(524), do: [524, 523, 519, 515] defp taps(525), do: [525, 524, 521, 519] defp taps(526), do: [526, 525, 521, 517] defp taps(527), do: [527, 526, 520, 518] defp taps(528), do: [528, 526, 522, 517] defp taps(529), do: [529, 528, 525, 522] defp taps(530), do: [530, 527, 523, 520] defp taps(531), do: [531, 529, 525, 519] defp taps(532), do: [532, 529, 528, 522] defp taps(533), do: [533, 531, 530, 529] defp taps(534), do: [534, 533, 529, 527] defp taps(535), do: [535, 533, 529, 527] defp taps(536), do: [536, 533, 531, 529] defp taps(537), do: [537, 536, 535, 527] defp taps(538), do: [538, 537, 536, 533] defp taps(539), do: [539, 535, 534, 529] defp taps(540), do: [540, 537, 534, 529] defp taps(541), do: [541, 537, 531, 528] defp taps(542), do: [542, 540, 539, 533] defp taps(543), do: [543, 538, 536, 532] defp taps(544), do: [544, 538, 535, 531] defp taps(545), do: [545, 539, 537, 532] defp taps(546), do: [546, 545, 544, 538] defp taps(547), do: [547, 543, 540, 534] defp taps(548), do: [548, 545, 543, 538] defp taps(549), do: [549, 546, 545, 533] defp taps(550), do: [550, 546, 533, 529] defp taps(551), do: [551, 550, 547, 542] defp taps(552), do: [552, 550, 547, 532] defp taps(553), do: [553, 550, 549, 542] defp taps(554), do: [554, 551, 546, 543] defp taps(555), do: [555, 551, 546, 545] defp taps(556), do: [556, 549, 546, 540] defp taps(557), do: [557, 552, 551, 550] defp taps(558), do: [558, 553, 549, 544] defp taps(559), do: [559, 557, 552, 550] defp taps(560), do: [560, 554, 551, 549] defp taps(561), do: [561, 558, 552, 550] defp taps(562), do: [562, 560, 558, 551] defp taps(563), do: [563, 561, 554, 549] defp taps(564), do: [564, 563, 561, 558] defp taps(565), do: [565, 564, 559, 554] defp taps(566), do: [566, 564, 561, 560] defp taps(567), do: [567, 563, 557, 556] defp taps(568), do: [568, 558, 557, 551] defp taps(569), do: [569, 568, 559, 557] defp taps(570), do: [570, 563, 558, 552] defp taps(571), do: [571, 569, 566, 561] defp taps(572), do: [572, 571, 564, 560] defp taps(573), do: [573, 569, 567, 563] defp taps(574), do: [574, 569, 565, 560] defp taps(575), do: [575, 572, 570, 569] defp taps(576), do: [576, 573, 572, 563] defp taps(577), do: [577, 575, 574, 569] defp taps(578), do: [578, 562, 556, 555] defp taps(579), do: [579, 572, 570, 567] defp taps(580), do: [580, 579, 576, 574] defp taps(581), do: [581, 575, 574, 568] defp taps(582), do: [582, 579, 576, 571] defp taps(583), do: [583, 581, 577, 575] defp taps(584), do: [584, 581, 571, 570] defp taps(585), do: [585, 583, 582, 577] defp taps(586), do: [586, 584, 581, 579] defp taps(587), do: [587, 586, 581, 576] defp taps(588), do: [588, 577, 572, 571] defp taps(589), do: [589, 586, 585, 579] defp taps(590), do: [590, 588, 587, 578] defp taps(591), do: [591, 587, 585, 582] defp taps(592), do: [592, 591, 573, 568] defp taps(593), do: [593, 588, 585, 584] defp taps(594), do: [594, 586, 584, 583] defp taps(595), do: [595, 594, 593, 586] defp taps(596), do: [596, 592, 591, 590] defp taps(597), do: [597, 588, 585, 583] defp taps(598), do: [598, 597, 592, 591] defp taps(599), do: [599, 593, 591, 590] defp taps(600), do: [600, 599, 590, 589] defp taps(601), do: [601, 600, 597, 589] defp taps(602), do: [602, 596, 594, 591] defp taps(603), do: [603, 600, 599, 597] defp taps(604), do: [604, 600, 598, 589] defp taps(605), do: [605, 600, 598, 595] defp taps(606), do: [606, 602, 599, 591] defp taps(607), do: [607, 600, 598, 595] defp taps(608), do: [608, 606, 602, 585] defp taps(609), do: [609, 601, 600, 597] defp taps(610), do: [610, 602, 600, 599] defp taps(611), do: [611, 609, 607, 601] defp taps(612), do: [612, 607, 602, 598] defp taps(613), do: [613, 609, 603, 594] defp taps(614), do: [614, 613, 612, 607] defp taps(615), do: [615, 614, 609, 608] defp taps(616), do: [616, 614, 602, 597] defp taps(617), do: [617, 612, 608, 607] defp taps(618), do: [618, 615, 604, 598] defp taps(619), do: [619, 614, 611, 610] defp taps(620), do: [620, 619, 618, 611] defp taps(621), do: [621, 616, 615, 609] defp taps(622), do: [622, 612, 610, 605] defp taps(623), do: [623, 614, 613, 612] defp taps(624), do: [624, 617, 615, 612] defp taps(625), do: [625, 620, 617, 613] defp taps(626), do: [626, 623, 621, 613] defp taps(627), do: [627, 622, 617, 613] defp taps(628), do: [628, 626, 617, 616] defp taps(629), do: [629, 627, 624, 623] defp taps(630), do: [630, 628, 626, 623] defp taps(631), do: [631, 625, 623, 617] defp taps(632), do: [632, 629, 619, 613] defp taps(633), do: [633, 632, 631, 626] defp taps(634), do: [634, 631, 629, 627] defp taps(635), do: [635, 631, 625, 621] defp taps(636), do: [636, 632, 628, 623] defp taps(637), do: [637, 636, 628, 623] defp taps(638), do: [638, 637, 633, 632] defp taps(639), do: [639, 636, 635, 629] defp taps(640), do: [640, 638, 637, 626] defp taps(641), do: [641, 640, 636, 622] defp taps(642), do: [642, 636, 633, 632] defp taps(643), do: [643, 641, 640, 632] defp taps(644), do: [644, 634, 633, 632] defp taps(645), do: [645, 641, 637, 634] defp taps(646), do: [646, 635, 634, 633] defp taps(647), do: [647, 646, 643, 642] defp taps(648), do: [648, 647, 626, 625] defp taps(649), do: [649, 648, 644, 638] defp taps(650), do: [650, 644, 635, 632] defp taps(651), do: [651, 646, 638, 637] defp taps(652), do: [652, 647, 643, 641] defp taps(653), do: [653, 646, 645, 643] defp taps(654), do: [654, 649, 643, 640] defp taps(655), do: [655, 653, 639, 638] defp taps(656), do: [656, 646, 638, 637] defp taps(657), do: [657, 656, 650, 649] defp taps(658), do: [658, 651, 648, 646] defp taps(659), do: [659, 657, 655, 644] defp taps(660), do: [660, 657, 656, 648] defp taps(661), do: [661, 657, 650, 649] defp taps(662), do: [662, 659, 656, 650] defp taps(663), do: [663, 655, 652, 649] defp taps(664), do: [664, 662, 660, 649] defp taps(665), do: [665, 661, 659, 654] defp taps(666), do: [666, 664, 659, 656] defp taps(667), do: [667, 664, 660, 649] defp taps(668), do: [668, 658, 656, 651] defp taps(669), do: [669, 667, 665, 664] defp taps(670), do: [670, 669, 665, 664] defp taps(671), do: [671, 669, 665, 662] defp taps(672), do: [672, 667, 666, 661] defp taps(673), do: [673, 666, 664, 663] defp taps(674), do: [674, 671, 665, 660] defp taps(675), do: [675, 674, 672, 669] defp taps(676), do: [676, 675, 671, 664] defp taps(677), do: [677, 674, 673, 669] defp taps(678), do: [678, 675, 673, 663] defp taps(679), do: [679, 676, 667, 661] defp taps(680), do: [680, 679, 650, 645] defp taps(681), do: [681, 678, 672, 670] defp taps(682), do: [682, 681, 679, 675] defp taps(683), do: [683, 682, 677, 672] defp taps(684), do: [684, 681, 671, 666] defp taps(685), do: [685, 684, 682, 681] defp taps(686), do: [686, 684, 674, 673] defp taps(687), do: [687, 682, 675, 673] defp taps(688), do: [688, 682, 674, 669] defp taps(689), do: [689, 686, 683, 681] defp taps(690), do: [690, 687, 683, 680] defp taps(691), do: [691, 689, 685, 678] defp taps(692), do: [692, 687, 686, 678] defp taps(693), do: [693, 691, 685, 678] defp taps(694), do: [694, 691, 681, 677] defp taps(695), do: [695, 694, 691, 686] defp taps(696), do: [696, 694, 686, 673] defp taps(697), do: [697, 689, 685, 681] defp taps(698), do: [698, 690, 689, 688] defp taps(699), do: [699, 698, 689, 684] defp taps(700), do: [700, 698, 695, 694] defp taps(701), do: [701, 699, 697, 685] defp taps(702), do: [702, 701, 699, 695] defp taps(703), do: [703, 702, 696, 691] defp taps(704), do: [704, 701, 699, 692] defp taps(705), do: [705, 704, 698, 697] defp taps(706), do: [706, 697, 695, 692] defp taps(707), do: [707, 702, 699, 692] defp taps(708), do: [708, 706, 704, 703] defp taps(709), do: [709, 708, 706, 705] defp taps(710), do: [710, 709, 696, 695] defp taps(711), do: [711, 704, 703, 700] defp taps(712), do: [712, 709, 708, 707] defp taps(713), do: [713, 706, 703, 696] defp taps(714), do: [714, 709, 707, 701] defp taps(715), do: [715, 714, 711, 708] defp taps(716), do: [716, 706, 705, 704] defp taps(717), do: [717, 716, 710, 701] defp taps(718), do: [718, 717, 716, 713] defp taps(719), do: [719, 711, 710, 707] defp taps(720), do: [720, 718, 712, 709] defp taps(721), do: [721, 720, 713, 712] defp taps(722), do: [722, 721, 718, 707] defp taps(723), do: [723, 717, 710, 707] defp taps(724), do: [724, 719, 716, 711] defp taps(725), do: [725, 720, 719, 716] defp taps(726), do: [726, 725, 722, 721] defp taps(727), do: [727, 721, 719, 716] defp taps(728), do: [728, 726, 725, 724] defp taps(729), do: [729, 726, 724, 718] defp taps(730), do: [730, 726, 715, 711] defp taps(731), do: [731, 729, 725, 723] defp taps(732), do: [732, 729, 728, 725] defp taps(733), do: [733, 731, 726, 725] defp taps(734), do: [734, 724, 721, 720] defp taps(735), do: [735, 733, 728, 727] defp taps(736), do: [736, 730, 728, 723] defp taps(737), do: [737, 736, 733, 732] defp taps(738), do: [738, 730, 729, 727] defp taps(739), do: [739, 731, 723, 721] defp taps(740), do: [740, 737, 728, 716] defp taps(741), do: [741, 738, 733, 732] defp taps(742), do: [742, 741, 738, 730] defp taps(743), do: [743, 742, 731, 730] defp taps(744), do: [744, 743, 733, 731] defp taps(745), do: [745, 740, 738, 737] defp taps(746), do: [746, 738, 733, 728] defp taps(747), do: [747, 743, 741, 737] defp taps(748), do: [748, 744, 743, 733] defp taps(749), do: [749, 748, 743, 742] defp taps(750), do: [750, 746, 741, 734] defp taps(751), do: [751, 750, 748, 740] defp taps(752), do: [752, 749, 732, 731] defp taps(753), do: [753, 748, 745, 740] defp taps(754), do: [754, 742, 740, 735] defp taps(755), do: [755, 754, 745, 743] defp taps(756), do: [756, 755, 747, 740] defp taps(757), do: [757, 756, 751, 750] defp taps(758), do: [758, 757, 746, 741] defp taps(759), do: [759, 757, 756, 750] defp taps(760), do: [760, 757, 747, 734] defp taps(761), do: [761, 760, 759, 758] defp taps(762), do: [762, 761, 755, 745] defp taps(763), do: [763, 754, 749, 747] defp taps(764), do: [764, 761, 759, 758] defp taps(765), do: [765, 760, 755, 754] defp taps(766), do: [766, 757, 747, 744] defp taps(767), do: [767, 763, 760, 759] defp taps(768), do: [768, 764, 751, 749] defp taps(769), do: [769, 763, 762, 760] defp taps(770), do: [770, 768, 765, 756] defp taps(771), do: [771, 765, 756, 754] defp taps(772), do: [772, 767, 766, 764] defp taps(773), do: [773, 767, 765, 763] defp taps(774), do: [774, 767, 760, 758] defp taps(775), do: [775, 771, 769, 768] defp taps(776), do: [776, 773, 764, 759] defp taps(777), do: [777, 776, 767, 761] defp taps(778), do: [778, 775, 762, 759] defp taps(779), do: [779, 776, 771, 769] defp taps(780), do: [780, 775, 772, 764] defp taps(781), do: [781, 779, 765, 764] defp taps(782), do: [782, 780, 779, 773] defp taps(783), do: [783, 782, 776, 773] defp taps(784), do: [784, 778, 775, 771] defp taps(785), do: [785, 780, 776, 775] defp taps(786), do: [786, 782, 780, 771] defp taps(1024), do: [1024, 1015, 1002, 1001] defp taps(2048), do: [2048, 2035, 2034, 2029] defp taps(4096), do: [4096, 4095, 4081, 4069] defp taps(size) do raise ArgumentError, message: "no entry for size #{size} found in the table of maximum-cycle LFSR taps" end end
lib/lfsr.ex
0.887979
0.702607
lfsr.ex
starcoder
defmodule AWS.Inspector do @moduledoc """ Amazon Inspector Amazon Inspector enables you to analyze the behavior of your AWS resources and to identify potential security issues. For more information, see [ Amazon Inspector User Guide](https://docs.aws.amazon.com/inspector/latest/userguide/inspector_introduction.html). """ alias AWS.Client alias AWS.Request def metadata do %AWS.ServiceMetadata{ abbreviation: nil, api_version: "2016-02-16", content_type: "application/x-amz-json-1.1", credential_scope: nil, endpoint_prefix: "inspector", global?: false, protocol: "json", service_id: "Inspector", signature_version: "v4", signing_name: "inspector", target_prefix: "InspectorService" } end @doc """ Assigns attributes (key and value pairs) to the findings that are specified by the ARNs of the findings. """ def add_attributes_to_findings(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "AddAttributesToFindings", input, options) end @doc """ Creates a new assessment target using the ARN of the resource group that is generated by `CreateResourceGroup`. If resourceGroupArn is not specified, all EC2 instances in the current AWS account and region are included in the assessment target. If the [service-linked role](https://docs.aws.amazon.com/inspector/latest/userguide/inspector_slr.html) isn’t already registered, this action also creates and registers a service-linked role to grant Amazon Inspector access to AWS Services needed to perform security assessments. You can create up to 50 assessment targets per AWS account. You can run up to 500 concurrent agents per AWS account. For more information, see [ Amazon Inspector Assessment Targets](https://docs.aws.amazon.com/inspector/latest/userguide/inspector_applications.html). """ def create_assessment_target(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "CreateAssessmentTarget", input, options) end @doc """ Creates an assessment template for the assessment target that is specified by the ARN of the assessment target. If the [service-linked role](https://docs.aws.amazon.com/inspector/latest/userguide/inspector_slr.html) isn’t already registered, this action also creates and registers a service-linked role to grant Amazon Inspector access to AWS Services needed to perform security assessments. """ def create_assessment_template(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "CreateAssessmentTemplate", input, options) end @doc """ Starts the generation of an exclusions preview for the specified assessment template. The exclusions preview lists the potential exclusions (ExclusionPreview) that Inspector can detect before it runs the assessment. """ def create_exclusions_preview(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "CreateExclusionsPreview", input, options) end @doc """ Creates a resource group using the specified set of tags (key and value pairs) that are used to select the EC2 instances to be included in an Amazon Inspector assessment target. The created resource group is then used to create an Amazon Inspector assessment target. For more information, see `CreateAssessmentTarget`. """ def create_resource_group(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "CreateResourceGroup", input, options) end @doc """ Deletes the assessment run that is specified by the ARN of the assessment run. """ def delete_assessment_run(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DeleteAssessmentRun", input, options) end @doc """ Deletes the assessment target that is specified by the ARN of the assessment target. """ def delete_assessment_target(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DeleteAssessmentTarget", input, options) end @doc """ Deletes the assessment template that is specified by the ARN of the assessment template. """ def delete_assessment_template(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DeleteAssessmentTemplate", input, options) end @doc """ Describes the assessment runs that are specified by the ARNs of the assessment runs. """ def describe_assessment_runs(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeAssessmentRuns", input, options) end @doc """ Describes the assessment targets that are specified by the ARNs of the assessment targets. """ def describe_assessment_targets(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeAssessmentTargets", input, options) end @doc """ Describes the assessment templates that are specified by the ARNs of the assessment templates. """ def describe_assessment_templates(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeAssessmentTemplates", input, options) end @doc """ Describes the IAM role that enables Amazon Inspector to access your AWS account. """ def describe_cross_account_access_role(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeCrossAccountAccessRole", input, options) end @doc """ Describes the exclusions that are specified by the exclusions' ARNs. """ def describe_exclusions(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeExclusions", input, options) end @doc """ Describes the findings that are specified by the ARNs of the findings. """ def describe_findings(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeFindings", input, options) end @doc """ Describes the resource groups that are specified by the ARNs of the resource groups. """ def describe_resource_groups(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeResourceGroups", input, options) end @doc """ Describes the rules packages that are specified by the ARNs of the rules packages. """ def describe_rules_packages(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeRulesPackages", input, options) end @doc """ Produces an assessment report that includes detailed and comprehensive results of a specified assessment run. """ def get_assessment_report(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "GetAssessmentReport", input, options) end @doc """ Retrieves the exclusions preview (a list of ExclusionPreview objects) specified by the preview token. You can obtain the preview token by running the CreateExclusionsPreview API. """ def get_exclusions_preview(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "GetExclusionsPreview", input, options) end @doc """ Information about the data that is collected for the specified assessment run. """ def get_telemetry_metadata(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "GetTelemetryMetadata", input, options) end @doc """ Lists the agents of the assessment runs that are specified by the ARNs of the assessment runs. """ def list_assessment_run_agents(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListAssessmentRunAgents", input, options) end @doc """ Lists the assessment runs that correspond to the assessment templates that are specified by the ARNs of the assessment templates. """ def list_assessment_runs(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListAssessmentRuns", input, options) end @doc """ Lists the ARNs of the assessment targets within this AWS account. For more information about assessment targets, see [Amazon Inspector Assessment Targets](https://docs.aws.amazon.com/inspector/latest/userguide/inspector_applications.html). """ def list_assessment_targets(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListAssessmentTargets", input, options) end @doc """ Lists the assessment templates that correspond to the assessment targets that are specified by the ARNs of the assessment targets. """ def list_assessment_templates(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListAssessmentTemplates", input, options) end @doc """ Lists all the event subscriptions for the assessment template that is specified by the ARN of the assessment template. For more information, see `SubscribeToEvent` and `UnsubscribeFromEvent`. """ def list_event_subscriptions(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListEventSubscriptions", input, options) end @doc """ List exclusions that are generated by the assessment run. """ def list_exclusions(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListExclusions", input, options) end @doc """ Lists findings that are generated by the assessment runs that are specified by the ARNs of the assessment runs. """ def list_findings(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListFindings", input, options) end @doc """ Lists all available Amazon Inspector rules packages. """ def list_rules_packages(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListRulesPackages", input, options) end @doc """ Lists all tags associated with an assessment template. """ def list_tags_for_resource(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListTagsForResource", input, options) end @doc """ Previews the agents installed on the EC2 instances that are part of the specified assessment target. """ def preview_agents(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "PreviewAgents", input, options) end @doc """ Registers the IAM role that grants Amazon Inspector access to AWS Services needed to perform security assessments. """ def register_cross_account_access_role(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "RegisterCrossAccountAccessRole", input, options) end @doc """ Removes entire attributes (key and value pairs) from the findings that are specified by the ARNs of the findings where an attribute with the specified key exists. """ def remove_attributes_from_findings(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "RemoveAttributesFromFindings", input, options) end @doc """ Sets tags (key and value pairs) to the assessment template that is specified by the ARN of the assessment template. """ def set_tags_for_resource(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "SetTagsForResource", input, options) end @doc """ Starts the assessment run specified by the ARN of the assessment template. For this API to function properly, you must not exceed the limit of running up to 500 concurrent agents per AWS account. """ def start_assessment_run(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "StartAssessmentRun", input, options) end @doc """ Stops the assessment run that is specified by the ARN of the assessment run. """ def stop_assessment_run(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "StopAssessmentRun", input, options) end @doc """ Enables the process of sending Amazon Simple Notification Service (SNS) notifications about a specified event to a specified SNS topic. """ def subscribe_to_event(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "SubscribeToEvent", input, options) end @doc """ Disables the process of sending Amazon Simple Notification Service (SNS) notifications about a specified event to a specified SNS topic. """ def unsubscribe_from_event(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "UnsubscribeFromEvent", input, options) end @doc """ Updates the assessment target that is specified by the ARN of the assessment target. If resourceGroupArn is not specified, all EC2 instances in the current AWS account and region are included in the assessment target. """ def update_assessment_target(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "UpdateAssessmentTarget", input, options) end end
lib/aws/generated/inspector.ex
0.853486
0.426859
inspector.ex
starcoder
defmodule AWS.SageMakerA2IRuntime do @moduledoc """ Amazon Augmented AI is in preview release and is subject to change. We do not recommend using this product in production environments. Amazon Augmented AI (Amazon A2I) adds the benefit of human judgment to any machine learning application. When an AI application can't evaluate data with a high degree of confidence, human reviewers can take over. This human review is called a human review workflow. To create and start a human review workflow, you need three resources: a *worker task template*, a *flow definition*, and a *human loop*. For information about these resources and prerequisites for using Amazon A2I, see [Get Started with Amazon Augmented AI](https://docs.aws.amazon.com/sagemaker/latest/dg/a2i-getting-started.html) in the Amazon SageMaker Developer Guide. This API reference includes information about API actions and data types that you can use to interact with Amazon A2I programmatically. Use this guide to: * Start a human loop with the `StartHumanLoop` operation when using Amazon A2I with a *custom task type*. To learn more about the difference between custom and built-in task types, see [Use Task Types ](https://docs.aws.amazon.com/sagemaker/latest/dg/a2i-task-types-general.html). To learn how to start a human loop using this API, see [Create and Start a Human Loop for a Custom Task Type ](https://docs.aws.amazon.com/sagemaker/latest/dg/a2i-start-human-loop.html#a2i-instructions-starthumanloop) in the Amazon SageMaker Developer Guide. * Manage your human loops. You can list all human loops that you have created, describe individual human loops, and stop and delete human loops. To learn more, see [Monitor and Manage Your Human Loop ](https://docs.aws.amazon.com/sagemaker/latest/dg/a2i-monitor-humanloop-results.html) in the Amazon SageMaker Developer Guide. Amazon A2I integrates APIs from various AWS services to create and start human review workflows for those services. To learn how Amazon A2I uses these APIs, see [Use APIs in Amazon A2I](https://docs.aws.amazon.com/sagemaker/latest/dg/a2i-api-references.html) in the Amazon SageMaker Developer Guide. """ @doc """ Deletes the specified human loop for a flow definition. """ def delete_human_loop(client, human_loop_name, input, options \\ []) do path_ = "/human-loops/#{URI.encode(human_loop_name)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, nil) end @doc """ Returns information about the specified human loop. """ def describe_human_loop(client, human_loop_name, options \\ []) do path_ = "/human-loops/#{URI.encode(human_loop_name)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Returns information about human loops, given the specified parameters. If a human loop was deleted, it will not be included. """ def list_human_loops(client, creation_time_after \\ nil, creation_time_before \\ nil, flow_definition_arn, max_results \\ nil, next_token \\ nil, sort_order \\ nil, options \\ []) do path_ = "/human-loops" headers = [] query_ = [] query_ = if !is_nil(sort_order) do [{"SortOrder", sort_order} | query_] else query_ end query_ = if !is_nil(next_token) do [{"NextToken", next_token} | query_] else query_ end query_ = if !is_nil(max_results) do [{"MaxResults", max_results} | query_] else query_ end query_ = if !is_nil(flow_definition_arn) do [{"FlowDefinitionArn", flow_definition_arn} | query_] else query_ end query_ = if !is_nil(creation_time_before) do [{"CreationTimeBefore", creation_time_before} | query_] else query_ end query_ = if !is_nil(creation_time_after) do [{"CreationTimeAfter", creation_time_after} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Starts a human loop, provided that at least one activation condition is met. """ def start_human_loop(client, input, options \\ []) do path_ = "/human-loops" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @doc """ Stops the specified human loop. """ def stop_human_loop(client, input, options \\ []) do path_ = "/human-loops/stop" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, nil) end @spec request(AWS.Client.t(), binary(), binary(), list(), list(), map(), list(), pos_integer()) :: {:ok, map() | nil, map()} | {:error, term()} defp request(client, method, path, query, headers, input, options, success_status_code) do client = %{client | service: "sagemaker"} host = build_host("a2i-runtime.sagemaker", 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/sage_maker_a2i_runtime.ex
0.787646
0.69259
sage_maker_a2i_runtime.ex
starcoder
defmodule PointOfInterest do alias PointOfInterest.Secrets, as: Secrets @moduledoc """ -->Takes a Country as Input -->Fetches top 100 cities -->Fetches Top 200 Points of Interest for Each City -->Writes the result to a file after parsing the data """ @base_url "https://www.triposo.com/api/20181213" def fetch_request_triposo(url) do %{account: account, token: token} = Secrets.triposo_ids() headers = ["X-Triposo-Account": account, "X-Triposo-Token": token] IO.inspect(headers) wait = :rand.uniform(5) * 1000 IO.puts("Lets Sleep for #{wait} milliseconds") :timer.sleep(wait) case HTTPoison.get(url, headers) do {:ok, %HTTPoison.Response{status_code: 200, body: body}} -> {:ok, body} {:ok, %HTTPoison.Response{status_code: _}} -> {:error, "Nothing"} {:error, %HTTPoison.Error{reason: reason}} -> {:error, reason} end end defp pmap(collection, func) do collection |> Enum.map(&Task.async(fn -> func.(&1) end)) |> Enum.map(&Task.await(&1, :infinity)) end defp get_cities(country) do url = "#{@base_url}/location.json?countrycode=#{country}&order_by=-score&count=100&fields=id,name" fetch_cities = Task.async(fn -> fetch_request_triposo(url) end) with {:ok, body} <- Task.await(fetch_cities, 25000) do response = Poison.decode!(body) Enum.map(response["results"], fn x -> %{:city => x["id"], :country => country} end) else _ -> {:error, "Cannot Fetch Cities"} end end def download_and_save_image(url, filename) when is_nil(url), do: nil def download_and_save_image(url, filename) do download_image = Task.async(fn -> case HTTPoison.get(url, [], follow_redirect: true, max_redirect: 10) do {:ok, %HTTPoison.Response{status_code: 200, body: body}} -> {:ok, body} {:ok, %HTTPoison.Response{status_code: _}} -> {:error, "Nothing"} _ -> {:error, "Cannot Download Image"} end end) with {:ok, body} <- Task.await(download_image, 30000) do File.write!("./poi_images/#{filename}.jpg", body) "/poi_images/#{filename}.jpg" else _ -> nil end end defp get_image(images, poi_id) do url = images |> Enum.fetch(0) |> (fn {:ok, value} -> value["sizes"]["thumbnail"]["url"] _ -> nil end).() download_and_save_image(url, poi_id) end defp parse_poi(poi) do case poi do %{ "name" => poi_name, "location_id" => poi_location, "coordinates" => poi_coordinates, "snippet" => poi_snippet, "images" => poi_images, "id" => poi_id } -> {:ok, %{ "type" => "Feature", "id" => poi_id, "properties" => %{ "osm_id" => poi_id, "other_tags" => "amenity, historic, tourism, attractions", "name" => poi_name, "place" => poi_location }, "geometry" => %{ "type" => "Point", "coordinates" => [poi_coordinates["longitude"], poi_coordinates["latitude"]] }, "extract" => poi_snippet, "image" => get_image(poi_images, poi_id), "random_text" => poi_snippet }} _ -> {:error, %{}} end end defp write_poi(poi, filename) do {:ok, cwd} = File.cwd() File.write!("#{cwd}/#{filename}", Poison.encode!(poi), [:write]) {:ok, poi} end def read_file_contents(filename) do {:ok, cwd} = File.cwd() case File.exists?("#{cwd}/#{filename}") do true -> File.read!("#{cwd}/#{filename}") |> Poison.decode() |> case do {:ok, contents} -> contents _ -> {:error, "Cannot Read File Contents"} end false -> %{ "type" => "FeatureCollection", "name" => "points", "crs" => %{ "type" => "name", "properties" => %{ "name" => "urn:ogc:def:crs:OGC:1.3:CRS84" } }, "features" => [] } end end defp get_poi(%{city: city, country: country}) do url = "#{@base_url}/poi.json?score=>=6&tag_labels=nightlife|topattractions|sightseeing|foodexperiences&location_id=#{ city }&countrycode=#{country}&order_by=-score&count=30" fetch_poi = Task.async(fn -> fetch_request_triposo(url) end) with {:ok, body} <- Task.await(fetch_poi, :infinity) do response = Poison.decode!(body) %{"results" => pois} = response pois |> pmap(&parse_poi(&1)) else _ -> {:error, "Cannot Fetch POI Data"} end end defp status_message({:ok, data}), do: "Wrote #{Enum.count(data)} succesfully" defp status_message(_), do: "Failed to wrote Data to file" def get_pois_for_country(%{country: country, filename: filename, city: city}) do all_pois = %{country: country, city: city} |> get_poi |> List.flatten() pois = for {:ok, data} <- all_pois, do: data {_, new_pois} = read_file_contents(filename) |> Map.get_and_update!("features", fn current_value -> {current_value, Enum.concat(current_value, pois)} end) write_poi(new_pois, filename) |> status_message |> IO.puts() end def get_pois_for_country(%{country: country, filename: filename}) do all_pois = country |> get_cities |> pmap(&get_poi(&1)) |> List.flatten() pois = for {:ok, data} <- all_pois, do: data {_, new_pois} = read_file_contents(filename) |> Map.get_and_update!("features", fn current_value -> {current_value, Enum.concat(current_value, pois)} end) write_poi(new_pois, filename) |> status_message |> IO.puts() end end
lib/point_of_interest.ex
0.646572
0.456531
point_of_interest.ex
starcoder
defmodule Plymio.Codi do @moduledoc ~S""" `Plymio.Codi` generates *quoted forms* for common code *patterns*. The `produce_codi/2` function produces the *quoted forms* for the *patterns*. The `reify_codi/2` macro calls `produce_codi/2` and then compiles the forms. ## Documentation Terms In the documentation below these terms, usually in *italics*, are used to mean the same thing. ### *opts* *opts* is a `Keyword` list. ### *form* and *forms* A *form* is a quoted form (`Macro.t`). A *forms* is a list of zero, one or more *form*s. ### *vekil* The proxy patterns (see below) use a dictionary called the *vekil*: The *proxy* can be though of as the *key* while its value (called a *from*) "realises" to a *form* / *forms*. The *vekil* implements the `Plymio.Vekil` protocol. If the vekil given to `new/1` or `update/2` is a `Map` or `Keyword`, it will be used to create a `Plymio.Vekil.Form` *vekil*. The *forom* in the *vekil* **must** "realise" (`Plymio.Vekil.Forom.realise/2`) to *forms*. It is more efficient to pre-create (ideally at compile time) the *vekil*; it can be edited later using e.g. `:proxy_put`. ## Options (*opts*) The first argument to both of these functions is an *opts*. The canonical form of a *pattern* definition in the *opts* is the key `:pattern` with an *opts* value specific to the *pattern* e.g. [pattern: [pattern: :delegate, name: :fun_one, arity: 1, module: ModuleA] The value is referred to as the *cpo* below, short for *codi pattern opts*. **All pattern definitions are normalised to this format.** However, for convenience, the key can be the *pattern* name (e.g. `:delegate`) and the value the (pre normalised) *cpo*: [delegate: [name: :fun_one, arity: 1, module: ModuleA] This example shows the code produced for the above: iex> {:ok, {forms, _}} = [ ...> delegate: [name: :fun_one, arity: 1, module: ModuleA], ...> ] |> produce_codi ...> forms |> harnais_helper_show_forms! ["@doc(\"Delegated to `ModuleA.fun_one/1`\")", "defdelegate(fun_one(var1), to: ModuleA)"] Also, again for convenience, some *patterns* will normalise the value. For example the `:doc` pattern normalises this: [doc: "This is a docstring"] into this: [pattern: [pattern: doc, doc: "This is a docstring"] The keys in the *cpo* have aliases. Note the aliases are pattern-specific. For examples `:args` is both an alias for `:spec_args` and `:fun_args`. Each pattern below lists its keys' aliases. ### Common Codi Pattern Opts Keys These are the keys that can appear in a *cpo* as well as the pattern-specific ones: | Key | Aliases | Role | | :--- | :--- | :--- | | `:pattern` | | *the name of the pattern* | | `:forms_edit` | *:form_edit, :edit_forms, :edit_form* | *forms_edit/2 opts* | > there are other, internal use, keys that can appear as well. ## Editing Pattern Forms Most patterns produce *forms*. Individual pattern *forms* can be edited by giving a `:forms_edit` key in the *cpo* where the value is an *opts* understood by `Plymio.Fontais.Form.forms_edit/2`. Alternatively the `:forms_edit` can be given in the *opts* to `produce_codi/2` (or `reify_codi/2`) and will be applied to *all* produced *forms*. ## Patterns There are a number of patterns, some having aliases, described below: | Pattern | Aliases | | :--- | :--- | | `:form` | *:forms, :ast, :asts* | | `:typespec_spec` | *:spec* | | `:doc` | | | `:since` | | | `:delegate` | | | `:delegate_module` | | | `:bang` | | | `:bang_module` | | | `:query` | | | `:query_module` | | | `:proxy_fetch` | *:proxy, :proxies, :proxies_fetch* | | `:proxy_put` | *:proxies_put* | | `:proxy_delete` | *:proxies_delete* | | `:proxy_get` | *:proxies_get* | | `:struct_get` | | | `:struct_fetch` | | | `:struct_put` | | | `:struct_maybe_put` | | | `:struct_has?` | | | `:struct_update` | | | `:struct_set` | | | `:struct_export` | | ### Pattern: *form* The *form* pattern is a convenience to embed arbitrary code. See `Plymio.Codi.Pattern.Other` for details and examples. ### Pattern: *typespec_spec* The *typespec_spec* pattern builds a `@spec` module attribute form. See `Plymio.Codi.Pattern.Typespec` for details and examples. ### Pattern: *doc* The *doc* pattern builds a `@doc` module attribute form. See `Plymio.Codi.Pattern.Doc` for details and examples. ### Pattern: *since* The *since* pattern builds a `@since` module attribute form. See `Plymio.Codi.Pattern.Other` for details and examples. ### Pattern: *deprecated* The *deprecated* pattern builds a `@deprecated` module attribute form. See `Plymio.Codi.Pattern.Other` for details and examples. ### Pattern: *delegate* and *delegate_module* The *delegate* pattern builds a `Kernel.defdelegate/2` call, together, optionally, with a `@doc`, `@since`, and/or `@spec`. The *delegate_module* pattern builds a `Kernel.defdelegate/2` call for one or more functions in a module. As with `:delegate` a `@doc` and/or `@since` can be generated at the same time. See `Plymio.Codi.Pattern.Delegate` for details and examples. ### Pattern: *bang* and *bang_module* The *bang* pattern builds bang functions (e.g. `myfun!(arg)`) using existing base functions (e.g. `myfun(arg)`). The *bang_module* pattern builds a bang function for one or more functions in a module. As with `:bang` a `@doc` or `@since` can be generated at the same time. See `Plymio.Codi.Pattern.Bang` for details and examples. ### Pattern: *query* and *query_module* The *query* pattern works like *bang* but builds a query function (e.g. `myfun?(arg)`) using a base function (e.g. `myfun(arg)`). The *query_module* pattern builds a query function for one or more functions in a module. As with `:query` a `@doc` or `@since` can be generated at the same time. See `Plymio.Codi.Pattern.Query` for details and examples. ### Pattern: *proxy* patterns The *proxy* patterns manage the *vekil*.. See `Plymio.Codi.Pattern.Proxy` for details and examples. ### Pattern: *struct* patterns The *struct* patterns create a range of transform functions for a module's struct. See `Plymio.Codi.Pattern.Struct` for details and examples. """ require Plymio.Vekil.Utility, as: VEKILUTIL require Plymio.Fontais.Option, as: PFO use Plymio.Fontais.Attribute use Plymio.Vekil.Attribute use Plymio.Codi.Attribute @codi_opts [ {@plymio_vekil_key_vekil, Plymio.Vekil.Codi.__vekil__()} ] import Plymio.Codi.Error, only: [ new_error_result: 1 ], warn: false import Plymio.Fontais.Guard, only: [ is_value_set: 1, is_value_unset: 1, is_value_unset_or_nil: 1 ] import Plymio.Fontais.Option, only: [ opzioni_flatten: 1, opts_create_aliases_dict: 1 ] import Plymio.Codi.Utility.Dispatch, only: [ validate_pattern_dispatch_vector: 1 ] import Plymio.Codi.Utility, only: [ validate_module_dict: 1, validate_fun_module: 1 ], warn: false import Plymio.Codi.CPO, only: [ cpo_get_status: 2, cpo_get_patterns: 1, cpo_put_set_struct_field: 3, cpo_edit_forms: 1 ] import Plymio.Funcio.Enum.Map.Collate, only: [ map_collate0_enum: 2 ] @plymio_codi_pattern_dicts @plymio_fontais_the_unset_value @plymio_codi_pattern_normalisers %{ @plymio_codi_pattern_form => &Plymio.Codi.Pattern.Other.cpo_pattern_form_normalise/1, @plymio_codi_pattern_doc => &Plymio.Codi.Pattern.Doc.cpo_pattern_doc_normalise/1, @plymio_codi_pattern_since => &Plymio.Codi.Pattern.Other.cpo_pattern_since_normalise/1, @plymio_codi_pattern_deprecated => &Plymio.Codi.Pattern.Other.cpo_pattern_deprecated_normalise/1, @plymio_codi_pattern_typespec_spec => &Plymio.Codi.Pattern.Typespec.cpo_pattern_typespec_spec_normalise/1, @plymio_codi_pattern_bang => &Plymio.Codi.Pattern.Bang.cpo_pattern_bang_normalise/1, @plymio_codi_pattern_bang_module => &Plymio.Codi.Pattern.Bang.cpo_pattern_bang_module_normalise/1, @plymio_codi_pattern_query => &Plymio.Codi.Pattern.Query.cpo_pattern_query_normalise/1, @plymio_codi_pattern_query_module => &Plymio.Codi.Pattern.Query.cpo_pattern_query_module_normalise/1, @plymio_codi_pattern_delegate => &Plymio.Codi.Pattern.Delegate.cpo_pattern_delegate_normalise/1, @plymio_codi_pattern_delegate_module => &Plymio.Codi.Pattern.Delegate.cpo_pattern_delegate_module_normalise/1, @plymio_codi_pattern_proxy_fetch => &Plymio.Codi.Pattern.Proxy.cpo_pattern_proxy_fetch_normalise/1, @plymio_codi_pattern_proxy_put => &Plymio.Codi.Pattern.Proxy.cpo_pattern_proxy_put_normalise/1, @plymio_codi_pattern_proxy_get => &Plymio.Codi.Pattern.Proxy.cpo_pattern_proxy_get_normalise/1, @plymio_codi_pattern_proxy_delete => &Plymio.Codi.Pattern.Proxy.cpo_pattern_proxy_delete_normalise/1, @plymio_codi_pattern_struct_export => &Plymio.Codi.Pattern.Struct.cpo_pattern_struct_export_normalise/1, @plymio_codi_pattern_struct_update => &Plymio.Codi.Pattern.Struct.cpo_pattern_struct_update_normalise/1, @plymio_codi_pattern_struct_set => &Plymio.Codi.Pattern.Struct.cpo_pattern_struct_set_normalise/1, @plymio_codi_pattern_struct_get => &Plymio.Codi.Pattern.Struct.cpo_pattern_struct_get_normalise/1, @plymio_codi_pattern_struct_get1 => &Plymio.Codi.Pattern.Struct.cpo_pattern_struct_get_normalise/1, @plymio_codi_pattern_struct_get2 => &Plymio.Codi.Pattern.Struct.cpo_pattern_struct_get_normalise/1, @plymio_codi_pattern_struct_fetch => &Plymio.Codi.Pattern.Struct.cpo_pattern_struct_fetch_normalise/1, @plymio_codi_pattern_struct_put => &Plymio.Codi.Pattern.Struct.cpo_pattern_struct_put_normalise/1, @plymio_codi_pattern_struct_maybe_put => &Plymio.Codi.Pattern.Struct.cpo_pattern_struct_maybe_put_normalise/1, @plymio_codi_pattern_struct_has? => &Plymio.Codi.Pattern.Struct.cpo_pattern_struct_has_normalise/1 } @plymio_codi_pattern_express_dispatch %{ @plymio_codi_pattern_form => &Plymio.Codi.Pattern.Other.express_pattern/3, @plymio_codi_pattern_doc => &Plymio.Codi.Pattern.Doc.express_pattern/3, @plymio_codi_pattern_since => &Plymio.Codi.Pattern.Other.express_pattern/3, @plymio_codi_pattern_deprecated => &Plymio.Codi.Pattern.Other.express_pattern/3, @plymio_codi_pattern_typespec_spec => &Plymio.Codi.Pattern.Typespec.express_pattern/3, @plymio_codi_pattern_bang => &Plymio.Codi.Pattern.Bang.express_pattern/3, @plymio_codi_pattern_bang_module => &Plymio.Codi.Pattern.Bang.express_pattern/3, @plymio_codi_pattern_query => &Plymio.Codi.Pattern.Query.express_pattern/3, @plymio_codi_pattern_query_module => &Plymio.Codi.Pattern.Query.express_pattern/3, @plymio_codi_pattern_delegate => &Plymio.Codi.Pattern.Delegate.express_pattern/3, @plymio_codi_pattern_delegate_module => &Plymio.Codi.Pattern.Delegate.express_pattern/3, @plymio_codi_pattern_proxy_fetch => &Plymio.Codi.Pattern.Proxy.express_pattern/3, @plymio_codi_pattern_proxy_put => &Plymio.Codi.Pattern.Proxy.express_pattern/3, @plymio_codi_pattern_proxy_get => &Plymio.Codi.Pattern.Proxy.express_pattern/3, @plymio_codi_pattern_proxy_delete => &Plymio.Codi.Pattern.Proxy.express_pattern/3, @plymio_codi_pattern_struct_update => &Plymio.Codi.Pattern.Struct.express_pattern/3, @plymio_codi_pattern_struct_export => &Plymio.Codi.Pattern.Struct.express_pattern/3, @plymio_codi_pattern_struct_set => &Plymio.Codi.Pattern.Struct.express_pattern/3, @plymio_codi_pattern_struct_get => &Plymio.Codi.Pattern.Struct.express_pattern/3, @plymio_codi_pattern_struct_get1 => &Plymio.Codi.Pattern.Struct.express_pattern/3, @plymio_codi_pattern_struct_get2 => &Plymio.Codi.Pattern.Struct.express_pattern/3, @plymio_codi_pattern_struct_fetch => &Plymio.Codi.Pattern.Struct.express_pattern/3, @plymio_codi_pattern_struct_put => &Plymio.Codi.Pattern.Struct.express_pattern/3, @plymio_codi_pattern_struct_maybe_put => &Plymio.Codi.Pattern.Struct.express_pattern/3, @plymio_codi_pattern_struct_has? => &Plymio.Codi.Pattern.Struct.express_pattern/3 } @plymio_codi_stage_dispatch [ {@plymio_codi_stage_normalise, &__MODULE__.Stage.Normalise.produce_stage/1}, {@plymio_codi_stage_commit, &__MODULE__.Stage.Commit.produce_stage/1}, {@plymio_codi_stage_express, &__MODULE__.Stage.Express.produce_stage/1}, {@plymio_codi_stage_review, &__MODULE__.Stage.Review.produce_stage/1} ] @plymio_codi_kvs_verb [ # struct @plymio_codi_field_alias_snippets, @plymio_codi_field_alias_stage_dispatch, @plymio_codi_field_alias_patterns, @plymio_codi_field_alias_pattern_dicts, @plymio_codi_field_alias_pattern_normalisers, @plymio_codi_field_alias_pattern_express_dispatch, @plymio_codi_field_alias_forms, @plymio_codi_field_alias_forms_edit, @plymio_codi_field_alias_vekil, @plymio_codi_field_alias_module_fva_dict, @plymio_codi_field_alias_module_doc_dict, # virtual @plymio_codi_pattern_alias_form, @plymio_codi_pattern_alias_doc, @plymio_codi_pattern_alias_typespec_spec, @plymio_codi_pattern_alias_since, @plymio_codi_pattern_alias_deprecated, @plymio_codi_pattern_alias_bang, @plymio_codi_pattern_alias_bang_module, @plymio_codi_pattern_alias_query, @plymio_codi_pattern_alias_query_module, @plymio_codi_pattern_alias_delegate, @plymio_codi_pattern_alias_delegate_module, @plymio_codi_pattern_alias_proxy_fetch, @plymio_codi_pattern_alias_proxy_put, @plymio_codi_pattern_alias_proxy_get, @plymio_codi_pattern_alias_proxy_delete, @plymio_codi_pattern_alias_struct_export, @plymio_codi_pattern_alias_struct_update, @plymio_codi_pattern_alias_struct_set, @plymio_codi_pattern_alias_struct_get, @plymio_codi_pattern_alias_struct_get1, @plymio_codi_pattern_alias_struct_get2, @plymio_codi_pattern_alias_struct_fetch, @plymio_codi_pattern_alias_struct_put, @plymio_codi_pattern_alias_struct_maybe_put, @plymio_codi_pattern_alias_struct_has?, @plymio_codi_key_alias_pattern ] @plymio_codi_dict_verb @plymio_codi_kvs_verb |> opts_create_aliases_dict @plymio_codi_defstruct [ {@plymio_codi_field_snippets, @plymio_fontais_the_unset_value}, {@plymio_codi_field_stage_dispatch, @plymio_codi_stage_dispatch}, {@plymio_codi_field_patterns, @plymio_fontais_the_unset_value}, {@plymio_codi_field_pattern_express_dispatch, @plymio_codi_pattern_express_dispatch}, {@plymio_codi_field_pattern_dicts, @plymio_codi_pattern_dicts}, {@plymio_codi_field_pattern_normalisers, @plymio_codi_pattern_normalisers}, {@plymio_codi_field_forms, @plymio_fontais_the_unset_value}, {@plymio_codi_field_forms_edit, @plymio_fontais_the_unset_value}, {@plymio_codi_field_vekil, @plymio_fontais_the_unset_value}, {@plymio_codi_field_module_fva_dict, @plymio_fontais_the_unset_value}, {@plymio_codi_field_module_doc_dict, @plymio_fontais_the_unset_value} ] defstruct @plymio_codi_defstruct @type t :: %__MODULE__{} @type kv :: Plymio.Fontais.kv() @type opts :: Plymio.Fontais.opts() @type error :: Plymio.Fontais.error() @type result :: Plymio.Fontais.result() @type form :: Plymio.Fontais.form() @type forms :: Plymio.Fontais.forms() @doc false def update_canonical_opts(opts, dict \\ @plymio_codi_dict_verb) do opts |> PFO.opts_canonical_keys(dict) end [ :state_base_package, :state_defp_update_field_header, :state_defp_update_proxy_field_normalise ] |> VEKILUTIL.reify_proxies( @codi_opts ++ [ {@plymio_fontais_key_rename_atoms, [proxy_field: @plymio_codi_field_module_fva_dict]}, {@plymio_fontais_key_rename_funs, [proxy_field_normalise: :validate_module_dict]} ] ) defp update_field(%__MODULE__{} = state, {k, v}) when k == @plymio_codi_field_vekil do cond do Plymio.Vekil.Utility.vekil?(v) -> {:ok, state |> struct!([{@plymio_codi_field_vekil, v}])} true -> with {:ok, vekil} <- [{@plymio_vekil_field_dict, v}] |> Plymio.Vekil.Form.new() do {:ok, state |> struct!([{@plymio_codi_field_vekil, vekil}])} else {:error, %{__exception__: true}} = result -> result end end end defp update_field(%__MODULE__{} = state, {k, v}) when k in @plymio_codi_pattern_types or k == @plymio_codi_key_pattern do state |> add_snippets({k, v}) end defp update_field(%__MODULE__{} = state, {k, v}) when k == @plymio_codi_field_pattern_express_dispatch do with {:ok, dispatch_vector} <- v |> validate_pattern_dispatch_vector do state |> struct!([{@plymio_codi_field_pattern_express_dispatch, dispatch_vector}]) else {:error, %{__exception__: true}} = result -> result end end :state_defp_update_proxy_field_keyword |> VEKILUTIL.reify_proxies( @codi_opts ++ [ {@plymio_fontais_key_rename_atoms, [proxy_field: @plymio_codi_field_forms_edit]} ] ) :state_defp_update_proxy_field_opzioni_validate |> VEKILUTIL.reify_proxies( @codi_opts ++ [ {@plymio_fontais_key_rename_atoms, [proxy_field: @plymio_codi_field_patterns]} ] ) :state_defp_update_proxy_field_passthru |> VEKILUTIL.reify_proxies( @codi_opts ++ [ {@plymio_fontais_key_rename_atoms, [proxy_field: @plymio_codi_field_snippets]} ] ) :state_defp_update_field_unknown |> VEKILUTIL.reify_proxies(@codi_opts) @plymio_codi_defstruct_updaters @plymio_codi_defstruct for {name, _} <- @plymio_codi_defstruct_updaters do update_fun = "update_#{name}" |> String.to_atom() @doc false def unquote(update_fun)(%__MODULE__{} = state, value) do state |> update([{unquote(name), value}]) end end @plymio_codi_defstruct_reseters @plymio_codi_defstruct |> Keyword.take([ @plymio_codi_field_snippets, @plymio_codi_field_patterns ]) for {name, _} <- @plymio_codi_defstruct_reseters do reset_fun = "reset_#{name}" |> String.to_atom() @doc false def unquote(reset_fun)(%__MODULE__{} = state, value \\ @plymio_fontais_the_unset_value) do state |> update([{unquote(name), value}]) end end defp add_snippets(state, patterns) defp add_snippets(%__MODULE__{@plymio_codi_field_snippets => snippets} = state, new_snippets) do snippets |> case do x when is_value_unset(x) -> state |> update_snippets(List.wrap(new_snippets)) x when is_list(x) -> state |> update_snippets(x ++ List.wrap(new_snippets)) end end [ :doc_false, :workflow_def_produce ] |> VEKILUTIL.reify_proxies( @codi_opts ++ [ {@plymio_fontais_key_postwalk, fn {:express, ctx, args} -> {:produce_recurse, ctx, args} :PRODUCESTAGESTRUCT -> __MODULE__ x -> x end} ] ) @doc false @since "0.1.0" @spec produce_recurse(t) :: {:ok, {opts, t}} | {:error, error} def produce_recurse(codi) def produce_recurse(%__MODULE__{@plymio_codi_field_snippets => snippets} = state) when is_value_set(snippets) do with {:ok, {_product, %__MODULE__{} = state}} <- state |> __MODULE__.Stage.Normalise.normalise_snippets(), {:ok, %__MODULE__{} = state} = state |> reset_snippets, {:ok, {_product, %__MODULE__{}}} = result <- state |> produce_recurse do result else {:error, %{__exception__: true}} = result -> result end end def produce_recurse(%__MODULE__{} = state) do with {:ok, {product, state}} <- state |> produce_stages, {:ok, cpos} <- product |> cpo_get_patterns do # unless all cpos have status "done" need to recurse. default is done. cpos |> map_collate0_enum(fn cpo -> cpo |> cpo_get_status(@plymio_codi_status_done) end) |> case do {:error, %{__struct__: _}} = result -> result {:ok, statuses} -> statuses |> Enum.all?(fn status -> status == @plymio_codi_status_done end) |> case do true -> {:ok, {product, state}} _ -> state |> produce_recurse end end else {:error, %{__exception__: true}} = result -> result end end @since "0.1.0" @spec produce_codi(any, any) :: {:ok, {forms, t}} | {:error, error} def produce_codi(opts, codi_or_opts \\ []) def produce_codi(opts, %__MODULE__{} = state) do # need to reset patterns to stop infinite recursion with {:ok, %__MODULE__{} = state} <- state |> reset_patterns, {:ok, %__MODULE__{} = state} <- state |> reset_snippets, {:ok, %__MODULE__{} = state} <- state |> update(opts), {:ok, {opts_patterns, %__MODULE__{} = state}} <- state |> produce, {:ok, opzionis} <- opts_patterns |> cpo_get_patterns, {:ok, cpo} <- opzionis |> opzioni_flatten, {:ok, cpo} <- cpo |> cpo_put_set_struct_field(state, @plymio_codi_field_forms_edit), {:ok, forms} <- cpo |> cpo_edit_forms do {:ok, {forms, state}} else {:error, %{__exception__: true}} = result -> result end end def produce_codi(opts, new_opts) do with {:ok, %__MODULE__{} = state} <- new_opts |> new, {:ok, _} = result <- opts |> produce_codi(state) do result else {:error, %{__exception__: true}} = result -> result end end defmacro reify_codi(opts \\ [], other_opts \\ []) do module = __CALLER__.module quote bind_quoted: [opts: opts, other_opts: other_opts, module: module] do with {:ok, {forms, _}} <- opts |> Plymio.Codi.produce_codi(other_opts), {:ok, forms} <- forms |> Plymio.Fontais.Form.forms_normalise() do result = try do forms |> Code.eval_quoted([], __ENV__) |> case do {_, _} = value -> {:ok, value} value -> {:error, %RuntimeError{message: "Code.eval_quoted failed, got: #{inspect(value)}"}} end rescue error -> {:error, error} end {:ok, [ {:forms, forms}, {:module, module}, {:result, result} ]} else {:error, %{__exception__: true} = error} -> raise error end end end [ :doc_false, :workflow_def_produce_stages ] |> VEKILUTIL.reify_proxies( @codi_opts ++ [ {@plymio_fontais_key_postwalk, fn :produce_stage_field -> @plymio_codi_field_stage_dispatch :PRODUCESTAGESTRUCT -> __MODULE__ x -> x end} ] ) defmacro __using__(_opts \\ []) do quote do require Plymio.Codi, as: CODI require Plymio.Fontais.Guard use Plymio.Fontais.Attribute use Plymio.Codi.Attribute end end end defimpl Inspect, for: Plymio.Codi do use Plymio.Codi.Attribute import Plymio.Fontais.Guard, only: [ is_value_unset: 1 ] def inspect( %Plymio.Codi{ @plymio_codi_field_vekil => vekil, @plymio_codi_field_snippets => snippets, @plymio_codi_field_patterns => patterns, @plymio_codi_field_forms => forms }, _opts ) do vekil_telltale = vekil |> case do x when is_value_unset(x) -> nil x -> "K=#{inspect(x)}" end snippets_telltale = snippets |> case do x when is_value_unset(x) -> nil x when is_list(x) -> "S=#{x |> length}" _ -> "S=?" end patterns_telltale = patterns |> case do x when is_value_unset(x) -> nil x when is_list(x) -> [ "P=#{x |> length}/(", x |> Stream.take(5) |> Stream.map(fn opts -> opts |> Keyword.new() |> Keyword.get(@plymio_codi_key_pattern) |> to_string end) |> Enum.join(","), ")" ] |> Enum.join() end forms_telltale = forms |> case do x when is_value_unset(x) -> nil x when is_list(x) -> "F=#{x |> length}" end codi_telltale = [ snippets_telltale, patterns_telltale, forms_telltale, vekil_telltale ] |> List.flatten() |> Enum.reject(&is_nil/1) |> Enum.join("; ") "CODI(#{codi_telltale})" end end
lib/codi/codi.ex
0.902876
0.684238
codi.ex
starcoder
defmodule AwsExRay.Subsegment do @moduledoc ~S""" This module provides data structure which represents X-Ray's **subsegment** """ alias AwsExRay.Record.Error alias AwsExRay.Record.SQL alias AwsExRay.Record.HTTPRequest alias AwsExRay.Record.HTTPResponse alias AwsExRay.Segment alias AwsExRay.Subsegment.Formatter alias AwsExRay.Trace alias AwsExRay.Util @type namespace :: :none | :remote | :aws @type t :: %__MODULE__{ segment: Segment.t, namespace: namespace, sql: SQL.t | nil, aws: map | nil, } defstruct segment: nil, namespace: :none, sql: nil, aws: nil @spec new( trace :: Trace.t, name :: String.t, namespace :: namespace ) :: t def new(trace, name, namespace \\ :none) do %__MODULE__{ segment: Segment.new(trace, name), namespace: namespace, sql: nil, aws: nil } end @spec id(seg :: t) :: String.t def id(seg), do: seg.segment.id @spec add_annotations( seg :: t, annotations :: map ) :: t def add_annotations(seg, annotations) do annotations |> Enum.reduce(seg, fn {key, value}, seg -> add_annotation(seg, key, value) end) end @spec add_annotation( seg :: t, key :: atom | String.t, value :: any ) :: t def add_annotation(seg, key, value) do annotation = seg.segment.annotation annotation = Map.put(annotation, key, value) put_in(seg.segment.annotation, annotation) end @spec set_aws(seg :: t, params :: map) :: t def set_aws(seg, params) do Map.put(seg, :aws, params) end @spec set_start_time(seg :: t, start_time :: float) :: t def set_start_time(seg, start_time) do put_in(seg.segment.start_time, start_time) end @spec get_trace(seg :: t) :: Trace.t def get_trace(seg) do seg.segment.trace end @spec set_sql(seg :: t, sql :: SQL.t) :: t def set_sql(seg, sql) do Map.put(seg, :sql, sql) end @spec set_http_request(seg :: t, req :: HTTPRequest.t) :: t def set_http_request(seg, req) do put_in(seg.segment.http.request, req) end @spec set_http_response(seg :: t, res :: HTTPResponse.t) :: t def set_http_response(seg, res) do put_in(seg.segment.http.response, res) end @spec set_error(seg :: t, error :: Error.t) :: t def set_error(seg, error) do put_in(seg.segment.error, error) end @spec generate_trace_value(seg :: t) :: String.t def generate_trace_value(seg) do trace = seg.segment.trace trace = %{trace|parent: seg.segment.id} Trace.to_string(trace) end @spec sampled?(seg :: t) :: boolean def sampled?(seg) do Segment.sampled?(seg.segment) end @spec finished?(seg :: t) :: boolean def finished?(seg) do seg.segment.end_time > 0 end @spec finish(seg :: t, end_time :: float) :: t def finish(seg, end_time \\ Util.now()) do if finished?(seg) do seg else put_in(seg.segment.end_time, end_time) end end @spec to_json(seg :: t) :: String.t def to_json(seg), do: Formatter.to_json(seg) end
lib/aws_ex_ray/subsegment.ex
0.814311
0.434341
subsegment.ex
starcoder
defmodule Raxx.Server do @moduledoc """ Interface to handle server side communication in an HTTP message exchange. *Using `Raxx.Server` allows an application to be run on multiple adapters. For example [Ace](https://github.com/CrowdHailer/Ace) has several adapters for different versions of the HTTP protocol, HTTP/1.x and HTTP/2* ## Getting Started **Send complete response after receiving complete request.** defmodule EchoServer do use Raxx.Server def handle_request(%Raxx.Request{method: :POST, path: [], body: body}, _state) do response(:ok) |> set_header("content-type", "text/plain") |> set_body(body) end end **Send complete response as soon as request headers are received.** defmodule SimpleServer do use Raxx.Server def handle_head(%Raxx.Request{method: :GET, path: []}, _state) do response(:ok) |> set_header("content-type", "text/plain") |> set_body("Hello, World!") end end **Store data as it is available from a clients request** defmodule StreamingRequest do use Raxx.Server def handle_head(%Raxx.Request{method: :PUT, body: true}, _state) do {:ok, io_device} = File.open("my/path") {[], {:file, device}} end def handle_body(body, state = {:file, device}) do IO.write(device, body) {[], state} end def handle_tail(_trailers, state) do response(:see_other) |> set_header("location", "/") end end **Subscribe server to event source and forward notifications to client.** defmodule SubscribeToMessages do use Raxx.Server def handle_head(_request, _state) do {:ok, _} = ChatRoom.join() response(:ok) |> set_header("content-type", "text/event-stream") |> set_body(true) end def handle_info({ChatRoom, data}, state) do {[body(data)], state} end end ### Notes - `handle_head/2` will always be called with a request that has body as a boolean. For small requests where buffering the whole request is acceptable a simple middleware can be used. - Acceptable return values are the same for all callbacks; either a `Raxx.Response`, which must be complete or a list of message parts and a new state. ## Streaming `Raxx.Server` defines an interface to stream the body of request and responses. This has several advantages: - Large payloads do not need to be help in memory - Server can push information as it becomes available, using Server Sent Events. - If a request has invalid headers then a reply can be set without handling the body. - Content can be generated as requested using HTTP/2 flow control The body of a Raxx message (Raxx.Request or `Raxx.Response`) may be one of three types: - `io_list` - This is the complete body for the message. - `:false` - There **is no** body, for example `:GET` requests never have a body. - `:true` - There **is** a body, it can be processed as it is received ## Server Isolation To start an exchange a client sends a request. The server, upon receiving this message, sends a reply. A logical HTTP exchange consists of a single request and response. Methods such as [pipelining](https://en.wikipedia.org/wiki/HTTP_pipelining) and [multiplexing](http://qnimate.com/what-is-multiplexing-in-http2/) combine multiple logical exchanges onto a single connection. This is done to improve performance and is a detail not exposed a server. A Raxx server handles a single HTTP exchange. Therefore a single connection my have multiple servers each isolated in their own process. ## Termination An exchange can be stopped early by terminating the server process. Support for early termination is not consistent between versions of HTTP. - HTTP/2: server exit with reason `:normal`, stream reset with error `CANCEL`. - HTTP/2: server exit any other reason, stream reset with error `INTERNAL_ERROR`. - HTTP/1.x: server exit with any reason, connection is closed. `Raxx.Server` does not provide a terminate callback. Any cleanup that needs to be done from an aborted exchange should be handled by monitoring the server process. """ @typedoc """ alias for Raxx.Request type. """ @type request :: Raxx.Request.t() @typedoc """ State of application server. Original value is the configuration given when starting the raxx application. """ @type state :: any() @typedoc """ Set of all components that make up a message to or from server. """ @type part :: Raxx.Request.t() | Raxx.Response.t() | Raxx.Data.t() | Raxx.Tail.t() @typedoc """ Possible return values instructing server to send client data and update state if appropriate. """ @type next :: {[part], state} | Raxx.Response.t() @doc """ Called with a complete request once all the data parts of a body are received. Passed a `Raxx.Request` and server configuration. Note the value of the request body will be a string. This callback will never be called if handle_head/handle_body/handle_tail are overwritten. """ @callback handle_request(request, state()) :: next @doc """ Called once when a client starts a stream, Passed a `Raxx.Request` and server configuration. Note the value of the request body will be a boolean. This callback can be relied upon to execute before any other callbacks """ @callback handle_head(request, state()) :: next @doc """ Called every time data from the request body is received """ @callback handle_data(binary(), state()) :: next @doc """ Called once when a request finishes. This will be called with an empty list of headers is request is completed without trailers. """ @callback handle_tail([{binary(), binary()}], state()) :: next @doc """ Called for all other messages the server may recieve """ @callback handle_info(any(), state()) :: next defmacro __using__(_opts) do quote do @behaviour unquote(__MODULE__) use Raxx.NotFound import Raxx alias Raxx.{Request, Response} end end @doc false def is_implemented?(module) when is_atom(module) do if Code.ensure_compiled?(module) do module.module_info[:attributes] |> Keyword.get(:behaviour, []) |> Enum.member?(__MODULE__) else false end end end
lib/raxx/server.ex
0.869687
0.48621
server.ex
starcoder
defmodule Day15 do def find_next_vertex(not_visited) do not_visited |> Enum.min_by(&elem(&1, 1)) end def iterate({weights, visited, not_visited}) do {vertex, vertex_distance} = find_next_vertex(not_visited) visited = Map.put(visited, vertex, vertex_distance) not_visited = Map.delete(not_visited, vertex) not_visited = vertex |> Grid.get_adjacent_positions(weights) |> Enum.reject(&Map.has_key?(visited, &1)) |> Enum.reduce(not_visited, fn v, not_visited -> v_weight = Grid.get(weights, v) Map.update(not_visited, v, vertex_distance + v_weight, fn v_distance -> min(vertex_distance + v_weight, v_distance) end) end) {weights, visited, not_visited} end def find_path({w, v, nv}, from, to) do nv = Map.put(nv, from, 0) find_path({w, v, nv}, to) end def find_path({w, v, nv}, to) do if Map.has_key?(v, to) do {w, v, nv} else {w, v, nv} = iterate({w, v, nv}) find_path({w, v, nv}, to) end end def build_entire_cave(w) do cave = Grid.new(w.width * 5, w.height * 5) cave |> Grid.get_all_points() |> Enum.reduce(cave, fn {x, y}, cave -> tile_x = div(x, w.width) w_x = rem(x, w.width) tile_y = div(y, w.height) w_y = rem(y, w.height) w_val = Grid.get({w_x, w_y}, w) cave_val = w_val + tile_x + tile_y cave_val = if cave_val > 9, do: cave_val - 9, else: cave_val Grid.put({x, y}, cave, cave_val) end) end def part_1(contents) do w = Grid.new(contents) {_w, v, _nv} = {w, %{}, %{}} |> find_path(0, w.size - 1) v[w.size - 1] end @spec part_2(binary) :: nil | maybe_improper_list | map def part_2(contents) do w = Grid.new(contents) w = w |> build_entire_cave() {_w, v, _nv} = {w, %{}, %{}} |> find_path(0, w.size - 1) v[w.size - 1] end def main do {:ok, contents} = File.read("data/day15.txt") IO.inspect(contents |> part_1(), label: "part 1") IO.inspect(contents |> part_2(), label: "part 2") end end
aoc21/lib/day15.ex
0.744099
0.402363
day15.ex
starcoder
defmodule AWS.Chime do @moduledoc """ The Amazon Chime API (application programming interface) is designed for developers to perform key tasks, such as creating and managing Amazon Chime accounts, users, and Voice Connectors. This guide provides detailed information about the Amazon Chime API, including operations, types, inputs and outputs, and error codes. It also includes some server-side API actions to use with the Amazon Chime SDK. For more information about the Amazon Chime SDK, see [Using the Amazon Chime SDK](https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the *Amazon Chime Developer Guide*. You can use an AWS SDK, the AWS Command Line Interface (AWS CLI), or the REST API to make API calls. We recommend using an AWS SDK or the AWS CLI. Each API operation includes links to information about using it with a language-specific AWS SDK or the AWS CLI. ## Definitions ### Using an AWS SDK You don't need to write code to calculate a signature for request authentication. The SDK clients authenticate your requests by using access keys that you provide. For more information about AWS SDKs, see the [AWS Developer Center](http://aws.amazon.com/developer/). ### Using the AWS CLI Use your access keys with the AWS CLI to make API calls. For information about setting up the AWS CLI, see [Installing the AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/installing.html) in the *AWS Command Line Interface User Guide*. For a list of available Amazon Chime commands, see the [Amazon Chime commands](https://docs.aws.amazon.com/cli/latest/reference/chime/index.html) in the *AWS CLI Command Reference*. ### Using REST API If you use REST to make API calls, you must authenticate your request by providing a signature. Amazon Chime supports signature version 4. For more information, see [Signature Version 4 Signing Process](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html) in the *Amazon Web Services General Reference*. When making REST API calls, use the service name `chime` and REST endpoint `https://service.chime.aws.amazon.com`. Administrative permissions are controlled using AWS Identity and Access Management (IAM). For more information, see [Identity and Access Management for Amazon Chime](https://docs.aws.amazon.com/chime/latest/ag/security-iam.html) in the *Amazon Chime Administration Guide*. """ @doc """ Associates a phone number with the specified Amazon Chime user. """ def associate_phone_number_with_user(client, account_id, user_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/users/#{URI.encode(user_id)}?operation=associate-phone-number" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Associates phone numbers with the specified Amazon Chime Voice Connector. """ def associate_phone_numbers_with_voice_connector(client, voice_connector_id, input, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}?operation=associate-phone-numbers" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Associates phone numbers with the specified Amazon Chime Voice Connector group. """ def associate_phone_numbers_with_voice_connector_group(client, voice_connector_group_id, input, options \\ []) do path_ = "/voice-connector-groups/#{URI.encode(voice_connector_group_id)}?operation=associate-phone-numbers" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Associates the specified sign-in delegate groups with the specified Amazon Chime account. """ def associate_signin_delegate_groups_with_account(client, account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}?operation=associate-signin-delegate-groups" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Creates up to 100 new attendees for an active Amazon Chime SDK meeting. For more information about the Amazon Chime SDK, see [Using the Amazon Chime SDK](https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the *Amazon Chime Developer Guide*. """ def batch_create_attendee(client, meeting_id, input, options \\ []) do path_ = "/meetings/#{URI.encode(meeting_id)}/attendees?operation=batch-create" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 201) end @doc """ Adds up to 50 members to a chat room in an Amazon Chime Enterprise account. Members can be either users or bots. The member role designates whether the member is a chat room administrator or a general chat room member. """ def batch_create_room_membership(client, account_id, room_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/rooms/#{URI.encode(room_id)}/memberships?operation=batch-create" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 201) end @doc """ Moves phone numbers into the **Deletion queue**. Phone numbers must be disassociated from any users or Amazon Chime Voice Connectors before they can be deleted. Phone numbers remain in the **Deletion queue** for 7 days before they are deleted permanently. """ def batch_delete_phone_number(client, input, options \\ []) do path_ = "/phone-numbers?operation=batch-delete" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Suspends up to 50 users from a `Team` or `EnterpriseLWA` Amazon Chime account. For more information about different account types, see [Managing Your Amazon Chime Accounts](https://docs.aws.amazon.com/chime/latest/ag/manage-chime-account.html) in the *Amazon Chime Administration Guide*. Users suspended from a `Team` account are disassociated from the account, but they can continue to use Amazon Chime as free users. To remove the suspension from suspended `Team` account users, invite them to the `Team` account again. You can use the `InviteUsers` action to do so. Users suspended from an `EnterpriseLWA` account are immediately signed out of Amazon Chime and can no longer sign in. To remove the suspension from suspended `EnterpriseLWA` account users, use the `BatchUnsuspendUser` action. To sign out users without suspending them, use the `LogoutUser` action. """ def batch_suspend_user(client, account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/users?operation=suspend" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Removes the suspension from up to 50 previously suspended users for the specified Amazon Chime `EnterpriseLWA` account. Only users on `EnterpriseLWA` accounts can be unsuspended using this action. For more information about different account types, see [Managing Your Amazon Chime Accounts](https://docs.aws.amazon.com/chime/latest/ag/manage-chime-account.html) in the *Amazon Chime Administration Guide*. Previously suspended users who are unsuspended using this action are returned to `Registered` status. Users who are not previously suspended are ignored. """ def batch_unsuspend_user(client, account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/users?operation=unsuspend" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Updates phone number product types or calling names. You can update one attribute at a time for each `UpdatePhoneNumberRequestItem`. For example, you can update either the product type or the calling name. For product types, choose from Amazon Chime Business Calling and Amazon Chime Voice Connector. For toll-free numbers, you must use the Amazon Chime Voice Connector product type. Updates to outbound calling names can take up to 72 hours to complete. Pending updates to outbound calling names must be complete before you can request another update. """ def batch_update_phone_number(client, input, options \\ []) do path_ = "/phone-numbers?operation=batch-update" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Updates user details within the `UpdateUserRequestItem` object for up to 20 users for the specified Amazon Chime account. Currently, only `LicenseType` updates are supported for this action. """ def batch_update_user(client, account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/users" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Creates an Amazon Chime account under the administrator's AWS account. Only `Team` account types are currently supported for this action. For more information about different account types, see [Managing Your Amazon Chime Accounts](https://docs.aws.amazon.com/chime/latest/ag/manage-chime-account.html) in the *Amazon Chime Administration Guide*. """ def create_account(client, input, options \\ []) do path_ = "/accounts" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 201) end @doc """ Creates a new attendee for an active Amazon Chime SDK meeting. For more information about the Amazon Chime SDK, see [Using the Amazon Chime SDK](https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the *Amazon Chime Developer Guide*. """ def create_attendee(client, meeting_id, input, options \\ []) do path_ = "/meetings/#{URI.encode(meeting_id)}/attendees" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 201) end @doc """ Creates a bot for an Amazon Chime Enterprise account. """ def create_bot(client, account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/bots" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 201) end @doc """ Creates a new Amazon Chime SDK meeting in the specified media Region with no initial attendees. For more information about specifying media Regions, see [Amazon Chime SDK Media Regions](https://docs.aws.amazon.com/chime/latest/dg/chime-sdk-meetings-regions.html) in the *Amazon Chime Developer Guide*. For more information about the Amazon Chime SDK, see [Using the Amazon Chime SDK](https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the *Amazon Chime Developer Guide*. """ def create_meeting(client, input, options \\ []) do path_ = "/meetings" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 201) end @doc """ Creates a new Amazon Chime SDK meeting in the specified media Region, with attendees. For more information about specifying media Regions, see [Amazon Chime SDK Media Regions](https://docs.aws.amazon.com/chime/latest/dg/chime-sdk-meetings-regions.html) in the *Amazon Chime Developer Guide*. For more information about the Amazon Chime SDK, see [Using the Amazon Chime SDK](https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the *Amazon Chime Developer Guide*. """ def create_meeting_with_attendees(client, input, options \\ []) do path_ = "/meetings?operation=create-attendees" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 201) end @doc """ Creates an order for phone numbers to be provisioned. Choose from Amazon Chime Business Calling and Amazon Chime Voice Connector product types. For toll-free numbers, you must use the Amazon Chime Voice Connector product type. """ def create_phone_number_order(client, input, options \\ []) do path_ = "/phone-number-orders" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 201) end @doc """ Creates a proxy session on the specified Amazon Chime Voice Connector for the specified participant phone numbers. """ def create_proxy_session(client, voice_connector_id, input, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/proxy-sessions" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 201) end @doc """ Creates a chat room for the specified Amazon Chime Enterprise account. """ def create_room(client, account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/rooms" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 201) end @doc """ Adds a member to a chat room in an Amazon Chime Enterprise account. A member can be either a user or a bot. The member role designates whether the member is a chat room administrator or a general chat room member. """ def create_room_membership(client, account_id, room_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/rooms/#{URI.encode(room_id)}/memberships" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 201) end @doc """ Creates a user under the specified Amazon Chime account. """ def create_user(client, account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/users?operation=create" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 201) end @doc """ Creates an Amazon Chime Voice Connector under the administrator's AWS account. You can choose to create an Amazon Chime Voice Connector in a specific AWS Region. Enabling `CreateVoiceConnectorRequest$RequireEncryption` configures your Amazon Chime Voice Connector to use TLS transport for SIP signaling and Secure RTP (SRTP) for media. Inbound calls use TLS transport, and unencrypted outbound calls are blocked. """ def create_voice_connector(client, input, options \\ []) do path_ = "/voice-connectors" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 201) end @doc """ Creates an Amazon Chime Voice Connector group under the administrator's AWS account. You can associate Amazon Chime Voice Connectors with the Amazon Chime Voice Connector group by including `VoiceConnectorItems` in the request. You can include Amazon Chime Voice Connectors from different AWS Regions in your group. This creates a fault tolerant mechanism for fallback in case of availability events. """ def create_voice_connector_group(client, input, options \\ []) do path_ = "/voice-connector-groups" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 201) end @doc """ Deletes the specified Amazon Chime account. You must suspend all users before deleting a `Team` account. You can use the `BatchSuspendUser` action to do so. For `EnterpriseLWA` and `EnterpriseAD` accounts, you must release the claimed domains for your Amazon Chime account before deletion. As soon as you release the domain, all users under that account are suspended. Deleted accounts appear in your `Disabled` accounts list for 90 days. To restore a deleted account from your `Disabled` accounts list, you must contact AWS Support. After 90 days, deleted accounts are permanently removed from your `Disabled` accounts list. """ def delete_account(client, account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, 204) end @doc """ Deletes an attendee from the specified Amazon Chime SDK meeting and deletes their `JoinToken`. Attendees are automatically deleted when a Amazon Chime SDK meeting is deleted. For more information about the Amazon Chime SDK, see [Using the Amazon Chime SDK](https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the *Amazon Chime Developer Guide*. """ def delete_attendee(client, attendee_id, meeting_id, input, options \\ []) do path_ = "/meetings/#{URI.encode(meeting_id)}/attendees/#{URI.encode(attendee_id)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, 204) end @doc """ Deletes the events configuration that allows a bot to receive outgoing events. """ def delete_events_configuration(client, account_id, bot_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/bots/#{URI.encode(bot_id)}/events-configuration" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, 204) end @doc """ Deletes the specified Amazon Chime SDK meeting. When a meeting is deleted, its attendees are also deleted and clients can no longer join it. For more information about the Amazon Chime SDK, see [Using the Amazon Chime SDK](https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the *Amazon Chime Developer Guide*. """ def delete_meeting(client, meeting_id, input, options \\ []) do path_ = "/meetings/#{URI.encode(meeting_id)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, 204) end @doc """ Moves the specified phone number into the **Deletion queue**. A phone number must be disassociated from any users or Amazon Chime Voice Connectors before it can be deleted. Deleted phone numbers remain in the **Deletion queue** for 7 days before they are deleted permanently. """ def delete_phone_number(client, phone_number_id, input, options \\ []) do path_ = "/phone-numbers/#{URI.encode(phone_number_id)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, 204) end @doc """ Deletes the specified proxy session from the specified Amazon Chime Voice Connector. """ def delete_proxy_session(client, proxy_session_id, voice_connector_id, input, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/proxy-sessions/#{URI.encode(proxy_session_id)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, 204) end @doc """ Deletes a chat room in an Amazon Chime Enterprise account. """ def delete_room(client, account_id, room_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/rooms/#{URI.encode(room_id)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, 204) end @doc """ Removes a member from a chat room in an Amazon Chime Enterprise account. """ def delete_room_membership(client, account_id, member_id, room_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/rooms/#{URI.encode(room_id)}/memberships/#{URI.encode(member_id)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, 204) end @doc """ Deletes the specified Amazon Chime Voice Connector. Any phone numbers associated with the Amazon Chime Voice Connector must be disassociated from it before it can be deleted. """ def delete_voice_connector(client, voice_connector_id, input, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, 204) end @doc """ Deletes the emergency calling configuration details from the specified Amazon Chime Voice Connector. """ def delete_voice_connector_emergency_calling_configuration(client, voice_connector_id, input, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/emergency-calling-configuration" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, 204) end @doc """ Deletes the specified Amazon Chime Voice Connector group. Any `VoiceConnectorItems` and phone numbers associated with the group must be removed before it can be deleted. """ def delete_voice_connector_group(client, voice_connector_group_id, input, options \\ []) do path_ = "/voice-connector-groups/#{URI.encode(voice_connector_group_id)}" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, 204) end @doc """ Deletes the origination settings for the specified Amazon Chime Voice Connector. If emergency calling is configured for the Amazon Chime Voice Connector, it must be deleted prior to deleting the origination settings. """ def delete_voice_connector_origination(client, voice_connector_id, input, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/origination" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, 204) end @doc """ Deletes the proxy configuration from the specified Amazon Chime Voice Connector. """ def delete_voice_connector_proxy(client, voice_connector_id, input, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/programmable-numbers/proxy" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, 204) end @doc """ Deletes the streaming configuration for the specified Amazon Chime Voice Connector. """ def delete_voice_connector_streaming_configuration(client, voice_connector_id, input, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/streaming-configuration" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, 204) end @doc """ Deletes the termination settings for the specified Amazon Chime Voice Connector. If emergency calling is configured for the Amazon Chime Voice Connector, it must be deleted prior to deleting the termination settings. """ def delete_voice_connector_termination(client, voice_connector_id, input, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/termination" headers = [] query_ = [] request(client, :delete, path_, query_, headers, input, options, 204) end @doc """ Deletes the specified SIP credentials used by your equipment to authenticate during call termination. """ def delete_voice_connector_termination_credentials(client, voice_connector_id, input, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/termination/credentials?operation=delete" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 204) end @doc """ Disassociates the primary provisioned phone number from the specified Amazon Chime user. """ def disassociate_phone_number_from_user(client, account_id, user_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/users/#{URI.encode(user_id)}?operation=disassociate-phone-number" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Disassociates the specified phone numbers from the specified Amazon Chime Voice Connector. """ def disassociate_phone_numbers_from_voice_connector(client, voice_connector_id, input, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}?operation=disassociate-phone-numbers" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Disassociates the specified phone numbers from the specified Amazon Chime Voice Connector group. """ def disassociate_phone_numbers_from_voice_connector_group(client, voice_connector_group_id, input, options \\ []) do path_ = "/voice-connector-groups/#{URI.encode(voice_connector_group_id)}?operation=disassociate-phone-numbers" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Disassociates the specified sign-in delegate groups from the specified Amazon Chime account. """ def disassociate_signin_delegate_groups_from_account(client, account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}?operation=disassociate-signin-delegate-groups" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Retrieves details for the specified Amazon Chime account, such as account type and supported licenses. """ def get_account(client, account_id, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Retrieves account settings for the specified Amazon Chime account ID, such as remote control and dial out settings. For more information about these settings, see [Use the Policies Page](https://docs.aws.amazon.com/chime/latest/ag/policies.html) in the *Amazon Chime Administration Guide*. """ def get_account_settings(client, account_id, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/settings" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Gets the Amazon Chime SDK attendee details for a specified meeting ID and attendee ID. For more information about the Amazon Chime SDK, see [Using the Amazon Chime SDK](https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the *Amazon Chime Developer Guide*. """ def get_attendee(client, attendee_id, meeting_id, options \\ []) do path_ = "/meetings/#{URI.encode(meeting_id)}/attendees/#{URI.encode(attendee_id)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Retrieves details for the specified bot, such as bot email address, bot type, status, and display name. """ def get_bot(client, account_id, bot_id, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/bots/#{URI.encode(bot_id)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Gets details for an events configuration that allows a bot to receive outgoing events, such as an HTTPS endpoint or Lambda function ARN. """ def get_events_configuration(client, account_id, bot_id, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/bots/#{URI.encode(bot_id)}/events-configuration" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Retrieves global settings for the administrator's AWS account, such as Amazon Chime Business Calling and Amazon Chime Voice Connector settings. """ def get_global_settings(client, options \\ []) do path_ = "/settings" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Gets the Amazon Chime SDK meeting details for the specified meeting ID. For more information about the Amazon Chime SDK, see [Using the Amazon Chime SDK](https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the *Amazon Chime Developer Guide*. """ def get_meeting(client, meeting_id, options \\ []) do path_ = "/meetings/#{URI.encode(meeting_id)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Retrieves details for the specified phone number ID, such as associations, capabilities, and product type. """ def get_phone_number(client, phone_number_id, options \\ []) do path_ = "/phone-numbers/#{URI.encode(phone_number_id)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Retrieves details for the specified phone number order, such as order creation timestamp, phone numbers in E.164 format, product type, and order status. """ def get_phone_number_order(client, phone_number_order_id, options \\ []) do path_ = "/phone-number-orders/#{URI.encode(phone_number_order_id)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Retrieves the phone number settings for the administrator's AWS account, such as the default outbound calling name. """ def get_phone_number_settings(client, options \\ []) do path_ = "/settings/phone-number" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Gets the specified proxy session details for the specified Amazon Chime Voice Connector. """ def get_proxy_session(client, proxy_session_id, voice_connector_id, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/proxy-sessions/#{URI.encode(proxy_session_id)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Gets the retention settings for the specified Amazon Chime Enterprise account. For more information about retention settings, see [Managing Chat Retention Policies](https://docs.aws.amazon.com/chime/latest/ag/chat-retention.html) in the *Amazon Chime Administration Guide*. """ def get_retention_settings(client, account_id, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/retention-settings" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Retrieves room details, such as the room name, for a room in an Amazon Chime Enterprise account. """ def get_room(client, account_id, room_id, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/rooms/#{URI.encode(room_id)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Retrieves details for the specified user ID, such as primary email address, license type, and personal meeting PIN. To retrieve user details with an email address instead of a user ID, use the `ListUsers` action, and then filter by email address. """ def get_user(client, account_id, user_id, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/users/#{URI.encode(user_id)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Retrieves settings for the specified user ID, such as any associated phone number settings. """ def get_user_settings(client, account_id, user_id, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/users/#{URI.encode(user_id)}/settings" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Retrieves details for the specified Amazon Chime Voice Connector, such as timestamps, name, outbound host, and encryption requirements. """ def get_voice_connector(client, voice_connector_id, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Gets the emergency calling configuration details for the specified Amazon Chime Voice Connector. """ def get_voice_connector_emergency_calling_configuration(client, voice_connector_id, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/emergency-calling-configuration" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Retrieves details for the specified Amazon Chime Voice Connector group, such as timestamps, name, and associated `VoiceConnectorItems`. """ def get_voice_connector_group(client, voice_connector_group_id, options \\ []) do path_ = "/voice-connector-groups/#{URI.encode(voice_connector_group_id)}" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Retrieves the logging configuration details for the specified Amazon Chime Voice Connector. Shows whether SIP message logs are enabled for sending to Amazon CloudWatch Logs. """ def get_voice_connector_logging_configuration(client, voice_connector_id, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/logging-configuration" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Retrieves origination setting details for the specified Amazon Chime Voice Connector. """ def get_voice_connector_origination(client, voice_connector_id, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/origination" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Gets the proxy configuration details for the specified Amazon Chime Voice Connector. """ def get_voice_connector_proxy(client, voice_connector_id, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/programmable-numbers/proxy" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Retrieves the streaming configuration details for the specified Amazon Chime Voice Connector. Shows whether media streaming is enabled for sending to Amazon Kinesis. It also shows the retention period, in hours, for the Amazon Kinesis data. """ def get_voice_connector_streaming_configuration(client, voice_connector_id, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/streaming-configuration" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Retrieves termination setting details for the specified Amazon Chime Voice Connector. """ def get_voice_connector_termination(client, voice_connector_id, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/termination" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Retrieves information about the last time a SIP `OPTIONS` ping was received from your SIP infrastructure for the specified Amazon Chime Voice Connector. """ def get_voice_connector_termination_health(client, voice_connector_id, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/termination/health" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Sends email to a maximum of 50 users, inviting them to the specified Amazon Chime `Team` account. Only `Team` account types are currently supported for this action. """ def invite_users(client, account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/users?operation=add" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 201) end @doc """ Lists the Amazon Chime accounts under the administrator's AWS account. You can filter accounts by account name prefix. To find out which Amazon Chime account a user belongs to, you can filter by the user's email address, which returns one account result. """ def list_accounts(client, max_results \\ nil, name \\ nil, next_token \\ nil, user_email \\ nil, options \\ []) do path_ = "/accounts" headers = [] query_ = [] query_ = if !is_nil(user_email) do [{"user-email", user_email} | query_] else query_ end query_ = if !is_nil(next_token) do [{"next-token", next_token} | query_] else query_ end query_ = if !is_nil(name) do [{"name", name} | 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 applied to an Amazon Chime SDK attendee resource. """ def list_attendee_tags(client, attendee_id, meeting_id, options \\ []) do path_ = "/meetings/#{URI.encode(meeting_id)}/attendees/#{URI.encode(attendee_id)}/tags" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Lists the attendees for the specified Amazon Chime SDK meeting. For more information about the Amazon Chime SDK, see [Using the Amazon Chime SDK](https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the *Amazon Chime Developer Guide*. """ def list_attendees(client, meeting_id, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/meetings/#{URI.encode(meeting_id)}/attendees" 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, 200) end @doc """ Lists the bots associated with the administrator's Amazon Chime Enterprise account ID. """ def list_bots(client, account_id, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/bots" 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, 200) end @doc """ Lists the tags applied to an Amazon Chime SDK meeting resource. """ def list_meeting_tags(client, meeting_id, options \\ []) do path_ = "/meetings/#{URI.encode(meeting_id)}/tags" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Lists up to 100 active Amazon Chime SDK meetings. For more information about the Amazon Chime SDK, see [Using the Amazon Chime SDK](https://docs.aws.amazon.com/chime/latest/dg/meetings-sdk.html) in the *Amazon Chime Developer Guide*. """ def list_meetings(client, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/meetings" 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, 200) end @doc """ Lists the phone number orders for the administrator's Amazon Chime account. """ def list_phone_number_orders(client, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/phone-number-orders" 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, 200) end @doc """ Lists the phone numbers for the specified Amazon Chime account, Amazon Chime user, Amazon Chime Voice Connector, or Amazon Chime Voice Connector group. """ def list_phone_numbers(client, filter_name \\ nil, filter_value \\ nil, max_results \\ nil, next_token \\ nil, product_type \\ nil, status \\ nil, options \\ []) do path_ = "/phone-numbers" headers = [] query_ = [] query_ = if !is_nil(status) do [{"status", status} | query_] else query_ end query_ = if !is_nil(product_type) do [{"product-type", product_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 query_ = if !is_nil(filter_value) do [{"filter-value", filter_value} | query_] else query_ end query_ = if !is_nil(filter_name) do [{"filter-name", filter_name} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists the proxy sessions for the specified Amazon Chime Voice Connector. """ def list_proxy_sessions(client, voice_connector_id, max_results \\ nil, next_token \\ nil, status \\ nil, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/proxy-sessions" headers = [] query_ = [] query_ = if !is_nil(status) do [{"status", status} | 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, 200) end @doc """ Lists the membership details for the specified room in an Amazon Chime Enterprise account, such as the members' IDs, email addresses, and names. """ def list_room_memberships(client, account_id, room_id, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/rooms/#{URI.encode(room_id)}/memberships" 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, 200) end @doc """ Lists the room details for the specified Amazon Chime Enterprise account. Optionally, filter the results by a member ID (user ID or bot ID) to see a list of rooms that the member belongs to. """ def list_rooms(client, account_id, max_results \\ nil, member_id \\ nil, next_token \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/rooms" headers = [] query_ = [] query_ = if !is_nil(next_token) do [{"next-token", next_token} | query_] else query_ end query_ = if !is_nil(member_id) do [{"member-id", member_id} | 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, 200) end @doc """ Lists the tags applied to an Amazon Chime SDK meeting resource. """ def list_tags_for_resource(client, resource_a_r_n, options \\ []) do path_ = "/tags" headers = [] query_ = [] query_ = if !is_nil(resource_a_r_n) do [{"arn", resource_a_r_n} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Lists the users that belong to the specified Amazon Chime account. You can specify an email address to list only the user that the email address belongs to. """ def list_users(client, account_id, max_results \\ nil, next_token \\ nil, user_email \\ nil, user_type \\ nil, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/users" headers = [] query_ = [] query_ = if !is_nil(user_type) do [{"user-type", user_type} | query_] else query_ end query_ = if !is_nil(user_email) do [{"user-email", user_email} | 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, 200) end @doc """ Lists the Amazon Chime Voice Connector groups for the administrator's AWS account. """ def list_voice_connector_groups(client, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/voice-connector-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, 200) end @doc """ Lists the SIP credentials for the specified Amazon Chime Voice Connector. """ def list_voice_connector_termination_credentials(client, voice_connector_id, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/termination/credentials" headers = [] query_ = [] request(client, :get, path_, query_, headers, nil, options, 200) end @doc """ Lists the Amazon Chime Voice Connectors for the administrator's AWS account. """ def list_voice_connectors(client, max_results \\ nil, next_token \\ nil, options \\ []) do path_ = "/voice-connectors" 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, 200) end @doc """ Logs out the specified user from all of the devices they are currently logged into. """ def logout_user(client, account_id, user_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/users/#{URI.encode(user_id)}?operation=logout" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 204) end @doc """ Creates an events configuration that allows a bot to receive outgoing events sent by Amazon Chime. Choose either an HTTPS endpoint or a Lambda function ARN. For more information, see `Bot`. """ def put_events_configuration(client, account_id, bot_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/bots/#{URI.encode(bot_id)}/events-configuration" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, 201) end @doc """ Puts retention settings for the specified Amazon Chime Enterprise account. We recommend using AWS CloudTrail to monitor usage of this API for your account. For more information, see [Logging Amazon Chime API Calls with AWS CloudTrail](https://docs.aws.amazon.com/chime/latest/ag/cloudtrail.html) in the *Amazon Chime Administration Guide*. To turn off existing retention settings, remove the number of days from the corresponding **RetentionDays** field in the **RetentionSettings** object. For more information about retention settings, see [Managing Chat Retention Policies](https://docs.aws.amazon.com/chime/latest/ag/chat-retention.html) in the *Amazon Chime Administration Guide*. """ def put_retention_settings(client, account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/retention-settings" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, 204) end @doc """ Puts emergency calling configuration details to the specified Amazon Chime Voice Connector, such as emergency phone numbers and calling countries. Origination and termination settings must be enabled for the Amazon Chime Voice Connector before emergency calling can be configured. """ def put_voice_connector_emergency_calling_configuration(client, voice_connector_id, input, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/emergency-calling-configuration" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, 200) end @doc """ Adds a logging configuration for the specified Amazon Chime Voice Connector. The logging configuration specifies whether SIP message logs are enabled for sending to Amazon CloudWatch Logs. """ def put_voice_connector_logging_configuration(client, voice_connector_id, input, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/logging-configuration" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, 200) end @doc """ Adds origination settings for the specified Amazon Chime Voice Connector. If emergency calling is configured for the Amazon Chime Voice Connector, it must be deleted prior to turning off origination settings. """ def put_voice_connector_origination(client, voice_connector_id, input, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/origination" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, 200) end @doc """ Puts the specified proxy configuration to the specified Amazon Chime Voice Connector. """ def put_voice_connector_proxy(client, voice_connector_id, input, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/programmable-numbers/proxy" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, nil) end @doc """ Adds a streaming configuration for the specified Amazon Chime Voice Connector. The streaming configuration specifies whether media streaming is enabled for sending to Amazon Kinesis. It also sets the retention period, in hours, for the Amazon Kinesis data. """ def put_voice_connector_streaming_configuration(client, voice_connector_id, input, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/streaming-configuration" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, 200) end @doc """ Adds termination settings for the specified Amazon Chime Voice Connector. If emergency calling is configured for the Amazon Chime Voice Connector, it must be deleted prior to turning off termination settings. """ def put_voice_connector_termination(client, voice_connector_id, input, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/termination" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, 200) end @doc """ Adds termination SIP credentials for the specified Amazon Chime Voice Connector. """ def put_voice_connector_termination_credentials(client, voice_connector_id, input, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/termination/credentials?operation=put" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 204) end @doc """ Redacts the specified message from the specified Amazon Chime conversation. """ def redact_conversation_message(client, account_id, conversation_id, message_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/conversations/#{URI.encode(conversation_id)}/messages/#{URI.encode(message_id)}?operation=redact" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Redacts the specified message from the specified Amazon Chime chat room. """ def redact_room_message(client, account_id, message_id, room_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/rooms/#{URI.encode(room_id)}/messages/#{URI.encode(message_id)}?operation=redact" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Regenerates the security token for a bot. """ def regenerate_security_token(client, account_id, bot_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/bots/#{URI.encode(bot_id)}?operation=regenerate-security-token" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Resets the personal meeting PIN for the specified user on an Amazon Chime account. Returns the `User` object with the updated personal meeting PIN. """ def reset_personal_p_i_n(client, account_id, user_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/users/#{URI.encode(user_id)}?operation=reset-personal-pin" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Moves a phone number from the **Deletion queue** back into the phone number **Inventory**. """ def restore_phone_number(client, phone_number_id, input, options \\ []) do path_ = "/phone-numbers/#{URI.encode(phone_number_id)}?operation=restore" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Searches phone numbers that can be ordered. """ def search_available_phone_numbers(client, area_code \\ nil, city \\ nil, country \\ nil, max_results \\ nil, next_token \\ nil, state \\ nil, toll_free_prefix \\ nil, options \\ []) do path_ = "/search?type=phone-numbers" headers = [] query_ = [] query_ = if !is_nil(toll_free_prefix) do [{"toll-free-prefix", toll_free_prefix} | query_] else query_ end query_ = if !is_nil(state) do [{"state", state} | 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 query_ = if !is_nil(country) do [{"country", country} | query_] else query_ end query_ = if !is_nil(city) do [{"city", city} | query_] else query_ end query_ = if !is_nil(area_code) do [{"area-code", area_code} | query_] else query_ end request(client, :get, path_, query_, headers, nil, options, nil) end @doc """ Applies the specified tags to the specified Amazon Chime SDK attendee. """ def tag_attendee(client, attendee_id, meeting_id, input, options \\ []) do path_ = "/meetings/#{URI.encode(meeting_id)}/attendees/#{URI.encode(attendee_id)}/tags?operation=add" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 204) end @doc """ Applies the specified tags to the specified Amazon Chime SDK meeting. """ def tag_meeting(client, meeting_id, input, options \\ []) do path_ = "/meetings/#{URI.encode(meeting_id)}/tags?operation=add" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 204) end @doc """ Applies the specified tags to the specified Amazon Chime SDK meeting resource. """ def tag_resource(client, input, options \\ []) do path_ = "/tags?operation=tag-resource" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 204) end @doc """ Untags the specified tags from the specified Amazon Chime SDK attendee. """ def untag_attendee(client, attendee_id, meeting_id, input, options \\ []) do path_ = "/meetings/#{URI.encode(meeting_id)}/attendees/#{URI.encode(attendee_id)}/tags?operation=delete" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 204) end @doc """ Untags the specified tags from the specified Amazon Chime SDK meeting. """ def untag_meeting(client, meeting_id, input, options \\ []) do path_ = "/meetings/#{URI.encode(meeting_id)}/tags?operation=delete" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 204) end @doc """ Untags the specified tags from the specified Amazon Chime SDK meeting resource. """ def untag_resource(client, input, options \\ []) do path_ = "/tags?operation=untag-resource" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 204) end @doc """ Updates account details for the specified Amazon Chime account. Currently, only account name updates are supported for this action. """ def update_account(client, account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Updates the settings for the specified Amazon Chime account. You can update settings for remote control of shared screens, or for the dial-out option. For more information about these settings, see [Use the Policies Page](https://docs.aws.amazon.com/chime/latest/ag/policies.html) in the *Amazon Chime Administration Guide*. """ def update_account_settings(client, account_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/settings" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, 204) end @doc """ Updates the status of the specified bot, such as starting or stopping the bot from running in your Amazon Chime Enterprise account. """ def update_bot(client, account_id, bot_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/bots/#{URI.encode(bot_id)}" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Updates global settings for the administrator's AWS account, such as Amazon Chime Business Calling and Amazon Chime Voice Connector settings. """ def update_global_settings(client, input, options \\ []) do path_ = "/settings" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, 204) end @doc """ Updates phone number details, such as product type or calling name, for the specified phone number ID. You can update one phone number detail at a time. For example, you can update either the product type or the calling name in one action. For toll-free numbers, you must use the Amazon Chime Voice Connector product type. Updates to outbound calling names can take up to 72 hours to complete. Pending updates to outbound calling names must be complete before you can request another update. """ def update_phone_number(client, phone_number_id, input, options \\ []) do path_ = "/phone-numbers/#{URI.encode(phone_number_id)}" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Updates the phone number settings for the administrator's AWS account, such as the default outbound calling name. You can update the default outbound calling name once every seven days. Outbound calling names can take up to 72 hours to update. """ def update_phone_number_settings(client, input, options \\ []) do path_ = "/settings/phone-number" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, 204) end @doc """ Updates the specified proxy session details, such as voice or SMS capabilities. """ def update_proxy_session(client, proxy_session_id, voice_connector_id, input, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}/proxy-sessions/#{URI.encode(proxy_session_id)}" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 201) end @doc """ Updates room details, such as the room name, for a room in an Amazon Chime Enterprise account. """ def update_room(client, account_id, room_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/rooms/#{URI.encode(room_id)}" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Updates room membership details, such as the member role, for a room in an Amazon Chime Enterprise account. The member role designates whether the member is a chat room administrator or a general chat room member. The member role can be updated only for user IDs. """ def update_room_membership(client, account_id, member_id, room_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/rooms/#{URI.encode(room_id)}/memberships/#{URI.encode(member_id)}" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Updates user details for a specified user ID. Currently, only `LicenseType` updates are supported for this action. """ def update_user(client, account_id, user_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/users/#{URI.encode(user_id)}" headers = [] query_ = [] request(client, :post, path_, query_, headers, input, options, 200) end @doc """ Updates the settings for the specified user, such as phone number settings. """ def update_user_settings(client, account_id, user_id, input, options \\ []) do path_ = "/accounts/#{URI.encode(account_id)}/users/#{URI.encode(user_id)}/settings" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, 204) end @doc """ Updates details for the specified Amazon Chime Voice Connector. """ def update_voice_connector(client, voice_connector_id, input, options \\ []) do path_ = "/voice-connectors/#{URI.encode(voice_connector_id)}" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, 200) end @doc """ Updates details for the specified Amazon Chime Voice Connector group, such as the name and Amazon Chime Voice Connector priority ranking. """ def update_voice_connector_group(client, voice_connector_group_id, input, options \\ []) do path_ = "/voice-connector-groups/#{URI.encode(voice_connector_group_id)}" headers = [] query_ = [] request(client, :put, path_, query_, headers, input, options, 202) 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: "chime", region: "us-east-1"} host = build_host("chime", 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, %{endpoint: endpoint}) do "#{endpoint_prefix}.#{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/chime.ex
0.874761
0.551695
chime.ex
starcoder
defmodule ElixirKeeb.PinMapper do @moduledoc """ Imagine a 3x4 keyboard like this: ----------------- | Q | W | E | R | | A | S | D | F | | Z | X | C | V | ----------------- The controller has 8 pins, P1, P2, ..., P7, P8. (A) P1, P3, P5, P8 => "Lines" P2, P4, P6, P7 => "Columns" Each key connected to "randomly" assigned pins: (B) --------------------------------- | P1,P4 | P3,P2 | P1,P7 | P3,P6 | | P3,P7 | P1,P6 | P8,P6 | P5,P7 | | P5,P2 | P5,P4 | P3,P4 | P8,P2 | --------------------------------- We want a way to say Q corresponds to P1,P4, W corresponds to P3,P2, and so on. In the end we want a matrix like this: (C) [ # kx0:P2 kx1:P4 kx2:P6 kx3:P7 cols [kc_no, k01, k02, k03 ], # k0y:P1 P1,P2 P1,P4 P1,P6 P1,P7 [k10, k11, k12, k13 ], # k1y:P3 P3,P2 P3,P4 P3,P6 P3,P7 [k20, k21, kc_no, k23 ], # k2y:P5 P5,P2 P5,P4 P5,P6 P5,P7 [k30, kc_no, k32, kc_no], # k3y:P8 P8,P2 P8,P4 P8,P6 P8,P7 ] # rows Where `kc_no` means this pin combination isn't connected to any key. The QMK macro receives: [ [k01, k10, k03, k12], [k13, k02, k32, k23], [k20, k21, k11, k30], ] The QMK macro maps the "physical" matrix to the pin matrix. With the list of pins (A) and the "matrix" (B), we're able to create the (C) end result. """ alias ElixirKeeb.Utils require Logger @disabled_keycode :kc_no @doc """ Receives the "physical" matrix, the list of line pins and column pins, and returns the physical matrix using the `:kc_xy` representation. If the `line_pins` look like (ie., `{:alias, pin_number}`): ``` [{:P1, 1}, {:P3, 3}, {:P5, 5}, {:P8, 8}] ``` And the `column_pins` look like (ie., `{:alias, pin_number}`): ``` [{:P2, 2}, {:P4, 4}, {:P6, 6}, {:P7, 7}] ``` The keyboard is a 3x4 keeb, so the physical_matrix has 3 lists of 4 elements each: ``` [ [ {:P1, :P4} , {:P3, :P2} , {:P1, :P7} , {:P3, :P6} ], [ {:P3, :P7} , {:P1, :P6} , {:P8, :P6} , {:P5, :P7} ], [ {:P5, :P2} , {:P5, :P4} , {:P3, :P4} , {:P8, :P2} ], ] ``` It returns the following physical matrix in `:kc_xy` representation: ``` [ [:kc_01, :kc_10, :kc_03, :kc_12], [:kc_13, :kc_02, :kc_32, :kc_23], [:kc_20, :kc_21, :kc_11, :kc_30], ] """ def physical_matrix_kc_xy(physical_matrix, lines: line_pins, columns: column_pins) do for matrix_line <- physical_matrix do for {line_pin, column_pin} <- matrix_line do line_index = index_in_pin_list(line_pin, line_pins) column_index = index_in_pin_list(column_pin, column_pins) Utils.kc(line_index, column_index) end end end @doc """ Receives the "physical" matrix, the list of line pins and column pins, and returns the pin matrix. If the `line_pins` look like (ie., `{:alias, pin_number}`): ``` [{:P1, 1}, {:P3, 3}, {:P5, 5}, {:P8, 8}] ``` And the `column_pins` look like (ie., `{:alias, pin_number}`): ``` [{:P2, 2}, {:P4, 4}, {:P6, 6}, {:P7, 7}] ``` The keyboard is a 3x4 keeb, so the physical_matrix has 3 lists of 4 elements each: ``` [ [ {:P1, :P4} , {:P3, :P2} , {:P1, :P7} , {:P3, :P6} ], [ {:P3, :P7} , {:P1, :P6} , {:P8, :P6} , {:P5, :P7} ], [ {:P5, :P2} , {:P5, :P4} , {:P3, :P4} , {:P8, :P2} ], ] ``` It returns the following pin matrix (we have 4 line pins and 4 column pins, hence we have a 4x4 pin matrix): ``` [ [:kc_no, :kc_01, :kc_02, :kc_03], [:kc_10, :kc_11, :kc_12, :kc_13], [:kc_20, :kc_21, :kc_no, :kc_23], [:kc_30, :kc_no, :kc_32, :kc_no] ] ``` """ def pin_matrix(physical_matrix, lines: line_pins, columns: column_pins) do line_pins = Utils.zip_with_index(line_pins) column_pins = Utils.zip_with_index(column_pins) for {{line_alias, _line_pin}, line_pin_index} <- line_pins do for {{column_alias, _column_pin}, column_pin_index} <- column_pins do case exists_in?(physical_matrix, {line_alias, column_alias}) do true -> Utils.kc(line_pin_index, column_pin_index) _ -> @disabled_keycode end end end end defmacro __using__(_options) do quote do import unquote(__MODULE__) @before_compile unquote(__MODULE__) end end defmacro __before_compile__(%Macro.Env{module: module}) do physical_matrix = Module.get_attribute(module, :physical_matrix) line_pins = Module.get_attribute(module, :line_pins) |> Enum.sort() column_pins = Module.get_attribute(module, :column_pins) |> Enum.sort() physical_matrix_kc_xy = physical_matrix_kc_xy( physical_matrix, lines: line_pins, columns: column_pins) physical_matrix_kc_xy_vars = physical_matrix_kc_xy |> Enum.map(fn line -> Enum.map(line, fn keycode -> quoted_var(keycode) end) end) pin_matrix = pin_matrix( physical_matrix, lines: line_pins, columns: column_pins) quoted_pin_matrix = pin_matrix |> Enum.map(fn line -> Enum.map(line, fn keycode -> quoted_var(keycode) end) end) Logger.debug(inspect(physical_matrix_kc_xy_vars), label: "Physical matrix") Logger.debug(inspect(quoted_pin_matrix), label: "Pin matrix") quote do def map(unquote(physical_matrix_kc_xy_vars)) do unquote(quoted_pin_matrix) end def physical_matrix_kc_xy() do unquote(physical_matrix_kc_xy) end def pin_matrix() do unquote(pin_matrix) end end end defp quoted_var(@disabled_keycode), do: @disabled_keycode defp quoted_var(var) when is_atom(var), do: {var, [], Elixir} defp index_in_pin_list(pin_alias_to_find, pin_list) do Enum.find_index( pin_list, fn {pin_alias, _pin} -> pin_alias == pin_alias_to_find end ) |> case do nil -> raise("Pin #{pin_alias_to_find} can't be found on pin list: #{inspect(pin_list)}") index -> index end end defp exists_in?(matrix, elem) do Enum.reduce_while(matrix, false, fn matrix_line, acc -> if elem in matrix_line do {:halt, true} else {:cont, acc} end end) end end
lib/pin_mapper.ex
0.874225
0.861713
pin_mapper.ex
starcoder
defmodule Day14 do import Bitwise require Logger def part1(path) do or_mask = 0 and_mask = ~~~or_mask masks = {and_mask, or_mask} solve(path, &exec/2, masks) end def part2(path) do or_mask = 0 floating_bits = [] solve(path, &exec_v2/2, {or_mask, floating_bits}) end def solve(path, exec, masks) do path |> File.stream!() |> Enum.reduce(%{mem: %{}, masks: masks}, exec) |> Map.fetch!(:mem) |> Map.values() |> Enum.sum() end def exec("mask = " <> mask, state) do mask = String.trim_trailing(mask) or_mask = parse_mask(mask, "0") and_mask = parse_mask(mask, "1") %{state | masks: {and_mask, or_mask}} end def exec("mem" <> command, %{mem: mem, masks: {and_mask, or_mask}} = state) do [addr, value] = parse_command(command) masked = value |> band(and_mask) |> bor(or_mask) mem = Map.put(mem, addr, masked) %{state | mem: mem} end def exec_v2("mask = " <> mask, state) do mask = String.trim_trailing(mask) or_mask = parse_mask(mask, "0") floating_bits = parse_floating(mask) Logger.debug( "or_mask:#{Integer.to_string(or_mask, 2)}, floating_bits:#{inspect(floating_bits)}" ) %{state | masks: {or_mask, floating_bits}} end def exec_v2("mem" <> command, %{mem: mem, masks: {or_mask, floating_bits}} = state) do [addr, value] = parse_command(command) masked = addr ||| or_mask mem = apply_floating_bits(masked, floating_bits) |> Enum.reduce(mem, fn addr, mem -> Logger.debug("mem[#{addr}] = #{value}") Map.put(mem, addr, value) end) %{state | mem: mem} end defp parse_command(command) do Regex.run(~r/^\[(\d+)\] = (\d+)$/, command, capture: :all_but_first) |> Enum.map(&String.to_integer/1) end defp parse_mask(mask, x_replacement) do String.replace(mask, "X", x_replacement) |> String.to_integer(2) end def parse_floating(mask) do String.graphemes(mask) |> Enum.reverse() |> Enum.with_index() |> Enum.flat_map(fn {bit, idx} -> if bit == "X", do: [idx], else: [] end) end def apply_floating_bits(num, floating_bits) do combinations = Math.pow(2, Enum.count(floating_bits)) Enum.map(0..(combinations - 1), &set_bits(&1, floating_bits, num)) end def set_bits(bits, positions, number) do bits |> Integer.digits(2) |> Enum.reverse() |> Stream.concat(Stream.cycle([0])) |> Enum.zip(positions) |> Enum.reduce(number, &set_bit/2) end def set_bit({0, pos}, n) do n &&& ~~~(1 <<< pos) end def set_bit({1, pos}, n) do n ||| 1 <<< pos end end
lib/day_14.ex
0.512205
0.526465
day_14.ex
starcoder
defmodule RethinkDB.Pseudotypes do @moduledoc false defmodule Binary do @moduledoc false defstruct data: nil def parse(%{"$reql_type$" => "BINARY", "data" => data}, opts) do case Keyword.get(opts, :binary_format) do :raw -> %__MODULE__{data: data} _ -> :base64.decode(data) end end end defmodule Geometry do @moduledoc false defmodule Point do @moduledoc false defstruct coordinates: [] end defmodule Line do @moduledoc false defstruct coordinates: [] end defmodule Polygon do @moduledoc false defstruct coordinates: [] end def parse(%{"$reql_type$" => "GEOMETRY", "coordinates" => [x, y], "type" => "Point"}) do %Point{coordinates: {x, y}} end def parse(%{"$reql_type$" => "GEOMETRY", "coordinates" => coords, "type" => "LineString"}) do %Line{coordinates: Enum.map(coords, &List.to_tuple/1)} end def parse(%{"$reql_type$" => "GEOMETRY", "coordinates" => coords, "type" => "Polygon"}) do %Polygon{coordinates: for(points <- coords, do: Enum.map(points, &List.to_tuple/1))} end end defmodule Time do @moduledoc false defstruct epoch_time: nil, timezone: nil def parse( %{"$reql_type$" => "TIME", "epoch_time" => epoch_time, "timezone" => timezone}, opts ) do case Keyword.get(opts, :time_format) do :raw -> %__MODULE__{epoch_time: epoch_time, timezone: timezone} _ -> time = (epoch_time * 1000) |> trunc() |> Timex.from_unix(:millisecond) zone = if is_offset?(timezone) do Timex.Timezone.name_of(timezone) |> Timex.timezone(time) else Timex.timezone(timezone, time) end time |> struct(utc_offset: Map.get(zone, :offset_utc), time_zone: Map.get(zone, :full_name), zone_abbr: Map.get(zone, :abbreviation)) end end defp is_offset?("+" <> <<_::bytes-size(2)>> <> ":" <> <<_::bytes-size(2)>>) do true end defp is_offset?("-" <> <<_::bytes-size(2)>> <> ":" <> <<_::bytes-size(2)>>) do true end defp is_offset?(_string) do false end end def convert_reql_pseudotypes(nil, _opts), do: nil def convert_reql_pseudotypes(%{"$reql_type$" => "BINARY"} = data, opts) do Binary.parse(data, opts) end def convert_reql_pseudotypes(%{"$reql_type$" => "GEOMETRY"} = data, _opts) do Geometry.parse(data) end def convert_reql_pseudotypes(%{"$reql_type$" => "GROUPED_DATA"} = data, _opts) do parse_grouped_data(data) end def convert_reql_pseudotypes(%{"$reql_type$" => "TIME"} = data, opts) do Time.parse(data, opts) end def convert_reql_pseudotypes(list, opts) when is_list(list) do Enum.map(list, fn data -> convert_reql_pseudotypes(data, opts) end) end def convert_reql_pseudotypes(map, opts) when is_map(map) do Enum.map(map, fn {k, v} -> {k, convert_reql_pseudotypes(v, opts)} end) |> Enum.into(%{}) end def convert_reql_pseudotypes(string, _opts), do: string def parse_grouped_data(%{"$reql_type$" => "GROUPED_DATA", "data" => data}) do Enum.map(data, fn [k, data] -> {k, data} end) |> Enum.into(%{}) end def create_grouped_data(data) when is_map(data) do data = data |> Enum.map(fn {k, v} -> [k, v] end) %{"$reql_type$" => "GROUPED_DATA", "data" => data} end end
lib/rethinkdb/pseudotypes.ex
0.514888
0.568775
pseudotypes.ex
starcoder
defmodule Mollie.Connect do import Mollie alias Mollie.Client @moduledoc """ Mollie Connect is a set of APIs and tools that allows you to connect multiple Mollie accounts together. More info at: https://docs.mollie.com/connect/overview """ @doc """ Generates the authorization URL Params example ``` %{ "client_id" => "app_dnR5f6uPDWhrvZkiL9ex7Wjj", "state" => "a63f5cfcdaa209e2302be84da28008e8", "scope" => "payments.read payments.write profiles.read organizations.read", "response_type" => "code", "approval_prompt" => "auto", "redirect_uri" => "https://example.com" } ``` ## Example Mollie.Connect.authorization_url client, params More info at: https://docs.mollie.com/reference/oauth2/authorize """ @spec authorization_url(Client.t(), map | Keyword.t()) :: binary() def authorization_url(client, params) when is_map(params) do client |> url("oauth2/authorize") |> add_params_to_url(params) end def authorization_url(client, params) do map = Enum.into(params, %{}) authorization_url(client, map) end @doc """ Exchange the auth code received at the Authorize endpoint for an actual access token, with which you can communicate with the Mollie API. Token body example ``` %{ "grant_type" => "authorization_code", "code" => "auth_IbyEKUrXmGW1J8hPg6Ciyo4aaU6OAu" } ``` ## Example Mollie.Connect.create_token client, token_body More info at: https://docs.mollie.com/reference/oauth2/tokens """ @spec create_token(Client.t(), map) :: Mollie.response() def create_token(client, body) do post("oauth2/tokens", client, body) end @doc """ Revoke an access- or a refresh token. Once revoked the token can not be used anymore. When you revoke a refresh token, all access tokens based on the same authorization grant will be revoked as well. Token body example ``` %{ "token_type_hint" => "access_token", "token" => "<KEY>" } ``` ## Example Mollie.Connect.revoke_token client, token_body More info at: https://docs.mollie.com/reference/oauth2/tokens """ @spec revoke_token(Client.t(), map) :: Mollie.response() def revoke_token(client, body) do delete("oauth2/tokens", client, body) end end
lib/mollie/connect.ex
0.802788
0.558598
connect.ex
starcoder
defmodule AWS.Lambda do @moduledoc """ AWS Lambda **Overview** This is the *AWS Lambda API Reference*. The AWS Lambda Developer Guide provides additional information. For the service overview, see [What is AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html), and for information about how the service works, see [AWS Lambda: How it Works](https://docs.aws.amazon.com/lambda/latest/dg/lambda-introduction.html) in the **AWS Lambda Developer Guide**. """ @doc """ Adds permissions to the resource-based policy of a version of an [AWS Lambda layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html). Use this action to grant layer usage permission to other accounts. You can grant permission to a single account, all AWS accounts, or all accounts in an organization. To revoke permission, call `RemoveLayerVersionPermission` with the statement ID that you specified when you added it. """ def add_layer_version_permission(client, layer_name, version_number, input, options \\ []) do url = "/2018-10-31/layers/#{URI.encode(layer_name)}/versions/#{URI.encode(version_number)}/policy" headers = [] request(client, :post, url, headers, input, options, 201) end @doc """ Grants an AWS service or another account permission to use a function. You can apply the policy at the function level, or specify a qualifier to restrict access to a single version or alias. If you use a qualifier, the invoker must use the full Amazon Resource Name (ARN) of that version or alias to invoke the function. To grant permission to another account, specify the account ID as the `Principal`. For AWS services, the principal is a domain-style identifier defined by the service, like `s3.amazonaws.com` or `sns.amazonaws.com`. For AWS services, you can also specify the ARN or owning account of the associated resource as the `SourceArn` or `SourceAccount`. If you grant permission to a service principal without specifying the source, other accounts could potentially configure resources in their account to invoke your Lambda function. This action adds a statement to a resource-based permission policy for the function. For more information about function policies, see [Lambda Function Policies](https://docs.aws.amazon.com/lambda/latest/dg/access-control-resource-based.html). """ def add_permission(client, function_name, input, options \\ []) do url = "/2015-03-31/functions/#{URI.encode(function_name)}/policy" headers = [] request(client, :post, url, headers, input, options, 201) end @doc """ Creates an [alias](https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html) for a Lambda function version. Use aliases to provide clients with a function identifier that you can update to invoke a different version. You can also map an alias to split invocation requests between two versions. Use the `RoutingConfig` parameter to specify a second version and the percentage of invocation requests that it receives. """ def create_alias(client, function_name, input, options \\ []) do url = "/2015-03-31/functions/#{URI.encode(function_name)}/aliases" headers = [] request(client, :post, url, headers, input, options, 201) end @doc """ Creates a mapping between an event source and an AWS Lambda function. Lambda reads items from the event source and triggers the function. For details about each event source type, see the following topics. <ul> <li> [Using AWS Lambda with Amazon Kinesis](https://docs.aws.amazon.com/lambda/latest/dg/with-kinesis.html) </li> <li> [Using AWS Lambda with Amazon SQS](https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html) </li> <li> [Using AWS Lambda with Amazon DynamoDB](https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html) </li> </ul> """ def create_event_source_mapping(client, input, options \\ []) do url = "/2015-03-31/event-source-mappings" headers = [] request(client, :post, url, headers, input, options, 202) end @doc """ Creates a Lambda function. To create a function, you need a [deployment package](https://docs.aws.amazon.com/lambda/latest/dg/deployment-package-v2.html) and an [execution role](https://docs.aws.amazon.com/lambda/latest/dg/intro-permission-model.html#lambda-intro-execution-role). The deployment package contains your function code. The execution role grants the function permission to use AWS services, such as Amazon CloudWatch Logs for log streaming and AWS X-Ray for request tracing. A function has an unpublished version, and can have published versions and aliases. The unpublished version changes when you update your function's code and configuration. A published version is a snapshot of your function code and configuration that can't be changed. An alias is a named resource that maps to a version, and can be changed to map to a different version. Use the `Publish` parameter to create version `1` of your function from its initial configuration. The other parameters let you configure version-specific and function-level settings. You can modify version-specific settings later with `UpdateFunctionConfiguration`. Function-level settings apply to both the unpublished and published versions of the function, and include tags (`TagResource`) and per-function concurrency limits (`PutFunctionConcurrency`). If another account or an AWS service invokes your function, use `AddPermission` to grant permission by creating a resource-based IAM policy. You can grant permissions at the function level, on a version, or on an alias. To invoke your function directly, use `Invoke`. To invoke your function in response to events in other AWS services, create an event source mapping (`CreateEventSourceMapping`), or configure a function trigger in the other service. For more information, see [Invoking Functions](https://docs.aws.amazon.com/lambda/latest/dg/invoking-lambda-functions.html). """ def create_function(client, input, options \\ []) do url = "/2015-03-31/functions" headers = [] request(client, :post, url, headers, input, options, 201) end @doc """ Deletes a Lambda function [alias](https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html). """ def delete_alias(client, function_name, name, input, options \\ []) do url = "/2015-03-31/functions/#{URI.encode(function_name)}/aliases/#{URI.encode(name)}" headers = [] request(client, :delete, url, headers, input, options, 204) end @doc """ Deletes an [event source mapping](https://docs.aws.amazon.com/lambda/latest/dg/intro-invocation-modes.html). You can get the identifier of a mapping from the output of `ListEventSourceMappings`. """ def delete_event_source_mapping(client, uuid, input, options \\ []) do url = "/2015-03-31/event-source-mappings/#{URI.encode(uuid)}" headers = [] request(client, :delete, url, headers, input, options, 202) end @doc """ Deletes a Lambda function. To delete a specific function version, use the `Qualifier` parameter. Otherwise, all versions and aliases are deleted. To delete Lambda event source mappings that invoke a function, use `DeleteEventSourceMapping`. For AWS services and resources that invoke your function directly, delete the trigger in the service where you originally configured it. """ def delete_function(client, function_name, input, options \\ []) do url = "/2015-03-31/functions/#{URI.encode(function_name)}" headers = [] request(client, :delete, url, headers, input, options, 204) end @doc """ Removes a concurrent execution limit from a function. """ def delete_function_concurrency(client, function_name, input, options \\ []) do url = "/2017-10-31/functions/#{URI.encode(function_name)}/concurrency" headers = [] request(client, :delete, url, headers, input, options, 204) end @doc """ Deletes a version of an [AWS Lambda layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html). Deleted versions can no longer be viewed or added to functions. To avoid breaking functions, a copy of the version remains in Lambda until no functions refer to it. """ def delete_layer_version(client, layer_name, version_number, input, options \\ []) do url = "/2018-10-31/layers/#{URI.encode(layer_name)}/versions/#{URI.encode(version_number)}" headers = [] request(client, :delete, url, headers, input, options, 204) end @doc """ Retrieves details about your account's [limits](https://docs.aws.amazon.com/lambda/latest/dg/limits.html) and usage in an AWS Region. """ def get_account_settings(client, options \\ []) do url = "/2016-08-19/account-settings" headers = [] request(client, :get, url, headers, nil, options, 200) end @doc """ Returns details about a Lambda function [alias](https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html). """ def get_alias(client, function_name, name, options \\ []) do url = "/2015-03-31/functions/#{URI.encode(function_name)}/aliases/#{URI.encode(name)}" headers = [] request(client, :get, url, headers, nil, options, 200) end @doc """ Returns details about an event source mapping. You can get the identifier of a mapping from the output of `ListEventSourceMappings`. """ def get_event_source_mapping(client, uuid, options \\ []) do url = "/2015-03-31/event-source-mappings/#{URI.encode(uuid)}" headers = [] request(client, :get, url, headers, nil, options, 200) end @doc """ Returns information about the function or function version, with a link to download the deployment package that's valid for 10 minutes. If you specify a function version, only details that are specific to that version are returned. """ def get_function(client, function_name, options \\ []) do url = "/2015-03-31/functions/#{URI.encode(function_name)}" headers = [] request(client, :get, url, headers, nil, options, 200) end @doc """ Returns the version-specific settings of a Lambda function or version. The output includes only options that can vary between versions of a function. To modify these settings, use `UpdateFunctionConfiguration`. To get all of a function's details, including function-level settings, use `GetFunction`. """ def get_function_configuration(client, function_name, options \\ []) do url = "/2015-03-31/functions/#{URI.encode(function_name)}/configuration" headers = [] request(client, :get, url, headers, nil, options, 200) end @doc """ Returns information about a version of an [AWS Lambda layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html), with a link to download the layer archive that's valid for 10 minutes. """ def get_layer_version(client, layer_name, version_number, options \\ []) do url = "/2018-10-31/layers/#{URI.encode(layer_name)}/versions/#{URI.encode(version_number)}" headers = [] request(client, :get, url, headers, nil, options, 200) end @doc """ Returns the permission policy for a version of an [AWS Lambda layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html). For more information, see `AddLayerVersionPermission`. """ def get_layer_version_policy(client, layer_name, version_number, options \\ []) do url = "/2018-10-31/layers/#{URI.encode(layer_name)}/versions/#{URI.encode(version_number)}/policy" headers = [] request(client, :get, url, headers, nil, options, 200) end @doc """ Returns the [resource-based IAM policy](https://docs.aws.amazon.com/lambda/latest/dg/access-control-resource-based.html) for a function, version, or alias. """ def get_policy(client, function_name, options \\ []) do url = "/2015-03-31/functions/#{URI.encode(function_name)}/policy" headers = [] request(client, :get, url, headers, nil, options, 200) end @doc """ Invokes a Lambda function. You can invoke a function synchronously (and wait for the response), or asynchronously. To invoke a function asynchronously, set `InvocationType` to `Event`. For synchronous invocation, details about the function response, including errors, are included in the response body and headers. For either invocation type, you can find more information in the [execution log](https://docs.aws.amazon.com/lambda/latest/dg/monitoring-functions.html) and [trace](https://docs.aws.amazon.com/lambda/latest/dg/dlq.html). To record function errors for asynchronous invocations, configure your function with a [dead letter queue](https://docs.aws.amazon.com/lambda/latest/dg/dlq.html). The status code in the API response doesn't reflect function errors. Error codes are reserved for errors that prevent your function from executing, such as permissions errors, [limit errors](https://docs.aws.amazon.com/lambda/latest/dg/limits.html), or issues with your function's code and configuration. For example, Lambda returns `TooManyRequestsException` if executing the function would cause you to exceed a concurrency limit at either the account level (`ConcurrentInvocationLimitExceeded`) or function level (`ReservedFunctionConcurrentInvocationLimitExceeded`). For functions with a long timeout, your client might be disconnected during synchronous invocation while it waits for a response. Configure your HTTP client, SDK, firewall, proxy, or operating system to allow for long connections with timeout or keep-alive settings. This operation requires permission for the `lambda:InvokeFunction` action. """ def invoke(client, function_name, input, options \\ []) do url = "/2015-03-31/functions/#{URI.encode(function_name)}/invocations" headers = [] if Dict.has_key?(input, "ClientContext") do headers = [{"X-Amz-Client-Context", input["ClientContext"]}|headers] input = Dict.delete(input, "ClientContext") end if Dict.has_key?(input, "InvocationType") do headers = [{"X-Amz-Invocation-Type", input["InvocationType"]}|headers] input = Dict.delete(input, "InvocationType") end if Dict.has_key?(input, "LogType") do headers = [{"X-Amz-Log-Type", input["LogType"]}|headers] input = Dict.delete(input, "LogType") end case request(client, :post, url, headers, input, options, nil) do {:ok, body, response} -> if !is_nil(response.headers["X-Amz-Executed-Version"]) do body = %{body | "ExecutedVersion" => response.headers["X-Amz-Executed-Version"]} end if !is_nil(response.headers["X-Amz-Function-Error"]) do body = %{body | "FunctionError" => response.headers["X-Amz-Function-Error"]} end if !is_nil(response.headers["X-Amz-Log-Result"]) do body = %{body | "LogResult" => response.headers["X-Amz-Log-Result"]} end {:ok, body, response} result -> result end end @doc """ <important> For asynchronous function invocation, use `Invoke`. </important> Invokes a function asynchronously. """ def invoke_async(client, function_name, input, options \\ []) do url = "/2014-11-13/functions/#{URI.encode(function_name)}/invoke-async" headers = [] request(client, :post, url, headers, input, options, 202) end @doc """ Returns a list of [aliases](https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html) for a Lambda function. """ def list_aliases(client, function_name, options \\ []) do url = "/2015-03-31/functions/#{URI.encode(function_name)}/aliases" headers = [] request(client, :get, url, headers, nil, options, 200) end @doc """ Lists event source mappings. Specify an `EventSourceArn` to only show event source mappings for a single event source. """ def list_event_source_mappings(client, options \\ []) do url = "/2015-03-31/event-source-mappings" headers = [] request(client, :get, url, headers, nil, options, 200) end @doc """ Returns a list of Lambda functions, with the version-specific configuration of each. Set `FunctionVersion` to `ALL` to include all published versions of each function in addition to the unpublished version. To get more information about a function or version, use `GetFunction`. """ def list_functions(client, options \\ []) do url = "/2015-03-31/functions" headers = [] request(client, :get, url, headers, nil, options, 200) end @doc """ Lists the versions of an [AWS Lambda layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html). Versions that have been deleted aren't listed. Specify a [runtime identifier](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html) to list only versions that indicate that they're compatible with that runtime. """ def list_layer_versions(client, layer_name, options \\ []) do url = "/2018-10-31/layers/#{URI.encode(layer_name)}/versions" headers = [] request(client, :get, url, headers, nil, options, 200) end @doc """ Lists [AWS Lambda layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) and shows information about the latest version of each. Specify a [runtime identifier](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html) to list only layers that indicate that they're compatible with that runtime. """ def list_layers(client, options \\ []) do url = "/2018-10-31/layers" headers = [] request(client, :get, url, headers, nil, options, 200) end @doc """ Returns a function's [tags](https://docs.aws.amazon.com/lambda/latest/dg/tagging.html). You can also view tags with `GetFunction`. """ def list_tags(client, resource, options \\ []) do url = "/2017-03-31/tags/#{URI.encode(resource)}" headers = [] request(client, :get, url, headers, nil, options, nil) end @doc """ Returns a list of [versions](https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html), with the version-specific configuration of each. """ def list_versions_by_function(client, function_name, options \\ []) do url = "/2015-03-31/functions/#{URI.encode(function_name)}/versions" headers = [] request(client, :get, url, headers, nil, options, 200) end @doc """ Creates an [AWS Lambda layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) from a ZIP archive. Each time you call `PublishLayerVersion` with the same version name, a new version is created. Add layers to your function with `CreateFunction` or `UpdateFunctionConfiguration`. """ def publish_layer_version(client, layer_name, input, options \\ []) do url = "/2018-10-31/layers/#{URI.encode(layer_name)}/versions" headers = [] request(client, :post, url, headers, input, options, 201) end @doc """ Creates a [version](https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html) from the current code and configuration of a function. Use versions to create a snapshot of your function code and configuration that doesn't change. AWS Lambda doesn't publish a version if the function's configuration and code haven't changed since the last version. Use `UpdateFunctionCode` or `UpdateFunctionConfiguration` to update the function before publishing a version. Clients can invoke versions directly or with an alias. To create an alias, use `CreateAlias`. """ def publish_version(client, function_name, input, options \\ []) do url = "/2015-03-31/functions/#{URI.encode(function_name)}/versions" headers = [] request(client, :post, url, headers, input, options, 201) end @doc """ Sets the maximum number of simultaneous executions for a function, and reserves capacity for that concurrency level. Concurrency settings apply to the function as a whole, including all published versions and the unpublished version. Reserving concurrency both ensures that your function has capacity to process the specified number of events simultaneously, and prevents it from scaling beyond that level. Use `GetFunction` to see the current setting for a function. Use `GetAccountSettings` to see your regional concurrency limit. You can reserve concurrency for as many functions as you like, as long as you leave at least 100 simultaneous executions unreserved for functions that aren't configured with a per-function limit. For more information, see [Managing Concurrency](https://docs.aws.amazon.com/lambda/latest/dg/concurrent-executions.html). """ def put_function_concurrency(client, function_name, input, options \\ []) do url = "/2017-10-31/functions/#{URI.encode(function_name)}/concurrency" headers = [] request(client, :put, url, headers, input, options, 200) end @doc """ Removes a statement from the permissions policy for a version of an [AWS Lambda layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html). For more information, see `AddLayerVersionPermission`. """ def remove_layer_version_permission(client, layer_name, statement_id, version_number, input, options \\ []) do url = "/2018-10-31/layers/#{URI.encode(layer_name)}/versions/#{URI.encode(version_number)}/policy/#{URI.encode(statement_id)}" headers = [] request(client, :delete, url, headers, input, options, 204) end @doc """ Revokes function-use permission from an AWS service or another account. You can get the ID of the statement from the output of `GetPolicy`. """ def remove_permission(client, function_name, statement_id, input, options \\ []) do url = "/2015-03-31/functions/#{URI.encode(function_name)}/policy/#{URI.encode(statement_id)}" headers = [] request(client, :delete, url, headers, input, options, 204) end @doc """ Adds [tags](https://docs.aws.amazon.com/lambda/latest/dg/tagging.html) to a function. """ def tag_resource(client, resource, input, options \\ []) do url = "/2017-03-31/tags/#{URI.encode(resource)}" headers = [] request(client, :post, url, headers, input, options, 204) end @doc """ Removes [tags](https://docs.aws.amazon.com/lambda/latest/dg/tagging.html) from a function. """ def untag_resource(client, resource, input, options \\ []) do url = "/2017-03-31/tags/#{URI.encode(resource)}" headers = [] request(client, :delete, url, headers, input, options, 204) end @doc """ Updates the configuration of a Lambda function [alias](https://docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html). """ def update_alias(client, function_name, name, input, options \\ []) do url = "/2015-03-31/functions/#{URI.encode(function_name)}/aliases/#{URI.encode(name)}" headers = [] request(client, :put, url, headers, input, options, 200) end @doc """ Updates an event source mapping. You can change the function that AWS Lambda invokes, or pause invocation and resume later from the same location. """ def update_event_source_mapping(client, uuid, input, options \\ []) do url = "/2015-03-31/event-source-mappings/#{URI.encode(uuid)}" headers = [] request(client, :put, url, headers, input, options, 202) end @doc """ Updates a Lambda function's code. The function's code is locked when you publish a version. You can't modify the code of a published version, only the unpublished version. """ def update_function_code(client, function_name, input, options \\ []) do url = "/2015-03-31/functions/#{URI.encode(function_name)}/code" headers = [] request(client, :put, url, headers, input, options, 200) end @doc """ Modify the version-specifc settings of a Lambda function. These settings can vary between versions of a function and are locked when you publish a version. You can't modify the configuration of a published version, only the unpublished version. To configure function concurrency, use `PutFunctionConcurrency`. To grant invoke permissions to an account or AWS service, use `AddPermission`. """ def update_function_configuration(client, function_name, input, options \\ []) do url = "/2015-03-31/functions/#{URI.encode(function_name)}/configuration" headers = [] request(client, :put, url, headers, input, options, 200) end defp request(client, method, url, headers, input, options, success_status_code) do client = %{client | service: "lambda"} host = get_host("lambda", client) url = get_url(host, url, client) headers = Enum.concat([{"Host", host}, {"Content-Type", "application/x-amz-json-1.1"}], headers) payload = encode_payload(input) headers = AWS.Request.sign_v4(client, method, url, headers, payload) perform_request(method, url, payload, headers, options, success_status_code) end defp perform_request(method, url, payload, headers, options, nil) do case HTTPoison.request(method, url, payload, headers, options) do {:ok, response=%HTTPoison.Response{status_code: 200, body: ""}} -> {:ok, response} {:ok, response=%HTTPoison.Response{status_code: 200, body: body}} -> {:ok, Poison.Parser.parse!(body), response} {:ok, response=%HTTPoison.Response{status_code: 202, body: body}} -> {:ok, Poison.Parser.parse!(body), response} {:ok, response=%HTTPoison.Response{status_code: 204, body: body}} -> {:ok, Poison.Parser.parse!(body), response} {:ok, _response=%HTTPoison.Response{body: body}} -> reason = Poison.Parser.parse!(body)["message"] {:error, reason} {:error, %HTTPoison.Error{reason: reason}} -> {:error, %HTTPoison.Error{reason: reason}} end end defp perform_request(method, url, payload, headers, options, success_status_code) do case HTTPoison.request(method, url, payload, headers, options) do {:ok, response=%HTTPoison.Response{status_code: ^success_status_code, body: ""}} -> {:ok, nil, response} {:ok, response=%HTTPoison.Response{status_code: ^success_status_code, body: body}} -> {:ok, Poison.Parser.parse!(body), response} {:ok, _response=%HTTPoison.Response{body: body}} -> reason = Poison.Parser.parse!(body)["message"] {:error, reason} {:error, %HTTPoison.Error{reason: reason}} -> {:error, %HTTPoison.Error{reason: reason}} end end defp get_host(endpoint_prefix, client) do if client.region == "local" do "localhost" else "#{endpoint_prefix}.#{client.region}.#{client.endpoint}" end end defp get_url(host, url, %{:proto => proto, :port => port}) do "#{proto}://#{host}:#{port}#{url}/" end defp encode_payload(input) do if input != nil do Poison.Encoder.encode(input, []) else "" end end end
lib/aws/lambda.ex
0.88729
0.533397
lambda.ex
starcoder
defmodule Vaxin do @moduledoc """ Contains the core functionality to work with Vaxin. Vaxin at its core is a data validator combinator library. It tries to solve the problem of validating the shape and content of some data (most useful when such data come from an external source) and of conforming those data to arbitrary formats. Vaxin is based on the concept of validators: a validator is something that knows how to validate a term and transform it to something else if necessary. A good example of a validator could be something that validates that a term is a string representation of an integer and that converts such string to the represented integer. ## Validators A validator is a function that takes one argument and returns either: * `{:ok, transformed}` - indicating the validation has succeeded (the input term is considered valid) and `transformed` is the conformed value for the input term. * `{:error, reason}` - indicating means the validation has failed (the input term is invalid). `reason` can be a string representing the error message or a `Vaxin.Error`. Note that `validate/2` will eventually wrap the error message into a `Vaxin.Error`. * `true` - indicating the validation has succeeded. It has the same effect as `{:ok, transformed}`, but it can be used when the transformed value is the same as the input value. This is useful for "predicate" validators (functions that take one argument and return a boolean). * `false` - it means validation failed. It is the same as `{:error, reason}`, except the reason only mentions that a "predicate failed". Returning a boolean value is supported so that existing predicate functions can be used as validators without modification. Examples of such functions are type guards (`is_binary/1` or `is_list/1`), functions like `String.valid?/1`, and many others. The concept of validators is very powerful as they can be easily combined: for example, the `Vaxin.all_of/1` function takes a list of validators and returns a validator that passes if all of the given validators pass. Vaxin provides both "basic" validators as well as validator combinators. ## Built-in validators On top of powerful built-in Elixir predicate functions, Vaxin also provides a few built-in validators. You might notice that they are very similar to the `Ecto.Changeset` API. The intention is to enable developers who are familiar with Ecto to be immediately productive with Vaxin. However, there is a few fundamental difference between two libraries: * Vaxin built-in validators take in options and return a **validator** which can be used with `Vaxin.validate/2` later. * Vaxin does **not** have the concept of "empty" values. `nil` or empty strings are treated the same way as other Elixir data. Consider the following example: `nil` will be validated with Vaxin while Ecto would skip it. iex> import Vaxin iex> validator = validate_number(greater_than: 0) iex> {:error, error} = validate(validator, nil) iex> Exception.message(error) "must be a number" ## Examples Let's say S.H.I.E.L.D are looking for a replacement for Captain America and receive thousands of applications, they could use Vaxin to build a profile validator. iex> import Vaxin iex> iex> age_validator = ...> validate_number( ...> &is_integer/1, ...> greater_than: 18, ...> message: "is too young to be a superhero" ...> ) iex> iex> superpower_validator = ...> validate_inclusion( ...> &is_binary/1, ...> ["fly", "strength", "i-can-do-this-all-day"], ...> message: "is unfortunately not the super-power we are looking for" ...> ) iex> superhero_validator = ...> (&is_map/1) ...> |> validate_key("age", :required, age_validator) ...> |> validate_key("superpower", :required, superpower_validator) iex> iex> peter_parker = %{"age" => 16, "superpower" => "speed"} iex> {:error, error} = Vaxin.validate(superhero_validator, peter_parker) iex> Exception.message(error) ~s("age" is too young to be a superhero) iex> iex> falcon = %{"age" => 40, "superpower" => "fly"} iex> Vaxin.validate(superhero_validator, falcon) {:ok, %{"age" => 40, "superpower" => "fly"}} """ alias Vaxin.Error @type validator() :: (any() -> {:ok, any()} | {:error, String.t()} | {:error, Error.t()} | boolean()) @doc """ Validates `value` against `validator`. ### Examples iex> Vaxin.validate(&is_atom/1, :foo) {:ok, :foo} iex> Vaxin.validate(&is_atom/1, "foo") {:error, %Vaxin.Error{validator: &is_atom/1, message: "must be an atom", metadata: [kind: :is_atom]}} """ @spec validate(validator(), any()) :: {:ok, any()} | {:error, Error.t()} def validate(validator, value) do case validator.(value) do true -> {:ok, value} false -> {:error, Error.new(validator)} {:ok, value} -> {:ok, value} {:error, message} when is_binary(message) -> {:error, Error.new(validator, message)} {:error, error} -> {:error, error} end end @doc """ Returns a validator that passes when all the given validators pass. ### Examples iex> validator = Vaxin.all_of([&is_integer/1, &(&1 >= 1)]) iex> Vaxin.validate(validator, 1) {:ok, 1} iex> {:error, %Vaxin.Error{message: "is invalid"}} = Vaxin.validate(validator, 0) """ @spec all_of([validator(), ...]) :: validator() def all_of([_ | _] = validators) do Enum.reduce(validators, &combine(&2, &1)) end @doc """ Combines `validator1` with `validator2`. Note that `validator2` will only be executed if `validator1` succeeds. ### Examples iex> validator = Vaxin.combine(&is_integer/1, &(&1 >= 1)) iex> Vaxin.validate(validator, 1) {:ok, 1} iex> {:error, %Vaxin.Error{message: "is invalid"}} = Vaxin.validate(validator, 0) """ @spec combine(validator(), validator()) :: validator() def combine(validator1, validator2) when is_function(validator1, 1) when is_function(validator2, 1) do &with {:ok, term} <- validate(validator1, &1) do validate(validator2, term) end end @doc """ Returns a validator that always passes. It is useful placing in the beginning of the validator chain. ### Examples iex> validator = Vaxin.noop() |> Vaxin.validate_inclusion([:foo, "foo"]) iex> Vaxin.validate(validator, :foo) {:ok, :foo} iex> Vaxin.validate(validator, "foo") {:ok, "foo"} """ @spec noop() :: (any() -> {:ok, any()}) @compile {:inline, [noop: 0]} def noop(), do: &{:ok, &1} @doc """ Combines `combinator` with a validator that checks the value of `key` in a map. ## Options * `message` - the message on failure. Defaults to "is required" or the error returned by `value_validator`. ## Examples iex> tinyint_validator = validate_number(greater_than_or_equal_to: -128, less_than: 128, message: "must be a tinyint") iex> validator = Vaxin.validate_key(:id, :required, tinyint_validator) iex> Vaxin.validate(validator, %{id: 1}) {:ok, %{id: 1}} iex> {:error, error} = Vaxin.validate(validator, %{id: 129}) iex> Exception.message(error) "id must be a tinyint" """ @spec validate_key(validator(), any(), :required | :optional, validator(), Keyword.t()) :: validator() def validate_key( combinator \\ &is_map/1, key, required_or_optional, value_validator, options \\ [] ) def validate_key(combinator, key, required_or_optional, value_validator, options) do combine(combinator, fn map -> message = options[:message] case Map.fetch(map, key) do {:ok, value} -> case validate(value_validator, value) do {:ok, value} -> {:ok, Map.replace!(map, key, value)} {:error, error} -> error = error |> Error.maybe_update_message(message) |> Error.add_position({:key, key}) {:error, error} end :error -> if required?(required_or_optional) do {:error, Error.new(:required, message || "is required", position: {:key, key})} else {:ok, map} end end end) end defp required?(:required), do: true defp required?(:optional), do: false @doc """ Combines `combinator` with a validator that validates string length. ## Options * `exact` - the length must be exact this value. * `min` - the length must be greater than or equal to this value. * `max` - the length must be less than or equal to this value. * `message` - the message on failure. Defaults to either: * must be %{length} byte(s) * must be at least %{length} byte(s) * must be at most %{length} byte(s) ## Examples iex> validator = Vaxin.validate_string_length(min: 1, max: 20) iex> Vaxin.validate(validator, "Hello World!") {:ok, "Hello World!"} iex> {:error, error} = Vaxin.validate(validator, "") iex> Exception.message(error) "must be at least 1 byte(s)" """ @spec validate_string_length(validator(), Keyword.t()) :: validator() def validate_string_length(validator \\ &String.valid?/1, options) def validate_string_length(validator, options) do combine(validator, fn value -> {message, options} = Keyword.pop(options, :message) with :ok <- do_validate_length(options, byte_size(value), message), do: {:ok, value} end) end @length_validators %{ exact: {&==/2, "must be %{length} byte(s)"}, min: {&>=/2, "must be at least %{length} byte(s)"}, max: {&<=/2, "must be at most %{length} byte(s)"} } defp do_validate_length([], _, _), do: :ok defp do_validate_length([{spec, target} | rest], count, message) do {comparator, default_message} = Map.fetch!(@length_validators, spec) if comparator.(count, target) do do_validate_length(rest, count, message) else {:error, Error.new(:string_length, message || default_message, kind: spec, length: target)} end end @doc """ Combines `combinator` with a validator that validates the term as a number. ## Options * `less_than` - the number must be less than this value. * `greater_than` - the number must be greater than this value. * `less_than_or_equal_to` - the number must be less than or equal to this value. * `greater_than_or_equal_to` - the number must be greater than or equal to this value. * `equal_to` - the number must be equal to this value. * `not_equal_to` - the number must be not equal to this value. * `message` - the error message when the number validator fails. Defaults to either: * must be less than %{number} * must be greater than %{number} * must be less than or equal to %{number} * must be greater than or equal to %{number} * must be equal to %{number} * must be not equal to %{number} ## Examples iex> validator = Vaxin.validate_number(greater_than: 1, less_than: 20) iex> Vaxin.validate(validator, 10) {:ok, 10} iex> {:error, error} = Vaxin.validate(validator, 20) iex> Exception.message(error) "must be less than 20" """ @spec validate_number(validator(), Keyword.t()) :: validator() def validate_number(combinator \\ &is_number/1, options) do combine(combinator, fn value -> {message, options} = Keyword.pop(options, :message) Vaxin.Number.validate(value, options, message) end) end @doc """ Combines `combinator` with a validator that validates the term matches the given regular expression. ## Options * `message` - the error message when the format validator fails. Defaults to `"has invalid format"`. ## Examples iex> import Vaxin iex> validator = validate_format(&String.valid?/1, ~r/@/) iex> validate(validator, "<EMAIL>") {:ok, "<EMAIL>"} """ @spec validate_format(validator(), Regex.t(), Keyword.t()) :: validator() def validate_format(combinator \\ &String.valid?/1, format, options \\ []) do combine(combinator, fn value -> if value =~ format do {:ok, value} else {:error, Error.new(:format, options[:message] || "has invalid format", format: format)} end end) end @doc """ Combines `combinator` with a validator that validates the term is included in `permitted`. ## Options * `message` - the error message on failure. Defaults to "is invalid". ## Examples iex> import Vaxin iex> validator = validate_inclusion(["foo", "bar"]) iex> validate(validator, "foo") {:ok, "foo"} """ @spec validate_inclusion(validator(), Enum.t(), Keyword.t()) :: validator() def validate_inclusion(validator \\ noop(), permitted, options \\ []) def validate_inclusion(validator, permitted, options) do combine(validator, fn value -> if value in permitted do {:ok, value} else {:error, Error.new(:inclusion, options[:message] || "is invalid", enum: permitted)} end end) end @doc """ Combines `combinator` with a validator that validates the term is excluded in `permitted`. ## Options * `message` - the error message on failure. Defaults to "is reserved". ## Examples iex> import Vaxin iex> validator = validate_exclusion(["foo", "bar"]) iex> {:error, error} = validate(validator, "foo") iex> Exception.message(error) "is reserved" """ @spec validate_exclusion(validator(), Enum.t(), Keyword.t()) :: validator() def validate_exclusion(validator \\ noop(), reversed, options \\ []) do combine(validator, fn value -> if value not in reversed do {:ok, value} else {:error, Error.new(:exclusion, options[:message] || "is reserved", enum: reversed)} end end) end @doc """ Combine `combinator` with a validator that validates every item in an enum against `each_validator`. ## Options * `skip_invalid?` - (boolean) if `true`, skips all invalid items. Defaults to `false`. * `into` - the collectable where the transformed values should end up in. Defaults to `[]`. ## Examples iex> import Vaxin iex> validator = validate_enum(&is_list/1, &is_integer/1) iex> Vaxin.validate(validator, [1, 2]) {:ok, [1, 2]} iex> {:error, error} = Vaxin.validate(validator, [1, "2"]) iex> Exception.message(error) "[1] must be an integer" iex> validator = validate_enum(&is_list/1, &is_integer/1, skip_invalid?: true) iex> Vaxin.validate(validator, [1, "2"]) {:ok, [1]} """ @spec validate_enum(validator(), validator(), Keyword.t()) :: validator() def validate_enum(combinator, each_validator, options \\ []) def validate_enum(combinator, each_validator, options) do combine(combinator, fn enum -> skip_invalid? = Keyword.get(options, :skip_invalid?, false) into = Keyword.get(options, :into, []) enum # TODO: Handle map keys better. |> Enum.with_index() |> Vaxin.Enum.validate(each_validator, [], skip_invalid?, into, options[:message]) end) end @doc """ Returns a validator that always passes and applies the given `transformer`. ## Examples iex> import Vaxin iex> validator = transform(noop(), &String.to_integer/1) iex> validate(validator, "1") {:ok, 1} """ @spec transform(validator(), (any() -> any())) :: validator() def transform(combinator \\ noop(), transformer) do combine(combinator, &{:ok, transformer.(&1)}) end end
lib/vaxin.ex
0.92657
0.814533
vaxin.ex
starcoder
defmodule Mentat do @moduledoc """ Provides a basic cache with ttls. ## Usage A cache must be given a name when its started. ``` Mentat.start_link(name: :my_cache) ``` After its been started you can store and retrieve values: ``` Mentat.put(:my_cache, user_id, user) user = Mentat.get(:my_cache, user_id) ``` ## TTLs Both `put` and `fetch` operations allow you to specify the key's TTL. If no TTL is provided then the TTL is set to `:infinity`. TTL times are always in milliseconds. ``` Mentat.put(:my_cache, :key, "value", [ttl: 5_000]) Mentat.fetch(:my_cache, :key, [ttl: 5_000], fn key -> {:commit, "value"} end) ``` ## Limits Mentat supports optional limits per cache. ```elixir Mentat.start_link(name: LimitedCache, limit: [size: 100]) ``` When the limit is reached, the janitor will asynchronously reclaim a percentage of the keys ## Telemetry Mentat publishes multiple telemetry events. * `[:mentat, :get]` - executed after retrieving a value from the cache. Measurements are: * `:status` - Can be either `:hit` or `:miss` depending on if the key was found in the cache. Metadata are: * `:key` - The key requested * `:cache` - The cache name * `[:mentat, :put]` - executed when putting a key into the cache. No measurements are provided. Metadata are: * `:key` - The key requested * `:cache` - The name of the cache * `[:mentat, :janitor, :cleanup]` - executed after old keys are cleaned from the cache. Measurements are: * `:duration` - the time it took to clean up the old keys. Time is in `:native` units. * `total_removed_keys` - The count of keys removed from the cache. Metadata are: * `cache` - The cache name. """ use Supervisor alias Mentat.Janitor @cache_options [ name: [ type: :atom, required: true, ], cleanup_interval: [ type: :pos_integer, default: 5_000, doc: "How often the janitor process will remove old keys." ], ets_args: [ type: :any, doc: "Additional arguments to pass to `:ets.new/2`.", default: [], ], limit: [ doc: "Limits to the number of keys a cache will store.", type: :keyword_list, keys: [ size: [ type: :pos_integer, doc: "The maximum number of values to store in the cache.", required: true ], reclaim: [ type: :any, doc: "The percentage of keys to reclaim if the limit is exceeded.", default: 0.1 ] ], default: :none ], ] @doc """ Starts a new cache. Options: #{NimbleOptions.docs(@cache_options)} """ def start_link(args) do args = NimbleOptions.validate!(args, @cache_options) name = args[:name] Supervisor.start_link(__MODULE__, args, name: name) end @doc """ Retrieves a value from a the cache. Returns `nil` if the key is not found. """ def get(cache, key, opts \\ []) do now = ms_time(opts) case :ets.lookup(cache, key) do [] -> :telemetry.execute([:mentat, :get], %{status: :miss}, %{key: key, cache: cache}) nil [{^key, _val, ts, ttl}] when is_integer(ttl) and ts + ttl <= now -> :telemetry.execute([:mentat, :get], %{status: :miss}, %{key: key, cache: cache}) nil [{^key, val, _ts, _expire_at}] -> :telemetry.execute([:mentat, :get], %{status: :hit}, %{key: key, cache: cache}) val end end @doc """ Fetches a value or executes the fallback function. The function can return either `{:commit, term()}` or `{:ignore, term()}`. If `{:commit, term()}` is returned, the value will be stored in the cache before its returned. See the "TTLs" section for a list of options. ## Example ``` Mentat.fetch(:cache, user_id, fn user_id -> case get_user(user_id) do {:ok, user} -> {:commit, user} error -> {:ignore, error} end end) ``` """ def fetch(cache, key, opts \\ [], fallback) do with nil <- get(cache, key, opts) do case fallback.(key) do {:commit, value} -> put(cache, key, value, opts) value {:ignore, value} -> value end end end @doc """ Puts a new key into the cache. See the "TTLs" section for a list of options. """ def put(cache, key, value, opts \\ []) do %{limit: limit} = :persistent_term.get({__MODULE__, cache}) :telemetry.execute([:mentat, :put], %{}, %{key: key, cache: cache}) now = ms_time(opts) ttl = Keyword.get(opts, :ttl) || :infinity result = :ets.insert(cache, {key, value, now, ttl}) # If we've reached the limit on the table, we need to purge a number of old # keys. We do this by calling the janitor process and telling it to purge. # This will, in turn call immediately back into the remove_oldest function. # The back and forth here is confusing to follow, but its necessary because # we want to do the purging in a different process. if limit != :none && :ets.info(cache, :size) > limit.size do count = ceil(limit.size * limit.reclaim) Janitor.reclaim(janitor(cache), count) end result end @doc """ Updates a keys inserted at time. This is useful in conjunction with limits when you want to evict the oldest keys. """ def touch(cache, key, opts \\ []) do :ets.update_element(cache, key, {3, ms_time(opts)}) end @doc """ Deletes a key from the cache """ def delete(cache, key) do :ets.delete(cache, key) end @doc """ Returns a list of all keys. """ def keys(cache) do # :ets.fun2ms(fn({key, _, _} -> key end)) ms = [{{:"$1", :_, :_, :_}, [], [:"$1"]}] :ets.select(cache, ms) end @doc """ Removes all keys from the cache. """ def purge(cache) do :ets.delete_all_objects(cache) end @doc false def remove_expired(cache, opts \\ []) do now = ms_time(opts) # Find all expired keys by selecting the timestamp and ttl, adding them together # and finding the keys that are lower than the current time ms = [ {{:_, :_, :"$1", :"$2"}, [{:andalso, {:is_integer, :"$2"}, {:<, {:+, :"$1", :"$2"}, now}}], [true]} ] :ets.select_delete(cache, ms) end @doc false def remove_oldest(cache, count) do ms = [{{:_, :_, :"$1", :_}, [], [:"$1"]}] entries = :ets.select(cache, ms) oldest = entries |> Enum.sort() |> Enum.take(count) |> List.last() delete_ms = [{{:_, :_, :"$1", :_}, [{:"=<", :"$1", oldest}], [true]}] :ets.select_delete(cache, delete_ms) end def init(args) do name = Keyword.get(args, :name) interval = Keyword.get(args, :cleanup_interval) limit = Keyword.get(args, :limit) limit = if limit != :none, do: Map.new(limit), else: limit ets_args = Keyword.get(args, :ets_args) ^name = :ets.new(name, [:set, :named_table, :public] ++ ets_args) :persistent_term.put({__MODULE__, name}, %{limit: limit}) janitor_opts = [ name: janitor(name), interval: interval, cache: name ] children = [ {Mentat.Janitor, janitor_opts} ] Supervisor.init(children, strategy: :one_for_one) end defp timer(opts) do Keyword.get(opts, :clock, System) end defp ms_time(opts) do timer(opts).monotonic_time(:millisecond) end defp janitor(name) do :"#{name}_janitor" end end
lib/mentat.ex
0.90045
0.891481
mentat.ex
starcoder
defmodule HumanizeTime do @moduledoc """ Module for converting seconds and milliseconds to human readable timestamps. """ @type duration_map :: %{ days: integer(), hours: integer(), minutes: integer(), seconds: integer() } @doc """ Formatter for converting seconds to a human readable format ## Examples iex> HumanizeTime.format_seconds(23487) "6 hr 31 min" """ @spec format_seconds(integer() | float(), keyword()) :: String.t() def format_seconds(seconds, opts \\ []) def format_seconds(nil, nil_fallback: nil_fallback), do: nil_fallback def format_seconds(nil, _), do: "" def format_seconds(seconds, opts) when is_float(seconds) do seconds |> Float.round() |> Kernel.trunc() |> format_seconds(opts) end def format_seconds(seconds, opts) do initial_acc = %{ days: 0, hours: 0, minutes: 0, seconds: 0 } calculate_times(initial_acc, abs(seconds)) |> print_duration(opts[:formatters]) |> handle_negative_printing(seconds) end @spec calculate_times(duration_map(), integer()) :: duration_map() defp calculate_times(time_tracker, 0), do: time_tracker defp calculate_times(time_tracker, seconds) do day_seconds = 86_400 hour_seconds = 3_600 minute_seconds = 60 cond do seconds / day_seconds >= 1 -> days = time_tracker.days + div(seconds, day_seconds) remaining_seconds = seconds - days * day_seconds calculate_times(%{time_tracker | days: days}, remaining_seconds) seconds / hour_seconds >= 1 -> hours = time_tracker.hours + div(seconds, hour_seconds) remaining_seconds = seconds - hours * hour_seconds calculate_times(%{time_tracker | hours: hours}, remaining_seconds) seconds / minute_seconds >= 1 -> minutes = time_tracker.minutes + div(seconds, minute_seconds) remaining_seconds = seconds - minutes * minute_seconds calculate_times(%{time_tracker | minutes: minutes}, remaining_seconds) true -> %{time_tracker | seconds: seconds} end end @spec print_duration(duration_map(), duration_map() | nil) :: String.t() defp print_duration(duration, formatters) do %{days: days, hours: hours, minutes: minutes, seconds: seconds} = duration default_formatter = default_formatters() formats = case formatters do nil -> default_formatter user_formats -> user_formats end days_f = formats[:days] || default_formatter[:days] hours_f = formats[:hours] || default_formatter[:hours] minutes_f = formats[:minutes] || default_formatter[:minutes] seconds_f = formats[:seconds] || default_formatter[:seconds] cond do days > 0 -> day_string = days_f.(days) rounded_hours = if minutes >= 30 do hours + 1 else hours end hour_string = hours_f.(rounded_hours) String.trim("#{day_string} #{hour_string}") hours > 0 -> hour_string = hours_f.(hours) rounded_mins = if seconds >= 30 do minutes + 1 else minutes end minute_string = minutes_f.(rounded_mins) String.trim("#{hour_string} #{minute_string}") minutes > 0 -> minute_string = minutes_f.(minutes) seconds_string = seconds_f.(seconds) String.trim("#{minute_string} #{seconds_string}") true -> String.trim(seconds_f.(seconds)) end end @spec print_days(integer()) :: String.t() defp print_days(0), do: "" defp print_days(1), do: "1 day" defp print_days(duration), do: "#{duration} days" @spec print_hours(integer()) :: String.t() defp print_hours(0), do: "" defp print_hours(duration), do: "#{duration} hr" @spec print_minutes(integer()) :: String.t() defp print_minutes(0), do: "" defp print_minutes(duration), do: "#{duration} min" @spec print_seconds(integer()) :: String.t() defp print_seconds(0), do: "" defp print_seconds(duration), do: "#{duration} sec" @spec handle_negative_printing(integer(), integer()) :: String.t() defp handle_negative_printing(output, original_seconds) when original_seconds < 0 do "-#{output}" end defp handle_negative_printing(output, _), do: output defp default_formatters do %{ days: fn day -> print_days(day) end, hours: fn hour -> print_hours(hour) end, minutes: fn minute -> print_minutes(minute) end, seconds: fn second -> print_seconds(second) end } end end
lib/humanize_time.ex
0.845002
0.575081
humanize_time.ex
starcoder
defmodule Matrex.Validation do @moduledoc """ Basic validation Available options: - type: validates the type - :string - :integer - key: store in a different key - default: default value for optional - default_lazy: function to define a default - post: function to post process """ @typep key :: String.t() | atom @spec required(key, map, map, Keyword.t()) :: {:ok, map} | {:error, term} def required(key, args, acc, options \\ []) do case fetch(key, args) do :error -> {:error, {:missing_arg, key}} {:ok, value} -> validate_value(key, value, acc, options) end end @spec optional(key, map, map, Keyword.t()) :: {:ok, map} | {:error, term} def optional(key, args, acc, options \\ []) do case fetch(key, args) do :error -> default(key, acc, options) {:ok, value} -> validate_value(key, value, acc, options) end end @spec validate_value(key, any, map, Keyword.t()) :: {:ok, map} | {:error, term} defp validate_value(key, value, acc, options) do with :ok <- validate_type(value, options), {:ok, value} <- cast(value, options), :ok <- validate_allowed(value, options), {:ok, value} <- postprocess(value, options) do key = get_key(key, options) {:ok, Map.put(acc, key, value)} else {:error, error} -> {:error, {error, key}} end end @spec validate_type(any, Keyword.t()) :: :ok | {:error, atom} defp validate_type(value, options) do case Keyword.fetch(options, :type) do :error -> :ok {:ok, type} -> _validate_type(type, value) end end @spec _validate_type(atom, any) :: :ok | {:error, atom} defp _validate_type(:string, value) when is_binary(value), do: :ok defp _validate_type(:integer, value) when is_integer(value), do: :ok defp _validate_type(:boolean, value) when is_boolean(value), do: :ok defp _validate_type(:map, value) when is_map(value), do: :ok defp _validate_type(:list, value) when is_list(value), do: :ok defp _validate_type(_, _), do: {:error, :bad_type} @spec cast(any, Keyword.t()) :: {:ok, any} | {:error, atom} defp cast(value, options) do case Keyword.fetch(options, :as) do :error -> {:ok, value} {:ok, new_type} -> _cast(value, new_type) end end @spec _cast(any, atom) :: {:ok, any} | {:error, atom} defp _cast(value, :atom) when is_binary(value) do try do String.to_existing_atom(value) rescue ArgumentError -> {:error, :bad_value} else v -> {:ok, v} end end @spec validate_allowed(any, Keyword.t()) :: :ok | {:error, atom} defp validate_allowed(value, options) do case Keyword.fetch(options, :allowed) do :error -> :ok {:ok, allowed} -> case value in allowed do true -> :ok false -> {:error, :bad_value} end end end @spec postprocess(any, Keyword.t()) :: {:ok, any} | {:error, term} defp postprocess(value, options) do case Keyword.fetch(options, :post) do :error -> {:ok, value} {:ok, post} -> post.(value) end end @spec get_key(key, Keyword.t()) :: key defp get_key(key, options) do Keyword.get(options, :key, key) end @spec default(key, map, Keyword.t()) :: {:ok, map} defp default(key, acc, options) do case Keyword.fetch(options, :default) do :error -> default_lazy(key, acc, options) {:ok, default} -> key = get_key(key, options) {:ok, Map.put(acc, key, default)} end end @spec default_lazy(key, map, Keyword.t()) :: {:ok, map} defp default_lazy(key, acc, options) do case Keyword.fetch(options, :default_lazy) do :error -> {:ok, acc} {:ok, default} -> value = default.() key = get_key(key, options) {:ok, Map.put(acc, key, value)} end end @spec fetch(key, map) :: any defp fetch(key, args) do with :error <- Map.fetch(args, key) do if is_atom(key) do Map.fetch(args, Atom.to_string(key)) else :error end end end end
lib/matrex/validation.ex
0.825167
0.467271
validation.ex
starcoder
defmodule Optimizer do @moduledoc """ Provides a optimizer for [AST](https://elixirschool.com/en/lessons/advanced/metaprogramming/) """ import SumMag alias Pelemay.Db require Logger @term_options [Enum: true, String: true] @doc """ Optimize funcions which be enclosed `defpelemay`, using `optimize_***` function. Input is funcion definitions. ``` quote do def twice_plus(list) do twice = list |> Enum.map(&(&1*2)) twice |> Enum.map(&(&1+1)) end def foo, do: "foo" end ``` """ def replace(definitions, module) do nif_module = module |> Pelemay.Generator.elixir_nif_module() |> String.to_atom() definitions |> melt_block |> Enum.map(&optimize_func(&1)) |> iced_block |> consist_alias(nif_module) end def consist_alias(definitions, module) do Macro.prewalk( definitions, fn {:__aliases__, [alias: false], [:ReplaceModule]} -> module other -> other end ) end def consist_context(definitions) do Macro.prewalk( definitions, fn { ast, {{:., _, [_, func_name]}, [], _arg} = replacer } -> case Db.impl_validate(func_name) do true -> replacer _ -> ast end other -> other end ) end @doc """ Input is one funcion definition: ``` quote do def twice_plus(list) do twice = list |> Enum.map(&(&1*2)) twice |> Enum.map(&(&1+1)) end end ``` """ def optimize_func({def_key, meta, [arg_info, exprs]} = ast) do case def_key do :def -> {:def, meta, [arg_info, optimize_exprs(exprs)]} :defp -> {:defp, meta, [arg_info, optimize_exprs(exprs)]} _ -> raise ArgumentError, message: Macro.to_string(ast) end end @doc """ Input is some expresions: ``` quote do twice = list |> Enum.map(&(&1*2)) twice |> Enum.map(&(&1+1)) end ``` """ def optimize_exprs(exprs) do exprs |> melt_block |> Enum.map(&optimize_expr(&1)) |> iced_block end @doc """ Input is one expression: ``` quote do twice = list |> Enum.map(&(&1*2)) end ``` """ def optimize_expr(expr) do expr |> Macro.unpipe() |> accelerate_expr() |> pipe end defp accelerate_expr(unpiped_list) do # Delete pos unpiped_list |> delete_pos |> Enum.map(&parallelize_term(&1, @term_options)) |> add_pos end defp delete_pos(unpiped_list) do Enum.map(unpiped_list, fn {x, _} -> x end) end defp add_pos(unpiped_list) do Enum.map(unpiped_list, fn x -> {x, 0} end) end @doc """ Input is a term: ``` quote do: list quote do: Enum.map(&(&1*2)) ``` """ def parallelize_term({atom, _, nil} = arg, _) when is_atom(atom) do arg end def parallelize_term({atom, [], _} = arg, _) when is_atom(atom) do arg end def parallelize_term(term, options) when is_list(options) do term |> Macro.quoted_literal?() |> case do true -> term false -> info = extract_module_informations(term, options) init(term, info) end end def extract_module_informations(term, options) do Enum.reduce(options, [], fn opt, acc -> acc ++ extract_module_information(term, opt) end) end def extract_module_information(term, {module, true}) do str = Atom.to_string(module) <> ".__info__(:functions)" {module_functions, _} = Code.eval_string(str) SumMag.include_specified_functions?(term, [{module, module_functions}]) |> case do [] -> [] other -> [{module, other}] end end def init(ast, [{_, []}]), do: ast def init(ast, module_info) do {_func, _meta, args} = ast optimized_ast = Analyzer.parse(args) |> verify |> case do {:ok, polymap} -> # polymap |> IO.inspect(label: "polymap") {:ok, format(polymap, module_info)} {:error, _} -> {:error, "Not supported"} end case optimized_ast do {:ok, opt_ast} -> {ast, opt_ast} {:error, _} -> ast end end defp format(polymap, module_info) do modules = module_info |> Keyword.keys() functions = module_info |> Keyword.values() func_name = Generator.Name.generate_function_name(functions, polymap) case Db.validate(func_name) do false -> nil _ -> info = %{ module: modules, function: functions, nif_name: func_name, arg_num: 1, args: polymap, impl: nil } Db.register(info) end replace_function(func_name, polymap) end def replace_function(func_name, polymap) do func_name = func_name |> String.to_atom() flat_vars = polymap |> List.flatten() |> Keyword.get_values(:var) first_func_vars = generate_arguments(polymap) { {:., [], [{:__aliases__, [alias: false], [:ReplaceModule]}, func_name]}, [], flat_vars ++ first_func_vars } end def generate_arguments(func: %{operators: operators} = polymap) do operators |> Enum.filter(&(is_bitstring(&1) == true)) |> case do [] -> [] _ -> generate_arguments(polymap) end end def generate_arguments(%{args: args}) do Enum.map(args, &generate_argument(&1)) |> List.flatten() end def generate_arguments(_), do: [] def generate_argument({:&, _, [num]}) when is_number(num), do: [] def generate_argument(other), do: other defp verify(polymap) when is_list(polymap) do var_num = polymap |> List.flatten() |> Keyword.get_values(:var) |> length func_num = polymap |> List.flatten() |> Keyword.get_values(:func) |> length case {var_num, func_num} do {0, 1} -> {:ok, polymap} {0, 0} -> {:error, polymap} {_, 0} -> {:ok, polymap} _ -> {:error, polymap} end end end
lib/pelemay/optimizer.ex
0.828419
0.789842
optimizer.ex
starcoder
defmodule LoopsWithFriends.JamCollection.Collection do @moduledoc """ Represents a collection of jams, indexed by UUID and containing a list of users. Ensures that there are never more than `@max_users` users in a given jam. """ @behaviour LoopsWithFriends.JamCollection alias LoopsWithFriends.StatsCollection @max_users 7 def new(_opts \\ []), do: %{} def add_user(jams, jam_id, new_user, _opts \\ []) do jam_users = jams[jam_id] || [] collection = put_in(jams[jam_id], Enum.concat(jam_users, [new_user])) if length(collection[jam_id]) <= @max_users do {:ok, collection} else {:error} end end def most_populated_jam_with_capacity_or_new(jams) when jams == %{}, do: uuid() def most_populated_jam_with_capacity_or_new(jams) do jam_with_most_users_under_max(jams) || uuid() end def remove_user(jams, jam_id, user_id, _opts \\ []) do users = jams[jam_id] |> List.delete(user_id) update(jams, jam_id, users) end def stats(jams) do jams |> Enum.reduce(%StatsCollection{}, &accumulate_stats/2) end defp jam_with_most_users_under_max(jams) do jams |> Enum.filter(&less_than_max_users/1) |> Enum.sort_by(&users/1, &more_first/2) |> List.first |> jam_id_or_nil end defp jam_id_or_nil(nil), do: nil defp jam_id_or_nil({jam_id, _users}) do jam_id end defp less_than_max_users({_jam_id, users}) do length(users) < @max_users end defp users({_jam_id, users}) do users end defp more_first(users_1, users_2) do length(users_1) >= length(users_2) end defp update(jams, jam_id, []) do Map.delete(jams, jam_id) end defp update(jams, jam_id, users) do put_in jams[jam_id], users end defp accumulate_stats({jam_id, users}, stats) do %StatsCollection{ jam_count: stats.jam_count + 1, user_count: stats.user_count + length(users), jams: Map.merge(stats.jams, %{jam_id => %{user_count: length(users)}}) } end defp uuid do UUID.uuid4() end end
lib/loops_with_friends/jam_collection/collection.ex
0.672654
0.433382
collection.ex
starcoder
defmodule Farmbot.CeleryScript.AST do @moduledoc """ Handy functions for turning various data types into Farbot Celery Script Ast nodes. """ @typedoc "Arguments to a Node." @type args :: map @typedoc "Body of a Node." @type body :: [t] @typedoc "Kind of a Node." @type kind :: module @typedoc "AST node." @type t :: %__MODULE__{ kind: kind, args: args, body: body, comment: binary } # AST struct. defstruct [:kind, :args, :body, :comment] @doc "Encode a AST back to a map." def encode(%__MODULE__{kind: mod, args: args, body: body, comment: comment}) do case mod.encode_args(args) do {:ok, encoded_args} -> case encode_body(body) do {:ok, encoded_body} -> {:ok, %{kind: mod_to_kind(mod), args: encoded_args, body: encoded_body, comment: comment}} {:error, _} = err -> err end {:error, _} = err -> err end end def encode(thing) do {:error, "#{inspect thing} is not an AST node for encoding."} end @doc "Encode a list of asts." def encode_body(body, acc \\ []) def encode_body([ast | rest], acc) do case encode(ast) do {:ok, encoded} -> encode_body(rest, [encoded | acc]) {:error, _} = err -> err end end def encode_body([], acc), do: {:ok, Enum.reverse(acc)} @doc "Try to decode anything into an AST struct." def decode(arg1) def decode(binary) when is_binary(binary) do case Poison.decode(binary, keys: :atoms) do {:ok, map} -> decode(map) {:error, :invalid, _} -> {:error, :unknown_binary} {:error, _} -> {:error, :unknown_binary} end end def decode(list) when is_list(list), do: decode_body(list) def decode(%{__struct__: _} = herp) do Map.from_struct(herp) |> decode() end def decode(%{"kind" => kind, "args" => str_args} = str_map) do args = Map.new(str_args, &str_to_atom(&1)) case decode(str_map["body"] || []) do {:ok, body} -> %{kind: kind, args: args, body: body, comment: str_map["comment"]} |> decode() {:error, _} = err -> err end end def decode(%{kind: kind, args: %{}} = map) do case kind_to_mod(kind) do nil -> {:error, {:unknown_kind, kind}} mod when is_atom(mod) -> do_decode(mod, map) end end defp do_decode(mod, %{kind: kind, args: args} = map) do case decode_body(map[:body] || []) do {:ok, body} -> case mod.decode_args(args) do {:ok, decoded} -> opts = [kind: mod, args: decoded, body: body, comment: map[:comment]] val = struct(__MODULE__, opts) {:ok, val} {:error, reason} -> {:error, {kind, reason}} end {:error, _} = err -> err end end # decode a list of ast nodes. defp decode_body(body, acc \\ []) defp decode_body([node | rest], acc) do case decode(node) do {:ok, re} -> decode_body(rest, [re | acc]) {:error, _} = err -> err end end defp decode_body([], acc), do: {:ok, Enum.reverse(acc)} @doc "Lookup a module by it's kind." def kind_to_mod(kind) when is_binary(kind) do mod = [__MODULE__, "Node", Macro.camelize(kind)] |> Module.concat() case Code.ensure_loaded?(mod) do false -> nil true -> mod end end def kind_to_mod(module) when is_atom(module) do module end @doc "Change a module back to a kind." def mod_to_kind(module) when is_atom(module) do Module.split(module) |> List.last() |> Macro.underscore() end defp str_to_atom({key, value}) do k = if is_atom(key), do: key, else: String.to_atom(key) cond do is_map(value) -> {k, Map.new(value, &str_to_atom(&1))} is_list(value) -> {k, Enum.map(value, fn(sub_str_map) -> Map.new(sub_str_map, &str_to_atom(&1)) end)} is_binary(value) -> {k, value} is_atom(value) -> {k, value} is_number(value) -> {k, value} end end end
lib/farmbot/celery_script/ast/ast.ex
0.852245
0.485051
ast.ex
starcoder
defmodule Relax.Router do @moduledoc """ A DSL for defining a routing structure to determine what resources handle which requests. ## Example: defmodule MyApp.Router do use Relax.Router plug :route plug :not_found version :v1 do resource :posts, MyApp.Resources.V1.Posts do resource :comments, MyApp.Resources.V1.Comments end resource :authors, MyApp.Resources.V1.Authors end end This routes as such: /v1/posts(.*) -> MyApp.Resources.V1.Posts /v1/posts/:id/comments(.*) -> MyApp.Resources.V1.Comments /v1/authors(.*) -> MyApp.Resources.V1.Authors ### Provided Plugs Relax.Resource provides 2 plug functions, `route` and `not found`. * `plug :route` - Required to dispatch requests to the appropriate resource. * `plug :not_found` - Optionally returns a 404 for all unmatched requests. ## Plug.Builder vs Plug.Router By default `use Relax.Router` will also `use Plug.Builder`, however if you wish to capture non-standard routes you can pass the `plug: :router` option to the use statement and use Plug.Router along side your normal resource routes. defmodule MyRouter do use Relax.Router, plug: :router plug :route plug :match plug :dispatch version :v2 do resource :posts, MyApp.Resources.V1.Posts end get "ping", do: send_resp(conn, 200, "pong") end """ @doc false defmacro __using__(opts) do plug_module = case opts[:plug] do nil -> Plug.Builder :builder -> Plug.Builder :router -> Plug.Router end quote location: :keep do use unquote(plug_module) import Relax.Router def route(conn, _opts) do do_relax_route(conn, conn.path_info) end def not_found(conn, opts) do Relax.NotFound.call(conn, Dict.merge(opts, type: :route)) end end end @doc """ Define what version the api is. This can be any atom but it is expected to be part of the URL. """ defmacro version(version, do: block) do quote do @version Atom.to_string(unquote(version)) @nested_in nil unquote(block) @version nil end end @doc """ Defines each resource. Take a path fragment as an atom and module (a resource) to handle the path. May be nested one level deep. """ defmacro resource(name, module) do forward_resource(name, module) end defmacro resource(name, module, do: block) do forward_resource(name, module, block) end # Generate match to forward /:vs/:name to Module defp root_forward(name, target) do quote do def do_relax_route(conn, [@version, unquote(name) | glob]) do conn = Map.put(conn, :path_info, glob) apply(unquote(target), :call, [conn, []]) end end end # Generate match to forward /:vs/:parent_name/:parent_id/:name to Module defp nested_forward(name, target) do quote do def do_relax_route(conn, [@version, @nested_in, parent_id, unquote(name) | glob]) do conn = conn |> Plug.Conn.put_private(:relax_parent_name, @nested_in) |> Plug.Conn.put_private(:relax_parent_id, parent_id) |> Map.put(:path_info, glob) apply(unquote(target), :call, [conn, []]) end end end # Determine how to forward resource, as nested or top level. defp forward_resource(name, target) do name = Atom.to_string(name) quote do case @nested_in do nil -> unquote(root_forward(name, target)) nested_name -> unquote(nested_forward(name, target)) end end end # Forward resources and set nested context defp forward_resource(name, module, block) do quote do @nested_in Atom.to_string(unquote(name)) unquote(block) @nested_in nil unquote(forward_resource(name, module)) end end end
lib/relax/router.ex
0.83498
0.404125
router.ex
starcoder
defmodule VoteNerd.Poll do defstruct [:title, options: [], votes: nil] @doc """ Adds option `o` to the `poll`. Note that the options are stored in the inverse order that they were added. ## Examples iex> %VoteNerd.Poll{} |> VoteNerd.Poll.add_option("foobar") %VoteNerd.Poll{options: ["foobar"]} iex> %VoteNerd.Poll{} ...> |> VoteNerd.Poll.add_option("a") ...> |> VoteNerd.Poll.add_option("b") %VoteNerd.Poll{options: ["b", "a"]} """ def add_option(poll, o) do poll |> Map.update!(:options, &([o | &1])) end @doc """ Starts the `poll` allowing people to vote ## Examples iex> %VoteNerd.Poll{options: ["b", "a"]} ...> |> VoteNerd.Poll.start %VoteNerd.Poll{ options: ["b", "a"], votes: %{0 => MapSet.new, 1 => MapSet.new} } """ def start(%{options: os} = poll) do votes = for i <- 0..(length(os) - 1), into: %{}, do: {i, MapSet.new} Map.put(poll, :votes, votes) end @doc """ Votes as `voter` for the option with the given `index`. Note that this acs as a toggle. Voting for something that you've already voted for removes your vote. ## Examples iex> %VoteNerd.Poll{votes: %{0 => MapSet.new}} ...> |> VoteNerd.Poll.vote("bob", 0) %VoteNerd.Poll{votes: %{0 => MapSet.new(["bob"])}} iex> %VoteNerd.Poll{votes: %{0 => MapSet.new}} ...> |> VoteNerd.Poll.vote("bob", 0) ...> |> VoteNerd.Poll.vote("bob", 0) %VoteNerd.Poll{votes: %{0 => MapSet.new()}} iex> %VoteNerd.Poll{votes: %{0 => MapSet.new, 1 => MapSet.new}} ...> |> VoteNerd.Poll.vote("bob", 0) ...> |> VoteNerd.Poll.vote("bob", 1) %VoteNerd.Poll{votes: %{0 => MapSet.new(["bob"]), 1 => MapSet.new(["bob"])}} iex> %VoteNerd.Poll{votes: %{0 => MapSet.new, 1 => MapSet.new}} ...> |> VoteNerd.Poll.vote("bob", 0) ...> |> VoteNerd.Poll.vote("bob", 1) ...> |> VoteNerd.Poll.vote("bob", 1) %VoteNerd.Poll{votes: %{0 => MapSet.new(["bob"]), 1 => MapSet.new}} """ def vote(%{votes: vs} = poll, voter, index) do vs = Map.update!(vs, index, fn v -> if MapSet.member?(v, voter) do MapSet.delete(v, voter) else MapSet.put(v, voter) end end) Map.put(poll, :votes, vs) end @doc """ Tallies up the votes in `poll` and orders them so that the better options come out first. ## Examples iex> %VoteNerd.Poll{} ...> |> VoteNerd.Poll.results [] iex> %VoteNerd.Poll{options: ["foo"], votes: %{0 => MapSet.new}} ...> |> VoteNerd.Poll.results [{"foo", 0}] iex> %VoteNerd.Poll{options: ["foo", "bar", "baz"], votes: %{ ...> 0 => MapSet.new(["bob", "mary", "jane"]), ...> 1 => MapSet.new(["jane"]), ...> 2 => MapSet.new(["mary", "jane"]) ...> }} ...> |> VoteNerd.Poll.results [{"foo", 3}, {"baz", 2}, {"bar", 1}] """ def results(%{options: options, votes: votes}) do options |> Enum.with_index |> Enum.map(fn {o, i} -> size = votes |> Map.get(i) |> MapSet.size {o, size} end) |> Enum.sort_by(fn {_, s} -> -s end) end end
lib/vote_nerd/poll.ex
0.810404
0.453988
poll.ex
starcoder
defmodule Adventofcode.Day17TwoStepsForward.Utils do def open_doors(hashed_passcode) do hashed_passcode |> String.graphemes |> Enum.zip("UDLR" |> String.graphemes) |> Enum.filter(&open?/1) |> Enum.map(&elem(&1, 1)) end defp open?({"b", _}), do: true defp open?({"c", _}), do: true defp open?({"d", _}), do: true defp open?({"e", _}), do: true defp open?({"f", _}), do: true defp open?(_), do: false def hash(string), do: string |> md5 |> String.slice(0, 4) def md5(string), do: string |> :erlang.md5 |> Base.encode16(case: :lower) end defmodule Adventofcode.Day17TwoStepsForward.Traveler do import Adventofcode.Day17TwoStepsForward.Utils defstruct [passcode: nil, x: 0, y: 0] def travel(%__MODULE__{x: 3, y: 3} = traveler) do [traveler] end def travel(%__MODULE__{passcode: passcode} = traveler) do traveler |> fork |> Enum.flat_map(&travel/1) end def fork(%__MODULE__{passcode: passcode} = traveler) do passcode |> hash |> open_doors |> Enum.map(&neighbour(&1, traveler)) |> Enum.filter(&possible_position?/1) end defp neighbour("U", t), do: %{t | y: t.y - 1, passcode: t.passcode <> "U"} defp neighbour("D", t), do: %{t | y: t.y + 1, passcode: t.passcode <> "D"} defp neighbour("L", t), do: %{t | x: t.x - 1, passcode: t.passcode <> "L"} defp neighbour("R", t), do: %{t | x: t.x + 1, passcode: t.passcode <> "R"} def possible_position?(%{y: y}) when y < 0, do: false def possible_position?(%{y: y}) when y > 3, do: false def possible_position?(%{x: x}) when x < 0, do: false def possible_position?(%{x: x}) when x > 3, do: false def possible_position?(_), do: true end defmodule Adventofcode.Day17TwoStepsForward do alias Adventofcode.Day17TwoStepsForward.Traveler def shortest_path(passcode) do %Traveler{passcode: passcode} |> Traveler.travel |> Enum.map(&(&1.passcode)) |> Enum.sort_by(&(&1 |> String.length)) |> Enum.map(&String.trim(&1, passcode)) |> Enum.find(&(&1)) end def longest_path(passcode) do %Traveler{passcode: passcode} |> Traveler.travel |> Enum.map(&(&1.passcode)) |> Enum.sort_by(&(&1 |> String.length), &>=/2) |> Enum.map(&String.trim(&1, passcode)) |> Enum.map(&String.length/1) |> Enum.find(&(&1)) end end
lib/day_17_two_steps_forward.ex
0.694924
0.428144
day_17_two_steps_forward.ex
starcoder
defmodule Result.Calc do @moduledoc """ Result calculations """ @doc """ Calculate the AND of two results r_and :: Result e1 a -> Result e2 b -> Result [e1, e2] [a, b] ## Examples iex> Result.Calc.r_and({:ok, 1}, {:ok, 2}) {:ok, [1, 2]} iex> Result.Calc.r_and({:ok, 1}, {:error, 2}) {:error, [2]} iex> Result.Calc.r_and({:error, 1}, {:ok, 2}) {:error, [1]} iex> Result.Calc.r_and({:error, 1}, {:error, 2}) {:error, [1, 2]} """ @spec r_and(Result.t(any, any), Result.t(any, any)) :: Result.t([...], [...]) def r_and({:ok, val1}, {:ok, val2}) do {:ok, [val1, val2]} end def r_and({:ok, _}, {:error, val2}) do {:error, [val2]} end def r_and({:error, val1}, {:ok, _}) do {:error, [val1]} end def r_and({:error, val1}, {:error, val2}) do {:error, [val1, val2]} end @doc """ Calculate the OR of two results r_or :: Result e1 a -> Result e2 b -> Result [e1, e2] [a, b] ## Examples iex> Result.Calc.r_or({:ok, 1}, {:ok, 2}) {:ok, [1, 2]} iex> Result.Calc.r_or({:ok, 1}, {:error, 2}) {:ok, [1]} iex> Result.Calc.r_or({:error, 1}, {:ok, 2}) {:ok, [2]} iex> Result.Calc.r_or({:error, 1}, {:error, 2}) {:error, [1, 2]} """ @spec r_or(Result.t(any, any), Result.t(any, any)) :: Result.t([...], [...]) def r_or({:ok, val1}, {:ok, val2}) do {:ok, [val1, val2]} end def r_or({:ok, val1}, {:error, _}) do {:ok, [val1]} end def r_or({:error, _}, {:ok, val2}) do {:ok, [val2]} end def r_or({:error, val1}, {:error, val2}) do {:error, [val1, val2]} end @doc """ Calculate product of Results product :: List (Result e a) -> Result (List e) (List a) ## Examples iex> data = [{:ok, 1}, {:ok, 2}, {:ok, 3}] iex> Result.Calc.product(data) {:ok, [1, 2, 3]} iex> data = [{:error, 1}, {:ok, 2}, {:error, 3}] iex> Result.Calc.product(data) {:error, [1, 3]} iex> data = [{:error, 1}] iex> Result.Calc.product(data) {:error, [1]} iex> data = [] iex> Result.Calc.product(data) {:ok, []} """ @spec product([Result.t(any, any)]) :: Result.t([...], [...]) def product(list) do product(list, {:ok, []}) end defp product([head | tail], acc) do result = acc |> r_and(head) |> flatten() product(tail, result) end defp product([], acc) do acc end @doc """ Calculate sum of Results sum :: List (Result e a) -> Result (List e) (List a) ## Examples iex> data = [{:ok, 1}, {:ok, 2}, {:ok, 3}] iex> Result.Calc.sum(data) {:ok, [1, 2, 3]} iex> data = [{:error, 1}, {:ok, 2}, {:error, 3}] iex> Result.Calc.sum(data) {:ok, [2]} iex> data = [{:error, 1}, {:error, 2}, {:error, 3}] iex> Result.Calc.sum(data) {:error, [1, 2, 3]} iex> data = [{:error, 1}] iex> Result.Calc.sum(data) {:error, [1]} iex> data = [] iex> Result.Calc.sum(data) {:error, []} """ @spec sum([Result.t(any, any)]) :: Result.t([...], [...]) def sum(list) do sum(list, {:error, []}) end defp sum([head | tail], acc) do result = acc |> r_or(head) |> flatten sum(tail, result) end defp sum([], acc) do acc end defp flatten({state, [head | tail]}) when is_list(head) do {state, head ++ tail} end defp flatten({state, list}) do {state, list} end end
lib/operators/calc.ex
0.87266
0.725284
calc.ex
starcoder
defmodule FlowAssertions.Checkers do alias FlowAssertions.Define.Defchecker.Failure import FlowAssertions.Define.{Defchecker,BodyParts} alias FlowAssertions.Messages @moduledoc """ Functions that create handy predicates for use with `FlowAssertions.MiscA.assert_good_enough/2` actual |> assert_good_enough( in_any_order([1, 2, 3])) "Checkers" typically provide custom failure messages that are better than what a simple predicate would provide. This module is a work in progress, but what now works will continue to work and can be used safely. For examples of what checkers might come, see the [Midje documentation](https://github.com/marick/Midje/wiki). (Links are under the third bullet point of "The Core" on that page.) """ @doc """ Check equality of Enumerables, ignoring order. actual |> assert_good_enough( in_any_order([1, 2, 3])) In case of error, the actual and expected enumerables are sorted by by their `Kernel.inspect/1` representation. In combination with ExUnit's color-coded differences, that makes it easier to see what went wrong. """ def in_any_order(expected) do fn actual -> assert = fn value, message -> if !value do Failure.boa(actual, :in_any_order, expected) |> fail_helpfully(message, alphabetical_enums(actual, expected)) end end assert_enumerable = fn value, identifier -> elaborate_assert(Enumerable.impl_for(value), Messages.not_enumerable(identifier), [left: actual, right: expected]) end id = fn x -> x end unordered = &(Enum.group_by(&1, id)) assert_enumerable.(actual, "left") assert_enumerable.(expected, "right") assert.(length(actual) == length(expected), Messages.different_length_collections) assert.(unordered.(actual) == unordered.(expected), Messages.different_elements_collections) true end end defp alphabetical_enums(actual, expected), do: [left: alphabetical(actual), right: alphabetical(expected)] defp alphabetical(xs), do: Enum.sort_by(xs, &inspect/1) @doc """ Checks whether a String or List contains another. [1, 2, 3] |> assert_good_enough( has_slice([2, 3])) "abcdefg" |> assert_good_enough( has_slice("abc")) """ def has_slice(expected) when is_binary(expected) do fn actual when is_binary(actual) -> if String.contains?(actual, expected), do: true, else: Failure.boa(actual, :has_slice, expected) end end def has_slice(expected) when is_list(expected) do fn actual when is_list(actual) -> if has_prefix?(actual, expected), do: true, else: Failure.boa(actual, :has_slice, expected) end end defp has_prefix?([], []), do: true defp has_prefix?([], _), do: false defp has_prefix?([_ | rest] = larger, prefix) when is_list(prefix) do comparison_length = length(prefix) cond do length(larger) < comparison_length -> false Enum.take(larger, comparison_length) == prefix -> true true -> has_prefix?(rest, prefix) end end end
lib/checkers.ex
0.877674
0.767646
checkers.ex
starcoder
defmodule AWS.MarketplaceMetering do @moduledoc """ AWS Marketplace Metering Service This reference provides descriptions of the low-level AWS Marketplace Metering Service API. AWS Marketplace sellers can use this API to submit usage data for custom usage dimensions. For information on the permissions you need to use this API, see [AWS Marketing metering and entitlement API permissions](https://docs.aws.amazon.com/marketplace/latest/userguide/iam-user-policy-for-aws-marketplace-actions.html) in the *AWS Marketplace Seller Guide.* ## Submitting Metering Records * *MeterUsage*- Submits the metering record for a Marketplace product. MeterUsage is called from an EC2 instance or a container running on EKS or ECS. * *BatchMeterUsage*- Submits the metering record for a set of customers. BatchMeterUsage is called from a software-as-a-service (SaaS) application. ## Accepting New Customers * *ResolveCustomer*- Called by a SaaS application during the registration process. When a buyer visits your website during the registration process, the buyer submits a Registration Token through the browser. The Registration Token is resolved through this API to obtain a CustomerIdentifier and Product Code. ## Entitlement and Metering for Paid Container Products * Paid container software products sold through AWS Marketplace must integrate with the AWS Marketplace Metering Service and call the RegisterUsage operation for software entitlement and metering. Free and BYOL products for Amazon ECS or Amazon EKS aren't required to call RegisterUsage, but you can do so if you want to receive usage data in your seller reports. For more information on using the RegisterUsage operation, see [Container-Based Products](https://docs.aws.amazon.com/marketplace/latest/userguide/container-based-products.html). BatchMeterUsage API calls are captured by AWS CloudTrail. You can use Cloudtrail to verify that the SaaS metering records that you sent are accurate by searching for records with the eventName of BatchMeterUsage. You can also use CloudTrail to audit records over time. For more information, see the * [AWS CloudTrail User Guide](http://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-concepts.html) *. """ alias AWS.Client alias AWS.Request def metadata do %AWS.ServiceMetadata{ abbreviation: nil, api_version: "2016-01-14", content_type: "application/x-amz-json-1.1", credential_scope: nil, endpoint_prefix: "metering.marketplace", global?: false, protocol: "json", service_id: "Marketplace Metering", signature_version: "v4", signing_name: "aws-marketplace", target_prefix: "AWSMPMeteringService" } end @doc """ BatchMeterUsage is called from a SaaS application listed on the AWS Marketplace to post metering records for a set of customers. For identical requests, the API is idempotent; requests can be retried with the same records or a subset of the input records. Every request to BatchMeterUsage is for one product. If you need to meter usage for multiple products, you must make multiple calls to BatchMeterUsage. BatchMeterUsage can process up to 25 UsageRecords at a time. A UsageRecord can optionally include multiple usage allocations, to provide customers with usagedata split into buckets by tags that you define (or allow the customer to define). BatchMeterUsage requests must be less than 1MB in size. """ def batch_meter_usage(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "BatchMeterUsage", input, options) end @doc """ API to emit metering records. For identical requests, the API is idempotent. It simply returns the metering record ID. MeterUsage is authenticated on the buyer's AWS account using credentials from the EC2 instance, ECS task, or EKS pod. MeterUsage can optionally include multiple usage allocations, to provide customers with usage data split into buckets by tags that you define (or allow the customer to define). """ def meter_usage(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "MeterUsage", input, options) end @doc """ Paid container software products sold through AWS Marketplace must integrate with the AWS Marketplace Metering Service and call the RegisterUsage operation for software entitlement and metering. Free and BYOL products for Amazon ECS or Amazon EKS aren't required to call RegisterUsage, but you may choose to do so if you would like to receive usage data in your seller reports. The sections below explain the behavior of RegisterUsage. RegisterUsage performs two primary functions: metering and entitlement. * *Entitlement*: RegisterUsage allows you to verify that the customer running your paid software is subscribed to your product on AWS Marketplace, enabling you to guard against unauthorized use. Your container image that integrates with RegisterUsage is only required to guard against unauthorized use at container startup, as such a CustomerNotSubscribedException/PlatformNotSupportedException will only be thrown on the initial call to RegisterUsage. Subsequent calls from the same Amazon ECS task instance (e.g. task-id) or Amazon EKS pod will not throw a CustomerNotSubscribedException, even if the customer unsubscribes while the Amazon ECS task or Amazon EKS pod is still running. * *Metering*: RegisterUsage meters software use per ECS task, per hour, or per pod for Amazon EKS with usage prorated to the second. A minimum of 1 minute of usage applies to tasks that are short lived. For example, if a customer has a 10 node Amazon ECS or Amazon EKS cluster and a service configured as a Daemon Set, then Amazon ECS or Amazon EKS will launch a task on all 10 cluster nodes and the customer will be charged: (10 * hourly_rate). Metering for software use is automatically handled by the AWS Marketplace Metering Control Plane -- your software is not required to perform any metering specific actions, other than call RegisterUsage once for metering of software use to commence. The AWS Marketplace Metering Control Plane will also continue to bill customers for running ECS tasks and Amazon EKS pods, regardless of the customers subscription state, removing the need for your software to perform entitlement checks at runtime. """ def register_usage(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "RegisterUsage", input, options) end @doc """ ResolveCustomer is called by a SaaS application during the registration process. When a buyer visits your website during the registration process, the buyer submits a registration token through their browser. The registration token is resolved through this API to obtain a CustomerIdentifier and product code. """ def resolve_customer(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ResolveCustomer", input, options) end end
lib/aws/generated/marketplace_metering.ex
0.800887
0.508422
marketplace_metering.ex
starcoder
defmodule ExUnit.Case do @moduledoc """ This module is meant to be used in other modules as a way to configure and prepare them for testing. When used, it allows the following options: * :async - configure Elixir to run that specific test case in parallel with others. Must be used for performance when your test cases do not change any global state; This module automatically includes all callbacks defined in `ExUnit.Callbacks`. See that module's documentation for more information. ## Examples defmodule AssertionTest do # Use the module use ExUnit.Case, async: true # The `test` macro is imported by ExUnit.Case test "always pass" do assert true end end """ @doc false defmacro __using__(opts // []) do async = Keyword.get(opts, :async, false) unless Process.whereis(ExUnit.Server) do raise "cannot use ExUnit.Case without starting ExUnit application, " <> "please call ExUnit.start() or explicitly start the :ex_unit app" end quote do unless Module.get_attribute(__MODULE__, :ex_unit_case) do if unquote(async) do ExUnit.Server.add_async_case(__MODULE__) else ExUnit.Server.add_sync_case(__MODULE__) end use ExUnit.Callbacks end @ex_unit_case true import ExUnit.Callbacks import ExUnit.Assertions import ExUnit.Case import ExUnit.DocTest end end @doc """ Provides a convenient macro that allows a test to be defined with a string. This macro automatically inserts the atom :ok as the last line of the test. That said, a passing test always returns :ok, but, more important, it forces Elixir to not tail call optimize the test and therefore avoiding hiding lines from the backtrace. ## Examples test "true is equal to true" do assert true == true end """ defmacro test(message, var // quote(do: _), contents) do contents = case contents do [do: _] -> quote do unquote(contents) :ok end _ -> quote do try(unquote(contents)) :ok end end var = Macro.escape(var) contents = Macro.escape(contents, unquote: true) quote bind_quoted: binding do message = if is_binary(message) do :"test #{message}" else :"test_#{message}" end def unquote(message)(unquote(var)), do: unquote(contents) end end end
lib/ex_unit/lib/ex_unit/case.ex
0.742422
0.459197
case.ex
starcoder
defmodule AstraeaVirgoWeb.ProblemView do use AstraeaVirgoWeb, :view @moduledoc """ Response for Problem API """ @doc """ Response ## index.json Response for index Problems API: `GET /api/problems` Response: list of Object | field | type | required | descript | |----------|---------|----------|---------------------------| | id | ID | yes | | | name | string | yes | | | category | string | yes | category of problem | | ordinal | Ordinal | yes | problem ordinal | | testcase | integer | yes | number of testcase | | lock | boolean | yes | if true that can't submit | | public | boolean | yes | | | total | integer | yes | number of submissions | | ac | integer | yes | number of ac submissions | ## show.json Response for show Problem API: - `GET /api/problems/<problem_id>` - `PUT /api/problems/<problem_id>` Response: Object | field | type | required | descript | |----------|---------|----------|---------------------------| | id | ID | yes | | | name | string | yes | | | category | string | yes | category of problem | | ordinal | Ordinal | yes | problem ordinal | | testcase | integer | yes | number of testcase | | lock | boolean | yes | if true that can't submit | | public | boolean | yes | | | total | integer | yes | number of submissions | | ac | integer | yes | number of ac submissions | ## detail.json Response for Problem Detail API: - `GET /api/problems/<problem_id>/detail` - `GET /api/contests/<contest_id>/problems/<problem_id>/detail` Response: Object | field | type | required | descript | |--------------|---------|----------|---------------------------| | id | ID | yes | | | public | boolean | yes | | | detail | Base64 | yes | detail of problem | | mime | string | yes | mime type of detail | | time_limit | integer | yes | time limit (ms) | | memory_limit | integer | yes | memory limit (kiB) | ## create.json Response for create Language API: `POST /api/problems` Response: Object | field | type | required | null | descript | |-------------|------|----------|------|---------------| | problem_id | ID | yes | no | 问题的 ID | """ def render("index.json", assigns), do: assigns.data def render("show.json", assigns), do: assigns.data def render("detail.json", assigns), do: assigns.data def render("create.json", assigns) do %{ problem_id: assigns.problem_id } end end
lib/virgo_web/views/problem_view.ex
0.875794
0.425844
problem_view.ex
starcoder
defmodule Scidata.Caltech101 do @moduledoc """ Module for downloading the [Caltech101 dataset](http://www.vision.caltech.edu/Image_Datasets/Caltech101). """ require Scidata.Utils alias Scidata.Utils @base_url "https://s3.amazonaws.com/fast-ai-imageclas/" @dataset_file "caltech_101.tgz" @labels_shape {9144, 1} @label_mapping %{ accordion: 0, airplanes: 1, anchor: 2, ant: 3, background_google: 4, barrel: 5, bass: 6, beaver: 7, binocular: 8, bonsai: 9, brain: 10, brontosaurus: 11, buddha: 12, butterfly: 13, camera: 14, cannon: 15, car_side: 16, ceiling_fan: 17, cellphone: 18, chair: 19, chandelier: 20, cougar_body: 21, cougar_face: 22, crab: 23, crayfish: 24, crocodile: 25, crocodile_head: 26, cup: 27, dalmatian: 28, dollar_bill: 29, dolphin: 30, dragonfly: 31, electric_guitar: 32, elephant: 33, emu: 34, euphonium: 35, ewer: 36, faces: 37, faces_easy: 38, ferry: 39, flamingo: 40, flamingo_head: 41, garfield: 42, gerenuk: 43, gramophone: 44, grand_piano: 45, hawksbill: 46, headphone: 47, hedgehog: 48, helicopter: 49, ibis: 50, inline_skate: 51, joshua_tree: 52, kangaroo: 53, ketch: 54, lamp: 55, laptop: 56, leopards: 57, llama: 58, lobster: 59, lotus: 60, mandolin: 61, mayfly: 62, menorah: 63, metronome: 64, minaret: 65, motorbikes: 66, nautilus: 67, octopus: 68, okapi: 69, pagoda: 70, panda: 71, pigeon: 72, pizza: 73, platypus: 74, pyramid: 75, revolver: 76, rhino: 77, rooster: 78, saxophone: 79, schooner: 80, scissors: 81, scorpion: 82, sea_horse: 83, snoopy: 84, soccer_ball: 85, stapler: 86, starfish: 87, stegosaurus: 88, stop_sign: 89, strawberry: 90, sunflower: 91, tick: 92, trilobite: 93, umbrella: 94, watch: 95, water_lilly: 96, wheelchair: 97, wild_cat: 98, windsor_chair: 99, wrench: 100, yin_yang: 101 } @doc """ Downloads the Caltech101 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(1..102))) ## Options. * `:base_url` - Dataset base URL. Defaults to `"https://s3.amazonaws.com/fast-ai-imageclas/"` * `:dataset_file` - Dataset filename. Defaults to `"caltech_101.tgz"` * `:cache_dir` - Cache directory. Defaults to `System.tmp_dir!()` """ def download(opts \\ []) do unless Code.ensure_loaded?(StbImage) do raise "StbImage is missing, please add `{:stb_image, \"~> 0.4\"}` as a dependency to your mix.exs" end download_dataset(:train, opts) end defp download_dataset(_dataset_type, opts) do base_url = opts[:base_url] || @base_url dataset_file = opts[:dataset_file] || @dataset_file # Skip first file since it's a temporary file. [_ | files] = Utils.get!(base_url <> dataset_file, opts).body {images, shapes, labels} = files |> Enum.reverse() |> Task.async_stream(&generate_records/1, max_concurrency: Keyword.get(opts, :max_concurrency, System.schedulers_online()) ) |> Enum.reduce( {[], [], []}, fn {:ok, record}, {image_acc, shape_acc, label_acc} -> {%{data: image_bin, shape: shape}, label} = record {[image_bin | image_acc], [shape | shape_acc], [label | label_acc]} end ) {{images, {:u, 8}, shapes}, {IO.iodata_to_binary(labels), {:u, 8}, @labels_shape}} end @compile {:no_warn_undefined, StbImage} defp generate_records({fname, image}) do class_name = fname |> List.to_string() |> String.downcase() |> String.split("/") |> Enum.at(1) |> String.to_atom() label = Map.fetch!(@label_mapping, class_name) {:ok, stb_image} = StbImage.from_binary(image) {stb_image, label} end end
lib/scidata/caltech101.ex
0.824179
0.558387
caltech101.ex
starcoder
defmodule Protobuf.Wire.Varint do @moduledoc """ Varint encoding and decoding utilities. https://developers.google.com/protocol-buffers/docs/encoding#varints For performance reasons, varint decoding must be built through a macro, so that binary match contexts are reused and no new large binaries get allocated. You can define your own varint decoders with the `decoder` macro, which generates function heads for up to 10-bytes long varint-encoded data. defmodule VarintDecoders do import Protobuf.Wire.Varint decoder :def, :decode_and_sum, [:plus] do {:ok, value + plus, rest} end def decode_all(<<bin::bits>>), do: decode_all(bin, []) defp decode_all(<<>>, acc), do: acc defdecoderp decode_all(acc) do decode_all(rest, [value | acc]) end end iex> VarintDecoders.decode_and_sum(<<35>>, 7) {:ok, 42, ""} iex> VarintDecoders.decode_all("abcd asdf") [102, 100, 115, 97, 32, 100, 99, 98, 97] Refer to [efficiency guide](http://www1.erlang.org/doc/efficiency_guide/binaryhandling.html) for more on efficient binary handling. Encoding on the other hand is simpler. It takes an integer and returns an iolist with its varint representation: iex> Protobuf.Wire.Varint.encode(35) [35] iex> Protobuf.Wire.Varint.encode(1_234_567) [<<135>>, <<173>>, 75] """ use Bitwise @max_bits 64 @mask64 bsl(1, @max_bits) - 1 # generated: true is required here to silence compilation warnings in Elixir # 1.10 and 1.11. OK to remove once we support only 1.12+ @varints [ { quote(do: <<0::1, value::7>>), quote(do: value) }, { quote(do: <<fdf8:f53e:61e4::18, x0::7, 0::1, x1::7>>), quote(generated: true, do: x0 + bsl(x1, 7)) }, { quote(do: <<fdf8:f53e:61e4::18, x0::7, fdf8:f53e:61e4::18, x1::7, 0::1, x2::7>>), quote(generated: true, do: x0 + bsl(x1, 7) + bsl(x2, 14)) }, { quote(do: <<fdf8:f53e:61e4::18, x0::7, fdf8:f53e:61e4::18, x1::7, fdf8:f53e:61e4::18, x2::7, 0::1, x3::7>>), quote(generated: true, do: x0 + bsl(x1, 7) + bsl(x2, 14) + bsl(x3, 21)) }, { quote(do: <<fdf8:f53e:61e4::18, x0::7, fdf8:f53e:61e4::18, x1::7, fdf8:f53e:61e4::18, x2::7, fdf8:f53e:61e4::18, x3::7, 0::1, x4::7>>), quote(generated: true, do: x0 + bsl(x1, 7) + bsl(x2, 14) + bsl(x3, 21) + bsl(x4, 28)) }, { quote do <<fdf8:f53e:61e4::18, x0::7, fdf8:f53e:61e4::18, x1::7, fdf8:f53e:61e4::18, x2::7, fdf8:f53e:61e4::18, x3::7, fdf8:f53e:61e4::18, x4::7, 0::1, x5::7>> end, quote(generated: true) do x0 + bsl(x1, 7) + bsl(x2, 14) + bsl(x3, 21) + bsl(x4, 28) + bsl(x5, 35) end }, { quote do <<fdf8:f53e:61e4::18, x0::7, fdf8:f53e:61e4::18, x1::7, fdf8:f53e:61e4::18, x2::7, fdf8:f53e:61e4::18, x3::7, fdf8:f53e:61e4::18, x4::7, fdf8:f53e:61e4::18, x5::7, 0::1, x6::7>> end, quote(generated: true) do x0 + bsl(x1, 7) + bsl(x2, 14) + bsl(x3, 21) + bsl(x4, 28) + bsl(x5, 35) + bsl(x6, 42) end }, { quote do <<fdf8:f53e:61e4::18, x0::7, fdf8:f53e:61e4::18, x1::7, fdf8:f53e:61e4::18, x2::7, fdf8:f53e:61e4::18, x3::7, fdf8:f53e:61e4::18, x4::7, fdf8:f53e:61e4::18, x5::7, fdf8:f53e:61e4::18, x6::7, 0::1, x7::7>> end, quote(generated: true) do x0 + bsl(x1, 7) + bsl(x2, 14) + bsl(x3, 21) + bsl(x4, 28) + bsl(x5, 35) + bsl(x6, 42) + bsl(x7, 49) end }, { quote do <<fdf8:f53e:61e4::18, x0::7, fdf8:f53e:61e4::18, x1::7, fdf8:f53e:61e4::18, x2::7, fdf8:f53e:61e4::18, x3::7, fdf8:f53e:61e4::18, x4::7, fdf8:f53e:61e4::18, x5::7, fdf8:f53e:61e4::18, x6::7, fdf8:f53e:61e4::18, x7::7, 0::1, x8::7>> end, quote(generated: true) do x0 + bsl(x1, 7) + bsl(x2, 14) + bsl(x3, 21) + bsl(x4, 28) + bsl(x5, 35) + bsl(x6, 42) + bsl(x7, 49) + bsl(x8, 56) end }, { quote do <<fdf8:f53e:61e4::18, x0::7, fdf8:f53e:61e4::18, xfd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b, fdf8:f53e:61e4::18, x2::7, fdf8:f53e:61e4::18, x3::7, fdf8:f53e:61e4::18, x4::7, fdf8:f53e:61e4::18, x5::7, fdf8:f53e:61e4::18, x6::7, fdf8:f53e:61e4::18, x7::7, fdf8:f53e:61e4::18, x8::7, 0::1, x9::7>> end, quote(generated: true) do band( x0 + bsl(x1, 7) + bsl(x2, 14) + bsl(x3, 21) + bsl(x4, 28) + bsl(x5, 35) + bsl(x6, 42) + bsl(x7, 49) + bsl(x8, 56) + bsl(x9, 63), unquote(@mask64) ) end } ] defmacro defdecoderp(name_and_args, do: body) do {name, args} = Macro.decompose_call(name_and_args) def_decoder_success_clauses(name, args, body) ++ [def_decoder_failure_clause(name, args)] end defp def_decoder_success_clauses(name, args, body) do for {pattern, expression} <- @varints do quote do defp unquote(name)(<<unquote(pattern), rest::bits>>, unquote_splicing(args)) do var!(value) = unquote(expression) var!(rest) = rest unquote(body) end end end end defp def_decoder_failure_clause(name, args) do args = Enum.map(args, fn {:_, _meta, _ctxt} = underscore -> underscore {name, meta, ctxt} when is_atom(name) and is_atom(ctxt) -> {:"_#{name}", meta, ctxt} other -> other end) quote do defp unquote(name)(<<_::bits>>, unquote_splicing(args)) do raise Protobuf.DecodeError, message: "cannot decode binary data" end end end @spec encode(integer) :: iolist def encode(n) when n < 0 do <<n::64-unsigned-native>> = <<n::64-signed-native>> encode(n) end def encode(n) when n <= 127 do [n] end def encode(n) do [<<1::1, band(n, 127)::7>> | encode(bsr(n, 7))] end end
lib/protobuf/wire/varint.ex
0.605216
0.400105
varint.ex
starcoder
defmodule Aja.Vector.Raw do @moduledoc false import Kernel, except: [min: 2, max: 2] require Aja.Vector.CodeGen, as: C alias Aja.Vector.{Builder, Node, Tail, Trie} @empty {0} defmacrop small(size, tail, first) do # TODO distinguish match quote do {unquote(size), 0, nil, nil, unquote(tail), unquote(first)} end end defmacrop large(size, tail_offset, shift, trie, tail, first) do quote do {unquote(size), unquote(tail_offset), unquote(shift), unquote(trie), unquote(tail), unquote(first)} end end defmacro first_pattern(first) do quote do {_, _, _, _, _, unquote(first)} end end defmacro last_pattern(last) do tail_ast = [last] |> C.left_fill_with(C.var(_)) |> C.array() quote do {_, _, _, _, unquote(tail_ast), _} end end defmacrop empty_pattern() do quote do: {_} end defmacrop tuple_ast(list) when is_list(list) do quote do {:{}, [], unquote(list)} end end @spec empty :: t() def empty, do: @empty @type value :: term @type size :: non_neg_integer @type tail_offset :: non_neg_integer @type shift :: non_neg_integer @type t(value) :: {0} | {size, tail_offset, shift | nil, Trie.t(value) | nil, Tail.t(value), value} @type t() :: t(value) defmacro size(vector) do quote do :erlang.element(1, unquote(vector)) end end defmacro actual_index(raw_index, size) do # implemented using a macro because benches showed a significant improvement quote do size = unquote(size) case unquote(raw_index) do index when index >= size -> nil index when index >= 0 -> index index -> case size + index do negative when negative < 0 -> nil positive -> positive end end end end @spec from_list([val]) :: t(val) when val: value def from_list([]), do: @empty def from_list(list = [first | _]) do list |> Builder.from_list() |> from_builder(first) end defp from_builder({[], size, tail}, first) do small(size, tail, first) end defp from_builder({tries, tail_size, tail}, first) do {level, trie} = Builder.to_trie(tries, 0) tail_offset = Builder.tail_offset(tries, C.bits(), 0) large(tail_offset + tail_size, tail_offset, level, trie, tail, first) end @spec from_mapped_list([v1], (v1 -> v2)) :: t(v2) when v1: value, v2: value def from_mapped_list([], _fun), do: @empty def from_mapped_list(list, fun) when is_list(list) do list |> Builder.map_from_list(fun) |> from_builder() end defp from_builder({[], size, tail}) do first = :erlang.element(unquote(1 + C.branch_factor()) - size, tail) small(size, tail, first) end defp from_builder({tries, tail_size, tail}) do {level, trie} = Builder.to_trie(tries, 0) tail_offset = Builder.tail_offset(tries, C.bits(), 0) first = Trie.first(trie, level) large(tail_offset + tail_size, tail_offset, level, trie, tail, first) end def from_list_ast([]), do: unquote(Macro.escape(@empty) |> Macro.escape()) def from_list_ast(list = [first | _]) do {size, tail_offset, leaves, tail} = Trie.group_leaves_ast(list) case Trie.from_ast_leaves(leaves) do nil -> tuple_ast([size, 0, nil, nil, tail, first]) {shift, trie} -> tuple_ast([size, tail_offset, shift, trie, tail, first]) end end def from_first_last_ast(first, last) do tail = [last] |> C.left_fill_with(C.var(_)) |> C.array() tuple_ast([C.var(_), C.var(_), C.var(_), C.var(_), tail, first]) end @spec append(t(val), val) :: t(val) when val: value def append(vector, value) def append(small(size, tail, first), value) do if size == C.branch_factor() do large( size + 1, size, 0, tail, unquote([C.var(value)] |> C.left_fill_with(nil) |> C.array()), first ) else new_tail = Tail.append(tail, value) small(size + 1, new_tail, first) end end def append(large(size, tail_offset, level, trie, tail, first), value) do case C.radix_rem(size) do 0 -> {new_trie, new_level} = Trie.append_leaf(trie, level, tail_offset, tail) new_tail = unquote([C.var(value)] |> C.left_fill_with(nil) |> C.array()) large(size + 1, tail_offset + C.branch_factor(), new_level, new_trie, new_tail, first) _ -> new_tail = Tail.append(tail, value) large(size + 1, tail_offset, level, trie, new_tail, first) end end def append(empty_pattern(), value) do tail = unquote(C.value_with_nils(C.var(value)) |> Enum.reverse() |> C.array()) small(1, tail, value) end def concat_list(vector, []), do: vector def concat_list(vector, [value]), do: append(vector, value) def concat_list(small(size, tail, first), list) do case Tail.complete_tail(tail, size, list) do {new_tail, added, []} -> small(size + added, new_tail, first) {first_leaf, _added, list} -> [[first_leaf]] |> Builder.concat_list(list) |> from_builder(first) end end def concat_list(large(size, tail_offset, level, trie, tail, first), list) do case Tail.complete_tail(tail, size - tail_offset, list) do {new_tail, added, []} -> large(size + added, tail_offset, level, trie, new_tail, first) {first_leaf, _added, list} -> Builder.from_trie(trie, level, tail_offset) |> Builder.append_node(first_leaf) |> Builder.concat_list(list) |> from_builder(first) end end def concat_list(empty_pattern(), list) do from_list(list) end def concat_vector(empty_pattern(), right), do: right def concat_vector(left, empty_pattern()), do: left def concat_vector(left, right = small(_, _, _)) do concat_list(left, to_list(right)) end def concat_vector(left = small(_, _, _), right) do # can probably fo better left |> to_list(to_list(right)) |> from_list() end def concat_vector( large(size1, tail_offset1, level1, trie1, tail1, first1), large(size2, tail_offset2, level2, trie2, tail2, _first2) ) do leaves2 = Trie.list_leaves(trie2, level2, [], tail_offset2 - 1) Builder.from_trie(trie1, level1, tail_offset1) |> do_concat_vector(tail1, size1 - tail_offset1, leaves2, tail2, size2 - tail_offset2) |> from_builder(first1) end defp do_concat_vector( builder, tail1, _tail_size1 = C.branch_factor(), leaves2, tail2, tail_size2 ) do builder |> Builder.append_node(tail1) |> Builder.append_nodes(leaves2) |> Builder.append_tail(tail2, tail_size2) end defp do_concat_vector(builder, tail1, tail_size1, leaves2, tail2, tail_size2) do [first_right_leaf | _] = leaves2 {completed_tail, added, _list} = Tail.complete_tail(tail1, tail_size1, Node.to_list(first_right_leaf)) builder |> Builder.append_node(completed_tail) |> Builder.append_nodes_with_offset( leaves2, added, tail2, tail_size2 ) end def prepend(vector, value) do # TODO make this a bit more efficient by pattern matching on leaves [value | to_list(vector)] |> from_list() end @spec duplicate(val, non_neg_integer) :: t(val) when val: value def duplicate(_, 0), do: @empty def duplicate(value, n) when n <= C.branch_factor() do tail = Tail.partial_duplicate(value, n) small(n, tail, value) end def duplicate(value, n) do tail_size = C.radix_rem(n - 1) + 1 tail = Tail.partial_duplicate(value, tail_size) tail_offset = n - tail_size {level, trie} = Trie.duplicate(value, tail_offset) large(n, tail_offset, level, trie, tail, value) end @compile {:inline, fetch_positive!: 2} @spec fetch_positive!(t(val), non_neg_integer) :: val when val: value def fetch_positive!(small(size, tail, _first), index) do elem(tail, C.branch_factor() - size + index) end def fetch_positive!(large(size, tail_offset, shift, trie, tail, _first), index) do if index < tail_offset do Trie.lookup(trie, index, shift) else elem(tail, C.branch_factor() - size + index) end end @spec replace_positive!(t(val), non_neg_integer, val) :: t(val) when val: value def replace_positive!(vector, index, value) def replace_positive!(small(size, tail, first), index, value) do new_tail = put_elem(tail, C.branch_factor() - size + index, value) new_first = case index do 0 -> value _ -> first end small(size, new_tail, new_first) end def replace_positive!(large(size, tail_offset, level, trie, tail, first), index, value) do new_first = case index do 0 -> value _ -> first end if index < tail_offset do new_trie = Trie.replace(trie, index, level, value) large(size, tail_offset, level, new_trie, tail, new_first) else new_tail = put_elem(tail, C.branch_factor() - size + index, value) large(size, tail_offset, level, trie, new_tail, new_first) end end @spec update_positive!(t(val), non_neg_integer, (val -> val)) :: val when val: value def update_positive!(vector, index, fun) def update_positive!(small(size, tail, first), index, fun) do new_tail = Node.update_at(tail, C.branch_factor() - size + index, fun) new_first = case index do 0 -> elem(new_tail, C.branch_factor() - size) _ -> first end small(size, new_tail, new_first) end def update_positive!(large(size, tail_offset, level, trie, tail, first), index, fun) do if index < tail_offset do new_trie = Trie.update(trie, index, level, fun) new_first = case index do 0 -> Trie.first(new_trie, level) _ -> first end large(size, tail_offset, level, new_trie, tail, new_first) else new_tail = Node.update_at(tail, C.branch_factor() - size + index, fun) new_first = case index do 0 -> elem(new_tail, C.branch_factor() - size) _ -> first end large(size, tail_offset, level, trie, new_tail, new_first) end end def get_and_update(vector, raw_index, fun) do case actual_index(raw_index, size(vector)) do nil -> get_and_update_missing_index(vector, fun) index -> value = fetch_positive!(vector, index) case fun.(value) do {returned, new_value} -> new_vector = replace_positive!(vector, index, new_value) {returned, new_vector} :pop -> {value, delete_positive!(vector, index, size(vector))} other -> get_and_update_error(other) end end end defp get_and_update_missing_index(vector, fun) do case fun.(nil) do {returned, _} -> {returned, vector} :pop -> {nil, vector} other -> get_and_update_error(other) end end defp get_and_update_error(other) do raise "the given function must return a two-element tuple or :pop, got: #{inspect(other)}" end @spec pop_last(t(val)) :: {val, t(val)} | :error when val: value def pop_last(vector = last_pattern(last)) do {last, delete_last(vector)} end def pop_last(empty_pattern()) do :error end @spec delete_last(t(val)) :: t(val) when val: value def delete_last(small(1, _tail, _first)), do: @empty def delete_last(small(size, tail, first)) do new_tail = Tail.delete_last(tail) small(size - 1, new_tail, first) end def delete_last(large(unquote(C.branch_factor() + 1), _, _, trie, _tail, first)) do small(C.branch_factor(), trie, first) end def delete_last(large(size, tail_offset, level, trie, tail, first)) do case tail_offset + 1 do ^size -> {new_tail, new_trie, new_level} = Trie.pop_leaf(trie, level, tail_offset - 1) large(size - 1, tail_offset - C.branch_factor(), new_level, new_trie, new_tail, first) _ -> new_tail = Tail.delete_last(tail) large(size - 1, tail_offset, level, trie, new_tail, first) end end def pop_positive!(vector, index, size) do case index + 1 do ^size -> pop_last(vector) _ -> left = take(vector, index) [popped | right] = slice(vector, index, size - 1) new_vector = concat_list(left, right) {popped, new_vector} end end def delete_positive!(vector, index, size) do case index + 1 do ^size -> delete_last(vector) amount -> left = take(vector, index) right = slice(vector, amount, size - 1) concat_list(left, right) end end # LOOPS @spec to_list(t(val)) :: [val] when val: value def to_list(small(size, tail, _first)) do Tail.partial_to_list(tail, size) end def to_list(large(size, tail_offset, shift, trie, tail, _first)) do acc = Tail.partial_to_list(tail, size - tail_offset) Trie.to_list(trie, shift, acc) end def to_list(empty_pattern()) do [] end @spec to_list(t(val), [val]) :: [val] when val: value def to_list(small(size, tail, _first), list) do Tail.partial_to_list(tail, size) ++ list end def to_list(large(size, tail_offset, shift, trie, tail, _first), list) do acc = Tail.partial_to_list(tail, size - tail_offset) ++ list Trie.to_list(trie, shift, acc) end def to_list(empty_pattern(), list) do list end @spec reverse_to_list(t(val), [val]) :: [val] when val: value C.def_foldl reverse_to_list(arg, acc) do [arg | acc] end @spec sparse_to_list(t(val)) :: [val] when val: value C.def_foldr sparse_to_list(arg, acc \\ []) do case arg do nil -> acc value -> [value | acc] end end @spec foldl(t(val), acc, (val, acc -> acc)) :: acc when val: value, acc: term C.def_foldl foldl(arg, acc, fun) do fun.(arg, acc) end @spec reduce(t(val), (val, val -> val)) :: val when val: value C.def_foldl reduce(arg, acc \\ first(), fun) do fun.(arg, acc) end @spec foldr(t(val), acc, (val, acc -> acc)) :: acc when val: value, acc: term C.def_foldr foldr(arg, acc, fun) do fun.(arg, acc) end @spec each(t(val), (val -> term)) :: :ok when val: value def each(vector, fun) do do_each(vector, fun) :ok end C.def_foldl do_each(arg, fun) do fun.(arg) fun end @spec sum(t(number)) :: number C.def_foldl sum(arg, acc \\ 0) do acc + arg end @spec product(t(number)) :: number C.def_foldl product(arg, acc \\ 1) do acc * arg end @spec count(t(val), (val -> as_boolean(term))) :: non_neg_integer when val: value C.def_foldl count(arg, acc \\ 0, fun) do if fun.(arg) do acc + 1 else acc end end @spec intersperse_to_list(t(val), sep) :: [val | sep] when val: value, sep: value def intersperse_to_list(vector, separator) do case do_intersperse_to_list(vector, separator) do [] -> [] [_ | rest] -> rest end end C.def_foldr do_intersperse_to_list(arg, acc \\ [], separator) do [separator, arg | acc] end def map_to_list(vector, fun) do map_reverse_list(vector, fun) |> :lists.reverse() end C.def_foldl map_reverse_list(arg, acc \\ [], fun) do [fun.(arg) | acc] end def map_intersperse_to_list(vector, separator, mapper) do case do_map_intersperse_to_list(vector, separator, mapper) do [] -> [] [_ | rest] -> :lists.reverse(rest) end end C.def_foldl do_map_intersperse_to_list(arg, acc \\ [], separator, mapper) do [separator, mapper.(arg) | acc] end @spec join_as_iodata(t(val), String.t()) :: iodata when val: String.Chars.t() def join_as_iodata(vector, joiner) do case joiner do "" -> do_join(vector) _ -> case do_join(vector, joiner) do [] -> [] [_ | rest] -> rest end end end C.def_foldr do_join(arg, acc \\ []) do [entry_to_string(arg) | acc] end C.def_foldr do_join(arg, acc \\ [], joiner) do [joiner, entry_to_string(arg) | acc] end defp entry_to_string(entry) when is_binary(entry), do: entry defp entry_to_string(entry), do: String.Chars.to_string(entry) @spec max(t(val)) :: val when val: value C.def_foldl max(arg, acc \\ first()) do if acc >= arg do acc else arg end end C.def_foldl min(arg, acc \\ first()) do if acc <= arg do acc else arg end end @spec custom_min_max(t(val), (val, val -> boolean)) :: val when val: value C.def_foldl custom_min_max(arg, acc \\ first(), sorter) do if sorter.(acc, arg) do acc else arg end end @spec custom_min_max_by(t(val), (val -> mapped_val), (mapped_val, mapped_val -> boolean)) :: val when val: value, mapped_val: value def custom_min_max_by(vector, fun, sorter) do foldl(vector, nil, fn arg, acc -> case acc do nil -> {arg, fun.(arg)} {_, prev_value} -> arg_value = fun.(arg) if sorter.(prev_value, arg_value) do acc else {arg, arg_value} end end end) |> elem(0) end @spec frequencies(t(val)) :: %{optional(val) => non_neg_integer} when val: value C.def_foldl frequencies(arg, acc \\ %{}) do increase_frequency(acc, arg) end @spec frequencies_by(t(val), (val -> key)) :: %{optional(key) => non_neg_integer} when val: value, key: any C.def_foldl frequencies_by(arg, acc \\ %{}, key_fun) do key = key_fun.(arg) increase_frequency(acc, key) end defp increase_frequency(acc, key) do case acc do %{^key => value} -> %{acc | key => value + 1} _ -> Map.put(acc, key, 1) end end @spec group_by(t(val), (val -> key), (val -> mapped_val)) :: %{optional(key) => [mapped_val]} when val: value, key: any, mapped_val: any C.def_foldr group_by(arg, acc \\ %{}, key_fun, value_fun) do key = key_fun.(arg) value = value_fun.(arg) add_to_group(acc, key, value) end defp add_to_group(acc, key, value) do case acc do %{^key => list} -> %{acc | key => [value | list]} _ -> Map.put(acc, key, [value]) end end def uniq_list(vector) do vector |> do_uniq() |> elem(0) |> :lists.reverse() end C.def_foldl do_uniq(arg, acc \\ {[], %{}}) do add_to_set(acc, arg, arg) end def uniq_by_list(vector, fun) do vector |> do_uniq_by(fun) |> elem(0) |> :lists.reverse() end C.def_foldl do_uniq_by(arg, acc \\ {[], %{}}, fun) do key = fun.(arg) add_to_set(acc, key, arg) end defp add_to_set({list, set} = acc, key, value) do case set do %{^key => _} -> acc _ -> {[value | list], Map.put(set, key, true)} end end C.def_foldr dedup_list(arg, acc \\ []) do case acc do [^arg | _] -> acc _ -> [arg | acc] end end @spec filter_to_list(t(val), (val -> as_boolean(term))) :: [val] when val: value def filter_to_list(vector, fun) do vector |> do_filter(fun) |> :lists.reverse() end C.def_foldl do_filter(arg, acc \\ [], fun) do if fun.(arg) do [arg | acc] else acc end end @spec reject_to_list(t(val), (val -> as_boolean(term))) :: [val] when val: value def reject_to_list(vector, fun) do vector |> do_reject(fun) |> :lists.reverse() end C.def_foldl do_reject(arg, acc \\ [], fun) do if fun.(arg) do acc else [arg | acc] end end # FIND def member?(small(size, tail, _first), value) do Tail.partial_member?(tail, size, value) end def member?(large(size, tail_offset, level, trie, tail, _first), value) do Trie.member?(trie, level, value) or Tail.partial_member?(tail, size - tail_offset, value) end def member?(empty_pattern(), _value), do: false @spec any?(t()) :: boolean() def any?(small(size, tail, _first)) do Tail.partial_any?(tail, size) end def any?(large(size, tail_offset, level, trie, tail, _first)) do Trie.any?(trie, level) or Tail.partial_any?(tail, size - tail_offset) end def any?(empty_pattern()), do: false @spec any?(t(val), (val -> as_boolean(term))) :: boolean() when val: value def any?(small(size, tail, _first), fun) do Tail.partial_any?(tail, C.branch_factor() - size, fun) end def any?(large(size, tail_offset, level, trie, tail, _first), fun) do Trie.any?(trie, level, fun) or Tail.partial_any?(tail, C.branch_factor() + tail_offset - size, fun) end def any?(empty_pattern(), _fun), do: false @spec all?(t()) :: boolean() def all?(small(size, tail, _first)) do Tail.partial_all?(tail, size) end def all?(large(size, tail_offset, level, trie, tail, _first)) do Trie.all?(trie, level) and Tail.partial_all?(tail, size - tail_offset) end def all?(empty_pattern()), do: true @spec all?(t(val), (val -> as_boolean(term))) :: boolean() when val: value def all?(small(size, tail, _first), fun) do Tail.partial_all?(tail, C.branch_factor() - size, fun) end def all?(large(size, tail_offset, level, trie, tail, _first), fun) do Trie.all?(trie, level, fun) and Tail.partial_all?(tail, C.branch_factor() + tail_offset - size, fun) end def all?(empty_pattern(), _fun), do: true @spec find(t(val), default, (val -> as_boolean(term))) :: val | default when val: value, default: any def find(vector, default, fun) do case do_find(vector, fun) do {:ok, value} -> value nil -> default end end defp do_find(small(size, tail, _first), fun) do Tail.partial_find(tail, C.branch_factor() - size, fun) end defp do_find(large(size, tail_offset, level, trie, tail, _first), fun) do Trie.find(trie, level, fun) || Tail.partial_find(tail, C.branch_factor() + tail_offset - size, fun) end defp do_find(empty_pattern(), _fun), do: nil @spec find_value(t(val), (val -> new_val)) :: new_val | nil when val: value, new_val: value def find_value(small(size, tail, _first), fun) do Tail.partial_find_value(tail, C.branch_factor() - size, fun) end def find_value(large(size, tail_offset, level, trie, tail, _first), fun) do Trie.find_value(trie, level, fun) || Tail.partial_find_value(tail, C.branch_factor() + tail_offset - size, fun) end def find_value(empty_pattern(), _fun), do: nil @spec find_index(t(val), (val -> as_boolean(term))) :: non_neg_integer | nil when val: value def find_index(small(size, tail, _first), fun) do case Tail.partial_find_index(tail, C.branch_factor() - size, fun) do nil -> nil index -> index + size - C.branch_factor() end end def find_index(large(size, tail_offset, level, trie, tail, _first), fun) do cond do index = Trie.find_index(trie, level, fun) -> index index = Tail.partial_find_index(tail, C.branch_factor() + tail_offset - size, fun) -> index + size - C.branch_factor() true -> nil end end def find_index(empty_pattern(), _fun), do: nil @spec find_falsy_index(t(val), (val -> as_boolean(term))) :: non_neg_integer | nil when val: value def find_falsy_index(small(size, tail, _first), fun) do case Tail.partial_find_falsy_index(tail, C.branch_factor() - size, fun) do nil -> nil index -> index + size - C.branch_factor() end end def find_falsy_index(large(size, tail_offset, level, trie, tail, _first), fun) do cond do index = Trie.find_falsy_index(trie, level, fun) -> index index = Tail.partial_find_falsy_index(tail, C.branch_factor() + tail_offset - size, fun) -> index + size - C.branch_factor() true -> nil end end def find_falsy_index(empty_pattern(), _fun), do: nil @compile {:inline, map: 2} @spec map(t(v1), (v1 -> v2)) :: t(v2) when v1: value, v2: value def map(vector, fun) def map(small(size, tail, _first), fun) do new_tail = Tail.partial_map(tail, fun, size) new_first = elem(new_tail, C.branch_factor() - size) small(size, new_tail, new_first) end def map(large(size, tail_offset, level, trie, tail, _first), fun) do new_trie = Trie.map(trie, level, fun) new_tail = Tail.partial_map(tail, fun, size - tail_offset) large(size, tail_offset, level, new_trie, new_tail, Trie.first(new_trie, level)) end def map(empty_pattern(), _fun), do: @empty @compile {:inline, slice: 3} @spec slice(t(val), non_neg_integer, non_neg_integer) :: [val] when val: value def slice(vector, start, last) def slice(small(size, tail, _first), start, last) do Tail.slice(tail, start, last, size) end def slice(large(size, tail_offset, level, trie, tail, _first), start, last) do acc = if last < tail_offset do [] else Tail.slice( tail, Kernel.max(0, start - tail_offset), last - tail_offset, size - tail_offset ) end if start < tail_offset do Trie.slice(trie, start, Kernel.min(last, tail_offset - 1), level, acc) else acc end end def slice(empty_pattern(), _start, _last), do: [] @compile {:inline, take: 2} @spec take(t(val), non_neg_integer) :: t(val) when val: value def take(vector, amount) def take(small(size, tail, first) = vector, amount) do case amount do 0 -> @empty too_big when too_big >= size -> vector new_size -> new_tail = Tail.partial_take(tail, size - new_size) small(new_size, new_tail, first) end end def take(large(size, tail_offset, level, trie, tail, first) = vector, amount) do case amount do 0 -> @empty too_big when too_big >= size -> vector new_size -> case new_size > tail_offset do true -> new_tail = Tail.partial_take(tail, size - new_size) large(new_size, tail_offset, level, trie, new_tail, first) _ -> case Trie.take(trie, level, new_size) do {:small, new_tail} -> small(new_size, new_tail, first) {:large, new_trie, new_level, new_tail} -> large(new_size, get_tail_offset(new_size), new_level, new_trie, new_tail, first) end end end end def take(empty_pattern(), _amount), do: @empty defp get_tail_offset(size) do size - C.radix_rem(size - 1) - 1 end @spec with_index(t(val), integer) :: t({val, integer}) when val: value def with_index(vector, offset) def with_index(small(size, tail, _first), offset) do new_tail = Tail.partial_with_index(tail, C.branch_factor() - size, offset) new_first = elem(new_tail, C.branch_factor() - size) small(size, new_tail, new_first) end def with_index(large(size, tail_offset, level, trie, tail, _first), offset) do new_trie = Trie.with_index(trie, level, offset) new_tail = Tail.partial_with_index(tail, C.branch_factor() + tail_offset - size, offset + tail_offset) large(size, tail_offset, level, new_trie, new_tail, Trie.first(new_trie, level)) end def with_index(empty_pattern(), _offset), do: @empty def with_index(vector, offset, fun) def with_index(small(size, tail, _first), offset, fun) do new_tail = Tail.partial_with_index(tail, C.branch_factor() - size, offset, fun) new_first = elem(new_tail, C.branch_factor() - size) small(size, new_tail, new_first) end def with_index(large(size, tail_offset, level, trie, tail, _first), offset, fun) do new_trie = Trie.with_index(trie, level, offset, fun) new_tail = Tail.partial_with_index( tail, C.branch_factor() + tail_offset - size, offset + tail_offset, fun ) large(size, tail_offset, level, new_trie, new_tail, Trie.first(new_trie, level)) end def with_index(empty_pattern(), _offset, _fun), do: @empty @compile {:inline, random: 1} def random(empty_pattern()) do raise Enum.EmptyError end def random(vector) do index = :rand.uniform(size(vector)) - 1 fetch_positive!(vector, index) end def take_random(empty_pattern(), _amount), do: @empty def take_random(_vector, 0), do: @empty def take_random(vector, 1) do picked = random(vector) tail = unquote([C.var(picked)] |> C.left_fill_with(nil) |> C.array()) small(1, tail, picked) end def take_random(vector, amount) when amount >= size(vector) do vector |> to_list() |> Enum.shuffle() |> from_list() end def take_random(vector, amount) do vector |> to_list() |> Enum.take_random(amount) |> from_list() end def scan(vector, fun) do ref = make_ref() scan(vector, ref, fn value, ^ref -> value value, acc -> fun.(value, acc) end) end def scan(small(size, tail, _first), acc, fun) do new_tail = Tail.partial_scan(tail, C.branch_factor() - size, acc, fun) new_first = elem(new_tail, C.branch_factor() - size) small(size, new_tail, new_first) end def scan( large(size, tail_offset, level, trie, tail, _first), acc, fun ) do {new_trie, acc} = Trie.scan(trie, level, acc, fun) new_tail = Tail.partial_scan(tail, C.branch_factor() + tail_offset - size, acc, fun) large(size, tail_offset, level, new_trie, new_tail, Trie.first(new_trie, level)) end def scan(empty_pattern(), _acc, _fun), do: @empty def map_reduce(small(size, tail, _first), acc, fun) do {new_tail, acc} = Tail.partial_map_reduce(tail, C.branch_factor() - size, acc, fun) new_first = elem(new_tail, C.branch_factor() - size) new_raw = small(size, new_tail, new_first) {new_raw, acc} end def map_reduce( large(size, tail_offset, level, trie, tail, _first), acc, fun ) do {new_trie, acc} = Trie.map_reduce(trie, level, acc, fun) {new_tail, acc} = Tail.partial_map_reduce(tail, C.branch_factor() + tail_offset - size, acc, fun) new_first = Trie.first(new_trie, level) new_raw = large(size, tail_offset, level, new_trie, new_tail, new_first) {new_raw, acc} end def map_reduce(empty_pattern(), acc, _fun), do: {@empty, acc} @spec zip(t(val1), t(val2)) :: t({val1, val2}) when val1: value, val2: value def zip(vector1, vector2) do size1 = size(vector1) size2 = size(vector2) cond do size1 > size2 -> do_zip(take(vector1, size2), vector2) size1 == size2 -> do_zip(vector1, vector2) true -> do_zip(vector1, take(vector2, size1)) end end defp do_zip(small(size, tail1, first1), small(size, tail2, first2)) do new_tail = Tail.partial_zip(tail1, tail2, C.branch_factor() - size) small(size, new_tail, {first1, first2}) end defp do_zip( large(size, tail_offset, level, trie1, tail1, first1), large(size, tail_offset, level, trie2, tail2, first2) ) do new_tail = Tail.partial_zip(tail1, tail2, C.branch_factor() + tail_offset - size) new_trie = Trie.zip(trie1, trie2, level) large(size, tail_offset, level, new_trie, new_tail, {first1, first2}) end defp do_zip(empty_pattern(), empty_pattern()), do: @empty @spec zip_with(t(val1), t(val2), (val1, val2 -> val3)) :: t(val3) when val1: value, val2: value, val3: value def zip_with(vector1, vector2, fun) do size1 = size(vector1) size2 = size(vector2) cond do size1 > size2 -> do_zip_with(take(vector1, size2), vector2, fun) size1 == size2 -> do_zip_with(vector1, vector2, fun) true -> do_zip_with(vector1, take(vector2, size1), fun) end end defp do_zip_with(small(size, tail1, _first1), small(size, tail2, _first2), fun) do new_tail = Tail.partial_zip_with(tail1, tail2, C.branch_factor() - size, fun) new_first = elem(new_tail, C.branch_factor() - size) small(size, new_tail, new_first) end defp do_zip_with( large(size, tail_offset, level, trie1, tail1, _first1), large(size, tail_offset, level, trie2, tail2, _first2), fun ) do new_tail = Tail.partial_zip_with(tail1, tail2, C.branch_factor() + tail_offset - size, fun) new_trie = Trie.zip_with(trie1, trie2, level, fun) new_first = Trie.first(new_trie, level) large(size, tail_offset, level, new_trie, new_tail, new_first) end defp do_zip_with(empty_pattern(), empty_pattern(), _fun), do: @empty @spec unzip(t({val1, val2})) :: {t(val1), t(val2)} when val1: value, val2: value def unzip(small(size, tail, _size)) do {tail1, tail2} = Tail.partial_unzip(tail, C.branch_factor() - size) first1 = elem(tail1, C.branch_factor() - size) first2 = elem(tail2, C.branch_factor() - size) {small(size, tail1, first1), small(size, tail2, first2)} end def unzip(large(size, tail_offset, level, trie, tail, first)) do {tail1, tail2} = Tail.partial_unzip(tail, C.branch_factor() + tail_offset - size) {trie1, trie2} = Trie.unzip(trie, level) {first1, first2} = first { large(size, tail_offset, level, trie1, tail1, first1), large(size, tail_offset, level, trie2, tail2, first2) } end def unzip(empty_pattern()), do: {@empty, @empty} end
lib/vector/raw.ex
0.516595
0.76625
raw.ex
starcoder
defmodule AdventOfCode.Y2020.Day4 do defstruct birth_year: nil, issued: nil, expire: nil, height: nil, hair_color: nil, eye_color: nil, pid: nil, country: nil alias AdventOfCode.Y2020.Day4 import AdventOfCode.Helpers.Data, only: [read_from_file_no_split: 1] def run() do read_from_file_no_split("2020/day4.txt") |> String.split("\n\n") |> Enum.map(&process_raw_data/1) |> Enum.filter(&is_valid/1) |> Enum.count() end def process_raw_data(data) do data |> String.split(~r{[\s\n]}, trim: true) |> Enum.reduce(%Day4{}, &capture_field/2) end def is_valid(%Day4{} = data) when is_nil(data.birth_year) or is_nil(data.issued) or is_nil(data.expire) or is_nil(data.height) or is_nil(data.hair_color) or is_nil(data.eye_color) or is_nil(data.pid) do false end def is_valid(%Day4{}), do: true def validate_number(number, low, high) do number = String.to_integer(number) if number >= low and number <= high do number else nil end end def test_field(str) do capture_field(str, %Day4{}) end # byr (Birth Year) - four digits; at least 1920 and at most 2002. def capture_field("byr:" <> birth_year, %Day4{} = data) when is_binary(birth_year) do %Day4{data | birth_year: validate_number(birth_year, 1920, 2002)} end # iyr (Issue Year) - four digits; at least 2010 and at most 2020. def capture_field("iyr:" <> issued, %Day4{} = data) do %Day4{data | issued: validate_number(issued, 2010, 2020)} end # eyr (Expiration Year) - four digits; at least 2020 and at most 2030. def capture_field("eyr:" <> expire, %Day4{} = data) do %Day4{data | expire: validate_number(expire, 2020, 2030)} end # hgt (Height) - a number followed by either cm or in: # If in, the number must be at least 59 and at most 76. def capture_field(<<"hgt:", height::binary-size(3), "cm">>, %Day4{} = data) do %Day4{data | height: validate_number(height, 150, 193)} end # hgt (Height) - a number followed by either cm or in: # If in, the number must be at least 59 and at most 76. def capture_field(<<"hgt:", height::binary-size(2), "in">>, %Day4{} = data) do %Day4{data | height: validate_number(height, 59, 76)} end # hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f. def capture_field("hcl:#" <> hair_color, %Day4{} = data) do if hair_color =~ ~r/[0-9a-f]{6}/ do %Day4{data | hair_color: hair_color} else data end end # ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth. def capture_field("ecl:" <> eye_color, %Day4{} = data) do if Enum.member?(["amb", "blu", "brn", "gry", "grn", "hzl", "oth"], eye_color) do %Day4{data | eye_color: eye_color} else data end end # pid (Passport ID) - a nine-digit number, including leading zeroes. def capture_field("pid:" <> pid, %Day4{} = data) do if pid =~ ~r/^[0-9]{9}$/ do %Day4{data | pid: pid} else data end end # cid (Country ID) - ignored, missing or not. def capture_field("cid:" <> country, %Day4{} = data), do: %Day4{data | country: country} def capture_field(_, %Day4{} = data), do: data end
lib/2020/day4.ex
0.597725
0.446072
day4.ex
starcoder
defmodule AntikytheraCore.TemplateEngine do @moduledoc """ This is an implementation of `EEx.Engine` that auto-escape dynamic parts within HAML templates. """ @behaviour EEx.Engine alias Antikythera.TemplateSanitizer @impl true def init(_opts) do %{ iodata: [], dynamic: [], vars_count: 0, } end @impl true def handle_begin(state) do %{state | iodata: [], dynamic: []} end @impl true def handle_end(quoted) do handle_body(quoted) end @impl true def handle_body(state) do %{iodata: iodata, dynamic: dynamic} = state q = quote do IO.iodata_to_binary(unquote(Enum.reverse(iodata))) end {:__block__, [], Enum.reverse([{:safe, q} | dynamic])} end @impl true def handle_text(state, text) do %{iodata: iodata} = state %{state | iodata: [text | iodata]} end @impl true def handle_expr(state, "=", expr) do %{iodata: iodata, dynamic: dynamic, vars_count: vars_count} = state var = Macro.var(:"arg#{vars_count}", __MODULE__) q = quote do unquote(var) = unquote(to_safe_expr(expr)) end %{state | dynamic: [q | dynamic], iodata: [var | iodata], vars_count: vars_count + 1} end def handle_expr(state, "", expr) do %{dynamic: dynamic} = state %{state | dynamic: [expr | dynamic]} end def handle_expr(state, marker, expr) do EEx.Engine.handle_expr(state, marker, expr) end # For literals we can do the work at compile time defp to_safe_expr(s) when is_binary(s) , do: TemplateSanitizer.html_escape(s) defp to_safe_expr(nil) , do: "" defp to_safe_expr(a) when is_atom(a) , do: TemplateSanitizer.html_escape(Atom.to_string(a)) defp to_safe_expr(i) when is_integer(i), do: Integer.to_string(i) defp to_safe_expr(f) when is_float(f) , do: Float.to_string(f) # Otherwise we do the work at runtime defp to_safe_expr(expr) do quote do AntikytheraCore.TemplateEngine.to_safe_iodata(unquote(expr)) end end def to_safe_iodata({:safe, data}) , do: data def to_safe_iodata(s) when is_binary(s) , do: TemplateSanitizer.html_escape(s) def to_safe_iodata(nil) , do: "" def to_safe_iodata(a) when is_atom(a) , do: TemplateSanitizer.html_escape(Atom.to_string(a)) def to_safe_iodata(i) when is_integer(i) , do: Integer.to_string(i) def to_safe_iodata(f) when is_float(f) , do: Float.to_string(f) def to_safe_iodata([]) , do: "" def to_safe_iodata([h | _] = l) when is_integer(h), do: List.to_string(l) # convert charlist to String.t def to_safe_iodata([h | t]) , do: [to_safe_iodata(h) | to_safe_iodata(t)] end
core/web/template_engine.ex
0.752877
0.413773
template_engine.ex
starcoder
defmodule(ExAliyunOts.TableStoreSearch.AggregationType) do @moduledoc false ( defstruct([]) ( @spec default() :: :AGG_AVG def(default()) do :AGG_AVG end ) @spec encode(atom()) :: integer() | atom() [ ( def(encode(:AGG_AVG)) do 1 end def(encode("AGG_AVG")) do 1 end ), ( def(encode(:AGG_DISTINCT_COUNT)) do 6 end def(encode("AGG_DISTINCT_COUNT")) do 6 end ), ( def(encode(:AGG_MAX)) do 2 end def(encode("AGG_MAX")) do 2 end ), ( def(encode(:AGG_MIN)) do 3 end def(encode("AGG_MIN")) do 3 end ), ( def(encode(:AGG_SUM)) do 4 end def(encode("AGG_SUM")) do 4 end ), ( def(encode(:AGG_COUNT)) do 5 end def(encode("AGG_COUNT")) do 5 end ) ] def(encode(x)) do x end @spec decode(integer()) :: atom() | integer() [ def(decode(1)) do :AGG_AVG end, def(decode(2)) do :AGG_MAX end, def(decode(3)) do :AGG_MIN end, def(decode(4)) do :AGG_SUM end, def(decode(5)) do :AGG_COUNT end, def(decode(6)) do :AGG_DISTINCT_COUNT end ] def(decode(x)) do x end @spec constants() :: [{integer(), atom()}] def(constants()) do [ {1, :AGG_AVG}, {6, :AGG_DISTINCT_COUNT}, {2, :AGG_MAX}, {3, :AGG_MIN}, {4, :AGG_SUM}, {5, :AGG_COUNT} ] end @spec has_constant?(any()) :: boolean() ( [ def(has_constant?(:AGG_AVG)) do true end, def(has_constant?(:AGG_DISTINCT_COUNT)) do true end, def(has_constant?(:AGG_MAX)) do true end, def(has_constant?(:AGG_MIN)) do true end, def(has_constant?(:AGG_SUM)) do true end, def(has_constant?(:AGG_COUNT)) do true end ] def(has_constant?(_)) do false end ) ) end
lib/elixir_ex_aliyun_ots_table_store_search_aggregation_type.ex
0.770249
0.461502
elixir_ex_aliyun_ots_table_store_search_aggregation_type.ex
starcoder
defmodule Google.Protobuf.FileDescriptorSet do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ file: [Google.Protobuf.FileDescriptorProto.t()] } defstruct [:file] field :file, 1, repeated: true, type: Google.Protobuf.FileDescriptorProto end defmodule Google.Protobuf.FileDescriptorProto do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ name: String.t(), package: String.t(), dependency: [String.t()], public_dependency: [integer], weak_dependency: [integer], message_type: [Google.Protobuf.DescriptorProto.t()], enum_type: [Google.Protobuf.EnumDescriptorProto.t()], service: [Google.Protobuf.ServiceDescriptorProto.t()], extension: [Google.Protobuf.FieldDescriptorProto.t()], options: Google.Protobuf.FileOptions.t() | nil, source_code_info: Google.Protobuf.SourceCodeInfo.t() | nil, syntax: String.t() } defstruct [ :name, :package, :dependency, :public_dependency, :weak_dependency, :message_type, :enum_type, :service, :extension, :options, :source_code_info, :syntax ] field :name, 1, optional: true, type: :string field :package, 2, optional: true, type: :string field :dependency, 3, repeated: true, type: :string field :public_dependency, 10, repeated: true, type: :int32 field :weak_dependency, 11, repeated: true, type: :int32 field :message_type, 4, repeated: true, type: Google.Protobuf.DescriptorProto field :enum_type, 5, repeated: true, type: Google.Protobuf.EnumDescriptorProto field :service, 6, repeated: true, type: Google.Protobuf.ServiceDescriptorProto field :extension, 7, repeated: true, type: Google.Protobuf.FieldDescriptorProto field :options, 8, optional: true, type: Google.Protobuf.FileOptions field :source_code_info, 9, optional: true, type: Google.Protobuf.SourceCodeInfo field :syntax, 12, optional: true, type: :string end defmodule Google.Protobuf.DescriptorProto do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ name: String.t(), field: [Google.Protobuf.FieldDescriptorProto.t()], extension: [Google.Protobuf.FieldDescriptorProto.t()], nested_type: [Google.Protobuf.DescriptorProto.t()], enum_type: [Google.Protobuf.EnumDescriptorProto.t()], extension_range: [Google.Protobuf.DescriptorProto.ExtensionRange.t()], oneof_decl: [Google.Protobuf.OneofDescriptorProto.t()], options: Google.Protobuf.MessageOptions.t() | nil, reserved_range: [Google.Protobuf.DescriptorProto.ReservedRange.t()], reserved_name: [String.t()] } defstruct [ :name, :field, :extension, :nested_type, :enum_type, :extension_range, :oneof_decl, :options, :reserved_range, :reserved_name ] field :name, 1, optional: true, type: :string field :field, 2, repeated: true, type: Google.Protobuf.FieldDescriptorProto field :extension, 6, repeated: true, type: Google.Protobuf.FieldDescriptorProto field :nested_type, 3, repeated: true, type: Google.Protobuf.DescriptorProto field :enum_type, 4, repeated: true, type: Google.Protobuf.EnumDescriptorProto field :extension_range, 5, repeated: true, type: Google.Protobuf.DescriptorProto.ExtensionRange field :oneof_decl, 8, repeated: true, type: Google.Protobuf.OneofDescriptorProto field :options, 7, optional: true, type: Google.Protobuf.MessageOptions field :reserved_range, 9, repeated: true, type: Google.Protobuf.DescriptorProto.ReservedRange field :reserved_name, 10, repeated: true, type: :string end defmodule Google.Protobuf.DescriptorProto.ExtensionRange do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ start: integer, end: integer, options: Google.Protobuf.ExtensionRangeOptions.t() | nil } defstruct [:start, :end, :options] field :start, 1, optional: true, type: :int32 field :end, 2, optional: true, type: :int32 field :options, 3, optional: true, type: Google.Protobuf.ExtensionRangeOptions end defmodule Google.Protobuf.DescriptorProto.ReservedRange do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ start: integer, end: integer } defstruct [:start, :end] field :start, 1, optional: true, type: :int32 field :end, 2, optional: true, type: :int32 end defmodule Google.Protobuf.ExtensionRangeOptions do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ uninterpreted_option: [Google.Protobuf.UninterpretedOption.t()] } defstruct [:uninterpreted_option] field :uninterpreted_option, 999, repeated: true, type: Google.Protobuf.UninterpretedOption end defmodule Google.Protobuf.FieldDescriptorProto do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ name: String.t(), number: integer, label: integer, type: integer, type_name: String.t(), extendee: String.t(), default_value: String.t(), oneof_index: integer, json_name: String.t(), options: Google.Protobuf.FieldOptions.t() | nil } defstruct [ :name, :number, :label, :type, :type_name, :extendee, :default_value, :oneof_index, :json_name, :options ] field :name, 1, optional: true, type: :string field :number, 3, optional: true, type: :int32 field :label, 4, optional: true, type: Google.Protobuf.FieldDescriptorProto.Label, enum: true field :type, 5, optional: true, type: Google.Protobuf.FieldDescriptorProto.Type, enum: true field :type_name, 6, optional: true, type: :string field :extendee, 2, optional: true, type: :string field :default_value, 7, optional: true, type: :string field :oneof_index, 9, optional: true, type: :int32 field :json_name, 10, optional: true, type: :string field :options, 8, optional: true, type: Google.Protobuf.FieldOptions end defmodule Google.Protobuf.FieldDescriptorProto.Type do @moduledoc false use Protobuf, enum: true, syntax: :proto2 field :TYPE_DOUBLE, 1 field :TYPE_FLOAT, 2 field :TYPE_INT64, 3 field :TYPE_UINT64, 4 field :TYPE_INT32, 5 field :TYPE_FIXED64, 6 field :TYPE_FIXED32, 7 field :TYPE_BOOL, 8 field :TYPE_STRING, 9 field :TYPE_GROUP, 10 field :TYPE_MESSAGE, 11 field :TYPE_BYTES, 12 field :TYPE_UINT32, 13 field :TYPE_ENUM, 14 field :TYPE_SFIXED32, 15 field :TYPE_SFIXED64, 16 field :TYPE_SINT32, 17 field :TYPE_SINT64, 18 end defmodule Google.Protobuf.FieldDescriptorProto.Label do @moduledoc false use Protobuf, enum: true, syntax: :proto2 field :LABEL_OPTIONAL, 1 field :LABEL_REQUIRED, 2 field :LABEL_REPEATED, 3 end defmodule Google.Protobuf.OneofDescriptorProto do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ name: String.t(), options: Google.Protobuf.OneofOptions.t() | nil } defstruct [:name, :options] field :name, 1, optional: true, type: :string field :options, 2, optional: true, type: Google.Protobuf.OneofOptions end defmodule Google.Protobuf.EnumDescriptorProto do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ name: String.t(), value: [Google.Protobuf.EnumValueDescriptorProto.t()], options: Google.Protobuf.EnumOptions.t() | nil, reserved_range: [Google.Protobuf.EnumDescriptorProto.EnumReservedRange.t()], reserved_name: [String.t()] } defstruct [:name, :value, :options, :reserved_range, :reserved_name] field :name, 1, optional: true, type: :string field :value, 2, repeated: true, type: Google.Protobuf.EnumValueDescriptorProto field :options, 3, optional: true, type: Google.Protobuf.EnumOptions field :reserved_range, 4, repeated: true, type: Google.Protobuf.EnumDescriptorProto.EnumReservedRange field :reserved_name, 5, repeated: true, type: :string end defmodule Google.Protobuf.EnumDescriptorProto.EnumReservedRange do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ start: integer, end: integer } defstruct [:start, :end] field :start, 1, optional: true, type: :int32 field :end, 2, optional: true, type: :int32 end defmodule Google.Protobuf.EnumValueDescriptorProto do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ name: String.t(), number: integer, options: Google.Protobuf.EnumValueOptions.t() | nil } defstruct [:name, :number, :options] field :name, 1, optional: true, type: :string field :number, 2, optional: true, type: :int32 field :options, 3, optional: true, type: Google.Protobuf.EnumValueOptions end defmodule Google.Protobuf.ServiceDescriptorProto do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ name: String.t(), method: [Google.Protobuf.MethodDescriptorProto.t()], options: Google.Protobuf.ServiceOptions.t() | nil } defstruct [:name, :method, :options] field :name, 1, optional: true, type: :string field :method, 2, repeated: true, type: Google.Protobuf.MethodDescriptorProto field :options, 3, optional: true, type: Google.Protobuf.ServiceOptions end defmodule Google.Protobuf.MethodDescriptorProto do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ name: String.t(), input_type: String.t(), output_type: String.t(), options: Google.Protobuf.MethodOptions.t() | nil, client_streaming: boolean, server_streaming: boolean } defstruct [:name, :input_type, :output_type, :options, :client_streaming, :server_streaming] field :name, 1, optional: true, type: :string field :input_type, 2, optional: true, type: :string field :output_type, 3, optional: true, type: :string field :options, 4, optional: true, type: Google.Protobuf.MethodOptions field :client_streaming, 5, optional: true, type: :bool, default: false field :server_streaming, 6, optional: true, type: :bool, default: false end defmodule Google.Protobuf.FileOptions do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ java_package: String.t(), java_outer_classname: String.t(), java_multiple_files: boolean, java_generate_equals_and_hash: boolean, java_string_check_utf8: boolean, optimize_for: integer, go_package: String.t(), cc_generic_services: boolean, java_generic_services: boolean, py_generic_services: boolean, php_generic_services: boolean, deprecated: boolean, cc_enable_arenas: boolean, objc_class_prefix: String.t(), csharp_namespace: String.t(), swift_prefix: String.t(), php_class_prefix: String.t(), php_namespace: String.t(), php_metadata_namespace: String.t(), ruby_package: String.t(), uninterpreted_option: [Google.Protobuf.UninterpretedOption.t()] } defstruct [ :java_package, :java_outer_classname, :java_multiple_files, :java_generate_equals_and_hash, :java_string_check_utf8, :optimize_for, :go_package, :cc_generic_services, :java_generic_services, :py_generic_services, :php_generic_services, :deprecated, :cc_enable_arenas, :objc_class_prefix, :csharp_namespace, :swift_prefix, :php_class_prefix, :php_namespace, :php_metadata_namespace, :ruby_package, :elixir_module_prefix, :uninterpreted_option ] field :java_package, 1, optional: true, type: :string field :java_outer_classname, 8, optional: true, type: :string field :java_multiple_files, 10, optional: true, type: :bool, default: false field :java_generate_equals_and_hash, 20, optional: true, type: :bool, deprecated: true field :java_string_check_utf8, 27, optional: true, type: :bool, default: false field :optimize_for, 9, optional: true, type: Google.Protobuf.FileOptions.OptimizeMode, default: :SPEED, enum: true field :go_package, 11, optional: true, type: :string field :cc_generic_services, 16, optional: true, type: :bool, default: false field :java_generic_services, 17, optional: true, type: :bool, default: false field :py_generic_services, 18, optional: true, type: :bool, default: false field :php_generic_services, 42, optional: true, type: :bool, default: false field :deprecated, 23, optional: true, type: :bool, default: false field :cc_enable_arenas, 31, optional: true, type: :bool, default: false field :objc_class_prefix, 36, optional: true, type: :string field :csharp_namespace, 37, optional: true, type: :string field :swift_prefix, 39, optional: true, type: :string field :php_class_prefix, 40, optional: true, type: :string field :php_namespace, 41, optional: true, type: :string field :php_metadata_namespace, 44, optional: true, type: :string field :ruby_package, 45, optional: true, type: :string field :elixir_module_prefix, 1047, optional: true, type: :string field :uninterpreted_option, 999, repeated: true, type: Google.Protobuf.UninterpretedOption end defmodule Google.Protobuf.FileOptions.OptimizeMode do @moduledoc false use Protobuf, enum: true, syntax: :proto2 field :SPEED, 1 field :CODE_SIZE, 2 field :LITE_RUNTIME, 3 end defmodule Google.Protobuf.MessageOptions do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ message_set_wire_format: boolean, no_standard_descriptor_accessor: boolean, deprecated: boolean, map_entry: boolean, uninterpreted_option: [Google.Protobuf.UninterpretedOption.t()] } defstruct [ :message_set_wire_format, :no_standard_descriptor_accessor, :deprecated, :map_entry, :uninterpreted_option ] field :message_set_wire_format, 1, optional: true, type: :bool, default: false field :no_standard_descriptor_accessor, 2, optional: true, type: :bool, default: false field :deprecated, 3, optional: true, type: :bool, default: false field :map_entry, 7, optional: true, type: :bool field :uninterpreted_option, 999, repeated: true, type: Google.Protobuf.UninterpretedOption end defmodule Google.Protobuf.FieldOptions do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ ctype: integer, packed: boolean, jstype: integer, lazy: boolean, deprecated: boolean, weak: boolean, uninterpreted_option: [Google.Protobuf.UninterpretedOption.t()] } defstruct [:ctype, :packed, :jstype, :lazy, :deprecated, :weak, :uninterpreted_option] field :ctype, 1, optional: true, type: Google.Protobuf.FieldOptions.CType, default: :STRING, enum: true field :packed, 2, optional: true, type: :bool field :jstype, 6, optional: true, type: Google.Protobuf.FieldOptions.JSType, default: :JS_NORMAL, enum: true field :lazy, 5, optional: true, type: :bool, default: false field :deprecated, 3, optional: true, type: :bool, default: false field :weak, 10, optional: true, type: :bool, default: false field :uninterpreted_option, 999, repeated: true, type: Google.Protobuf.UninterpretedOption end defmodule Google.Protobuf.FieldOptions.CType do @moduledoc false use Protobuf, enum: true, syntax: :proto2 field :STRING, 0 field :CORD, 1 field :STRING_PIECE, 2 end defmodule Google.Protobuf.FieldOptions.JSType do @moduledoc false use Protobuf, enum: true, syntax: :proto2 field :JS_NORMAL, 0 field :JS_STRING, 1 field :JS_NUMBER, 2 end defmodule Google.Protobuf.OneofOptions do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ uninterpreted_option: [Google.Protobuf.UninterpretedOption.t()] } defstruct [:uninterpreted_option] field :uninterpreted_option, 999, repeated: true, type: Google.Protobuf.UninterpretedOption end defmodule Google.Protobuf.EnumOptions do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ allow_alias: boolean, deprecated: boolean, uninterpreted_option: [Google.Protobuf.UninterpretedOption.t()] } defstruct [:allow_alias, :deprecated, :uninterpreted_option] field :allow_alias, 2, optional: true, type: :bool field :deprecated, 3, optional: true, type: :bool, default: false field :uninterpreted_option, 999, repeated: true, type: Google.Protobuf.UninterpretedOption end defmodule Google.Protobuf.EnumValueOptions do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ deprecated: boolean, uninterpreted_option: [Google.Protobuf.UninterpretedOption.t()] } defstruct [:deprecated, :uninterpreted_option] field :deprecated, 1, optional: true, type: :bool, default: false field :uninterpreted_option, 999, repeated: true, type: Google.Protobuf.UninterpretedOption end defmodule Google.Protobuf.ServiceOptions do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ deprecated: boolean, uninterpreted_option: [Google.Protobuf.UninterpretedOption.t()] } defstruct [:deprecated, :uninterpreted_option] field :deprecated, 33, optional: true, type: :bool, default: false field :uninterpreted_option, 999, repeated: true, type: Google.Protobuf.UninterpretedOption end defmodule Google.Protobuf.MethodOptions do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ deprecated: boolean, idempotency_level: integer, uninterpreted_option: [Google.Protobuf.UninterpretedOption.t()] } defstruct [:deprecated, :idempotency_level, :uninterpreted_option] field :deprecated, 33, optional: true, type: :bool, default: false field :idempotency_level, 34, optional: true, type: Google.Protobuf.MethodOptions.IdempotencyLevel, default: :IDEMPOTENCY_UNKNOWN, enum: true field :uninterpreted_option, 999, repeated: true, type: Google.Protobuf.UninterpretedOption end defmodule Google.Protobuf.MethodOptions.IdempotencyLevel do @moduledoc false use Protobuf, enum: true, syntax: :proto2 field :IDEMPOTENCY_UNKNOWN, 0 field :NO_SIDE_EFFECTS, 1 field :IDEMPOTENT, 2 end defmodule Google.Protobuf.UninterpretedOption do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ name: [Google.Protobuf.UninterpretedOption.NamePart.t()], identifier_value: String.t(), positive_int_value: non_neg_integer, negative_int_value: integer, double_value: float, string_value: String.t(), aggregate_value: String.t() } defstruct [ :name, :identifier_value, :positive_int_value, :negative_int_value, :double_value, :string_value, :aggregate_value ] field :name, 2, repeated: true, type: Google.Protobuf.UninterpretedOption.NamePart field :identifier_value, 3, optional: true, type: :string field :positive_int_value, 4, optional: true, type: :uint64 field :negative_int_value, 5, optional: true, type: :int64 field :double_value, 6, optional: true, type: :double field :string_value, 7, optional: true, type: :bytes field :aggregate_value, 8, optional: true, type: :string end defmodule Google.Protobuf.UninterpretedOption.NamePart do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ name_part: String.t(), is_extension: boolean } defstruct [:name_part, :is_extension] field :name_part, 1, required: true, type: :string field :is_extension, 2, required: true, type: :bool end defmodule Google.Protobuf.SourceCodeInfo do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ location: [Google.Protobuf.SourceCodeInfo.Location.t()] } defstruct [:location] field :location, 1, repeated: true, type: Google.Protobuf.SourceCodeInfo.Location end defmodule Google.Protobuf.SourceCodeInfo.Location do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ path: [integer], span: [integer], leading_comments: String.t(), trailing_comments: String.t(), leading_detached_comments: [String.t()] } defstruct [:path, :span, :leading_comments, :trailing_comments, :leading_detached_comments] field :path, 1, repeated: true, type: :int32, packed: true field :span, 2, repeated: true, type: :int32, packed: true field :leading_comments, 3, optional: true, type: :string field :trailing_comments, 4, optional: true, type: :string field :leading_detached_comments, 6, repeated: true, type: :string end defmodule Google.Protobuf.GeneratedCodeInfo do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ annotation: [Google.Protobuf.GeneratedCodeInfo.Annotation.t()] } defstruct [:annotation] field :annotation, 1, repeated: true, type: Google.Protobuf.GeneratedCodeInfo.Annotation end defmodule Google.Protobuf.GeneratedCodeInfo.Annotation do @moduledoc false use Protobuf, syntax: :proto2 @type t :: %__MODULE__{ path: [integer], source_file: String.t(), begin: integer, end: integer } defstruct [:path, :source_file, :begin, :end] field :path, 1, repeated: true, type: :int32, packed: true field :source_file, 2, optional: true, type: :string field :begin, 3, optional: true, type: :int32 field :end, 4, optional: true, type: :int32 end
lib/google/descriptor.pb.ex
0.706899
0.407392
descriptor.pb.ex
starcoder
defmodule Braintree.Customer do @moduledoc """ You can create a customer by itself, with a payment method, or with a credit card with a billing address. For additional reference see: https://developers.braintreepayments.com/reference/request/customer/create/ruby """ use Braintree.Construction alias Braintree.{CreditCard, HTTP, PaymentMethod, PaypalAccount, Search} alias Braintree.ErrorResponse, as: Error @type t :: %__MODULE__{ id: String.t(), company: String.t(), email: String.t(), fax: String.t(), first_name: String.t(), last_name: String.t(), phone: String.t(), website: String.t(), created_at: String.t(), updated_at: String.t(), custom_fields: map, addresses: [map], payment_methods: [PaymentMethod.t()], credit_cards: [CreditCard.t()], paypal_accounts: [PaypalAccount.t()], coinbase_accounts: [map] } defstruct id: nil, company: nil, email: nil, fax: nil, first_name: nil, last_name: nil, phone: nil, website: nil, created_at: nil, updated_at: nil, custom_fields: %{}, addresses: [], credit_cards: [], coinbase_accounts: [], paypal_accounts: [] @doc """ Create a customer record, or return an error response with after failed validation. ## Example {:ok, customer} = Braintree.Customer.create(%{ first_name: "Jen", last_name: "Smith", company: "Braintree", email: "<EMAIL>", phone: "312.555.1234", fax: "614.555.5678", website: "www.example.com" }) customer.company # Braintree """ @spec create(map, Keyword.t()) :: {:ok, t} | {:error, Error.t()} def create(params \\ %{}, opts \\ []) do with {:ok, payload} <- HTTP.post("customers", %{customer: params}, opts) do {:ok, new(payload)} end end @doc """ You can delete a customer using its ID. When a customer is deleted, all associated payment methods are also deleted, and all associated recurring billing subscriptions are canceled. ## Example :ok = Braintree.Customer.delete("customer_id") """ @spec delete(binary, Keyword.t()) :: :ok | {:error, Error.t()} def delete(id, opts \\ []) when is_binary(id) do with {:ok, _response} <- HTTP.delete("customers/" <> id, opts) do :ok end end @doc """ If you want to look up a single customer using its ID, use the find method. ## Example customer = Braintree.Customer.find("customer_id") """ @spec find(binary, Keyword.t()) :: {:ok, t} | {:error, Error.t()} def find(id, opts \\ []) when is_binary(id) do with {:ok, payload} <- HTTP.get("customers/" <> id, opts) do {:ok, new(payload)} end end @doc """ To update a customer, use its ID along with new attributes. The same validations apply as when creating a customer. Any attribute not passed will remain unchanged. ## Example {:ok, customer} = Braintree.Customer.update("customer_id", %{ company: "New Company Name" }) customer.company # "New Company Name" """ @spec update(binary, map, Keyword.t()) :: {:ok, t} | {:error, Error.t()} def update(id, params, opts \\ []) when is_binary(id) and is_map(params) do with {:ok, payload} <- HTTP.put("customers/" <> id, %{customer: params}, opts) do {:ok, new(payload)} end end @doc """ To search for customers, pass a map of search parameters. ## Example: {:ok, customers} = Braintree.Customer.search(%{first_name: %{is: "Jenna"}}) """ @spec search(map, Keyword.t()) :: {:ok, t} | {:error, Error.t()} def search(params, opts \\ []) when is_map(params) do Search.perform(params, "customers", &new/1, opts) end @doc """ Convert a map into a Company struct along with nested payment options. Credit cards and paypal accounts are converted to a list of structs as well. ## Example customer = Braintree.Customer.new(%{"company" => "Soren", "email" => "<EMAIL>"}) """ def new(%{"customer" => map}) do new(map) end def new(map) when is_map(map) do customer = super(map) %{ customer | credit_cards: CreditCard.new(customer.credit_cards), payment_methods: PaymentMethod.new(customer.payment_methods), paypal_accounts: PaypalAccount.new(customer.paypal_accounts) } end def new(list) when is_list(list) do Enum.map(list, &new/1) end end
lib/customer.ex
0.857201
0.505188
customer.ex
starcoder
defmodule OMG.Watcher.ExitProcessor.Piggyback do @moduledoc """ Encapsulates managing and executing the behaviors related to treating exits by the child chain and watchers Keeps a state of exits that are in progress, updates it with news from the root chain, compares to the state of the ledger (`OMG.State`), issues notifications as it finds suitable. Should manage all kinds of exits allowed in the protocol and handle the interactions between them. This is the functional, zero-side-effect part of the exit processor. Logic should go here: - orchestrating the persistence of the state - finding invalid exits, disseminating them as events according to rules - enabling to challenge invalid exits - figuring out critical failure of invalid exit challenging (aka `:unchallenged_exit` event) - MoreVP protocol managing in general For the imperative shell, see `OMG.Watcher.ExitProcessor` """ alias OMG.State.Transaction alias OMG.Utxo alias OMG.Watcher.Event alias OMG.Watcher.ExitProcessor alias OMG.Watcher.ExitProcessor.Core alias OMG.Watcher.ExitProcessor.DoubleSpend alias OMG.Watcher.ExitProcessor.InFlightExitInfo alias OMG.Watcher.ExitProcessor.KnownTx import OMG.Watcher.ExitProcessor.Tools require Transaction.Payment use OMG.Utils.LoggerExt @type piggyback_type_t() :: :input | :output @type piggyback_t() :: {piggyback_type_t(), non_neg_integer()} @type input_challenge_data :: %{ in_flight_txbytes: Transaction.tx_bytes(), in_flight_input_index: 0..3, spending_txbytes: Transaction.tx_bytes(), spending_input_index: 0..3, spending_sig: <<_::520>>, input_tx: Transaction.tx_bytes(), input_utxo_pos: Utxo.Position.t() } @type output_challenge_data :: %{ in_flight_txbytes: Transaction.tx_bytes(), in_flight_output_pos: pos_integer(), in_flight_input_index: 4..7, spending_txbytes: Transaction.tx_bytes(), spending_input_index: 0..3, spending_sig: <<_::520>> } @type piggyback_challenge_data_error() :: :ife_not_known_for_tx | Transaction.decode_error() | :no_double_spend_on_particular_piggyback def get_input_challenge_data(request, state, txbytes, input_index) do case input_index in 0..(Transaction.Payment.max_inputs() - 1) do true -> get_piggyback_challenge_data(request, state, txbytes, {:input, input_index}) false -> {:error, :piggybacked_index_out_of_range} end end def get_output_challenge_data(request, state, txbytes, output_index) do case output_index in 0..(Transaction.Payment.max_outputs() - 1) do true -> get_piggyback_challenge_data(request, state, txbytes, {:output, output_index}) false -> {:error, :piggybacked_index_out_of_range} end end @doc """ Returns a tuple of ivalid piggybacks and invalid piggybacks that are past SLA margin. This is inclusive, invalid piggybacks past SLA margin are included in the invalid piggybacks list. """ @spec get_invalid_piggybacks_events(Core.t(), KnownTx.known_txs_by_input_t(), pos_integer()) :: {list(Event.InvalidPiggyback.t()), list(Event.UnchallengedPiggyback.t())} def get_invalid_piggybacks_events( %Core{sla_margin: sla_margin, in_flight_exits: ifes}, known_txs_by_input, eth_height_now ) do invalid_piggybacks_by_ife = ifes |> Map.values() |> all_invalid_piggybacks_by_ife(known_txs_by_input) invalid_piggybacks_events = to_events(invalid_piggybacks_by_ife, &to_invalid_piggyback_event/1) past_sla_margin = fn {ife, _type, _materials} -> ife.eth_height + sla_margin <= eth_height_now end unchallenged_piggybacks_events = invalid_piggybacks_by_ife |> Enum.filter(past_sla_margin) |> to_events(&to_unchallenged_piggyback_event/1) {invalid_piggybacks_events, unchallenged_piggybacks_events} end defp all_invalid_piggybacks_by_ife(ifes_values, known_txs_by_input) do [:input, :output] |> Enum.flat_map(fn pb_type -> invalid_piggybacks_by_ife(known_txs_by_input, pb_type, ifes_values) end) end defp to_events(piggybacks_by_ife, to_event) do piggybacks_by_ife |> group_by_txbytes() |> Enum.map(to_event) end defp to_invalid_piggyback_event({txbytes, type_materials_pairs}) do %Event.InvalidPiggyback{ txbytes: txbytes, inputs: invalid_piggyback_indices(type_materials_pairs, :input), outputs: invalid_piggyback_indices(type_materials_pairs, :output) } end defp to_unchallenged_piggyback_event({txbytes, type_materials_pairs}) do %Event.UnchallengedPiggyback{ txbytes: txbytes, inputs: invalid_piggyback_indices(type_materials_pairs, :input), outputs: invalid_piggyback_indices(type_materials_pairs, :output) } end # we need to produce only one event per IFE, with both piggybacks on inputs and outputs defp group_by_txbytes(invalid_piggybacks) do invalid_piggybacks |> Enum.map(fn {ife, type, materials} -> {Transaction.raw_txbytes(ife.tx), type, materials} end) |> Enum.group_by(&elem(&1, 0), fn {_, type, materials} -> {type, materials} end) end defp invalid_piggyback_indices(type_materials_pairs, pb_type) do # here we need to additionally group the materials found by type input/output # then we gut just the list of indices to present to the user in the event type_materials_pairs |> Enum.filter(fn {type, _materials} -> type == pb_type end) |> Enum.flat_map(fn {_type, materials} -> Map.keys(materials) end) end @spec invalid_piggybacks_by_ife(KnownTx.known_txs_by_input_t(), piggyback_type_t(), list(InFlightExitInfo.t())) :: list({InFlightExitInfo.t(), piggyback_type_t(), %{non_neg_integer => DoubleSpend.t()}}) defp invalid_piggybacks_by_ife(known_txs_by_input, pb_type, ifes) do ifes |> Enum.map(&InFlightExitInfo.unchallenged_piggybacks_by_ife(&1, pb_type)) |> Enum.filter(&ife_has_something?/1) |> Enum.map(fn {ife, indexed_piggybacked_utxo_positions} -> proof_materials = DoubleSpend.all_double_spends_by_index(indexed_piggybacked_utxo_positions, known_txs_by_input, ife.tx) {ife, pb_type, proof_materials} end) |> Enum.filter(&ife_has_something?/1) end defp ife_has_something?({_ife, finds_for_ife}), do: !Enum.empty?(finds_for_ife) defp ife_has_something?({_ife, _, finds_for_ife}), do: !Enum.empty?(finds_for_ife) @spec get_piggyback_challenge_data(ExitProcessor.Request.t(), Core.t(), binary(), piggyback_t()) :: {:ok, input_challenge_data() | output_challenge_data()} | {:error, piggyback_challenge_data_error()} defp get_piggyback_challenge_data(%ExitProcessor.Request{blocks_result: blocks}, state, txbytes, piggyback) do with {:ok, tx} <- Transaction.decode(txbytes), {:ok, ife} <- get_ife(tx, state.in_flight_exits) do known_txs_by_input = KnownTx.get_all_from_blocks_appendix(blocks, state) produce_invalid_piggyback_proof(ife, known_txs_by_input, piggyback) end end @spec produce_invalid_piggyback_proof(InFlightExitInfo.t(), KnownTx.known_txs_by_input_t(), piggyback_t()) :: {:ok, input_challenge_data() | output_challenge_data()} | {:error, :no_double_spend_on_particular_piggyback} defp produce_invalid_piggyback_proof(ife, known_txs_by_input, {pb_type, pb_index} = piggyback) do with {:ok, proof_materials} <- get_proofs_for_particular_ife(ife, pb_type, known_txs_by_input), {:ok, proof} <- get_proof_for_particular_piggyback(pb_index, proof_materials) do {:ok, prepare_piggyback_challenge_response(ife, piggyback, proof)} end end # gets all proof materials for all possibly invalid piggybacks for a single ife, for a determined type (input/output) defp get_proofs_for_particular_ife(ife, pb_type, known_txs_by_input) do invalid_piggybacks_by_ife(known_txs_by_input, pb_type, [ife]) |> case do [] -> {:error, :no_double_spend_on_particular_piggyback} # ife and pb_type are pinned here for a runtime sanity check - we got what we explicitly asked for [{^ife, ^pb_type, proof_materials}] -> {:ok, proof_materials} end end # gets any proof of a particular invalid piggyback, after we have figured the exact piggyback index affected defp get_proof_for_particular_piggyback(pb_index, proof_materials) do proof_materials |> Map.get(pb_index) |> case do nil -> {:error, :no_double_spend_on_particular_piggyback} # any challenging tx will do, taking the very first [proof | _] -> {:ok, proof} end end @spec prepare_piggyback_challenge_response(InFlightExitInfo.t(), piggyback_t(), DoubleSpend.t()) :: input_challenge_data() | output_challenge_data() defp prepare_piggyback_challenge_response(ife, {:input, input_index}, proof) do %{ in_flight_txbytes: Transaction.raw_txbytes(ife.tx), in_flight_input_index: input_index, spending_txbytes: Transaction.raw_txbytes(proof.known_tx.signed_tx), spending_input_index: proof.known_spent_index, spending_sig: Enum.at(proof.known_tx.signed_tx.sigs, proof.known_spent_index), input_tx: Enum.at(ife.input_txs, input_index), input_utxo_pos: Enum.at(ife.input_utxos_pos, input_index) } end defp prepare_piggyback_challenge_response(ife, {:output, _output_index}, proof) do {_, inclusion_proof} = ife.tx_seen_in_blocks_at %{ in_flight_txbytes: Transaction.raw_txbytes(ife.tx), in_flight_output_pos: proof.utxo_pos, in_flight_proof: inclusion_proof, spending_txbytes: Transaction.raw_txbytes(proof.known_tx.signed_tx), spending_input_index: proof.known_spent_index, spending_sig: Enum.at(proof.known_tx.signed_tx.sigs, proof.known_spent_index) } end end
apps/omg_watcher/lib/omg_watcher/exit_processor/piggyback.ex
0.728941
0.473049
piggyback.ex
starcoder
defmodule DAL do @moduledoc """ Global Data Access Layer to replace direct use of `Ecto.Repo` and other data services. The DAL performs two core functions: 1. Provides an abstraction for other data repositories 1. Provides a set of macros representing all available data types that can be used in services ## Data Abstraction We use a number of different databases at Expert360. Right now all of them are SQL (either MySQL or PostgreSQL) and use `Ecto.Repo` but in the future they may also be other databases such as Redis or Elasticsearch. The DAL uses a discovery mechanism (see `DAL.Repo.Discovery`) which uses Elixir protocols to determine what Repo and attached database to use for a particular query. This way the caller does not need to know where to find the data - they just need to query the DAL. The DAL emulates the `Ecto.Repo` API so that it can be used in place of an actual Repo in most scenarios (for example in `ex_machina` factories). But be aware that it does not actually adhere to the `Ecto.Repo` behaviour as it does not define callbacks such as `start_link/1`. You can use the DAL in exactly the same way that you would a normal ecto repo: ```elixir DAL.get(Profiles.Project, 1) ``` ## Schema Macros In the DAL architecture, services need to define their own schema models. However, to have multiple services that define schema fields would be cumbersome and error prone. Consequently, the DAL defines macros for each data type that it supports (including implementations for `DAL.Repo.Discoverable`) that can be used by services. For example, to create a project schema model in the `Profiles` service: ``` defmodule Profiles.Project do use DAL.Types.Project end """ @behaviour DAL.Behaviour alias DAL.Repo.Discovery alias Ecto.Multi import Ecto.Query @doc """ Delegates to an appropriate repo determined by `DAL.Repo.Discoverable` then behaves just like `c:Ecto.Repo.get/3` """ @spec get( queryable :: Ecto.Queryable.t(), id :: term, opts :: Keyword.t() ) :: Ecto.Schema.t() | nil | no_return def get(queryable, id, opts \\ []) do execute(queryable, :get, [id, opts]) end @doc """ Delegates to an appropriate repo determined by `DAL.Repo.Discoverable` then behaves just like `c:Ecto.Repo.get!/3` """ @spec get!( queryable :: Ecto.Queryable.t(), id :: term, opts :: Keyword.t() ) :: Ecto.Schema.t() | nil | no_return def get!(queryable, id, opts \\ []) do execute(queryable, :get!, [id, opts]) end @doc """ Delegates to an appropriate repo determined by `DAL.Repo.Discoverable` then behaves just like `c:Ecto.Repo.get_by/3` """ @spec get_by( queryable :: Ecto.Queryable.t(), clauses :: Keyword.t() | map, opts :: Keyword.t() ) :: Ecto.Schema.t() | nil | no_return def get_by(queryable, params, opts \\ []) do execute(queryable, :get_by, [params, opts]) end @doc """ Delegates to an appropriate repo determined by `DAL.Repo.Discoverable` then behaves just like `c:Ecto.Repo.get_by!/3` """ @spec get_by!( queryable :: Ecto.Queryable.t(), clauses :: Keyword.t() | map, opts :: Keyword.t() ) :: Ecto.Schema.t() | nil | no_return def get_by!(queryable, params, opts \\ []) do execute(queryable, :get_by!, [params, opts]) end @doc """ Delegates to an appropriate repo determined by `DAL.Repo.Discoverable` then behaves just like `c:Ecto.Repo.one!/2` """ @spec one( queryable :: Ecto.Query.t(), opts :: Keyword.t() ) :: Ecto.Schema.t() | nil | no_return() def one(queryable, opts \\ []) do execute(queryable, :one, [opts]) end @doc """ Delegates to an appropriate repo determined by `DAL.Repo.Discoverable` then behaves just like `c:Ecto.Repo.get_by!/2` """ @spec all(queryable :: Ecto.Query.t(), opts :: Keyword.t()) :: [Ecto.Schema.t()] | no_return def all(queryable, opts \\ []) do execute(queryable, :all, [opts]) end @doc """ Delegates to an appropriate repo determined by `DAL.Repo.Discoverable` then behaves just like `c:Ecto.Repo.aggregate/4` """ @spec aggregate( queryable :: Ecto.Query.t(), aggregate :: :avg | :count | :max | :min | :sum, field :: atom(), opts :: Keyword.t() ) :: [Ecto.Schema.t()] | no_return def aggregate(queryable, aggregate, field, opts \\ []) do execute(queryable, :aggregate, [aggregate, field, opts]) end @doc """ Delegates to an appropriate repo determined by `DAL.Repo.Discoverable` and then constrains the results to the given list of ids before passing to `all/2`. """ @spec all_ids( queryable :: Ecto.Query.t(), id_list :: list(term), opts :: Keyword.t() ) :: [Ecto.Schema.t()] | no_return def all_ids(queryable, id_list, opts \\ []) do queryable |> where([q], q.id in ^id_list) |> all(opts) end @doc """ Delegates to an appropriate repo determined by `DAL.Repo.Discoverable` then behaves just like `c:Ecto.Repo.insert/2` """ @spec insert( struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(), opts :: Keyword.t() ) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} def insert(struct_or_changeset, opts \\ []) do execute(struct_or_changeset, :insert, [opts]) end @doc """ Delegates to an appropriate repo determined by `DAL.Repo.Discoverable` then behaves just like `c:Ecto.Repo.insert!/2` """ @spec insert!( struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(), opts :: Keyword.t() ) :: Ecto.Schema.t() | no_return def insert!(struct_or_changeset, opts \\ []) do execute(struct_or_changeset, :insert!, [opts]) end @doc """ Delegates to an appropriate repo determined by `DAL.Repo.Discoverable` then behaves just like `c:Ecto.Repo.insert_or_update/2` """ @spec insert_or_update( struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(), opts :: Keyword.t() ) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} def insert_or_update(struct_or_changeset, opts \\ []) do execute(struct_or_changeset, :insert_or_update, [opts]) end @doc """ Delegates to an appropriate repo determined by `DAL.Repo.Discoverable` then behaves just like `c:Ecto.Repo.insert_or_update!/2` """ @spec insert_or_update!( struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(), opts :: Keyword.t() ) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} def insert_or_update!(struct_or_changeset, opts \\ []) do execute(struct_or_changeset, :insert_or_update!, [opts]) end @doc """ Delegates to an appropriate repo determined by `DAL.Repo.Discoverable` then behaves just like `c:Ecto.Repo.delete/2` """ @spec delete( struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(), opts :: Keyword.t() ) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} def delete(struct_or_changeset, opts \\ []) do execute(struct_or_changeset, :delete, [opts]) end @doc """ Delegates to an appropriate repo determined by `DAL.Repo.Discoverable` then behaves just like `c:Ecto.Repo.delete_all/2` """ @spec delete_all( queryable :: Ecto.Queryable.t(), opts :: Keyword.t() ) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} def delete_all(queryable, opts \\ []) do execute(queryable, :delete_all, [opts]) end @doc """ Delegates to an appropriate repo determined by `DAL.Repo.Discoverable` then behaves just like `c:Ecto.Repo.delete!/2` """ @spec delete!( struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(), opts :: Keyword.t() ) :: Ecto.Schema.t() | no_return def delete!(struct_or_changeset, opts \\ []) do execute(struct_or_changeset, :delete!, [opts]) end @doc """ Delegates to an appropriate repo determined by `DAL.Repo.Discoverable` then behaves just like `c:Ecto.Repo.update/2` """ @spec update( struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(), opts :: Keyword.t() ) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} def update(struct_or_changeset, opts \\ []) do execute(struct_or_changeset, :update, [opts]) end @doc """ Delegates to an appropriate repo determined by `DAL.Repo.Discoverable` then behaves just like `c:Ecto.Repo.update!/2` """ @spec update!( struct_or_changeset :: Ecto.Schema.t() | Ecto.Changeset.t(), opts :: Keyword.t() ) :: Ecto.Schema.t() | no_return def update!(struct_or_changeset, opts \\ []) do execute(struct_or_changeset, :update!, [opts]) end @doc """ Delegates to an appropriate repo determined by `DAL.Repo.Discoverable` then behaves just like `c:Ecto.Repo.stream/2` """ @spec stream(queryable :: Ecto.Query.t(), opts :: Keyword.t()) :: Enum.t() def stream(queryable, opts \\ []) do execute(queryable, :stream, [opts]) end @doc """ Helper function that inserts a list of `Ecto.Changeset` via `Ecto.Multi`, wrapping it in a transaction.' """ @spec insert_bulk( changesets :: [Ecto.Changeset.t()], opts: list() ) :: {:ok, [map()]} | {:error, Ecto.Changeset.t()} def insert_bulk(changesets, opts \\ []) do changesets |> Enum.with_index() |> Enum.reduce(Multi.new(), fn {changeset, index}, multi -> Multi.insert(multi, Integer.to_string(index), changeset, opts) end) |> transaction(opts) |> case do {:ok, result} -> {:ok, Map.values(result)} {:error, _, changeset, _} -> {:error, changeset} end end @spec insert_all( schema_or_source :: binary() | {binary(), Ecto.Schema.t()} | Ecto.Schema.t(), entries :: [map() | Keyword.t()], opts :: Keyword.t() ) :: {integer(), nil | [term()]} | no_return() def insert_all(schema_or_source, entries, opts \\ []) do execute(schema_or_source, :insert_all, [entries, opts]) end @spec transaction(Multi.t() | Ecto.Query.t()) :: {:ok, any()} | {:error, any()} | {:error, Ecto.Multi.name(), any(), %{optional(Ecto.Multi.name()) => any()}} @doc """ Wrapper over `Ecto.transaction` to handle `Ecto.Multi` and a standard `Ecto.Query`, built in repo discovery. """ def transaction(queryable, opts \\ []) def transaction(%Multi{} = multi, opts) do multi |> Multi.to_list() |> Enum.reduce(nil, fn {_id, {_action, changeset, _opts}}, acc -> repo = discover(changeset) cond do acc == nil -> repo repo != acc -> raise "Multiple repos in transaction not allowed" repo == acc -> repo end end) |> apply(:transaction, [multi, opts]) end def transaction(queryable, _opts) when is_function(queryable) do raise(ArgumentError, "Can't use DAL discovery with a function argument") end def transaction(queryable, opts) do queryable |> discover() |> apply(:transaction, [queryable, opts]) end @doc """ Convenience function for using repo discovery. """ @spec discover( queryable :: nil | Ecto.Query.t() | Ecto.Changeset.t() | Ecto.Schema.t() | [Ecto.Schema.t()] ) :: Ecto.Repo.t() def discover(%Ecto.Changeset{data: data}) do discover(data) end def discover(structs) when is_list(structs) do structs |> Enum.find(& &1) |> discover() end def discover(nil), do: nil def discover(queryable) do Discovery.fetch(queryable) end def preload(struct_or_structs_or_nil, preloads, opts \\ []) do repo = discover(struct_or_structs_or_nil) Ecto.Repo.Preloader.preload(struct_or_structs_or_nil, repo, preloads, opts) end defp execute(target, function, args) do target |> discover() |> apply(function, [target | args]) end end
lib/dal.ex
0.916521
0.862815
dal.ex
starcoder
defmodule Abacus.Eval do @moduledoc """ Function definitions on how to evaluate a syntax tree. You usually don't need to call `eval/2` yourself, use `Abacus.eval/2` instead. """ use Bitwise alias Abacus.Util @spec eval(expr :: tuple | number, scope :: map) :: {:ok, result :: number} | {:ok, boolean} | {:ok, nil} | {:error, term} # BASIC ARITHMETIC def eval({:add, a, b}, _) when is_number(a) and is_number(b), do: {:ok, a + b} def eval({:subtract, a, b}, _) when is_number(a) and is_number(b), do: {:ok, a - b} def eval({:divide, a, b}, _) when is_number(a) and is_number(b), do: {:ok, a / b} def eval({:multiply, a, b}, _) when is_number(a) and is_number(b), do: {:ok, a * b} # OTHER OPERATORS def eval({:power, a, b}, _) when is_number(a) and is_number(b), do: {:ok, :math.pow(a, b)} def eval({:factorial, a}, _) when is_number(a), do: {:ok, Util.factorial(a)} # COMPARISION def eval({:eq, a, b}, _), do: {:ok, equals(a, b)} def eval({:neq, a, b}, _), do: {:ok, not equals(a, b)} def eval({:gt, a, b}, _), do: {:ok, a > b} def eval({:gte, a, b}, _), do: {:ok, a >= b} def eval({:lt, a, b}, _), do: {:ok, a < b} def eval({:lte, a, b}, _), do: {:ok, a <= b} # LOGICAL COMPARISION def eval({:logical_and, a, b}, _) when is_boolean(a) and is_boolean(b), do: {:ok, a && b} def eval({:logical_or, a, b}, _) when is_boolean(a) and is_boolean(b), do: {:ok, a || b} def eval({:logical_not, a}, _) when is_boolean(a), do: {:ok, not a} def eval({:ternary_if, condition, if_true, if_false}, _) do if condition do {:ok, if_true} else {:ok, if_false} end end # FUNCTIONS def eval({:function, "sin", [a]}, _) when is_number(a), do: {:ok, :math.sin(a)} def eval({:function, "cos", [a]}, _) when is_number(a), do: {:ok, :math.cos(a)} def eval({:function, "tan", [a]}, _) when is_number(a), do: {:ok, :math.tan(a)} def eval({:function, "floor", [a]}, _) when is_number(a), do: {:ok, Float.floor(a)} def eval({:function, "floor", [a, precision]}, _) when is_number(a) and is_number(precision), do: {:ok, Float.floor(a, precision)} def eval({:function, "ceil", [a]}, _) when is_number(a), do: {:ok, Float.ceil(a)} def eval({:function, "ceil", [a, precision]}, _) when is_number(a) and is_number(precision), do: {:ok, Float.ceil(a, precision)} def eval({:function, "round", [a]}, _) when is_number(a), do: {:ok, Float.round(a)} def eval({:function, "round", [a, precision]}, _) when is_number(a) and is_number(precision), do: {:ok, Float.round(a, precision)} def eval({:function, "log10", [a]}, _) when is_number(a), do: {:ok, :math.log10(a)} def eval({:function, "sqrt", [a]}, _) when is_number(a), do: {:ok, :math.sqrt(a)} def eval({:function, "abs", [a]}, _) when is_number(a), do: {:ok, Kernel.abs(a)} def eval({:function, "mod", [a, b]}, _) when is_number(a), do: {:ok, :math.fmod(a, b)} def eval({:function, "max", data_set}, _scope) do with false <- Enum.any?(data_set, fn x -> !is_number(x) end) do {:ok, Enum.max(data_set)} else _ -> {:error, :einval} end end def eval({:function, "min", data_set}, _scope) do with false <- Enum.any?(data_set, fn x -> !is_number(x) end) do {:ok, Enum.min(data_set)} else _ -> {:error, :einval} end end def eval({:function, "count", data_set}, _scope) do with false <- Enum.any?(data_set, fn x -> !is_number(x) end) do {:ok, Enum.count(data_set)} else _ -> {:error, :einval} end end def eval({:function, "sum", data_set}, _scope) do with false <- Enum.any?(data_set, fn x -> !is_number(x) end) do {:ok, Enum.sum(data_set)} else _ -> {:error, :einval} end end # IDENTITY def eval(number, _) when is_number(number), do: {:ok, number} def eval(reserved, _) when reserved in [nil, true, false], do: {:ok, reserved} def eval(string, _) when is_binary(string), do: {:ok, string} # ACCESS def eval({:access, _} = expr, scope) do eval(expr, scope, scope) end # BINARY OPERATORS def eval({:not, expr}, _) when is_number(expr), do: {:ok, bnot(expr)} def eval({:and, a, b}, _) when is_number(a) and is_number(b), do: {:ok, band(a, b)} def eval({:or, a, b}, _) when is_number(a) and is_number(b), do: {:ok, bor(a, b)} def eval({:xor, a, b}, _) when is_number(a) and is_number(b), do: {:ok, bxor(a, b)} def eval({:shift_right, a, b}, _) when is_number(a) and is_number(b), do: {:ok, a >>> b} def eval({:shift_left, a, b}, _) when is_number(a) and is_number(b), do: {:ok, a <<< b} # CATCH-ALL # !!! write new evaluations above this definition !!! def eval(_expr, _scope), do: {:error, :einval} # SPECIAL HANDLING FOR ACCESS import Abacus.Tree, only: [reduce: 2] defp eval({:access, [{:variable, name} | rest]}, scope, root) do case Map.get(scope, name, nil) do nil -> {:error, :einkey} value -> eval({:access, rest}, value, root) end end defp eval({:access, [{:index, index} | rest]}, scope, root) do {:ok, index} = reduce(index, &eval(&1, root)) case Enum.at(scope, index, nil) do nil -> {:error, :einkey} value -> eval({:access, rest}, value, root) end end defp eval({:access, []}, value, _root), do: {:ok, value} defp equals(str, atom) when is_binary(str) and is_atom(atom), do: str == Atom.to_string(atom) defp equals(atom, str) when is_binary(str) and is_atom(atom), do: str == Atom.to_string(atom) defp equals(a, b), do: a == b end
lib/eval.ex
0.794185
0.461381
eval.ex
starcoder
defmodule ExtrText.MetadataHandler do @behaviour Saxy.Handler def handle_event(:start_element, {name, _attributes}, state) do {:ok, %{state | name: name}} end def handle_event(:end_element, _name, state) do {:ok, %{state | name: nil}} end def handle_event(:characters, chars, %{name: "dc:title", metadata: metadata} = state) do {:ok, %{state | metadata: Map.put(metadata, :title, chars)}} end def handle_event(:characters, chars, %{name: "dc:subject", metadata: metadata} = state) do {:ok, %{state | metadata: Map.put(metadata, :subject, chars)}} end def handle_event(:characters, chars, %{name: "dc:description", metadata: metadata} = state) do {:ok, %{state | metadata: Map.put(metadata, :description, chars)}} end def handle_event(:characters, chars, %{name: "dc:language", metadata: metadata} = state) do {:ok, %{state | metadata: Map.put(metadata, :language, chars)}} end def handle_event(:characters, chars, %{name: "dc:creator", metadata: metadata} = state) do {:ok, %{state | metadata: Map.put(metadata, :creator, chars)}} end def handle_event(:characters, chars, %{name: "cp:keywords", metadata: metadata} = state) do {:ok, %{state | metadata: Map.put(metadata, :keywords, chars)}} end def handle_event(:characters, chars, %{name: "cp:lastModifiedBy", metadata: metadata} = state) do {:ok, %{state | metadata: Map.put(metadata, :last_modified_by, chars)}} end def handle_event(:characters, chars, %{name: "cp:revision", metadata: metadata} = state) do {:ok, %{state | metadata: Map.put(metadata, :revision, parse_int(chars))}} end def handle_event(:characters, chars, %{name: "dcterms:created", metadata: metadata} = state) do {:ok, %{state | metadata: Map.put(metadata, :created, parse_datetime_string(chars))}} end def handle_event(:characters, chars, %{name: "dcterms:modified", metadata: metadata} = state) do {:ok, %{state | metadata: Map.put(metadata, :modified, parse_datetime_string(chars))}} end def handle_event(_, _, state) do {:ok, state} end defp parse_int(chars) do case Integer.parse(chars) do {i, ""} -> i _ -> nil end end defp parse_datetime_string(chars) do case DateTime.from_iso8601(chars) do {:ok, dt, _offset} -> dt {:error, _} -> nil end end end
lib/handlers/metadata_handler.ex
0.697609
0.484014
metadata_handler.ex
starcoder
defmodule ElasticsearchElixirBulkProcessor do alias ElasticsearchElixirBulkProcessor.Bulk.{BulkStage, Upload} @moduledoc """ Elasticsearch Elixir Bulk Processor is a configurable manager for efficiently inserting data into Elasticsearch. This processor uses genstages for handling backpressure, and various settings to control the bulk payloads being uploaded to Elasticsearch. Inspired by the [Java Bulk Processor](https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-docs-bulk-processor.html) ## Configuration ### Elasticsearch endpoint Can be configurate via the `ELASTICSEARCH_URL` environment variable, defaults to: `"http://localhost:9200"`. ### Action count Number of actions/items to send per bulk (can be changed at run time) ``` ElasticsearchElixirBulkProcessor.set_event_count_threshold(100) ``` ### Byte size Max number of bytes to send per bulk (can be changed at run time) ``` ElasticsearchElixirBulkProcessor.set_byte_threshold(100) ``` ### Action order Preservation of order of actions/items ``` config :elasticsearch_elixir_bulk_processor, preserve_event_order: false ``` ### Retries Retry policy, this uses the [ElixirRetry](https://github.com/safwank/ElixirRetry) DSL. See `ElasticsearchElixirBulkProcessor.Bulk.Retry.policy`. ``` config :elasticsearch_elixir_bulk_processor, retry_function: &MyApp.Retry.policy/0 ``` Default: `constant_backoff(100) |> Stream.take(5)` ### Success and error handlers The callbacks on a successful upload or in case of failed items or failed request can bet set through the config. On success, the handler is called with the Elasticsearch bulk request. On failure, the hanlder is called with`%{data: any, error: any}`, `data` being the original payload and `error` being the response or HTTP error. See `ElasticsearchElixirBulkProcessor.Bulk.Handlers`. ``` config :elasticsearch_elixir_bulk_processor, success_function: &MyApp.success_handler/1, error_function: &MyApp.error_handler/1 ``` """ @doc """ Send a list of request items to ELasticsearch. This mechanism uses GenStages for back pressure. NOTE: It should be completely reasonable to use this function by passing single element lists, the mechanism aggregates the items together prior to sending them. The list elements must be structs: * `ElasticsearchElixirBulkProcessor.Items.Index` * `ElasticsearchElixirBulkProcessor.Items.Create` * `ElasticsearchElixirBulkProcessor.Items.Update` * `ElasticsearchElixirBulkProcessor.Items.Delete` ## Examples iex> alias ElasticsearchElixirBulkProcessor.Items.Index ...> [ ...> %Index{index: "test_index", source: %{"field" => "value1"}}, ...> %Index{index: "test_index", source: %{"field" => "value2"}}, ...> %Index{index: "test_index", source: %{"field" => "value3"}} ...> ] ...> |> ElasticsearchElixirBulkProcessor.send_requests() :ok """ @spec send_requests(list(ElasticsearchElixirBulkProcessor.Items.Item.t())) :: :ok def send_requests(bulk_items) when is_list(bulk_items) do Upload.add_requests(bulk_items) end @doc """ Set the maximum number of bytes to send to elasticsearch per bulk request. ## Examples iex> ElasticsearchElixirBulkProcessor.set_byte_threshold(10) :ok """ @spec set_byte_threshold(integer()) :: :ok def set_byte_threshold(bytes) do BulkStage.set_byte_threshold(bytes) end @doc """ Set the maximum count of items to send to elasticsearch per bulk request. ## Examples iex> ElasticsearchElixirBulkProcessor.set_byte_threshold(10) :ok """ @spec set_event_count_threshold(integer()) :: :ok def set_event_count_threshold(count) do BulkStage.set_event_count_threshold(count) end end
lib/elasticsearch_elixir_bulk_processor.ex
0.910132
0.910067
elasticsearch_elixir_bulk_processor.ex
starcoder
defmodule Ecto.Adapter do @moduledoc """ This module specifies the adapter API that an adapter is required to implement. """ use Behaviour @type t :: module @type query_meta :: map @type model_meta :: %{source: {prefix :: binary, table :: binary}, model: atom, context: term} @type fields :: Keyword.t @type filters :: Keyword.t @type constraints :: Keyword.t @type returning :: [atom] @type prepared :: term @type preprocess :: (field :: Macro.t, value :: term, context :: term -> term) @type autogenerate_id :: {field :: atom, type :: :id | :binary_id, value :: term} | nil @typep repo :: Ecto.Repo.t @typep options :: Keyword.t @doc """ The callback invoked in case the adapter needs to inject code. """ defmacrocallback __before_compile__(Macro.Env.t) :: Macro.t ## Types @doc """ Called for every known Ecto type when loading data from the adapter. This allows developers to properly translate values coming from the adapters into Ecto ones. For example, if the database does not support booleans but instead returns 0 and 1 for them, you could add: def load(:boolean, 0), do: {:ok, false} def load(:boolean, 1), do: {:ok, true} def load(type, value), do: Ecto.Type.load(type, value, &load/2) Notice that `Ecto.Type.load/3` provides a default implementation which also expects the current `load/2` for handling recursive types like arrays and embeds. Finally, notice all adapters are required to implement a clause for :binary_id types, since they are adapter specific. If your adapter does not provide binary ids, you may simply use Ecto.UUID: def load(:binary_id, value), do: load(Ecto.UUID, value) def load(type, value), do: Ecto.Type.load(type, value, &load/2) """ defcallback load(Ecto.Type.t, term) :: {:ok, term} | :error @doc """ Called for every known Ecto type when dumping data to the adapter. This allows developers to properly translate values coming from the Ecto into adapter ones. For example, if the database does not support booleans but instead returns 0 and 1 for them, you could add: def dump(:boolean, false), do: {:ok, 0} def dump(:boolean, true), do: {:ok, 1} def dump(type, value), do: Ecto.Type.dump(type, value, &dump/2) Notice that `Ecto.Type.dump/3` provides a default implementation which also expects the current `dump/2` for handling recursive types like arrays and embeds. Finally, notice all adapters are required to implement a clause for :binary_id types, since they are adapter specific. If your adapter does not provide binary ids, you may simply use Ecto.UUID: def dump(:binary_id, value), do: dump(Ecto.UUID, value) def dump(type, value), do: Ecto.Type.dump(type, value, &dump/2) """ defcallback dump(Ecto.Type.t, term) :: {:ok, term} | :error @doc """ Called every time an id is needed for an embedded model. It receives the `Ecto.Embedded` struct. """ defcallback embed_id(Ecto.Embedded.t) :: String.t @doc """ Starts any connection pooling or supervision and return `{:ok, pid}`. Returns `{:error, {:already_started, pid}}` if the repo already started or `{:error, term}` in case anything else goes wrong. ## Adapter start Because some Ecto tasks like migration may run without starting the parent application, it is recommended that start_link in adapters make sure the adapter application is started by calling `Application.ensure_all_started/1`. """ defcallback start_link(repo, options) :: {:ok, pid} | {:error, {:already_started, pid}} | {:error, term} @doc """ Shuts down the repository represented by the given pid. This callback must be called by the process that called `start_link/2`. Therefore, it is useful for scripts. """ defcallback stop(repo, pid, timeout) :: :ok @doc """ Commands invoked to prepare a query for `all`, `update_all` and `delete_all`. The returned result is given to `execute/6`. """ defcallback prepare(:all | :update_all | :delete_all, query :: Ecto.Query.t) :: {:cache, prepared} | {:nocache, prepared} @doc """ Executes a previously prepared query. It must return a tuple containing the number of entries and the result set as a list of lists. The result set may also be `nil` if a particular operation does not support them. The `meta` field is a map containing some of the fields found in the `Ecto.Query` struct. It receives a preprocess function that should be invoked for each selected field in the query result in order to convert them to the expected Ecto type. The `preprocess` function will be nil if no result set is expected from the query. """ defcallback execute(repo, query_meta :: map, prepared, params :: list(), preprocess | nil, options) :: {integer, [[term]] | nil} | no_return @doc """ Inserts a single new model in the data store. ## Autogenerate The `autogenerate_id` tells if there is a primary key to be autogenerated and, if so, its name, type and value. The type is `:id` or `:binary_id` and the adapter should raise if it cannot handle those types. If the value is `nil`, it means no value was supplied by the user and the database MUST return a new one. `autogenerate_id` also allows drivers to detect if a value was assigned to a primary key that does not support assignment. In this case, `value` will be a non `nil` value. """ defcallback insert(repo, model_meta, fields, autogenerate_id, returning, options) :: {:ok, Keyword.t} | {:invalid, constraints} | no_return @doc """ Updates a single model with the given filters. While `filters` can be any record column, it is expected that at least the primary key (or any other key that uniquely identifies an existing record) be given as a filter. Therefore, in case there is no record matching the given filters, `{:error, :stale}` is returned. ## Autogenerate The `autogenerate_id` tells if there is an autogenerated primary key and if so, its name type and value. The type is `:id` or `:binary_id` and the adapter should raise if it cannot handle those types. If the value is `nil`, it means there is no autogenerate primary key. `autogenerate_id` also allows drivers to detect if a value was assigned to a primary key that does not support assignment. In this case, `value` will be a non `nil` value. """ defcallback update(repo, model_meta, fields, filters, autogenerate_id, returning, options) :: {:ok, Keyword.t} | {:invalid, constraints} | {:error, :stale} | no_return @doc """ Deletes a single model with the given filters. While `filters` can be any record column, it is expected that at least the primary key (or any other key that uniquely identifies an existing record) be given as a filter. Therefore, in case there is no record matching the given filters, `{:error, :stale}` is returned. ## Autogenerate The `autogenerate_id` tells if there is an autogenerated primary key and if so, its name type and value. The type is `:id` or `:binary_id` and the adapter should raise if it cannot handle those types. If the value is `nil`, it means there is no autogenerate primary key. """ defcallback delete(repo, model_meta, filters, autogenerate_id, options) :: {:ok, Keyword.t} | {:invalid, constraints} | {:error, :stale} | no_return end
lib/ecto/adapter.ex
0.909948
0.474814
adapter.ex
starcoder
defmodule SpaceEx.Event do alias SpaceEx.{API, Types, Stream, KRPC, ObjectReference, Protobufs} @bool_type API.Type.parse(%{"code" => "BOOL"}) @moduledoc """ Allows for the server to notify us only when a conditional expression becomes true. Events are an efficient way to wait for a particular condition or state. This could be e.g. waiting for a vessel to reach a given altitude, waiting for a certain time, waiting for a burn to be nearly complete, etc. To set up an event, you will need to create a `SpaceEx.KRPC.Expression` that returns a boolean value. Generally, this is done by issuing one or more "call" expressions (to retrieve useful data), and comparing them with one or more "constant" expressions, using comparison expressions like "equals", "greater than", etc. Complex logic chains may be created with boolean expressions like "and", "or", etc. Events are really just streams that receive their first (and only) update once the condition becomes true. As such, they cannot currently be reused; once an event becomes true, subsequent attempts to wait on the same event will always return immediately, even if the conditional expression is no longer true. """ @doc """ Creates an event from an expression. `expression` should be a `SpaceEx.KRPC.Expression` reference. The expression must return a boolean type. ## Options * `:start` — whether the event stream should be started immediately. If `false`, you can prepare an event before it becomes needed later. Default: `true` * `:rate` — how often the server checks the condition, per second. Default: `0` (unlimited. """ def create(%ObjectReference{} = expression, opts \\ []) do start = Keyword.get(opts, :start, true) rate = Keyword.get(opts, :rate, 0) conn = expression.conn %Protobufs.Event{stream: %Protobufs.Stream{id: stream_id}} = KRPC.add_event(conn, expression) stream = Stream.launch(conn, stream_id, &decode_event/1) if rate != 0 do KRPC.set_stream_rate(conn, stream_id, rate) end if start do KRPC.start_stream(conn, stream_id) end stream end @doc """ Waits for an event to trigger (become true). This will wait until the server reports that the conditional expression has become true. It will block for up to `opts[:timeout]` milliseconds (default: forever, aka `:infinity`), after which it will throw an `exit` signal. You can technically catch this exit signal with `try ... catch :exit, _`, but it's not generally considered good practice to do so. As such, `wait/2` timeouts should generally be reserved for "something has gone badly wrong". If this function is called and returns (i.e. does not time out), then the event is complete. As long as the stream remains alive, future calls will immediately return `true` as well, even if the condition is no longer true. Since events are single-use, by default, this will call `Event.remove/1` before returning. This will allow the underlying stream to unregister itself from the server. You may suppress this behaviour with the `remove: true` option. """ def wait(event, opts \\ []) do remove = Keyword.get(opts, :remove, true) timeout = Keyword.get(opts, :timeout, :infinity) # Don't use Stream.wait here, because it may have already received the # "true" value if the condition was true immediately. The only thing we # care about is that the stream has received its first value. value = Stream.get(event, timeout) if remove, do: remove(event) value end @doc """ Start a previously created event. See `SpaceEx.Stream.start/1`. """ defdelegate start(event), to: SpaceEx.Stream @doc """ Set the polling rate of an event. See `SpaceEx.Stream.set_rate/2`. """ defdelegate set_rate(event, rate), to: SpaceEx.Stream @doc """ Detach from an event, and shut down the underlying stream if possible. See `SpaceEx.Stream.remove/1`. """ defdelegate remove(event), to: SpaceEx.Stream @doc """ Receive a message when an event triggers (becomes true). This is the non-blocking version of `wait/2`. Once the event is complete, a message will be delivered to the calling process. By default, this will also call `Event.remove/1` to clean up the event stream. Because events are effectively just streams, this message will be in the form of `{:stream_result, id, result}` where `id` is the value of `event.id` (or the `:name` option, if specified). You can use `Stream.decode/2` to decode `result`, or you can just check that `result.value == <<1>>` (`true` in wire format) which is almost always the case for event streams. This function behaves identically to `SpaceEx.Stream.subscribe/2`, except that the `:immediate` and `:remove` options are both `true` by default. It's unlikely that you'll want to change either of these, since event streams only ever get a single message. """ def subscribe(event, opts \\ []) do opts = opts |> Keyword.put_new(:immediate, true) |> Keyword.put_new(:remove, true) Stream.subscribe(event, opts) end defp decode_event(value), do: Types.decode(value, @bool_type, nil) end
lib/space_ex/event.ex
0.859413
0.609611
event.ex
starcoder
defmodule GitHubActions.Mix do @moduledoc """ Some functions for handling mix commands in workflows. """ alias GitHubActions.Config alias GitHubActions.ConvCase @doc """ Generates a mix task. ## Examples iex> mix(:compile) "mix compile" """ @spec mix(atom()) :: String.t() def mix(task) when is_atom(task) do mix(task, nil, []) end @doc ~S| Generates a mix task with a sub task or options. The options will be converted to comman line options. The "special" options `:env` and `:os` are used to set `MIX_ENV`. ## Examples iex> mix(:deps, :compile) "mix deps.compile" iex> mix(:credo, strict: true) "mix credo --strict" iex> mix(:credo, strict: false) "mix credo" iex> mix(:sample, arg: 42) "mix sample --arg 42" iex> mix(:compile, env: :test) "MIX_ENV=test mix compile" iex> mix(:compile, env: :test, os: :windows) "set MIX_ENV=test\nmix compile\n" iex> mix(:compile, os: :windows) "mix compile" | @spec mix(atom(), atom() | keyword()) :: String.t() def mix(task, sub_task_or_opts) when is_atom(task) and is_list(sub_task_or_opts) do mix(task, nil, sub_task_or_opts) end def mix(task, sub_task_or_opts) when is_atom(task) and is_atom(sub_task_or_opts) do mix(task, sub_task_or_opts, []) end @doc """ Generates a mix task with a sub task or options. ## Examples iex> mix(:deps, :compile, warnings_as_errors: true) "mix deps.compile --warnings-as-errors" """ def mix(task, sub_task, opts) when is_atom(task) and is_atom(sub_task) and is_list(opts) do {os, opts} = Keyword.pop(opts, :os) {env, opts} = Keyword.pop(opts, :env) case {os, env(env)} do {:windows, nil} -> "mix #{task(task, sub_task)}#{args(opts)}" {:windows, env} -> """ set #{env} mix #{task(task, sub_task)}#{args(opts)} """ {_nix, nil} -> "mix #{task(task, sub_task)}#{args(opts)}" {_nix, env} -> "#{env} mix #{task(task, sub_task)}#{args(opts)}" end end defp task(task, nil), do: "#{task}" defp task(task, sub_task), do: "#{task}.#{sub_task}" defp args(opts) do opts |> Enum.reduce([], fn {key, true}, acc -> ["--#{to_kebab_case(key)}" | acc] {_key, false}, acc -> acc {key, value}, acc -> ["--#{to_kebab_case(key)} #{to_string(value)}" | acc] end) |> Enum.join(" ") |> case do "" -> "" string -> " #{string}" end end defp to_kebab_case(value) do value |> to_string() |> ConvCase.to_kebab() end defp env(target) do case Config.get([:mix, :env]) || target do nil -> nil target -> "MIX_ENV=#{target}" end end end
lib/git_hub_actions/mix.ex
0.861378
0.41327
mix.ex
starcoder
defmodule Astarte.Device.Handler do @moduledoc """ This module defines a behaviour for handling incoming messages directed to an `Astarte.Device`. Modules implementing this behaviour will be executed in a separate process, to avoid blocking the MQTT connection process. """ @doc """ Initialize the state that will be passed as second argument to `handle_message/2`. If this function returns `{:error, reason}`, the handler process is stopped with reason `reason`. """ @callback init_state(args :: term()) :: {:ok, state :: term()} | {:error, reason :: term()} @doc """ Handle incoming data from Astarte. `message` is an `%Astarte.Device.Handler.Message{}`, which contains the following keys: * `realm` - the realm of the device. * `device_id` - the device id of the device. * `interface_name` - the interface name of the incoming message. * `path_tokens` - the path of the incoming message, split in a list of tokens (e.g. `String.split(path, "/", trim: true)`). * `value` - the value contained in the incoming message, already decoded to a standard Elixir type. * `timestamp` - if present, the timestamp contained in the incoming message, nil otherwise `state` is the current state of the handler. It's possible to return an updated state that will be passed to next `handle_message/2` calls. """ @callback handle_message(message :: Astarte.Device.Handler.Message.t(), state :: term()) :: {:ok, new_state :: term()} | {:error, reason :: term()} defmacro __using__(_args) do quote location: :keep do use GenServer require Logger @doc """ Starts the Handler process. """ @spec start_link(args :: term) :: GenServer.on_start() def start_link(args) do GenServer.start_link(__MODULE__, args) end @impl true def init(args) do user_args = Keyword.fetch!(args, :user_args) realm = Keyword.fetch!(args, :realm) device_id = Keyword.fetch!(args, :device_id) case init_state(user_args) do {:ok, user_state} -> state = %{ realm: realm, device_id: device_id, user_state: user_state } {:ok, state} {:error, reason} -> {:stop, reason} end end @impl true def handle_cast({:msg, interface_name, path_tokens, value, timestamp}, state) do alias Astarte.Device.Handler.Message %{ realm: realm, device_id: device_id, user_state: user_state } = state message = %Message{ realm: realm, device_id: device_id, interface_name: interface_name, path_tokens: path_tokens, value: value, timestamp: timestamp } new_state = with {:ok, new_user_state} <- handle_message(message, user_state) do %{state | user_state: new_user_state} else {:error, reason} -> _ = Logger.warn("#{realm}/#{device_id}: error handling message #{inspect(reason)}") state end {:noreply, new_state} end end end end
lib/astarte_device/handler.ex
0.871064
0.434941
handler.ex
starcoder
defmodule Schedule do defstruct [ schedule_id: nil, delay: nil, count: nil, concurrency: nil, func_id: nil, func_name: nil, scheduled_datetime: nil, start_datetime: nil, end_datetime: nil, count_200: nil, # dur_min: nil, # dur_max: nil, # dur_avg: nil, # dur_mean: nil, ] @doc """ Is this scheduled batch complete """ def is_done(%Schedule{end_datetime: nil}), do: false def is_done(%Schedule{}), do: true end defmodule Scheduler do @moduledoc """ Schedule out all of the needed tests in batches. Glossary: - A single poll of a function = "poll" - Several polls of a single function = "batch" - Several batches of a tests = "schedule" Dimensions: - delay: how long since last poll (minimum delay between poll) - count: how many polls to run for the test batch - concurrency: how many polls to run in parallel """ # NOTE: this may need to be moved into configuration @delay [1, 10, 30, 60, 90, 120, 240, 480, 1024] @count [1, 10, 30, 60, 90, 120, 240, 480, 1024] @concurrency [1, 10, 30, 60, 90, 120, 240, 480, 1024] @doc """ Matrix the combinations of factors to build all schedule configurations ## Examples iex> Scheduler.matrix() |> List.first() %Schedule{ count_200: nil, end_datetime: nil, func_id: nil, func_name: nil, scheduled_datetime: nil, start_datetime: nil, concurrency: 1, count: 1, delay: 1} """ def matrix do for delay <- @delay, count <- @count, concurrency <- @concurrency do %Schedule{ delay: delay, count: count, concurrency: concurrency, } end # remove any schedule where the concurrency is higher than the count |> Enum.filter(fn(%{count: count, concurrency: concurrency}) -> count >= concurrency end) end @doc """ Add a function to a Schedule """ def assign_func(%Schedule{} = sched, func_name, func_id) do sched |> Map.merge(%{ func_name: func_name, func_id: func_id, }) end @doc """ Add a schedule_id to a Schedule """ def assign_schedule_id(%Schedule{ func_id: func_id, delay: delay, count: count, concurrency: concurrency, } = sched) do sched |> Map.merge(%{ schedule_id: [ func_id, delay, count, concurrency, ] |> Enum.join("Z") }) end @doc """ Save this schedule to the database """ def save(%Schedule{}) do TODO end end
auditor/lib/scheduler.ex
0.587233
0.463566
scheduler.ex
starcoder
defmodule Sanbase.Cache.RehydratingCache do @moduledoc ~s""" A service that automatically re-runs functions and caches their values at intervals smaller than the TTL so the cache never expires but is just renewed. This service is useful when heavy queries need to be cached without any waiting for recalculation when the cache expires. Example usage: cache the function `f` under the key `:key` for up to 1 hour but refresh the data every 15 minutes. Under expected conditions the value will be refreshed every 15 minutes and the cache will expire only if the function fails to evaluate for more than 1 hour. """ use GenServer alias Sanbase.Cache.RehydratingCache.Store require Logger @name :__rehydrating_cache__ @store_name Store.name(@name) def name(), do: @name @run_interval 10_000 @purge_timeout_interval 30_000 @function_runtime_timeout 5 * 1000 * 60 defguard are_proper_function_arguments(fun, ttl, refresh_time_delta) when is_function(fun, 0) and is_integer(ttl) and ttl > 0 and is_integer(refresh_time_delta) and refresh_time_delta < ttl @doc ~s""" Start the self rehydrating cache service. """ def start_link(opts \\ []) do GenServer.start_link(__MODULE__, opts, name: @name) end def init(opts) do initial_state = %{ init_time: Timex.now(), task_supervisor: Keyword.fetch!(opts, :task_supervisor), functions: %{}, progress: %{}, fails: %{}, waiting: %{} } Process.send_after(self(), :purge_timeouts, @purge_timeout_interval) {:ok, initial_state, {:continue, :initialize}} end # Public API @doc ~s""" Register a new cache function record. The arguments are: - function: Anonymous 0-arity function that computes the value - key: The key the computed value will be associated with - ttl: The maximal time the value will be stored for in seconds - refresh_time_delta: A number of seconds strictly smaller than ttl. Every refresh_time_delta seconds the cache will be recomputed and stored again. The count for ttl starts from 0 again when value is recomputed. """ @spec register_function((() -> any()), any(), pos_integer(), pos_integer()) :: :ok | {:error, :already_registered} def register_function(fun, key, ttl, refresh_time_delta, description \\ nil) when are_proper_function_arguments(fun, ttl, refresh_time_delta) do map = %{ function: fun, key: key, ttl: ttl, refresh_time_delta: refresh_time_delta, description: description } GenServer.call(@name, {:register_function, map}) end @doc ~s""" Get the value associated with key. If the function computing this key is not registered return an error straight away. If the function is registered there are two cases. The timeout cannot be :infinity. 1. The first computation of the value is still going. In this case wait at most timeout seconds for the result. If the result is computed in that time it is returned 2. The value has been already computed and it's returned straight away. Note that if a recomputation is running when get is invoked, the old value is returned. """ @spec get(any(), non_neg_integer(), Keyword.t()) :: {:ok, any()} | {:nocache, {:ok, any()}} | {:error, :timeout} | {:error, :not_registered} def get(key, timeout \\ 30_000, opts \\ []) when is_integer(timeout) and timeout > 0 do try do case Store.get(@store_name, key) do nil -> GenServer.call(@name, {:get, key, timeout}, timeout) |> handle_get_response(opts) {:ok, value} -> {:ok, value} {:nocache, {:ok, _value}} = value -> handle_get_response(value, opts) data -> data end catch :exit, {:timeout, _} -> {:error, :timeout} end end defp handle_get_response(data, opts) do case data do {:ok, value} -> {:ok, value} {:nocache, {:ok, value}} -> if Keyword.get(opts, :return_nocache) do {:nocache, {:ok, value}} else {:ok, value} end {:error, error} -> {:error, error} end end # handle_* callbacks def handle_continue(:initialize, state) do {:noreply, do_run(state)} end def handle_call({:get, key, timeout}, from, state) do # There a few different cases that need to be handled # 1. The value is present in the store - serve it # 2. Computation is in progress - add the caller to the wait list # 3. Computation is not in progress but the function is registered - # re-register the function and add the caller to the wait list # 4. None of the above - the key has not been registered tuple = %{ value: Store.get(@store_name, key), progress: Map.get(state.progress, key), function: Map.get(state.functions, key) } case tuple do %{value: value} when not is_nil(value) -> {:reply, value, state} %{progress: {:in_progress, _task_pid, _started_time_tuple}} -> # If the value is still computing the response will be sent # once the value is computed. This will be reached only on the first # computation. For subsequent calls with :in_progress progress, the # stored value will be available and the previous case will be matched new_state = do_fill_waiting_list(state, key, from, timeout) {:noreply, new_state} %{progress: :failed} -> # If progress :failed it will get started on the next run new_state = do_fill_waiting_list(state, key, from, timeout) {:noreply, new_state} %{function: fun_map} when is_map(fun_map) -> # Reaching here is unexpected. If we reached here the function is # registered but for some reason it has not started executing because # there's no stored value and no progress new_state = state |> do_register_function(fun_map) |> do_fill_waiting_list(key, from, timeout) {:noreply, new_state} _ -> {:reply, {:error, :not_registered}, state} end end def handle_call({:register_function, %{key: key} = fun_map}, _from, state) do case Map.has_key?(state.functions, key) do true -> {:reply, {:error, :already_registered}, state} false -> new_state = do_register_function(state, fun_map) {:reply, :ok, new_state} end end def handle_info(:run, state) do new_state = do_run(state) {:noreply, new_state} end def handle_info({:store_result, fun_map, data}, state) do %{progress: progress, waiting: waiting, functions: functions} = state %{key: key, refresh_time_delta: refresh_time_delta, ttl: ttl} = fun_map now_unix = Timex.now() |> DateTime.to_unix() case data do {:error, _} -> # Can be reevaluated immediately new_progress = Map.put(progress, key, now_unix) {:noreply, %{state | progress: new_progress}} # Store the result but let it be reevaluated immediately on the next run. # This is to not calculate a function that always returns :nocache on # every run. {:nocache, {:ok, _value}} = result -> {reply_to_list, new_waiting} = Map.pop(waiting, key, []) reply_to_waiting(reply_to_list, result) new_fun_map = Map.update(fun_map, :nocache_refresh_count, 1, &(&1 + 1)) new_functions = Map.put(functions, key, new_fun_map) new_progress = Map.put(progress, key, now_unix) Store.put(@store_name, key, result, ttl) {:noreply, %{state | progress: new_progress, waiting: new_waiting, functions: new_functions}} # Put the value in the store. Send the result to the waiting callers. {:ok, _value} = result -> {reply_to_list, new_waiting} = Map.pop(waiting, key, []) reply_to_waiting(reply_to_list, result) new_fun_map = Map.update(fun_map, :refresh_count, 1, &(&1 + 1)) new_functions = Map.put(functions, key, new_fun_map) new_progress = Map.put(progress, key, now_unix + refresh_time_delta) Store.put(@store_name, key, result, ttl) {:noreply, %{state | progress: new_progress, waiting: new_waiting, functions: new_functions}} # The function returned malformed result. Send error to the waiting callers. _ -> result = {:error, :malformed_result} {reply_to_list, new_waiting} = Map.pop(waiting, key, []) reply_to_waiting(reply_to_list, result) new_progress = Map.put(progress, key, now_unix + refresh_time_delta) Store.put(@store_name, key, {:error, :malformed_result}, ttl) {:noreply, %{state | progress: new_progress, waiting: new_waiting}} end end def handle_info(:purge_timeouts, state) do new_state = do_purge_timeouts(state) {:noreply, new_state} end def handle_info({ref, _}, state) when is_reference(ref) do {:noreply, state} end def handle_info({:DOWN, _ref, _, _pid, :normal}, state) do {:noreply, state} end def handle_info({:DOWN, _ref, _, pid, reason}, state) do %{progress: progress, fails: fails} = state new_state = case Enum.find(progress, fn {_k, v} -> match?({:in_progress, ^pid, _}, v) end) do {k, _v} -> new_progress = Map.update!(progress, k, fn _ -> :failed end) new_fails = Map.update(fails, k, {1, reason}, fn {count, _last_reason} -> {count + 1, reason} end) %{state | progress: new_progress, fails: new_fails} nil -> state end {:noreply, new_state} end def handle_info(msg, state) do Logger.error("[Rehydrating Cache] Got unexpected message: #{inspect(msg)}") {:noreply, state} end # Private functions defp do_register_function(state, fun_map) do %{key: key} = fun_map fun_map = fun_map |> Map.merge(%{ registered_at: Timex.now(), refresh_count: 0, nocache_refresh_count: 0 }) %{pid: pid} = run_function(self(), fun_map, state.task_supervisor) now = Timex.now() new_progress = Map.put(state.progress, key, {:in_progress, pid, {now, DateTime.to_unix(now)}}) new_functions = Map.put(state.functions, key, fun_map) %{state | functions: new_functions, progress: new_progress} end defp do_purge_timeouts(state) do %{waiting: waiting} = state now = Timex.now() new_waiting = Enum.reduce(waiting, %{}, fn {key, waiting_for_key}, acc -> # Remove from the waiting list all timed out records. These are the `call`s # that are no longer waiting for response. still_waiting_for_key = waiting_for_key |> Enum.filter(fn {_from, send_before} -> DateTime.compare(send_before, now) != :lt end) case still_waiting_for_key do [] -> acc _ -> Map.put(acc, key, still_waiting_for_key) end end) Process.send_after(self(), :purge_timeouts, @purge_timeout_interval) %{state | waiting: new_waiting} end defp do_run(state) do now = Timex.now() now_unix = now |> DateTime.to_unix() %{progress: progress, functions: functions, task_supervisor: task_supervisor} = state run_fun_update_progress = fn prog, key, fun_map -> %{pid: pid} = run_function(self(), fun_map, task_supervisor) Map.put(prog, key, {:in_progress, pid, {now, DateTime.to_unix(now)}}) end new_progress = Enum.reduce(functions, %{}, fn {key, fun_map}, acc -> case Map.get(progress, key, now_unix) do :failed -> # Task execution failed, retry immediatelly run_fun_update_progress.(progress, key, fun_map) run_after_unix when is_integer(run_after_unix) and now_unix >= run_after_unix -> # It is time to execute the function again run_fun_update_progress.(progress, key, fun_map) {:in_progress, pid, {_started_datetime, started_unix}} -> case Process.alive?(pid) do false -> # If the process is dead but for some reason the progress is not # changed to some timestamp or to :failed, we rerun it run_fun_update_progress.(progress, key, fun_map) true -> if now_unix - started_unix > @function_runtime_timeout do # Process computing the function is alive but it is taking # too long, maybe something is stuck. Restart the computation Process.exit(pid, :kill) run_fun_update_progress.(progress, key, fun_map) else progress end end nil -> # No recorded progress. Should not happend. run_fun_update_progress.(progress, key, fun_map) run_after_unix when is_integer(run_after_unix) and now_unix < run_after_unix -> # It's still not time to reevaluate the function again Map.put(acc, key, run_after_unix) end end) Process.send_after(self(), :run, @run_interval) %{state | progress: new_progress} end defp reply_to_waiting([], _), do: :ok defp reply_to_waiting(from_list, value) do now = Timex.now() Enum.each(from_list, fn {from, send_before} -> # Do not reply in case of timeout case DateTime.compare(send_before, now) do :lt -> :ok _ -> GenServer.reply(from, value) end end) end defp do_fill_waiting_list(state, key, from, timeout) do elem = {from, Timex.shift(Timex.now(), milliseconds: timeout)} new_waiting = Map.update(state.waiting, key, [elem], fn list -> [elem | list] end) %{state | waiting: new_waiting} end defp run_function(pid, fun_map, task_supervisor) do Task.Supervisor.async_nolink(task_supervisor, fn -> %{function: fun} = fun_map result = fun.() Process.send(pid, {:store_result, fun_map, result}, []) end) end end
lib/sanbase/cache/rehydrating_cache/rehydrating_cache.ex
0.819749
0.564579
rehydrating_cache.ex
starcoder
defmodule SymbolicExpression.Canonical.Writer do @doc """ Converts the abstract representation of an s-expression into a string holding an s-expression in canonical form. Returns `{:ok, result}` on success, `{:error, reason}` otherwise. ## Example iex> alias SymbolicExpression.Canonical.Writer iex> Writer.write [1, 2, 3] {:ok, "(1:11:21:3)"} iex> Writer.write [%{invalid: true}] {:error, :bad_arg} """ def write(exp) when is_list(exp) do try do {:ok, write!(exp)} rescue _ in [ArgumentError] -> {:error, :bad_arg} end end @doc """ Like `write/1` except throws an exception on error. ## Example iex> alias SymbolicExpression.Canonical.Writer iex> Writer.write! [1, 2, 3] "(1:11:21:3)" iex> Writer.write! [[1, 2, 3], "This is a test", :atom, []] "((1:11:21:3)[24:text/plain;charset=utf-8]14:This is a test4:atom())" iex> try do iex> Writer.write! [%{invalid: true}] iex> rescue iex> _ in [ArgumentError] -> iex> :exception_raised iex> end :exception_raised """ def write!(exp) when is_list(exp), do: _write!(exp, "") defp _write!([head | tail], result), do: _write!(tail, result <> format(head)) defp _write!([], result), do: result |> String.trim |> (&"(#{&1})").() # Catch all for errors. defp _write!(exp, result) do raise ArgumentError, message: """ Invalid s-expression with remaining expression: #{inspect exp} current result: #{inspect result} """ end defp format(x) when is_list(x), do: _write!(x, "") defp format(x) when is_atom(x), do: x |> Atom.to_string |> _format defp format(x) when is_integer(x), do: x |> Integer.to_string |> _format defp format(x) when is_float(x) do :erlang.float_to_binary(x, [:compact, {:decimals, 8}]) end defp format(x) when is_binary(x) do "[24:text/plain;charset=utf-8]#{_format x}" end defp format(x) do raise ArgumentError, message: """ Unable to format "#{inspect x}" for s-expression. """ end defp _format(string) when is_binary(string) do "#{String.length string}:#{string}" end end
lib/symbolic_expression/canonical/writer.ex
0.821832
0.504455
writer.ex
starcoder
defmodule NervesjpBasis.Sensor.Aht20 do @moduledoc """ Documentation for `Aht20`. 温湿度センサAHT20の制御モジュール """ # 関連するライブラリを読み込み require Logger use Bitwise alias Circuits.I2C # 定数 ## i2c-1 for Raspberry Pi, i2c-2 for BBB/BBG Board @i2c_bus "i2c-1" ## AHT32 I2C Addr @i2c_addr 0x38 # 定数 ## I2C通信待機時間(ms) ## (50msくらいまでOK。40ms以下になると測定に失敗する) @i2c_delay 100 ## 換算定数の事前計算 @two_pow_20 :math.pow(2, 20) @doc """ 温度を表示 ## Examples iex> Aht20.print_temp > temp (degree Celsius) 22.1 :ok """ def print_temp() do IO.puts(" > temp: #{temp()} (degree Celsius)") end # 温度の値を取得 defp temp do # AHT20から読み出し {:ok, {temp, _}} = read_from_aht20() temp end @doc """ 湿度を表示 ## Examples iex> Aht20.print_humi > humi (%) 41.2 :ok """ def print_humi() do IO.puts(" > humi: #{humi()} (%)") end # 湿度の値を取得 defp humi do # AHT20から読み出し {:ok, {_, humi}} = read_from_aht20() humi end @doc """ AHT20から温度・湿度を取得 ## Examples iex> Aht20.read_from_ath20 {:ok, {22.4, 40.3}} {:error, "Sensor is not connected"} """ def read_from_aht20() do # I2Cを開く {:ok, ref} = I2C.open(@i2c_bus) # AHT20を初期化する I2C.write(ref, @i2c_addr, <<0xBE, 0x08, 0x00>>) # 処理完了まで一定時間待機 Process.sleep(@i2c_delay) # 温度・湿度を読み出しコマンドを送る I2C.write(ref, @i2c_addr, <<0xAC, 0x33, 0x00>>) # 処理完了まで一定時間待機 Process.sleep(@i2c_delay) # 温度・湿度を読み出す ret = case I2C.read(ref, @i2c_addr, 7) do # 正常に値が取得できたときは温度・湿度の値をタプルで返す {:ok, val} -> {:ok, val |> convert()} # センサからの応答がないときはメッセージを返す {:error, :i2c_nak} -> {:error, "Sensor is not connected"} # その他のエラーのときもメッセージを返す _ -> {:error, "An error occurred"} end # I2Cを閉じる I2C.close(ref) # 結果を返す ret end #生データを温度と湿度の値に変換 ## Parameters ## - val: POSTする内容 defp convert(src) do # バイナリデータ部をビット長でパターンマッチ # <<0:state, 1:humi1, 2:humi2, 3:humi3/temp1, 4:temp2, 5:temp3, 6:crc>> <<_state::8, raw_humi::20, raw_temp::20, _crc::8>> = src # 湿度に換算する計算(データシートの換算方法に準じた) humi = Float.round(raw_humi / @two_pow_20 * 100.0, 1) # 温度に換算する計算(データシートの換算方法に準じた) temp = Float.round(raw_temp / @two_pow_20 * 200.0 - 50.0, 1) # 温度と湿度をタプルにして返す {temp, humi} end end
lib/sensor/aht20.ex
0.538255
0.49469
aht20.ex
starcoder
defmodule Farmbot.BotState.Transport.HTTP do @moduledoc """ RESTful API for accessing internal Farmbot state. # Accessing the API A developer should be able to access the REST API at `http://<my_farmbot_id>:27347/api/v1/`. The calls will require an authentication token. See the [API docs](https://github.com/farmbot/Farmbot-Web-App#q-how-can-i-generate-an-api-token) for information about generating a token. Access to the local api should be the same as accessing the cloud API. You will need to have an HTTP header: `Authorization`:`Bearer <long encrypted token>` Each of the routes will be described below. * GET `/api/v1/bot/state` - returns the bot's current state. * POST `/api/v1/celery_script` - execute celery script node. """ use GenStage alias Farmbot.BotState.Transport.HTTP.Router alias Farmbot.System.ConfigStorage @port 27_347 @doc "Subscribe to events." def subscribe do GenStage.call(__MODULE__, :subscribe) end @doc "Unsubscribe." def unsubscribe do GenStage.call(__MODULE__, :unsubscribe) end def public_key do GenStage.call(__MODULE__, :public_key) end @doc false def start_link do GenStage.start_link(__MODULE__, [], [name: __MODULE__]) end def stop(reason \\ :normal) do if Process.whereis(__MODULE__) do GenStage.stop(__MODULE__, reason) else :ok end end def init([]) do s = ConfigStorage.get_config_value(:string, "authorization", "server") req = {'#{s}/api/public_key', []} {:ok, {_, _, body}} = :httpc.request(:get, req, [], [body_format: :binary]) public_key = body |> JOSE.JWK.from_pem # FIXME(Connor) The router should probably # be put in an externally supervised module.. protocol_options = [ idle_timeout: :infinity, shutdown_timeout: :infinity, inactivity_timeout: :infinity, shutdown_timeout: :infinity, request_timeout: :infinity ] opts = [ port: @port, acceptors: 2, dispatch: [cowboy_dispatch()], protocol_options: protocol_options ] case Plug.Adapters.Cowboy2.http(Router, [], opts) do {:ok, web} -> state = %{web: web, bot_state: nil, sockets: [], public_key: public_key} Process.link(state.web) {:consumer, state, [subscribe_to: [Farmbot.BotState, Farmbot.Logger]]} {:error, {:already_started, web}} -> state = %{web: web, bot_state: nil, sockets: [], public_key: public_key} Process.link(state.web) {:consumer, state, [subscribe_to: [Farmbot.BotState, Farmbot.Logger]]} err -> err end end def handle_events(events, {pid, _}, state) do dispatch Process.info(pid)[:registered_name], events, state end def handle_call(:subscribe, {pid, _ref}, state) do {:reply, :ok, [], %{state | sockets: [pid | state.sockets]}} end def handle_call(:unsubscribe, {pid, _ref}, state) do {:reply, :ok, [], %{state | sockets: List.delete(state.sockets, pid)}} end def handle_call(:public_key, _, state) do {:reply, {:ok, state.public_key}, [], state} end defp dispatch(Farmbot.BotState = dispatcher, events, state) do bot_state = List.last(events) for socket <- state.sockets do send socket, {dispatcher, bot_state} end {:noreply, [], %{state | bot_state: bot_state}} end defp dispatch(Farmbot.Logger = dispatcher, logs, state) do for socket <- state.sockets do send socket, {dispatcher, logs} end {:noreply, [], state} end defp cowboy_dispatch do {:_, [ # {"/ws", SocketHandler, []}, {:_, Plug.Adapters.Cowboy2.Handler, {Router, []}}, ] } end end
lib/farmbot/bot_state/transport/http/http.ex
0.607197
0.400134
http.ex
starcoder
defmodule OptionParser do @doc """ Parses the argv and returns one tuple with parsed options and the arguments. ## Examples iex> OptionParser.parse(["--debug"]) { [debug: true], [] } iex> OptionParser.parse(["--source", "lib"]) { [source: "lib"], [] } iex> OptionParser.parse(["--source", "lib", "test/enum_test.exs", "--verbose"]) { [source: "lib", verbose: true], ["test/enum_test.exs"] } ## Aliases A set of aliases can be given as second argument: iex> OptionParser.parse(["-d"], aliases: [d: :debug]) { [debug: true], [] } ## Switches Extra information about switches can be given as argument too. This is useful in order to say a switch must behave as a boolean or if duplicated switches should be kept, overriden or accumulated. The following types are supported: * `:boolean` - Mark the given switch as boolean. Boolean switches never consumes the following value unless it is true or false; The following extra options are supported: * `:keep` - Keep duplicated items in the list instead of overriding; Examples: iex> OptionParser.parse(["--unlock", "path/to/file"], switches: [unlock: :boolean]) { [unlock: true], ["path/to/file"] } iex> OptionParser.parse(["--unlock", "false", "path/to/file"], switches: [unlock: :boolean]) { [unlock: false], ["path/to/file"] } ## Negation switches Any switches starting with `--no-` are always considered to be booleans and never parse the next value: iex> OptionParser.parse(["--no-op", "path/to/file"]) { [no_op: true], ["path/to/file"] } """ def parse(argv, opts // []) when is_list(argv) and is_list(opts) do parse(argv, opts, true) end @doc """ Similar to parse but only parses the head of the argv. I.e. as soon as it finds a non switch, it stops parsing. Check `parse/2` for more info. ## Example iex> OptionParser.parse_head(["--source", "lib", "test/enum_test.exs", "--verbose"]) { [source: "lib"], ["test/enum_test.exs", "--verbose"] } """ def parse_head(argv, opts // []) when is_list(argv) and is_list(opts) do parse(argv, opts, false) end ## Helpers defp parse(argv, opts, bool) do aliases = opts[:aliases] || [] switches = opts[:switches] || [] parse(argv, aliases, switches, bool) end defp parse(argv, aliases, switches, all) do parse(argv, aliases, switches, [], [], all) end defp parse(["-" <> option|t], aliases, switches, dict, args, all) do { option, value } = normalize_option(option, aliases) kind = switches[option] if value == nil do { value, t } = if is_switch_a? :boolean, kind do boolean_from_tail(t) else value_from_tail(t) end end dict = store_option dict, option, value, kind parse(t, aliases, switches, dict, args, all) end defp parse([h|t], aliases, switches, dict, args, true) do parse(t, aliases, switches, dict, [h|args], true) end defp parse([], _, switches, dict, args, true) do { reverse_dict(dict, switches), Enum.reverse(args) } end defp parse(value, _, switches, dict, _args, false) do { reverse_dict(dict, switches), value } end defp boolean_from_tail([h|t]) when h in ["false", "true"], do: { h, t } defp boolean_from_tail(t) , do: { true, t } defp value_from_tail(["-" <> _|_] = t), do: { true, t } defp value_from_tail([h|t]), do: { h, t } defp value_from_tail([]), do: { true, [] } defp store_option(dict, option, value, switches) when value in ["true", "false"] do store_option dict, option, binary_to_atom(value), switches end defp store_option(dict, option, value, kind) do if is_switch_a? :keep, kind do [{ option, value }|dict] else [{ option, value }|Keyword.delete(dict, option)] end end defp reverse_dict(dict, switches) do switches = lc { k, v } inlist switches, is_switch_a?(:boolean, v), not Keyword.has_key?(dict, k), do: { k, false } Enum.reverse switches ++ dict end defp normalize_option(<<?-, option :: binary>>, aliases) do normalize_option(option, aliases) end defp normalize_option(option, aliases) do { option, value } = split_option(option) if is_no?(option), do: value = true atom = option |> to_underscore |> binary_to_atom { aliases[atom] || atom, value } end defp split_option(option) do case :binary.split(option, "=") do [h] -> { h, nil } [h|t] -> { h, Enum.join(t, "=") } end end defp to_underscore(option) do bc <<c>> inbits option, do: << if c == ?-, do: ?_, else: c >> end defp is_no?("no-" <> _), do: true defp is_no?(_), do: false defp is_switch_a?(kind, list) when is_list(list), do: kind in list defp is_switch_a?(kind, kind), do: true defp is_switch_a?(_, _), do: false end
lib/elixir/lib/option_parser.ex
0.73914
0.439146
option_parser.ex
starcoder
defmodule AWS.ApplicationInsights do @moduledoc """ Amazon CloudWatch Application Insights Amazon CloudWatch Application Insights is a service that helps you detect common problems with your applications. It enables you to pinpoint the source of issues in your applications (built with technologies such as Microsoft IIS, .NET, and Microsoft SQL Server), by providing key insights into detected problems. After you onboard your application, CloudWatch Application Insights identifies, recommends, and sets up metrics and logs. It continuously analyzes and correlates your metrics and logs for unusual behavior to surface actionable problems with your application. For example, if your application is slow and unresponsive and leading to HTTP 500 errors in your Application Load Balancer (ALB), Application Insights informs you that a memory pressure problem with your SQL Server database is occurring. It bases this analysis on impactful metrics and log errors. """ alias AWS.Client alias AWS.Request def metadata do %AWS.ServiceMetadata{ abbreviation: "Application Insights", api_version: "2018-11-25", content_type: "application/x-amz-json-1.1", credential_scope: nil, endpoint_prefix: "applicationinsights", global?: false, protocol: "json", service_id: "Application Insights", signature_version: "v4", signing_name: "applicationinsights", target_prefix: "EC2WindowsBarleyService" } end @doc """ Adds an application that is created from a resource group. """ def create_application(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "CreateApplication", input, options) end @doc """ Creates a custom component by grouping similar standalone instances to monitor. """ def create_component(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "CreateComponent", input, options) end @doc """ Adds an log pattern to a `LogPatternSet`. """ def create_log_pattern(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "CreateLogPattern", input, options) end @doc """ Removes the specified application from monitoring. Does not delete the application. """ def delete_application(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DeleteApplication", input, options) end @doc """ Ungroups a custom component. When you ungroup custom components, all applicable monitors that are set up for the component are removed and the instances revert to their standalone status. """ def delete_component(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DeleteComponent", input, options) end @doc """ Removes the specified log pattern from a `LogPatternSet`. """ def delete_log_pattern(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DeleteLogPattern", input, options) end @doc """ Describes the application. """ def describe_application(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeApplication", input, options) end @doc """ Describes a component and lists the resources that are grouped together in a component. """ def describe_component(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeComponent", input, options) end @doc """ Describes the monitoring configuration of the component. """ def describe_component_configuration(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeComponentConfiguration", input, options) end @doc """ Describes the recommended monitoring configuration of the component. """ def describe_component_configuration_recommendation(%Client{} = client, input, options \\ []) do Request.request_post( client, metadata(), "DescribeComponentConfigurationRecommendation", input, options ) end @doc """ Describe a specific log pattern from a `LogPatternSet`. """ def describe_log_pattern(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeLogPattern", input, options) end @doc """ Describes an anomaly or error with the application. """ def describe_observation(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeObservation", input, options) end @doc """ Describes an application problem. """ def describe_problem(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeProblem", input, options) end @doc """ Describes the anomalies or errors associated with the problem. """ def describe_problem_observations(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "DescribeProblemObservations", input, options) end @doc """ Lists the IDs of the applications that you are monitoring. """ def list_applications(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListApplications", input, options) end @doc """ Lists the auto-grouped, standalone, and custom components of the application. """ def list_components(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListComponents", input, options) end @doc """ Lists the INFO, WARN, and ERROR events for periodic configuration updates performed by Application Insights. Examples of events represented are: * INFO: creating a new alarm or updating an alarm threshold. * WARN: alarm not created due to insufficient data points used to predict thresholds. * ERROR: alarm not created due to permission errors or exceeding quotas. """ def list_configuration_history(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListConfigurationHistory", input, options) end @doc """ Lists the log pattern sets in the specific application. """ def list_log_pattern_sets(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListLogPatternSets", input, options) end @doc """ Lists the log patterns in the specific log `LogPatternSet`. """ def list_log_patterns(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListLogPatterns", input, options) end @doc """ Lists the problems with your application. """ def list_problems(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListProblems", input, options) end @doc """ Retrieve a list of the tags (keys and values) that are associated with a specified application. A *tag* is a label that you optionally define and associate with an application. Each tag consists of a required *tag key* and an optional associated *tag value*. A tag key is a general label that acts as a category for more specific tag values. A tag value acts as a descriptor within a tag key. """ def list_tags_for_resource(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "ListTagsForResource", input, options) end @doc """ Add one or more tags (keys and values) to a specified application. A *tag* is a label that you optionally define and associate with an application. Tags can help you categorize and manage application in different ways, such as by purpose, owner, environment, or other criteria. Each tag consists of a required *tag key* and an associated *tag value*, both of which you define. A tag key is a general label that acts as a category for more specific tag values. A tag value acts as a descriptor within a tag key. """ def tag_resource(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "TagResource", input, options) end @doc """ Remove one or more tags (keys and values) from a specified application. """ def untag_resource(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "UntagResource", input, options) end @doc """ Updates the application. """ def update_application(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "UpdateApplication", input, options) end @doc """ Updates the custom component name and/or the list of resources that make up the component. """ def update_component(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "UpdateComponent", input, options) end @doc """ Updates the monitoring configurations for the component. The configuration input parameter is an escaped JSON of the configuration and should match the schema of what is returned by `DescribeComponentConfigurationRecommendation`. """ def update_component_configuration(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "UpdateComponentConfiguration", input, options) end @doc """ Adds a log pattern to a `LogPatternSet`. """ def update_log_pattern(%Client{} = client, input, options \\ []) do Request.request_post(client, metadata(), "UpdateLogPattern", input, options) end end
lib/aws/generated/application_insights.ex
0.906849
0.436082
application_insights.ex
starcoder
defmodule Rexbug.Translator do @moduledoc """ Utility module for translating Elixir syntax to the one expected by `:redbug`. You probably don't need to use it directly. """ @valid_guard_functions [ :is_atom, :is_binary, :is_bitstring, :is_boolean, :is_float, :is_function, :is_integer, :is_list, :is_map, :is_nil, :is_number, :is_pid, :is_port, :is_reference, :is_tuple, :abs, :bit_size, :byte_size, :hd, :length, :map_size, :round, :tl, :trunc, :tuple_size, # erlang guard :size ] @infix_guards_mapping %{ # comparison :== => :==, :!= => :"/=", :=== => :"=:=", :!== => :"=/=", :> => :>, :>= => :>=, :< => :<, :<= => :"=<" } @valid_infix_guards Map.keys(@infix_guards_mapping) @infix_guard_combinators_mapping %{ :and => :andalso, :or => :orelse } @valid_infix_guard_combinators Map.keys(@infix_guard_combinators_mapping) # =========================================================================== # Public functions # =========================================================================== # --------------------------------------------------------------------------- # Translating trace pattern # --------------------------------------------------------------------------- @spec translate(Rexbug.trace_pattern()) :: {:ok, charlist | atom} | {:ok, [charlist | atom]} | {:error, term} @doc """ Translates the Elixir trace pattern(s) (understood by Rexbug) to the Erlang trace pattern charlist(s) understood by `:redbug`. The translated version is not necessarily the cleanest possible, but should be correct and functionally equivalent. ## Example iex> import Rexbug.Translator iex> translate(":cowboy.start_clear/3") {:ok, '\\'cowboy\\':\\'start_clear\\'/3'} iex> translate("MyModule.do_sth(_, [pretty: true])") {:ok, '\\'Elixir.MyModule\\':\\'do_sth\\'(_, [{\\'pretty\\', true}])'} """ def translate(s) when s in [:send, "send"], do: {:ok, :send} def translate(r) when r in [:receive, "receive"], do: {:ok, :receive} def translate(patterns) when is_list(patterns) do patterns |> Enum.map(&translate/1) |> collapse_errors() end def translate(trace_pattern) when is_binary(trace_pattern) do with {mfag, actions} = split_to_mfag_and_actions!(trace_pattern), {:ok, quoted} <- Code.string_to_quoted(mfag), {:ok, {mfa, guards}} = split_quoted_into_mfa_and_guards(quoted), {:ok, {mfa, arity}} = split_mfa_into_mfa_and_arity(mfa), {:ok, {module, function, args}} = split_mfa_into_module_function_and_args(mfa), :ok <- validate_mfaa(module, function, args, arity), {:ok, translated_module} <- translate_module(module), {:ok, translated_function} <- translate_function(function), {:ok, translated_args} <- translate_args(args), {:ok, translated_arity} <- translate_arity(arity), {:ok, translated_guards} <- translate_guards(guards), translated_actions = translate_actions!(actions) do translated = case translated_arity do :any -> # no args, no arity "#{translated_module}#{translated_function}#{translated_actions}" arity when is_integer(arity) -> # no args, arity present "#{translated_module}#{translated_function}/#{arity}#{translated_actions}" nil -> # args present, no arity "#{translated_module}#{translated_function}#{translated_args}#{translated_guards}#{ translated_actions }" end {:ok, String.to_charlist(translated)} end end def translate(_), do: {:error, :invalid_trace_pattern_type} @doc false def split_to_mfag_and_actions!(trace_pattern) do {mfag, actions} = case String.split(trace_pattern, " ::", parts: 2) do [mfag, actions] -> {mfag, actions} [mfag] -> {mfag, ""} end {String.trim(mfag), String.trim(actions)} end @spec translate_guards(term) :: {:ok, String.t()} | {:error, term} defp translate_guards(nil), do: {:ok, ""} defp translate_guards(els) do _translate_guards(els) |> map_success(fn guards -> " when #{guards}" end) end # --------------------------------------------------------------------------- # Translating options # --------------------------------------------------------------------------- @spec translate_options(Keyword.t()) :: {:ok, Keyword.t()} | {:error, term} @doc """ Translates the options to be passed to `Rexbug.start/2` to the format expected by `:redbug` Relevant values passed as strings will be converted to charlists. """ def translate_options(options) when is_list(options) do options |> Enum.map(&translate_option/1) |> collapse_errors() end def translate_options(_), do: {:error, :invalid_options} # =========================================================================== # Private functions # =========================================================================== @binary_to_charlist_options [:file, :print_file] defp translate_option({file_option, filename}) when file_option in @binary_to_charlist_options and is_binary(filename) do {:ok, {file_option, String.to_charlist(filename)}} end defp translate_option({k, v}) do {:ok, {k, v}} end defp translate_option(_), do: {:error, :invalid_options} @spec collapse_errors([{:ok, term} | {:error, term}]) :: {:ok, [term]} | {:error, term} defp collapse_errors(tuples) do # we could probably play around with some monads for this first_error = Enum.find(tuples, :no_error_to_collapse, fn res -> !match?({:ok, _}, res) end) case first_error do :no_error_to_collapse -> results = Enum.map(tuples, fn {:ok, res} -> res end) {:ok, results} err -> err end end defp split_quoted_into_mfa_and_guards({:when, _line, [mfa, guards]}) do {:ok, {mfa, guards}} end defp split_quoted_into_mfa_and_guards(els) do {:ok, {els, nil}} end defp split_mfa_into_mfa_and_arity({:/, _line, [mfa, arity]}) do {:ok, {mfa, arity}} end defp split_mfa_into_mfa_and_arity(els) do {:ok, {els, nil}} end defp split_mfa_into_module_function_and_args({{:., _l1, [module, function]}, _l2, args}) do {:ok, {module, function, args}} end defp split_mfa_into_module_function_and_args(els) do {:ok, {els, nil, nil}} end # handling fringe cases that shouldn't happen defp validate_mfaa(module, function, args, arity) defp validate_mfaa(nil, _, _, _), do: {:error, :missing_module} defp validate_mfaa(_, nil, args, _) when not (args in [nil, []]), do: {:error, :missing_function} defp validate_mfaa(_, nil, _, arity) when arity != nil, do: {:error, :missing_function} defp validate_mfaa(_, _, args, arity) when not (args in [nil, []]) and arity != nil do {:error, :both_args_and_arity_provided} end defp validate_mfaa(_, _, _, _), do: :ok defp translate_module({:__aliases__, _line, elixir_module}) when is_list(elixir_module) do joined = [:"Elixir" | elixir_module] |> Enum.map(&Atom.to_string/1) |> Enum.join(".") {:ok, "'#{joined}'"} end defp translate_module(erlang_mod) when is_atom(erlang_mod) do {:ok, "\'#{Atom.to_string(erlang_mod)}\'"} end defp translate_module(module), do: {:error, {:invalid_module, module}} defp translate_function(nil) do {:ok, ""} end defp translate_function(f) when is_atom(f) do {:ok, ":'#{Atom.to_string(f)}'"} end defp translate_function(els) do {:error, {:invalid_function, els}} end defp translate_args(nil), do: {:ok, ""} defp translate_args(args) when is_list(args) do args |> Enum.map(&translate_arg/1) |> collapse_errors() |> map_success(&Enum.join(&1, ", ")) |> map_success(fn res -> "(#{res})" end) end defp translate_args(els) do {:error, {:invalid_args, els}} end defp translate_arg(nil), do: {:ok, "nil"} defp translate_arg(boolean) when is_boolean(boolean) do {:ok, "#{boolean}"} end defp translate_arg(arg) when is_atom(arg) do {:ok, "'#{Atom.to_string(arg)}'"} end defp translate_arg(string) when is_binary(string) do # TODO: more strict ASCII checking here if String.printable?(string) && byte_size(string) == String.length(string) do {:ok, "<<\"#{string}\">>"} else translate_arg({:<<>>, [line: 1], [string]}) end end defp translate_arg({:<<>>, _line, contents}) when is_list(contents) do contents |> Enum.map(&translate_binary_element/1) |> collapse_errors() |> map_success(&Enum.join(&1, ", ")) |> map_success(fn res -> "<<#{res}>>" end) end # defp translate_arg(bs) when is_bitstring(bs) do # :error # end defp translate_arg(ls) when is_list(ls) do ls |> Enum.map(&translate_arg/1) |> collapse_errors() |> map_success(fn elements -> "[#{Enum.join(elements, ", ")}]" end) end defp translate_arg({:-, _line, [num]}) when is_integer(num) do with {:ok, translated_num} = translate_arg(num), do: {:ok, "-#{translated_num}"} end defp translate_arg(num) when is_integer(num) do {:ok, "#{num}"} end defp translate_arg(f) when is_float(f) do {:error, {:bad_type, :float}} end defp translate_arg({:%{}, _line, kvs}) when is_list(kvs) do {ks, vs} = Enum.unzip(kvs) if Enum.any?(ks, &is_variable/1) do {:error, :variable_in_map_key} else key_args = ks |> Enum.map(&translate_arg/1) |> collapse_errors() value_args = vs |> Enum.map(&translate_arg/1) |> collapse_errors() [key_args, value_args] |> collapse_errors |> map_success(fn [keys, values] -> middle = keys |> Enum.zip(values) |> Enum.map(fn {k, v} -> "#{k} => #{v}" end) |> Enum.join(", ") "\#{#{middle}}" end) end end # there's a catch here: # iex(12)> Code.string_to_quoted!("{1,2,3}") # {:{}, [line: 1], [1, 2, 3]} # iex(13)> Code.string_to_quoted!("{1,2}") # {1, 2} defp translate_arg({:{}, _line, tuple_elements}) do tuple_elements |> Enum.map(&translate_arg/1) |> collapse_errors() |> map_success(fn elements -> "{#{Enum.join(elements, ", ")}}" end) end # the literally represented 2-tuples defp translate_arg({x, y}), do: translate_arg({:{}, [line: 1], [x, y]}) # other atoms are just variable names defp translate_arg({var, _line, nil}) when is_atom(var) do var |> Atom.to_string() |> String.capitalize() |> wrap_in_ok() end defp translate_arg(arg) do {:error, {:invalid_arg, arg}} end defp is_variable({var, _line, nil}) when is_atom(var), do: true defp is_variable(_), do: false defp translate_binary_element(i) when is_integer(i) do {:ok, "#{i}"} end defp translate_binary_element(s) when is_binary(s) do res = s |> :binary.bin_to_list() |> Enum.join(", ") {:ok, res} end defp translate_binary_element(els), do: {:error, {:invalid_binary_element, els}} defp translate_arity({var, [line: 1], nil}) when is_atom(var) do {:ok, :any} end defp translate_arity(i) when is_integer(i) do {:ok, i} end defp translate_arity(none) when none in [nil, ""] do {:ok, nil} end defp translate_arity(els) do {:error, {:invalid_arity, els}} end defp translate_actions!(empty) when empty in [nil, ""] do "" end defp translate_actions!(actions) when is_binary(actions) do " -> #{actions}" end # --------------------------------------------------------------------------- # Guards # --------------------------------------------------------------------------- @spec _translate_guards(term) :: {:ok, String.t()} | {:error, term} defp _translate_guards({:not, _line, [arg]}) do _translate_guards(arg) |> map_success(fn guard -> "not #{guard}" end) end defp _translate_guards({combinator, _line, [a, b]}) when combinator in @valid_infix_guard_combinators do erlang_combinator = @infix_guard_combinators_mapping[combinator] |> Atom.to_string() with {:ok, a_guards} <- _translate_guards(a), {:ok, b_guards} <- _translate_guards(b), do: {:ok, "(#{a_guards} #{erlang_combinator} #{b_guards})"} end defp _translate_guards(els), do: translate_guard(els) @spec translate_guard(term) :: {:ok, String.t()} | {:error, term} defp translate_guard({guard_fun, _line, args}) when guard_fun in @valid_guard_functions do with translated_fun = Atom.to_string(guard_fun), {:ok, translated_args} <- translate_args(args), do: {:ok, "#{translated_fun}#{translated_args}"} end defp translate_guard({infix_guard_fun, _line, [a, b]}) when infix_guard_fun in @valid_infix_guards do translated_infix_function = @infix_guards_mapping[infix_guard_fun] |> Atom.to_string() with {:ok, a_guard} <- translate_guard(a), {:ok, b_guard} <- translate_guard(b), do: {:ok, "#{a_guard} #{translated_infix_function} #{b_guard}"} end defp translate_guard(els) do translate_arg(els) end # --------------------------------------------------------------------------- # Helper functions # --------------------------------------------------------------------------- defp map_success({:ok, var}, fun) do {:ok, fun.(var)} end defp map_success(els, _), do: els defp wrap_in_ok(x), do: {:ok, x} end
lib/rexbug/translator.ex
0.717606
0.479565
translator.ex
starcoder
defmodule GroupManager.Data.TimedSet do require Record require GroupManager.Data.Item require GroupManager.Data.LocalClock require GroupManager.Data.TimedItem require Chatter.NetID alias GroupManager.Data.TimedItem alias Chatter.NetID alias GroupManager.Data.Item alias GroupManager.Data.LocalClock Record.defrecord :timed_set, items: [] @type t :: record( :timed_set, items: list(TimedItem.t) ) @spec new() :: t def new() do timed_set() end defmacro is_valid(data) do case Macro.Env.in_guard?(__CALLER__) do true -> quote do is_tuple(unquote(data)) and tuple_size(unquote(data)) == 2 and :erlang.element(1, unquote(data)) == :timed_set and # items is_list(:erlang.element(2, unquote(data))) end false -> quote bind_quoted: binding() do is_tuple(data) and tuple_size(data) == 2 and :erlang.element(1, data) == :timed_set and # items is_list(:erlang.element(2, data)) end end end defmacro is_empty(data) do case Macro.Env.in_guard?(__CALLER__) do true -> quote do # items :erlang.element(2, unquote(data)) == [] end false -> quote do # items :erlang.element(2, unquote(data)) == [] end end end @spec valid?(t) :: boolean def valid?(data) when is_valid(data) do true end def valid?(_), do: false @spec empty?(t) :: boolean def empty?(data) when is_valid(data) and is_empty(data) do true end def empty?(data) when is_valid(data) do false end @spec items(t) :: list(TimedItem.t) def items(set) when is_valid(set) do timed_set(set, :items) end @spec add(t, TimedItem.t) :: t def add(set, item) when is_valid(set) and TimedItem.is_valid(item) do timed_set(items: TimedItem.merge(timed_set(set, :items), item)) end @spec merge(t, t) :: t def merge(lhs, rhs) when is_valid(lhs) and is_valid(rhs) do timed_set(items: TimedItem.merge(timed_set(lhs, :items), timed_set(rhs, :items))) end @spec count(t, NetID.t) :: integer def count(set, id) when is_valid(set) and NetID.is_valid(id) do List.foldl(timed_set(set, :items), 0, fn(x, acc) -> item_id = TimedItem.item(x) |> Item.member if( item_id == id ) do acc + 1 else acc end end) end @spec count(t, LocalClock.t) :: integer def count(set, id) when is_valid(set) and LocalClock.is_valid(id) do List.foldl(timed_set(set, :items), 0, fn(x, acc) -> if( TimedItem.updated_at(x) == id ) do acc + 1 else acc end end) end @spec extract_netids(t) :: list(NetID.t) def extract_netids(set) when is_valid(set) do Enum.map(timed_set(set, :items), fn(x) -> TimedItem.updated_at(x) |> LocalClock.member end) |> Enum.uniq end @spec encode_with(t, map) :: binary def encode_with(set, id_map) when is_valid(set) and is_map(id_map) do timed_set(set, :items) |> TimedItem.encode_list_with(id_map) end @spec decode_with(binary, map) :: {t, binary} def decode_with(bin, id_map) when is_binary(bin) and byte_size(bin) > 0 and is_map(id_map) do {elems, remaining} = TimedItem.decode_list_with(bin, id_map) {timed_set(items: elems), remaining} end end
lib/group_manager/data/timed_set.ex
0.606265
0.413684
timed_set.ex
starcoder
defmodule Data.Type do @moduledoc """ Helper functions for types saved to the database """ alias Data.Type.Changeset import Changeset, only: [add_error: 3] @type changeset :: Changeset.t() @doc """ Load all non-nil keys from a struct iex> Data.Type.keys(%{key: 1, nil: nil}) [:key] iex> Data.Type.keys(%{slot: :chest}) [:slot] """ @spec keys(struct) :: [String.t()] def keys(struct) do struct |> Map.delete(:__struct__) |> Enum.reject(fn {_key, val} -> is_nil(val) end) |> Enum.map(&elem(&1, 0)) |> Enum.sort() end @doc """ Start data validation """ @spec validate(map()) :: changeset() def validate(data), do: %Changeset{data: data, valid?: true} @doc """ Validate the right keys are in the map """ @spec validate_keys(changeset(), Keyword.t()) :: changeset() def validate_keys(changeset, opts) do required = Keyword.fetch!(opts, :required) one_of = Keyword.get(opts, :one_of, []) optional = Keyword.get(opts, :optional, []) keys = keys(changeset.data) required_missing_keys = Enum.reject(required, &Enum.member?(keys, &1)) required_valid? = Enum.empty?(required_missing_keys) required_one_of_keys_count = one_of |> Enum.map(&Enum.member?(keys, &1)) |> Enum.filter(& &1) |> length() one_of_valid? = Enum.empty?(one_of) || required_one_of_keys_count == 1 extra_keys = ((keys -- required) -- optional) -- one_of no_extra_keys? = Enum.empty?(extra_keys) case required_valid? && one_of_valid? && no_extra_keys? do true -> changeset false -> changeset |> maybe_add_required(required_valid?, required_missing_keys) |> maybe_add_one_off(one_of_valid?, one_of) |> maybe_add_extra_keys(no_extra_keys?, extra_keys) end end defp maybe_add_required(changeset, valid?, required_missing_keys) do case valid? do true -> changeset false -> add_error(changeset, :keys, "missing keys: #{Enum.join(required_missing_keys, ", ")}") end end defp maybe_add_one_off(changeset, valid?, one_of) do case valid? do true -> changeset false -> add_error(changeset, :keys, "requires exactly one of: #{Enum.join(one_of, ", ")}") end end defp maybe_add_extra_keys(changeset, valid?, extra_keys) do case valid? do true -> changeset false -> add_error( changeset, :keys, "there are extra keys, please remove them: #{Enum.join(extra_keys, ", ")}" ) end end @doc """ Validate the values of the map """ @spec validate_values(changeset(), ({any(), any()} -> boolean())) :: changeset() def validate_values(changeset, fun) do fields = changeset.data |> Enum.reject(fun) |> Enum.into(%{}) |> Map.keys() case Enum.empty?(fields) do true -> changeset false -> add_error(changeset, :values, "invalid types for: #{Enum.join(fields, ", ")}") end end @doc """ Ensure that a field exists in a map/struct """ @spec ensure(map(), atom(), any()) :: map() def ensure(data, field, default) do case Map.has_key?(data, field) && Map.get(data, field) != nil do true -> data false -> Map.put(data, field, default) end end end
lib/data/type.ex
0.735737
0.482734
type.ex
starcoder
defmodule ForgeAbi.Util.BigInt do @moduledoc """ Big int operators. Note that at the moment we only need `:+` and `:-`. As for `==`, `!=`, `>`, `>=`, `<`, `<=` the default behavior is as expected so we won't override them. """ import Kernel, except: [+: 2, -: 2, >=: 2, >: 2, <=: 2, <: 2] alias ForgeAbi.{BigSint, BigUint} @doc false defmacro __using__(_opts) do quote do import Kernel, except: [+: 2, -: 2, >=: 2, >: 2, <=: 2, <: 2] import ForgeAbi.Util.BigInt alias ForgeAbi.{BigSint, BigUint} end end @doc """ Create a `ForgeAbi.BigUint`. iex> use ForgeAbi.Util.BigInt iex> biguint(1234) %ForgeAbi.BigUint{value: <<4, 210>>} iex> biguint(1111111111111111111111111111111111111111) %ForgeAbi.BigUint{value: <<3, 67, 232, 55, 78, 152, 132, 21, 75, 248, 55, 181, 113, 199, 28, 113, 199>>} """ @spec biguint(integer() | nil) :: BigUint.t() def biguint(nil), do: nil def biguint(i) when Kernel.<(i, 0), do: BigUint.new(value: <<0>>) def biguint(i), do: BigUint.new(value: to_binary(i)) @doc """ Convert BigInt to integer iex> use ForgeAbi.Util.BigInt iex> to_int(biguint(1)) === 1 true iex> to_int(bigsint(1)) === 1 true iex> to_int(bigsint(-1)) === 1 false """ @spec to_int(BigUint.t() | BigSint.t() | integer() | nil) :: integer() def to_int(nil), do: 0 def to_int(i) when is_integer(i), do: i def to_int(%BigSint{} = v), do: sign(v.minus) * to_unsigned(v.value) def to_int(%BigUint{} = v), do: to_unsigned(v.value) @doc """ Create a `ForgeAbi.BigSint`. iex> use ForgeAbi.Util.BigInt iex> bigsint(1234) %ForgeAbi.BigSint{value: <<4, 210>>, minus: false} iex> bigsint(-1234) %ForgeAbi.BigSint{value: <<4, 210>>, minus: true} iex> bigsint(-1111111111111111111111111111111111111111) %ForgeAbi.BigSint{value: <<3, 67, 232, 55, 78, 152, 132, 21, 75, 248, 55, 181, 113, 199, 28, 113, 199>>, minus: true} """ @spec bigsint(integer()) :: BigSint.t() def bigsint(i) when Kernel.<(i, 0), do: BigSint.new(value: to_binary(abs(i)), minus: true) def bigsint(i), do: BigSint.new(value: to_binary(i)) @doc """ Convert a sint to uint iex> use ForgeAbi.Util.BigInt iex> to_uint(bigsint(-1234)) %ForgeAbi.BigUint{value: <<4, 210>>} iex> to_uint(biguint(1234)) %ForgeAbi.BigUint{value: <<4, 210>>} """ @spec to_uint(BigUint.t() | BigSint.t() | nil) :: BigUint.t() def to_uint(nil), do: biguint(0) def to_uint(v), do: BigUint.new(value: v.value) @doc """ Convert a uint to sint iex> use ForgeAbi.Util.BigInt iex> to_sint(bigsint(-1234)) %ForgeAbi.BigSint{value: <<4, 210>>, minus: true} iex> to_sint(biguint(1234)) %ForgeAbi.BigSint{value: <<4, 210>>, minus: false} """ @spec to_sint(BigUint.t() | BigSint.t()) :: BigSint.t() def to_sint(%BigSint{} = v), do: v def to_sint(v), do: BigSint.new(value: v.value) @doc """ Generate a BigSint with a regular integer iex> use ForgeAbi.Util.BigInt iex> to_unit(-1234) %ForgeAbi.BigSint{minus: true, value: <<171, 64, 124, 158, 176, 82, 0, 0>>} iex> to_unit(200) %ForgeAbi.BigSint{minus: false, value: <<27, 193, 109, 103, 78, 200, 0, 0>>} """ @spec to_unit(integer(), non_neg_integer()) :: BigSint.t() def to_unit(v, decimal \\ 0), do: bigsint(v * one_token(decimal)) @spec one_token(non_neg_integer()) :: non_neg_integer() def one_token(decimal \\ 0), do: decimal_to_int(decimal) @doc """ Add two big int. Should return a BigUint. iex> use ForgeAbi.Util.BigInt iex> biguint(1234) + biguint(1234) %ForgeAbi.BigUint{value: <<9, 164>>} """ @spec (BigUint.t() | BigSint.t() | number() | nil) + (BigUint.t() | BigSint.t() | number() | nil) :: BigUint.t() | number() def (%{value: va} = a) + (%{value: vb} = b) when is_binary(va) and is_binary(vb) do sa = Map.get(a, :minus, false) sb = Map.get(b, :minus, false) vc = do_add(sa, sb, va, vb) biguint(vc) end def a + (%{value: vb} = b) when is_binary(vb) and is_integer(a) do bigsint(a) + b end def (%{value: va} = a) + b when is_binary(va) and is_integer(b) do a + bigsint(b) end def nil + nil, do: 0 def nil + b, do: b def a + nil, do: a def a + b, do: Kernel.+(a, b) @doc """ Substract two big int. Should return a BigUint. iex> use ForgeAbi.Util.BigInt iex> biguint(1234) - biguint(1233) %ForgeAbi.BigUint{value: <<1>>} iex> biguint(1234) - biguint(1235) %ForgeAbi.BigUint{value: <<0>>} iex> biguint(1234) - bigsint(-1235) %ForgeAbi.BigUint{value: <<9, 165>>} iex> bigsint(-1234) - biguint(1235) %ForgeAbi.BigUint{value: <<0>>} """ @spec (BigUint.t() | number()) - (BigUint.t() | BigSint.t() | number()) :: BigUint.t() | number() def %{value: va} - (%{value: vb} = b) when is_binary(va) and is_binary(vb) do sb = Map.get(b, :minus, false) vc = do_sub(sb, va, vb) biguint(vc) end def (%{value: va} = a) - b when is_binary(va) and is_integer(b) do a - bigsint(b) end def nil - nil, do: 0 def nil - b, do: Kernel.-(0, b) def a - nil, do: a def a - b, do: Kernel.-(a, b) @doc """ Compare biguint, bigsint(we just use its abs value), and normal integer/float iex> use ForgeAbi.Util.BigInt iex> biguint(1234) > biguint(1233) true iex> biguint(1234) <= biguint(1235) true iex> biguint(1234) > bigsint(-1235) false iex> bigsint(-1234) > biguint(100) true iex> bigsint(-1234) > 1000 true iex> bigsint(-1234) > 2000 false iex> 1000 >= biguint(999) true iex> 1000 >= biguint(1001) false """ def a >= b, do: Kernel.>=(to_unsigned(a), to_unsigned(b)) def a > b, do: Kernel.>(to_unsigned(a), to_unsigned(b)) def a <= b, do: Kernel.<=(to_unsigned(a), to_unsigned(b)) def a < b, do: Kernel.<(to_unsigned(a), to_unsigned(b)) # private function defp sign(false), do: 1 defp sign(true), do: -1 defp to_binary(i), do: :binary.encode_unsigned(i) defp to_unsigned(nil), do: 0 defp to_unsigned(v) when is_integer(v), do: v defp to_unsigned(v) when is_float(v), do: v defp to_unsigned(%{value: a}), do: to_unsigned(a) defp to_unsigned(v), do: :binary.decode_unsigned(v) defp do_add(false, false, va, vb), do: to_unsigned(va) + to_unsigned(vb) defp do_add(false, true, va, vb), do: to_unsigned(va) - to_unsigned(vb) defp do_add(true, false, va, vb), do: to_unsigned(vb) - to_unsigned(va) defp do_add(true, true, _va, _vb), do: 0 defp do_sub(false, va, vb), do: to_unsigned(va) - to_unsigned(vb) defp do_sub(true, va, vb), do: to_unsigned(va) + to_unsigned(vb) defp decimal_to_int(0) do decimal = Application.get_env(:forge_abi, :decimal) round(:math.pow(10, decimal)) end defp decimal_to_int(d), do: round(:math.pow(10, d)) end
lib/forge_abi/util/bigint.ex
0.748904
0.754802
bigint.ex
starcoder
defmodule Blinkchain.Config.Channel do @pwm_0_pins [12, 18, 40, 52] @pwm_1_pins [13, 19, 41, 45, 53] @valid_types [ :rgb, :rbg, :grb, :gbr, :brg, :bgr, :rgbw, :rbgw, :grbw, :gbrw, :brgw, :bgrw ] @moduledoc """ Represents a single "chain" of pixels of the same type, connected to the same I/O pin. * `arrangement`: The list of `t:Blinkchain.Config.Strip.t/0` structs that describe each straight section of pixels. * `brightness`: The scale factor used for all pixels in the channel (`0`-`255`, default: `255`). * `gamma`: A custom gamma curve to apply to the color of each pixel (default is linear). Specified as a list of 256 integer values between `0` and `255`, which will be indexed to transform each color channel from the canvas to the hardware pixels. * `invert`: Whether to invert the PWM signal sent to the I/O pin (required by some hardware types (default: `false`). * `number`: Which PWM block to use (must be `0` or `1`) * `pin`: The I/O pin number to use for this channel (default: `18`) Only certain I/O pins are supported and only one pin from each PWM hardware block can be used simultaneously. Reference the `BCM` pin numbers on https://pinout.xyz/ for physical pin locations. * Available pins for PWM block 0: `#{inspect(@pwm_0_pins)}` * Available pins for PWM block 1: `#{inspect(@pwm_1_pins)}` * `type`: The order of color channels to send to each pixel. (default: `:gbr`) You may have to experiment to determine the correct setting for your pixel hardware, for example, by setting a pixel to full-intensity for each color channel one-by-one and seeing which color actually lights up. Valid options: `#{inspect(@valid_types)}` """ alias Blinkchain.Config.{ Channel, Matrix, Strip } @typedoc @moduledoc @type t :: %__MODULE__{ arrangement: [Strip.t()], brightness: Blinkchain.uint8(), gamma: [Blinkchain.uint8()], invert: boolean(), number: Blinkchain.channel_number(), pin: non_neg_integer(), type: atom() } defstruct arrangement: [], brightness: 255, gamma: nil, invert: false, number: nil, pin: 0, type: :gbr @doc "Build a `t:Blinkchain.Config.Channel.t/0` struct from given configuration options" @spec new(Keyword.t(), Blinkchain.channel_number()) :: Channel.t() def new(nil, number) when number in [0, 1], do: %Channel{number: number} def new(channel_config, number) when number in [0, 1] do %Channel{number: number} |> set_arrangement(Keyword.get(channel_config, :arrangement)) |> set_brightness(Keyword.get(channel_config, :brightness)) |> set_gamma(Keyword.get(channel_config, :gamma)) |> set_invert(Keyword.get(channel_config, :invert)) |> set_pin(Keyword.get(channel_config, :pin)) |> set_type(Keyword.get(channel_config, :type)) end @doc "Return the hardware PWM channel for a `t:Channel.t/0` or I/O pin" @spec pwm_channel(Channel.t() | non_neg_integer()) :: 0 | 1 | nil def pwm_channel(%Channel{pin: pin}), do: pwm_channel(pin) def pwm_channel(pin) when pin in @pwm_0_pins, do: 0 def pwm_channel(pin) when pin in @pwm_1_pins, do: 1 def pwm_channel(_), do: nil @doc "Count the total number of pixels in the channel" @spec total_count(Channel.t()) :: non_neg_integer() def total_count(%Channel{arrangement: arrangement}) do Enum.reduce(arrangement, 0, fn %Strip{count: count}, acc -> acc + count end) end # Private Helpers defp set_arrangement(channel, sections) when is_list(sections) do strips = sections |> Enum.map(&load_section/1) |> List.flatten() %Channel{channel | arrangement: strips} end defp set_arrangement(_channel, _arrangement) do raise "You must configure the :arrangement of pixels in each channel as a list" end defp set_brightness(channel, nil), do: channel defp set_brightness(channel, brightness) when brightness in 0..255 do %Channel{channel | brightness: brightness} end defp set_brightness(_channel, _brightness) do raise "Channel :brightness must be in 0..255" end defp set_gamma(channel, nil), do: channel defp set_gamma(channel, gamma) when is_list(gamma) and length(gamma) == 256 do %Channel{channel | gamma: gamma} end defp set_gamma(_channel, _gamma) do raise "The :gamma on a :channel must be set as a list of 256 8-bit integers" end defp set_invert(channel, nil), do: channel defp set_invert(channel, invert) when invert in [true, false] do %Channel{channel | invert: invert} end defp set_invert(_channel, _invert) do raise "Channel :invert must be true or false" end defp set_pin(%Channel{number: 0} = channel, pin) do if pin in @pwm_0_pins do %Channel{channel | pin: pin} else raise "Channel 0 :pin must be in #{inspect(@pwm_0_pins)}" end end defp set_pin(%Channel{number: 1} = channel, pin) do if pin in @pwm_1_pins do %Channel{channel | pin: pin} else raise "Channel 1 :pin must be in #{inspect(@pwm_1_pins)}" end end defp set_type(channel, nil), do: channel defp set_type(channel, type) when type in @valid_types, do: %Channel{channel | type: type} defp set_type(_channel, _), do: raise("Channel :type must be one of #{inspect(@valid_types)}") defp load_section(%{type: :matrix} = matrix_config) do matrix_config |> Matrix.new() |> Matrix.to_strip_list() end defp load_section(%{type: :strip} = strip_config) do Strip.new(strip_config) end defp load_section(_section) do raise "The :arrangement configuration must be a list of %{type: :strip} or %{type: :matrix} maps" end end
lib/blinkchain/config/channel.ex
0.840946
0.599514
channel.ex
starcoder
defmodule MsgPackObject do defmodule MsgPackExtension do @type t :: %__MODULE__{ type: integer, value: binary } defstruct [ type: 0, value: <<>> ] end @type object_type :: :integer | :nil | :boolean | :float | :string | :binary | :array | :map | :extension @type value_type :: integer | nil | boolean | float | binary | [any] | map | MsgPackExtension.t @type t :: %__MODULE__{ type: object_type, value: value_type } defstruct [ type: :nil, value: nil ] defmodule MsgPackObjectState do @type t :: %__MODULE__{ object: MsgPackObject.t, message: binary } defstruct [ object: %MsgPackObject{}, message: <<>> ] end @spec parse_map(message :: binary, size :: integer, map :: map) :: MsgPackObjectState.t defp parse_map(message, size, map) do if size == 0 do %MsgPackObjectState{object: %__MODULE__{type: :map, value: map}, message: message} else %MsgPackObjectState{object: key_object, message: key_rest} = parse_head(message) %MsgPackObjectState{object: value_object, message: value_rest} = parse_head(key_rest) updated_map = Map.put(map, key_object, value_object) parse_map(value_rest, size - 1, updated_map) end end @spec parse_array(message :: binary, size :: integer, array :: [any]) :: MsgPackObjectState.t defp parse_array(message, size, array) do if size == 0 do %MsgPackObjectState{object: %__MODULE__{type: :array, value: array}, message: message} else %MsgPackObjectState{object: value_object, message: value_rest} = parse_head(message) updated_array = array ++ [value_object] parse_array(value_rest, size - 1, updated_array) end end @spec negative_fixint_to_integer(negative_fixint :: bitstring) :: integer defp negative_fixint_to_integer(negative_fixint) do <<value :: integer - signed - size(8)>> = <<0b111 :: size(3), negative_fixint :: bitstring - size(5)>> value end @spec parse_head(message :: binary) :: MsgPackObjectState.t defp parse_head(message) do case message do <<0b0 :: size(1), positive_fixint :: integer - size(7), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :integer, value: positive_fixint}, message: rest} <<0b1000 :: size(4), fixmap_size :: integer - size(4), key_value_pair_description :: binary>> -> parse_map(key_value_pair_description, fixmap_size, %{}) <<0b1001 :: size(4), fixarray_size :: integer - size(4), value_description :: binary>> -> parse_array(value_description, fixarray_size, []) <<0b101 :: size(3), fixstr_size :: integer - size(5), fixstr :: binary - size(fixstr_size), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :string, value: fixstr}, message: rest} <<0b11000000 :: size(8), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :nil, value: nil}, message: rest} <<0b11000010 :: size(8), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :boolean, value: false}, message: rest} <<0b11000011 :: size(8), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :boolean, value: true}, message: rest} <<0b11000100 :: size(8), bin8_size :: integer - size(8), bin8 :: binary - size(bin8_size), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :binary, value: bin8}, message: rest} <<0b11000101 :: size(8), bin16_size :: integer - size(16), bin16 :: binary - size(bin16_size), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :binary, value: bin16}, message: rest} <<0b11000110 :: size(8), bin32_size :: integer - size(32), bin32 :: binary - size(bin32_size), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :binary, value: bin32}, message: rest} <<0b11000111 :: size(8), ext8_size :: integer - size(8), ext8_type :: integer - signed - size(8), ext8 :: binary - size(ext8_size), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :extension, value: %MsgPackExtension{type: ext8_type, value: ext8}}, message: rest} <<0b11001000 :: size(8), ext16_size :: integer - size(16), ext16_type :: integer - signed - size(8), ext16 :: binary - size(ext16_size), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :extension, value: %MsgPackExtension{type: ext16_type, value: ext16}}, message: rest} <<0b11001001 :: size(8), ext32_size :: integer - size(32), ext32_type :: integer - signed - size(8), ext32 :: binary - size(ext32_size), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :extension, value: %MsgPackExtension{type: ext32_type, value: ext32}}, message: rest} <<0b11001010 :: size(8), float32 :: float - size(32), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :float, value: float32}, message: rest} <<0b11001011 :: size(8), float64 :: float - size(64), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :float, value: float64}, message: rest} <<0b11001100 :: size(8), uint8 :: integer - size(8), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :integer, value: uint8}, message: rest} <<0b11001101 :: size(8), uint16 :: integer - size(16), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :integer, value: uint16}, message: rest} <<0b11001110 :: size(8), uint32 :: integer - size(32), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :integer, value: uint32}, message: rest} <<0b11001111 :: size(8), uint64 :: integer - size(64), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :integer, value: uint64}, message: rest} <<0b11010000 :: size(8), int8 :: integer - signed - size(8), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :integer, value: int8}, message: rest} <<0b11010001 :: size(8), int16 :: integer - signed - size(16), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :integer, value: int16}, message: rest} <<0b11010010 :: size(8), int32 :: integer - signed - size(32), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :integer, value: int32}, message: rest} <<0b11010011 :: size(8), int64 :: integer - signed - size(64), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :integer, value: int64}, message: rest} <<0b11010100 :: size(8), fixext1_type :: integer - signed - size(8), fixext1 :: binary - size(1), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :extension, value: %MsgPackExtension{type: fixext1_type, value: fixext1}}, message: rest} <<0b11010101 :: size(8), fixext2_type :: integer - signed - size(8), fixext2 :: binary - size(2), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :extension, value: %MsgPackExtension{type: fixext2_type, value: fixext2}}, message: rest} <<0b11010110 :: size(8), fixext4_type :: integer - signed - size(8), fixext4 :: binary - size(4), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :extension, value: %MsgPackExtension{type: fixext4_type, value: fixext4}}, message: rest} <<0b11010111 :: size(8), fixext8_type :: integer - signed - size(8), fixext8 :: binary - size(8), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :extension, value: %MsgPackExtension{type: fixext8_type, value: fixext8}}, message: rest} <<0b11011000 :: size(8), fixext16_type :: integer - signed - size(8), fixext16 :: binary - size(16), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :extension, value: %MsgPackExtension{type: fixext16_type, value: fixext16}}, message: rest} <<0b11011001 :: size(8), str8_size :: integer - size(8), str8 :: binary - size(str8_size), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :string, value: str8}, message: rest} <<0b11011010 :: size(8), str16_size :: integer - size(16), str16 :: binary - size(str16_size), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :string, value: str16}, message: rest} <<0b11011011 :: size(8), str32_size :: integer - size(32), str32 :: binary - size(str32_size), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :string, value: str32}, message: rest} <<0b11011100 :: size(8), array16_size :: integer - size(16), value_description :: binary>> -> parse_array(value_description, array16_size, []) <<0b11011101 :: size(8), array32_size :: integer - size(32), value_description :: binary>> -> parse_array(value_description, array32_size, []) <<0b11011110 :: size(8), map16_size :: integer - size(16), key_value_pair_description :: binary>> -> parse_map(key_value_pair_description, map16_size, %{}) <<0b11011111 :: size(8), map32_size :: integer - size(32), key_value_pair_description :: binary>> -> parse_map(key_value_pair_description, map32_size, %{}) <<0b111 :: size(3), negative_fixint :: bitstring - size(5), rest :: binary>> -> %MsgPackObjectState{object: %__MODULE__{type: :integer, value: negative_fixint_to_integer(negative_fixint)}, message: rest} end end @spec parse(message :: binary) :: t def parse(message) do %MsgPackObjectState{object: msgpack_object, message: _} = parse_head(message) msgpack_object end @spec get_bare_object(msgpack_object :: t) :: any def get_bare_object(%MsgPackObject{type: obj_type, value: obj_value}) do case obj_type do :array -> obj_value |> Enum.map(fn element -> get_bare_object(element) end) :map -> obj_value |> Map.new(fn {key, value} -> {get_bare_object(key), get_bare_object(value)} end) _ -> obj_value end end @spec serialize_integer(value :: integer) :: binary defp serialize_integer(value) do case value do n when n in 0 .. 127 -> <<value :: integer - size(8)>> n when n in 128 .. 255 -> <<0b11001100 :: size(8), value :: integer - size(8)>> n when n in 256 .. 65535 -> <<0b11001101 :: size(8), value :: integer - size(16)>> n when n in 65536 .. 4294967295 -> <<0b11001110 :: size(8), value :: integer - size(32)>> n when n in -32 .. -1 -> <<value :: integer - signed - size(8)>> n when n in -128 .. -33 -> <<0b11010000 :: size(8), value :: integer - signed - size(8)>> n when n in -32768 .. -129 -> <<0b11010001 :: size(8), value :: integer - signed - size(16)>> n when n in -2147483648 .. -32769 -> <<0b11010010 :: size(8), value :: integer - signed - size(32)>> n when n >= 4294967296 -> <<0b11001111 :: size(8), value :: integer - size(64)>> _ -> <<0b11010011 :: size(8), value :: integer - signed - size(64)>> end end @spec serialize_boolean(value :: boolean) :: binary defp serialize_boolean(value) do case value do false -> <<0b11000010 :: size(8)>> true -> <<0b11000011 :: size(8)>> end end @spec serialize_binary(value :: binary) :: binary defp serialize_binary(value) do case byte_size(value) do size when size in 0 .. 255 -> <<0b11000100 :: size(8), size :: integer - size(8), value :: binary - size(size)>> size when size in 256 .. 65535 -> <<0b11000101 :: size(8), size :: integer - size(16), value :: binary - size(size)>> size -> <<0b11000110 :: size(8), size :: integer - size(32), value :: binary - size(size)>> end end @spec serialize_string(value :: binary) :: binary defp serialize_string(value) do case byte_size(value) do size when size in 0 .. 31 -> <<0b101 :: size(3), size :: integer - size(5), value :: binary - size(size)>> size when size in 32 .. 255 -> <<0b11011001 :: size(8), size :: integer - size(8), value :: binary - size(size)>> size when size in 256 .. 65535 -> <<0b11011010 :: size(8), size :: integer - size(16), value :: binary - size(size)>> size -> <<0b11011011 :: size(8), size :: integer - size(32), value :: binary - size(size)>> end end @spec serialize_binary_or_string(value :: binary) :: binary defp serialize_binary_or_string(value) do if String.valid?(value) do serialize_string(value) else serialize_binary(value) end end @spec serialize_array(value :: [any]) :: binary defp serialize_array(value) do header = case Enum.count(value) do size when size in 0 .. 15 -> <<0b1001 :: size(4), size :: integer - size(4)>> size when size in 16 .. 255 -> <<0b11011100 :: size(8), size :: integer - size(16)>> size -> <<0b11011101 :: size(8), size :: integer - size(32)>> end value_description = value |> Enum.map(&serialize/1) |> Enum.join() header <> value_description end @spec serialize_map(value :: map) :: binary defp serialize_map(value) do header = case Enum.count(value) do size when size in 0 .. 15 -> <<0b1000 :: size(4), size :: integer - size(4)>> size when size in 16 .. 255 -> <<0b11011110 :: size(8), size :: integer - size(16)>> size -> <<0b11011111 :: size(8), size :: integer - size(32)>> end key_value_pair_description = value |> Enum.map(fn key_value_pair -> (elem(key_value_pair, 0) |> serialize) <> (elem(key_value_pair, 1) |> serialize) end) |> Enum.join() header <> key_value_pair_description end @spec serialize_extension(type :: integer, value :: binary) :: binary defp serialize_extension(type, value) do case byte_size(value) do 1 -> <<0b11010100 :: size(8), type :: integer - signed - size(8), value :: binary - size(1)>> 2 -> <<0b11010101 :: size(8), type :: integer - signed - size(8), value :: binary - size(2)>> 4 -> <<0b11010110 :: size(8), type :: integer - signed - size(8), value :: binary - size(4)>> 8 -> <<0b11010111 :: size(8), type :: integer - signed - size(8), value :: binary - size(8)>> 16 -> <<0b11011000 :: size(8), type :: integer - signed - size(8), value :: binary - size(16)>> size when size in 0 .. 255 -> <<0b11000111 :: size(8), size :: integer - size(8), type :: integer - signed - size(8), value :: binary - size(size)>> size when size in 256 .. 65535 -> <<0b11001000 :: size(8), size :: integer - size(16), type :: integer - signed - size(8), value :: binary - size(size)>> size -> <<0b11001001 :: size(8), size :: integer - size(32), type :: integer - signed - size(8), value :: binary - size(size)>> end end @spec serialize(value :: value_type) :: binary def serialize(value) do cond do is_integer(value) -> serialize_integer(value) is_nil(value) -> <<0b11000000 :: size(8)>> is_boolean(value) -> serialize_boolean(value) is_float(value) -> <<0b11001011 :: size(8), value :: float - size(64)>> is_binary(value) -> serialize_binary_or_string(value) is_list(value) -> serialize_array(value) is_map(value) -> serialize_map(value) %MsgPackExtension{type: ext_type, value: ext_value} = value -> serialize_extension(ext_type, ext_value) end end end
lib/msgpack.ex
0.733452
0.413418
msgpack.ex
starcoder
defmodule Maestro.Store.Adapter do @moduledoc """ Defines the minimal API for a well-behaved storage implementation. """ alias Maestro.Types.{Event, Snapshot} @type id :: Event.aggregate_id() @type seq :: Event.sequence() @type options :: map() @doc """ If any transactional projections are present, this function is an extension of `commit_events` that within the same transaction applies all projections to the store as well. Otherwise, this function dispatches to `commit_events`. """ @callback commit_all([Event.t()], [module()]) :: :ok | {:error, :retry_command} @doc """ Events are validated according to the `Event.changeset/1` function. If successful, events are committed transactionally. In the event of a conflict on sequence number, the storage mechanism should indicate that the command _could be_ retried by returning `{:error, :retry_command}`. The `Aggregate`'s command lifecycle will see the conflict and update the aggregate's state before attempting to evaluate the command again. This allows for making stricter evaluation rules for commands. If the events could not be committed for any other reason, the storage mechanism should raise an appropriate exception. """ @callback commit_events([Event.t()]) :: :ok | {:error, :retry_command} | :no_return @doc """ Snapshots are committed iff the proposed version is newer than the version already stored. This allows disconnected nodes to optimistically write their snapshots and still have a single version stored without conflicts. """ @callback commit_snapshot(Snapshot.t()) :: :ok | :no_return @doc """ Events are retrieved by aggregate_id and with at least a minimum sequence number, `seq`. They should be ordered by sequence number to ensure that aggregates always process events in the same order. Additional option(s): * `:max_sequence` (integer): a hard upper limit on the sequence number. This is useful when attempting to recreate a past state of an aggregate. """ @callback get_events(id, seq, options) :: [Event.t()] @doc """ Snapshots can also be retrieved by aggregate_id and with at least a minimum sequence number, `seq`. Additional option(s): * `:max_sequence` (integer): a hard upper limit on the sequence number. This is useful when attempting to recreate a past state of an aggregate. """ @callback get_snapshot(id, seq, options) :: nil | Snapshot.t() end
lib/maestro/store/adapter.ex
0.885167
0.451085
adapter.ex
starcoder
defmodule Ane do @moduledoc """ A very efficient way to share mutable data by utilizing `:atomics` and `:ets` modules. [github.com/gyson/ane](https://github.com/gyson/ane) has detailed guides. """ @type atomics_ref() :: :atomics.atomics_ref() @type tid() :: :ets.tid() | atom() @type t_for_ane_mode() :: {tid(), atomics_ref(), atomics_ref(), map()} @type t_for_ets_mode() :: {tid(), pos_integer()} @type t() :: t_for_ane_mode() | t_for_ets_mode() @destroyed_message "Ane instance is destroyed" @doc """ Create and return an Ane instance. ## Options * `:mode` (atom) - set mode of Ane instance. Default to `:ane`. * `:read_concurrency` (boolean) - set read_concurrency for underneath ETS table. Default to `false`. * `:write_concurrency` (boolean) - set write_concurrency for underneath ETS table. Default to `false`. * `:compressed` (boolean) - set compressed for underneath ETS table. Default to `false`. ## Example iex> a = Ane.new(1, read_concurrency: false, write_concurrency: false, compressed: false) iex> t = Ane.get_table(a) iex> :ets.info(t, :read_concurrency) false iex> :ets.info(t, :write_concurrency) false iex> :ets.info(t, :compressed) false """ @spec new(pos_integer(), keyword()) :: t() def new(size, options \\ []) do read = Keyword.get(options, :read_concurrency, false) write = Keyword.get(options, :write_concurrency, false) compressed = case Keyword.get(options, :compressed, false) do true -> [:compressed] false -> [] end table_options = [ :set, :public, {:read_concurrency, read}, {:write_concurrency, write} | compressed ] case Keyword.get(options, :mode, :ane) do :ane -> a1 = :atomics.new(size, signed: true) a2 = :atomics.new(size, signed: true) e = :ets.new(__MODULE__, table_options) {e, a1, a2, %{}} :ets -> e = :ets.new(__MODULE__, table_options) {e, size} end end @doc """ Get value at one-based index in Ane instance. It returns a tuple with two elements: * First element is new Ane instance which includes latest cached data. - Note: we need to use this returned new Ane instance for following read operations to make cache work properly. * Second element is the value at one-based index. Value is initialized as `nil` by default. ## Example iex> a = Ane.new(1) iex> {a, value} = Ane.get(a, 1) iex> value nil iex> Ane.put(a, 1, "hello") :ok iex> {_, value} = Ane.get(a, 1) iex> value "hello" """ @spec get(t(), pos_integer()) :: {t(), any()} def get({e, a1, a2, cache} = ane, i) do case :atomics.get(a2, i) do version when version > 0 -> case cache do # cache hit %{^i => {^version, value}} -> {ane, value} # cache miss _ -> {_, value} = updated = lookup(e, a2, i, version) {{e, a1, a2, Map.put(cache, i, updated)}, value} end 0 -> {ane, nil} _ -> raise ArgumentError, @destroyed_message end end def get({e, size} = ane, i) when is_integer(i) and i > 0 and i <= size do case :ets.lookup(e, i) do [{_, value}] -> {ane, value} [] -> {ane, nil} end end @spec lookup(tid(), atomics_ref(), pos_integer(), integer()) :: {integer(), any()} defp lookup(e, a2, i, version) do case :ets.lookup(e, [i, version]) do [{_, value}] -> {version, value} [] -> case :atomics.get(a2, i) do new_version when new_version > 0 -> lookup(e, a2, i, new_version) _ -> raise ArgumentError, @destroyed_message end end end @doc """ Put value at one-based index in Ane instance. It would always return `:ok`. `Ane.put` includes one `:ets.insert` operation and one `:ets.delete` operation. When the process running `Ane.put` is interrupted (e.g. by `:erlang.exit(pid, :kill)`), garbage data could be generated if it finished insert operation but did not start delete operation. These garbabge data could be removed by `Ane.clear`. ## Example iex> a = Ane.new(1) iex> {a, value} = Ane.get(a, 1) iex> value nil iex> Ane.put(a, 1, "world") :ok iex> {_, value} = Ane.get(a, 1) iex> value "world" """ @spec put(t(), pos_integer(), any()) :: :ok def put({e, a1, a2, _} = _ane, i, value) do case :atomics.add_get(a1, i, 1) do new_version when new_version > 0 -> :ets.insert(e, {[i, new_version], value}) commit(e, a2, i, new_version - 1, new_version) _ -> raise ArgumentError, @destroyed_message end end def put({e, size} = _ane, i, value) when is_integer(i) and i > 0 and i <= size do :ets.insert(e, {i, value}) :ok end @spec commit(tid(), atomics_ref(), pos_integer(), integer(), integer()) :: :ok defp commit(e, a2, i, expected, desired) do case :atomics.compare_exchange(a2, i, expected, desired) do :ok -> :ets.delete(e, [i, expected]) :ok actual when actual < 0 -> raise ArgumentError, @destroyed_message actual when actual < desired -> commit(e, a2, i, actual, desired) _ -> :ets.delete(e, [i, desired]) :ok end end @doc """ Clear garbage data which could be generated when `Ane.put` is interrupted. ## Example iex> a = Ane.new(1) iex> Ane.clear(a) :ok """ @spec clear(t()) :: :ok def clear({e, _, a2, _} = _ane) do :ets.safe_fixtable(e, true) clear_table(e, a2, %{}, :ets.first(e)) :ets.safe_fixtable(e, false) :ok end def clear({_, _} = _ane), do: :ok @spec clear_table(tid(), atomics_ref(), map(), any()) :: :ok defp clear_table(_, _, _, :"$end_of_table"), do: :ok defp clear_table(e, a2, cache, [i, version] = key) do {updated_cache, current_version} = case cache do %{^i => v} -> {cache, v} _ -> v = :atomics.get(a2, i) {Map.put(cache, i, v), v} end if version < current_version do :ets.delete(e, key) end clear_table(e, a2, updated_cache, :ets.next(e, key)) end @doc """ Destroy an Ane instance. ## Example iex> a = Ane.new(1) iex> Ane.destroyed?(a) false iex> Ane.destroy(a) :ok iex> Ane.destroyed?(a) true """ @spec destroy(t()) :: :ok def destroy({e, a1, a2, _} = ane) do # min for 64 bits signed number min = -9_223_372_036_854_775_808 1..get_size(ane) |> Enum.each(fn i -> :atomics.put(a1, i, min) :atomics.put(a2, i, min) end) :ets.delete(e) :ok end def destroy({e, _} = _ane) do :ets.delete(e) :ok end @doc """ Check if Ane instance is destroyed. ## Example iex> a = Ane.new(1) iex> Ane.destroyed?(a) false iex> Ane.destroy(a) :ok iex> Ane.destroyed?(a) true """ @spec destroyed?(t()) :: boolean() def destroyed?({e, _, _, _} = _ane), do: :ets.info(e, :type) == :undefined def destroyed?({e, _} = _ane), do: :ets.info(e, :type) == :undefined @doc """ Get mode of Ane instance. ## Example iex> Ane.new(1) |> Ane.get_mode() :ane iex> Ane.new(1, mode: :ane) |> Ane.get_mode() :ane iex> Ane.new(1, mode: :ets) |> Ane.get_mode() :ets """ @spec get_mode(t()) :: :ane | :ets def get_mode({_, _, _, _} = _ane), do: :ane def get_mode({_, _} = _ane), do: :ets @doc """ Get size of Ane instance. ## Example iex> Ane.new(1) |> Ane.get_size() 1 iex> Ane.new(10) |> Ane.get_size() 10 """ @spec get_size(t()) :: pos_integer() def get_size({_, _, a2, _} = _ane), do: :atomics.info(a2).size def get_size({_, size} = _ane), do: size @doc """ Get ETS table of Ane instance. The returned ETS table could be used to * get more info via `:ets.info` * change ownership via `:ets.give_away` * change configuration via `:ets.setopts` ## Example iex> Ane.new(1) |> Ane.get_table() |> :ets.info(:type) :set """ @spec get_table(t()) :: tid() def get_table({e, _, _, _} = _ane), do: e def get_table({e, _} = _ane), do: e end
lib/ane.ex
0.890026
0.768494
ane.ex
starcoder
alias Generator.State, as: State alias Generator.Result, as: Result alias InterpreterTerms.Regex, as: RegexTerm alias InterpreterTerms.Nothing, as: Nothing alias InterpreterTerms.RegexEmitter, as: RegexEmitter defmodule InterpreterTerms.RegexMatch do defstruct [:match, {:whitespace, ""}, { :external, %{} }] defimpl String.Chars do def to_string( %InterpreterTerms.RegexMatch{ match: match } ) do { :match, match } end end end defmodule RegexEmitter do defstruct [:state, :known_matches] defimpl EbnfParser.Generator do def emit( %RegexEmitter{ known_matches: [] } ) do # IO.inspect( [], label: "No known matches" ) { :fail } end def emit( %RegexEmitter{ state: state, known_matches: [string] } ) do # IO.inspect( [string], label: "known matches" ) { :ok, %Nothing{}, RegexEmitter.generate_result( state, string ) } end def emit( %RegexEmitter{ state: state, known_matches: [match|rest] } = emitter ) do # IO.inspect( [match|rest], label: "Known matches" ) # IO.inspect( match, label: "Current match" ) { :ok, %{ emitter | known_matches: rest }, RegexEmitter.generate_result( state, match ) } end end def generate_result( state, string ) do %State{ chars: chars } = state %Result{ leftover: Enum.drop( chars, String.length( string ) ), matched_string: string, match_construct: [%InterpreterTerms.RegexMatch{ match: string }] } end end defmodule InterpreterTerms.Regex do defstruct [regex: "", state: %State{}, known_matches: []] defimpl EbnfParser.GeneratorProtocol do def make_generator( %RegexTerm{ regex: regex, state: state } = regex_term ) do # regex # |> IO.inspect( label: "Received regex" ) # Get the charactors from our state char_string = state |> Generator.State.chars_as_string # |> IO.inspect( label: "Character string to operate on" ) # TODO be smart and use Regex.run instead matching_strings = regex |> Regex.scan( char_string, [capture: :first] ) |> ( fn (results) -> results || [] end ).() |> Enum.map( &(Enum.at(&1, 0)) ) # |> IO.inspect( label: "Matching strings" ) %RegexEmitter{ state: state, known_matches: matching_strings } end end end
lib/ebnf_parser/interpreter_terms/regex.ex
0.517571
0.47926
regex.ex
starcoder
defmodule Board do defstruct [:board] def new(row_count \\ 10, col_count \\ 10) do %Board{ board: empty_board(row_count, col_count) } end def row_count(board) do length(board) end def col_count(board) do first_row = Enum.at(board, 0) length(first_row) end def all_tiles(board) do List.flatten(board) end def get_tile(board, {row_index, col_index}) do board |> Enum.at(row_index) |> Enum.at(col_index) end def flag_or_unflag_tile(board, coordinate_pair) do tile = get_tile(board, coordinate_pair) cond do Tile.is_revealed?(tile) -> {:error, :cannot_flag_revealed_tile} Tile.is_flagged?(tile) -> board = hide_tile(board, coordinate_pair) {:ok, board} !Tile.is_flagged?(tile) -> board = flag_tile(board, coordinate_pair) {:ok, board} end end def select_tile(board, coordinate_pair) do tile = get_tile(board, coordinate_pair) if Tile.is_revealed?(tile) do {:error, :already_selected} else board = reveal_tile(board, coordinate_pair) |> FloodFiller.flood_fill(coordinate_pair) {:ok, board} end end def flag_tile(board, coordinate_pair) do tile = get_tile(board, coordinate_pair) replace_tile(board, coordinate_pair, Tile.flag(tile)) end def hide_tile(board, coordinate_pair) do tile = get_tile(board, coordinate_pair) replace_tile(board, coordinate_pair, Tile.hide(tile)) end def reveal_tile(board, coordinate_pair) do tile = get_tile(board, coordinate_pair) replace_tile(board, coordinate_pair, Tile.reveal(tile)) end def replace_tile(board, {row_index, col_index}, value) do List.update_at(board, row_index, fn row -> List.replace_at(row, col_index, value) end) end def update_all_tiles(board, func) do Enum.reduce(Enum.with_index(board), board, fn {row, row_index}, board -> Enum.reduce(Enum.with_index(row), board, fn {tile, col_index}, board -> func.(board, tile, {row_index, col_index}) end) end) end def out_of_bounds?(board, {row_index, col_index}) do row_out_of_bounds?(board, row_index) || col_out_of_bounds?(board, col_index) end defp empty_board(row_count, col_count) do List.duplicate(empty_row(col_count), row_count) end defp empty_row(col_count) do List.duplicate(empty_tile(), col_count) end defp empty_tile do Tile.new(:empty) end defp row_out_of_bounds?(board, row_index) do row_index < 0 || row_index >= Board.row_count(board) end defp col_out_of_bounds?(board, col_index) do col_index < 0 || col_index >= Board.col_count(board) end end
lib/board.ex
0.591015
0.560192
board.ex
starcoder
defmodule Harmonex.Interval do @moduledoc """ Provides functions for working with intervals between pitches on the Western dodecaphonic scale. """ alias Harmonex.{Ordinal,Pitch} defstruct quality: nil, size: nil @typedoc """ A `Harmonex.Interval` struct. """ @type interval :: %Harmonex.Interval{quality: quality, size: size} @typedoc """ An expression describing an interval. """ @type t :: %{quality: quality, size: size} | interval @typedoc """ The qualified variation of an interval’s size. """ @type quality :: :perfect | :minor | :major | :diminished | :augmented | :doubly_diminished | :doubly_augmented @qualities ~w(perfect minor major diminished augmented doubly_diminished doubly_augmented)a @typedoc """ The number of staff lines and spaces spanned by an interval. """ @type size :: pos_integer @typedoc """ The distance in half steps across an interval. """ @type semitones :: non_neg_integer @quality_by_semitones_and_size %{{ 0, 1} => :perfect, { 1, 1} => :augmented, { 2, 1} => :doubly_augmented, { 0, 2} => :diminished, { 1, 2} => :minor, { 2, 2} => :major, { 3, 2} => :augmented, { 4, 2} => :doubly_augmented, { 1, 3} => :doubly_diminished, { 2, 3} => :diminished, { 3, 3} => :minor, { 4, 3} => :major, { 5, 3} => :augmented, { 6, 3} => :doubly_augmented, { 3, 4} => :doubly_diminished, { 4, 4} => :diminished, { 5, 4} => :perfect, { 6, 4} => :augmented, { 7, 4} => :doubly_augmented, { 5, 5} => :doubly_diminished, { 6, 5} => :diminished, { 7, 5} => :perfect, { 8, 5} => :augmented, { 9, 5} => :doubly_augmented, { 6, 6} => :doubly_diminished, { 7, 6} => :diminished, { 8, 6} => :minor, { 9, 6} => :major, {10, 6} => :augmented, {11, 6} => :doubly_augmented, { 8, 7} => :doubly_diminished, { 9, 7} => :diminished, {10, 7} => :minor, {11, 7} => :major, {12, 7} => :augmented, {13, 7} => :doubly_augmented, {10, 8} => :doubly_diminished, {11, 8} => :diminished, {12, 8} => :perfect, {13, 8} => :augmented, {14, 8} => :doubly_augmented, {11, 9} => :doubly_diminished, {12, 9} => :diminished, {13, 9} => :minor, {14, 9} => :major, {15, 9} => :augmented, {16, 9} => :doubly_augmented} unless MapSet.new(@qualities) == MapSet.new(Map.values(@quality_by_semitones_and_size)) do raise "Qualities mismatch between @qualities and @quality_by_semitones_and_size" end @intervals @quality_by_semitones_and_size |> Enum.reduce([], fn({{_, size}, quality}, acc) -> [{quality, size} | acc] end) unless MapSet.new(@qualities) == MapSet.new(Keyword.keys(@intervals)) do raise "Qualities mismatch between @qualities and @intervals" end @semitones_by_quality_and_size @quality_by_semitones_and_size |> Enum.reduce(%{}, fn({{semitones, size}, quality}, acc) -> acc |> Map.put({quality, size}, semitones) end) unless MapSet.new(@qualities) == MapSet.new(Enum.map(Map.keys(@semitones_by_quality_and_size), fn {quality, _} -> quality end)) do raise "Qualities mismatch between @qualities and @semitones_by_quality_and_size" end quality_score = fn(quality) -> @qualities |> Enum.find_index(&(&1 == quality)) end @quality_list_by_size @intervals |> Enum.reduce(%{}, fn({quality, size}, acc) -> acc |> Map.put_new(size, []) |> Map.update!(size, &([quality | &1] |> Enum.sort_by(fn(q) -> quality_score.(q) end))) end) unless MapSet.new(@qualities) == MapSet.new(List.flatten(Map.values(@quality_list_by_size))) do raise "Qualities mismatch between @qualities and @quality_list_by_size" end @intervals_invalid @quality_list_by_size |> Enum.reduce([], fn({size, qualities}, acc) -> for_quality = for q <- (@qualities -- qualities) do {q, size} end acc ++ for_quality end) @invalid_quality "Invalid quality -- must be in #{inspect @qualities}" @invalid_size "Size must be a positive integer" @invalid_interval "Invalid interval" @doc """ Enharmonically compares the specified `interval1` and `interval2`. Enharmonic comparison is made on the basis of `semitones/1`. It returns: * `:eq` if they are identical or enharmonically equivalent * `:lt` if `interval1` is enharmonically narrower * `:gt` if `interval1` is enharmonically wider ## Examples iex> Harmonex.Interval.compare %{quality: :perfect, size: 4}, %{quality: :perfect, size: 4} :eq iex> Harmonex.Interval.compare %{quality: :major, size: 3}, %{quality: :diminished, size: 4} :eq iex> Harmonex.Interval.compare %{quality: :doubly_diminished, size: 6}, %{quality: :doubly_augmented, size: 4} :lt iex> Harmonex.Interval.compare %{quality: :minor, size: 10}, %{quality: :major, size: 9} :gt """ @spec compare(t, t) :: Harmonex.comparison | Harmonex.error def compare(interval1, interval2) do with semitones1 when is_integer(semitones1) <- interval1 |> semitones, semitones2 when is_integer(semitones2) <- interval2 |> semitones do cond do semitones1 < semitones2 -> :lt semitones2 < semitones1 -> :gt :else -> :eq end end end @doc """ Computes the interval between the specified `pitch1` and `pitch2`. If either specified pitch is missing an octave (see `Harmonex.Pitch.octave/1`) then octaves are ignored and the smaller of the two intervals between them is computed. ## Examples iex> Harmonex.Interval.from_pitches %{natural_name: :a, accidental: :sharp, octave: 4}, %{natural_name: :c, octave: 6} %Harmonex.Interval{quality: :diminished, size: 10} iex> Harmonex.Interval.from_pitches :a_sharp, :c %Harmonex.Interval{quality: :diminished, size: 3} iex> Harmonex.Interval.from_pitches :d_double_sharp, :a_double_sharp %Harmonex.Interval{quality: :perfect, size: 4} iex> Harmonex.Interval.from_pitches :c_flat, :c_natural %Harmonex.Interval{quality: :augmented, size: 1} iex> Harmonex.Interval.from_pitches :a_flat, :e_sharp %Harmonex.Interval{quality: :doubly_diminished, size: 4} iex> Harmonex.Interval.from_pitches :a_flat, :e_double_sharp {:error, #{inspect @invalid_interval}} """ @spec from_pitches(Pitch.t, Pitch.t) :: interval | Harmonex.error def from_pitches(pitch1, pitch2) do with semitones when is_integer(semitones) <- Pitch.semitones(pitch1, pitch2), semitones_simple <- semitones |> Integer.mod(12), interval_size_simple <- 1 + Pitch.staff_positions(pitch1, pitch2), interval_quality when is_atom(interval_quality) <- Map.get(@quality_by_semitones_and_size, {semitones_simple, interval_size_simple}, {:error, @invalid_interval}), interval_size <- interval_size_simple + (7 * div(semitones, 12)) do new %{quality: interval_quality, size: interval_size} end end @doc """ Constructs a new interval with the specified `definition`. ## Examples iex> Harmonex.Interval.new %{quality: :perfect, size: 1} %Harmonex.Interval{quality: :perfect, size: 1} iex> Harmonex.Interval.new %{quality: :augmented, size: 17} %Harmonex.Interval{quality: :augmented, size: 17} iex> Harmonex.Interval.new %{quality: :minor, size: 1} {:error, "Quality of unison must be in [:perfect, :augmented, :doubly_augmented]"} iex> Harmonex.Interval.new %{quality: :major, size: 8} {:error, "Quality of octave must be in [:perfect, :diminished, :augmented, :doubly_diminished, :doubly_augmented]"} iex> Harmonex.Interval.new %{quality: :perfect, size: 0} {:error, #{inspect @invalid_size}} iex> Harmonex.Interval.new %{quality: :minor, size: -3} {:error, #{inspect @invalid_size}} iex> Harmonex.Interval.new %{quality: :minor} {:error, #{inspect @invalid_size}} """ @spec new(t) :: interval | Harmonex.error @spec new(quality, size) :: interval | Harmonex.error for {quality, size} <- @intervals do def new(%{quality: unquote(quality), size: unquote(size)}=definition) do __MODULE__ |> struct(Map.delete(definition, :__struct__)) end @doc """ Constructs a new interval with the specified `quality` and `size`. ## Examples iex> Harmonex.Interval.new :perfect, 1 %Harmonex.Interval{quality: :perfect, size: 1} iex> Harmonex.Interval.new :augmented, 17 %Harmonex.Interval{quality: :augmented, size: 17} iex> Harmonex.Interval.new :minor, 1 {:error, "Quality of unison must be in [:perfect, :augmented, :doubly_augmented]"} iex> Harmonex.Interval.new :major, 8 {:error, "Quality of octave must be in [:perfect, :diminished, :augmented, :doubly_diminished, :doubly_augmented]"} iex> Harmonex.Interval.new :imperfect, 1 {:error, #{inspect @invalid_quality}} iex> Harmonex.Interval.new :perfect, 0 {:error, #{inspect @invalid_size}} iex> Harmonex.Interval.new :minor, -3 {:error, #{inspect @invalid_size}} iex> Harmonex.Interval.new :minor, nil {:error, #{inspect @invalid_size}} """ def new(unquote(quality)=quality, unquote(size)=size) do new %{quality: quality, size: size} end end for {quality, size} <- @intervals_invalid do def new(%{quality: unquote(quality), size: unquote(size)=size}=_definition) do error_quality size, size end def new(unquote(quality), unquote(size)=size), do: error_quality(size, size) end for quality <- @qualities do def new(%{quality: unquote(quality), size: size}=_definition) when not is_integer(size) do {:error, @invalid_size} end def new(%{quality: unquote(quality), size: size}=_definition) when size <= 0 do {:error, @invalid_size} end def new(%{quality: unquote(quality), size: size}=definition) do next_size = size - 7 case new(%{definition | size: next_size}) do interval when is_map(interval) -> __MODULE__ |> struct(Map.delete(definition, :__struct__)) {:error, _} -> error_quality next_size, size end end def new(%{quality: unquote(quality)}=_definition) do {:error, @invalid_size} end def new(unquote(quality)=quality, size) do new %{quality: quality, size: size} end end def new(_definition), do: {:error, @invalid_quality} def new(_quality, _size), do: {:error, @invalid_quality} @doc """ Computes the distance in half steps across the specified `interval`. ## Examples iex> Harmonex.Interval.semitones %{quality: :major, size: 3} 4 iex> Harmonex.Interval.semitones %{quality: :doubly_diminished, size: 9} 11 iex> Harmonex.Interval.semitones %{quality: :doubly_diminished, size: 16} 23 iex> Harmonex.Interval.semitones %{quality: :augmented, size: 300} 514 """ @spec semitones(t) :: semitones | Harmonex.error def semitones(interval) do with %{quality: interval_quality, size: interval_size} <- interval |> new do case @semitones_by_quality_and_size |> Map.get({interval_quality, interval_size}) do semitones when is_integer(semitones) -> semitones _ -> simple_size = interval_size |> Integer.mod(7) case %{quality: interval_quality, size: simple_size} |> semitones do semitones when is_integer(semitones) -> semitones + (12 * div(interval_size, 7)) _ -> semitones = %{quality: interval_quality, size: simple_size + 7} |> semitones semitones + (12 * (div(interval_size, 7) - 1)) end end end end @doc """ Determines if the specified `interval` cannot be simplified (see `simplify/1`). Simple intervals are no more than 11 semitones across (see `semitones/1`). ## Examples iex> Harmonex.Interval.simple? %{quality: :major, size: 10} false iex> Harmonex.Interval.simple? %{quality: :major, size: 3} true iex> Harmonex.Interval.simple? %{quality: :augmented, size: 8} false iex> Harmonex.Interval.simple? %{quality: :diminished, size: 8} true """ @spec simple?(t) :: boolean | Harmonex.error def simple?(interval) do with interval_struct when is_map(interval_struct) <- interval |> new, simplified <- simplify(interval) do interval_struct == simplified end end @doc """ Computes the simple interval that corresponds to the specified `interval`. Simple intervals are no more than 11 semitones across (see `semitones/1`). ## Examples iex> Harmonex.Interval.simplify %{quality: :major, size: 10} %Harmonex.Interval{quality: :major, size: 3} iex> Harmonex.Interval.simplify %{quality: :major, size: 3} %Harmonex.Interval{quality: :major, size: 3} iex> Harmonex.Interval.simplify %{quality: :augmented, size: 8} %Harmonex.Interval{quality: :augmented, size: 1} iex> Harmonex.Interval.simplify %{quality: :diminished, size: 8} %Harmonex.Interval{quality: :diminished, size: 8} """ @spec simplify(t) :: interval | Harmonex.error def simplify(interval) do with interval_struct when is_map(interval_struct) <- new(interval), simplified <- simplify_impl(interval_struct) do if simplified |> new |> is_map, do: simplified, else: interval_struct end end @spec error_quality(size, size) :: Harmonex.error for {size_in_lookup, qualities} <- @quality_list_by_size do defp error_quality(unquote(size_in_lookup), size) do {:error, "Quality of #{Ordinal.to_string size} must be in #{inspect unquote(qualities)}"} end end defp error_quality(size_in_lookup, size) do error_quality size_in_lookup - 7, size end @spec simplify_impl(t) :: t defp simplify_impl(%{size: size}=interval) do %{interval | size: Integer.mod(size, 7)} end end
lib/harmonex/interval.ex
0.871789
0.767189
interval.ex
starcoder
defmodule Bolt.Sips.Internals.PackStream.EncoderV2 do @moduledoc false use Bolt.Sips.Internals.PackStream.Markers alias Bolt.Sips.Internals.PackStream.EncoderHelper alias Bolt.Sips.Types.{TimeWithTZOffset, DateTimeWithTZOffset, Duration, Point} @doc """ Encode a Time (represented by Time) into Bolt binary format. Encoded in a structure. Signature: `0x74` Encoding: `Marker` `Size` `Signature` ` Content` where `Content` is: `Nanoseconds_from_00:00:00` ## Example iex> :erlang.iolist_to_binary(Bolt.Sips.Internals.PackStream.EncoderV2.encode_local_time(~T[06:54:32.453], 2)) <<0xB1, 0x74, 0xCB, 0x0, 0x0, 0x16, 0x9F, 0x11, 0xB9, 0xCB, 0x40>> """ @spec encode_local_time(Time.t(), integer()) :: Bolt.Sips.Internals.PackStream.value() def encode_local_time(local_time, bolt_version), do: EncoderHelper.call_encode(:local_time, local_time, bolt_version) @doc """ Encode a TIME WITH TIMEZONE OFFSET (represented by TimeWithTZOffset) into Bolt binary format. Encoded in a structure. Signature: `0x54` Encoding: `Marker` `Size` `Signature` ` Content` where `Content` is: `Nanoseconds_from_00:00:00` `Offset_in_seconds` ## Example iex> time_with_tz = Bolt.Sips.Types.TimeWithTZOffset.create(~T[06:54:32.453], 3600) iex> :erlang.iolist_to_binary(Bolt.Sips.Internals.PackStream.EncoderV2.encode_time_with_tz(time_with_tz, 2)) <<0xB2, 0x54, 0xCB, 0x0, 0x0, 0x16, 0x9F, 0x11, 0xB9, 0xCB, 0x40, 0xC9, 0xE, 0x10>> """ def encode_time_with_tz(%TimeWithTZOffset{time: time, timezone_offset: offset}, bolt_version), do: EncoderHelper.call_encode(:time_with_tz, %TimeWithTZOffset{time: time, timezone_offset: offset}, bolt_version ) @doc """ Encode a DATE (represented by Date) into Bolt binary format. Encoded in a structure. Signature: `0x44` Encoding: `Marker` `Size` `Signature` ` Content` where `Content` is: `Nb_days_since_epoch` ## Example iex> :erlang.iolist_to_binary(Bolt.Sips.Internals.PackStream.EncoderV2.encode_date(~D[2019-04-23], 2)) <<0xB1, 0x44, 0xC9, 0x46, 0x59>> """ @spec encode_date(Date.t(), integer()) :: Bolt.Sips.Internals.PackStream.value() def encode_date(date, bolt_version), do: EncoderHelper.call_encode(:date, date, bolt_version) @doc """ Encode a LOCAL DATETIME (Represented by NaiveDateTime) into Bolt binary format. Encoded in a structure. WARNING: Nanoseconds are left off as NaiveDateTime doesn't handle them. A new Calendar should be implemented to manage them. Signature: `0x64` Encoding: `Marker` `Size` `Signature` ` Content` where `Content` is: `Nb_seconds_since_epoch` `Remainder_in_nanoseconds` ## Example iex> :erlang.iolist_to_binary(Bolt.Sips.Internals.PackStream.EncoderV2.encode_local_datetime(~N[2019-04-23 13:45:52.678], 2)) <<0xB2, 0x64, 0xCA, 0x5C, 0xBF, 0x17, 0x10, 0xCA, 0x28, 0x69, 0x75, 0x80>> """ @spec encode_local_datetime(Calendar.naive_datetime(), integer()) :: Bolt.Sips.Internals.PackStream.value() def encode_local_datetime(local_datetime, bolt_version), do: EncoderHelper.call_encode(:local_datetime, local_datetime, bolt_version) @doc """ Encode DATETIME WITH TIMEZONE ID (represented by Calendar.DateTime) into Bolt binary format. Encoded in a structure. WARNING: Nanoseconds are left off as NaiveDateTime doesn't handle them. A new Calendar should be implemented to manage them. Signature: `0x66` Encoding: `Marker` `Size` `Signature` ` Content` where `Content` is: `Nb_seconds_since_epoch` `Remainder_in_nanoseconds` `Zone_id` ## Example iex> d = Bolt.Sips.TypesHelper.datetime_with_micro(~N[2013-11-12 07:32:02.003], ...> "Europe/Berlin") #DateTime<2013-11-12 07:32:02.003+01:00 CET Europe/Berlin> iex> :erlang.iolist_to_binary(Bolt.Sips.Internals.PackStream.EncoderV2.encode_datetime_with_tz_id(d, 2)) <<0xB3, 0x66, 0xCA, 0x52, 0x81, 0xD9, 0x72, 0xCA, 0x0, 0x2D, 0xC6, 0xC0, 0x8D, 0x45, 0x75, 0x72, 0x6F, 0x70, 0x65, 0x2F, 0x42, 0x65, 0x72, 0x6C, 0x69, 0x6E>> """ @spec encode_datetime_with_tz_id(Calendar.datetime(), integer()) :: Bolt.Sips.Internals.PackStream.value() def encode_datetime_with_tz_id(datetime, bolt_version), do: EncoderHelper.call_encode(:datetime_with_tz_id, datetime, bolt_version) @doc """ Encode DATETIME WITH TIMEZONE OFFSET (represented by DateTimeWithTZOffset) into Bolt binary format. Encoded in a structure. WARNING: Nanoseconds are left off as NaiveDateTime doesn't handle them. A new Calendar should be implemented to manage them. Signature: `0x46` Encoding: `Marker` `Size` `Signature` ` Content` where `Content` is: `Nb_seconds_since_epoch` `Remainder_in_nanoseconds` `Zone_offset` ## Example iex> d = Bolt.Sips.Types.DateTimeWithTZOffset.create(~N[2013-11-12 07:32:02.003], 7200) %Bolt.Sips.Types.DateTimeWithTZOffset{ naive_datetime: ~N[2013-11-12 07:32:02.003], timezone_offset: 7200 } iex> :erlang.iolist_to_binary(Bolt.Sips.Internals.PackStream.EncoderV2.encode_datetime_with_tz_offset(d, 2)) <<0xB3, 0x46, 0xCA, 0x52, 0x81, 0xD9, 0x72, 0xCA, 0x0, 0x2D, 0xC6, 0xC0, 0xC9, 0x1C, 0x20>> """ @spec encode_datetime_with_tz_offset(DateTimeWithTZOffset.t(), integer()) :: Bolt.Sips.Internals.PackStream.value() def encode_datetime_with_tz_offset( %DateTimeWithTZOffset{naive_datetime: ndt, timezone_offset: tz_offset}, bolt_version ), do: EncoderHelper.call_encode(:datetime_with_tz_offset, %DateTimeWithTZOffset{naive_datetime: ndt, timezone_offset: tz_offset}, bolt_version ) @doc """ Encode DURATION (represented by Duration) into Bolt binary format. Encoded in a structure. Signature: `0x45` Encoding: `Marker` `Size` `Signature` ` Content` where `Content` is: `Months` `Days` `Seconds` `Nanoseconds` ## Example iex(60)> d = %Bolt.Sips.Types.Duration{ ...(60)> years: 3, ...(60)> months: 1, ...(60)> weeks: 7, ...(60)> days: 4, ...(60)> hours: 13, ...(60)> minutes: 2, ...(60)> seconds: 21, ...(60)> nanoseconds: 554 ...(60)> } %Bolt.Sips.Types.Duration{ days: 4, hours: 13, minutes: 2, months: 1, nanoseconds: 554, seconds: 21, weeks: 7, years: 3 } iex> :erlang.iolist_to_binary(Bolt.Sips.Internals.PackStream.EncoderV2.encode_duration(d, 2)) <<0xB4, 0x45, 0x25, 0x35, 0xCA, 0x0, 0x0, 0xB7, 0x5D, 0xC9, 0x2, 0x2A>> """ @spec encode_duration(Duration.t(), integer()) :: Bolt.Sips.Internals.PackStream.value() def encode_duration(%Duration{} = duration, bolt_version), do: EncoderHelper.call_encode(:duration, duration, bolt_version) @doc """ Encode POINT 2D & 3D (represented by Point) into Bolt binary format. Encoded in a structure. ## Point 2D Signature: `0x58` Encoding: `Marker` `Size` `Signature` ` Content` where `Content` is: `SRID` `x_or_longitude` `y_or_latitude` ## Example iex> p = Bolt.Sips.Types.Point.create(:wgs_84, 65.43, 12.54) %Bolt.Sips.Types.Point{ crs: "wgs-84", height: nil, latitude: 12.54, longitude: 65.43, srid: 4326, x: 65.43, y: 12.54, z: nil } iex> :erlang.iolist_to_binary(Bolt.Sips.Internals.PackStream.EncoderV2.encode_point(p, 2)) <<0xB3, 0x58, 0xC9, 0x10, 0xE6, 0xC1, 0x40, 0x50, 0x5B, 0x85, 0x1E, 0xB8, 0x51, 0xEC, 0xC1, 0x40, 0x29, 0x14, 0x7A, 0xE1, 0x47, 0xAE, 0x14>> ## Point 3D Signature: `0x58` Encoding: `Marker` `Size` `Signature` ` Content` where `Content` is: `SRID` `x_or_longitude` `y_or_latitude` `z_or_height` ## Example iex> p = Bolt.Sips.Types.Point.create(:wgs_84, 45.0003, 40.3245, 23.1) %Bolt.Sips.Types.Point{ crs: "wgs-84-3d", height: 23.1, latitude: 40.3245, longitude: 45.0003, srid: 4979, x: 45.0003, y: 40.3245, z: 23.1 } iex> :erlang.iolist_to_binary(Bolt.Sips.Internals.PackStream.EncoderV2.encode_point(p, 2)) <<0xB4, 0x59, 0xC9, 0x13, 0x73, 0xC1, 0x40, 0x46, 0x80, 0x9, 0xD4, 0x95, 0x18, 0x2B, 0xC1, 0x40, 0x44, 0x29, 0x89, 0x37, 0x4B, 0xC6, 0xA8, 0xC1, 0x40, 0x37, 0x19, 0x99, 0x99, 0x99, 0x99, 0x9A>> """ @spec encode_point(Point.t(), integer()) :: Bolt.Sips.Internals.PackStream.value() def encode_point(%Point{z: nil} = point, bolt_version), do: EncoderHelper.call_encode(:point, point, bolt_version) def encode_point(%Point{} = point, bolt_version), do: EncoderHelper.call_encode(:point, point, bolt_version) end
lib/bolt_sips/internals/pack_stream/encoder_v2.ex
0.903182
0.713818
encoder_v2.ex
starcoder
defmodule Membrane.Element.Base.Source do @moduledoc """ Module defining behaviour for sources - elements producing data. Behaviours for filters are specified, besides this place, in modules `Membrane.Element.Base.Mixin.CommonBehaviour`, `Membrane.Element.Base.Mixin.SourceBehaviour`. Source elements can define only source pads. Job of a usual source is to produce some data (read from soundcard, download through HTTP, etc.) and send it through such pad. If the pad works in pull mode, then element is also responsible for receiving demands, and send buffers only if they have previously been demanded (for more details, see `c:Membrane.Element.Base.Mixin.SourceBehaviour.handle_demand/5` callback). Sources, like all elements, can of course have multiple pads if needed to provide more complex solutions. """ alias Membrane.Element alias Element.Base.Mixin alias Element.{CallbackContext, Pad} @doc """ Callback that is called when buffers should be emitted by the source. In contrast to `c:Membrane.Element.Base.Mixin.SourceBehaviour.handle_demand/5`, size is not passed, but should always be considered to equal 1. Called by default implementation of `c:Membrane.Element.Base.Mixin.SourceBehaviour.handle_demand/5`, check documentation for that callback for more information. """ @callback handle_demand1( pad :: Pad.name_t(), context :: CallbackContext.Demand.t(), state :: Element.state_t() ) :: Mixin.CommonBehaviour.callback_return_t() defmacro __using__(_) do quote location: :keep do use Mixin.CommonBehaviour use Mixin.SourceBehaviour @behaviour unquote(__MODULE__) @impl true def membrane_element_type, do: :source @impl true def handle_demand1(_pad, _context, state), do: {{:error, :handle_demand_not_implemented}, state} @impl true def handle_demand(pad, size, :buffers, context, state) do args_list = Stream.repeatedly(fn -> nil end) |> Stream.take(size) |> Enum.map(fn _ -> [pad, context] end) {{:ok, split: {:handle_demand1, args_list}}, state} end def handle_demand(_pad, _size, _unit, _context, state), do: {{:error, :handle_demand_not_implemented}, state} defoverridable handle_demand1: 3, handle_demand: 5 end end end
lib/membrane/element/base/source.ex
0.869396
0.405508
source.ex
starcoder
defmodule Starchoice do @external_resource "README.md" @moduledoc "README.md" |> File.read!() |> String.split("<!-- MDOC !-->") |> Enum.fetch!(1) alias Starchoice.Decoder @type decoder :: Decoder.t() | function() | module() | {module(), atom()} @type decode_option :: {:as_map, boolean()} @doc """ Decodes a map into a `{:ok, _} | {:error | _}` tuple format. It accepts the same options and parameters as `decode!/3` """ @spec decode(any(), decoder(), [decode_option()]) :: {:ok, any()} | {:error, any()} def decode(item, decoder, options \\ []) do result = decode!(item, decoder, options) {:ok, result} rescue error -> {:error, error} end @doc """ Decodes a map into according to the given decoder. A decoder can either be a `%Starchoice.Decoder{}`, a one or two arity function that returns a decoder or a module implementing `Starchoice.Decoder`. See module `Starchoice.Decoder` for more information about decoders. ## Examples ```elixir iex> decoder = %Decoder{struct: User, fields: [first_name: [], age: [with: &String.to_integer/1]]} iex> Decoder.decode!(%{"first_name" => "<NAME>", "age" => "13"}, decoder) %User{first_name: "<NAME>", age: 13} ``` If the module `User` implements `Starchoice.Decoder`, it can be used directly ```elixir iex> Decoder.decode!(%{"first_name" => "<NAME>", "age" => "13"}, User) iex> Decoder.decode!(%{"first_name" => "<NAME>", "age" => "13"}, {User, :default}) # same as above ``` """ @spec decode!(any(), decoder(), [decode_option]) :: any() def decode!(items, decoder, options \\ []) def decode!(items, decoder, options) when is_list(items) do Enum.map(items, &decode!(&1, decoder, options)) end def decode!(item, _decoder, _options) when is_nil(item), do: nil def decode!(item, %Decoder{fields: fields, struct: struct}, options) do fields = Enum.reduce(fields, %{}, fn {field, opts}, map -> source_name = opts |> Keyword.get(:source, field) |> to_string() value = item |> Map.get(source_name) |> decode_field!(field, opts, options) Map.put(map, field, value) end) if Keyword.get(options, :as_map, struct == :map) do fields else struct(struct, fields) end end def decode!(item, decoder, options) do case fetch_decoder(item, decoder, options) do %Decoder{} = decoder -> decode!(item, decoder, options) result -> result end end defp fetch_decoder(item, decoder, options) do case decoder do {decoder, sub_decoder} -> decoder.__decoder__(sub_decoder) decoder when is_atom(decoder) -> decoder.__decoder__(:default) func when is_function(func, 1) -> func.(item) func when is_function(func, 2) -> func.(item, options) end end defp decode_field!(nil, field, opts, _) do cond do Keyword.has_key?(opts, :default) -> Keyword.get(opts, :default) Keyword.get(opts, :required, false) -> raise "Field #{field} is marked as required" true -> nil end end defp decode_field!(value, _, opts, decode_options) do value = sanitize_field(value, opts) case Keyword.get(opts, :with) do nil -> value decoder -> decode!(value, decoder, decode_options) end end defp sanitize_field(value, opts) do case Keyword.get(opts, :sanitize, true) do true -> sanitize(value) func when is_function(func) -> func.(value) _ -> value end end defp sanitize(""), do: nil defp sanitize(str) when is_bitstring(str) do case String.trim(str) do "" -> nil str -> str end end defp sanitize(value), do: value end
lib/starchoice.ex
0.900479
0.734358
starchoice.ex
starcoder
defmodule Unicode.Block do @moduledoc """ Functions to introspect Unicode blocks for binaries (Strings) and codepoints. """ @behaviour Unicode.Property.Behaviour alias Unicode.Utils @blocks Utils.blocks() |> Utils.remove_annotations() @doc """ Returns the map of Unicode blocks. The block name is the map key and a list of codepoint ranges as tuples as the value. """ def blocks do @blocks end @doc """ Returns a list of known Unicode block names. This function does not return the names of any block aliases. """ @known_blocks Map.keys(@blocks) def known_blocks do @known_blocks end @block_alias Utils.property_value_alias() |> Map.get("blk") |> Utils.invert_map() |> Utils.atomize_values() |> Utils.downcase_keys_and_remove_whitespace() |> Utils.add_canonical_alias() @doc """ Returns a map of aliases for Unicode blocks. An alias is an alternative name for referring to a block. Aliases are resolved by the `fetch/1` and `get/1` functions. """ @impl Unicode.Property.Behaviour def aliases do @block_alias end @doc """ Returns the Unicode ranges for a given block as a list of ranges as 2-tuples. Aliases are resolved by this function. Returns either `{:ok, range_list}` or `:error`. """ @impl Unicode.Property.Behaviour def fetch(block) when is_atom(block) do Map.fetch(blocks(), block) end def fetch(block) do block = Utils.downcase_and_remove_whitespace(block) block = Map.get(aliases(), block, block) Map.fetch(blocks(), block) end @doc """ Returns the Unicode ranges for a given block as a list of ranges as 2-tuples. Aliases are resolved by this function. Returns either `range_list` or `nil`. """ @impl Unicode.Property.Behaviour def get(block) do case fetch(block) do {:ok, block} -> block _ -> nil end end @doc """ Returns the count of the number of characters for a given block. Aliases are resolved by this function. ## Example iex> Unicode.Block.count(:old_north_arabian) 32 """ @impl Unicode.Property.Behaviour def count(block) do with {:ok, block} <- fetch(block) do Enum.reduce(block, 0, fn {from, to}, acc -> acc + to - from + 1 end) end end @doc """ Returns the block name(s) for the given binary or codepoint. In the case of a codepoint, a single block name is returned. For a binary a list of distinct block names represented by the graphemes in the binary is returned. """ def block(string) when is_binary(string) do string |> String.to_charlist() |> Enum.map(&block/1) |> Enum.uniq() end for {block, ranges} <- @blocks do def block(codepoint) when unquote(Utils.ranges_to_guard_clause(ranges)) do unquote(block) end end def block(codepoint) when is_integer(codepoint) and codepoint in 0..0x10FFFF do :no_block end @doc """ Returns a list of tuples representing the assigned ranges of all Unicode code points. """ @assigned @blocks |> Map.values() |> Enum.map(&hd/1) |> Enum.sort() |> Unicode.compact_ranges() def assigned do @assigned end end
lib/unicode/block.ex
0.918045
0.611324
block.ex
starcoder
defmodule DemoWeb.UrGame do @special_positions [4, 8, 14] @battle_ground 5..12 @home_position 15 @initial_state %{ current_roll: nil, alice_socket: nil, bob_socket: nil, current_player: :alice, alice: Enum.map(1..7, fn _ -> 0 end), bob: Enum.map(1..7, fn _ -> 0 end), winner: nil } def initial_state do @initial_state end def special_position?(index) do @special_positions |> Enum.member?(index) end def possible_moves(state) do current_positions = case state.current_roll do nil -> [] _ -> Map.get(state, state.current_player) end current_positions |> Enum.map(fn index -> index + state.current_roll end) |> Enum.reject(fn index -> index > @home_position end) |> Enum.reject(fn index -> index in 1..(@home_position - 1) && Enum.member?(current_positions, index) end) |> Enum.reject(fn index -> blocked_by_opponent(state, index) end) |> Enum.uniq() end def roll_update(state) do state = state |> Map.merge(%{current_roll: roll()}) move_count = state |> possible_moves |> Enum.count() if move_count == 0, do: switch_player(state), else: state end def move_update(state, move_to) do player = Map.get(state, state.current_player) moved_index = player |> Enum.find_index(fn position -> position == move_to - state.current_roll end) new_player_positions = List.replace_at(player, moved_index, move_to) state = state |> Map.put(state.current_player, new_player_positions) |> maybe_bump_opponent |> maybe_declare_victory |> Map.put(:current_roll, nil) if special_position?(move_to), do: state, else: switch_player(state) end defp roll() do Enum.sum([Enum.random(0..1), Enum.random(0..1), Enum.random(0..1), Enum.random(0..1)]) end defp blocked_by_opponent(state, index) do opponent_positions = Map.get(state, opponent(state)) special_position?(index) && Enum.member?(opponent_positions, index) && Enum.member?(@battle_ground, index) end defp switch_player(state) do state |> Map.merge(%{current_player: opponent(state), current_roll: nil}) end defp opponent(state) do case state.current_player do :alice -> :bob _ -> :alice end end defp maybe_declare_victory(state) do positions = Map.get(state, state.current_player) if Enum.all?(positions, fn position -> position == @home_position end) do state |> Map.put(:winner, state.current_player) else state end end defp maybe_bump_opponent(state) do player_positions = Map.get(state, state.current_player) opponent_positions = Map.get(state, opponent(state)) bump_index = opponent_positions |> Enum.find_index(fn position -> Enum.member?(@battle_ground, position) && Enum.member?(player_positions, position) end) if bump_index, do: bump_at(state, bump_index), else: state end defp bump_at(state, index) do opponent_positions = Map.get(state, opponent(state)) |> List.replace_at(index, 0) state |> Map.put(opponent(state), opponent_positions) end end
lib/demo_web/live/ur_game.ex
0.508788
0.412205
ur_game.ex
starcoder
defmodule Instream.Encoder.Line do @moduledoc """ Encoder module for the line protocol. Takes a list of points and returns the data string to be passed to the write endpoint of influxdb. """ @type point_map :: %{ required(:fields) => [{term, term}], required(:measurement) => term, optional(:tags) => [{term, term}], optional(:timestamp) => term } @doc """ Creates the write string for a list of data points. """ @spec encode([point_map()]) :: binary def encode(points), do: points |> encode([]) defp encode([], lines) do lines |> Enum.reverse() |> Enum.join("\n") end defp encode([point | points], lines) do line = point.measurement |> encode_property() |> append_tags(point) |> append_fields(point) |> append_timestamp(point) encode(points, [line | lines]) end defp append_fields(line, %{fields: fields}) do "#{line} #{encode_fields(fields)}" end defp append_tags(line, %{tags: tags}) do tags |> Enum.filter(fn {_, nil} -> false {_, _} -> true end) |> Enum.reduce([], fn {tag, value}, acc -> ["#{encode_property(tag)}=#{encode_property(value)}" | acc] end) |> List.insert_at(0, line) |> Enum.join(",") end defp append_tags(line, _), do: line defp append_timestamp(line, %{timestamp: nil}), do: line defp append_timestamp(line, %{timestamp: ts}), do: "#{line} #{ts}" defp append_timestamp(line, _), do: line defp encode_fields(fields) do fields |> Enum.filter(fn {_, nil} -> false {_, _} -> true end) |> Enum.reduce([], fn {field, value}, acc -> ["#{encode_property(field)}=#{encode_value(value)}" | acc] end) |> Enum.join(",") end defp encode_value(i) when is_integer(i), do: "#{i}i" defp encode_value(s) when is_binary(s), do: "\"#{String.replace(s, "\"", "\\\"")}\"" defp encode_value(true), do: "true" defp encode_value(false), do: "false" defp encode_value(other), do: inspect(other) defp encode_property([a | _] = atoms) when is_atom(a) do atoms |> Enum.map(&Atom.to_string/1) |> escape() |> Enum.join(",") end defp encode_property(l) when is_list(l) do l |> Enum.map(&Kernel.to_string/1) |> escape() |> Enum.join(",") end defp encode_property(s) do s |> Kernel.to_string() |> escape() end defp escape(l) when is_list(l), do: Enum.map(l, &escape/1) defp escape(s) when is_binary(s) do s |> String.replace(",", "\\,", global: true) |> String.replace(" ", "\\ ", global: true) |> String.replace("=", "\\=", global: true) end end
lib/instream/encoder/line.ex
0.757122
0.472501
line.ex
starcoder
defmodule ExopData.Generators.Float do @moduledoc """ Implements ExopData generators behaviour for `float` parameter type. """ alias ExopData.Generators.AliasResolvers.Numericality @behaviour ExopData.Generator @diff 0.1 def generate(opts \\ %{}, _props_opts \\ %{}) do opts |> Map.get(:numericality) |> Numericality.resolve_aliases() |> do_generate() end @spec do_generate(map()) :: StreamData.t() defp do_generate(%{equal_to: exact}), do: constant(exact) defp do_generate(%{equals: exact}), do: constant(exact) defp do_generate(%{is: exact}), do: constant(exact) defp do_generate(%{eq: exact}), do: constant(exact) # defp do_generate(%{gt: gt} = contract) do # contract # |> Map.delete(:gt) # |> Map.put(:greater_than, gt) # |> do_generate() # end # defp do_generate(%{gte: gte} = contract) do # contract # |> Map.delete(:gte) # |> Map.put(:greater_than_or_equal_to, gte) # |> do_generate() # end # defp do_generate(%{min: min} = contract) do # contract # |> Map.delete(:min) # |> Map.put(:greater_than_or_equal_to, min) # |> do_generate() # end # defp do_generate(%{lt: lt} = contract) do # contract # |> Map.delete(:lt) # |> Map.put(:less_than, lt) # |> do_generate() # end # defp do_generate(%{lte: lte} = contract) do # contract # |> Map.delete(:lte) # |> Map.put(:less_than_or_equal_to, lte) # |> do_generate() # end # defp do_generate(%{max: max} = contract) do # contract # |> Map.delete(:max) # |> Map.put(:less_than_or_equal_to, max) # |> do_generate() # end defp do_generate(%{greater_than: greater_than, less_than: less_than}) do StreamData.filter( StreamData.float(min: greater_than - @diff, max: less_than + @diff), &(&1 > greater_than && &1 < less_than) ) end defp do_generate(%{greater_than: greater_than, less_than_or_equal_to: less_than_or_equal_to}) do StreamData.filter( StreamData.float(min: greater_than - @diff, max: less_than_or_equal_to), &(&1 > greater_than && &1 <= less_than_or_equal_to) ) end defp do_generate(%{greater_than_or_equal_to: greater_than_or_equal_to, less_than: less_than}) do StreamData.filter( StreamData.float(min: greater_than_or_equal_to, max: less_than + @diff), &(&1 >= greater_than_or_equal_to && &1 < less_than) ) end defp do_generate(%{ greater_than_or_equal_to: greater_than_or_equal_to, less_than_or_equal_to: less_than_or_equal_to }) do StreamData.filter( StreamData.float(min: greater_than_or_equal_to, max: less_than_or_equal_to), &(&1 >= greater_than_or_equal_to && &1 <= less_than_or_equal_to) ) end defp do_generate(%{greater_than: greater_than}) do StreamData.filter(StreamData.float(min: greater_than - @diff), &(&1 > greater_than)) end defp do_generate(%{greater_than_or_equal_to: greater_than_or_equal_to}) do StreamData.filter( StreamData.float(min: greater_than_or_equal_to), &(&1 >= greater_than_or_equal_to) ) end defp do_generate(%{less_than: less_than}) do StreamData.filter(StreamData.float(max: less_than + @diff), &(&1 < less_than)) end defp do_generate(%{less_than_or_equal_to: less_than_or_equal_to}) do StreamData.filter( StreamData.float(max: less_than_or_equal_to), &(&1 <= less_than_or_equal_to) ) end defp do_generate(_), do: StreamData.float() @spec constant(float()) :: StreamData.t() defp constant(value), do: StreamData.constant(value) end
lib/exop_data/generators/float.ex
0.742982
0.555978
float.ex
starcoder
defmodule Axon.Training do @moduledoc """ Abstractions for training machine learning models. """ require Axon require Axon.Updates alias Axon.Training.Step @doc false def step({_, _} = model, {_, _} = update), do: step(model, update, []) @doc """ Represents a single training step. The first two arguments are tuples: * The first tuple contains the model initialization function and the objective function. For a Neural Network, the objective function is the loss function of the Neural Network prediction * The second pairs contains the updater initialization function and the update function itself ## Options * `:metrics` - metrics to track during each training step. Can be an atom representing a function in `Axon.Metrics`, or a 2-arity function taking `y_true` and `y_pred` as args. """ def step({init_model_fn, objective_fn}, {init_update_fn, update_fn}, opts) when is_function(init_model_fn, 0) and is_function(objective_fn, 3) and is_function(init_update_fn, 1) and is_function(update_fn, 3) and is_list(opts) do metrics = opts[:metrics] || [] update_metrics_fn = fn old_metrics, step, y_true, y_pred -> Map.new(metrics, fn {key, fun} -> batch_metric = fun.(y_true, y_pred) avg_metric = old_metrics[key] |> Nx.multiply(step) |> Nx.add(batch_metric) |> Nx.divide(Nx.add(step, 1)) {key, avg_metric} key -> batch_metric = apply(Axon.Metrics, key, [y_true, y_pred]) avg_metric = old_metrics[key] |> Nx.multiply(step) |> Nx.add(batch_metric) |> Nx.divide(Nx.add(step, 1)) {key, avg_metric} end) end init_fn = fn -> params = init_model_fn.() optim_params = init_update_fn.(params) init_metrics = Map.new(metrics, fn k -> {k, Nx.tensor(0.0, backend: Nx.Defn.Expr)} end) %{ epoch: Nx.tensor(0, backend: Nx.Defn.Expr), epoch_step: Nx.tensor(0, backend: Nx.Defn.Expr), epoch_loss: Nx.tensor(0.0, backend: Nx.Defn.Expr), params: params, optimizer_state: optim_params, metrics: init_metrics } end step_fn = fn train_state, input, target -> {{preds, batch_loss}, gradients} = Nx.Defn.value_and_grad( train_state[:params], &objective_fn.(&1, input, target), fn x -> elem(x, 1) end ) new_metrics = case metrics do [] -> %{} _ -> update_metrics_fn.(train_state[:metrics], train_state[:epoch_step], target, preds) end epoch_avg_loss = train_state[:epoch_loss] |> Nx.multiply(train_state[:epoch_step]) |> Nx.add(batch_loss) |> Nx.divide(Nx.add(train_state[:epoch_step], 1)) {updates, new_update_state} = update_fn.(gradients, train_state[:optimizer_state], train_state[:params]) # TODO(seanmor5): We probably shouldn't cast here updates = updates |> Map.new(fn {k, v} -> {k, Nx.as_type(v, Nx.type(train_state[:params][k]))} end) %{ epoch: train_state[:epoch], epoch_step: Nx.add(train_state[:epoch_step], 1), epoch_loss: epoch_avg_loss, params: Axon.Updates.apply_updates(train_state[:params], updates), optimizer_state: new_update_state, metrics: new_metrics } end %Step{init: init_fn, step: step_fn, callbacks: []} end @doc false def step(%Axon{} = model, loss, {_, _} = optimizer) when is_function(loss, 2) or is_atom(loss), do: step(model, loss, optimizer, []) @doc """ Represents a single training step using an Axon `model`, `loss` function, and `optimizer`. The `loss` function is either an atom or a two arity anonymous function. """ def step(%Axon{} = model, loss, optimizer, opts) when is_function(loss, 2) and is_list(opts) do {init_fn, predict_fn} = Axon.compile(model) objective_fn = fn params, input, target -> preds = predict_fn.(params, input) loss = Nx.add(loss.(target, preds), Axon.penalty(model, params)) {preds, loss} end step({init_fn, objective_fn}, optimizer, opts) end def step(%Axon{} = model, loss, optimizer, opts) when is_atom(loss) and is_list(opts) do loss_fn = &apply(Axon.Losses, loss, [&1, &2, [reduction: :mean]]) step(model, loss_fn, optimizer, opts) end @doc false def step(%Axon{} = model, train_state, loss, {_, _} = optimizer) when is_function(loss, 2) or is_atom(loss), do: step(model, train_state, loss, optimizer, []) @doc """ Represents a single training step using an Axon `model`, initial state `train_state`, `loss` function and `optimizer`. The `loss` function is either an atom or a two arity anonymous function. """ def step(%Axon{} = model, train_state, loss, optimizer, opts) when is_function(loss, 2) and is_list(opts) do init_fn = fn -> train_state |> Tuple.to_list() |> Enum.map(&Nx.tensor(&1, backend: Nx.Defn.Expr)) |> List.to_tuple() end objective_fn = fn params, input, target -> preds = Axon.predict(model, params, input) Nx.add(loss.(target, preds), Axon.penalty(model, params)) end step({init_fn, objective_fn}, optimizer, opts) end def step(%Axon{} = model, train_state, loss, optimizer, opts) when is_atom(loss) and is_list(opts) do loss_fn = &apply(Axon.Losses, loss, [&1, &2, [reduction: :mean]]) step(model, train_state, loss_fn, optimizer, opts) end @valid_callbacks [:early_stopping] @doc false def callback(%Step{} = step, callback) when callback in @valid_callbacks do callback(step, callback, []) end @doc """ Adds a callback from `Axon.Training.Callbacks` to the training step. """ def callback(%Step{} = step, callback, opts) when callback in @valid_callbacks do fun = &apply(Axon.Training.Callbacks, callback, [&1, &2, &3]) callback(step, fun, :all, opts) end @doc """ Adds a callback function to the training step. Callback functions instrument specific points in the training loop. You can specify an `event` which is one of: - `:before_{train, epoch, batch}` - `:after_{train, epoch, batch}` The default `event` is `:all`, meaning the callback will run at every callback point. Callback functions have the following signature: callback_fn(train_state :: map, event :: atom, opts :: keyword) :: {:cont, train_state} | {:halt, train_state} You can trigger event-specific behavior using pattern matching: def my_callback(train_state, :before_epoch, _opts) do {:cont, %{train_state | my_metadata: 0}} end def my_callback(train_state, :after_epoch, _opts) do {:cont, %{train_state | my_metadata: train_state[:metadata] + 1}} end def my_callback(train_state, _event, _opts), do: {:cont, train_state} Returning `{:halt, train_state}` will immediately terminate the training loop: def early_stopping(train_state, :after_epoch, opts) do if stop?(train_state, opts) do {:halt, train_state} else {:cont, train_state} end end """ def callback(%Step{callbacks: callbacks} = step, function, event \\ :all, opts \\ []) when is_function(function, 3) and is_atom(event) and is_list(opts) do %{step | callbacks: [{function, event, opts} | callbacks]} end @doc """ Implements a common training loop. Its arguments are: * A tuple with the initialization function and the step function. Often retrieved from `step/3` but it could also be manually provided. * The inputs tensors * The targets tensors * A list of options ## Options * `:epochs` - number of epochs to train for. Defaults to `5`. * `:compiler` - `defn` compiler to use to run training loop. Defaults to `Nx.Defn.Evaluator`. * `:log_every` - frequency with which to log training loss. Accepts an integer referring to number of batches, `:epoch`, or `:none`. Defaults to `:epoch`. All other options are given to the underlying compiler. ## A note on Nx and anonymous functions When training, both `init_fn` and `step_fn` are executed within the given Nx `:compiler`. Therefore, it is required that `init_fn` and `step_fn` work on tensor expressions instead of tensor values. For example, let's suppose you want to initialize the values with: Nx.random_uniform({40, 28}, 0, 1) The following won't work: params = Nx.random_uniform({40, 28}, 0, 1) init_fn = fn -> params end Instead, we want to build the values inside the given compiler. The correct way to build those values is by computing them inside a defn: defn init_values, do: Nx.random_uniform({40, 28}, 0, 1) And then: init_fn = &init_values/0 """ def train( %Step{init: init_fn, step: step_fn, callbacks: callbacks}, inputs, targets, opts \\ [] ) do epochs = opts[:epochs] || 5 compiler = opts[:compiler] || Nx.Defn.Evaluator log_every = opts[:log_every] || 50 callbacks = [ {&Axon.Training.Callbacks.standard_io_logger(&1, &2, &3), :all, log_every: log_every} | Enum.reverse(callbacks) ] jit_opts = [compiler: compiler] ++ opts train_state = Nx.Defn.jit(init_fn, [], jit_opts) train_state = case apply_callback(callbacks, train_state, jit_opts, :before_train) do {:cont, train_state} -> Enum.reduce_while(1..epochs, train_state, fn epoch, train_state -> case apply_callback(callbacks, train_state, jit_opts, :before_epoch) do {:cont, train_state} -> {time, train_state} = :timer.tc(&train_epoch/6, [ step_fn, train_state, inputs, targets, callbacks, jit_opts ]) zero_metrics = Map.new(train_state[:metrics], fn {k, _} -> {k, 0.0} end) case apply_callback( callbacks, Map.put(train_state, :time, time), jit_opts, :after_epoch ) do {:cont, train_state} -> train_state = %{ Map.delete(train_state, :time) | metrics: zero_metrics, epoch: epoch, epoch_step: 0, epoch_loss: 0.0 } {:cont, train_state} {:halt, train_state} -> {:halt, train_state} end {:halt, train_state} -> {:halt, train_state} end end) {:halt, train_state} -> train_state end {_, train_state} = apply_callback(callbacks, train_state, jit_opts, :after_train) train_state end ## Helpers defp train_epoch(step_fn, train_state, inputs, targets, callbacks, opts) do dataset = Stream.zip(inputs, targets) Enum.reduce_while(dataset, train_state, fn {inp, tar}, train_state -> case apply_callback(callbacks, train_state, opts, :before_batch) do {:cont, train_state} -> train_state = Nx.Defn.jit(step_fn, [train_state, inp, tar], opts) apply_callback(callbacks, train_state, opts, :after_batch) {:halt, train_state} -> {:halt, train_state} end end) end defp apply_callback([], train_state, _, _), do: {:cont, train_state} defp apply_callback(callbacks, train_state, train_opts, event) do result = Enum.reduce_while(callbacks, train_state, fn {callback, :all, opts}, train_state -> case apply(callback, [train_state, event, opts ++ train_opts]) do {:halt, acc} -> {:halt, {:stopped, acc}} {:cont, acc} -> {:cont, acc} other -> raise "invalid return from callback #{inspect(other)}" end {callback, event, opts}, train_state -> case apply(callback, [train_state, event, opts ++ train_opts]) do {:halt, acc} -> {:halt, {:halt, acc}} {:cont, acc} -> {:cont, {:cont, acc}} other -> raise "invalid return from callback #{inspect(other)}" end end) case result do {:stopped, acc} -> {:halt, acc} acc -> {:cont, acc} end end end
lib/axon/training.ex
0.855384
0.713163
training.ex
starcoder
defmodule AbsintheCache.BeforeSend do @moduledoc ~s""" Cache & Persist API Call Data right before sending the response. This module is responsible for persisting the whole result of some queries right before it is send to the client. All queries that did not raise exceptions and were successfully handled by the GraphQL layer pass through this module. The Blueprint's `result` field contains the final result as a single map. This result is made up of the top-level resolver and all custom resolvers. Caching the end result instead of each resolver separately allows to resolve the whole query with a single cache call - some queries could have thousands of custom resolver invocations. In order to cache a result all of the following conditions must be true: - All queries must be present in the `@cached_queries` list - The resolved value must not be an error - During resolving there must not be any `:nocache` returned. Most of the simple queries use 1 cache call and won't benefit from this approach. Only queries with many resolvers are included in the list of allowed queries. """ defmacro __using__(opts) do quote location: :keep, bind_quoted: [opts: opts] do @compile :inline_list_funcs @compile inline: [cache_result: 2, queries_in_request: 1, has_graphql_errors?: 1] @cached_queries Keyword.get(opts, :cached_queries, []) def before_send(conn, %Absinthe.Blueprint{} = blueprint) do # Do not cache in case of: # -`:nocache` returend from a resolver # - result is taken from the cache and should not be stored again. Storing # it again `touch`es it and the TTL timer is restarted. This can lead # to infinite storing the same value if there are enough requests queries = queries_in_request(blueprint) do_not_cache? = is_nil(Process.get(:do_not_cache_query)) case do_not_cache? or has_graphql_errors?(blueprint) do true -> :ok false -> cache_result(queries, blueprint) end conn end defp cache_result(queries, blueprint) do all_queries_cachable? = queries |> Enum.all?(&Enum.member?(@cached_queries, &1)) if all_queries_cachable? do AbsintheCache.store( blueprint.execution.context.query_cache_key, blueprint.result ) end end defp queries_in_request(%{operations: operations}) do operations |> Enum.flat_map(fn %{selections: selections} -> selections |> Enum.map(fn %{name: name} -> Inflex.camelize(name, :lower) end) end) end defp has_graphql_errors?(%Absinthe.Blueprint{result: %{errors: _}}), do: true defp has_graphql_errors?(_), do: false end end end
lib/before_send.ex
0.764672
0.474692
before_send.ex
starcoder
defmodule Oauth2MetadataUpdater do @moduledoc """ Oauth2MetadataUpdater dynamically loads metadata (lazy-loading) and keeps it in memory for further access. Examples: It Implements the following standards: - [RFC8414](https://tools.ietf.org/html/rfc8414) - OAuth 2.0 Authorization Server Metadata - Except section 2.1 (Signed Authorization Server Metadata) - [OpenID Connect Discovery 1.0 incorporating errata set 1](https://openid.net/specs/openid-connect-discovery-1_0.html) - Except section 2 The following functions accept the following options: - `suffix`: the well-know URI suffix as documented in the [IANA registry](https://www.iana.org/assignments/well-known-uris/well-known-uris.xhtml). Defaults to `"openid-configuration"` - `refresh_interval`: the number of seconds to keep metadata in cache before it is fetched again. Defaults to `3600` seconds - `min_refresh_interval`: the delay before Oauth2MetadataUpdater will try to fetch metadata of an issuer again. It is intended to prevent fetching storms when the metadata is unavailable. Defaults to `10` seconds - `on_refresh_failure`: determines the behaviour of Oauth2MetadataUpdater when the issuer metadata *becomes* unavailable: `:keep_metadata` will keep the metadata in the cache, `:discard` will delete the metadata. Defaults to `:keep_metadata` - `:tesla_middlewares`: `Tesla` middlewares to add to the outgoing request - `url_construction`: `:standard` (default) or `:non_standard_append`. Given the issuer `"https://www.example.com/auth"` the result URI would be: - `:standard`: `"https://www.example.com/.well-known/oauth-authorization-server/auth"` - `:non_standard_append`: `"https://www.example.com/auth/.well-known/oauth-authorization-server"` - `validation`: in addition to the mandatory metadata values of the OAuth2 specification, OpenID Connect makes the `jwks_uri`, `subject_types_supported` and `id_token_signing_alg_values_supported` values mandatory. This option determines against which standard to validate: `:oauth2` or `:oidc`. Defaults to `:oidc` The `:suffix`, `:on_refresh_failure`, `:url_construction`, `:validation` options shall be used unchanged for a given issuer between multiple calls, otherwise an exception will be raised. Note that OAuth2 and OpenID Connect default values are automatically added to the responses. """ use Application @doc false def start(_type, _args) do import Supervisor.Spec children = [worker(Oauth2MetadataUpdater.Updater, [])] {:ok, _} = Supervisor.start_link(children, strategy: :one_for_one, name: :oauth2_metadata_updater_sup) end @doc """ Returns `{:ok, value}` of the metadata of an issuer, or `{:error, error}` if it could not be retrieved or if validation failed. ## Examples ```elixir iex> Oauth2MetadataUpdater.get_metadata_value("https://accounts.google.com", "authorization_endpoint", suffix: "openid-configuration") {:ok, "https://accounts.google.com/o/oauth2/v2/auth"} iex> Oauth2MetadataUpdater.get_metadata_value("https://accounts.google.com", "token_endpoint", suffix: "openid-configuration") {:ok, "https://oauth2.googleapis.com/token"} iex> Oauth2MetadataUpdater.get_metadata_value("https://login.live.com", "response_modes_supported", suffix: "openid-configuration") {:ok, ["query", "fragment", "form_post"]} iex> Oauth2MetadataUpdater.get_metadata_value("https://login.live.com", "nonexisting_val", suffix: "openid-configuration") {:ok, nil} iex> Oauth2MetadataUpdater.get_metadata_value("https://openid-connect.onelogin.com/oidc", "claims_supported", suffix: "openid-configuration") {:error, :invalid_http_response_code} iex> Oauth2MetadataUpdater.get_metadata_value("https://openid-connect.onelogin.com/oidc", "claims_supported", suffix: "openid-configuration", url_construction: :non_standard_append) {:ok, ["acr", "auth_time", "company", "custom_fields", "department", "email", "family_name", "given_name", "groups", "iss", "locale_code", "name", "phone_number", "preferred_username", "sub", "title", "updated_at"]} ``` """ defdelegate get_metadata_value(issuer, claim, opts \\ []), to: Oauth2MetadataUpdater.Updater @doc """ Returns `{:ok, map_of_all_values}` of the metadata of an issuer, or `{:error, error}` if it could not be retrieved or if validation failed. ## Example ```elixir iex> Oauth2MetadataUpdater.get_metadata("https://auth.login.yahoo.co.jp/yconnect/v2", suffix: "openid-configuration", url_construction: :non_standard_append) {:ok, %{ "authorization_endpoint" => "https://auth.login.yahoo.co.jp/yconnect/v2/authorization", "claims_locales_supported" => ["ja-JP"], "claims_supported" => ["sub", "name", "given_name", "family_name", "email", "email_verified", "gender", "birthdate", "zoneinfo", "locale", "address", "iss", "aud", "exp", "iat", "nickname", "picture"], "display_values_supported" => ["page", "popup", "touch"], "grant_types_supported" => ["authorization_code", "implicit"], "id_token_signing_alg_values_supported" => ["RS256"], "issuer" => "https://auth.login.yahoo.co.jp/yconnect/v2", "jwks_uri" => "https://auth.login.yahoo.co.jp/yconnect/v2/jwks", "op_policy_uri" => "https://developer.yahoo.co.jp/yconnect/v2/guideline.html", "op_tos_uri" => "https://developer.yahoo.co.jp/yconnect/v2/guideline.html", "response_modes_supported" => ["query", "fragment"], "response_types_supported" => ["code", "token", "id_token", "code token", "code id_token", "token id_token", "code token id_token"], "revocation_endpoint_auth_methods_supported" => ["client_secret_basic"], "scopes_supported" => ["openid", "email", "profile", "address"], "service_documentation" => "https://developer.yahoo.co.jp/yconnect/", "subject_types_supported" => ["public"], "token_endpoint" => "https://auth.login.yahoo.co.jp/yconnect/v2/token", "token_endpoint_auth_methods_supported" => ["client_secret_post", "client_secret_basic"], "ui_locales_supported" => ["ja-JP"], "userinfo_endpoint" => "https://userinfo.yahooapis.jp/yconnect/v2/attribute" }} ``` """ defdelegate get_metadata(issuer, opts \\ []), to: Oauth2MetadataUpdater.Updater end
lib/oauth2_metadata_updater.ex
0.869105
0.866641
oauth2_metadata_updater.ex
starcoder
defmodule Ecto.Adapter.Queryable do @moduledoc """ Specifies the query API required from adapters. If your adapter is only able to respond to one or a couple of the query functions, add custom implementations of those functions directly to the Repo by using `c:Ecto.Adapter.__before_compile__/1` instead. """ @typedoc "Proxy type to the adapter meta" @type adapter_meta :: Ecto.Adapter.adapter_meta() @typedoc "Ecto.Query metadata fields (stored in cache)" @type query_meta :: %{sources: tuple, preloads: term, select: map} @typedoc """ Cache query metadata that is passed to `c:execute/5`. The cache can be in 3 states, documented below. If `{:nocache, prepared}` is given, it means the query was not and cannot be cached. The `prepared` value is the value returned by `c:prepare/2`. If `{:cache, cache_function, prepared}` is given, it means the query can be cached and it must be cached by calling the `cache_function` function with the cache entry of your choice. Once `cache_function` is called, the next time the same query is given to `c:execute/5`, it will receive the `:cached` tuple. If `{:cached, update_function, reset_function, cached}` is given, it means the query has been cached. You may call `update_function/1` if you want to update the cached result. Or you may call `reset_function/1`, with a new prepared query, to force the query to be cached again. If `reset_function/1` is called, the next time the same query is given to `c:execute/5`, it will receive the `:cache` tuple. """ @type query_cache :: {:nocache, prepared} | {:cache, cache_function :: (cached -> :ok), prepared} | {:cached, update_function :: (cached -> :ok), reset_function :: (prepared -> :ok), cached} @type prepared :: term @type cached :: term @type options :: Keyword.t() @type selected :: term @doc """ Commands invoked to prepare a query. It is used on `c:Ecto.Repo.all/2`, `c:Ecto.Repo.update_all/3`, and `c:Ecto.Repo.delete_all/2`. If returns a tuple, saying if this query can be cached or not, and the `prepared` query. The `prepared` query is any term that will be passed to the adapter's `c:execute/5`. """ @callback prepare(atom :: :all | :update_all | :delete_all, query :: Ecto.Query.t()) :: {:cache, prepared} | {:nocache, prepared} @doc """ Executes a previously prepared query. The `query_meta` field is a map containing some of the fields found in the `Ecto.Query` struct, after they have been normalized. For example, the values `selected` by the query, which then have to be returned, can be found in `query_meta`. The `query_cache` and its state is documented in `t:query_cache/0`. The `params` is the list of query parameters. For example, for a query such as `from Post, where: [id: ^123]`, `params` will be `[123]`. Finally, `options` is a keyword list of options given to the `Repo` operation that triggered the adapter call. Any option is allowed, as this is a mechanism to allow users of Ecto to customize how the adapter behaves per operation. It must return a tuple containing the number of entries and the result set as a list of lists. The entries in the actual list will depend on what has been selected by the query. The result set may also be `nil`, if no value is being selected. """ @callback execute(adapter_meta, query_meta, query_cache, params :: list(), options) :: {non_neg_integer, [[selected]] | nil} @doc """ Streams a previously prepared query. See `c:execute/5` for a description of arguments. It returns a stream of values. """ @callback stream(adapter_meta, query_meta, query_cache, params :: list(), options) :: Enumerable.t @doc """ Plans and prepares a query for the given repo, leveraging its query cache. This operation uses the query cache if one is available. """ def prepare_query(operation, repo_name_or_pid, queryable) do {adapter, %{cache: cache}} = Ecto.Repo.Registry.lookup(repo_name_or_pid) {_meta, prepared, params} = queryable |> Ecto.Queryable.to_query() |> Ecto.Query.Planner.ensure_select(operation == :all) |> Ecto.Query.Planner.query(operation, cache, adapter, 0) {prepared, params} end @doc """ Plans a query using the given adapter. This does not expect the repository and therefore does not leverage the cache. """ def plan_query(operation, adapter, queryable) do query = Ecto.Queryable.to_query(queryable) {query, params, _key} = Ecto.Query.Planner.plan(query, operation, adapter) {query, _} = Ecto.Query.Planner.normalize(query, operation, adapter, 0) {query, params} end end
lib/ecto/adapter/queryable.ex
0.919615
0.634204
queryable.ex
starcoder
defmodule Cli.Render do @moduledoc """ Module used for formatting output into charts and tables. """ @bar_chart_block "▇" @bar_chart_empty_block "-" @bar_chart_ellipsis "..." @day_minutes 24 * 60 @week_minutes 7 * @day_minutes @month_minutes 31 * @day_minutes @doc """ Builds a line chart from the supplied data. The chart will show the total duration of the task(s) per period. The available periods are: `:day`, `:week`, `:month`. """ def task_aggregation_as_line_chart(aggregation, query, task_regex, group_period) do case aggregation do [_ | _] -> footer_label = case group_period do :day -> "Daily" :week -> "Weekly" :month -> "Monthly" end footer = "#{footer_label} task duration between [#{query.from}] and [#{query.to}], for tasks matching [#{ task_regex |> Regex.source() }]" chart_data = aggregation |> Enum.map(fn {_, total_duration, _} -> total_duration / 60 end) {:ok, chart} = Asciichart.plot(chart_data) {:ok, "#{chart}\n#{footer}"} [] -> {:error, "No data"} end end @doc """ Builds a bar chart from the supplied data. The chart will show the distribution of tasks throughout the specified period. The available periods are: `:day`, `:week`, `:month`. """ def period_aggregation_as_bar_chart(aggregation, query, group_period) do case aggregation do [_ | _] -> current_periods = get_current_periods() {total_minutes, header_label, footer_label} = case group_period do :day -> {@day_minutes, "Day", "Daily"} :week -> {@week_minutes, "Week", "Weekly"} :month -> {@month_minutes, "Month", "Monthly"} end header = [label: header_label, value_label: "Duration"] footer = [ label: "#{footer_label} task distribution between [#{query.from}] and [#{query.to}]" ] minutes = 1..total_minutes |> Enum.map(fn minute -> {minute, :empty} end) |> Enum.into(%{}) rows = aggregation |> Enum.map(fn {start_period, total_duration, entries} -> formatted_total_duration = "#{duration_to_formatted_string(total_duration, Enum.at(entries, 0).start)} " {group_colour, group_start} = group_data_from_period_data(group_period, start_period, current_periods) entries = entries |> Enum.flat_map(fn entry -> offset = div(NaiveDateTime.diff(entry.start, group_start, :second), 60) offset..(offset + entry.duration - 1) |> Enum.map(fn minute -> {minute + 1, group_colour} end) end) |> Enum.into(%{}) entries = Map.merge(minutes, entries) |> Enum.sort_by(fn {minute, _} -> minute end) |> Enum.reverse() |> Enum.reduce(%{}, fn {_, group_colour}, acc -> block_id = max(Map.size(acc) - 1, 0) block_op = case Map.get(acc, block_id, {0, group_colour}) do {block_size, ^group_colour} -> {:update, {block_size + 1, group_colour}} _ -> {:add, {1, group_colour}} end case block_op do {:add, block_data} -> Map.put(acc, block_id + 1, block_data) {:update, block_data} -> Map.put(acc, block_id, block_data) end end) |> Enum.map(fn {_, entry} -> entry end) {start_period, total_minutes, formatted_total_duration, entries} end) {:ok, bar_chart(header, rows, footer)} [] -> {:error, "No data"} end end @doc """ Builds a bar chart from the supplied data. The chart will show the total duration of each task for the queried period. """ def duration_aggregation_as_bar_chart(aggregation, query) do case aggregation do [_ | _] -> current_periods = get_current_periods() header = [label: "Task", value_label: "Duration"] footer = [label: "Total duration of tasks between [#{query.from}] and [#{query.to}]"] rows = aggregation |> Enum.map(fn {task, total_duration, entries} -> formatted_total_duration = "#{duration_to_formatted_string(total_duration, Enum.at(entries, 0).start)} " entries = entries |> Enum.map(fn entry -> start_string = naive_date_time_to_string(entry.start) colour = naive_date_time_to_period(entry.start, start_string, current_periods) |> period_to_colour() {%{entry | start: start_string}, colour} end) |> Enum.sort_by(fn {entry, _} -> entry.start end) |> Enum.map(fn {entry, colour} -> {entry.duration, colour} end) {task, total_duration, formatted_total_duration, entries} end) {:ok, bar_chart(header, rows, footer)} [] -> {:error, "No data"} end end @doc """ Builds a table from the supplied data. The table will show all tasks that are overlapping and the day on which the overlap occurs. """ def overlapping_tasks_table(list) do rows = list |> Enum.flat_map(fn {start_date, entries} -> entries |> Enum.map(fn entry -> [ start_date |> NaiveDateTime.to_date(), entry.id, entry.task, entry.start, duration_to_formatted_string(entry.duration, entry.start) ] end) end) case rows do [_ | _] -> table_header = ["Overlap Day", "ID", "Task", "Start", "Duration"] table = TableRex.Table.new(rows, table_header) |> TableRex.Table.put_column_meta(4, align: :right) |> TableRex.Table.render!() {:ok, table} [] -> {:error, "No data"} end end @doc """ Builds a table from the supplied data. The table will show all tasks. """ def tasks_table(list) do rows = list |> to_table_rows() case rows do [_ | _] -> table_header = ["ID", "Task", "Start", "Duration"] table = TableRex.Table.new(rows, table_header) |> TableRex.Table.put_column_meta(3, align: :right) |> TableRex.Table.render!() {:ok, table} [] -> {:error, "No data"} end end @doc """ Converts the supplied period data (period type, start, current periods) into a {colour, period string} tuple. """ def group_data_from_period_data(group_period, start_period, current_periods) do case group_period do :day -> day_string = "#{start_period}T00:00:00" {:ok, day} = NaiveDateTime.from_iso8601(day_string) day_period = naive_date_time_to_period(day, day_string, current_periods) {day_period |> period_to_colour(), day} :week -> day_string = "#{start_period}T00:00:00" {:ok, day} = NaiveDateTime.from_iso8601(day_string) day_period = naive_date_time_to_period(day, day_string, current_periods) day_period = case day_period do :current_day -> :current_week other -> other end {day_period |> period_to_colour(), day} :month -> day_string = "#{start_period}-01T00:00:00" {:ok, day} = NaiveDateTime.from_iso8601(day_string) day_period = naive_date_time_to_period(day, day_string, current_periods) day_period = case day_period do :current_day -> :current_month :current_week -> :current_month other -> other end {day_period |> period_to_colour(), day} end end @doc """ Builds a colour legend showing a brief description of what the various chart/table colours mean. """ def period_colour_legend() do [ current_day: "Today's tasks", current_week: "This week's tasks", current_month: "This month's tasks", future: "Future tasks", past: "Older tasks" ] |> Enum.map(fn {period, description} -> block = case period_to_colour(period) do :default -> @bar_chart_block colour -> IO.ANSI.format([colour, @bar_chart_block], true) end " #{block} -> #{description}" end) |> Enum.join("\n") end @doc """ Builds a bar chart from the supplied header, rows and footer data. The header supports the following options: - `label` - the string to be used for describing the table's label (left column) - `value_label` - the string to be used for describing the table's value label (label prepended to each entry in the chart) The footer supports the following options: - `label` - the string to be used as footer; should be a brief description of what the chart represents """ def bar_chart(header, rows, footer) do default_width = 80 separator = " | " {largest_label_size, largest_value_label_size, largest_value} = rows |> Enum.reduce({0, 0, 0}, fn {current_label, current_value, current_formatted_value, _}, {max_label_size, max_value_label_size, max_value} -> { max(max_label_size, String.length(current_label)), max(max_value_label_size, String.length(current_formatted_value)), max(max_value, current_value) } end) max_shell_width = 180 shell_width = min(max_shell_width, get_shell_width(default_width)) max_label_size = trunc(shell_width * 0.25) largest_label_size = min(largest_label_size, max_label_size) chart_header = "#{String.pad_trailing(header[:label], largest_label_size)}#{separator}#{ header[:value_label] }\n" chart_separator = "#{String.pad_trailing("", largest_label_size, "-")} + #{ String.pad_trailing("", String.length(header[:value_label]), "-") }\n" chart_header = "#{chart_header}#{chart_separator}" chart_footer = "\n#{chart_separator}#{footer[:label]}" chart = rows |> Enum.map(fn {label, total_value, formatted_total_value, entries} -> label = if String.length(label) > largest_label_size do truncated = String.slice(label, 0, largest_label_size - String.length(@bar_chart_ellipsis)) "#{truncated}#{@bar_chart_ellipsis}" else String.pad_trailing(label, largest_label_size) end value_label = formatted_total_value |> String.pad_leading(largest_value_label_size) separator_size = String.length(separator) labels_size = largest_label_size + String.length(value_label) max_value_size = shell_width - labels_size - separator_size chart_blocks = trunc(max_value_size * total_value / largest_value) {_, entries} = entries |> Enum.reduce({0, []}, fn {size, colour}, {remainder, entries} -> current_remainder = rem(chart_blocks * size, total_value) cond do current_remainder == 0 -> { remainder, [{div(chart_blocks * size, total_value), colour} | entries] } remainder == 0 -> { current_remainder, [{div(chart_blocks * size, total_value), colour} | entries] } true -> updated_remainder = rem(chart_blocks * size + remainder, total_value) entry_blocks = div(chart_blocks * size + remainder, total_value) { updated_remainder, [{entry_blocks, colour} | entries] } end end) value = entries |> Enum.map(fn {entry_blocks, colour} -> if entry_blocks > 0 do case colour do :default -> entry_chart_segment(@bar_chart_block, entry_blocks) :empty -> entry_chart_segment(@bar_chart_empty_block, entry_blocks) colour -> coloured_entry_chart_segment(@bar_chart_block, entry_blocks, colour) end else "" end end) "#{label}#{separator}#{value_label}#{value}" end) |> Enum.join("\n") "#{chart_header}#{chart}#{chart_footer}" end @doc """ Creates a bar chart segment and applies the specified colour to it. """ def coloured_entry_chart_segment(block, num_blocks, colour) do IO.ANSI.format( [colour, entry_chart_segment(block, num_blocks)], true ) end @doc """ Creates a bar chart segment. """ def entry_chart_segment(block, num_blocks) do List.duplicate(block, num_blocks) end @doc """ Converts the supplied list of tasks into table rows. """ def to_table_rows(list) do current_periods = get_current_periods() list |> Enum.map(fn entry -> start_string = naive_date_time_to_string(entry.start) date_colour = naive_date_time_to_period(entry.start, start_string, current_periods) |> period_to_colour() start_string = case date_colour do :default -> start_string colour -> IO.ANSI.format([colour, start_string], true) end [ entry.id, entry.task, start_string, duration_to_formatted_string(entry.duration, entry.start) ] end) end @doc """ Retrieves the current periods: {now, current day, list of days for the current week, current month}. """ def get_current_periods() do now = NaiveDateTime.utc_now() today = NaiveDateTime.to_date(now) current_day = Date.to_string(today) current_week_monday = Date.add( today, -(Calendar.ISO.day_of_week(today.year, today.month, today.day) - 1) ) current_week_days = Enum.map(0..6, fn week_day -> Date.to_string(Date.add(current_week_monday, week_day)) end) current_month = "#{today.year}-#{today.month |> Integer.to_string() |> String.pad_leading(2, "0")}" {now, current_day, current_week_days, current_month} end @doc """ Calculates the supplied date/time's period. The period can be one of: `:current_day`, `:future`, `:current_week`, `:current_month`, `:past`. > Any period that is in the current day will be marked as such, even if it is in the future. > However, `:current_week` and `:current_month` only apply to periods in the past. > If the supplied period is in the current week/month but in the future it will be marked as `:future`. """ def naive_date_time_to_period( dt, dt_string, {now, current_day, current_week_days, current_month} ) do cond do String.starts_with?(dt_string, current_day) -> :current_day NaiveDateTime.compare(dt, now) == :gt -> :future Enum.any?(current_week_days, &String.starts_with?(dt_string, &1)) -> :current_week String.starts_with?(dt_string, current_month) -> :current_month true -> :past end end @doc """ Converts the specified period to a colour. Example: `:future` -> `:blue`. """ def period_to_colour(period) do case period do :future -> :blue :current_day -> :green :current_week -> :yellow :current_month -> :red :past -> :default end end @doc """ Converts the supplied date/time to a string to be shown to the user. The output format is: `YYYY-MM-DD HH:mm` For example: `2015-12-21 23:45` """ def naive_date_time_to_string(dt) do date = NaiveDateTime.to_date(dt) hours = dt.hour |> Integer.to_string() |> String.pad_leading(2, "0") minutes = dt.minute |> Integer.to_string() |> String.pad_leading(2, "0") "#{date} #{hours}:#{minutes}" end @doc """ Converts the supplied duration and start time to a string to be shown to the user. The format is: `HH:mm` For example: `75:58` (total duration of 75 hours and 58 minutes) For active tasks, the expected duration is calculated. The format is: `(A) HH:mm` For example: `(A) 75:58` (the task was started 75 hours and 58 minutes ago) """ def duration_to_formatted_string(duration, start) do duration = abs(duration) if duration > 0 do hours = div(duration, 60) minutes = (duration - hours * 60) |> Integer.to_string() |> String.pad_leading(2, "0") "#{hours}:#{minutes}" else local_now = :calendar.local_time() |> NaiveDateTime.from_erl!() expected_duration = NaiveDateTime.diff(local_now, start, :second) |> div(60) if expected_duration > 0 do "(A) #{duration_to_formatted_string(expected_duration, start)}" else "(A) 0:00" end end end @doc """ Retrieves the current width of the user's terminal or returns the specified default. """ def get_shell_width(default_width) do case System.cmd("tput", ["cols"]) do {width, 0} -> width |> String.trim() |> String.to_integer() _ -> default_width end end end
lib/cli/render.ex
0.83545
0.538923
render.ex
starcoder
defmodule AWS.AutoScaling do @moduledoc """ With Application Auto Scaling, you can automatically scale your AWS resources. The experience similar to that of [Auto Scaling](https://aws.amazon.com/autoscaling/). You can use Application Auto Scaling to accomplish the following tasks: <ul> <li> Define scaling policies to automatically scale your AWS resources </li> <li> Scale your resources in response to CloudWatch alarms </li> <li> View the history of your scaling events </li> </ul> Application Auto Scaling can scale the following AWS resources: <ul> <li> Amazon ECS services. For more information, see [Service Auto Scaling](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-auto-scaling.html) in the *Amazon EC2 Container Service Developer Guide*. </li> <li> Amazon EC2 Spot fleets. For more information, see [Automatic Scaling for Spot Fleet](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/fleet-auto-scaling.html) in the *Amazon EC2 User Guide*. </li> <li> Amazon EMR clusters. For more information, see [Using Automatic Scaling in Amazon EMR](http://docs.aws.amazon.com/ElasticMapReduce/latest/ManagementGuide/emr-automatic-scaling.html) in the *Amazon EMR Management Guide*. </li> </ul> For a list of supported regions, see [AWS Regions and Endpoints: Application Auto Scaling](http://docs.aws.amazon.com/general/latest/gr/rande.html#as-app_region) in the *AWS General Reference*. """ @doc """ Deletes the specified Application Auto Scaling scaling policy. Deleting a policy deletes the underlying alarm action, but does not delete the CloudWatch alarm associated with the scaling policy, even if it no longer has an associated action. To create a scaling policy or update an existing one, see `PutScalingPolicy`. """ def delete_scaling_policy(client, input, options \\ []) do request(client, "DeleteScalingPolicy", input, options) end @doc """ Deregisters a scalable target. Deregistering a scalable target deletes the scaling policies that are associated with it. To create a scalable target or update an existing one, see `RegisterScalableTarget`. """ def deregister_scalable_target(client, input, options \\ []) do request(client, "DeregisterScalableTarget", input, options) end @doc """ Provides descriptive information about the scalable targets in the specified namespace. You can filter the results using the `ResourceIds` and `ScalableDimension` parameters. To create a scalable target or update an existing one, see `RegisterScalableTarget`. If you are no longer using a scalable target, you can deregister it using `DeregisterScalableTarget`. """ def describe_scalable_targets(client, input, options \\ []) do request(client, "DescribeScalableTargets", input, options) end @doc """ Provides descriptive information about the scaling activities in the specified namespace from the previous six weeks. You can filter the results using the `ResourceId` and `ScalableDimension` parameters. Scaling activities are triggered by CloudWatch alarms that are associated with scaling policies. To view the scaling policies for a service namespace, see `DescribeScalingPolicies`. To create a scaling policy or update an existing one, see `PutScalingPolicy`. """ def describe_scaling_activities(client, input, options \\ []) do request(client, "DescribeScalingActivities", input, options) end @doc """ Provides descriptive information about the scaling policies in the specified namespace. You can filter the results using the `ResourceId`, `ScalableDimension`, and `PolicyNames` parameters. To create a scaling policy or update an existing one, see `PutScalingPolicy`. If you are no longer using a scaling policy, you can delete it using `DeleteScalingPolicy`. """ def describe_scaling_policies(client, input, options \\ []) do request(client, "DescribeScalingPolicies", input, options) end @doc """ Creates or updates a policy for an Application Auto Scaling scalable target. Each scalable target is identified by a service namespace, resource ID, and scalable dimension. A scaling policy applies to the scalable target identified by those three attributes. You cannot create a scaling policy without first registering a scalable target using `RegisterScalableTarget`. To update a policy, specify its policy name and the parameters that you want to change. Any parameters that you don't specify are not changed by this update request. You can view the scaling policies for a service namespace using `DescribeScalingPolicies`. If you are no longer using a scaling policy, you can delete it using `DeleteScalingPolicy`. """ def put_scaling_policy(client, input, options \\ []) do request(client, "PutScalingPolicy", input, options) end @doc """ Registers or updates a scalable target. A scalable target is a resource that Application Auto Scaling can scale out or scale in. After you have registered a scalable target, you can use this operation to update the minimum and maximum values for your scalable dimension. After you register a scalable target, you can create and apply scaling policies using `PutScalingPolicy`. You can view the scaling policies for a service namespace using `DescribeScalableTargets`. If you are no longer using a scalable target, you can deregister it using `DeregisterScalableTarget`. """ def register_scalable_target(client, input, options \\ []) do request(client, "RegisterScalableTarget", input, options) end @spec request(map(), binary(), map(), list()) :: {:ok, Poison.Parser.t | nil, Poison.Response.t} | {:error, Poison.Parser.t} | {:error, HTTPoison.Error.t} defp request(client, action, input, options) do client = %{client | service: "autoscaling"} host = get_host("autoscaling", client) url = get_url(host, client) headers = [{"Host", host}, {"Content-Type", "application/x-amz-json-1.1"}, {"X-Amz-Target", "AnyScaleFrontendService.#{action}"}] payload = Poison.Encoder.encode(input, []) headers = AWS.Request.sign_v4(client, "POST", url, headers, payload) case HTTPoison.post(url, payload, headers, options) do {:ok, response=%HTTPoison.Response{status_code: 200, body: ""}} -> {:ok, nil, response} {:ok, response=%HTTPoison.Response{status_code: 200, body: body}} -> {:ok, Poison.Parser.parse!(body), response} {:ok, _response=%HTTPoison.Response{body: body}} -> error = Poison.Parser.parse!(body) exception = error["__type"] message = error["message"] {:error, {exception, message}} {:error, %HTTPoison.Error{reason: reason}} -> {:error, %HTTPoison.Error{reason: reason}} end end defp get_host(endpoint_prefix, client) do if client.region == "local" do "localhost" else "#{endpoint_prefix}.#{client.region}.#{client.endpoint}" end end defp get_url(host, %{:proto => proto, :port => port}) do "#{proto}://#{host}:#{port}/" end end
lib/aws/autoscaling.ex
0.89539
0.52543
autoscaling.ex
starcoder
defmodule AWS.Streams.DynamoDB do @moduledoc """ Amazon DynamoDB Amazon DynamoDB Streams provides API actions for accessing streams and processing stream records. To learn more about application development with Streams, see [Capturing Table Activity with DynamoDB Streams](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html) in the Amazon DynamoDB Developer Guide. """ @doc """ Returns information about a stream, including the current status of the stream, its Amazon Resource Name (ARN), the composition of its shards, and its corresponding DynamoDB table. <note> You can call `DescribeStream` at a maximum rate of 10 times per second. </note> Each shard in the stream has a `SequenceNumberRange` associated with it. If the `SequenceNumberRange` has a `StartingSequenceNumber` but no `EndingSequenceNumber`, then the shard is still open (able to receive more stream records). If both `StartingSequenceNumber` and `EndingSequenceNumber` are present, then that shard is closed and can no longer receive more data. """ def describe_stream(client, input, options \\ []) do request(client, "DescribeStream", input, options) end @doc """ Retrieves the stream records from a given shard. Specify a shard iterator using the `ShardIterator` parameter. The shard iterator specifies the position in the shard from which you want to start reading stream records sequentially. If there are no stream records available in the portion of the shard that the iterator points to, `GetRecords` returns an empty list. Note that it might take multiple calls to get to a portion of the shard that contains stream records. <note> `GetRecords` can retrieve a maximum of 1 MB of data or 1000 stream records, whichever comes first. </note> """ def get_records(client, input, options \\ []) do request(client, "GetRecords", input, options) end @doc """ Returns a shard iterator. A shard iterator provides information about how to retrieve the stream records from within a shard. Use the shard iterator in a subsequent `GetRecords` request to read the stream records from the shard. <note> A shard iterator expires 15 minutes after it is returned to the requester. </note> """ def get_shard_iterator(client, input, options \\ []) do request(client, "GetShardIterator", input, options) end @doc """ Returns an array of stream ARNs associated with the current account and endpoint. If the `TableName` parameter is present, then `ListStreams` will return only the streams ARNs for that table. <note> You can call `ListStreams` at a maximum rate of 5 times per second. </note> """ def list_streams(client, input, options \\ []) do request(client, "ListStreams", input, options) end @spec request(AWS.Client.t(), binary(), map(), list()) :: {:ok, Poison.Parser.t() | nil, Poison.Response.t()} | {:error, Poison.Parser.t()} | {:error, HTTPoison.Error.t()} defp request(client, action, input, options) do client = %{client | service: "dynamodb"} host = build_host("streams.dynamodb", client) url = build_url(host, client) headers = [ {"Host", host}, {"Content-Type", "application/x-amz-json-1.0"}, {"X-Amz-Target", "DynamoDBStreams_20120810.#{action}"} ] payload = Poison.Encoder.encode(input, %{}) headers = AWS.Request.sign_v4(client, "POST", url, headers, payload) case HTTPoison.post(url, payload, headers, options) do {:ok, %HTTPoison.Response{status_code: 200, body: ""} = response} -> {:ok, nil, response} {:ok, %HTTPoison.Response{status_code: 200, body: body} = response} -> {:ok, Poison.Parser.parse!(body, %{}), response} {:ok, %HTTPoison.Response{body: body}} -> error = Poison.Parser.parse!(body, %{}) {:error, error} {:error, %HTTPoison.Error{reason: reason}} -> {:error, %HTTPoison.Error{reason: reason}} end end defp build_host(_endpoint_prefix, %{region: "local"}) do "localhost" end defp build_host(endpoint_prefix, %{region: region, endpoint: endpoint}) do "#{endpoint_prefix}.#{region}.#{endpoint}" end defp build_url(host, %{:proto => proto, :port => port}) do "#{proto}://#{host}:#{port}/" end end
lib/aws/streams_dynamodb.ex
0.886844
0.54698
streams_dynamodb.ex
starcoder
defmodule Sponsorly.Accounts.User do use Ecto.Schema import Ecto.Changeset @derive {Inspect, except: [:password]} schema "users" do field :confirmed_at, :naive_datetime field :email, :string field :hashed_password, :string field :slug, :string field :is_creator, :boolean field :is_sponsor, :boolean field :password, :string, virtual: true field :type, Ecto.Enum, values: [:creator, :sponsor, :both], virtual: true timestamps() end @doc """ A user changeset for registration. It is important to validate the length of both email and password. Otherwise databases may truncate the email without warnings, which could lead to unpredictable or insecure behaviour. Long passwords may also be very expensive to hash for certain algorithms. ## Options * `:hash_password` - Hashes the password so it can be stored securely in the database and ensures the password field is cleared to prevent leaks in the logs. If password hashing is not needed and clearing the password field is not desired (like when using this changeset for validations on a LiveView form), this option can be set to `false`. Defaults to `true`. """ def registration_changeset(user, attrs, opts \\ []) do user |> cast(attrs, [:email, :password, :type]) |> validate_type() |> validate_email() |> validate_password(opts) end defp validate_type(changeset) do changeset |> set_is_creator() |> set_is_sponsor() |> validate_required([:type, :is_creator, :is_sponsor]) end defp set_is_creator(changeset) do case get_field(changeset, :type) do type when type in [:creator, :both] -> put_change(changeset, :is_creator, true) _ -> put_change(changeset, :is_creator, false) end end defp set_is_sponsor(changeset) do case get_field(changeset, :type) do type when type in [:sponsor, :both] -> put_change(changeset, :is_sponsor, true) _ -> put_change(changeset, :is_sponsor, false) end end defp validate_email(changeset) do changeset |> validate_required([:email]) |> validate_format(:email, ~r/^[^\s]+@[^\s]+$/, message: "must have the @ sign and no spaces") |> validate_length(:email, max: 160) |> unsafe_validate_unique(:email, Sponsorly.Repo) |> unique_constraint(:email) end defp validate_password(changeset, opts) do changeset |> validate_required([:password]) |> validate_length(:password, min: 12, max: 80) # |> validate_format(:password, ~r/[a-z]/, message: "at least one lower case character") # |> validate_format(:password, ~r/[A-Z]/, message: "at least one upper case character") # |> validate_format(:password, ~r/[!?@#$%^&*_0-9]/, message: "at least one digit or punctuation character") |> maybe_hash_password(opts) end defp maybe_hash_password(changeset, opts) do hash_password? = Keyword.get(opts, :hash_password, true) password = get_change(changeset, :password) if hash_password? && password && changeset.valid? do changeset |> put_change(:hashed_password, Bcrypt.hash_pwd_salt(password)) |> delete_change(:password) else changeset end end @doc """ A user changeset for changing the email. It requires the email to change otherwise an error is added. """ def email_changeset(user, attrs) do user |> cast(attrs, [:email]) |> validate_email() |> case do %{changes: %{email: _}} = changeset -> changeset %{} = changeset -> add_error(changeset, :email, "did not change") end end @doc """ A user changeset for changing the password. ## Options * `:hash_password` - Hashes the password so it can be stored securely in the database and ensures the password field is cleared to prevent leaks in the logs. If password hashing is not needed and clearing the password field is not desired (like when using this changeset for validations on a LiveView form), this option can be set to `false`. Defaults to `true`. """ def password_changeset(user, attrs, opts \\ []) do user |> cast(attrs, [:password]) |> validate_confirmation(:password, message: "does not match password") |> validate_password(opts) end @doc """ Confirms the account by setting `confirmed_at`. """ def confirm_changeset(user) do now = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second) change(user, confirmed_at: now) end @doc """ Onboards the account by setting `slug` """ def onboard_changeset(user, attrs) do user |> cast(attrs, [:slug]) |> validate_required([:slug]) |> validate_slug() end @doc """ A changeset for user fields except email and password """ def user_changeset(user, attrs) do user |> cast(attrs, [:is_creator, :is_sponsor, :slug]) |> validate_required([:is_creator, :is_sponsor]) |> validate_slug() end defp validate_slug(changeset) do changeset |> validate_format(:slug, ~r/^[a-z0-9-]+$/, message: "must only contain lowercase characters (a-z), numbers (0-9), and \"-\"") |> unique_constraint(:slug) end @doc """ Verifies the password. If there is no user or the user doesn't have a password, we call `Bcrypt.no_user_verify/0` to avoid timing attacks. """ def valid_password?(%Sponsorly.Accounts.User{hashed_password: <PASSWORD>_password}, password) when is_binary(hashed_password) and byte_size(password) > 0 do Bcrypt.verify_pass(password, <PASSWORD>) end def valid_password?(_, _) do Bcrypt.no_user_verify() false end @doc """ Validates the current password otherwise adds an error to the changeset. """ def validate_current_password(changeset, password) do if valid_password?(changeset.data, password) do changeset else add_error(changeset, :current_password, "is not valid") end end end
lib/sponsorly/accounts/user.ex
0.685213
0.434461
user.ex
starcoder
defmodule ResxDropbox do @moduledoc """ A producer to handle dropbox URIs. ResxDropbox.open("dbpath:/path/to/file.txt") ResxDropbox.open("dbid:AAAAAAAAAAAAAAAAAAAAAA") Add `ResxDropbox` to your list of resx producers. config :resx, producers: [ResxDropbox] ### Types MIME types are inferred from file extension names. Following the behaviour of `Resx.Producers.File.mime/1`. ### Authorities Authorities are used to match with a dropbox access token. When no authority is provided, it will attempt to find an access token for `nil`. These tokens can be configured by setting the `:token` configuration option for `:resx_dropbox`. config :resx_dropbox, token: "TOKEN" config :resx_dropbox, token: %{ nil => "TOKEN1", "foo@bar" => "TOKEN2", "main" => "TOKEN3" } config :resx_dropbox, token: { MyDropboxTokenRetriever, :to_token, 1 } The `:token` field should contain either a string which will be the token used by any authority, or a map of authority keys and token string values, or a callback function that will be passed the authority and should return `{ :ok, token }` or `:error` if there is no token for the given authority. Valid function formats are any callback variant, see `Callback` for more information. ### Sources Dropbox sources are dropbox content references with a backup data source, so if the content no longer exists it will revert back to getting the data from the source and creating the content again. The data source is any compatible URI. ResxDropbox.open("dbpath:/foo.txt?source=ZGF0YTp0ZXh0L3BsYWluO2NoYXJzZXQ9VVMtQVNDSUk7YmFzZTY0LGRHVnpkQT09") If the source cannot be accessed anymore but the content exists, it will access the content. If both cannot be accessed then the request will fail. """ use Resx.Producer use Resx.Storer require Callback alias Resx.Resource alias Resx.Resource.Content alias Resx.Resource.Reference alias Resx.Resource.Reference.Integrity defp get_token(name) do case Application.get_env(:resx_dropbox, :token, %{}) do to_token when Callback.is_callback(to_token) -> Callback.call(to_token, [name]) tokens when is_map(tokens) -> Map.fetch(tokens, name) token -> { :ok, token } end end defp to_path(%Reference{ repository: repo }), do: { :ok, repo } defp to_path(%URI{ scheme: "dbpath", path: nil, authority: authority, query: query }), do: build_repo(authority, { :path, "" }, query) defp to_path(%URI{ scheme: "dbpath", path: "/", authority: authority, query: query }), do: build_repo(authority, { :path, "" }, query) defp to_path(%URI{ scheme: "dbpath", path: path, authority: authority, query: query }), do: build_repo(authority, { :path, path }, query) defp to_path(%URI{ scheme: "dbid", path: "/" }), do: { :error, { :invalid_reference, "no ID" } } defp to_path(%URI{ scheme: "dbid", path: "/" <> path, authority: authority, query: query }), do: build_repo(authority, { :id, "id:" <> path }, query) defp to_path(%URI{ scheme: "dbid", path: path, authority: authority, query: query }) when not is_nil(path), do: build_repo(authority, { :id, "id:" <> path }, query) defp to_path(uri) when is_binary(uri), do: URI.decode(uri) |> URI.parse |> to_path defp to_path(_), do: { :error, { :invalid_reference, "not a dropbox reference" } } defp build_repo(authority, path, nil), do: { :ok, { authority, path, nil } } defp build_repo(_, { :id, _ }, _), do: { :error, { :invalid_reference, "dbid cannot have a source" } } defp build_repo(authority, path, query) do with %{ "source" => data } <- URI.decode_query(query), { :ok, source } <- Base.decode64(data) do { :ok, { authority, path, source } } else _ -> { :error, { :invalid_reference, "source is not base64" } } end end defp format_api_error(%{ "error" => %{ ".tag" => "path", "path" => %{ ".tag" => "malformed_path" } } }, _), do: { :error, { :invalid_reference, "invalid path format" } } defp format_api_error(%{ "error" => %{ ".tag" => "path", "path" => %{ ".tag" => "restricted_content" } } }, _), do: { :error, { :invalid_reference, "content is restricted" } } defp format_api_error(%{ "error" => %{ ".tag" => "path", "path" => %{ ".tag" => error } } }, path) when error in ["not_found", "not_file", "not_folder"], do: { :error, { :unknown_resource, path } } defp format_api_error(%{ "error_summary" => summary }, _), do: { :error, { :internal, summary } } defp format_http_error({ :ok, response = %{ status_code: 400 } }, _, _), do: { :error, { :internal, response.body } } defp format_http_error({ :ok, response }, path, _) do case Poison.decode(response.body) do { :ok, error } -> format_api_error(error, path) _ -> { :error, { :internal, response.body } } end end defp format_http_error({ :error, error }, _, action), do: { :error, { :internal, "failed to #{action} due to: #{HTTPoison.Error.message(error)}" } } defp header(token), do: [{"Authorization", "Bearer #{token}"}] defp get_header([{ key, value }|_], key), do: value defp get_header([_|headers], key), do: get_header(headers, key) defp get_header(_, _), do: nil defp api_result(response), do: get_header(response.headers, "dropbox-api-result") defp format_timestamp(timestamp) do { :ok, timestamp, _ } = DateTime.from_iso8601(timestamp) timestamp end defp timestamp(data, :server), do: data["server_modified"] |> format_timestamp defp timestamp(data, :client), do: data["client_modified"] |> format_timestamp defp timestamp(data, nil), do: timestamp(data, Application.get_env(:resx_dropbox, :timestamp, :server)) defp get_metadata(path, token), do: HTTPoison.post("https://api.dropboxapi.com/2/files/get_metadata", Poison.encode!(%{ path: path }), [{"Content-Type", "application/json"}|header(token)]) defp download(path, token), do: HTTPoison.post("https://content.dropboxapi.com/2/files/download", "", [{"Dropbox-API-Arg", Poison.encode!(%{ path: path })}|header(token)]) defp upload(path, token, contents, timestamp, mute), do: HTTPoison.post("https://content.dropboxapi.com/2/files/upload", contents, [{"Dropbox-API-Arg", Poison.encode!(%{ path: path, mode: :overwrite, client_modified: timestamp, mute: mute })}|header(token)]) defp delete(path, token), do: HTTPoison.post("https://api.dropboxapi.com/2/files/delete", Poison.encode!(%{ path: path }), [{"Content-Type", "application/json"}|header(token)]) @impl Resx.Producer def schemes(), do: ["dbpath", "dbid"] @doc """ Opens a dropbox resource. The `:timestamp` allows for choosing between `:server` or `:client` timestamps. By default the server timestamp is used, or whatever application timestamp setting was given. config :resx_dropbox, timestamp: :client If it is a source reference then a `:mute` option may be passed, which expects a boolean indicating whether the action should appear in the dropbox change history or not. """ @impl Resx.Producer def open(reference, opts \\ []) do with { :path, { :ok, repo = { name, { _, path }, _ } } } <- { :path, to_path(reference) }, { :token, { :ok, token }, _ } <- { :token, get_token(name), name }, { :content, { :ok, response = %HTTPoison.Response{ status_code: 200 } }, _ } <- { :content, download(path, token), repo }, { :data, { :ok, data } } <- { :data, api_result(response) |> Poison.decode } do content = %Content{ type: Resx.Producers.File.mime(data["name"]), data: response.body } resource = %Resource{ reference: %Reference{ adapter: __MODULE__, repository: repo, integrity: %Integrity{ timestamp: timestamp(data, opts[:timestamp]), checksum: { :dropbox, data["content_hash"] } } }, content: content } { :ok, resource } else { :path, error } -> error { :token, _, name } -> { :error, { :invalid_reference, "no token for authority (#{inspect name})" } } { :content, error, { _, { _, path }, nil } } -> format_http_error(error, path, "retrieve content") { :content, _, { name, { :path, path }, source } } -> Resource.store(source, __MODULE__, auth: name, path: path, mute: opts[:mute]) { :data, _ } -> { :error, { :internal, "unable to process api result" } } end end @impl Resx.Producer def exists?(reference) do with { :path, { :ok, repo = { name, { _, path }, _ } } } <- { :path, to_path(reference) }, { :token, { :ok, token }, _ } <- { :token, get_token(name), name }, { :metadata, { :ok, %HTTPoison.Response{ status_code: 200 } }, _ } <- { :metadata, get_metadata(path, token), repo } do { :ok, true } else { :path, error } -> error { :token, _, name } -> { :error, { :invalid_reference, "no token for authority (#{inspect name})" } } { :metadata, error, { _, { _, path }, nil } } -> case format_http_error(error, path, "retrieve metadata") do { :error, { :unknown_resource, _ } } -> { :ok, false } error -> error end { :metadata, _, { _, _, source } } -> Resource.exists?(source) end end @doc """ See if two references are alike. This will check if two references are referring to the same content regardless of if they're not of the same kind (aren't both paths or ids) or have different access tokens (two different accounts referencing the same shared file). Due to this not all the comparisons can be made without making an API request, if there is ever a failure accessing that API then the function will assume that the two references are not alike. """ @impl Resx.Producer def alike?(a, b) do with { :a, { :ok, repo_a } } <- { :a, to_path(a) }, { :b, { :ok, repo_b } } <- { :b, to_path(b) } do case { repo_a, repo_b } do { repo, repo } -> true { { _, { :id, id }, _ }, { _, { :id, id }, _ } } -> true { { name_a, path_a, _ }, { name_b, path_b, _ } } -> with { :token_a, { :ok, token_a }, _ } <- { :token_a, get_token(name_a), name_a }, { :token_b, { :ok, token_b }, _ } <- { :token_b, get_token(name_b), name_b } do a = case path_a do ^path_b when token_a == token_b -> true { :id, id } -> id { :path, path } -> with { :metadata, { :ok, response = %HTTPoison.Response{ status_code: 200 } }, _ } <- { :metadata, get_metadata(path, token_a), path }, { :data, { :ok, data } } <- { :data, response.body |> Poison.decode } do data["id"] else _ -> false end end case { path_b, a } do { _, false } -> false { _, true } -> true { { :id, id }, id } -> true { { :id, _ }, _ } -> false { { :path, path }, id } -> with { :metadata, { :ok, response = %HTTPoison.Response{ status_code: 200 } }, _ } <- { :metadata, get_metadata(path, token_b), path }, { :data, { :ok, data } } <- { :data, response.body |> Poison.decode } do data["id"] == id else _ -> false end end else _ -> false end end else _ -> false end end @impl Resx.Producer def source(reference) do case to_path(reference) do { :ok, { _, _, source } } -> { :ok, source } error -> error end end @impl Resx.Producer def resource_uri(reference) do case to_path(reference) do { :ok, { nil, { :id, id }, nil } } -> { :ok, URI.encode("db" <> id) } { :ok, { authority, { :id, "id:" <> id }, nil } } -> { :ok, URI.encode("dbid://" <> authority <> "/" <> id) } { :ok, { nil, { :path, path }, nil } } -> { :ok, URI.encode("dbpath:" <> path) } { :ok, { authority, { :path, path }, nil } } -> { :ok, URI.encode("dbpath://" <> authority <> path) } { :ok, { authority, { :path, path }, source } } -> case Resource.uri(source) do { :ok, uri } -> case authority do nil -> { :ok, URI.encode("dbpath:" <> path <> "?source=#{Base.encode64(uri)}") } authority -> { :ok, URI.encode("dbpath://" <> authority <> path <> "?source=#{Base.encode64(uri)}") } end error -> error end error -> error end end @impl Resx.Producer def resource_attributes(reference) do with { :path, { :ok, repo = { name, { _, path }, _ } } } <- { :path, to_path(reference) }, { :token, { :ok, token }, _ } <- { :token, get_token(name), name }, { :metadata, { :ok, metadata = %HTTPoison.Response{ status_code: 200 } }, _ } <- { :metadata, get_metadata(path, token), repo }, { :data, { :ok, data } } <- { :data, metadata.body |> Poison.decode } do { :ok, data } else { :path, error } -> error { :token, _, name } -> { :error, { :invalid_reference, "no token for authority (#{inspect name})" } } { :metadata, error, { _, { _, path }, nil } } -> format_http_error(error, path, "retrieve metadata") { :metadata, _, { _, _, source } } -> Resource.attributes(source) { :data, _ } -> { :error, { :internal, "unable to process api result" } } end end @doc """ Store a resource as a file in dropbox. The required options are: * `:path` - expects a string denoting the path the file will be stored at. The following options are all optional: * `:auth` - expects the authority to lookup the token of. * `:mute` - expects a boolean indicating whether the action should appear in the dropbox change history or not. """ @impl Resx.Storer def store(resource, options) do with { :path, { :ok, path } } <- { :path, Keyword.fetch(options, :path) }, name <- options[:auth], { :token, { :ok, token }, _ } <- { :token, get_token(name), name }, mute <- options[:mute] || false, data <- resource.content |> Content.reducer |> Enum.into(<<>>), meta_path <- path <> ".meta", timestamp <- DateTime.truncate(resource.reference.integrity.timestamp, :second) |> DateTime.to_iso8601, { :upload_meta, { :ok, %HTTPoison.Response{ status_code: 200 } }, _ } <- { :upload_meta, upload(meta_path, token, :erlang.term_to_binary(resource.meta), timestamp, mute), meta_path }, { :upload_content, { :ok, %HTTPoison.Response{ status_code: 200 } }, _ } <- { :upload_content, upload(path, token, data, timestamp, mute), path } do content = %Content{ type: Resx.Producers.File.mime(path), data: data } reference = %Reference{ adapter: __MODULE__, repository: { name, { :path, path }, resource.reference }, integrity: %Integrity{ timestamp: DateTime.utc_now } } { :ok, %{ resource | reference: reference, content: content } } else { :path, _ } -> { :error, { :internal, "a store :path must be specified" } } { :token, _, name } -> { :error, { :invalid_reference, "no token for authority (#{inspect name})" } } { :upload_content, error, path } -> format_http_error(error, path, "upload content") { :upload_meta, error, path } -> format_http_error(error, path, "upload meta") end end @doc """ Discard a dropbox resource. The following options are all optional: * `:meta` - specify whether the meta file should also be deleted. By default it is. * `:content` - specify whether the content file should also be deleted. By default it is. """ @impl Resx.Storer @spec discard(Resx.ref, [meta: boolean, content: boolean]) :: :ok | Resx.error(Resx.resource_error | Resx.reference_error) def discard(reference, opts) do with { :path, { :ok, { name, { _, path }, _ } } } <- { :path, to_path(reference) }, { :token, { :ok, token }, _ } <- { :token, get_token(name), name }, { :delete, { :ok, %HTTPoison.Response{ status_code: 200 } }, _, _ } <- { :delete, if(opts[:meta] != false, do: delete(path <> ".meta", token), else: { :ok, %HTTPoison.Response{ status_code: 200 } }), path, "meta" }, { :delete, { :ok, %HTTPoison.Response{ status_code: 200 } }, _, _ } <- { :delete, if(opts[:content] != false, do: delete(path, token), else: { :ok, %HTTPoison.Response{ status_code: 200 } }), path, "content" } do :ok else { :path, error } -> error { :token, _, name } -> { :error, { :invalid_reference, "no token for authority (#{inspect name})" } } { :delete, error, path, kind } -> format_http_error(error, path, "delete #{kind}") end end end
lib/resx_dropbox.ex
0.743075
0.414484
resx_dropbox.ex
starcoder
defmodule Joi do @external_resource "README.md" @moduledoc "README.md" |> File.read!() |> String.split("<!-- MDOC !-->") |> Enum.fetch!(1) alias Joi.Type @doc ~S""" Validate the data by schema Examples: iex> schema = %{ ...> id: [:string, uuid: true], ...> username: [:string, min_length: 6], ...> pin: [:integer, min: 1000, max: 9999], ...> new_user: [:boolean, truthy: ["1"], falsy: ["0"], required: false], ...> account_ids: [:list, type: :integer, max_length: 3], ...> remember_me: [:boolean, required: false] ...> } %{ account_ids: [:list, {:type, :integer}, {:max_length, 3}], id: [:string, {:uuid, true}], new_user: [:boolean, {:truthy, ["1"]}, {:falsy, ["0"]}, {:required, false}], pin: [:integer, {:min, 1000}, {:max, 9999}], remember_me: [:boolean, {:required, false}], username: [:string, {:min_length, 6}] } iex> data = %{id: "c8ce4d74-fab8-44fc-90c2-736b8d27aa30", username: "user@123", pin: 1234, new_user: "1", account_ids: [1, 3, 9]} %{ account_ids: [1, 3, 9], id: "c8ce4d74-fab8-44fc-90c2-736b8d27aa30", new_user: "1", pin: 1234, username: "user@123" } iex> Joi.validate(data, schema) {:ok, %{ account_ids: [1, 3, 9], id: "c8ce4d74-fab8-44fc-90c2-736b8d27aa30", new_user: true, pin: 1234, username: "user@123" }} iex> error_data = %{id: "1", username: "user", pin: 999, new_user: 1, account_ids: [1, 3, 9, 12]} %{account_ids: [1, 3, 9, 12], id: "1", new_user: 1, pin: 999, username: "user"} iex> Joi.validate(error_data, schema) {:error, [ %Joi.Error{ context: %{key: :username, limit: 6, value: "user"}, message: "username length must be at least 6 characters long", path: [:username], type: "string.min_length" }, %Joi.Error{ context: %{key: :pin, limit: 1000, value: 999}, message: "pin must be greater than or equal to 1000", path: [:pin], type: "integer.min" }, %Joi.Error{ context: %{key: :new_user, value: 1}, message: "new_user must be a boolean", path: [:new_user], type: "boolean.base" }, %Joi.Error{ context: %{key: :id, value: "1"}, message: "id must be a uuid", path: [:id], type: "string.uuid" }, %Joi.Error{ context: %{key: :account_ids, limit: 3, value: [1, 3, 9, 12]}, message: "account_ids must contain less than or equal to 3 items", path: [:account_ids], type: "list.max_length" } ]} """ @spec validate(map(), map()) :: {:error, list(Joi.Error.t())} | {:ok, map()} def validate(data, schema) do data |> Map.put(:joi_errors, []) |> validate_all_fields(schema) |> parse_result() end defp validate_all_fields(data, schema) do Enum.reduce(schema, {:ok, data}, fn {field, [type | options]}, {:ok, modified_data} -> case Type.validate(type, field, modified_data, options) do {:error, error} -> {:ok, %{modified_data | joi_errors: [error | modified_data.joi_errors]}} {:ok, new_data} -> {:ok, new_data} end end) end defp parse_result(result) do {:ok, data} = result case data.joi_errors do [] -> {:ok, Map.drop(data, [:joi_errors])} errors -> {:error, errors |> List.flatten()} end end end
lib/joi.ex
0.734596
0.406361
joi.ex
starcoder
defmodule Raxx.Router do @moduledoc """ Simple router for Raxx applications. A router is a list of associations between a request pattern and controller module. `Raxx.Router` needs to be used after `Raxx.Server`, it is an extension to a standard Raxx.Server. Each controller module that is passed requests from `Raxx.Router` are also standalone `Raxx.Server`s. *`Raxx.Router` is a deliberatly low level interface that can act as a base for more sophisticated routers. `Raxx.Blueprint` part of the [tokumei project](https://hexdocs.pm/tokumei/Raxx.Blueprint.html) is one example. ## Examples defmodule MyRouter do use Raxx.Server use Raxx.Router, [ {%{method: :GET, path: []}, HomePage}, {%{method: :GET, path: ["users"]}, UsersPage}, {%{method: :GET, path: ["users", _id]}, UserPage}, {%{method: :POST, path: ["users"]}, CreateUser}, {_, NotFoundPage} ] end """ @doc false defmacro __using__(actions) when is_list(actions) do routes = for {match, controller} <- actions do {resolved_module, []} = Module.eval_quoted(__CALLER__, controller) case Code.ensure_compiled(resolved_module) do {:module, ^resolved_module} -> behaviours = resolved_module.module_info[:attributes] |> Keyword.get(:behaviour, []) case Enum.member?(behaviours, Raxx.Server) do true -> :no_op false -> raise "module #{Macro.to_string(resolved_module)} should implement behaviour Raxx.Server" end {:error, :nofile} -> raise "module #{Macro.to_string(resolved_module)} is not loaded" end # NOTE use resolved module to include any aliasing controller_string = inspect(resolved_module) match_string = Macro.to_string(match) quote do def handle_head(request = unquote(match), state) do Logger.metadata("raxx.action": unquote(controller_string)) Logger.metadata("raxx.route": unquote(match_string)) case unquote(controller).handle_head(request, state) do {outbound, new_state} -> {outbound, {unquote(controller), new_state}} response = %{status: _status} -> response end end end end quote location: :keep do @impl Raxx.Server def handle_request(_request, _state) do raise "This callback should never be called in a on #{__MODULE__}." end @impl Raxx.Server unquote(routes) @impl Raxx.Server def handle_data(data, {controller, state}) do case controller.handle_data(data, state) do {outbound, new_state} -> {outbound, {controller, new_state}} response = %{status: _status} -> response end end @impl Raxx.Server def handle_tail(trailers, {controller, state}) do case controller.handle_tail(trailers, state) do {outbound, new_state} -> {outbound, {controller, new_state}} response = %{status: _status} -> response end end @impl Raxx.Server def handle_info(message, {controller, state}) do case controller.handle_info(message, state) do {outbound, new_state} -> {outbound, {controller, new_state}} response = %{status: _status} -> response end end end end end
lib/raxx/router.ex
0.794664
0.532729
router.ex
starcoder
defmodule Dataset do @moduledoc """ Defines the structure of a dataset within Hindsight. Datasets track the metadata attached to a collection of data including the owning entity (source) for the data, a description and keywords for catagorizing and discoverability, and a profile of updates to the data and its metadata, as well as relevant temporal or spatial boundaries represented by the data. The "updated_ts" records the last data/time the data was amended. The "modified_meta_ts" reflects the last time the metadata in the dataset definition was changed. # Examples iex> Dataset.new( ...> version: 1, ...> id: "123-456", ...> owner_id: "456-789", ...> name: "Cooldata", ...> description: "The coolest data", ...> keywords: ["cool", "awesome", "inspirational"], ...> license: "GPL", ...> created_ts: "2020-01-20 18:05:00Z", ...> profile: %{ ...> updated_ts: "2020-01-20 18:05:00Z", ...> profiled_ts: "2020-01-20 18:05:00Z", ...> modified_meta_ts: "", ...> spatial: [], ...> temporal: ["2020-01-01 00:00:00Z", "2020-01-15 12:00:00Z"] ...> } ...> ) {:ok, %Dataset{ version: 1, id: "123-456", owner_id: "456-789", name: "Cooldata", description: "The coolest data", keywords: ["cool", "awesome", "inspirational"], license: "GPL", created_ts: "2020-01-20 18:05:00Z", profile: %{ updated_ts: "2020-01-20 18:05:00Z", profiled_ts: "2020-01-20 18:05:00Z", modified_meta_ts: "", spatial: [], temporal: ["2020-01-01 00:00:00Z", "2020-01-15 12:00:00Z"] } } } """ use Definition, schema: Dataset.V1 defstruct version: nil, id: nil, owner_id: nil, name: nil, description: "", keywords: [], license: nil, created_ts: nil, profile: %{ updated_ts: "", profiled_ts: "", modified_meta_ts: "", spatial: [], temporal: [] } end
apps/definition_dataset/lib/dataset.ex
0.775732
0.768603
dataset.ex
starcoder
defmodule Porterage do @moduledoc """ Checks, fetches and delivers configurable data sources. ## Usage Place a porterage instance in your supervision tree: { Porterage, %{ deliverer: MyDeliverer, deliverer_opts: %{}, fetcher: MyFetcher, fetcher_opts: %{}, scheduler: MyScheduler, scheduler_opts: %{}, supervisor: [], tester: MyTester, tester_opts: %{} } } See `t:config/0` for a specification of the available configuration keys. ### Supervisor Configuration If a `:supervisor` key is set the values are passed as the options argument to `Supervisor.start_link/3`. ## Data Flow 1. `Porterage.Scheduler` Depending on the `:scheduler` chosen a `:tick` will start the data flow. 2. `Porterage.Tester` If the scheduler decided it is time to test the data source the chosen `:tester` will receive a notification to do so. 3. `Porterage.Fetcher` Every time a test for new data was deemed successful the `:fetcher` will retrieve the data to be delivered. 4. `Porterage.Deliverer` Once the data was fetched in the previous step the `:deliverer` will take care of delivering it to the target. Every step of the flow can be manually triggered. """ use Supervisor alias Porterage.Deliverer alias Porterage.Fetcher alias Porterage.Scheduler alias Porterage.Tester @type config :: %{ :deliverer => module, :fetcher => module, :scheduler => module, :tester => module, optional(:deliverer_opts) => map, optional(:fetcher_opts) => map, optional(:scheduler_opts) => map, optional(:supervisor) => [ Supervisor.option() | Supervisor.init_option() ], optional(:tester_opts) => map } @doc false @spec start_link(config) :: Supervisor.on_start() def start_link(config) do Supervisor.start_link(__MODULE__, config, config[:supervisor] || []) end @doc false @spec init(config) :: {:ok, {:supervisor.sup_flags(), [:supervisor.child_spec()]}} def init(config) do children = [ {Scheduler, [self(), config[:scheduler], config[:scheduler_opts]]}, {Tester, [self(), config[:tester], config[:tester_opts]]}, {Fetcher, [self(), config[:fetcher], config[:fetcher_opts]]}, {Deliverer, [self(), config[:deliverer], config[:deliverer_opts]]} ] Supervisor.init(children, strategy: :one_for_one) end @doc """ Force a delivery for a specific instance with custom data. """ @spec deliver(Supervisor.supervisor(), any) :: :ok | :error def deliver(supervisor, data), do: cast_to_process(supervisor, Deliverer, {:deliver, data}) @doc """ Force a fetch for a specific instance. """ @spec fetch(Supervisor.supervisor()) :: :ok | :error def fetch(supervisor), do: cast_to_process(supervisor, Fetcher, :fetch) @doc """ Force a test for a specific instance. """ @spec test(Supervisor.supervisor()) :: :ok | :error def test(supervisor), do: cast_to_process(supervisor, Tester, :test) @doc """ Force a tick for a specific instance. """ @spec tick(Supervisor.supervisor()) :: :ok | :error def tick(supervisor), do: cast_to_process(supervisor, Scheduler, :tick) defp cast_to_process(supervisor, module, message) do case child(supervisor, module) do pid when is_pid(pid) -> GenServer.cast(pid, message) _ -> :error end end defp child(supervisor, id) do supervisor |> Supervisor.which_children() |> find_child(id) end defp find_child([], _), do: nil defp find_child([{id, pid, :worker, _} | _], id), do: pid defp find_child([_ | children], id), do: find_child(children, id) end
lib/porterage.ex
0.81409
0.429429
porterage.ex
starcoder
defmodule BSON.Binary do @moduledoc """ Represents BSON binary type """ defstruct [binary: nil, subtype: :generic] defimpl Inspect do def inspect(%BSON.Binary{binary: value, subtype: :generic}, _opts) do "#BSON.Binary<#{Base.encode16(value, case: :lower)}>" end def inspect(%BSON.Binary{binary: value, subtype: subtype}, _opts) do "#BSON.Binary<#{Base.encode16(value, case: :lower)}, #{subtype}>" end end end defmodule BSON.ObjectId do @moduledoc """ Represents BSON ObjectId type """ defstruct [:value] @doc """ Creates a new ObjectId from the consisting parts """ def new(machine_id, proc_id, secs, counter) do value = <<secs :: unsigned-big-32, machine_id :: unsigned-big-24, proc_id :: unsigned-big-16, counter :: unsigned-big-24>> %BSON.ObjectId{value: value} end defimpl Inspect do def inspect(%BSON.ObjectId{value: value}, _opts) do "#BSON.ObjectId<#{Base.encode16(value, case: :lower)}>" end end end defmodule BSON.DateTime do @moduledoc """ Represents BSON DateTime type """ defstruct [:utc] @epoch :calendar.datetime_to_gregorian_seconds({{1970, 1, 1}, {0, 0, 0}}) @doc """ Converts `BSON.DateTime` into a `{{year, month, day}, {hour, min, sec, usec}}` tuple. """ def to_datetime(%BSON.DateTime{utc: utc}) do seconds = div(utc, 1000) + @epoch usec = rem(utc, 1000) * 1000 {date, {hour, min, sec}} = :calendar.gregorian_seconds_to_datetime(seconds) {date, {hour, min, sec, usec}} end @doc """ Converts `{{year, month, day}, {hour, min, sec, usec}}` into a `BSON.DateTime` struct. """ def from_datetime({date, {hour, min, sec, usec}}) do greg_secs = :calendar.datetime_to_gregorian_seconds({date, {hour, min, sec}}) epoch_secs = greg_secs - @epoch %BSON.DateTime{utc: epoch_secs * 1000 + div(usec, 1000)} end @doc """ Converts `BSON.DateTime` to its ISO8601 representation """ def to_iso8601(%BSON.DateTime{} = datetime) do {{year, month, day}, {hour, min, sec, usec}} = to_datetime(datetime) str = zero_pad(year, 4) <> "-" <> zero_pad(month, 2) <> "-" <> zero_pad(day, 2) <> "T" <> zero_pad(hour, 2) <> ":" <> zero_pad(min, 2) <> ":" <> zero_pad(sec, 2) case usec do 0 -> str <> "Z" _ -> str <> "." <> zero_pad(usec, 6) <> "Z" end end defp zero_pad(val, count) do num = Integer.to_string(val) :binary.copy("0", count - byte_size(num)) <> num end defimpl Inspect do def inspect(%BSON.DateTime{} = datetime, _opts) do "#BSON.DateTime<#{BSON.DateTime.to_iso8601(datetime)}>" end end end defmodule BSON.Regex do @moduledoc """ Represents BSON Regex type """ defstruct [:pattern, :options] defimpl Inspect do def inspect(%BSON.Regex{pattern: pattern, options: nil}, _opts) do "#BSON.Regex<#{inspect pattern}>" end def inspect(%BSON.Regex{pattern: pattern, options: options}, _opts) do "#BSON.Regex<#{inspect pattern}, #{inspect options}>" end end end defmodule BSON.JavaScript do @moduledoc """ Represents BSON JavaScript (with and without scope) types """ defstruct [:code, :scope] defimpl Inspect do def inspect(%BSON.JavaScript{code: code, scope: nil}, _opts) do "#BSON.JavaScript<#{inspect code}>" end def inspect(%BSON.JavaScript{code: code, scope: scope}, _opts) do "#BSON.JavaScript<#{inspect code}, #{inspect(scope)}>" end end end defmodule BSON.Timestamp do @moduledoc """ Represents BSON Timestamp type """ defstruct [:value] defimpl Inspect do def inspect(%BSON.Timestamp{value: value}, _opts) do "#BSON.Timestamp<#{value}>" end end end
lib/bson/types.ex
0.772273
0.519521
types.ex
starcoder
defmodule Fxnk.Logic do @moduledoc """ `Fxnk.Logic` are functions for dealing with booleans. """ import Fxnk.Functions, only: [curry: 1] @doc """ Curried `and?/2`. ## Examples iex> isTwo? = Fxnk.Logic.and?(2) iex> isTwo?.(2) true iex> isTwo?.(3) false """ @spec and?(any) :: (any() -> boolean()) def and?(x) do curry(fn y -> and?(x, y) end) end @doc """ `and?` returns true if both inputs are the same, opposite of `is_not/2`. ## Examples iex> Fxnk.Logic.and?(2, 2) true iex> Fxnk.Logic.and?("hello", "world") false """ @spec and?(any, any) :: boolean() def and?(x, x), do: true def and?(_, _), do: false @doc """ Curried `both?/3`. ## Examples iex> gt10lt20? = Fxnk.Logic.both?(fn x -> x > 10 end, fn x -> x < 20 end) iex> gt10lt20?.(15) true iex> gt10lt20?.(30) false """ @spec both?(function(), function()) :: (any() -> boolean()) def both?(func1, func2) do curry(fn input -> both?(input, func1, func2) end) end @doc """ `both?/3` takes an input and two predicate functions, returning true if both functions are true when passed the input. ## Examples iex> Fxnk.Logic.both?(15, fn x -> x > 10 end, fn x -> x < 20 end) true iex> Fxnk.Logic.both?(30, fn x -> x > 10 end, fn x -> x < 20 end) false """ @spec both?(function(), function(), any) :: boolean def both?(input, func1, func2) do func1.(input) && func2.(input) end @doc """ `complement/1` returns the opposite of the boolean passed to it. ## Examples iex> Fxnk.Logic.complement(true) false iex> Fxnk.Logic.complement(false) true """ @spec complement(any()) :: boolean() def complement(bool), do: !bool @doc """ Curried `default_to/2` ## Examples iex> defaultTo42 = Fxnk.Logic.default_to(42) iex> defaultTo42.(false) 42 iex> defaultTo42.(nil) 42 iex> defaultTo42.("thanks for all the fish") "thanks for all the fish" """ @spec default_to(any()) :: (any() -> boolean()) def default_to(x), do: curry(fn y -> default_to(y, x) end) @doc """ `default_to/2` takes two values and returns the right side value if the left side is `false` or `nil` ## Examples iex> false |> Fxnk.Logic.default_to(42) 42 iex> nil |> Fxnk.Logic.default_to(42) 42 iex> "hello, world" |> Fxnk.Logic.default_to(42) "hello, world" """ @spec default_to(any(), any()) :: any() def default_to(x, y) do case x do false -> y nil -> y _ -> x end end @doc """ Curried `either/3` ## Examples iex> lt10orGt30? = Fxnk.Logic.either?(fn x -> x < 10 end, fn x -> x > 30 end) iex> lt10orGt30?.(5) true iex> lt10orGt30?.(15) false """ @spec either?(function(), function()) :: (any() -> boolean()) def either?(func1, func2) do curry(fn input -> either?(input, func1, func2) end) end @doc """ `either?/3` takes an input and two predicate functions and returns true if either predicate is true. ## Examples iex> Fxnk.Logic.either?(5, fn x -> x < 10 end, fn x -> x > 30 end) true iex> Fxnk.Logic.either?(15, fn x -> x < 10 end, fn x -> x > 30 end) false """ @spec either?(any, function(), function()) :: boolean() def either?(input, func1, func2) do func1.(input) || func2.(input) end @doc """ Curried `equals/2` ## Example iex> eq_three = Fxnk.Logic.equals(3) iex> eq_three.(3) true iex> eq_three.(4) false """ @spec equals(any) :: (any -> boolean) def equals(x) do fn y -> equals(x, y) end end @doc """ Returns true if the two values passed to it are the same, false otherwise. ## Example iex> Fxnk.Logic.equals(%{foo: "foo"}, %{foo: "foo"}) true iex> Fxnk.Logic.equals(%{foo: "foo"}, %{bar: "bar"}) false """ @spec equals(any(), any()) :: boolean() def equals(x, x), do: true def equals(_, _), do: false @doc """ Curried `equals_by/3` ## Example iex> eq_by_math_abs = Fxnk.Logic.equals_by(&Kernel.abs/1) iex> eq_by_math_abs.(5).(-5) true """ @spec equals_by(function()) :: (any -> (any -> boolean)) def equals_by(func) do curry(fn x, y -> equals_by(func, x, y) end) end @doc """ Takes a function and applies the function to both arguments, returning if they are equal. ## Example iex> Fxnk.Logic.equals_by(&Kernel.abs/1, 5, -5) true """ @spec equals_by((function() -> any()), any(), any()) :: boolean() def equals_by(func, x, y) do func.(x) == func.(y) end @doc """ `is_empty/1` returns true if passed an empty `Map` or `List`. ## Examples iex> Fxnk.Logic.is_empty([]) true iex> Fxnk.Logic.is_empty(%{}) true iex> Fxnk.Logic.is_empty([1,1,2,3,5,8]) false """ @spec is_empty(any) :: boolean() def is_empty([]), do: true def is_empty(%{}), do: true def is_empty(_), do: false @doc """ Curried `is_not?/2` ## Examples iex> isNotThree = Fxnk.Logic.is_not?(3) iex> isNotThree.(3) false iex> isNotThree.(4) true """ @spec is_not?(any) :: (any() -> boolean()) def is_not?(x), do: curry(fn y -> is_not?(x, y) end) @doc """ `is_not/3` returns true if both inputs are not the same, opposite of `and?/2` ## Examples iex> Fxnk.Logic.is_not?(3, 3) false iex> Fxnk.Logic.is_not?(3, 4) true """ @spec is_not?(any, any) :: boolean() def is_not?(x, x), do: false def is_not?(_, _), do: true @doc """ Curried `or/2` ## Examples iex> willBeTrue = Fxnk.Logic.or?(true) iex> willBeTrue.(false) true """ @spec or?(any) :: (boolean() -> boolean()) def or?(x), do: curry(fn y -> or?(x, y) end) @doc """ `or/2` returns true if one or both of its arguments are true. ## Examples iex> Fxnk.Logic.or?(true, false) true iex> Fxnk.Logic.or?(true, true) true iex> Fxnk.Logic.or?(false, false) false """ @spec or?(boolean(), boolean()) :: boolean() def or?(true, _), do: true def or?(_, true), do: true def or?(_, _), do: false @doc """ Curried greater than function, returns a function that returns true if the second number passed in is greater than the first. ## Examples iex> greaterThan5? = Fxnk.Logic.gt?(5) iex> greaterThan5?.(19) true iex> greaterThan5?.(3) false """ @spec gt?(number) :: (number -> boolean()) def gt?(x) do curry(fn y -> x < y end) end @doc """ Curried less than function, returns a function that returns true if the second number passed in is less than the first. ## Examples iex> lessThan5? = Fxnk.Logic.lt?(5) iex> lessThan5?.(19) false iex> lessThan5?.(3) true """ @spec lt?(number) :: (number -> boolean()) def lt?(x) do curry(fn y -> x > y end) end @doc """ Checks if a value is equal to `nil`. ## Examples iex> Fxnk.Logic.nil?(nil) true iex> Fxnk.Logic.nil?("not nil") false """ @spec nil?(any()) :: boolean() def nil?(x) do x === nil end @doc """ Checks if a value is not `nil`. ## Examples iex> Fxnk.Logic.not_nil?(nil) false iex> Fxnk.Logic.not_nil?("not nil") true """ @spec not_nil?(any()) :: boolean() def not_nil?(x) do x !== nil end end
lib/fxnk/logic.ex
0.908496
0.652975
logic.ex
starcoder
defmodule Condiment do @moduledoc """ Add flavors to your context APIs easily! No need to create different functions to cater to different use cases, instead you can have one single public function and add flavors conditionally, with Condiment. """ @type t :: %__MODULE__{ token: any(), opts: list(), resolvers: list(), condiment_opts: list() } defstruct [:token, :opts, :resolvers, :condiment_opts] defmodule NotImplementedError do defexception [:message] end defimpl Inspect do import Inspect.Algebra def inspect(condiment, _opts) do data = condiment |> Map.from_struct() |> Enum.into([]) concat(["#Condiment<", inspect(data), ">"]) end end @doc """ To use `Condiment`, you start with the `Condiment.new/2,3` interface. The currently available options for `condiment_opts` is: - `:on_unknown_fields one of `:nothing`, `:error`, or `:raise` (default). This option specify what to do when user supplies a field that's not resolvable. """ @spec new(any, list(), list()) :: Condiment.t() def new(token, opts, condiment_opts \\ []) do %__MODULE__{ token: token, opts: opts, resolvers: [], condiment_opts: condiment_opts } end @doc """ `field` is what you allow users to query for. The resolver is how to resolve that query. The resolver has to be 2-arity, the first argument is the the result of the previously ran resolver (the first resolver gets `token` instead). """ @spec add(Condiment.t(), atom, (any, map() -> any)) :: Condiment.t() def add(%__MODULE__{} = condiment, key, resolver) when is_function(resolver, 2) and is_atom(key) do %{condiment | resolvers: [{key, resolver} | condiment.resolvers]} end @doc """ Runs all of the resolvers conditionally based on what user requested, it runs in the order that you defined (not the order the user supplied). """ @spec run(Condiment.t()) :: any def run(%__MODULE__{ token: token, opts: opts, resolvers: resolvers, condiment_opts: condiment_opts }) do resolvable_fields = Keyword.keys(resolvers) requested_fields = Keyword.keys(opts) validation = validate_opts(opts, resolvers) unknown_fields_strategy = Keyword.get(condiment_opts, :on_unknown_fields, :raise) case {validation, unknown_fields_strategy} do {{:error, field}, :error} -> {:error, build_message(field, resolvable_fields)} {{:error, field}, :raise} -> raise NotImplementedError, build_message(field, resolvable_fields) _ -> map_opts = opts |> Enum.into(%{}) resolvers |> Enum.reverse() |> Enum.filter(fn {field, _resolver} -> field in requested_fields end) |> Enum.reduce(token, fn {_field, resolver}, acc -> resolver.(acc, map_opts) end) end end defp validate_opts(opts, resolvers) do resolvable_fields = Keyword.keys(resolvers) requested_fields = Keyword.keys(opts) requested_fields |> Enum.reduce_while(:ok, fn f, _acc -> case f in resolvable_fields do true -> {:cont, :ok} false -> {:halt, {:error, f}} end end) end defp build_message(field, resolvable_fields) do "Don't know how to resolve #{inspect(field)}. You can add to #{__MODULE__} with `#{__MODULE__}.add/3`. Current known resolvables: #{ inspect(resolvable_fields) }" end end
lib/condiment.ex
0.781956
0.581511
condiment.ex
starcoder
defmodule HLClock do @moduledoc """ Hybrid Logical Clock Provides globally-unique, monotonic timestamps. Timestamps are bounded by the clock synchronization constraint, max_drift. By default the max_drift is set to 300 seconds. In order to account for physical time drift within the system, timestamps should regularly be exchanged between nodes. Generate a timestamp at one node via HLClock.send_timestamp/1; at the other node, call HLClock.recv_timestamp/2 with the received timestamp from the first node. Inspired by https://www.cse.buffalo.edu/tech-reports/2014-04.pdf """ alias HLClock.Timestamp @doc """ Returns a specification to start an `HLClock.Server` under a supervisor In addition to standard `GenServer` opts, this allows for two other options to be passed to the underlying server: * `:node_id` - a zero arity function returning a 64 bit integer for the node ID or a constant value that was precomputed prior to starting; defaults to `HLClock.NodeId.hash/0` * `:max_drift` - the clock synchronization bound which is applied in either direction (i.e. timestamps are too far in the past or too far in the future); this value is in milliseconds and defaults to `300_000` """ def child_spec(opts) do %{ id: __MODULE__, type: :worker, start: {__MODULE__, :start_link, [opts]} } end def start_link(opts \\ []) do HLClock.Server.start_link(opts) end @doc """ Generate a single HLC Timestamp for sending to other nodes or local causality tracking """ def send_timestamp(server) do GenServer.call(server, :send_timestamp) end @doc """ Given the current timestamp for this node and a provided remote timestamp, perform the merge of both logical time and logical counters. Returns the new current timestamp for the local node. """ def recv_timestamp(server, remote) do GenServer.call(server, {:recv_timestamp, remote}) end @doc """ Functionally equivalent to using `send_timestamp/1`. This generates a timestamp for local causality tracking. """ def now(server) do GenServer.call(server, :send_timestamp) end @doc """ Determines if the clock's timestamp "happened before" a different timestamp """ def before?(t1, t2) do Timestamp.before?(t1, t2) end end
lib/hlclock.ex
0.918192
0.580293
hlclock.ex
starcoder
defmodule Velocy.Decoder do @moduledoc false # The implementation of this decoder is heavily inspired by that of Jason (https://github.com/michalmuskala/jason) use Bitwise alias Velocy.{Codegen, Error} import Codegen, only: [bytecase: 2] @spec parse(binary(), keyword()) :: {:ok, any()} | {:error, any()} def parse(data, _opts \\ []) when is_binary(data) do try do case value(data) do {value, <<>>} -> {:ok, value} {value, tail} -> {:ok, {value, tail}} end rescue e in MatchError -> {:error, Error.exception(e)} e in CaseClauseError -> {:error, Error.exception(e)} catch error -> {:error, error} end end @spec value(binary()) :: {any(), binary()} defp value(data) do bytecase data do _ in 0x01, rest -> {[], rest} type in 0x02..0x05, rest -> parse_array_without_index_table(type, rest) type in 0x06..0x09, rest -> parse_array_with_index_table(type, rest) _ in 0x0A, rest -> {%{}, rest} type in 0x0B..0x0E, rest -> parse_object(type, rest) # TODO: 0x0f..0x12 - objects with unsorted index table _ in 0x13, rest -> parse_compact_array(rest) _ in 0x14, rest -> parse_compact_object(rest) # 0x15..0x16 - reserved _ in 0x17, rest -> {:illegal, rest} _ in 0x18, rest -> {nil, rest} _ in 0x19, rest -> {false, rest} _ in 0x1A, rest -> {true, rest} _ in 0x1B, rest -> parse_double(rest) _ in 0x1C, rest -> parse_date_time(rest) # 0x1d - external -> not supported _ in 0x1E, rest -> {:min_key, rest} _ in 0x1F, rest -> {:max_key, rest} type in 0x20..0x27, rest -> parse_int(type, rest) type in 0x28..0x2F, rest -> parse_uint(type, rest) type in 0x30..0x39, rest -> parse_small_int(type, rest) type in 0x3A..0x3F, rest -> parse_neg_small_int(type, rest) _ in 0x40, rest -> {"", rest} type in 0x41..0xBE, rest -> parse_short_string(type, rest) _ in 0xBF, rest -> parse_string(rest) type in 0xC0..0xC7, rest -> parse_binary(type, rest) # 0xc8..0xcf - BCD -> not supported # 0xd0..0xd7 - negative BCD -> not supported # 0xd8..0xef - reserved # 0xf0..0xff - custom types -> not supported type, _rest -> error({:unsupported_type, type}) <<>> -> error(:unexpected_end) end end defp error(err), do: throw(err) @spec value_size(binary()) :: integer() | no_return() defp value_size(data) do bytecase data do _ in 0x01, _ -> 1 type in 0x02..0x09, rest -> get_array_size(type, rest) _ in 0x0A, _ -> 1 type in 0x0B..0x0E, rest -> get_object_size(type, rest) _ in 0x13..0x14, rest -> get_compact_size(rest) # 0x15..0x16 - reserved _ in 0x17..0x1A, _ -> 1 _ in 0x1B..0x1C, _ -> 9 # 0x1d - external -> not supported _ in 0x1E..0x1F, _ -> 1 type in 0x20..0x27, _ -> type - 0x1F + 1 type in 0x28..0x2F, _ -> type - 0x27 + 1 _ in 0x30..0x3F, _ -> 1 type in 0x40..0xBE, _ -> type - 0x40 _ in 0xBF, rest -> get_string_size(rest) type in 0xC0..0xC7, rest -> get_binary_size(type, rest) # 0xc8..0xcf - BCD -> not supported # 0xd0..0xd7 - negative BCD -> not supported # 0xd8..0xef - reserved # 0xf0..0xff - custom types -> not supported type, _rest -> error({:unsupported_type, type}) <<>> -> error(:unexpected_end) end end @compile {:inline, parse_double: 1} @spec parse_double(binary()) :: {any(), binary()} defp parse_double(<<value::float-little-size(64), rest::binary>>), do: {value, rest} @compile {:inline, parse_date_time: 1} @spec parse_date_time(binary()) :: {any(), binary()} defp parse_date_time(<<value::integer-unsigned-little-size(64), rest::binary>>), do: {DateTime.from_unix!(value, :millisecond), rest} @compile {:inline, parse_int: 2} @spec parse_int(integer(), binary()) :: {any(), binary()} defp parse_int(type, data) do size = type - 0x1F <<value::integer-signed-little-unit(8)-size(size), rest::binary>> = data {value, rest} end @compile {:inline, parse_uint: 2} @spec parse_uint(integer(), binary()) :: {any(), binary()} defp parse_uint(type, data) do size = type - 0x27 <<value::integer-unsigned-little-unit(8)-size(size), rest::binary>> = data {value, rest} end @compile {:inline, parse_small_int: 2} @spec parse_small_int(integer(), binary()) :: {any(), binary()} defp parse_small_int(type, rest), do: {type - 0x30, rest} @compile {:inline, parse_neg_small_int: 2} @spec parse_neg_small_int(integer(), binary()) :: {any(), binary()} defp parse_neg_small_int(type, rest), do: {type - 0x40, rest} @compile {:inline, parse_short_string: 2} @spec parse_short_string(integer(), binary()) :: {any(), binary()} defp parse_short_string(type, data) do length = type - 0x40 parse_short_string_content(length, data) end @spec parse_short_string_content(integer(), binary()) :: {any(), binary()} defp parse_short_string_content(length, data) do <<value::binary-size(length), rest::binary>> = data {value, rest} end @spec parse_string(binary()) :: {any(), binary()} defp parse_string( <<length::integer-unsigned-little-size(64), value::binary-size(length), rest::binary>> ) do {value, rest} end @compile {:inline, parse_binary: 2} @spec parse_binary(integer(), binary()) :: {any(), binary()} defp parse_binary(type, data) do size = type - 0xBF parse_binary_content(size, data) end @spec parse_binary_content(integer(), binary()) :: {any(), binary()} defp parse_binary_content(size, data) do <<length::integer-unsigned-little-unit(8)-size(size), value::binary-size(length), rest::binary>> = data {value, rest} end @spec get_array_size(integer(), binary()) :: integer() defp get_array_size(type, data) do offset = if type < 0x06, do: 0x02, else: 0x06 size_bytes = 1 <<< (type - offset) <<size::integer-unsigned-little-unit(8)-size(size_bytes), _rest::binary>> = data size end @spec get_object_size(integer(), binary()) :: integer() defp get_object_size(type, data) do offset = if type < 0x0E, do: 0x0B, else: 0x0E size_bytes = 1 <<< (type - offset) <<size::integer-unsigned-little-unit(8)-size(size_bytes), _rest::binary>> = data size end @spec get_binary_size(integer(), binary()) :: integer() defp get_binary_size(type, data) do size = type - 0xBF <<length::integer-unsigned-little-unit(8)-size(size), _rest::binary>> = data length end @spec get_compact_size(binary()) :: integer() defp get_compact_size(data) do {size, _} = parse_length(data, 0, 0, false) size end @spec get_string_size(binary()) :: integer() defp get_string_size(<<length::integer-unsigned-little-size(64), _::binary>>), do: length + 8 + 1 @spec parse_array_without_index_table(integer(), binary()) :: {list(), binary()} defp parse_array_without_index_table(type, data) do size_bytes = 1 <<< (type - 0x02) <<total_size::integer-unsigned-little-unit(8)-size(size_bytes), rest::binary>> = data data_size = byte_size(rest) rest = skip_zeros(rest) zeros = data_size - byte_size(rest) elem_size = value_size(rest) length = div(total_size - size_bytes - 1 - zeros, elem_size) parse_fixed_size_array_elements(length, elem_size, rest) end @spec parse_fixed_size_array_elements(integer(), integer(), binary()) :: {list(), binary()} defp parse_fixed_size_array_elements(0, _, data), do: {[], data} defp parse_fixed_size_array_elements(length, elem_size, data) do <<elem::binary-unit(8)-size(elem_size), rest::binary>> = data {elem, <<>>} = value(elem) {list, rest} = parse_fixed_size_array_elements(length - 1, elem_size, rest) {[elem | list], rest} end @spec parse_array_with_index_table(integer(), binary()) :: {list(), binary()} defp parse_array_with_index_table( 0x09, <<total_size::integer-unsigned-little-size(64), rest::binary>> ) do data_size = total_size - 1 - 8 - 8 <<data::binary-size(data_size), length::integer-unsigned-little-size(64), rest::binary>> = rest {parse_array_with_index_table_elements(length, 8, data), rest} end defp parse_array_with_index_table(type, data) do size_bytes = 1 <<< (type - 0x06) <<total_size::integer-unsigned-little-unit(8)-size(size_bytes), length::integer-unsigned-little-unit(8)-size(size_bytes), rest::binary>> = data data_size = total_size - 1 - 2 * size_bytes <<data::binary-size(data_size), rest::binary>> = rest data = skip_zeros(data) list = parse_array_with_index_table_elements(length, size_bytes, data) {list, rest} end @spec parse_array_with_index_table_elements(integer(), integer(), binary()) :: list() defp parse_array_with_index_table_elements(length, size_bytes, data) do index_table_size = if length == 1, do: 0, else: length * size_bytes {list, <<_index_table::binary-size(index_table_size)>>} = parse_variable_size_array_elements(length, data) list end @spec parse_compact_array(binary()) :: {list(), binary()} defp parse_compact_array(data) do {data, length, rest} = parse_compact_header(data) {list, <<>>} = parse_variable_size_array_elements(length, data) {list, rest} end # Yes, we totaly do this in a non-tail-recursive way. # Performance tests for large arrays (~10000 entries) showed # that this is ~10% faster than a tail-recursive version. @spec parse_variable_size_array_elements(integer(), binary()) :: {list(), binary()} defp parse_variable_size_array_elements(0, data), do: {[], data} defp parse_variable_size_array_elements(length, data) do {elem, rest} = value(data) {list, rest} = parse_variable_size_array_elements(length - 1, rest) {[elem | list], rest} end @spec parse_object(integer(), binary()) :: {map(), binary()} defp parse_object(type, data) do size_bytes = 1 <<< (type - 0x0B) <<total_size::integer-unsigned-little-unit(8)-size(size_bytes), length::integer-unsigned-little-unit(8)-size(size_bytes), rest::binary>> = data data_size = total_size - 1 - 2 * size_bytes <<data::binary-size(data_size), rest::binary>> = rest index_table_size = if length == 1, do: 0, else: length * size_bytes case parse_object_members(length, %{}, skip_zeros(data)) do {obj, <<_index_table::binary-size(index_table_size)>>} -> {obj, rest} {obj, <<3>>} -> {obj, rest} end end @spec parse_compact_object(binary()) :: {map(), binary()} defp parse_compact_object(data) do {data, length, rest} = parse_compact_header(data) {obj, <<>>} = parse_object_members(length, %{}, data) {obj, rest} end @spec parse_object_members(integer(), map(), binary()) :: {map(), binary()} defp parse_object_members(0, obj, data), do: {obj, data} defp parse_object_members(length, obj, data) do {key, rest} = value(data) {value, rest} = value(rest) obj = Map.put(obj, key, value) parse_object_members(length - 1, obj, rest) end @spec parse_compact_header(binary()) :: {binary(), integer(), binary()} defp parse_compact_header(data) do {size, rest} = parse_length(data, 0, 0, false) data_size = size - (byte_size(data) - byte_size(rest)) - 1 <<data::binary-size(data_size), rest::binary>> = rest {length, data} = parse_length(data, 0, 0, true) {data, length, rest} end @spec skip_zeros(binary()) :: binary() defp skip_zeros(<<0, rest::binary>>), do: skip_zeros(rest) defp skip_zeros(data), do: data @spec parse_length(binary(), integer(), integer(), boolean()) :: {integer(), binary()} defp parse_length(data, len, p, reverse) do {v, rest} = if reverse do size = byte_size(data) - 1 <<rest::binary-size(size), v>> = data {v, rest} else <<v, rest::binary>> = data {v, rest} end len = len + ((v &&& 0x7F) <<< p) p = p + 7 if (v &&& 0x80) != 0 do parse_length(rest, len, p, reverse) else {len, rest} end end end
lib/velocy/decoder.ex
0.514156
0.565239
decoder.ex
starcoder
defmodule Vnu.Assertions do @moduledoc "ExUnit assertions for checking the validity of HTML, CSS, and SVG documents." alias Vnu.{CLI, Formatter} @doc """ Asserts that the given HTML document is valid. ## Options - `:server_url` - The URL of [the Checker server](https://github.com/validator/validator). Defaults to `http://localhost:8888`. - `:fail_on_warnings` - Messages of type `:info` and subtype `:warning` will be treated as if they were validation errors. Their presence will mean the document is invalid. Defaults to `false`. - `:filter` - A module implementing the `Vnu.MessageFilter` behavior that will be used to exclude messages matching the filter from the result. Defaults to `nil` (no excluded messages). - `:http_client` - A module implementing the `Vnu.HTTPClient` behaviour that will be used to make the HTTP request to the server. Defaults to `Vnu.HTTPClient.Hackney`. - `:message_print_limit` - The maximum number of validation messages that will me printed in the error when the assertion fails. Can be an integer or `:infinity`. Defaults to `:infinity`. """ def assert_valid_html(html, opts \\ []) do assert_valid(html, :html, opts) end @doc """ Asserts that the given CSS document is valid. See `assert_valid_html/2` for the list of options and other details. """ def assert_valid_css(css, opts \\ []) do assert_valid(css, :css, opts) end @doc """ Asserts that the given SVG document is valid. See `assert_valid_html/2` for the list of options and other details. """ def assert_valid_svg(svg, opts \\ []) do assert_valid(svg, :svg, opts) end @doc false # credo:disable-for-next-line Credo.Check.Refactor.CyclomaticComplexity defp assert_valid(string, format, opts) do {validate_function, label} = CLI.format_to_function_and_pretty_name(format) case validate_function.(string, opts) do {:ok, result} -> if Vnu.valid?(result, opts) do string else fail_on_warnings? = Keyword.get(opts, :fail_on_warnings, false) message_print_limit = Keyword.get(opts, :message_print_limit, :infinity) grouped = Enum.group_by(result.messages, & &1.type) errors = Map.get(grouped, :error, []) infos = Map.get(grouped, :info, []) warnings = Enum.filter(infos, &(&1.sub_type == :warning)) error_count = Enum.count(errors) warning_count = Enum.count(warnings) counts = %{error_count: error_count, warning_count: warning_count, info_count: nil} format_count_opts = [ exclude_zeros: true, exclude_infos: true, with_colors: false ] {messages, expected_string} = if fail_on_warnings? do {errors ++ warnings, Formatter.format_counts(counts, format_count_opts)} else {errors, Formatter.format_counts( counts, Keyword.merge(format_count_opts, exclude_warnings: true) )} end {messages_to_be_printed, omitted_messages_number} = if message_print_limit != :infinity && message_print_limit < Enum.count(messages) do {Enum.take(Formatter.sort(messages), message_print_limit), Enum.count(messages) - message_print_limit} else {messages, 0} end messages_string = Formatter.format_messages(messages_to_be_printed) |> Enum.join("\n\n") error_message = """ Expected the #{label} document to be valid, but got #{expected_string} #{messages_string} """ error_message = if omitted_messages_number > 0 do error_message <> "\n...and #{omitted_messages_number} more.\n" else error_message end raise ExUnit.AssertionError, message: error_message end {:error, error} -> reason = case error.reason do :unexpected_server_response -> "an unexpected response from the server" :invalid_config -> "an invalid configuration" end raise ExUnit.AssertionError, message: """ Could not validate the #{label} document due to #{reason}: "#{error.message}" """ end end end
lib/vnu/assertions.ex
0.836103
0.628279
assertions.ex
starcoder
defmodule Macro.Env do @moduledoc """ A struct that holds compile time environment information. The current environment can be accessed at any time as `__ENV__/0`. Inside macros, the caller environment can be accessed as `__CALLER__/0`. An instance of `Macro.Env` must not be modified by hand. If you need to create a custom environment to pass to `Code.eval_quoted/3`, use the following trick: def make_custom_env do import SomeModule, only: [some_function: 2] alias A.B.C __ENV__ end You may then call `make_custom_env()` to get a struct with the desired imports and aliases included. It contains the following fields: * `context` - the context of the environment; it can be `nil` (default context), `:guard` (inside a guard) or `:match` (inside a match) * `context_modules` - a list of modules defined in the current context * `file` - the current file name as a binary * `function` - a tuple as `{atom, integer}`, where the first element is the function name and the second its arity; returns `nil` if not inside a function * `line` - the current line as an integer * `module` - the current module name The following fields are private to Elixir's macro expansion mechanism and must not be accessed directly: * `aliases` * `functions` * `macro_aliases` * `macros` * `lexical_tracker` * `requires` * `tracers` * `versioned_vars` """ @type context :: :match | :guard | nil @type context_modules :: [module] @type file :: binary @type line :: non_neg_integer @type name_arity :: {atom, arity} @type variable :: {atom, atom | term} @typep aliases :: [{module, module}] @typep functions :: [{module, [name_arity]}] @typep lexical_tracker :: pid | nil @typep macro_aliases :: [{module, {term, module}}] @typep macros :: [{module, [name_arity]}] @typep requires :: [module] @typep tracers :: [module] @typep versioned_vars :: %{optional(variable) => var_version :: non_neg_integer} @type t :: %{ __struct__: __MODULE__, aliases: aliases, context: context, context_modules: context_modules, file: file, function: name_arity | nil, functions: functions, lexical_tracker: lexical_tracker, line: line, macro_aliases: macro_aliases, macros: macros, module: module, requires: requires, tracers: tracers, versioned_vars: versioned_vars } # Define the __struct__ callbacks by hand for bootstrap reasons. @doc false def __struct__ do %{ __struct__: __MODULE__, aliases: [], context: nil, context_modules: [], file: "nofile", function: nil, functions: [], lexical_tracker: nil, line: 0, macro_aliases: [], macros: [], module: nil, requires: [], tracers: [], versioned_vars: %{} } end @doc false def __struct__(kv) do Enum.reduce(kv, __struct__(), fn {k, v}, acc -> :maps.update(k, v, acc) end) end @doc """ Prunes compile information from the environment. This happens when the environment is captured at compilation time, for example, in the module body, and then used to evaluate code after the module has been defined. """ @doc since: "1.14.0" @spec prune_compile_info(t) :: t def prune_compile_info(env) do %{env | lexical_tracker: nil, tracers: []} end @doc """ Returns a list of variables in the current environment. Each variable is identified by a tuple of two elements, where the first element is the variable name as an atom and the second element is its context, which may be an atom or an integer. """ @doc since: "1.7.0" @spec vars(t) :: [variable] def vars(env) def vars(%{__struct__: Macro.Env, versioned_vars: vars}) do Map.keys(vars) end @doc """ Checks if a variable belongs to the environment. ## Examples iex> x = 13 iex> x 13 iex> Macro.Env.has_var?(__ENV__, {:x, nil}) true iex> Macro.Env.has_var?(__ENV__, {:unknown, nil}) false """ @doc since: "1.7.0" @spec has_var?(t, variable) :: boolean() def has_var?(env, var) def has_var?(%{__struct__: Macro.Env, versioned_vars: vars}, var) do Map.has_key?(vars, var) end @doc """ Returns a keyword list containing the file and line information as keys. """ @spec location(t) :: keyword def location(env) def location(%{__struct__: Macro.Env, file: file, line: line}) do [file: file, line: line] end @doc """ Fetches the alias for the given atom. Returns `{:ok, alias}` if the alias exists, `:error` otherwise. ## Examples iex> alias Foo.Bar, as: Baz iex> Baz Foo.Bar iex> Macro.Env.fetch_alias(__ENV__, :Baz) {:ok, Foo.Bar} iex> Macro.Env.fetch_alias(__ENV__, :Unknown) :error """ @doc since: "1.13.0" @spec fetch_alias(t, atom) :: {:ok, atom} | :error def fetch_alias(%{__struct__: Macro.Env, aliases: aliases}, atom) when is_atom(atom), do: Keyword.fetch(aliases, :"Elixir.#{atom}") @doc """ Fetches the macro alias for the given atom. Returns `{:ok, macro_alias}` if the alias exists, `:error` otherwise. A macro alias is only used inside quoted expansion. See `fetch_alias/2` for a more general example. """ @doc since: "1.13.0" @spec fetch_macro_alias(t, atom) :: {:ok, atom} | :error def fetch_macro_alias(%{__struct__: Macro.Env, macro_aliases: aliases}, atom) when is_atom(atom), do: Keyword.fetch(aliases, :"Elixir.#{atom}") @doc """ Returns the modules from which the given `{name, arity}` was imported. It returns a list of two element tuples in the shape of `{:function | :macro, module}`. The elements in the list are in no particular order and the order is not guaranteed. ## Examples iex> Macro.Env.lookup_import(__ENV__, {:duplicate, 2}) [] iex> import Tuple, only: [duplicate: 2], warn: false iex> Macro.Env.lookup_import(__ENV__, {:duplicate, 2}) [{:function, Tuple}] iex> import List, only: [duplicate: 2], warn: false iex> Macro.Env.lookup_import(__ENV__, {:duplicate, 2}) [{:function, List}, {:function, Tuple}] iex> Macro.Env.lookup_import(__ENV__, {:def, 1}) [{:macro, Kernel}] """ @doc since: "1.13.0" @spec lookup_import(t, name_arity) :: [{:function | :macro, module}] def lookup_import( %{__struct__: Macro.Env, functions: functions, macros: macros}, {name, arity} = pair ) when is_atom(name) and is_integer(arity) do f = for {mod, pairs} <- functions, :ordsets.is_element(pair, pairs), do: {:function, mod} m = for {mod, pairs} <- macros, :ordsets.is_element(pair, pairs), do: {:macro, mod} f ++ m end @doc """ Returns true if the given module has been required. ## Examples iex> Macro.Env.required?(__ENV__, Integer) false iex> require Integer iex> Macro.Env.required?(__ENV__, Integer) true iex> Macro.Env.required?(__ENV__, Kernel) true """ @doc since: "1.13.0" @spec required?(t, module) :: boolean def required?(%{__struct__: Macro.Env, requires: requires}, mod) when is_atom(mod), do: mod in requires @doc """ Prepend a tracer to the list of tracers in the environment. ## Examples Macro.Env.prepend_tracer(__ENV__, MyCustomTracer) """ @doc since: "1.13.0" @spec prepend_tracer(t, module) :: t def prepend_tracer(%{__struct__: Macro.Env, tracers: tracers} = env, tracer) do %{env | tracers: [tracer | tracers]} end @doc """ Returns a `Macro.Env` in the match context. """ @spec to_match(t) :: t def to_match(%{__struct__: Macro.Env} = env) do %{env | context: :match} end @doc """ Returns whether the compilation environment is currently inside a guard. """ @spec in_guard?(t) :: boolean def in_guard?(env) def in_guard?(%{__struct__: Macro.Env, context: context}), do: context == :guard @doc """ Returns whether the compilation environment is currently inside a match clause. """ @spec in_match?(t) :: boolean def in_match?(env) def in_match?(%{__struct__: Macro.Env, context: context}), do: context == :match @doc """ Returns the environment stacktrace. """ @spec stacktrace(t) :: list def stacktrace(%{__struct__: Macro.Env} = env) do cond do is_nil(env.module) -> [{:elixir_compiler, :__FILE__, 1, relative_location(env)}] is_nil(env.function) -> [{env.module, :__MODULE__, 0, relative_location(env)}] true -> {name, arity} = env.function [{env.module, name, arity, relative_location(env)}] end end defp relative_location(env) do [file: String.to_charlist(Path.relative_to_cwd(env.file)), line: env.line] end end
lib/elixir/lib/macro/env.ex
0.916016
0.464902
env.ex
starcoder
defmodule Tzdata do @moduledoc """ The Tzdata module provides data from the IANA tz database. Also known as the Olson/Eggert database, zoneinfo, tzdata and other names. A list of time zone names (e.g. `America/Los_Angeles`) are provided. As well as functions for finding out the UTC offset, abbreviation, standard offset (DST) for a specific point in time in a certain timezone. """ @doc """ zone_list provides a list of all the zone names that can be used with DateTime. This includes aliases. """ def zone_list, do: Tzdata.ReleaseReader.zone_and_link_list @doc """ Like zone_list, but excludes aliases for zones. """ def canonical_zone_list, do: Tzdata.ReleaseReader.zone_list @doc """ A list of aliases for zone names. For instance Europe/Jersey is an alias for Europe/London. Aliases are also known as linked zones. """ def zone_alias_list, do: Tzdata.ReleaseReader.link_list @doc """ Takes the name of a zone. Returns true if zone exists. Otherwise false. iex> Tzdata.zone_exists? "Pacific/Auckland" true iex> Tzdata.zone_exists? "America/Sao_Paulo" true iex> Tzdata.zone_exists? "Europe/Jersey" true """ def zone_exists?(name), do: Enum.member?(zone_list(), name) @doc """ Takes the name of a zone. Returns true if zone exists and is canonical. Otherwise false. iex> Tzdata.canonical_zone? "Europe/London" true iex> Tzdata.canonical_zone? "Europe/Jersey" false """ def canonical_zone?(name), do: Enum.member?(canonical_zone_list(), name) @doc """ Takes the name of a zone. Returns true if zone exists and is an alias. Otherwise false. iex> Tzdata.zone_alias? "Europe/Jersey" true iex> Tzdata.zone_alias? "Europe/London" false """ def zone_alias?(name), do: Enum.member?(zone_alias_list(), name) @doc """ Returns a map of links. Also known as aliases. iex> Tzdata.links["Europe/Jersey"] "Europe/London" """ def links, do: Tzdata.ReleaseReader.links @doc """ Returns a map with keys being group names and the values lists of time zone names. The group names mirror the file names used by the tzinfo database. """ def zone_lists_grouped, do: Tzdata.ReleaseReader.by_group @doc """ Returns tzdata release version as a string. Example: Tzdata.tzdata_version "2014i" """ def tzdata_version, do: Tzdata.ReleaseReader.release_version @doc """ Returns a list of periods for the `zone_name` provided as an argument. A period in this case is a period of time where the UTC offset and standard offset are in a certain way. When they change, for instance in spring when DST takes effect, a new period starts. For instance a period can begin in spring when winter time ends and summer time begins. The period lasts until DST ends. If either the UTC or standard offset change for any reason, a new period begins. For instance instead of DST ending or beginning, a rule change that changes the UTC offset will also mean a new period. The result is tagged with :ok if the zone_name is correct. The from and until times can be :mix, :max or gregorian seconds. ## Example iex> Tzdata.periods("Europe/Madrid") |> elem(1) |> Enum.take(1) [%{from: %{standard: :min, utc: :min, wall: :min}, std_off: 0, until: %{standard: 59989763760, utc: 59989764644, wall: 59989763760}, utc_off: -884, zone_abbr: "LMT"}] iex> Tzdata.periods("Not existing") {:error, :not_found} """ def periods(zone_name) do {tag, p} = Tzdata.ReleaseReader.periods_for_zone_or_link(zone_name) case tag do :ok -> mapped_p = for {_, f_utc, f_wall, f_std, u_utc, u_wall, u_std, utc_off, std_off, zone_abbr} <- p do %{ std_off: std_off, utc_off: utc_off, from: %{utc: f_utc, wall: f_wall, standard: f_std}, until: %{utc: u_utc, standard: u_std, wall: u_wall}, zone_abbr: zone_abbr } end {:ok, mapped_p} _ -> {:error, p} end end @doc """ Get the periods that cover a certain point in time. Usually it will be a list with just one period. But in some cases it will be zero or two periods. For instance when going from summer to winter time (DST to standard time) there will be an overlap if `time_type` is `:wall`. `zone_name` should be a valid time zone name. The function `zone_list/0` provides a valid list of valid zone names. `time_point` is the point in time in gregorian seconds (see erlang calendar module documentation for more info on gregorian seconds). Valid values for `time_type` is `:utc`, `:wall` or `:standard`. ## Examples # 63555753600 seconds is equivalent to {{2015, 1, 1}, {0, 0, 0}} iex> Tzdata.periods_for_time("Asia/Tokyo", 63587289600, :wall) [%{from: %{standard: 61589286000, utc: 61589253600, wall: 61589286000}, std_off: 0, until: %{standard: :max, utc: :max, wall: :max}, utc_off: 32400, zone_abbr: "JST"}] # 63612960000 seconds is equivalent to 2015-10-25 02:40:00 and is an ambiguous # wall time for the zone. So two possible periods will be returned. iex> Tzdata.periods_for_time("Europe/Copenhagen", 63612960000, :wall) [%{from: %{standard: 63594813600, utc: 63594810000, wall: 63594817200}, std_off: 3600, until: %{standard: 63612957600, utc: 63612954000, wall: 63612961200}, utc_off: 3600, zone_abbr: "CEST"}, %{from: %{standard: 63612957600, utc: 63612954000, wall: 63612957600}, std_off: 0, until: %{standard: 63626263200, utc: 63626259600, wall: 63626263200}, utc_off: 3600, zone_abbr: "CET"}] # 63594816000 seconds is equivalent to 2015-03-29 02:40:00 and is a # non-existing wall time for the zone. It is spring and the clock skips that hour. iex> Tzdata.periods_for_time("Europe/Copenhagen", 63594816000, :wall) [] """ def periods_for_time(zone_name, time_point, time_type) do {:ok, periods} = possible_periods_for_zone_and_time(zone_name, time_point) match_fn = fn %{from: from, until: until} -> smaller_than_or_equals(Map.get(from, time_type), time_point) && bigger_than(Map.get(until, time_type), time_point) end do_consecutive_matching(periods, match_fn, [], false) end # Like Enum.filter, but returns the first consecutive result. # If we have found consecutive matches we do not need to look at the # remaining list. defp do_consecutive_matching([], _fun, [], _did_last_match), do: [] defp do_consecutive_matching([], _fun, matched, _did_last_match), do: matched defp do_consecutive_matching(_list, _fun, matched, false) when matched != [] do # If there are matches and previous did not match then the matches are no # long consecutive. So we return the result. matched |> Enum.reverse end defp do_consecutive_matching([h|t], fun, matched, _did_last_match) do if fun.(h) == true do do_consecutive_matching(t, fun, [h|matched], true) else do_consecutive_matching(t, fun, matched, false) end end # Use dynamic periods for points in time that are about 40 years into the future @years_in_the_future_where_precompiled_periods_are_used 40 @point_from_which_to_use_dynamic_periods :calendar.datetime_to_gregorian_seconds {{(:calendar.universal_time|>elem(0)|>elem(0)) + @years_in_the_future_where_precompiled_periods_are_used, 1, 1}, {0, 0, 0}} defp possible_periods_for_zone_and_time(zone_name, time_point) when time_point >= @point_from_which_to_use_dynamic_periods do if Tzdata.FarFutureDynamicPeriods.zone_in_30_years_in_eternal_period?(zone_name) do periods(zone_name) else link_status = Tzdata.ReleaseReader.links |> Map.get(zone_name) if link_status == nil do Tzdata.FarFutureDynamicPeriods.periods_for_point_in_time(time_point, zone_name) else possible_periods_for_zone_and_time(link_status, time_point) end end end defp possible_periods_for_zone_and_time(zone_name, _time_point) do periods(zone_name) end @doc """ Get a list of maps with known leap seconds and the difference between UTC and the TAI in seconds. See also `leap_seconds/1` ## Example iex> Tzdata.leap_seconds_with_tai_diff |> Enum.take(3) [%{date_time: {{1971, 12, 31}, {23, 59, 60}}, tai_diff: 10}, %{date_time: {{1972, 6, 30}, {23, 59, 60}}, tai_diff: 11}, %{date_time: {{1972, 12, 31}, {23, 59, 60}}, tai_diff: 12}] """ def leap_seconds_with_tai_diff do leap_seconds_data = Tzdata.ReleaseReader.leap_sec_data leap_seconds_data.leap_seconds end @doc """ Get a list of known leap seconds. The leap seconds are datetime tuples representing the extra leap second to be inserted. The date-times are in UTC. See also `leap_seconds_with_tai_diff/1` ## Example iex> Tzdata.leap_seconds |> Enum.take(3) [{{1971, 12, 31}, {23, 59, 60}}, {{1972, 6, 30}, {23, 59, 60}}, {{1972, 12, 31}, {23, 59, 60}}] """ def leap_seconds do for %{date_time: date_time} <- leap_seconds_with_tai_diff() do date_time end end @doc """ The time when the leap second information returned from the other leap second related function expires. The date-time is in UTC. ## Example Tzdata.leap_second_data_valid_until {{2015, 12, 28}, {0, 0, 0}} """ def leap_second_data_valid_until do leap_seconds_data = Tzdata.ReleaseReader.leap_sec_data leap_seconds_data.valid_until end defp smaller_than_or_equals(:min, _), do: true defp smaller_than_or_equals(first, second), do: first <= second defp bigger_than(:max, _), do: true defp bigger_than(first, second), do: first > second end
deps/tzdata/lib/tzdata.ex
0.900729
0.441372
tzdata.ex
starcoder
defmodule Ockam.Wire do @moduledoc """ Encodes and decodes messages that can be transported on the wire. """ alias Ockam.Address alias Ockam.Message alias Ockam.Wire.DecodeError alias Ockam.Wire.EncodeError require DecodeError require EncodeError @default_implementation Ockam.Wire.Binary.V1 @doc """ Encodes a message into a binary. Returns `{:ok, iodata}`, if it succeeds. Returns `{:error, error}`, if it fails. """ @callback encode(message :: Message.t()) :: {:ok, encoded :: iodata} | {:error, error :: EncodeError.t()} @doc """ Encodes a route into a binary. Returns `{:ok, iodata}`, if it succeeds. Returns `{:error, error}`, if it fails. """ @callback encode_route(route :: Address.route()) :: {:ok, encoded :: iodata} | {:error, error :: EncodeError.t()} @doc """ Encodes an address into a binary. Returns `{:ok, iodata}`, if it succeeds. Returns `{:error, error}`, if it fails. """ @callback encode_address(address :: Address.t()) :: {:ok, encoded :: iodata} | {:error, error :: EncodeError.t()} @doc """ Decodes a message from a binary. Returns `{:ok, message}`, if it succeeds. Returns `{:error, error}`, if it fails. """ @callback decode(encoded :: binary()) :: {:ok, message :: Message.t()} | {:error, error :: DecodeError.t()} @doc """ Decodes a route from a binary. Returns `{:ok, message}`, if it succeeds. Returns `{:error, error}`, if it fails. """ @callback decode_route(encoded :: binary()) :: {:ok, route :: Address.route()} | {:error, error :: DecodeError.t()} @doc """ Decodes an address from a binary. Returns `{:ok, message}`, if it succeeds. Returns `{:error, error}`, if it fails. """ @callback decode_address(encoded :: binary()) :: {:ok, address :: Address.t()} | {:error, error :: DecodeError.t()} @doc """ Encode a message to a binary using the provided encoder. """ @spec encode(encoder :: atom, message :: Message.t()) :: {:ok, encoded :: iodata} | {:error, error :: EncodeError.t()} def encode(encoder \\ nil, message) do with_implementation(encoder, :encode, [message]) end @doc """ Encode a route to a binary using the provided encoder. """ @spec encode_route(encoder :: atom, route :: Address.route()) :: {:ok, encoded :: iodata} | {:error, error :: EncodeError.t()} def encode_route(encoder \\ nil, route) do with_implementation(encoder, :encode_route, [route]) end @doc """ Encode an address to a binary using the provided encoder. """ @spec encode_address(encoder :: atom, message :: Address.t()) :: {:ok, encoded :: iodata} | {:error, error :: EncodeError.t()} def encode_address(encoder \\ nil, address) do with_implementation(encoder, :encode_address, [address]) end @doc """ Decode a message from binary using the provided decoder. """ @spec decode(decoder :: atom, encoded :: binary) :: {:ok, message :: Message.t()} | {:error, error :: DecodeError.t()} def decode(decoder \\ nil, encoded) def decode(decoder, encoded) when is_binary(encoded) do with_implementation(decoder, :decode, [encoded]) end def decode(_decoder, encoded) do {:error, error(:decode, {:encoded_input_is_not_binary, encoded})} end @doc """ Decode a route from binary using the provided decoder. """ @spec decode_route(decoder :: atom, encoded :: binary) :: {:ok, route :: Address.route()} | {:error, error :: DecodeError.t()} def decode_route(decoder \\ nil, encoded) def decode_route(decoder, encoded) when is_binary(encoded) do with_implementation(decoder, :decode_route, [encoded]) end def decode_route(_decoder, encoded) do {:error, error(:decode_route, {:encoded_input_is_not_binary, encoded})} end @doc """ Decode an address from binary using the provided decoder. """ @spec decode_address(decoder :: atom, encoded :: binary) :: {:ok, address :: Address.t()} | {:error, error :: DecodeError.t()} def decode_address(decoder \\ nil, encoded) def decode_address(decoder, encoded) when is_binary(encoded) do with_implementation(decoder, :decode_address, [encoded]) end def decode_address(_decoder, encoded) do {:error, error(:decode_address, {:encoded_input_is_not_binary, encoded})} end def with_implementation(nil, fun_name, args) do case default_implementation() do nil -> error(fun_name, :no_default_implementation) module when is_atom(module) -> with :ok <- ensure_loaded(fun_name, module), :ok <- ensure_exported(module, fun_name, Enum.count(args)) do apply(module, fun_name, args) else {:error, reason} -> error(fun_name, reason) end other -> error(fun_name, {:implementation_is_not_a_module, other}) end end def error(:encode, reason) do {:error, EncodeError.new(reason)} end def error(:encode_route, reason) do {:error, EncodeError.new(reason)} end def error(:encode_address, reason) do {:error, EncodeError.new(reason)} end def error(:decode, reason) do {:error, DecodeError.new(reason)} end def error(:decode_route, reason) do {:error, DecodeError.new(reason)} end def error(:decode_address, reason) do {:error, DecodeError.new(reason)} end # returns :ok if module is loaded, {:error, reason} otherwise defp ensure_loaded(type, module) do case Code.ensure_loaded?(module) do true -> :ok false -> {:error, {:module_not_loaded, {type, module}}} end end # returns :ok if a module exports the given function, {:error, reason} otherwise defp ensure_exported(module, function, arity) do case function_exported?(module, function, arity) do true -> :ok false -> {:error, {:module_does_not_export, {module, function, arity}}} end end defp default_implementation do module_config = Application.get_env(:ockam, __MODULE__, []) Keyword.get(module_config, :default, @default_implementation) end def format_error(%DecodeError{reason: :decoder_is_nil_and_no_default_decoder}), do: "Decoder argument is nil and there is no default decoder configured." def format_error(%DecodeError{reason: {:decoder_is_not_a_module, decoder}}), do: "Decoder argument is not a module: #{inspect(decoder)}" def format_error(%DecodeError{reason: {:encoded_input_is_not_binary, encoded}}), do: "Encoded input cannot be decoded as it is not a binary: #{inspect(encoded)}" def format_error(%DecodeError{reason: {:module_not_loaded, {:decoder, module}}}), do: "Decoder module is not loaded: #{inspect(module)}" def format_error(%DecodeError{reason: {:module_does_not_export, {module, :decode, 1}}}), do: "Decoder module does not export: #{inspect(module)}.decode/1" def format_error(%EncodeError{reason: :encoder_is_nil_and_no_default_encoder}), do: "Encoder argument is nil and there is no default encoder configured." def format_error(%EncodeError{reason: {:encoder_is_not_a_module, encoder}}), do: "Encoder argument is not a module: #{inspect(encoder)}" def format_error(%EncodeError{reason: {:module_not_loaded, {:encoder, module}}}), do: "Encoder module is not loaded: #{inspect(module)}" def format_error(%EncodeError{reason: {:module_does_not_export, {module, :encode, 1}}}), do: "Encoder module does not export: #{inspect(module)}.encode/1" def format_error(%DecodeError{reason: {:too_much_data, encoded, rest}}), do: "Too much data in #{inspect(encoded)} ; extra data: #{inspect(rest)}" def format_error(%DecodeError{reason: {:not_enough_data, data}}), do: "Not enough data in #{inspect(data)}" def format_error(%DecodeError{reason: {:invalid_version, data, version}}), do: "Unknown message format or version: #{inspect(version)} #{inspect(data)}" def format_error(%{reason: reason}), do: inspect(reason) end
implementations/elixir/ockam/ockam/lib/ockam/wire.ex
0.936416
0.451871
wire.ex
starcoder
defmodule ShopifexWeb.PaymentController do @moduledoc """ You can use this module inside of another controller to handle initial iFrame load and shop installation Example: mix phx.gen.html Shops Plan plans name:string price:string features:array grants:array test:boolean mix phx.gen.html Shops Grant grants shop:references:shops charge_id:integer grants:array ```elixir defmodule MyAppWeb.PaymentController do use MyAppWeb, :controller use ShopifexWeb.PaymentController # Thats it! You can now configure your purchasable products :) end ``` """ @doc """ An optional callback called after a payment is completed. By default, this function redirects the user to the app index within their Shopify admin panel. ## Example def after_payment(conn, shop, plan, grant, redirect_after) do # send yourself an e-mail about payment # follow default behaviour. super(conn, shop, plan, grant, redirect_after) end """ @callback after_payment( Plug.Conn.t(), Ecto.Schema.t(), Ecto.Schema.t(), Ecto.Schema.t(), String.t() ) :: Plug.Conn.t() @optional_callbacks after_payment: 5 defmacro __using__(_opts) do quote do @behaviour ShopifexWeb.PaymentController require Logger def show_plans(conn, params) do payment_guard = Application.fetch_env!(:shopifex, :payment_guard) path_prefix = Application.get_env(:shopifex, :path_prefix, "") default_redirect_after = path_prefix <> "/?token=" <> Guardian.Plug.current_token(conn) payment_guard.show_plans( conn, Map.get(params, "guard_identifier"), Map.get(params, "redirect_after", default_redirect_after) ) end def select_plan(conn, %{"plan_id" => plan_id, "redirect_after" => redirect_after}) do payment_guard = Application.fetch_env!(:shopifex, :payment_guard) redirect_after_agent = Application.get_env(:shopifex, :redirect_after_agent, Shopifex.RedirectAfterAgent) plan = payment_guard.get_plan(plan_id) shop = case conn.private do %{shop: shop} -> shop %{guardian_default_resource: shop} -> shop end {:ok, charge} = create_charge(shop, plan) redirect_after_agent.set(charge["id"], redirect_after) send_resp(conn, 200, Jason.encode!(charge)) end # annual billing is only possible w/ the GraphQL API defp create_charge(shop, plan = %{type: "recurring_application_charge", annual: true}) do redirect_uri = Application.get_env(:shopifex, :payment_redirect_uri) case Neuron.query( """ mutation appSubscriptionCreate($name: String!, $return_url: URL!, $test: Boolean!, $price: Decimal!) { appSubscriptionCreate(name: $name, returnUrl: $return_url, test: $test, lineItems: [{plan: {appRecurringPricingDetails: {price: {amount: $price, currencyCode: USD}, interval: ANNUAL}}}]) { appSubscription { id } confirmationUrl userErrors { field message } } } """, %{ name: plan.name, price: plan.price, test: plan.test, return_url: "#{redirect_uri}?plan_id=#{plan.id}&shop=#{shop.url}" }, url: "https://#{shop.url}/admin/api/2021-04/graphql.json", headers: [ "X-Shopify-Access-Token": shop.access_token, "Content-Type": "application/json" ] ) do {:ok, %Neuron.Response{body: body}} -> app_subscription_create = body["data"]["appSubscriptionCreate"] # id comes back in this format: "gid://shopify/AppSubscription/4019552312" <<_::binary-size(30)>> <> id = app_subscription_create["appSubscription"]["id"] confirmation_url = app_subscription_create["confirmationUrl"] {:ok, %{"id" => id, "confirmation_url" => confirmation_url}} end end defp create_charge(shop, plan = %{type: "recurring_application_charge"}) do redirect_uri = Application.get_env(:shopifex, :payment_redirect_uri) body = Jason.encode!(%{ recurring_application_charge: %{ name: plan.name, price: plan.price, test: plan.test, return_url: "#{redirect_uri}?plan_id=#{plan.id}&shop=#{shop.url}" } }) case HTTPoison.post( "https://#{shop.url}/admin/api/2021-01/recurring_application_charges.json", body, "X-Shopify-Access-Token": shop.access_token, "Content-Type": "application/json" ) do {:ok, resp} -> {:ok, Jason.decode!(resp.body)["recurring_application_charge"]} end end defp create_charge(shop, plan = %{type: "application_charge"}) do redirect_uri = Application.get_env(:shopifex, :payment_redirect_uri) body = Jason.encode!(%{ application_charge: %{ name: plan.name, price: plan.price, test: plan.test, return_url: "#{redirect_uri}?plan_id=#{plan.id}&shop=#{shop.url}" } }) case HTTPoison.post( "https://#{shop.url}/admin/api/2021-01/application_charges.json", body, "X-Shopify-Access-Token": shop.access_token, "Content-Type": "application/json" ) do {:ok, resp} -> {:ok, Jason.decode!(resp.body)["application_charge"]} end end def complete_payment(conn, %{ "charge_id" => charge_id, "plan_id" => plan_id, "shop" => shop_url }) do redirect_after_agent = Application.get_env(:shopifex, :redirect_after_agent, Shopifex.RedirectAfterAgent) # Shopify's API doesn't provide an HMAC validation on # this return-url. Use the token param in the redirect_after # url that is associated with this charge_id to validate # the request and get the current shop with redirect_after when redirect_after != nil <- redirect_after_agent.get(charge_id), redirect_after <- URI.decode_www_form(redirect_after), shop when not is_nil(shop) <- Shopifex.Shops.get_shop_by_url(shop_url) do payment_guard = Application.fetch_env!(:shopifex, :payment_guard) plan = payment_guard.get_plan(plan_id) {:ok, grant} = payment_guard.create_grant(shop, plan, charge_id) after_payment(conn, shop, plan, grant, redirect_after) else _ -> {:error, :forbidden} end end @impl ShopifexWeb.PaymentController def after_payment(conn, shop, _plan, _grant, redirect_after) do api_key = Application.get_env(:shopifex, :api_key) redirect(conn, external: "https://#{shop.url}/admin/apps/#{api_key}#{redirect_after}") end defoverridable after_payment: 5 end end end
lib/shopifex_web/controllers/payment_controller.ex
0.745954
0.44059
payment_controller.ex
starcoder
defmodule VintageNet.InterfacesMonitor.Info do @moduledoc false alias VintageNet.{IP, PropertyTable} @link_if_properties [:lower_up, :mac_address] @address_if_properties [:addresses] @all_if_properties [:present] ++ @link_if_properties ++ @address_if_properties defstruct ifname: nil, link: %{}, addresses: [] @type t() :: %__MODULE__{ifname: VintageNet.ifname(), link: map(), addresses: [map()]} @doc """ Create a new struct for caching interface notifications """ @spec new(VintageNet.ifname()) :: t() def new(ifname) do %__MODULE__{ifname: ifname} end @doc """ Add/replace an address report to the interface info Link reports have the form: ```elixir %{ broadcast: true, lower_up: true, mac_address: "70:85:c2:8f:98:e1", mac_broadcast: "ff:ff:ff:ff:ff:ff", mtu: 1500, multicast: true, operstate: :down, running: false, stats: %{ collisions: 0, multicast: 0, rx_bytes: 0, rx_dropped: 0, rx_errors: 0, rx_packets: 0, tx_bytes: 0, tx_dropped: 0, tx_errors: 0, tx_packets: 0 }, type: :ethernet, up: true } ``` """ @spec newlink(t(), map()) :: t() def newlink(info, link_report) do %{info | link: link_report} end @doc """ Add/replace an address report to the interface info Address reports have the form: ```elixir %{ address: {192, 168, 10, 10}, broadcast: {192, 168, 10, 255}, family: :inet, label: "eth0", local: {192, 168, 10, 10}, permanent: false, prefixlen: 24, scope: :universe } ``` """ @spec newaddr(t(), map()) :: t() def newaddr(info, address_report) do info = deladdr(info, address_report) new_addresses = [address_report | info.addresses] %{info | addresses: new_addresses} end @doc """ Remove and address from the interface info """ @spec deladdr(t(), map()) :: t() def deladdr(info, address_report) do new_addresses = info.addresses |> Enum.filter(fn entry -> entry.address != address_report.address end) %{info | addresses: new_addresses} end @doc """ Clear out all properties exported by this module """ @spec clear_properties(VintageNet.ifname()) :: :ok def clear_properties(ifname) do Enum.each(@all_if_properties, fn property -> PropertyTable.clear(VintageNet, ["interface", ifname, to_string(property)]) end) end @doc """ Report that the interface is present """ @spec update_present(t()) :: t() def update_present(%__MODULE__{ifname: ifname} = info) do PropertyTable.put(VintageNet, ["interface", ifname, "present"], true) info end @doc """ Update link-specific properties """ @spec update_link_properties(t()) :: t() def update_link_properties(%__MODULE__{ifname: ifname, link: link_report} = info) do Enum.each(@link_if_properties, fn property -> update_link_property(ifname, property, Map.get(link_report, property)) end) info end defp update_link_property(ifname, property, nil) do PropertyTable.clear(VintageNet, ["interface", ifname, to_string(property)]) end defp update_link_property(ifname, property, value) do PropertyTable.put(VintageNet, ["interface", ifname, to_string(property)], value) end @doc """ Update address-specific properties """ @spec update_address_properties(t()) :: t() def update_address_properties(%__MODULE__{ifname: ifname, addresses: address_reports} = info) do addresses = address_reports_to_property(address_reports) PropertyTable.put(VintageNet, ["interface", ifname, "addresses"], addresses) info end defp address_reports_to_property(address_reports) do for report <- address_reports do %{ family: report.family, scope: report.scope, address: report.address, prefix_length: report.prefixlen, netmask: IP.prefix_length_to_subnet_mask(report.family, report.prefixlen) } end end end
lib/vintage_net/interfaces_monitor/info.ex
0.788502
0.677714
info.ex
starcoder
defmodule Absinthe.Subscription do @moduledoc """ Real time updates via GraphQL For a how to guide on getting started with Absinthe.Subscriptions in your phoenix project see the Absinthe.Phoenix package. Define in your schema via `Absinthe.Schema.subscription/2` ## Basic Usage ## Performance Characteristics There are a couple of limitations to the beta release of subscriptions that are worth keeping in mind if you want to use this in production: By design, all subscription docs triggered by a mutation are run inside the mutation process as a form of back pressure. At the moment however database batching does not happen across the set of subscription docs. Thus if you have a lot of subscription docs and they each do a lot of extra DB lookups you're going to delay incoming mutation responses by however long it takes to do all that work. Before the final version of 1.4.0 we want - Batching across subscriptions - More user control over back pressure / async balance. """ require Logger alias __MODULE__ @doc """ Add Absinthe.Subscription to your process tree. """ defdelegate start_link(pubsub), to: Subscription.Supervisor def child_spec(pubsub) do %{ id: __MODULE__, start: {Subscription.Supervisor, :start_link, [pubsub]}, type: :supervisor } end @type subscription_field_spec :: {atom, term | (term -> term)} @doc """ Publish a mutation This function is generally used when trying to publish to one or more subscription fields "out of band" from any particular mutation. ## Examples Note: As with all subscription examples if you're using Absinthe.Phoenix `pubsub` will be `MyAppWeb.Endpoint`. ``` Absinthe.Subscription.publish(pubsub, user, [new_users: user.account_id]) ``` ``` # publish to two subscription fields Absinthe.Subscription.publish(pubsub, user, [ new_users: user.account_id, other_user_subscription_field: user.id, ]) ``` """ @spec publish( Absinthe.Subscription.Pubsub.t(), term, Absinthe.Resolution.t() | [subscription_field_spec] ) :: :ok def publish(pubsub, mutation_result, %Absinthe.Resolution{} = info) do subscribed_fields = get_subscription_fields(info) publish(pubsub, mutation_result, subscribed_fields) end def publish(pubsub, mutation_result, subscribed_fields) do _ = publish_remote(pubsub, mutation_result, subscribed_fields) _ = Subscription.Local.publish_mutation(pubsub, mutation_result, subscribed_fields) :ok end defp get_subscription_fields(resolution_info) do mutation_field = resolution_info.definition.schema_node schema = resolution_info.schema subscription = Absinthe.Schema.lookup_type(schema, :subscription) || %{fields: []} subscription_fields = fetch_fields(subscription.fields, mutation_field.triggers) for {sub_field_id, sub_field} <- subscription_fields do triggers = Absinthe.Type.function(sub_field, :triggers) config = Map.fetch!(triggers, mutation_field.identifier) {sub_field_id, config} end end # TODO: normalize the `.fields` type. defp fetch_fields(fields, triggers) when is_map(fields) do Map.take(fields, triggers) end defp fetch_fields(_, _), do: [] @doc false def subscribe(pubsub, field_key, doc_id, doc) do registry = pubsub |> registry_name {:ok, _} = Registry.register(registry, field_key, {doc_id, doc}) {:ok, _} = Registry.register(registry, {self(), doc_id}, field_key) end @doc false def unsubscribe(pubsub, doc_id) do registry = pubsub |> registry_name self = self() for {^self, field_key} <- Registry.lookup(registry, {self, doc_id}) do Registry.unregister_match(registry, field_key, {doc_id, :_}) end Registry.unregister(registry, {self, doc_id}) :ok end @doc false def get(pubsub, key) do pubsub |> registry_name |> Registry.lookup(key) |> Enum.map(&elem(&1, 1)) |> Map.new() end @doc false def registry_name(pubsub) do Module.concat([pubsub, :Registry]) end @doc false def publish_remote(pubsub, mutation_result, subscribed_fields) do {:ok, pool_size} = pubsub |> registry_name |> Registry.meta(:pool_size) shard = :erlang.phash2(mutation_result, pool_size) proxy_topic = Subscription.Proxy.topic(shard) :ok = pubsub.publish_mutation(proxy_topic, mutation_result, subscribed_fields) end ## Middleware callback @doc false def call(%{state: :resolved, errors: [], value: value} = res, _) do with {:ok, pubsub} <- extract_pubsub(res.context) do __MODULE__.publish(pubsub, value, res) end res end def call(res, _), do: res @doc false def extract_pubsub(context) do with {:ok, pubsub} <- Map.fetch(context, :pubsub), pid when is_pid(pid) <- Process.whereis(registry_name(pubsub)) do {:ok, pubsub} else _ -> :error end end @doc false def add_middleware(middleware) do middleware ++ [{__MODULE__, []}] end end
lib/absinthe/subscription.ex
0.804828
0.781038
subscription.ex
starcoder
defmodule Honcho.Cogs.Help do @moduledoc false # Adapted from https://github.com/jchristgit/bolt/blob/master/lib/bolt/cogs/help.ex @behaviour Nosedrum.Command alias Nosedrum.Storage.ETS, as: CommandStorage alias Nostrum.Api alias Nostrum.Struct.Embed @spec prefix() :: String.t() defp prefix, do: Application.fetch_env!(:nosedrum, :prefix) @spec format_command_detail(String.t(), Module.t()) :: Embed.t() def format_command_detail(name, command_module) do %Embed{ title: "❔ `#{name}`", description: """ ```ini #{ command_module.usage() |> Stream.map(&"#{prefix()}#{&1}") |> Enum.join("\n") } ``` #{command_module.description()} """, } end @impl true def usage, do: ["help [command:str]"] @impl true def description, do: """ Show information about the given command. With no arguments given, list all commands. """ @impl true def predicates, do: [] @impl true def command(msg, []) do embed = %Embed{ title: "All commands", description: CommandStorage.all_commands() |> Map.keys() |> Enum.sort() |> Stream.map(&"`#{prefix()}#{&1}`") |> (fn commands -> """ #{Enum.join(commands, ", ")} """ end).() } {:ok, _msg} = Api.create_message(msg.channel_id, embed: embed) end @impl true def command(msg, [command_name]) do case CommandStorage.lookup_command(command_name) do nil -> response = "🚫 unknown command, check `help` to view all" {:ok, _msg} = Api.create_message(msg.channel_id, response) command_module when not is_map(command_module) -> embed = format_command_detail(command_name, command_module) {:ok, _msg} = Api.create_message(msg.channel_id, embed: embed) subcommand_map -> embed = if Map.has_key?(subcommand_map, :default) do format_command_detail(command_name, subcommand_map.default) else subcommand_string = subcommand_map |> Map.keys() |> Stream.reject(&(&1 === :default)) |> Stream.map(&"`#{&1}`") |> Enum.join(", ") %Embed{ title: "`#{command_name}` - subcommands", description: subcommand_string, footer: %Embed.Footer{ text: "View `help #{command_name} <subcommand>` for details" } } end {:ok, _msg} = Api.create_message(msg.channel_id, embed: embed) end end def command(msg, [command_group, subcommand_name]) do # credo:disable-for-next-line Credo.Check.Refactor.WithClauses with command_map when is_map(command_map) <- CommandStorage.lookup_command(command_group) do case Map.fetch(command_map, subcommand_name) do {:ok, command_module} -> embed = format_command_detail("#{command_group} #{subcommand_name}", command_module) {:ok, _msg} = Api.create_message(msg.channel_id, embed: embed) :error -> subcommand_string = command_map |> Map.keys() |> Stream.map(&"`#{&1}`") |> Enum.join(", ") response = "🚫 unknown subcommand, known commands: #{subcommand_string}" {:ok, _msg} = Api.create_message(msg.channel_id, response) end else [] -> response = "🚫 no command group named that found" {:ok, _msg} = Api.create_message(msg.channel_id, response) [{_name, _module}] -> response = "🚫 that command has no subcommands, use" <> " `help #{command_group}` for information on it" {:ok, _msg} = Api.create_message(msg.channel_id, response) end end def command(msg, _args) do response = "ℹ️ usage: `help [command_name:str]` or `help [command_group:str] [subcommand_name:str]`" {:ok, _msg} = Api.create_message(msg.channel_id, response) end end
lib/honcho/cogs/help.ex
0.760606
0.536981
help.ex
starcoder
defmodule Phoenix.LiveDashboard.Router do @moduledoc """ Provides LiveView routing for LiveDashboard. """ @doc """ Defines a LiveDashboard route. It expects the `path` the dashboard will be mounted at and a set of options. ## Options * `:metrics` - Configures the module to retrieve metrics from. It can be a `module` or a `{module, function}`. If nothing is given, the metrics functionality will be disabled. ## Examples defmodule MyAppWeb.Router do use Phoenix.Router import Phoenix.LiveDashboard.Router scope "/", MyAppWeb do pipe_through [:browser] live_dashboard "/dashboard", metrics: {MyAppWeb.Telemetry, :metrics} end end """ defmacro live_dashboard(path, opts \\ []) do quote bind_quoted: binding() do scope path, alias: false, as: false do import Phoenix.LiveView.Router, only: [live: 4] opts = Phoenix.LiveDashboard.Router.__options__(opts) live "/", Phoenix.LiveDashboard.HomeLive, :home, opts live "/:node", Phoenix.LiveDashboard.HomeLive, :home, opts live "/:node/metrics", Phoenix.LiveDashboard.MetricsLive, :metrics, opts live "/:node/metrics/:group", Phoenix.LiveDashboard.MetricsLive, :metrics, opts live "/:node/ports", Phoenix.LiveDashboard.PortsLive, :ports, opts live "/:node/ports/:port", Phoenix.LiveDashboard.PortsLive, :ports, opts live "/:node/processes", Phoenix.LiveDashboard.ProcessesLive, :processes, opts live "/:node/processes/:pid", Phoenix.LiveDashboard.ProcessesLive, :processes, opts live "/:node/ets", Phoenix.LiveDashboard.EtsLive, :ets, opts live "/:node/ets/:ref", Phoenix.LiveDashboard.EtsLive, :ets, opts live "/:node/request_logger", Phoenix.LiveDashboard.RequestLoggerLive, :request_logger, opts live "/:node/request_logger/:stream", Phoenix.LiveDashboard.RequestLoggerLive, :request_logger, opts end end end @doc false def __options__(options) do metrics = case options[:metrics] do nil -> nil mod when is_atom(mod) -> {mod, :metrics} {mod, fun} when is_atom(mod) and is_atom(fun) -> {mod, fun} other -> raise ArgumentError, ":metrics must be a tuple with {Mod, fun}, " <> "such as {MyAppWeb.Telemetry, :metrics}, got: #{inspect(other)}" end [ session: {__MODULE__, :__session__, [metrics]}, layout: {Phoenix.LiveDashboard.LayoutView, :dash}, as: :live_dashboard ] end @doc false def __session__(conn, metrics) do %{ "metrics" => metrics, "request_logger" => Phoenix.LiveDashboard.RequestLogger.param_key(conn) } end end
lib/phoenix/live_dashboard/router.ex
0.86792
0.442576
router.ex
starcoder